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