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