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