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