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