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