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