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