]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
wxStaticBox constructor is not supposed to take a wxValidator
[wxWidgets.git] / src / common / filefn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "filefn.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26 #include "wx/defs.h"
27
28 #ifdef __BORLANDC__
29 #pragma hdrstop
30 #endif
31
32 #include "wx/utils.h"
33 #include "wx/intl.h"
34 #include "wx/file.h" // This does include filefn.h
35 #include "wx/filename.h"
36 #include "wx/dir.h"
37
38 // there are just too many of those...
39 #ifdef __VISUALC__
40 #pragma warning(disable:4706) // assignment within conditional expression
41 #endif // VC++
42
43 #include <ctype.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #if !defined(__WATCOMC__)
48 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
49 #include <errno.h>
50 #endif
51 #endif
52
53 #if defined(__WXMAC__)
54 #include "wx/mac/private.h" // includes mac headers
55 #endif
56
57 #include "wx/log.h"
58
59 // No, Cygwin doesn't appear to have fnmatch.h after all.
60 #if defined(HAVE_FNMATCH_H)
61 #include "fnmatch.h"
62 #endif
63
64 #ifdef __WINDOWS__
65 #include "wx/msw/wrapwin.h"
66 #include "wx/msw/mslu.h"
67
68 // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
69 //
70 // note that it must be included after <windows.h>
71 #ifdef __GNUWIN32__
72 #ifdef __CYGWIN__
73 #include <sys/cygwin.h>
74 #endif
75 #endif // __GNUWIN32__
76 #endif // __WINDOWS__
77
78 // TODO: Borland probably has _wgetcwd as well?
79 #ifdef _MSC_VER
80 #define HAVE_WGETCWD
81 #endif
82
83 // ----------------------------------------------------------------------------
84 // constants
85 // ----------------------------------------------------------------------------
86
87 #ifndef _MAXPATHLEN
88 #define _MAXPATHLEN 1024
89 #endif
90
91 #ifdef __WXMAC__
92 # include "MoreFilesX.h"
93 #endif
94
95 // ----------------------------------------------------------------------------
96 // private globals
97 // ----------------------------------------------------------------------------
98
99 // MT-FIXME: get rid of this horror and all code using it
100 static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
101
102 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
103 //
104 // VisualAge C++ V4.0 cannot have any external linkage const decs
105 // in headers included by more than one primary source
106 //
107 const off_t wxInvalidOffset = (off_t)-1;
108 #endif
109
110 // ----------------------------------------------------------------------------
111 // macros
112 // ----------------------------------------------------------------------------
113
114 // we need to translate Mac filenames before passing them to OS functions
115 #define OS_FILENAME(s) (s.fn_str())
116
117 // ============================================================================
118 // implementation
119 // ============================================================================
120
121 #ifdef wxNEED_WX_UNISTD_H
122
123 WXDLLEXPORT int wxStat( const wxChar *file_name, wxStructStat *buf )
124 {
125 return stat( wxConvFile.cWX2MB( file_name ), buf );
126 }
127
128 WXDLLEXPORT int wxAccess( const wxChar *pathname, int mode )
129 {
130 return access( wxConvFile.cWX2MB( pathname ), mode );
131 }
132
133 WXDLLEXPORT int wxOpen( const wxChar *pathname, int flags, mode_t mode )
134 {
135 return open( wxConvFile.cWX2MB( pathname ), flags, mode );
136 }
137
138 #endif
139 // wxNEED_WX_UNISTD_H
140
141 // ----------------------------------------------------------------------------
142 // wxPathList
143 // ----------------------------------------------------------------------------
144
145 // IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
146
147 static inline wxChar* MYcopystring(const wxString& s)
148 {
149 wxChar* copy = new wxChar[s.length() + 1];
150 return wxStrcpy(copy, s.c_str());
151 }
152
153 static inline wxChar* MYcopystring(const wxChar* s)
154 {
155 wxChar* copy = new wxChar[wxStrlen(s) + 1];
156 return wxStrcpy(copy, s);
157 }
158
159 void wxPathList::Add (const wxString& path)
160 {
161 wxStringList::Add (WXSTRINGCAST path);
162 }
163
164 // Add paths e.g. from the PATH environment variable
165 void wxPathList::AddEnvList (const wxString& envVariable)
166 {
167 // No environment variables on WinCE
168 #ifndef __WXWINCE__
169 static const wxChar PATH_TOKS[] =
170 #if defined(__WINDOWS__) || defined(__OS2__)
171 /*
172 The space has been removed from the tokenizers, otherwise a
173 path such as "C:\Program Files" would be split into 2 paths:
174 "C:\Program" and "Files"
175 */
176 // wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
177 wxT(";"); // Don't seperate with colon in DOS (used for drive)
178 #else
179 wxT(" :;");
180 #endif
181
182 wxChar *val = wxGetenv (WXSTRINGCAST envVariable);
183 if (val && *val)
184 {
185 wxChar *s = MYcopystring (val);
186 wxChar *save_ptr, *token = wxStrtok (s, PATH_TOKS, &save_ptr);
187
188 if (token)
189 {
190 Add(token);
191 while (token)
192 {
193 if ( (token = wxStrtok ((wxChar *) NULL, PATH_TOKS, &save_ptr))
194 != NULL )
195 {
196 Add(token);
197 }
198 }
199 }
200
201 // suppress warning about unused variable save_ptr when wxStrtok() is a
202 // macro which throws away its third argument
203 save_ptr = token;
204
205 delete [] s;
206 }
207 #endif
208 }
209
210 // Given a full filename (with path), ensure that that file can
211 // be accessed again USING FILENAME ONLY by adding the path
212 // to the list if not already there.
213 void wxPathList::EnsureFileAccessible (const wxString& path)
214 {
215 wxString path_only(wxPathOnly(path));
216 if ( !path_only.IsEmpty() )
217 {
218 if ( !Member(path_only) )
219 Add(path_only);
220 }
221 }
222
223 bool wxPathList::Member (const wxString& path)
224 {
225 for (wxStringList::compatibility_iterator node = GetFirst(); node; node = node->GetNext())
226 {
227 wxString path2( node->GetData() );
228 if (
229 #if defined(__WINDOWS__) || defined(__OS2__) || defined(__VMS__) || defined (__WXMAC__)
230 // Case INDEPENDENT
231 path.CompareTo (path2, wxString::ignoreCase) == 0
232 #else
233 // Case sensitive File System
234 path.CompareTo (path2) == 0
235 #endif
236 )
237 return true;
238 }
239 return false;
240 }
241
242 wxString wxPathList::FindValidPath (const wxString& file)
243 {
244 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer, file)))
245 return wxString(wxFileFunctionsBuffer);
246
247 wxChar buf[_MAXPATHLEN];
248 wxStrcpy(buf, wxFileFunctionsBuffer);
249
250 wxChar *filename = wxIsAbsolutePath (buf) ? wxFileNameFromPath (buf) : (wxChar *)buf;
251
252 for (wxStringList::compatibility_iterator node = GetFirst(); node; node = node->GetNext())
253 {
254 const wxChar *path = node->GetData();
255 wxStrcpy (wxFileFunctionsBuffer, path);
256 wxChar ch = wxFileFunctionsBuffer[wxStrlen(wxFileFunctionsBuffer)-1];
257 if (ch != wxT('\\') && ch != wxT('/'))
258 wxStrcat (wxFileFunctionsBuffer, wxT("/"));
259 wxStrcat (wxFileFunctionsBuffer, filename);
260 #ifdef __WINDOWS__
261 wxUnix2DosFilename (wxFileFunctionsBuffer);
262 #endif
263 if (wxFileExists (wxFileFunctionsBuffer))
264 {
265 return wxString(wxFileFunctionsBuffer); // Found!
266 }
267 } // for()
268
269 return wxEmptyString; // Not found
270 }
271
272 wxString wxPathList::FindAbsoluteValidPath (const wxString& file)
273 {
274 wxString f = FindValidPath(file);
275 if ( f.empty() || wxIsAbsolutePath(f) )
276 return f;
277
278 wxString buf;
279 wxGetWorkingDirectory(wxStringBuffer(buf, _MAXPATHLEN), _MAXPATHLEN);
280
281 if ( !wxEndsWithPathSeparator(buf) )
282 {
283 buf += wxFILE_SEP_PATH;
284 }
285 buf += f;
286
287 return buf;
288 }
289
290 bool
291 wxFileExists (const wxString& filename)
292 {
293 // we must use GetFileAttributes() instead of the ANSI C functions because
294 // it can cope with network (UNC) paths unlike them
295 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
296 DWORD ret = ::GetFileAttributes(filename);
297
298 return (ret != (DWORD)-1) && !(ret & FILE_ATTRIBUTE_DIRECTORY);
299 #else // !__WIN32__
300 wxStructStat st;
301 return wxStat(filename, &st) == 0 && (st.st_mode & S_IFREG);
302 #endif // __WIN32__/!__WIN32__
303 }
304
305 bool
306 wxIsAbsolutePath (const wxString& filename)
307 {
308 if (filename != wxT(""))
309 {
310 #if defined(__WXMAC__) && !defined(__DARWIN__)
311 // Classic or Carbon CodeWarrior like
312 // Carbon with Apple DevTools is Unix like
313
314 // This seems wrong to me, but there is no fix. since
315 // "MacOS:MyText.txt" is absolute whereas "MyDir:MyText.txt"
316 // is not. Or maybe ":MyDir:MyText.txt" has to be used? RR.
317 if (filename.Find(':') != wxNOT_FOUND && filename[0] != ':')
318 return true ;
319 #else
320 // Unix like or Windows
321 if (filename[0] == wxT('/'))
322 return true;
323 #endif
324 #ifdef __VMS__
325 if ((filename[0] == wxT('[') && filename[1] != wxT('.')))
326 return true;
327 #endif
328 #if defined(__WINDOWS__) || defined(__OS2__)
329 // MSDOS like
330 if (filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':')))
331 return true;
332 #endif
333 }
334 return false ;
335 }
336
337 /*
338 * Strip off any extension (dot something) from end of file,
339 * IF one exists. Inserts zero into buffer.
340 *
341 */
342
343 void wxStripExtension(wxChar *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(wxString& buffer)
359 {
360 size_t len = buffer.Length();
361 size_t i = len-1;
362 while (i > 0)
363 {
364 if (buffer.GetChar(i) == wxT('.'))
365 {
366 buffer = buffer.Left(i);
367 break;
368 }
369 i --;
370 }
371 }
372
373 // Destructive removal of /./ and /../ stuff
374 wxChar *wxRealPath (wxChar *path)
375 {
376 #ifdef __WXMSW__
377 static const wxChar SEP = wxT('\\');
378 wxUnix2DosFilename(path);
379 #else
380 static const wxChar SEP = wxT('/');
381 #endif
382 if (path[0] && path[1]) {
383 /* MATTHEW: special case "/./x" */
384 wxChar *p;
385 if (path[2] == SEP && path[1] == wxT('.'))
386 p = &path[0];
387 else
388 p = &path[2];
389 for (; *p; p++)
390 {
391 if (*p == SEP)
392 {
393 if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
394 {
395 wxChar *q;
396 for (q = p - 1; q >= path && *q != SEP; q--)
397 {
398 // Empty
399 }
400
401 if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
402 && (q - 1 <= path || q[-1] != SEP))
403 {
404 wxStrcpy (q, p + 3);
405 if (path[0] == wxT('\0'))
406 {
407 path[0] = SEP;
408 path[1] = wxT('\0');
409 }
410 #if defined(__WXMSW__) || defined(__OS2__)
411 /* Check that path[2] is NULL! */
412 else if (path[1] == wxT(':') && !path[2])
413 {
414 path[2] = SEP;
415 path[3] = wxT('\0');
416 }
417 #endif
418 p = q - 1;
419 }
420 }
421 else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
422 wxStrcpy (p, p + 2);
423 }
424 }
425 }
426 return path;
427 }
428
429 // Must be destroyed
430 wxChar *wxCopyAbsolutePath(const wxString& filename)
431 {
432 if (filename == wxT(""))
433 return (wxChar *) NULL;
434
435 if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename))) {
436 wxChar buf[_MAXPATHLEN];
437 buf[0] = wxT('\0');
438 wxGetWorkingDirectory(buf, WXSIZEOF(buf));
439 wxChar ch = buf[wxStrlen(buf) - 1];
440 #ifdef __WXMSW__
441 if (ch != wxT('\\') && ch != wxT('/'))
442 wxStrcat(buf, wxT("\\"));
443 #else
444 if (ch != wxT('/'))
445 wxStrcat(buf, wxT("/"));
446 #endif
447 wxStrcat(buf, wxFileFunctionsBuffer);
448 return MYcopystring( wxRealPath(buf) );
449 }
450 return MYcopystring( wxFileFunctionsBuffer );
451 }
452
453 /*-
454 Handles:
455 ~/ => home dir
456 ~user/ => user's home dir
457 If the environment variable a = "foo" and b = "bar" then:
458 Unix:
459 $a => foo
460 $a$b => foobar
461 $a.c => foo.c
462 xxx$a => xxxfoo
463 ${a}! => foo!
464 $(b)! => bar!
465 \$a => \$a
466 MSDOS:
467 $a ==> $a
468 $(a) ==> foo
469 $(a)$b ==> foo$b
470 $(a)$(b)==> foobar
471 test.$$ ==> test.$$
472 */
473
474 /* input name in name, pathname output to buf. */
475
476 wxChar *wxExpandPath(wxChar *buf, const wxChar *name)
477 {
478 register wxChar *d, *s, *nm;
479 wxChar lnm[_MAXPATHLEN];
480 int q;
481
482 // Some compilers don't like this line.
483 // const wxChar trimchars[] = wxT("\n \t");
484
485 wxChar trimchars[4];
486 trimchars[0] = wxT('\n');
487 trimchars[1] = wxT(' ');
488 trimchars[2] = wxT('\t');
489 trimchars[3] = 0;
490
491 #ifdef __WXMSW__
492 const wxChar SEP = wxT('\\');
493 #else
494 const wxChar SEP = wxT('/');
495 #endif
496 buf[0] = wxT('\0');
497 if (name == NULL || *name == wxT('\0'))
498 return buf;
499 nm = MYcopystring(name); // Make a scratch copy
500 wxChar *nm_tmp = nm;
501
502 /* Skip leading whitespace and cr */
503 while (wxStrchr((wxChar *)trimchars, *nm) != NULL)
504 nm++;
505 /* And strip off trailing whitespace and cr */
506 s = nm + (q = wxStrlen(nm)) - 1;
507 while (q-- && wxStrchr((wxChar *)trimchars, *s) != NULL)
508 *s = wxT('\0');
509
510 s = nm;
511 d = lnm;
512 #ifdef __WXMSW__
513 q = FALSE;
514 #else
515 q = nm[0] == wxT('\\') && nm[1] == wxT('~');
516 #endif
517
518 /* Expand inline environment variables */
519 #ifdef __VISAGECPP__
520 while (*d)
521 {
522 *d++ = *s;
523 if(*s == wxT('\\'))
524 {
525 *(d - 1) = *++s;
526 if (*d)
527 {
528 s++;
529 continue;
530 }
531 else
532 break;
533 }
534 else
535 #else
536 while ((*d++ = *s) != 0) {
537 # ifndef __WXMSW__
538 if (*s == wxT('\\')) {
539 if ((*(d - 1) = *++s)) {
540 s++;
541 continue;
542 } else
543 break;
544 } else
545 # endif
546 #endif
547 // No env variables on WinCE
548 #ifndef __WXWINCE__
549 #ifdef __WXMSW__
550 if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
551 #else
552 if (*s++ == wxT('$'))
553 #endif
554 {
555 register wxChar *start = d;
556 register int braces = (*s == wxT('{') || *s == wxT('('));
557 register wxChar *value;
558 while ((*d++ = *s) != 0)
559 if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
560 break;
561 else
562 s++;
563 *--d = 0;
564 value = wxGetenv(braces ? start + 1 : start);
565 if (value) {
566 for ((d = start - 1); (*d++ = *value++) != 0;)
567 {
568 // Empty
569 }
570
571 d--;
572 if (braces && *s)
573 s++;
574 }
575 }
576 #endif
577 // __WXWINCE__
578 }
579
580 /* Expand ~ and ~user */
581 nm = lnm;
582 if (nm[0] == wxT('~') && !q)
583 {
584 /* prefix ~ */
585 if (nm[1] == SEP || nm[1] == 0)
586 { /* ~/filename */
587 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
588 if ((s = WXSTRINGCAST wxGetUserHome(wxT(""))) != NULL) {
589 if (*++nm)
590 nm++;
591 }
592 } else
593 { /* ~user/filename */
594 register wxChar *nnm;
595 register wxChar *home;
596 for (s = nm; *s && *s != SEP; s++)
597 {
598 // Empty
599 }
600 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
601 was_sep = (*s == SEP);
602 nnm = *s ? s + 1 : s;
603 *s = 0;
604 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
605 if ((home = WXSTRINGCAST wxGetUserHome(wxString(nm + 1))) == NULL) {
606 if (was_sep) /* replace only if it was there: */
607 *s = SEP;
608 s = NULL;
609 } else {
610 nm = nnm;
611 s = home;
612 }
613 }
614 }
615
616 d = buf;
617 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
618 /* Copy home dir */
619 while (wxT('\0') != (*d++ = *s++))
620 /* loop */;
621 // Handle root home
622 if (d - 1 > buf && *(d - 2) != SEP)
623 *(d - 1) = SEP;
624 }
625 s = nm;
626 while ((*d++ = *s++) != 0)
627 {
628 // Empty
629 }
630 delete[] nm_tmp; // clean up alloc
631 /* Now clean up the buffer */
632 return wxRealPath(buf);
633 }
634
635 /* Contract Paths to be build upon an environment variable
636 component:
637
638 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
639
640 The call wxExpandPath can convert these back!
641 */
642 wxChar *
643 wxContractPath (const wxString& filename, const wxString& envname, const wxString& user)
644 {
645 static wxChar dest[_MAXPATHLEN];
646
647 if (filename == wxT(""))
648 return (wxChar *) NULL;
649
650 wxStrcpy (dest, WXSTRINGCAST filename);
651 #ifdef __WXMSW__
652 wxUnix2DosFilename(dest);
653 #endif
654
655 // Handle environment
656 const wxChar *val;
657 #ifndef __WXWINCE__
658 wxChar *tcp;
659 if (envname != WXSTRINGCAST NULL && (val = wxGetenv (WXSTRINGCAST envname)) != NULL &&
660 (tcp = wxStrstr (dest, val)) != NULL)
661 {
662 wxStrcpy (wxFileFunctionsBuffer, tcp + wxStrlen (val));
663 *tcp++ = wxT('$');
664 *tcp++ = wxT('{');
665 wxStrcpy (tcp, WXSTRINGCAST envname);
666 wxStrcat (tcp, wxT("}"));
667 wxStrcat (tcp, wxFileFunctionsBuffer);
668 }
669 #endif
670
671 // Handle User's home (ignore root homes!)
672 val = wxGetUserHome (user);
673 if (!val)
674 return dest;
675
676 const size_t len = wxStrlen(val);
677 if (len <= 2)
678 return dest;
679
680 if (wxStrncmp(dest, val, len) == 0)
681 {
682 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
683 if (user != wxT(""))
684 wxStrcat(wxFileFunctionsBuffer, (const wxChar*) user);
685 wxStrcat(wxFileFunctionsBuffer, dest + len);
686 wxStrcpy (dest, wxFileFunctionsBuffer);
687 }
688
689 return dest;
690 }
691
692 // Return just the filename, not the path (basename)
693 wxChar *wxFileNameFromPath (wxChar *path)
694 {
695 wxString p = path;
696 wxString n = wxFileNameFromPath(p);
697
698 return path + p.length() - n.length();
699 }
700
701 wxString wxFileNameFromPath (const wxString& path)
702 {
703 wxString name, ext;
704 wxFileName::SplitPath(path, NULL, &name, &ext);
705
706 wxString fullname = name;
707 if ( !ext.empty() )
708 {
709 fullname << wxFILE_SEP_EXT << ext;
710 }
711
712 return fullname;
713 }
714
715 // Return just the directory, or NULL if no directory
716 wxChar *
717 wxPathOnly (wxChar *path)
718 {
719 if (path && *path)
720 {
721 static wxChar buf[_MAXPATHLEN];
722
723 // Local copy
724 wxStrcpy (buf, path);
725
726 int l = wxStrlen(path);
727 int i = l - 1;
728
729 // Search backward for a backward or forward slash
730 while (i > -1)
731 {
732 #if defined(__WXMAC__) && !defined(__DARWIN__)
733 // Classic or Carbon CodeWarrior like
734 // Carbon with Apple DevTools is Unix like
735 if (path[i] == wxT(':') )
736 {
737 buf[i] = 0;
738 return buf;
739 }
740 #else
741 // Unix like or Windows
742 if (path[i] == wxT('/') || path[i] == wxT('\\'))
743 {
744 buf[i] = 0;
745 return buf;
746 }
747 #endif
748 #ifdef __VMS__
749 if (path[i] == wxT(']'))
750 {
751 buf[i+1] = 0;
752 return buf;
753 }
754 #endif
755 i --;
756 }
757
758 #if defined(__WXMSW__) || defined(__OS2__)
759 // Try Drive specifier
760 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
761 {
762 // A:junk --> A:. (since A:.\junk Not A:\junk)
763 buf[2] = wxT('.');
764 buf[3] = wxT('\0');
765 return buf;
766 }
767 #endif
768 }
769 return (wxChar *) NULL;
770 }
771
772 // Return just the directory, or NULL if no directory
773 wxString wxPathOnly (const wxString& path)
774 {
775 if (path != wxT(""))
776 {
777 wxChar buf[_MAXPATHLEN];
778
779 // Local copy
780 wxStrcpy (buf, WXSTRINGCAST path);
781
782 int l = path.Length();
783 int i = l - 1;
784
785 // Search backward for a backward or forward slash
786 while (i > -1)
787 {
788 #if defined(__WXMAC__) && !defined(__DARWIN__)
789 // Classic or Carbon CodeWarrior like
790 // Carbon with Apple DevTools is Unix like
791 if (path[i] == wxT(':') )
792 {
793 buf[i] = 0;
794 return wxString(buf);
795 }
796 #else
797 // Unix like or Windows
798 if (path[i] == wxT('/') || path[i] == wxT('\\'))
799 {
800 // Don't return an empty string
801 if (i == 0)
802 i ++;
803 buf[i] = 0;
804 return wxString(buf);
805 }
806 #endif
807 #ifdef __VMS__
808 if (path[i] == wxT(']'))
809 {
810 buf[i+1] = 0;
811 return wxString(buf);
812 }
813 #endif
814 i --;
815 }
816
817 #if defined(__WXMSW__) || defined(__OS2__)
818 // Try Drive specifier
819 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
820 {
821 // A:junk --> A:. (since A:.\junk Not A:\junk)
822 buf[2] = wxT('.');
823 buf[3] = wxT('\0');
824 return wxString(buf);
825 }
826 #endif
827 }
828 return wxString(wxT(""));
829 }
830
831 // Utility for converting delimiters in DOS filenames to UNIX style
832 // and back again - or we get nasty problems with delimiters.
833 // Also, convert to lower case, since case is significant in UNIX.
834
835 #if defined(__WXMAC__)
836
837 #if TARGET_API_MAC_OSX
838 #define kDefaultPathStyle kCFURLPOSIXPathStyle
839 #else
840 #define kDefaultPathStyle kCFURLHFSPathStyle
841 #endif
842
843 wxString wxMacFSRefToPath( const FSRef *fsRef , CFStringRef additionalPathComponent )
844 {
845 CFURLRef fullURLRef;
846 fullURLRef = CFURLCreateFromFSRef(NULL, fsRef);
847 if ( additionalPathComponent )
848 {
849 CFURLRef parentURLRef = fullURLRef ;
850 fullURLRef = CFURLCreateCopyAppendingPathComponent(NULL, parentURLRef,
851 additionalPathComponent,false);
852 CFRelease( parentURLRef ) ;
853 }
854 CFStringRef cfString = CFURLCopyFileSystemPath(fullURLRef, kDefaultPathStyle);
855 CFRelease( fullURLRef ) ;
856 return wxMacCFStringHolder(cfString).AsString(wxLocale::GetSystemEncoding());
857 }
858
859 OSStatus wxMacPathToFSRef( const wxString&path , FSRef *fsRef )
860 {
861 OSStatus err = noErr ;
862 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, wxMacCFStringHolder(path ,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle, false);
863 if ( NULL != url )
864 {
865 if ( CFURLGetFSRef(url, fsRef) == false )
866 err = fnfErr ;
867 CFRelease( url ) ;
868 }
869 else
870 {
871 err = fnfErr ;
872 }
873 return err ;
874 }
875
876 wxString wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname )
877 {
878 CFStringRef cfname = CFStringCreateWithCharacters( kCFAllocatorDefault,
879 uniname->unicode,
880 uniname->length );
881 return wxMacCFStringHolder(cfname).AsString() ;
882 }
883
884 wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
885 {
886 FSRef fsRef ;
887 if ( FSpMakeFSRef( spec , &fsRef) == noErr )
888 {
889 return wxMacFSRefToPath( &fsRef ) ;
890 }
891 return wxEmptyString ;
892 }
893
894 void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
895 {
896 OSStatus err = noErr ;
897 FSRef fsRef ;
898 wxMacPathToFSRef( path , &fsRef ) ;
899 err = FSRefMakeFSSpec( &fsRef , spec ) ;
900 }
901
902 #endif // __WXMAC__
903
904 void
905 wxDos2UnixFilename (wxChar *s)
906 {
907 if (s)
908 while (*s)
909 {
910 if (*s == _T('\\'))
911 *s = _T('/');
912 #ifdef __WXMSW__
913 else
914 *s = wxTolower (*s); // Case INDEPENDENT
915 #endif
916 s++;
917 }
918 }
919
920 void
921 #if defined(__WXMSW__) || defined(__OS2__)
922 wxUnix2DosFilename (wxChar *s)
923 #else
924 wxUnix2DosFilename (wxChar *WXUNUSED(s) )
925 #endif
926 {
927 // Yes, I really mean this to happen under DOS only! JACS
928 #if defined(__WXMSW__) || defined(__OS2__)
929 if (s)
930 while (*s)
931 {
932 if (*s == wxT('/'))
933 *s = wxT('\\');
934 s++;
935 }
936 #endif
937 }
938
939 // Concatenate two files to form third
940 bool
941 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
942 {
943 wxString outfile;
944 if ( !wxGetTempFileName( wxT("cat"), outfile) )
945 return false;
946
947 FILE *fp1 wxDUMMY_INITIALIZE(NULL);
948 FILE *fp2 = NULL;
949 FILE *fp3 = NULL;
950 // Open the inputs and outputs
951 if ((fp1 = wxFopen ( file1, wxT("rb"))) == NULL ||
952 (fp2 = wxFopen ( file2, wxT("rb"))) == NULL ||
953 (fp3 = wxFopen ( outfile, wxT("wb"))) == NULL)
954 {
955 if (fp1)
956 fclose (fp1);
957 if (fp2)
958 fclose (fp2);
959 if (fp3)
960 fclose (fp3);
961 return false;
962 }
963
964 int ch;
965 while ((ch = getc (fp1)) != EOF)
966 (void) putc (ch, fp3);
967 fclose (fp1);
968
969 while ((ch = getc (fp2)) != EOF)
970 (void) putc (ch, fp3);
971 fclose (fp2);
972
973 fclose (fp3);
974 bool result = wxRenameFile(outfile, file3);
975 return result;
976 }
977
978 // Copy files
979 bool
980 wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
981 {
982 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
983 // CopyFile() copies file attributes and modification time too, so use it
984 // instead of our code if available
985 //
986 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
987 if ( !::CopyFile(file1, file2, !overwrite) )
988 {
989 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
990 file1.c_str(), file2.c_str());
991
992 return false;
993 }
994 #elif defined(__OS2__)
995 if ( ::DosCopy(file2, file2, overwrite ? DCPY_EXISTING : 0) != 0 )
996 return false;
997 #else // !Win32
998
999 wxStructStat fbuf;
1000 // get permissions of file1
1001 if ( wxStat( file1.c_str(), &fbuf) != 0 )
1002 {
1003 // the file probably doesn't exist or we haven't the rights to read
1004 // from it anyhow
1005 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1006 file1.c_str());
1007 return false;
1008 }
1009
1010 // open file1 for reading
1011 wxFile fileIn(file1, wxFile::read);
1012 if ( !fileIn.IsOpened() )
1013 return false;
1014
1015 // remove file2, if it exists. This is needed for creating
1016 // file2 with the correct permissions in the next step
1017 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
1018 {
1019 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1020 file2.c_str());
1021 return false;
1022 }
1023
1024 #ifdef __UNIX__
1025 // reset the umask as we want to create the file with exactly the same
1026 // permissions as the original one
1027 mode_t oldUmask = umask( 0 );
1028 #endif // __UNIX__
1029
1030 // create file2 with the same permissions than file1 and open it for
1031 // writing
1032
1033 wxFile fileOut;
1034 if ( !fileOut.Create(file2, overwrite, fbuf.st_mode & 0777) )
1035 return false;
1036
1037 #ifdef __UNIX__
1038 /// restore the old umask
1039 umask(oldUmask);
1040 #endif // __UNIX__
1041
1042 // copy contents of file1 to file2
1043 char buf[4096];
1044 size_t count;
1045 for ( ;; )
1046 {
1047 count = fileIn.Read(buf, WXSIZEOF(buf));
1048 if ( fileIn.Error() )
1049 return false;
1050
1051 // end of file?
1052 if ( !count )
1053 break;
1054
1055 if ( fileOut.Write(buf, count) < count )
1056 return false;
1057 }
1058
1059 // we can expect fileIn to be closed successfully, but we should ensure
1060 // that fileOut was closed as some write errors (disk full) might not be
1061 // detected before doing this
1062 if ( !fileIn.Close() || !fileOut.Close() )
1063 return false;
1064
1065 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1066 // no chmod in VA. Should be some permission API for HPFS386 partitions
1067 // however
1068 if ( chmod(OS_FILENAME(file2), fbuf.st_mode) != 0 )
1069 {
1070 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1071 file2.c_str());
1072 return false;
1073 }
1074 #endif // OS/2 || Mac
1075 #endif // __WXMSW__ && __WIN32__
1076
1077 return true;
1078 }
1079
1080 bool
1081 wxRenameFile (const wxString& file1, const wxString& file2)
1082 {
1083 #ifndef __WXWINCE__
1084 // Normal system call
1085 if ( wxRename (file1, file2) == 0 )
1086 return true;
1087 #endif
1088
1089 // Try to copy
1090 if (wxCopyFile(file1, file2)) {
1091 wxRemoveFile(file1);
1092 return true;
1093 }
1094 // Give up
1095 return false;
1096 }
1097
1098 bool wxRemoveFile(const wxString& file)
1099 {
1100 #if defined(__VISUALC__) \
1101 || defined(__BORLANDC__) \
1102 || defined(__WATCOMC__) \
1103 || defined(__DMC__) \
1104 || defined(__GNUWIN32__) \
1105 || (defined(__MWERKS__) && defined(__MSL__))
1106 int res = wxRemove(file);
1107 #elif defined(__WXMAC__)
1108 int res = unlink(wxFNCONV(file));
1109 #else
1110 int res = unlink(OS_FILENAME(file));
1111 #endif
1112
1113 return res == 0;
1114 }
1115
1116 bool wxMkdir(const wxString& dir, int perm)
1117 {
1118 #if defined(__WXMAC__) && !defined(__UNIX__)
1119 return (mkdir( wxFNCONV(dir) , 0 ) == 0);
1120 #else // !Mac
1121 const wxChar *dirname = dir.c_str();
1122
1123 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1124 // for the GNU compiler
1125 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1126 #if defined(MSVCRT)
1127 wxUnusedVar(perm);
1128 if ( mkdir(wxFNCONV(dirname)) != 0 )
1129 #else
1130 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1131 #endif
1132 #elif defined(__OS2__)
1133 if (::DosCreateDir((PSZ)dirname, NULL) != 0) // enhance for EAB's??
1134 #elif defined(__DOS__)
1135 #if defined(__WATCOMC__)
1136 (void)perm;
1137 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1138 #elif defined(__DJGPP__)
1139 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1140 #else
1141 #error "Unsupported DOS compiler!"
1142 #endif
1143 #else // !MSW, !DOS and !OS/2 VAC++
1144 (void)perm;
1145 #ifdef __WXWINCE__
1146 if ( !CreateDirectory(dirname, NULL) )
1147 #else
1148 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1149 #endif
1150 #endif // !MSW/MSW
1151 {
1152 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1153
1154 return false;
1155 }
1156
1157 return true;
1158 #endif // Mac/!Mac
1159 }
1160
1161 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1162 {
1163 #ifdef __VMS__
1164 return false; //to be changed since rmdir exists in VMS7.x
1165 #elif defined(__OS2__)
1166 return (::DosDeleteDir((PSZ)dir.c_str()) == 0);
1167 #else
1168
1169 #ifdef __WXWINCE__
1170 return (CreateDirectory(dir, NULL) != 0);
1171 #else
1172 return (wxRmDir(OS_FILENAME(dir)) == 0);
1173 #endif
1174
1175 #endif
1176 }
1177
1178 // does the path exists? (may have or not '/' or '\\' at the end)
1179 bool wxPathExists(const wxChar *pszPathName)
1180 {
1181 wxString strPath(pszPathName);
1182
1183 #if defined(__WINDOWS__) || defined(__OS2__)
1184 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1185 // so remove all trailing backslashes from the path - but don't do this for
1186 // the pathes "d:\" (which are different from "d:") nor for just "\"
1187 while ( wxEndsWithPathSeparator(strPath) )
1188 {
1189 size_t len = strPath.length();
1190 if ( len == 1 || (len == 3 && strPath[len - 2] == _T(':')) )
1191 break;
1192
1193 strPath.Truncate(len - 1);
1194 }
1195 #endif // __WINDOWS__
1196
1197 #ifdef __OS2__
1198 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1199 if (strPath.length() == 2 && strPath[1u] == _T(':'))
1200 strPath << _T('.');
1201 #endif
1202
1203 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1204 // stat() can't cope with network paths
1205 DWORD ret = ::GetFileAttributes(strPath);
1206
1207 return (ret != (DWORD)-1) && (ret & FILE_ATTRIBUTE_DIRECTORY);
1208 #else // !__WIN32__
1209
1210 wxStructStat st;
1211 #ifndef __VISAGECPP__
1212 return wxStat(strPath.c_str(), &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR);
1213 #else
1214 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1215 return wxStat(pszPathName, &st) == 0 && (st.st_mode == S_IFDIR);
1216 #endif
1217
1218 #endif // __WIN32__/!__WIN32__
1219 }
1220
1221 // Get a temporary filename, opening and closing the file.
1222 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1223 {
1224 wxString filename = wxFileName::CreateTempFileName(prefix);
1225 if ( filename.empty() )
1226 return NULL;
1227
1228 if ( buf )
1229 wxStrcpy(buf, filename);
1230 else
1231 buf = MYcopystring(filename);
1232
1233 return buf;
1234 }
1235
1236 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1237 {
1238 buf = wxFileName::CreateTempFileName(prefix);
1239
1240 return !buf.empty();
1241 }
1242
1243 // Get first file name matching given wild card.
1244
1245 static wxDir *gs_dir = NULL;
1246 static wxString gs_dirPath;
1247
1248 wxString wxFindFirstFile(const wxChar *spec, int flags)
1249 {
1250 wxSplitPath(spec, &gs_dirPath, NULL, NULL);
1251 if ( gs_dirPath.IsEmpty() )
1252 gs_dirPath = wxT(".");
1253 if ( !wxEndsWithPathSeparator(gs_dirPath ) )
1254 gs_dirPath << wxFILE_SEP_PATH;
1255
1256 if (gs_dir)
1257 delete gs_dir;
1258 gs_dir = new wxDir(gs_dirPath);
1259
1260 if ( !gs_dir->IsOpened() )
1261 {
1262 wxLogSysError(_("Can not enumerate files '%s'"), spec);
1263 return wxEmptyString;
1264 }
1265
1266 int dirFlags;
1267 switch (flags)
1268 {
1269 case wxDIR: dirFlags = wxDIR_DIRS; break;
1270 case wxFILE: dirFlags = wxDIR_FILES; break;
1271 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1272 }
1273
1274 wxString result;
1275 gs_dir->GetFirst(&result, wxFileNameFromPath(wxString(spec)), dirFlags);
1276 if ( result.IsEmpty() )
1277 {
1278 wxDELETE(gs_dir);
1279 return result;
1280 }
1281
1282 return gs_dirPath + result;
1283 }
1284
1285 wxString wxFindNextFile()
1286 {
1287 wxASSERT_MSG( gs_dir, wxT("You must call wxFindFirstFile before!") );
1288
1289 wxString result;
1290 gs_dir->GetNext(&result);
1291
1292 if ( result.IsEmpty() )
1293 {
1294 wxDELETE(gs_dir);
1295 return result;
1296 }
1297
1298 return gs_dirPath + result;
1299 }
1300
1301
1302 // Get current working directory.
1303 // If buf is NULL, allocates space using new, else
1304 // copies into buf.
1305 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1306 {
1307 #ifdef __WXWINCE__
1308 return NULL;
1309 #else
1310 if ( !buf )
1311 {
1312 buf = new wxChar[sz + 1];
1313 }
1314
1315 bool ok wxDUMMY_INITIALIZE(false);
1316
1317 // for the compilers which have Unicode version of _getcwd(), call it
1318 // directly, for the others call the ANSI version and do the translation
1319 #if !wxUSE_UNICODE
1320 #define cbuf buf
1321 #else // wxUSE_UNICODE
1322 bool needsANSI = true;
1323
1324 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1325 // This is not legal code as the compiler
1326 // is allowed destroy the wxCharBuffer.
1327 // wxCharBuffer c_buffer(sz);
1328 // char *cbuf = (char*)(const char*)c_buffer;
1329 char cbuf[_MAXPATHLEN];
1330 #endif
1331
1332 #ifdef HAVE_WGETCWD
1333 #if wxUSE_UNICODE_MSLU
1334 if ( wxGetOsVersion() != wxWIN95 )
1335 #else
1336 char *cbuf = NULL; // never really used because needsANSI will always be false
1337 #endif
1338 {
1339 ok = _wgetcwd(buf, sz) != NULL;
1340 needsANSI = false;
1341 }
1342 #endif
1343
1344 if ( needsANSI )
1345 #endif // wxUSE_UNICODE
1346 {
1347 #if defined(_MSC_VER) || defined(__MINGW32__)
1348 ok = _getcwd(cbuf, sz) != NULL;
1349 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1350 char lbuf[1024] ;
1351 if ( getcwd( lbuf , sizeof( lbuf ) ) )
1352 {
1353 wxString res( lbuf , *wxConvCurrent ) ;
1354 wxStrcpy( buf , res ) ;
1355 ok = true;
1356 }
1357 else
1358 ok = false ;
1359 #elif defined(__OS2__)
1360 APIRET rc;
1361 ULONG ulDriveNum = 0;
1362 ULONG ulDriveMap = 0;
1363 rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
1364 ok = rc == 0;
1365 if (ok)
1366 {
1367 sz -= 3;
1368 rc = ::DosQueryCurrentDir( 0 // current drive
1369 ,cbuf + 3
1370 ,(PULONG)&sz
1371 );
1372 cbuf[0] = 'A' + (ulDriveNum - 1);
1373 cbuf[1] = ':';
1374 cbuf[2] = '\\';
1375 ok = rc == 0;
1376 }
1377 #else // !Win32/VC++ !Mac !OS2
1378 ok = getcwd(cbuf, sz) != NULL;
1379 #endif // platform
1380
1381 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1382 // finally convert the result to Unicode if needed
1383 wxConvFile.MB2WC(buf, cbuf, sz);
1384 #endif // wxUSE_UNICODE
1385 }
1386
1387 if ( !ok )
1388 {
1389 wxLogSysError(_("Failed to get the working directory"));
1390
1391 // VZ: the old code used to return "." on error which didn't make any
1392 // sense at all to me - empty string is a better error indicator
1393 // (NULL might be even better but I'm afraid this could lead to
1394 // problems with the old code assuming the return is never NULL)
1395 buf[0] = _T('\0');
1396 }
1397 else // ok, but we might need to massage the path into the right format
1398 {
1399 #ifdef __DJGPP__
1400 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1401 // with / deliminers. We don't like that.
1402 for (wxChar *ch = buf; *ch; ch++)
1403 {
1404 if (*ch == wxT('/'))
1405 *ch = wxT('\\');
1406 }
1407 #endif // __DJGPP__
1408
1409 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1410 // he needs Unix as opposed to Win32 pathnames
1411 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1412 // another example of DOS/Unix mix (Cygwin)
1413 wxString pathUnix = buf;
1414 cygwin_conv_to_full_win32_path(pathUnix, buf);
1415 #endif // __CYGWIN__
1416 }
1417
1418 return buf;
1419
1420 #if !wxUSE_UNICODE
1421 #undef cbuf
1422 #endif
1423
1424 #endif
1425 // __WXWINCE__
1426 }
1427
1428 wxString wxGetCwd()
1429 {
1430 wxChar *buffer = new wxChar[_MAXPATHLEN];
1431 wxGetWorkingDirectory(buffer, _MAXPATHLEN);
1432 wxString str( buffer );
1433 delete [] buffer;
1434
1435 return str;
1436 }
1437
1438 bool wxSetWorkingDirectory(const wxString& d)
1439 {
1440 #if defined(__OS2__)
1441 return (::DosSetCurrentDir((PSZ)d.c_str()) == 0);
1442 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1443 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1444 #elif defined(__WINDOWS__)
1445
1446 #ifdef __WIN32__
1447 #ifdef __WXWINCE__
1448 // No equivalent in WinCE
1449 return false;
1450 #else
1451 return (bool)(SetCurrentDirectory(d) != 0);
1452 #endif
1453 #else
1454 // Must change drive, too.
1455 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1456 if (isDriveSpec)
1457 {
1458 wxChar firstChar = d[0];
1459
1460 // To upper case
1461 if (firstChar > 90)
1462 firstChar = firstChar - 32;
1463
1464 // To a drive number
1465 unsigned int driveNo = firstChar - 64;
1466 if (driveNo > 0)
1467 {
1468 unsigned int noDrives;
1469 _dos_setdrive(driveNo, &noDrives);
1470 }
1471 }
1472 bool success = (chdir(WXSTRINGCAST d) == 0);
1473
1474 return success;
1475 #endif
1476
1477 #endif
1478 }
1479
1480 // Get the OS directory if appropriate (such as the Windows directory).
1481 // On non-Windows platform, probably just return the empty string.
1482 wxString wxGetOSDirectory()
1483 {
1484 #ifdef __WXWINCE__
1485 return wxString(wxT("\\Windows"));
1486 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1487 wxChar buf[256];
1488 GetWindowsDirectory(buf, 256);
1489 return wxString(buf);
1490 #elif defined(__WXMAC__)
1491 return wxMacFindFolder(kOnSystemDisk, 'macs', false);
1492 #else
1493 return wxEmptyString;
1494 #endif
1495 }
1496
1497 bool wxEndsWithPathSeparator(const wxChar *pszFileName)
1498 {
1499 size_t len = wxStrlen(pszFileName);
1500
1501 return len && wxIsPathSeparator(pszFileName[len - 1]);
1502 }
1503
1504 // find a file in a list of directories, returns false if not found
1505 bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
1506 {
1507 // we assume that it's not empty
1508 wxCHECK_MSG( !wxIsEmpty(pszFile), false,
1509 _T("empty file name in wxFindFileInPath"));
1510
1511 // skip path separator in the beginning of the file name if present
1512 if ( wxIsPathSeparator(*pszFile) )
1513 pszFile++;
1514
1515 // copy the path (strtok will modify it)
1516 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1517 wxStrcpy(szPath, pszPath);
1518
1519 wxString strFile;
1520 wxChar *pc, *save_ptr;
1521 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1522 pc != NULL;
1523 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1524 {
1525 // search for the file in this directory
1526 strFile = pc;
1527 if ( !wxEndsWithPathSeparator(pc) )
1528 strFile += wxFILE_SEP_PATH;
1529 strFile += pszFile;
1530
1531 if ( wxFileExists(strFile) ) {
1532 *pStr = strFile;
1533 break;
1534 }
1535 }
1536
1537 // suppress warning about unused variable save_ptr when wxStrtok() is a
1538 // macro which throws away its third argument
1539 save_ptr = pc;
1540
1541 delete [] szPath;
1542
1543 return pc != NULL; // if true => we breaked from the loop
1544 }
1545
1546 void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
1547 wxString *pstrPath,
1548 wxString *pstrName,
1549 wxString *pstrExt)
1550 {
1551 // it can be empty, but it shouldn't be NULL
1552 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
1553
1554 wxFileName::SplitPath(pszFileName, pstrPath, pstrName, pstrExt);
1555 }
1556
1557 time_t WXDLLEXPORT wxFileModificationTime(const wxString& filename)
1558 {
1559 #ifdef __WXWINCE__
1560 FILETIME creationTime, lastAccessTime, lastWriteTime;
1561 HANDLE fileHandle = ::CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1562 0, FILE_ATTRIBUTE_NORMAL, 0);
1563 if (fileHandle == INVALID_HANDLE_VALUE)
1564 return 0;
1565 else
1566 {
1567 if (GetFileTime(fileHandle, & creationTime, & lastAccessTime, & lastWriteTime))
1568 {
1569 CloseHandle(fileHandle);
1570
1571 wxDateTime dateTime;
1572 FILETIME ftLocal;
1573 if ( !::FileTimeToLocalFileTime(&lastWriteTime, &ftLocal) )
1574 {
1575 wxLogLastError(_T("FileTimeToLocalFileTime"));
1576 }
1577
1578 SYSTEMTIME st;
1579 if ( !::FileTimeToSystemTime(&ftLocal, &st) )
1580 {
1581 wxLogLastError(_T("FileTimeToSystemTime"));
1582 }
1583
1584 dateTime.Set(st.wDay, wxDateTime::Month(st.wMonth - 1), st.wYear,
1585 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
1586 return dateTime.GetTicks();
1587 }
1588 else
1589 return 0;
1590 }
1591 #else
1592 wxStructStat buf;
1593 wxStat( filename, &buf);
1594
1595 return buf.st_mtime;
1596 #endif
1597 }
1598
1599
1600 // Parses the filterStr, returning the number of filters.
1601 // Returns 0 if none or if there's a problem.
1602 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1603
1604 int WXDLLEXPORT wxParseCommonDialogsFilter(const wxString& filterStr, wxArrayString& descriptions, wxArrayString& filters)
1605 {
1606 descriptions.Clear();
1607 filters.Clear();
1608
1609 wxString str(filterStr);
1610
1611 wxString description, filter;
1612 int pos = 0;
1613 while( pos != wxNOT_FOUND )
1614 {
1615 pos = str.Find(wxT('|'));
1616 if ( pos == wxNOT_FOUND )
1617 {
1618 // if there are no '|'s at all in the string just take the entire
1619 // string as filter and make description empty for later autocompletion
1620 if ( filters.IsEmpty() )
1621 {
1622 descriptions.Add(wxEmptyString);
1623 filters.Add(filterStr);
1624 }
1625 else
1626 {
1627 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1628 }
1629
1630 break;
1631 }
1632
1633 description = str.Left(pos);
1634 str = str.Mid(pos + 1);
1635 pos = str.Find(wxT('|'));
1636 if ( pos == wxNOT_FOUND )
1637 {
1638 filter = str;
1639 }
1640 else
1641 {
1642 filter = str.Left(pos);
1643 str = str.Mid(pos + 1);
1644 }
1645
1646 descriptions.Add(description);
1647 filters.Add(filter);
1648 }
1649
1650 #if defined(__WXMOTIF__)
1651 // split it so there is one wildcard per entry
1652 for( size_t i = 0 ; i < descriptions.GetCount() ; i++ )
1653 {
1654 pos = filters[i].Find(wxT(';'));
1655 if (pos != wxNOT_FOUND)
1656 {
1657 // first split only filters
1658 descriptions.Insert(descriptions[i],i+1);
1659 filters.Insert(filters[i].Mid(pos+1),i+1);
1660 filters[i]=filters[i].Left(pos);
1661
1662 // autoreplace new filter in description with pattern:
1663 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1664 // cause split into:
1665 // C/C++ Files(*.cpp)|*.cpp
1666 // C/C++ Files(*.c;*.h)|*.c;*.h
1667 // and next iteration cause another split into:
1668 // C/C++ Files(*.cpp)|*.cpp
1669 // C/C++ Files(*.c)|*.c
1670 // C/C++ Files(*.h)|*.h
1671 for ( size_t k=i;k<i+2;k++ )
1672 {
1673 pos = descriptions[k].Find(filters[k]);
1674 if (pos != wxNOT_FOUND)
1675 {
1676 wxString before = descriptions[k].Left(pos);
1677 wxString after = descriptions[k].Mid(pos+filters[k].Len());
1678 pos = before.Find(_T('('),true);
1679 if (pos>before.Find(_T(')'),true))
1680 {
1681 before = before.Left(pos+1);
1682 before << filters[k];
1683 pos = after.Find(_T(')'));
1684 int pos1 = after.Find(_T('('));
1685 if (pos != wxNOT_FOUND && (pos<pos1 || pos1==wxNOT_FOUND))
1686 {
1687 before << after.Mid(pos);
1688 descriptions[k] = before;
1689 }
1690 }
1691 }
1692 }
1693 }
1694 }
1695 #endif
1696
1697 // autocompletion
1698 for( size_t j = 0 ; j < descriptions.GetCount() ; j++ )
1699 {
1700 if ( descriptions[j] == wxEmptyString && filters[j] != wxEmptyString )
1701 {
1702 descriptions[j].Printf(_("Files (%s)"), filters[j].c_str());
1703 }
1704 }
1705
1706 return filters.GetCount();
1707 }
1708
1709
1710 //------------------------------------------------------------------------
1711 // wild character routines
1712 //------------------------------------------------------------------------
1713
1714 bool wxIsWild( const wxString& pattern )
1715 {
1716 wxString tmp = pattern;
1717 wxChar *pat = WXSTRINGCAST(tmp);
1718 while (*pat)
1719 {
1720 switch (*pat++)
1721 {
1722 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1723 return true;
1724 case wxT('\\'):
1725 if (!*pat++)
1726 return false;
1727 }
1728 }
1729 return false;
1730 }
1731
1732 /*
1733 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1734 *
1735 * The match procedure is public domain code (from ircII's reg.c)
1736 */
1737
1738 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1739 {
1740 if (text.empty())
1741 {
1742 /* Match if both are empty. */
1743 return pat.empty();
1744 }
1745
1746 const wxChar *m = pat.c_str(),
1747 *n = text.c_str(),
1748 *ma = NULL,
1749 *na = NULL,
1750 *mp = NULL,
1751 *np = NULL;
1752 int just = 0,
1753 pcount = 0,
1754 acount = 0,
1755 count = 0;
1756
1757 if (dot_special && (*n == wxT('.')))
1758 {
1759 /* Never match so that hidden Unix files
1760 * are never found. */
1761 return false;
1762 }
1763
1764 for (;;)
1765 {
1766 if (*m == wxT('*'))
1767 {
1768 ma = ++m;
1769 na = n;
1770 just = 1;
1771 mp = NULL;
1772 acount = count;
1773 }
1774 else if (*m == wxT('?'))
1775 {
1776 m++;
1777 if (!*n++)
1778 return false;
1779 }
1780 else
1781 {
1782 if (*m == wxT('\\'))
1783 {
1784 m++;
1785 /* Quoting "nothing" is a bad thing */
1786 if (!*m)
1787 return false;
1788 }
1789 if (!*m)
1790 {
1791 /*
1792 * If we are out of both strings or we just
1793 * saw a wildcard, then we can say we have a
1794 * match
1795 */
1796 if (!*n)
1797 return true;
1798 if (just)
1799 return true;
1800 just = 0;
1801 goto not_matched;
1802 }
1803 /*
1804 * We could check for *n == NULL at this point, but
1805 * since it's more common to have a character there,
1806 * check to see if they match first (m and n) and
1807 * then if they don't match, THEN we can check for
1808 * the NULL of n
1809 */
1810 just = 0;
1811 if (*m == *n)
1812 {
1813 m++;
1814 if (*n == wxT(' '))
1815 mp = NULL;
1816 count++;
1817 n++;
1818 }
1819 else
1820 {
1821
1822 not_matched:
1823
1824 /*
1825 * If there are no more characters in the
1826 * string, but we still need to find another
1827 * character (*m != NULL), then it will be
1828 * impossible to match it
1829 */
1830 if (!*n)
1831 return false;
1832 if (mp)
1833 {
1834 m = mp;
1835 if (*np == wxT(' '))
1836 {
1837 mp = NULL;
1838 goto check_percent;
1839 }
1840 n = ++np;
1841 count = pcount;
1842 }
1843 else
1844 check_percent:
1845
1846 if (ma)
1847 {
1848 m = ma;
1849 n = ++na;
1850 count = acount;
1851 }
1852 else
1853 return false;
1854 }
1855 }
1856 }
1857 }
1858
1859
1860 #ifdef __VISUALC__
1861 #pragma warning(default:4706) // assignment within conditional expression
1862 #endif // VC++