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