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