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