]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
Avoid using buffer of already deallocated string in wxHTMLDataObject.
[wxWidgets.git] / src / common / filefn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/filefn.cpp
3 // Purpose: File- and directory-related functions
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #include "wx/filefn.h"
28
29 #ifndef WX_PRECOMP
30 #include "wx/intl.h"
31 #include "wx/log.h"
32 #include "wx/utils.h"
33 #include "wx/crt.h"
34 #endif
35
36 #include "wx/dynarray.h"
37 #include "wx/file.h"
38 #include "wx/filename.h"
39 #include "wx/dir.h"
40
41 #include "wx/tokenzr.h"
42
43 // there are just too many of those...
44 #ifdef __VISUALC__
45 #pragma warning(disable:4706) // assignment within conditional expression
46 #endif // VC++
47
48 #include <ctype.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
53 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
54 #include <errno.h>
55 #endif
56 #endif
57
58 #if defined(__WXMAC__)
59 #include "wx/osx/private.h" // includes mac headers
60 #endif
61
62 #ifdef __WINDOWS__
63 #include "wx/msw/private.h"
64 #include "wx/msw/missing.h"
65 #include "wx/msw/mslu.h"
66
67 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
68 // and for cygwin_conv_path()
69 //
70 // note that it must be included after <windows.h>
71 #ifdef __GNUWIN32__
72 #ifdef __CYGWIN__
73 #include <sys/cygwin.h>
74 #include <cygwin/version.h>
75 #endif
76 #endif // __GNUWIN32__
77
78 // io.h is needed for _get_osfhandle()
79 // Already included by filefn.h for many Windows compilers
80 #if defined __CYGWIN__
81 #include <io.h>
82 #endif
83 #endif // __WINDOWS__
84
85 #if defined(__VMS__)
86 #include <fab.h>
87 #endif
88
89 // TODO: Borland probably has _wgetcwd as well?
90 #ifdef _MSC_VER
91 #define HAVE_WGETCWD
92 #endif
93
94 // ----------------------------------------------------------------------------
95 // constants
96 // ----------------------------------------------------------------------------
97
98 #ifndef _MAXPATHLEN
99 #define _MAXPATHLEN 1024
100 #endif
101
102 // ----------------------------------------------------------------------------
103 // private globals
104 // ----------------------------------------------------------------------------
105
106 #if WXWIN_COMPATIBILITY_2_8
107 static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
108 #endif
109
110 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
111 //
112 // VisualAge C++ V4.0 cannot have any external linkage const decs
113 // in headers included by more than one primary source
114 //
115 const int wxInvalidOffset = -1;
116 #endif
117
118 // ============================================================================
119 // implementation
120 // ============================================================================
121
122 // ----------------------------------------------------------------------------
123 // wrappers around standard POSIX functions
124 // ----------------------------------------------------------------------------
125
126 #if wxUSE_UNICODE && defined __BORLANDC__ \
127 && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
128
129 // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
130 // regardless of the mode parameter. This hack works around the problem by
131 // setting the mode with _wchmod.
132 //
133 int wxCRT_OpenW(const wchar_t *pathname, int flags, mode_t mode)
134 {
135 int moreflags = 0;
136
137 // we only want to fix the mode when the file is actually created, so
138 // when creating first try doing it O_EXCL so we can tell if the file
139 // was already there.
140 if ((flags & O_CREAT) && !(flags & O_EXCL) && (mode & wxS_IWUSR) != 0)
141 moreflags = O_EXCL;
142
143 int fd = _wopen(pathname, flags | moreflags, mode);
144
145 // the file was actually created and needs fixing
146 if (fd != -1 && (flags & O_CREAT) != 0 && (mode & wxS_IWUSR) != 0)
147 {
148 close(fd);
149 _wchmod(pathname, mode);
150 fd = _wopen(pathname, flags & ~(O_EXCL | O_CREAT));
151 }
152 // the open failed, but it may have been because the added O_EXCL stopped
153 // the opening of an existing file, so try again without.
154 else if (fd == -1 && moreflags != 0)
155 {
156 fd = _wopen(pathname, flags & ~O_CREAT);
157 }
158
159 return fd;
160 }
161
162 #endif
163
164 // ----------------------------------------------------------------------------
165 // wxPathList
166 // ----------------------------------------------------------------------------
167
168 bool wxPathList::Add(const wxString& path)
169 {
170 // add a path separator to force wxFileName to interpret it always as a directory
171 // (i.e. if we are called with '/home/user' we want to consider it a folder and
172 // not, as wxFileName would consider, a filename).
173 wxFileName fn(path + wxFileName::GetPathSeparator());
174
175 // add only normalized relative/absolute paths
176 // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
177 // normalize paths which starts with ".." (which can be normalized only if
178 // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
179 if (!fn.Normalize(wxPATH_NORM_TILDE|wxPATH_NORM_LONG|wxPATH_NORM_ENV_VARS))
180 return false;
181
182 wxString toadd = fn.GetPath();
183 if (Index(toadd) == wxNOT_FOUND)
184 wxArrayString::Add(toadd); // do not add duplicates
185
186 return true;
187 }
188
189 void wxPathList::Add(const wxArrayString &arr)
190 {
191 for (size_t j=0; j < arr.GetCount(); j++)
192 Add(arr[j]);
193 }
194
195 // Add paths e.g. from the PATH environment variable
196 void wxPathList::AddEnvList (const wxString& WXUNUSED_IN_WINCE(envVariable))
197 {
198 // No environment variables on WinCE
199 #ifndef __WXWINCE__
200
201 // The space has been removed from the tokenizers, otherwise a
202 // path such as "C:\Program Files" would be split into 2 paths:
203 // "C:\Program" and "Files"; this is true for both Windows and Unix.
204
205 static const wxChar PATH_TOKS[] =
206 #if defined(__WINDOWS__) || defined(__OS2__)
207 wxT(";"); // Don't separate with colon in DOS (used for drive)
208 #else
209 wxT(":;");
210 #endif
211
212 wxString val;
213 if ( wxGetEnv(envVariable, &val) )
214 {
215 // split into an array of string the value of the env var
216 wxArrayString arr = wxStringTokenize(val, PATH_TOKS);
217 WX_APPEND_ARRAY(*this, arr);
218 }
219 #endif // !__WXWINCE__
220 }
221
222 // Given a full filename (with path), ensure that that file can
223 // be accessed again USING FILENAME ONLY by adding the path
224 // to the list if not already there.
225 bool wxPathList::EnsureFileAccessible (const wxString& path)
226 {
227 return Add(wxPathOnly(path));
228 }
229
230 #if WXWIN_COMPATIBILITY_2_6
231 bool wxPathList::Member (const wxString& path) const
232 {
233 return Index(path) != wxNOT_FOUND;
234 }
235 #endif
236
237 wxString wxPathList::FindValidPath (const wxString& file) const
238 {
239 // normalize the given string as it could be a path + a filename
240 // and not only a filename
241 wxFileName fn(file);
242 wxString strend;
243
244 // NB: normalize without making absolute otherwise calling this function with
245 // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
246 // below would only add to the paths of this list the 'c.txt' part when doing
247 // the existence checks...
248 // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
249 if (!fn.Normalize(wxPATH_NORM_TILDE|wxPATH_NORM_LONG|wxPATH_NORM_ENV_VARS))
250 return wxEmptyString;
251
252 wxASSERT_MSG(!fn.IsDir(), wxT("Cannot search for directories; only for files"));
253 if (fn.IsAbsolute())
254 strend = fn.GetFullName(); // search for the file name and ignore the path part
255 else
256 strend = fn.GetFullPath();
257
258 for (size_t i=0; i<GetCount(); i++)
259 {
260 wxString strstart = Item(i);
261 if (!strstart.IsEmpty() && strstart.Last() != wxFileName::GetPathSeparator())
262 strstart += wxFileName::GetPathSeparator();
263
264 if (wxFileExists(strstart + strend))
265 return strstart + strend; // Found!
266 }
267
268 return wxEmptyString; // Not found
269 }
270
271 wxString wxPathList::FindAbsoluteValidPath (const wxString& file) const
272 {
273 wxString f = FindValidPath(file);
274 if ( f.empty() || wxIsAbsolutePath(f) )
275 return f;
276
277 wxString buf = ::wxGetCwd();
278
279 if ( !wxEndsWithPathSeparator(buf) )
280 {
281 buf += wxFILE_SEP_PATH;
282 }
283 buf += f;
284
285 return buf;
286 }
287
288 // ----------------------------------------------------------------------------
289 // miscellaneous global functions
290 // ----------------------------------------------------------------------------
291
292 #if WXWIN_COMPATIBILITY_2_8
293 static inline wxChar* MYcopystring(const wxString& s)
294 {
295 wxChar* copy = new wxChar[s.length() + 1];
296 return wxStrcpy(copy, s.c_str());
297 }
298
299 template<typename CharType>
300 static inline CharType* MYcopystring(const CharType* s)
301 {
302 CharType* copy = new CharType[wxStrlen(s) + 1];
303 return wxStrcpy(copy, s);
304 }
305 #endif
306
307
308 bool
309 wxFileExists (const wxString& filename)
310 {
311 return wxFileName::FileExists(filename);
312 }
313
314 bool
315 wxIsAbsolutePath (const wxString& filename)
316 {
317 if (!filename.empty())
318 {
319 // Unix like or Windows
320 if (filename[0] == wxT('/'))
321 return true;
322 #ifdef __VMS__
323 if ((filename[0] == wxT('[') && filename[1] != wxT('.')))
324 return true;
325 #endif
326 #if defined(__WINDOWS__) || defined(__OS2__)
327 // MSDOS like
328 if (filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':')))
329 return true;
330 #endif
331 }
332 return false ;
333 }
334
335 #if WXWIN_COMPATIBILITY_2_8
336 /*
337 * Strip off any extension (dot something) from end of file,
338 * IF one exists. Inserts zero into buffer.
339 *
340 */
341
342 template<typename T>
343 static void wxDoStripExtension(T *buffer)
344 {
345 int len = wxStrlen(buffer);
346 int i = len-1;
347 while (i > 0)
348 {
349 if (buffer[i] == wxT('.'))
350 {
351 buffer[i] = 0;
352 break;
353 }
354 i --;
355 }
356 }
357
358 void wxStripExtension(char *buffer) { wxDoStripExtension(buffer); }
359 void wxStripExtension(wchar_t *buffer) { wxDoStripExtension(buffer); }
360
361 void wxStripExtension(wxString& buffer)
362 {
363 buffer = wxFileName::StripExtension(buffer);
364 }
365
366 // Destructive removal of /./ and /../ stuff
367 template<typename CharType>
368 static CharType *wxDoRealPath (CharType *path)
369 {
370 static const CharType SEP = wxFILE_SEP_PATH;
371 #ifdef __WINDOWS__
372 wxUnix2DosFilename(path);
373 #endif
374 if (path[0] && path[1]) {
375 /* MATTHEW: special case "/./x" */
376 CharType *p;
377 if (path[2] == SEP && path[1] == wxT('.'))
378 p = &path[0];
379 else
380 p = &path[2];
381 for (; *p; p++)
382 {
383 if (*p == SEP)
384 {
385 if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
386 {
387 CharType *q;
388 for (q = p - 1; q >= path && *q != SEP; q--)
389 {
390 // Empty
391 }
392
393 if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
394 && (q - 1 <= path || q[-1] != SEP))
395 {
396 wxStrcpy (q, p + 3);
397 if (path[0] == wxT('\0'))
398 {
399 path[0] = SEP;
400 path[1] = wxT('\0');
401 }
402 #if defined(__WINDOWS__) || defined(__OS2__)
403 /* Check that path[2] is NULL! */
404 else if (path[1] == wxT(':') && !path[2])
405 {
406 path[2] = SEP;
407 path[3] = wxT('\0');
408 }
409 #endif
410 p = q - 1;
411 }
412 }
413 else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
414 wxStrcpy (p, p + 2);
415 }
416 }
417 }
418 return path;
419 }
420
421 char *wxRealPath(char *path)
422 {
423 return wxDoRealPath(path);
424 }
425
426 wchar_t *wxRealPath(wchar_t *path)
427 {
428 return wxDoRealPath(path);
429 }
430
431 wxString wxRealPath(const wxString& path)
432 {
433 wxChar *buf1=MYcopystring(path);
434 wxChar *buf2=wxRealPath(buf1);
435 wxString buf(buf2);
436 delete [] buf1;
437 return buf;
438 }
439
440
441 // Must be destroyed
442 wxChar *wxCopyAbsolutePath(const wxString& filename)
443 {
444 if (filename.empty())
445 return NULL;
446
447 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename)))
448 {
449 wxString buf = ::wxGetCwd();
450 wxChar ch = buf.Last();
451 #ifdef __WINDOWS__
452 if (ch != wxT('\\') && ch != wxT('/'))
453 buf << wxT("\\");
454 #else
455 if (ch != wxT('/'))
456 buf << wxT("/");
457 #endif
458 buf << wxFileFunctionsBuffer;
459 buf = wxRealPath( buf );
460 return MYcopystring( buf );
461 }
462 return MYcopystring( wxFileFunctionsBuffer );
463 }
464
465 /*-
466 Handles:
467 ~/ => home dir
468 ~user/ => user's home dir
469 If the environment variable a = "foo" and b = "bar" then:
470 Unix:
471 $a => foo
472 $a$b => foobar
473 $a.c => foo.c
474 xxx$a => xxxfoo
475 ${a}! => foo!
476 $(b)! => bar!
477 \$a => \$a
478 MSDOS:
479 $a ==> $a
480 $(a) ==> foo
481 $(a)$b ==> foo$b
482 $(a)$(b)==> foobar
483 test.$$ ==> test.$$
484 */
485
486 /* input name in name, pathname output to buf. */
487
488 template<typename CharType>
489 static CharType *wxDoExpandPath(CharType *buf, const wxString& name)
490 {
491 register CharType *d, *s, *nm;
492 CharType lnm[_MAXPATHLEN];
493 int q;
494
495 // Some compilers don't like this line.
496 // const CharType trimchars[] = wxT("\n \t");
497
498 CharType trimchars[4];
499 trimchars[0] = wxT('\n');
500 trimchars[1] = wxT(' ');
501 trimchars[2] = wxT('\t');
502 trimchars[3] = 0;
503
504 static const CharType SEP = wxFILE_SEP_PATH;
505 #ifdef __WINDOWS__
506 //wxUnix2DosFilename(path);
507 #endif
508
509 buf[0] = wxT('\0');
510 if (name.empty())
511 return buf;
512 nm = ::MYcopystring(static_cast<const CharType*>(name.c_str())); // Make a scratch copy
513 CharType *nm_tmp = nm;
514
515 /* Skip leading whitespace and cr */
516 while (wxStrchr(trimchars, *nm) != NULL)
517 nm++;
518 /* And strip off trailing whitespace and cr */
519 s = nm + (q = wxStrlen(nm)) - 1;
520 while (q-- && wxStrchr(trimchars, *s) != NULL)
521 *s = wxT('\0');
522
523 s = nm;
524 d = lnm;
525 #ifdef __WINDOWS__
526 q = FALSE;
527 #else
528 q = nm[0] == wxT('\\') && nm[1] == wxT('~');
529 #endif
530
531 /* Expand inline environment variables */
532 #ifdef __VISAGECPP__
533 while (*d)
534 {
535 *d++ = *s;
536 if(*s == wxT('\\'))
537 {
538 *(d - 1) = *++s;
539 if (*d)
540 {
541 s++;
542 continue;
543 }
544 else
545 break;
546 }
547 else
548 #else
549 while ((*d++ = *s) != 0) {
550 # ifndef __WINDOWS__
551 if (*s == wxT('\\')) {
552 if ((*(d - 1) = *++s)!=0) {
553 s++;
554 continue;
555 } else
556 break;
557 } else
558 # endif
559 #endif
560 // No env variables on WinCE
561 #ifndef __WXWINCE__
562 #ifdef __WINDOWS__
563 if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
564 #else
565 if (*s++ == wxT('$'))
566 #endif
567 {
568 register CharType *start = d;
569 register int braces = (*s == wxT('{') || *s == wxT('('));
570 register CharType *value;
571 while ((*d++ = *s) != 0)
572 if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
573 break;
574 else
575 s++;
576 *--d = 0;
577 value = wxGetenv(braces ? start + 1 : start);
578 if (value) {
579 for ((d = start - 1); (*d++ = *value++) != 0;)
580 {
581 // Empty
582 }
583
584 d--;
585 if (braces && *s)
586 s++;
587 }
588 }
589 #endif
590 // __WXWINCE__
591 }
592
593 /* Expand ~ and ~user */
594 wxString homepath;
595 nm = lnm;
596 if (nm[0] == wxT('~') && !q)
597 {
598 /* prefix ~ */
599 if (nm[1] == SEP || nm[1] == 0)
600 { /* ~/filename */
601 homepath = wxGetUserHome(wxEmptyString);
602 if (!homepath.empty()) {
603 s = (CharType*)(const CharType*)homepath.c_str();
604 if (*++nm)
605 nm++;
606 }
607 } else
608 { /* ~user/filename */
609 register CharType *nnm;
610 for (s = nm; *s && *s != SEP; s++)
611 {
612 // Empty
613 }
614 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
615 was_sep = (*s == SEP);
616 nnm = *s ? s + 1 : s;
617 *s = 0;
618 homepath = wxGetUserHome(wxString(nm + 1));
619 if (homepath.empty())
620 {
621 if (was_sep) /* replace only if it was there: */
622 *s = SEP;
623 s = NULL;
624 }
625 else
626 {
627 nm = nnm;
628 s = (CharType*)(const CharType*)homepath.c_str();
629 }
630 }
631 }
632
633 d = buf;
634 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
635 /* Copy home dir */
636 while (wxT('\0') != (*d++ = *s++))
637 /* loop */;
638 // Handle root home
639 if (d - 1 > buf && *(d - 2) != SEP)
640 *(d - 1) = SEP;
641 }
642 s = nm;
643 while ((*d++ = *s++) != 0)
644 {
645 // Empty
646 }
647 delete[] nm_tmp; // clean up alloc
648 /* Now clean up the buffer */
649 return wxRealPath(buf);
650 }
651
652 char *wxExpandPath(char *buf, const wxString& name)
653 {
654 return wxDoExpandPath(buf, name);
655 }
656
657 wchar_t *wxExpandPath(wchar_t *buf, const wxString& name)
658 {
659 return wxDoExpandPath(buf, name);
660 }
661
662
663 /* Contract Paths to be build upon an environment variable
664 component:
665
666 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
667
668 The call wxExpandPath can convert these back!
669 */
670 wxChar *
671 wxContractPath (const wxString& filename,
672 const wxString& WXUNUSED_IN_WINCE(envname),
673 const wxString& user)
674 {
675 static wxChar dest[_MAXPATHLEN];
676
677 if (filename.empty())
678 return NULL;
679
680 wxStrcpy (dest, filename);
681 #ifdef __WINDOWS__
682 wxUnix2DosFilename(dest);
683 #endif
684
685 // Handle environment
686 wxString val;
687 #ifndef __WXWINCE__
688 wxChar *tcp;
689 if (!envname.empty() && !(val = wxGetenv (envname)).empty() &&
690 (tcp = wxStrstr (dest, val)) != NULL)
691 {
692 wxStrcpy (wxFileFunctionsBuffer, tcp + val.length());
693 *tcp++ = wxT('$');
694 *tcp++ = wxT('{');
695 wxStrcpy (tcp, envname);
696 wxStrcat (tcp, wxT("}"));
697 wxStrcat (tcp, wxFileFunctionsBuffer);
698 }
699 #endif
700
701 // Handle User's home (ignore root homes!)
702 val = wxGetUserHome (user);
703 if (val.empty())
704 return dest;
705
706 const size_t len = val.length();
707 if (len <= 2)
708 return dest;
709
710 if (wxStrncmp(dest, val, len) == 0)
711 {
712 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
713 if (!user.empty())
714 wxStrcat(wxFileFunctionsBuffer, user);
715 wxStrcat(wxFileFunctionsBuffer, dest + len);
716 wxStrcpy (dest, wxFileFunctionsBuffer);
717 }
718
719 return dest;
720 }
721
722 #endif // #if WXWIN_COMPATIBILITY_2_8
723
724 // Return just the filename, not the path (basename)
725 wxChar *wxFileNameFromPath (wxChar *path)
726 {
727 wxString p = path;
728 wxString n = wxFileNameFromPath(p);
729
730 return path + p.length() - n.length();
731 }
732
733 wxString wxFileNameFromPath (const wxString& path)
734 {
735 return wxFileName(path).GetFullName();
736 }
737
738 // Return just the directory, or NULL if no directory
739 wxChar *
740 wxPathOnly (wxChar *path)
741 {
742 if (path && *path)
743 {
744 static wxChar buf[_MAXPATHLEN];
745
746 // Local copy
747 wxStrcpy (buf, path);
748
749 int l = wxStrlen(path);
750 int i = l - 1;
751
752 // Search backward for a backward or forward slash
753 while (i > -1)
754 {
755 // Unix like or Windows
756 if (path[i] == wxT('/') || path[i] == wxT('\\'))
757 {
758 buf[i] = 0;
759 return buf;
760 }
761 #ifdef __VMS__
762 if (path[i] == wxT(']'))
763 {
764 buf[i+1] = 0;
765 return buf;
766 }
767 #endif
768 i --;
769 }
770
771 #if defined(__WINDOWS__) || defined(__OS2__)
772 // Try Drive specifier
773 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
774 {
775 // A:junk --> A:. (since A:.\junk Not A:\junk)
776 buf[2] = wxT('.');
777 buf[3] = wxT('\0');
778 return buf;
779 }
780 #endif
781 }
782 return NULL;
783 }
784
785 // Return just the directory, or NULL if no directory
786 wxString wxPathOnly (const wxString& path)
787 {
788 if (!path.empty())
789 {
790 wxChar buf[_MAXPATHLEN];
791
792 // Local copy
793 wxStrcpy(buf, path);
794
795 int l = path.length();
796 int i = l - 1;
797
798 // Search backward for a backward or forward slash
799 while (i > -1)
800 {
801 // Unix like or Windows
802 if (path[i] == wxT('/') || path[i] == wxT('\\'))
803 {
804 // Don't return an empty string
805 if (i == 0)
806 i ++;
807 buf[i] = 0;
808 return wxString(buf);
809 }
810 #ifdef __VMS__
811 if (path[i] == wxT(']'))
812 {
813 buf[i+1] = 0;
814 return wxString(buf);
815 }
816 #endif
817 i --;
818 }
819
820 #if defined(__WINDOWS__) || defined(__OS2__)
821 // Try Drive specifier
822 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
823 {
824 // A:junk --> A:. (since A:.\junk Not A:\junk)
825 buf[2] = wxT('.');
826 buf[3] = wxT('\0');
827 return wxString(buf);
828 }
829 #endif
830 }
831 return wxEmptyString;
832 }
833
834 // Utility for converting delimiters in DOS filenames to UNIX style
835 // and back again - or we get nasty problems with delimiters.
836 // Also, convert to lower case, since case is significant in UNIX.
837
838 #if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
839
840 #define kDefaultPathStyle kCFURLPOSIXPathStyle
841
842 wxString wxMacFSRefToPath( const FSRef *fsRef , CFStringRef additionalPathComponent )
843 {
844 CFURLRef fullURLRef;
845 fullURLRef = CFURLCreateFromFSRef(NULL, fsRef);
846 if ( fullURLRef == NULL)
847 return wxEmptyString;
848
849 if ( additionalPathComponent )
850 {
851 CFURLRef parentURLRef = fullURLRef ;
852 fullURLRef = CFURLCreateCopyAppendingPathComponent(NULL, parentURLRef,
853 additionalPathComponent,false);
854 CFRelease( parentURLRef ) ;
855 }
856 wxCFStringRef cfString( CFURLCopyFileSystemPath(fullURLRef, kDefaultPathStyle ));
857 CFRelease( fullURLRef ) ;
858
859 return wxCFStringRef::AsStringWithNormalizationFormC(cfString);
860 }
861
862 OSStatus wxMacPathToFSRef( const wxString&path , FSRef *fsRef )
863 {
864 OSStatus err = noErr ;
865 CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(path));
866 CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
867 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kDefaultPathStyle, false);
868 CFRelease( cfMutableString );
869 if ( NULL != url )
870 {
871 if ( CFURLGetFSRef(url, fsRef) == false )
872 err = fnfErr ;
873 CFRelease( url ) ;
874 }
875 else
876 {
877 err = fnfErr ;
878 }
879 return err ;
880 }
881
882 wxString wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname )
883 {
884 wxCFStringRef cfname( CFStringCreateWithCharacters( kCFAllocatorDefault,
885 uniname->unicode,
886 uniname->length ) );
887 return wxCFStringRef::AsStringWithNormalizationFormC(cfname);
888 }
889
890 #ifndef __LP64__
891
892 wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
893 {
894 FSRef fsRef ;
895 if ( FSpMakeFSRef( spec , &fsRef) == noErr )
896 {
897 return wxMacFSRefToPath( &fsRef ) ;
898 }
899 return wxEmptyString ;
900 }
901
902 void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
903 {
904 OSStatus err = noErr;
905 FSRef fsRef;
906 wxMacPathToFSRef( path , &fsRef );
907 err = FSGetCatalogInfo(&fsRef, kFSCatInfoNone, NULL, NULL, spec, NULL);
908 verify_noerr( err );
909 }
910 #endif
911
912 #endif // __WXMAC__
913
914
915 #if WXWIN_COMPATIBILITY_2_8
916
917 template<typename T>
918 static void wxDoDos2UnixFilename(T *s)
919 {
920 if (s)
921 while (*s)
922 {
923 if (*s == wxT('\\'))
924 *s = wxT('/');
925 #ifdef __WINDOWS__
926 else
927 *s = wxTolower(*s); // Case INDEPENDENT
928 #endif
929 s++;
930 }
931 }
932
933 void wxDos2UnixFilename(char *s) { wxDoDos2UnixFilename(s); }
934 void wxDos2UnixFilename(wchar_t *s) { wxDoDos2UnixFilename(s); }
935
936 template<typename T>
937 static void
938 #if defined(__WINDOWS__) || defined(__OS2__)
939 wxDoUnix2DosFilename(T *s)
940 #else
941 wxDoUnix2DosFilename(T *WXUNUSED(s) )
942 #endif
943 {
944 // Yes, I really mean this to happen under DOS only! JACS
945 #if defined(__WINDOWS__) || defined(__OS2__)
946 if (s)
947 while (*s)
948 {
949 if (*s == wxT('/'))
950 *s = wxT('\\');
951 s++;
952 }
953 #endif
954 }
955
956 void wxUnix2DosFilename(char *s) { wxDoUnix2DosFilename(s); }
957 void wxUnix2DosFilename(wchar_t *s) { wxDoUnix2DosFilename(s); }
958
959 #endif // #if WXWIN_COMPATIBILITY_2_8
960
961 // Concatenate two files to form third
962 bool
963 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
964 {
965 #if wxUSE_FILE
966
967 wxFile in1(file1), in2(file2);
968 wxTempFile out(file3);
969
970 if ( !in1.IsOpened() || !in2.IsOpened() || !out.IsOpened() )
971 return false;
972
973 ssize_t ofs;
974 unsigned char buf[1024];
975
976 for( int i=0; i<2; i++)
977 {
978 wxFile *in = i==0 ? &in1 : &in2;
979 do{
980 if ( (ofs = in->Read(buf,WXSIZEOF(buf))) == wxInvalidOffset ) return false;
981 if ( ofs > 0 )
982 if ( !out.Write(buf,ofs) )
983 return false;
984 } while ( ofs == (ssize_t)WXSIZEOF(buf) );
985 }
986
987 return out.Commit();
988
989 #else
990
991 wxUnusedVar(file1);
992 wxUnusedVar(file2);
993 wxUnusedVar(file3);
994 return false;
995
996 #endif
997 }
998
999 // helper of generic implementation of wxCopyFile()
1000 #if !(defined(__WIN32__) || defined(__OS2__)) && wxUSE_FILE
1001
1002 static bool
1003 wxDoCopyFile(wxFile& fileIn,
1004 const wxStructStat& fbuf,
1005 const wxString& filenameDst,
1006 bool overwrite)
1007 {
1008 // reset the umask as we want to create the file with exactly the same
1009 // permissions as the original one
1010 wxCHANGE_UMASK(0);
1011
1012 // create file2 with the same permissions than file1 and open it for
1013 // writing
1014
1015 wxFile fileOut;
1016 if ( !fileOut.Create(filenameDst, overwrite, fbuf.st_mode & 0777) )
1017 return false;
1018
1019 // copy contents of file1 to file2
1020 char buf[4096];
1021 for ( ;; )
1022 {
1023 ssize_t count = fileIn.Read(buf, WXSIZEOF(buf));
1024 if ( count == wxInvalidOffset )
1025 return false;
1026
1027 // end of file?
1028 if ( !count )
1029 break;
1030
1031 if ( fileOut.Write(buf, count) < (size_t)count )
1032 return false;
1033 }
1034
1035 // we can expect fileIn to be closed successfully, but we should ensure
1036 // that fileOut was closed as some write errors (disk full) might not be
1037 // detected before doing this
1038 return fileIn.Close() && fileOut.Close();
1039 }
1040
1041 #endif // generic implementation of wxCopyFile
1042
1043 // Copy files
1044 bool
1045 wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
1046 {
1047 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1048 // CopyFile() copies file attributes and modification time too, so use it
1049 // instead of our code if available
1050 //
1051 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1052 if ( !::CopyFile(file1.t_str(), file2.t_str(), !overwrite) )
1053 {
1054 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1055 file1.c_str(), file2.c_str());
1056
1057 return false;
1058 }
1059 #elif defined(__OS2__)
1060 if ( ::DosCopy(file1.c_str(), file2.c_str(), overwrite ? DCPY_EXISTING : 0) != 0 )
1061 return false;
1062 #elif wxUSE_FILE // !Win32
1063
1064 wxStructStat fbuf;
1065 // get permissions of file1
1066 if ( wxStat( file1, &fbuf) != 0 )
1067 {
1068 // the file probably doesn't exist or we haven't the rights to read
1069 // from it anyhow
1070 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1071 file1.c_str());
1072 return false;
1073 }
1074
1075 // open file1 for reading
1076 wxFile fileIn(file1, wxFile::read);
1077 if ( !fileIn.IsOpened() )
1078 return false;
1079
1080 // remove file2, if it exists. This is needed for creating
1081 // file2 with the correct permissions in the next step
1082 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
1083 {
1084 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1085 file2.c_str());
1086 return false;
1087 }
1088
1089 wxDoCopyFile(fileIn, fbuf, file2, overwrite);
1090
1091 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1092 // copy the resource fork of the file too if it's present
1093 wxString pathRsrcOut;
1094 wxFile fileRsrcIn;
1095
1096 {
1097 // suppress error messages from this block as resource forks don't have
1098 // to exist
1099 wxLogNull noLog;
1100
1101 // it's not enough to check for file existence: it always does on HFS
1102 // but is empty for files without resources
1103 if ( fileRsrcIn.Open(file1 + wxT("/..namedfork/rsrc")) &&
1104 fileRsrcIn.Length() > 0 )
1105 {
1106 // we must be using HFS or another filesystem with resource fork
1107 // support, suppose that destination file system also is HFS[-like]
1108 pathRsrcOut = file2 + wxT("/..namedfork/rsrc");
1109 }
1110 else // check if we have resource fork in separate file (non-HFS case)
1111 {
1112 wxFileName fnRsrc(file1);
1113 fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
1114
1115 fileRsrcIn.Close();
1116 if ( fileRsrcIn.Open( fnRsrc.GetFullPath() ) )
1117 {
1118 fnRsrc = file2;
1119 fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
1120
1121 pathRsrcOut = fnRsrc.GetFullPath();
1122 }
1123 }
1124 }
1125
1126 if ( !pathRsrcOut.empty() )
1127 {
1128 if ( !wxDoCopyFile(fileRsrcIn, fbuf, pathRsrcOut, overwrite) )
1129 return false;
1130 }
1131 #endif // wxMac || wxCocoa
1132
1133 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1134 // no chmod in VA. Should be some permission API for HPFS386 partitions
1135 // however
1136 if ( chmod(file2.fn_str(), fbuf.st_mode) != 0 )
1137 {
1138 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1139 file2.c_str());
1140 return false;
1141 }
1142 #endif // OS/2 || Mac
1143
1144 #else // !Win32 && ! wxUSE_FILE
1145
1146 // impossible to simulate with wxWidgets API
1147 wxUnusedVar(file1);
1148 wxUnusedVar(file2);
1149 wxUnusedVar(overwrite);
1150 return false;
1151
1152 #endif // __WINDOWS__ && __WIN32__
1153
1154 return true;
1155 }
1156
1157 bool
1158 wxRenameFile(const wxString& file1, const wxString& file2, bool overwrite)
1159 {
1160 if ( !overwrite && wxFileExists(file2) )
1161 {
1162 wxLogSysError
1163 (
1164 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1165 file1.c_str(), file2.c_str()
1166 );
1167
1168 return false;
1169 }
1170
1171 #if !defined(__WXWINCE__)
1172 // Normal system call
1173 if ( wxRename (file1, file2) == 0 )
1174 return true;
1175 #endif
1176
1177 // Try to copy
1178 if (wxCopyFile(file1, file2, overwrite)) {
1179 wxRemoveFile(file1);
1180 return true;
1181 }
1182 // Give up
1183 wxLogSysError(_("File '%s' couldn't be renamed '%s'"), file1, file2);
1184 return false;
1185 }
1186
1187 bool wxRemoveFile(const wxString& file)
1188 {
1189 #if defined(__VISUALC__) \
1190 || defined(__BORLANDC__) \
1191 || defined(__WATCOMC__) \
1192 || defined(__DMC__) \
1193 || defined(__GNUWIN32__)
1194 int res = wxRemove(file);
1195 #elif defined(__WXMAC__)
1196 int res = unlink(file.fn_str());
1197 #else
1198 int res = unlink(file.fn_str());
1199 #endif
1200 if ( res )
1201 {
1202 wxLogSysError(_("File '%s' couldn't be removed"), file);
1203 }
1204 return res == 0;
1205 }
1206
1207 bool wxMkdir(const wxString& dir, int perm)
1208 {
1209 #if defined(__WXMAC__) && !defined(__UNIX__)
1210 if ( mkdir(dir.fn_str(), 0) != 0 )
1211
1212 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1213 // for the GNU compiler
1214 #elif (!(defined(__WINDOWS__) || defined(__OS2__) || defined(__DOS__))) || \
1215 (defined(__GNUWIN32__) && !defined(__MINGW32__)) || \
1216 defined(__WINE__) || defined(__WXMICROWIN__)
1217 const wxChar *dirname = dir.c_str();
1218 #if defined(MSVCRT)
1219 wxUnusedVar(perm);
1220 if ( mkdir(wxFNCONV(dirname)) != 0 )
1221 #else
1222 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1223 #endif
1224 #elif defined(__OS2__)
1225 wxUnusedVar(perm);
1226 if (::DosCreateDir(dir.c_str(), NULL) != 0) // enhance for EAB's??
1227 #elif defined(__DOS__)
1228 const wxChar *dirname = dir.c_str();
1229 #if defined(__WATCOMC__)
1230 (void)perm;
1231 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1232 #elif defined(__DJGPP__)
1233 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1234 #else
1235 #error "Unsupported DOS compiler!"
1236 #endif
1237 #else // !MSW, !DOS and !OS/2 VAC++
1238 wxUnusedVar(perm);
1239 #ifdef __WXWINCE__
1240 if ( CreateDirectory(dir.fn_str(), NULL) == 0 )
1241 #else
1242 if ( wxMkDir(dir.fn_str()) != 0 )
1243 #endif
1244 #endif // !MSW/MSW
1245 {
1246 wxLogSysError(_("Directory '%s' couldn't be created"), dir);
1247 return false;
1248 }
1249
1250 return true;
1251 }
1252
1253 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1254 {
1255 #if defined(__VMS__)
1256 return false; //to be changed since rmdir exists in VMS7.x
1257 #else
1258 #if defined(__OS2__)
1259 if ( ::DosDeleteDir(dir.c_str()) != 0 )
1260 #elif defined(__WXWINCE__)
1261 if ( RemoveDirectory(dir.fn_str()) == 0 )
1262 #else
1263 if ( wxRmDir(dir.fn_str()) != 0 )
1264 #endif
1265 {
1266 wxLogSysError(_("Directory '%s' couldn't be deleted"), dir);
1267 return false;
1268 }
1269
1270 return true;
1271 #endif
1272 }
1273
1274 // does the path exists? (may have or not '/' or '\\' at the end)
1275 bool wxDirExists(const wxString& pathName)
1276 {
1277 return wxFileName::DirExists(pathName);
1278 }
1279
1280 #if WXWIN_COMPATIBILITY_2_8
1281
1282 // Get a temporary filename, opening and closing the file.
1283 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1284 {
1285 wxString filename;
1286 if ( !wxGetTempFileName(prefix, filename) )
1287 return NULL;
1288
1289 if ( buf )
1290 wxStrcpy(buf, filename);
1291 else
1292 buf = MYcopystring(filename);
1293
1294 return buf;
1295 }
1296
1297 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1298 {
1299 #if wxUSE_FILE
1300 buf = wxFileName::CreateTempFileName(prefix);
1301
1302 return !buf.empty();
1303 #else // !wxUSE_FILE
1304 wxUnusedVar(prefix);
1305 wxUnusedVar(buf);
1306
1307 return false;
1308 #endif // wxUSE_FILE/!wxUSE_FILE
1309 }
1310
1311 #endif // #if WXWIN_COMPATIBILITY_2_8
1312
1313 // Get first file name matching given wild card.
1314
1315 static wxDir *gs_dir = NULL;
1316 static wxString gs_dirPath;
1317
1318 wxString wxFindFirstFile(const wxString& spec, int flags)
1319 {
1320 wxFileName::SplitPath(spec, &gs_dirPath, NULL, NULL);
1321 if ( gs_dirPath.empty() )
1322 gs_dirPath = wxT(".");
1323 if ( !wxEndsWithPathSeparator(gs_dirPath ) )
1324 gs_dirPath << wxFILE_SEP_PATH;
1325
1326 delete gs_dir; // can be NULL, this is ok
1327 gs_dir = new wxDir(gs_dirPath);
1328
1329 if ( !gs_dir->IsOpened() )
1330 {
1331 wxLogSysError(_("Cannot enumerate files '%s'"), spec);
1332 return wxEmptyString;
1333 }
1334
1335 int dirFlags;
1336 switch (flags)
1337 {
1338 case wxDIR: dirFlags = wxDIR_DIRS; break;
1339 case wxFILE: dirFlags = wxDIR_FILES; break;
1340 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1341 }
1342
1343 wxString result;
1344 gs_dir->GetFirst(&result, wxFileNameFromPath(spec), dirFlags);
1345 if ( result.empty() )
1346 {
1347 wxDELETE(gs_dir);
1348 return result;
1349 }
1350
1351 return gs_dirPath + result;
1352 }
1353
1354 wxString wxFindNextFile()
1355 {
1356 wxCHECK_MSG( gs_dir, "", "You must call wxFindFirstFile before!" );
1357
1358 wxString result;
1359 if ( !gs_dir->GetNext(&result) || result.empty() )
1360 {
1361 wxDELETE(gs_dir);
1362 return result;
1363 }
1364
1365 return gs_dirPath + result;
1366 }
1367
1368
1369 // Get current working directory.
1370 // If buf is NULL, allocates space using new, else copies into buf.
1371 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1372 // wxDoGetCwd() is their common core to be moved
1373 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1374 // Do not expose wxDoGetCwd in headers!
1375
1376 wxChar *wxDoGetCwd(wxChar *buf, int sz)
1377 {
1378 #if defined(__WXWINCE__)
1379 // TODO
1380 if(buf && sz>0) buf[0] = wxT('\0');
1381 return buf;
1382 #else
1383 if ( !buf )
1384 {
1385 buf = new wxChar[sz + 1];
1386 }
1387
1388 bool ok wxDUMMY_INITIALIZE(false);
1389
1390 // for the compilers which have Unicode version of _getcwd(), call it
1391 // directly, for the others call the ANSI version and do the translation
1392 #if !wxUSE_UNICODE
1393 #define cbuf buf
1394 #else // wxUSE_UNICODE
1395 bool needsANSI = true;
1396
1397 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1398 char cbuf[_MAXPATHLEN];
1399 #endif
1400
1401 #ifdef HAVE_WGETCWD
1402 #if wxUSE_UNICODE_MSLU
1403 if ( wxGetOsVersion() != wxOS_WINDOWS_9X )
1404 #else
1405 char *cbuf = NULL; // never really used because needsANSI will always be false
1406 #endif
1407 {
1408 ok = _wgetcwd(buf, sz) != NULL;
1409 needsANSI = false;
1410 }
1411 #endif
1412
1413 if ( needsANSI )
1414 #endif // wxUSE_UNICODE
1415 {
1416 #if defined(_MSC_VER) || defined(__MINGW32__)
1417 ok = _getcwd(cbuf, sz) != NULL;
1418 #elif defined(__OS2__)
1419 APIRET rc;
1420 ULONG ulDriveNum = 0;
1421 ULONG ulDriveMap = 0;
1422 rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
1423 ok = rc == 0;
1424 if (ok)
1425 {
1426 sz -= 3;
1427 rc = ::DosQueryCurrentDir( 0 // current drive
1428 ,(PBYTE)cbuf + 3
1429 ,(PULONG)&sz
1430 );
1431 cbuf[0] = char('A' + (ulDriveNum - 1));
1432 cbuf[1] = ':';
1433 cbuf[2] = '\\';
1434 ok = rc == 0;
1435 }
1436 #else // !Win32/VC++ !Mac !OS2
1437 ok = getcwd(cbuf, sz) != NULL;
1438 #endif // platform
1439
1440 #if wxUSE_UNICODE
1441 // finally convert the result to Unicode if needed
1442 wxConvFile.MB2WC(buf, cbuf, sz);
1443 #endif // wxUSE_UNICODE
1444 }
1445
1446 if ( !ok )
1447 {
1448 wxLogSysError(_("Failed to get the working directory"));
1449
1450 // VZ: the old code used to return "." on error which didn't make any
1451 // sense at all to me - empty string is a better error indicator
1452 // (NULL might be even better but I'm afraid this could lead to
1453 // problems with the old code assuming the return is never NULL)
1454 buf[0] = wxT('\0');
1455 }
1456 else // ok, but we might need to massage the path into the right format
1457 {
1458 #ifdef __DJGPP__
1459 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1460 // with / deliminers. We don't like that.
1461 for (wxChar *ch = buf; *ch; ch++)
1462 {
1463 if (*ch == wxT('/'))
1464 *ch = wxT('\\');
1465 }
1466 #endif // __DJGPP__
1467
1468 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1469 // he needs Unix as opposed to Win32 pathnames
1470 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1471 // another example of DOS/Unix mix (Cygwin)
1472 wxString pathUnix = buf;
1473 #if wxUSE_UNICODE
1474 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1475 cygwin_conv_path(CCP_POSIX_TO_WIN_W, pathUnix.mb_str(wxConvFile), buf, sz);
1476 #else
1477 char bufA[_MAXPATHLEN];
1478 cygwin_conv_to_full_win32_path(pathUnix.mb_str(wxConvFile), bufA);
1479 wxConvFile.MB2WC(buf, bufA, sz);
1480 #endif
1481 #else
1482 #if CYGWIN_VERSION_DLL_MAJOR >= 1007
1483 cygwin_conv_path(CCP_POSIX_TO_WIN_A, pathUnix, buf, sz);
1484 #else
1485 cygwin_conv_to_full_win32_path(pathUnix, buf);
1486 #endif
1487 #endif // wxUSE_UNICODE
1488 #endif // __CYGWIN__
1489 }
1490
1491 return buf;
1492
1493 #if !wxUSE_UNICODE
1494 #undef cbuf
1495 #endif
1496
1497 #endif
1498 // __WXWINCE__
1499 }
1500
1501 #if WXWIN_COMPATIBILITY_2_6
1502 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1503 {
1504 return wxDoGetCwd(buf,sz);
1505 }
1506 #endif // WXWIN_COMPATIBILITY_2_6
1507
1508 wxString wxGetCwd()
1509 {
1510 wxString str;
1511 wxDoGetCwd(wxStringBuffer(str, _MAXPATHLEN), _MAXPATHLEN);
1512 return str;
1513 }
1514
1515 bool wxSetWorkingDirectory(const wxString& d)
1516 {
1517 bool success = false;
1518 #if defined(__OS2__)
1519 if (d[1] == ':')
1520 {
1521 ::DosSetDefaultDisk(wxToupper(d[0]) - wxT('A') + 1);
1522 // do not call DosSetCurrentDir when just changing drive,
1523 // since it requires e.g. "d:." instead of "d:"!
1524 if (d.length() == 2)
1525 return true;
1526 }
1527 success = (::DosSetCurrentDir(d.c_str()) == 0);
1528 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1529 success = (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1530 #elif defined(__WINDOWS__)
1531
1532 #ifdef __WIN32__
1533 #ifdef __WXWINCE__
1534 // No equivalent in WinCE
1535 wxUnusedVar(d);
1536 #else
1537 success = (SetCurrentDirectory(d.t_str()) != 0);
1538 #endif
1539 #else
1540 // Must change drive, too.
1541 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1542 if (isDriveSpec)
1543 {
1544 wxChar firstChar = d[0];
1545
1546 // To upper case
1547 if (firstChar > 90)
1548 firstChar = firstChar - 32;
1549
1550 // To a drive number
1551 unsigned int driveNo = firstChar - 64;
1552 if (driveNo > 0)
1553 {
1554 unsigned int noDrives;
1555 _dos_setdrive(driveNo, &noDrives);
1556 }
1557 }
1558 success = (chdir(WXSTRINGCAST d) == 0);
1559 #endif
1560
1561 #endif
1562 if ( !success )
1563 {
1564 wxLogSysError(_("Could not set current working directory"));
1565 }
1566 return success;
1567 }
1568
1569 // Get the OS directory if appropriate (such as the Windows directory).
1570 // On non-Windows platform, probably just return the empty string.
1571 wxString wxGetOSDirectory()
1572 {
1573 #ifdef __WXWINCE__
1574 return wxString(wxT("\\Windows"));
1575 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1576 wxChar buf[MAX_PATH];
1577 if ( !GetWindowsDirectory(buf, MAX_PATH) )
1578 {
1579 wxLogLastError(wxS("GetWindowsDirectory"));
1580 }
1581
1582 return wxString(buf);
1583 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1584 return wxMacFindFolderNoSeparator(kOnSystemDisk, 'macs', false);
1585 #else
1586 return wxEmptyString;
1587 #endif
1588 }
1589
1590 bool wxEndsWithPathSeparator(const wxString& filename)
1591 {
1592 return !filename.empty() && wxIsPathSeparator(filename.Last());
1593 }
1594
1595 // find a file in a list of directories, returns false if not found
1596 bool wxFindFileInPath(wxString *pStr, const wxString& szPath, const wxString& szFile)
1597 {
1598 // we assume that it's not empty
1599 wxCHECK_MSG( !szFile.empty(), false,
1600 wxT("empty file name in wxFindFileInPath"));
1601
1602 // skip path separator in the beginning of the file name if present
1603 wxString szFile2;
1604 if ( wxIsPathSeparator(szFile[0u]) )
1605 szFile2 = szFile.Mid(1);
1606 else
1607 szFile2 = szFile;
1608
1609 wxStringTokenizer tkn(szPath, wxPATH_SEP);
1610
1611 while ( tkn.HasMoreTokens() )
1612 {
1613 wxString strFile = tkn.GetNextToken();
1614 if ( !wxEndsWithPathSeparator(strFile) )
1615 strFile += wxFILE_SEP_PATH;
1616 strFile += szFile2;
1617
1618 if ( wxFileExists(strFile) )
1619 {
1620 *pStr = strFile;
1621 return true;
1622 }
1623 }
1624
1625 return false;
1626 }
1627
1628 #if WXWIN_COMPATIBILITY_2_8
1629 void WXDLLIMPEXP_BASE wxSplitPath(const wxString& fileName,
1630 wxString *pstrPath,
1631 wxString *pstrName,
1632 wxString *pstrExt)
1633 {
1634 wxFileName::SplitPath(fileName, pstrPath, pstrName, pstrExt);
1635 }
1636 #endif // #if WXWIN_COMPATIBILITY_2_8
1637
1638 #if wxUSE_DATETIME
1639
1640 time_t WXDLLIMPEXP_BASE wxFileModificationTime(const wxString& filename)
1641 {
1642 wxDateTime mtime;
1643 if ( !wxFileName(filename).GetTimes(NULL, &mtime, NULL) )
1644 return (time_t)-1;
1645
1646 return mtime.GetTicks();
1647 }
1648
1649 #endif // wxUSE_DATETIME
1650
1651
1652 // Parses the filterStr, returning the number of filters.
1653 // Returns 0 if none or if there's a problem.
1654 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1655
1656 int WXDLLIMPEXP_BASE wxParseCommonDialogsFilter(const wxString& filterStr,
1657 wxArrayString& descriptions,
1658 wxArrayString& filters)
1659 {
1660 descriptions.Clear();
1661 filters.Clear();
1662
1663 wxString str(filterStr);
1664
1665 wxString description, filter;
1666 int pos = 0;
1667 while( pos != wxNOT_FOUND )
1668 {
1669 pos = str.Find(wxT('|'));
1670 if ( pos == wxNOT_FOUND )
1671 {
1672 // if there are no '|'s at all in the string just take the entire
1673 // string as filter and make description empty for later autocompletion
1674 if ( filters.IsEmpty() )
1675 {
1676 descriptions.Add(wxEmptyString);
1677 filters.Add(filterStr);
1678 }
1679 else
1680 {
1681 wxFAIL_MSG( wxT("missing '|' in the wildcard string!") );
1682 }
1683
1684 break;
1685 }
1686
1687 description = str.Left(pos);
1688 str = str.Mid(pos + 1);
1689 pos = str.Find(wxT('|'));
1690 if ( pos == wxNOT_FOUND )
1691 {
1692 filter = str;
1693 }
1694 else
1695 {
1696 filter = str.Left(pos);
1697 str = str.Mid(pos + 1);
1698 }
1699
1700 descriptions.Add(description);
1701 filters.Add(filter);
1702 }
1703
1704 #if defined(__WXMOTIF__)
1705 // split it so there is one wildcard per entry
1706 for( size_t i = 0 ; i < descriptions.GetCount() ; i++ )
1707 {
1708 pos = filters[i].Find(wxT(';'));
1709 if (pos != wxNOT_FOUND)
1710 {
1711 // first split only filters
1712 descriptions.Insert(descriptions[i],i+1);
1713 filters.Insert(filters[i].Mid(pos+1),i+1);
1714 filters[i]=filters[i].Left(pos);
1715
1716 // autoreplace new filter in description with pattern:
1717 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1718 // cause split into:
1719 // C/C++ Files(*.cpp)|*.cpp
1720 // C/C++ Files(*.c;*.h)|*.c;*.h
1721 // and next iteration cause another split into:
1722 // C/C++ Files(*.cpp)|*.cpp
1723 // C/C++ Files(*.c)|*.c
1724 // C/C++ Files(*.h)|*.h
1725 for ( size_t k=i;k<i+2;k++ )
1726 {
1727 pos = descriptions[k].Find(filters[k]);
1728 if (pos != wxNOT_FOUND)
1729 {
1730 wxString before = descriptions[k].Left(pos);
1731 wxString after = descriptions[k].Mid(pos+filters[k].Len());
1732 pos = before.Find(wxT('('),true);
1733 if (pos>before.Find(wxT(')'),true))
1734 {
1735 before = before.Left(pos+1);
1736 before << filters[k];
1737 pos = after.Find(wxT(')'));
1738 int pos1 = after.Find(wxT('('));
1739 if (pos != wxNOT_FOUND && (pos<pos1 || pos1==wxNOT_FOUND))
1740 {
1741 before << after.Mid(pos);
1742 descriptions[k] = before;
1743 }
1744 }
1745 }
1746 }
1747 }
1748 }
1749 #endif
1750
1751 // autocompletion
1752 for( size_t j = 0 ; j < descriptions.GetCount() ; j++ )
1753 {
1754 if ( descriptions[j].empty() && !filters[j].empty() )
1755 {
1756 descriptions[j].Printf(_("Files (%s)"), filters[j].c_str());
1757 }
1758 }
1759
1760 return filters.GetCount();
1761 }
1762
1763 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1764 static bool wxCheckWin32Permission(const wxString& path, DWORD access)
1765 {
1766 // quoting the MSDN: "To obtain a handle to a directory, call the
1767 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1768 // doesn't work under Win9x/ME but then it's not needed there anyhow
1769 const DWORD dwAttr = ::GetFileAttributes(path.t_str());
1770 if ( dwAttr == INVALID_FILE_ATTRIBUTES )
1771 {
1772 // file probably doesn't exist at all
1773 return false;
1774 }
1775
1776 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
1777 {
1778 // FAT directories always allow all access, even if they have the
1779 // readonly flag set, and FAT files can only be read-only
1780 return (dwAttr & FILE_ATTRIBUTE_DIRECTORY) ||
1781 (access != GENERIC_WRITE ||
1782 !(dwAttr & FILE_ATTRIBUTE_READONLY));
1783 }
1784
1785 HANDLE h = ::CreateFile
1786 (
1787 path.t_str(),
1788 access,
1789 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1790 NULL,
1791 OPEN_EXISTING,
1792 dwAttr & FILE_ATTRIBUTE_DIRECTORY
1793 ? FILE_FLAG_BACKUP_SEMANTICS
1794 : 0,
1795 NULL
1796 );
1797 if ( h != INVALID_HANDLE_VALUE )
1798 CloseHandle(h);
1799
1800 return h != INVALID_HANDLE_VALUE;
1801 }
1802 #endif // __WINDOWS__
1803
1804 bool wxIsWritable(const wxString &path)
1805 {
1806 #if defined( __UNIX__ ) || defined(__OS2__)
1807 // access() will take in count also symbolic links
1808 return wxAccess(path.c_str(), W_OK) == 0;
1809 #elif defined( __WINDOWS__ )
1810 return wxCheckWin32Permission(path, GENERIC_WRITE);
1811 #else
1812 wxUnusedVar(path);
1813 // TODO
1814 return false;
1815 #endif
1816 }
1817
1818 bool wxIsReadable(const wxString &path)
1819 {
1820 #if defined( __UNIX__ ) || defined(__OS2__)
1821 // access() will take in count also symbolic links
1822 return wxAccess(path.c_str(), R_OK) == 0;
1823 #elif defined( __WINDOWS__ )
1824 return wxCheckWin32Permission(path, GENERIC_READ);
1825 #else
1826 wxUnusedVar(path);
1827 // TODO
1828 return false;
1829 #endif
1830 }
1831
1832 bool wxIsExecutable(const wxString &path)
1833 {
1834 #if defined( __UNIX__ ) || defined(__OS2__)
1835 // access() will take in count also symbolic links
1836 return wxAccess(path.c_str(), X_OK) == 0;
1837 #elif defined( __WINDOWS__ )
1838 return wxCheckWin32Permission(path, GENERIC_EXECUTE);
1839 #else
1840 wxUnusedVar(path);
1841 // TODO
1842 return false;
1843 #endif
1844 }
1845
1846 // Return the type of an open file
1847 //
1848 // Some file types on some platforms seem seekable but in fact are not.
1849 // The main use of this function is to allow such cases to be detected
1850 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1851 //
1852 // This is important for the archive streams, which benefit greatly from
1853 // being able to seek on a stream, but which will produce corrupt archives
1854 // if they unknowingly seek on a non-seekable stream.
1855 //
1856 // wxFILE_KIND_DISK is a good catch all return value, since other values
1857 // disable features of the archive streams. Some other value must be returned
1858 // for a file type that appears seekable but isn't.
1859 //
1860 // Known examples:
1861 // * Pipes on Windows
1862 // * Files on VMS with a record format other than StreamLF
1863 //
1864 wxFileKind wxGetFileKind(int fd)
1865 {
1866 #if defined __WINDOWS__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1867 switch (::GetFileType(wxGetOSFHandle(fd)) & ~FILE_TYPE_REMOTE)
1868 {
1869 case FILE_TYPE_CHAR:
1870 return wxFILE_KIND_TERMINAL;
1871 case FILE_TYPE_DISK:
1872 return wxFILE_KIND_DISK;
1873 case FILE_TYPE_PIPE:
1874 return wxFILE_KIND_PIPE;
1875 }
1876
1877 return wxFILE_KIND_UNKNOWN;
1878
1879 #elif defined(__UNIX__)
1880 if (isatty(fd))
1881 return wxFILE_KIND_TERMINAL;
1882
1883 struct stat st;
1884 fstat(fd, &st);
1885
1886 if (S_ISFIFO(st.st_mode))
1887 return wxFILE_KIND_PIPE;
1888 if (!S_ISREG(st.st_mode))
1889 return wxFILE_KIND_UNKNOWN;
1890
1891 #if defined(__VMS__)
1892 if (st.st_fab_rfm != FAB$C_STMLF)
1893 return wxFILE_KIND_UNKNOWN;
1894 #endif
1895
1896 return wxFILE_KIND_DISK;
1897
1898 #else
1899 #define wxFILEKIND_STUB
1900 (void)fd;
1901 return wxFILE_KIND_DISK;
1902 #endif
1903 }
1904
1905 wxFileKind wxGetFileKind(FILE *fp)
1906 {
1907 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1908 // Should be fixed in version 1.4.
1909 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
1910 (void)fp;
1911 return wxFILE_KIND_DISK;
1912 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
1913 return fp ? wxGetFileKind(_fileno(fp)) : wxFILE_KIND_UNKNOWN;
1914 #else
1915 return fp ? wxGetFileKind(fileno(fp)) : wxFILE_KIND_UNKNOWN;
1916 #endif
1917 }
1918
1919
1920 //------------------------------------------------------------------------
1921 // wild character routines
1922 //------------------------------------------------------------------------
1923
1924 bool wxIsWild( const wxString& pattern )
1925 {
1926 for ( wxString::const_iterator p = pattern.begin(); p != pattern.end(); ++p )
1927 {
1928 switch ( (*p).GetValue() )
1929 {
1930 case wxT('?'):
1931 case wxT('*'):
1932 case wxT('['):
1933 case wxT('{'):
1934 return true;
1935
1936 case wxT('\\'):
1937 if ( ++p == pattern.end() )
1938 return false;
1939 }
1940 }
1941 return false;
1942 }
1943
1944 /*
1945 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1946 *
1947 * The match procedure is public domain code (from ircII's reg.c)
1948 * but modified to suit our tastes (RN: No "%" syntax I guess)
1949 */
1950
1951 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1952 {
1953 if (text.empty())
1954 {
1955 /* Match if both are empty. */
1956 return pat.empty();
1957 }
1958
1959 const wxChar *m = pat.c_str(),
1960 *n = text.c_str(),
1961 *ma = NULL,
1962 *na = NULL;
1963 int just = 0,
1964 acount = 0,
1965 count = 0;
1966
1967 if (dot_special && (*n == wxT('.')))
1968 {
1969 /* Never match so that hidden Unix files
1970 * are never found. */
1971 return false;
1972 }
1973
1974 for (;;)
1975 {
1976 if (*m == wxT('*'))
1977 {
1978 ma = ++m;
1979 na = n;
1980 just = 1;
1981 acount = count;
1982 }
1983 else if (*m == wxT('?'))
1984 {
1985 m++;
1986 if (!*n++)
1987 return false;
1988 }
1989 else
1990 {
1991 if (*m == wxT('\\'))
1992 {
1993 m++;
1994 /* Quoting "nothing" is a bad thing */
1995 if (!*m)
1996 return false;
1997 }
1998 if (!*m)
1999 {
2000 /*
2001 * If we are out of both strings or we just
2002 * saw a wildcard, then we can say we have a
2003 * match
2004 */
2005 if (!*n)
2006 return true;
2007 if (just)
2008 return true;
2009 just = 0;
2010 goto not_matched;
2011 }
2012 /*
2013 * We could check for *n == NULL at this point, but
2014 * since it's more common to have a character there,
2015 * check to see if they match first (m and n) and
2016 * then if they don't match, THEN we can check for
2017 * the NULL of n
2018 */
2019 just = 0;
2020 if (*m == *n)
2021 {
2022 m++;
2023 count++;
2024 n++;
2025 }
2026 else
2027 {
2028
2029 not_matched:
2030
2031 /*
2032 * If there are no more characters in the
2033 * string, but we still need to find another
2034 * character (*m != NULL), then it will be
2035 * impossible to match it
2036 */
2037 if (!*n)
2038 return false;
2039
2040 if (ma)
2041 {
2042 m = ma;
2043 n = ++na;
2044 count = acount;
2045 }
2046 else
2047 return false;
2048 }
2049 }
2050 }
2051 }
2052
2053 #ifdef __VISUALC__
2054 #pragma warning(default:4706) // assignment within conditional expression
2055 #endif // VC++