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