s/wxSplitPath/wxFileName::SplitPath
[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 (TOFIX!)
298 // ----------------------------------------------------------------------------
299
300 static inline wxChar* MYcopystring(const wxString& s)
301 {
302 wxChar* copy = new wxChar[s.length() + 1];
303 return wxStrcpy(copy, s.c_str());
304 }
305
306 template<typename CharType>
307 static inline CharType* MYcopystring(const CharType* s)
308 {
309 CharType* copy = new CharType[wxStrlen(s) + 1];
310 return wxStrcpy(copy, s);
311 }
312
313
314 bool
315 wxFileExists (const wxString& filename)
316 {
317 #if defined(__WXPALMOS__)
318 return false;
319 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
320 // we must use GetFileAttributes() instead of the ANSI C functions because
321 // it can cope with network (UNC) paths unlike them
322 DWORD ret = ::GetFileAttributes(filename.fn_str());
323
324 return (ret != INVALID_FILE_ATTRIBUTES) && !(ret & FILE_ATTRIBUTE_DIRECTORY);
325 #else // !__WIN32__
326 #ifndef S_ISREG
327 #define S_ISREG(mode) ((mode) & S_IFREG)
328 #endif
329 wxStructStat st;
330 #ifndef wxNEED_WX_UNISTD_H
331 return (wxStat( filename.fn_str() , &st) == 0 && S_ISREG(st.st_mode))
332 #ifdef __OS2__
333 || (errno == EACCES) // if access is denied something with that name
334 // exists and is opened in exclusive mode.
335 #endif
336 ;
337 #else
338 return wxStat( filename , &st) == 0 && S_ISREG(st.st_mode);
339 #endif
340 #endif // __WIN32__/!__WIN32__
341 }
342
343 bool
344 wxIsAbsolutePath (const wxString& filename)
345 {
346 if (!filename.empty())
347 {
348 // Unix like or Windows
349 if (filename[0] == wxT('/'))
350 return true;
351 #ifdef __VMS__
352 if ((filename[0] == wxT('[') && filename[1] != wxT('.')))
353 return true;
354 #endif
355 #if defined(__WINDOWS__) || defined(__OS2__)
356 // MSDOS like
357 if (filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':')))
358 return true;
359 #endif
360 }
361 return false ;
362 }
363
364 #if WXWIN_COMPATIBILITY_2_8
365 /*
366 * Strip off any extension (dot something) from end of file,
367 * IF one exists. Inserts zero into buffer.
368 *
369 */
370
371 template<typename T>
372 static void wxDoStripExtension(T *buffer)
373 {
374 int len = wxStrlen(buffer);
375 int i = len-1;
376 while (i > 0)
377 {
378 if (buffer[i] == wxT('.'))
379 {
380 buffer[i] = 0;
381 break;
382 }
383 i --;
384 }
385 }
386
387 void wxStripExtension(char *buffer) { wxDoStripExtension(buffer); }
388 void wxStripExtension(wchar_t *buffer) { wxDoStripExtension(buffer); }
389
390 void wxStripExtension(wxString& buffer)
391 {
392 //RN: Be careful about the handling the case where
393 //buffer.length() == 0
394 for(size_t i = buffer.length() - 1; i != wxString::npos; --i)
395 {
396 if (buffer.GetChar(i) == wxT('.'))
397 {
398 buffer = buffer.Left(i);
399 break;
400 }
401 }
402 }
403
404 // Destructive removal of /./ and /../ stuff
405 template<typename CharType>
406 static CharType *wxDoRealPath (CharType *path)
407 {
408 static const CharType SEP = wxFILE_SEP_PATH;
409 #ifdef __WXMSW__
410 wxUnix2DosFilename(path);
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 static const CharType SEP = wxFILE_SEP_PATH;
543 #ifdef __WXMSW__
544 //wxUnix2DosFilename(path);
545 #endif
546
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 #endif // #if WXWIN_COMPATIBILITY_2_8
761
762 // Return just the filename, not the path (basename)
763 wxChar *wxFileNameFromPath (wxChar *path)
764 {
765 wxString p = path;
766 wxString n = wxFileNameFromPath(p);
767
768 return path + p.length() - n.length();
769 }
770
771 wxString wxFileNameFromPath (const wxString& path)
772 {
773 wxString name, ext;
774 wxFileName::SplitPath(path, NULL, &name, &ext);
775
776 wxString fullname = name;
777 if ( !ext.empty() )
778 {
779 fullname << wxFILE_SEP_EXT << ext;
780 }
781
782 return fullname;
783 }
784
785 // Return just the directory, or NULL if no directory
786 wxChar *
787 wxPathOnly (wxChar *path)
788 {
789 if (path && *path)
790 {
791 static wxChar buf[_MAXPATHLEN];
792
793 // Local copy
794 wxStrcpy (buf, path);
795
796 int l = wxStrlen(path);
797 int i = l - 1;
798
799 // Search backward for a backward or forward slash
800 while (i > -1)
801 {
802 // Unix like or Windows
803 if (path[i] == wxT('/') || path[i] == wxT('\\'))
804 {
805 buf[i] = 0;
806 return buf;
807 }
808 #ifdef __VMS__
809 if (path[i] == wxT(']'))
810 {
811 buf[i+1] = 0;
812 return buf;
813 }
814 #endif
815 i --;
816 }
817
818 #if defined(__WXMSW__) || defined(__OS2__)
819 // Try Drive specifier
820 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
821 {
822 // A:junk --> A:. (since A:.\junk Not A:\junk)
823 buf[2] = wxT('.');
824 buf[3] = wxT('\0');
825 return buf;
826 }
827 #endif
828 }
829 return (wxChar *) NULL;
830 }
831
832 // Return just the directory, or NULL if no directory
833 wxString wxPathOnly (const wxString& path)
834 {
835 if (!path.empty())
836 {
837 wxChar buf[_MAXPATHLEN];
838
839 // Local copy
840 wxStrcpy(buf, path);
841
842 int l = path.length();
843 int i = l - 1;
844
845 // Search backward for a backward or forward slash
846 while (i > -1)
847 {
848 // Unix like or Windows
849 if (path[i] == wxT('/') || path[i] == wxT('\\'))
850 {
851 // Don't return an empty string
852 if (i == 0)
853 i ++;
854 buf[i] = 0;
855 return wxString(buf);
856 }
857 #ifdef __VMS__
858 if (path[i] == wxT(']'))
859 {
860 buf[i+1] = 0;
861 return wxString(buf);
862 }
863 #endif
864 i --;
865 }
866
867 #if defined(__WXMSW__) || defined(__OS2__)
868 // Try Drive specifier
869 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
870 {
871 // A:junk --> A:. (since A:.\junk Not A:\junk)
872 buf[2] = wxT('.');
873 buf[3] = wxT('\0');
874 return wxString(buf);
875 }
876 #endif
877 }
878 return wxEmptyString;
879 }
880
881 // Utility for converting delimiters in DOS filenames to UNIX style
882 // and back again - or we get nasty problems with delimiters.
883 // Also, convert to lower case, since case is significant in UNIX.
884
885 #if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
886
887 #define kDefaultPathStyle kCFURLPOSIXPathStyle
888
889 wxString wxMacFSRefToPath( const FSRef *fsRef , CFStringRef additionalPathComponent )
890 {
891 CFURLRef fullURLRef;
892 fullURLRef = CFURLCreateFromFSRef(NULL, fsRef);
893 if ( additionalPathComponent )
894 {
895 CFURLRef parentURLRef = fullURLRef ;
896 fullURLRef = CFURLCreateCopyAppendingPathComponent(NULL, parentURLRef,
897 additionalPathComponent,false);
898 CFRelease( parentURLRef ) ;
899 }
900 CFStringRef cfString = CFURLCopyFileSystemPath(fullURLRef, kDefaultPathStyle);
901 CFRelease( fullURLRef ) ;
902 CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfString);
903 CFRelease( cfString );
904 CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
905 return wxCFStringRef(cfMutableString).AsString();
906 }
907
908 OSStatus wxMacPathToFSRef( const wxString&path , FSRef *fsRef )
909 {
910 OSStatus err = noErr ;
911 CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(path));
912 CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
913 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kDefaultPathStyle, false);
914 CFRelease( cfMutableString );
915 if ( NULL != url )
916 {
917 if ( CFURLGetFSRef(url, fsRef) == false )
918 err = fnfErr ;
919 CFRelease( url ) ;
920 }
921 else
922 {
923 err = fnfErr ;
924 }
925 return err ;
926 }
927
928 wxString wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname )
929 {
930 CFStringRef cfname = CFStringCreateWithCharacters( kCFAllocatorDefault,
931 uniname->unicode,
932 uniname->length );
933 CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfname);
934 CFRelease( cfname );
935 CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
936 return wxCFStringRef(cfMutableString).AsString() ;
937 }
938
939 #ifndef __LP64__
940
941 wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
942 {
943 FSRef fsRef ;
944 if ( FSpMakeFSRef( spec , &fsRef) == noErr )
945 {
946 return wxMacFSRefToPath( &fsRef ) ;
947 }
948 return wxEmptyString ;
949 }
950
951 void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
952 {
953 OSStatus err = noErr;
954 FSRef fsRef;
955 wxMacPathToFSRef( path , &fsRef );
956 err = FSGetCatalogInfo(&fsRef, kFSCatInfoNone, NULL, NULL, spec, NULL);
957 verify_noerr( err );
958 }
959 #endif
960
961 #endif // __WXMAC__
962
963
964 #if WXWIN_COMPATIBILITY_2_8
965
966 template<typename T>
967 static void wxDoDos2UnixFilename(T *s)
968 {
969 if (s)
970 while (*s)
971 {
972 if (*s == _T('\\'))
973 *s = _T('/');
974 #ifdef __WXMSW__
975 else
976 *s = wxTolower(*s); // Case INDEPENDENT
977 #endif
978 s++;
979 }
980 }
981
982 void wxDos2UnixFilename(char *s) { wxDoDos2UnixFilename(s); }
983 void wxDos2UnixFilename(wchar_t *s) { wxDoDos2UnixFilename(s); }
984
985 template<typename T>
986 static void
987 #if defined(__WXMSW__) || defined(__OS2__)
988 wxDoUnix2DosFilename(T *s)
989 #else
990 wxDoUnix2DosFilename(T *WXUNUSED(s) )
991 #endif
992 {
993 // Yes, I really mean this to happen under DOS only! JACS
994 #if defined(__WXMSW__) || defined(__OS2__)
995 if (s)
996 while (*s)
997 {
998 if (*s == wxT('/'))
999 *s = wxT('\\');
1000 s++;
1001 }
1002 #endif
1003 }
1004
1005 void wxUnix2DosFilename(char *s) { wxDoUnix2DosFilename(s); }
1006 void wxUnix2DosFilename(wchar_t *s) { wxDoUnix2DosFilename(s); }
1007
1008 #endif // #if WXWIN_COMPATIBILITY_2_8
1009
1010 // Concatenate two files to form third
1011 bool
1012 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
1013 {
1014 #if wxUSE_FILE
1015
1016 wxFile in1(file1), in2(file2);
1017 wxTempFile out(file3);
1018
1019 if ( !in1.IsOpened() || !in2.IsOpened() || !out.IsOpened() )
1020 return false;
1021
1022 ssize_t ofs;
1023 unsigned char buf[1024];
1024
1025 for( int i=0; i<2; i++)
1026 {
1027 wxFile *in = i==0 ? &in1 : &in2;
1028 do{
1029 if ( (ofs = in->Read(buf,WXSIZEOF(buf))) == wxInvalidOffset ) return false;
1030 if ( ofs > 0 )
1031 if ( !out.Write(buf,ofs) )
1032 return false;
1033 } while ( ofs == (ssize_t)WXSIZEOF(buf) );
1034 }
1035
1036 return out.Commit();
1037
1038 #else
1039
1040 wxUnusedVar(file1);
1041 wxUnusedVar(file2);
1042 wxUnusedVar(file3);
1043 return false;
1044
1045 #endif
1046 }
1047
1048 // helper of generic implementation of wxCopyFile()
1049 #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
1050 wxUSE_FILE
1051
1052 static bool
1053 wxDoCopyFile(wxFile& fileIn,
1054 const wxStructStat& fbuf,
1055 const wxString& filenameDst,
1056 bool overwrite)
1057 {
1058 // reset the umask as we want to create the file with exactly the same
1059 // permissions as the original one
1060 wxCHANGE_UMASK(0);
1061
1062 // create file2 with the same permissions than file1 and open it for
1063 // writing
1064
1065 wxFile fileOut;
1066 if ( !fileOut.Create(filenameDst, overwrite, fbuf.st_mode & 0777) )
1067 return false;
1068
1069 // copy contents of file1 to file2
1070 char buf[4096];
1071 for ( ;; )
1072 {
1073 ssize_t count = fileIn.Read(buf, WXSIZEOF(buf));
1074 if ( count == wxInvalidOffset )
1075 return false;
1076
1077 // end of file?
1078 if ( !count )
1079 break;
1080
1081 if ( fileOut.Write(buf, count) < (size_t)count )
1082 return false;
1083 }
1084
1085 // we can expect fileIn to be closed successfully, but we should ensure
1086 // that fileOut was closed as some write errors (disk full) might not be
1087 // detected before doing this
1088 return fileIn.Close() && fileOut.Close();
1089 }
1090
1091 #endif // generic implementation of wxCopyFile
1092
1093 // Copy files
1094 bool
1095 wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
1096 {
1097 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
1098 // CopyFile() copies file attributes and modification time too, so use it
1099 // instead of our code if available
1100 //
1101 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1102 if ( !::CopyFile(file1.fn_str(), file2.fn_str(), !overwrite) )
1103 {
1104 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1105 file1.c_str(), file2.c_str());
1106
1107 return false;
1108 }
1109 #elif defined(__OS2__)
1110 if ( ::DosCopy(file1.c_str(), file2.c_str(), overwrite ? DCPY_EXISTING : 0) != 0 )
1111 return false;
1112 #elif defined(__PALMOS__)
1113 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1114 return false;
1115 #elif wxUSE_FILE // !Win32
1116
1117 wxStructStat fbuf;
1118 // get permissions of file1
1119 if ( wxStat( file1.c_str(), &fbuf) != 0 )
1120 {
1121 // the file probably doesn't exist or we haven't the rights to read
1122 // from it anyhow
1123 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1124 file1.c_str());
1125 return false;
1126 }
1127
1128 // open file1 for reading
1129 wxFile fileIn(file1, wxFile::read);
1130 if ( !fileIn.IsOpened() )
1131 return false;
1132
1133 // remove file2, if it exists. This is needed for creating
1134 // file2 with the correct permissions in the next step
1135 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
1136 {
1137 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1138 file2.c_str());
1139 return false;
1140 }
1141
1142 wxDoCopyFile(fileIn, fbuf, file2, overwrite);
1143
1144 #if defined(__WXMAC__) || defined(__WXCOCOA__)
1145 // copy the resource fork of the file too if it's present
1146 wxString pathRsrcOut;
1147 wxFile fileRsrcIn;
1148
1149 {
1150 // suppress error messages from this block as resource forks don't have
1151 // to exist
1152 wxLogNull noLog;
1153
1154 // it's not enough to check for file existence: it always does on HFS
1155 // but is empty for files without resources
1156 if ( fileRsrcIn.Open(file1 + wxT("/..namedfork/rsrc")) &&
1157 fileRsrcIn.Length() > 0 )
1158 {
1159 // we must be using HFS or another filesystem with resource fork
1160 // support, suppose that destination file system also is HFS[-like]
1161 pathRsrcOut = file2 + wxT("/..namedfork/rsrc");
1162 }
1163 else // check if we have resource fork in separate file (non-HFS case)
1164 {
1165 wxFileName fnRsrc(file1);
1166 fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
1167
1168 fileRsrcIn.Close();
1169 if ( fileRsrcIn.Open( fnRsrc.GetFullPath() ) )
1170 {
1171 fnRsrc = file2;
1172 fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
1173
1174 pathRsrcOut = fnRsrc.GetFullPath();
1175 }
1176 }
1177 }
1178
1179 if ( !pathRsrcOut.empty() )
1180 {
1181 if ( !wxDoCopyFile(fileRsrcIn, fbuf, pathRsrcOut, overwrite) )
1182 return false;
1183 }
1184 #endif // wxMac || wxCocoa
1185
1186 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1187 // no chmod in VA. Should be some permission API for HPFS386 partitions
1188 // however
1189 if ( chmod(OS_FILENAME(file2), fbuf.st_mode) != 0 )
1190 {
1191 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1192 file2.c_str());
1193 return false;
1194 }
1195 #endif // OS/2 || Mac
1196
1197 #else // !Win32 && ! wxUSE_FILE
1198
1199 // impossible to simulate with wxWidgets API
1200 wxUnusedVar(file1);
1201 wxUnusedVar(file2);
1202 wxUnusedVar(overwrite);
1203 return false;
1204
1205 #endif // __WXMSW__ && __WIN32__
1206
1207 return true;
1208 }
1209
1210 bool
1211 wxRenameFile(const wxString& file1, const wxString& file2, bool overwrite)
1212 {
1213 if ( !overwrite && wxFileExists(file2) )
1214 {
1215 wxLogSysError
1216 (
1217 _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
1218 file1.c_str(), file2.c_str()
1219 );
1220
1221 return false;
1222 }
1223
1224 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1225 // Normal system call
1226 if ( wxRename (file1, file2) == 0 )
1227 return true;
1228 #endif
1229
1230 // Try to copy
1231 if (wxCopyFile(file1, file2, overwrite)) {
1232 wxRemoveFile(file1);
1233 return true;
1234 }
1235 // Give up
1236 return false;
1237 }
1238
1239 bool wxRemoveFile(const wxString& file)
1240 {
1241 #if defined(__VISUALC__) \
1242 || defined(__BORLANDC__) \
1243 || defined(__WATCOMC__) \
1244 || defined(__DMC__) \
1245 || defined(__GNUWIN32__) \
1246 || (defined(__MWERKS__) && defined(__MSL__))
1247 int res = wxRemove(file);
1248 #elif defined(__WXMAC__)
1249 int res = unlink(file.fn_str());
1250 #elif defined(__WXPALMOS__)
1251 int res = 1;
1252 // TODO with VFSFileDelete()
1253 #else
1254 int res = unlink(OS_FILENAME(file));
1255 #endif
1256
1257 return res == 0;
1258 }
1259
1260 bool wxMkdir(const wxString& dir, int perm)
1261 {
1262 #if defined(__WXPALMOS__)
1263 return false;
1264 #elif defined(__WXMAC__) && !defined(__UNIX__)
1265 return (mkdir(dir.fn_str() , 0 ) == 0);
1266 #else // !Mac
1267 const wxChar *dirname = dir.c_str();
1268
1269 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1270 // for the GNU compiler
1271 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1272 #if defined(MSVCRT)
1273 wxUnusedVar(perm);
1274 if ( mkdir(wxFNCONV(dirname)) != 0 )
1275 #else
1276 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1277 #endif
1278 #elif defined(__OS2__)
1279 wxUnusedVar(perm);
1280 if (::DosCreateDir((PSZ)dirname, NULL) != 0) // enhance for EAB's??
1281 #elif defined(__DOS__)
1282 #if defined(__WATCOMC__)
1283 (void)perm;
1284 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1285 #elif defined(__DJGPP__)
1286 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1287 #else
1288 #error "Unsupported DOS compiler!"
1289 #endif
1290 #else // !MSW, !DOS and !OS/2 VAC++
1291 wxUnusedVar(perm);
1292 #ifdef __WXWINCE__
1293 if ( !CreateDirectory(dirname, NULL) )
1294 #else
1295 if ( wxMkDir(dir.fn_str()) != 0 )
1296 #endif
1297 #endif // !MSW/MSW
1298 {
1299 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1300
1301 return false;
1302 }
1303
1304 return true;
1305 #endif // Mac/!Mac
1306 }
1307
1308 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1309 {
1310 #if defined(__VMS__)
1311 return false; //to be changed since rmdir exists in VMS7.x
1312 #elif defined(__OS2__)
1313 return (::DosDeleteDir(dir.c_str()) == 0);
1314 #elif defined(__WXWINCE__)
1315 return (RemoveDirectory(dir) != 0);
1316 #elif defined(__WXPALMOS__)
1317 // TODO with VFSFileRename()
1318 return false;
1319 #else
1320 return (wxRmDir(OS_FILENAME(dir)) == 0);
1321 #endif
1322 }
1323
1324 // does the path exists? (may have or not '/' or '\\' at the end)
1325 bool wxDirExists(const wxString& pathName)
1326 {
1327 wxString strPath(pathName);
1328
1329 #if defined(__WINDOWS__) || defined(__OS2__)
1330 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1331 // so remove all trailing backslashes from the path - but don't do this for
1332 // the paths "d:\" (which are different from "d:") nor for just "\"
1333 while ( wxEndsWithPathSeparator(strPath) )
1334 {
1335 size_t len = strPath.length();
1336 if ( len == 1 || (len == 3 && strPath[len - 2] == _T(':')) )
1337 break;
1338
1339 strPath.Truncate(len - 1);
1340 }
1341 #endif // __WINDOWS__
1342
1343 #ifdef __OS2__
1344 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1345 if (strPath.length() == 2 && strPath[1u] == _T(':'))
1346 strPath << _T('.');
1347 #endif
1348
1349 #if defined(__WXPALMOS__)
1350 return false;
1351 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1352 // stat() can't cope with network paths
1353 DWORD ret = ::GetFileAttributes(strPath.fn_str());
1354
1355 return (ret != INVALID_FILE_ATTRIBUTES) && (ret & FILE_ATTRIBUTE_DIRECTORY);
1356 #elif defined(__OS2__)
1357 FILESTATUS3 Info = {{0}};
1358 APIRET rc = ::DosQueryPathInfo((PSZ)(WXSTRINGCAST strPath), FIL_STANDARD,
1359 (void*) &Info, sizeof(FILESTATUS3));
1360
1361 return ((rc == NO_ERROR) && (Info.attrFile & FILE_DIRECTORY)) ||
1362 (rc == ERROR_SHARING_VIOLATION);
1363 // If we got a sharing violation, there must be something with this name.
1364 #else // !__WIN32__
1365
1366 wxStructStat st;
1367 #ifndef __VISAGECPP__
1368 return wxStat(strPath.c_str(), &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR);
1369 #else
1370 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1371 return wxStat(strPath.c_str(), &st) == 0 && (st.st_mode == S_IFDIR);
1372 #endif
1373
1374 #endif // __WIN32__/!__WIN32__
1375 }
1376
1377 #if WXWIN_COMPATIBILITY_2_8
1378
1379 // Get a temporary filename, opening and closing the file.
1380 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1381 {
1382 wxString filename;
1383 if ( !wxGetTempFileName(prefix, filename) )
1384 return NULL;
1385
1386 if ( buf )
1387 #ifdef _PACC_VER
1388 // work around the PalmOS pacc compiler bug
1389 wxStrcpy(buf, filename.data());
1390 #else
1391 wxStrcpy(buf, filename);
1392 #endif
1393 else
1394 buf = MYcopystring(filename);
1395
1396 return buf;
1397 }
1398
1399 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1400 {
1401 #if wxUSE_FILE
1402 buf = wxFileName::CreateTempFileName(prefix);
1403
1404 return !buf.empty();
1405 #else // !wxUSE_FILE
1406 wxUnusedVar(prefix);
1407 wxUnusedVar(buf);
1408
1409 return false;
1410 #endif // wxUSE_FILE/!wxUSE_FILE
1411 }
1412
1413 #endif // #if WXWIN_COMPATIBILITY_2_8
1414
1415 // Get first file name matching given wild card.
1416
1417 static wxDir *gs_dir = NULL;
1418 static wxString gs_dirPath;
1419
1420 wxString wxFindFirstFile(const wxString& spec, int flags)
1421 {
1422 wxFileName::SplitPath(spec, &gs_dirPath, NULL, NULL);
1423 if ( gs_dirPath.empty() )
1424 gs_dirPath = wxT(".");
1425 if ( !wxEndsWithPathSeparator(gs_dirPath ) )
1426 gs_dirPath << wxFILE_SEP_PATH;
1427
1428 delete gs_dir; // can be NULL, this is ok
1429 gs_dir = new wxDir(gs_dirPath);
1430
1431 if ( !gs_dir->IsOpened() )
1432 {
1433 wxLogSysError(_("Can not enumerate files '%s'"), spec);
1434 return wxEmptyString;
1435 }
1436
1437 int dirFlags;
1438 switch (flags)
1439 {
1440 case wxDIR: dirFlags = wxDIR_DIRS; break;
1441 case wxFILE: dirFlags = wxDIR_FILES; break;
1442 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1443 }
1444
1445 wxString result;
1446 gs_dir->GetFirst(&result, wxFileNameFromPath(spec), dirFlags);
1447 if ( result.empty() )
1448 {
1449 wxDELETE(gs_dir);
1450 return result;
1451 }
1452
1453 return gs_dirPath + result;
1454 }
1455
1456 wxString wxFindNextFile()
1457 {
1458 wxCHECK_MSG( gs_dir, "", "You must call wxFindFirstFile before!" );
1459
1460 wxString result;
1461 gs_dir->GetNext(&result);
1462
1463 if ( result.empty() )
1464 {
1465 wxDELETE(gs_dir);
1466 return result;
1467 }
1468
1469 return gs_dirPath + result;
1470 }
1471
1472
1473 // Get current working directory.
1474 // If buf is NULL, allocates space using new, else copies into buf.
1475 // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
1476 // wxDoGetCwd() is their common core to be moved
1477 // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
1478 // Do not expose wxDoGetCwd in headers!
1479
1480 wxChar *wxDoGetCwd(wxChar *buf, int sz)
1481 {
1482 #if defined(__WXPALMOS__)
1483 // TODO
1484 if(buf && sz>0) buf[0] = _T('\0');
1485 return buf;
1486 #elif defined(__WXWINCE__)
1487 // TODO
1488 if(buf && sz>0) buf[0] = _T('\0');
1489 return buf;
1490 #else
1491 if ( !buf )
1492 {
1493 buf = new wxChar[sz + 1];
1494 }
1495
1496 bool ok wxDUMMY_INITIALIZE(false);
1497
1498 // for the compilers which have Unicode version of _getcwd(), call it
1499 // directly, for the others call the ANSI version and do the translation
1500 #if !wxUSE_UNICODE
1501 #define cbuf buf
1502 #else // wxUSE_UNICODE
1503 bool needsANSI = true;
1504
1505 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1506 char cbuf[_MAXPATHLEN];
1507 #endif
1508
1509 #ifdef HAVE_WGETCWD
1510 #if wxUSE_UNICODE_MSLU
1511 if ( wxGetOsVersion() != wxOS_WINDOWS_9X )
1512 #else
1513 char *cbuf = NULL; // never really used because needsANSI will always be false
1514 #endif
1515 {
1516 ok = _wgetcwd(buf, sz) != NULL;
1517 needsANSI = false;
1518 }
1519 #endif
1520
1521 if ( needsANSI )
1522 #endif // wxUSE_UNICODE
1523 {
1524 #if defined(_MSC_VER) || defined(__MINGW32__)
1525 ok = _getcwd(cbuf, sz) != NULL;
1526 #elif defined(__OS2__)
1527 APIRET rc;
1528 ULONG ulDriveNum = 0;
1529 ULONG ulDriveMap = 0;
1530 rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
1531 ok = rc == 0;
1532 if (ok)
1533 {
1534 sz -= 3;
1535 rc = ::DosQueryCurrentDir( 0 // current drive
1536 ,cbuf + 3
1537 ,(PULONG)&sz
1538 );
1539 cbuf[0] = char('A' + (ulDriveNum - 1));
1540 cbuf[1] = ':';
1541 cbuf[2] = '\\';
1542 ok = rc == 0;
1543 }
1544 #else // !Win32/VC++ !Mac !OS2
1545 ok = getcwd(cbuf, sz) != NULL;
1546 #endif // platform
1547
1548 #if wxUSE_UNICODE
1549 // finally convert the result to Unicode if needed
1550 wxConvFile.MB2WC(buf, cbuf, sz);
1551 #endif // wxUSE_UNICODE
1552 }
1553
1554 if ( !ok )
1555 {
1556 wxLogSysError(_("Failed to get the working directory"));
1557
1558 // VZ: the old code used to return "." on error which didn't make any
1559 // sense at all to me - empty string is a better error indicator
1560 // (NULL might be even better but I'm afraid this could lead to
1561 // problems with the old code assuming the return is never NULL)
1562 buf[0] = _T('\0');
1563 }
1564 else // ok, but we might need to massage the path into the right format
1565 {
1566 #ifdef __DJGPP__
1567 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1568 // with / deliminers. We don't like that.
1569 for (wxChar *ch = buf; *ch; ch++)
1570 {
1571 if (*ch == wxT('/'))
1572 *ch = wxT('\\');
1573 }
1574 #endif // __DJGPP__
1575
1576 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1577 // he needs Unix as opposed to Win32 pathnames
1578 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1579 // another example of DOS/Unix mix (Cygwin)
1580 wxString pathUnix = buf;
1581 #if wxUSE_UNICODE
1582 char bufA[_MAXPATHLEN];
1583 cygwin_conv_to_full_win32_path(pathUnix.mb_str(wxConvFile), bufA);
1584 wxConvFile.MB2WC(buf, bufA, sz);
1585 #else
1586 cygwin_conv_to_full_win32_path(pathUnix, buf);
1587 #endif // wxUSE_UNICODE
1588 #endif // __CYGWIN__
1589 }
1590
1591 return buf;
1592
1593 #if !wxUSE_UNICODE
1594 #undef cbuf
1595 #endif
1596
1597 #endif
1598 // __WXWINCE__
1599 }
1600
1601 #if WXWIN_COMPATIBILITY_2_6
1602 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1603 {
1604 return wxDoGetCwd(buf,sz);
1605 }
1606 #endif // WXWIN_COMPATIBILITY_2_6
1607
1608 wxString wxGetCwd()
1609 {
1610 wxString str;
1611 wxDoGetCwd(wxStringBuffer(str, _MAXPATHLEN), _MAXPATHLEN);
1612 return str;
1613 }
1614
1615 bool wxSetWorkingDirectory(const wxString& d)
1616 {
1617 #if defined(__OS2__)
1618 if (d[1] == ':')
1619 {
1620 ::DosSetDefaultDisk(wxToupper(d[0]) - _T('A') + 1);
1621 // do not call DosSetCurrentDir when just changing drive,
1622 // since it requires e.g. "d:." instead of "d:"!
1623 if (d.length() == 2)
1624 return true;
1625 }
1626 return (::DosSetCurrentDir(d.c_str()) == 0);
1627 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1628 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1629 #elif defined(__WINDOWS__)
1630
1631 #ifdef __WIN32__
1632 #ifdef __WXWINCE__
1633 // No equivalent in WinCE
1634 wxUnusedVar(d);
1635 return false;
1636 #else
1637 return (bool)(SetCurrentDirectory(d.fn_str()) != 0);
1638 #endif
1639 #else
1640 // Must change drive, too.
1641 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1642 if (isDriveSpec)
1643 {
1644 wxChar firstChar = d[0];
1645
1646 // To upper case
1647 if (firstChar > 90)
1648 firstChar = firstChar - 32;
1649
1650 // To a drive number
1651 unsigned int driveNo = firstChar - 64;
1652 if (driveNo > 0)
1653 {
1654 unsigned int noDrives;
1655 _dos_setdrive(driveNo, &noDrives);
1656 }
1657 }
1658 bool success = (chdir(WXSTRINGCAST d) == 0);
1659
1660 return success;
1661 #endif
1662
1663 #endif
1664 }
1665
1666 // Get the OS directory if appropriate (such as the Windows directory).
1667 // On non-Windows platform, probably just return the empty string.
1668 wxString wxGetOSDirectory()
1669 {
1670 #ifdef __WXWINCE__
1671 return wxString(wxT("\\Windows"));
1672 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1673 wxChar buf[256];
1674 GetWindowsDirectory(buf, 256);
1675 return wxString(buf);
1676 #elif defined(__WXMAC__) && wxOSX_USE_CARBON
1677 return wxMacFindFolder(kOnSystemDisk, 'macs', false);
1678 #else
1679 return wxEmptyString;
1680 #endif
1681 }
1682
1683 bool wxEndsWithPathSeparator(const wxString& filename)
1684 {
1685 return !filename.empty() && wxIsPathSeparator(filename.Last());
1686 }
1687
1688 // find a file in a list of directories, returns false if not found
1689 bool wxFindFileInPath(wxString *pStr, const wxString& szPath, const wxString& szFile)
1690 {
1691 // we assume that it's not empty
1692 wxCHECK_MSG( !szFile.empty(), false,
1693 _T("empty file name in wxFindFileInPath"));
1694
1695 // skip path separator in the beginning of the file name if present
1696 wxString szFile2;
1697 if ( wxIsPathSeparator(szFile[0u]) )
1698 szFile2 = szFile.Mid(1);
1699 else
1700 szFile2 = szFile;
1701
1702 wxStringTokenizer tkn(szPath, wxPATH_SEP);
1703
1704 while ( tkn.HasMoreTokens() )
1705 {
1706 wxString strFile = tkn.GetNextToken();
1707 if ( !wxEndsWithPathSeparator(strFile) )
1708 strFile += wxFILE_SEP_PATH;
1709 strFile += szFile2;
1710
1711 if ( wxFileExists(strFile) )
1712 {
1713 *pStr = strFile;
1714 return true;
1715 }
1716 }
1717
1718 return false;
1719 }
1720
1721 #if WXWIN_COMPATIBILITY_2_8
1722 void WXDLLIMPEXP_BASE wxSplitPath(const wxString& fileName,
1723 wxString *pstrPath,
1724 wxString *pstrName,
1725 wxString *pstrExt)
1726 {
1727 wxFileName::SplitPath(fileName, pstrPath, pstrName, pstrExt);
1728 }
1729 #endif // #if WXWIN_COMPATIBILITY_2_8
1730
1731 #if wxUSE_DATETIME
1732
1733 time_t WXDLLIMPEXP_BASE wxFileModificationTime(const wxString& filename)
1734 {
1735 wxDateTime mtime;
1736 if ( !wxFileName(filename).GetTimes(NULL, &mtime, NULL) )
1737 return (time_t)-1;
1738
1739 return mtime.GetTicks();
1740 }
1741
1742 #endif // wxUSE_DATETIME
1743
1744
1745 // Parses the filterStr, returning the number of filters.
1746 // Returns 0 if none or if there's a problem.
1747 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1748
1749 int WXDLLIMPEXP_BASE wxParseCommonDialogsFilter(const wxString& filterStr,
1750 wxArrayString& descriptions,
1751 wxArrayString& filters)
1752 {
1753 descriptions.Clear();
1754 filters.Clear();
1755
1756 wxString str(filterStr);
1757
1758 wxString description, filter;
1759 int pos = 0;
1760 while( pos != wxNOT_FOUND )
1761 {
1762 pos = str.Find(wxT('|'));
1763 if ( pos == wxNOT_FOUND )
1764 {
1765 // if there are no '|'s at all in the string just take the entire
1766 // string as filter and make description empty for later autocompletion
1767 if ( filters.IsEmpty() )
1768 {
1769 descriptions.Add(wxEmptyString);
1770 filters.Add(filterStr);
1771 }
1772 else
1773 {
1774 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1775 }
1776
1777 break;
1778 }
1779
1780 description = str.Left(pos);
1781 str = str.Mid(pos + 1);
1782 pos = str.Find(wxT('|'));
1783 if ( pos == wxNOT_FOUND )
1784 {
1785 filter = str;
1786 }
1787 else
1788 {
1789 filter = str.Left(pos);
1790 str = str.Mid(pos + 1);
1791 }
1792
1793 descriptions.Add(description);
1794 filters.Add(filter);
1795 }
1796
1797 #if defined(__WXMOTIF__)
1798 // split it so there is one wildcard per entry
1799 for( size_t i = 0 ; i < descriptions.GetCount() ; i++ )
1800 {
1801 pos = filters[i].Find(wxT(';'));
1802 if (pos != wxNOT_FOUND)
1803 {
1804 // first split only filters
1805 descriptions.Insert(descriptions[i],i+1);
1806 filters.Insert(filters[i].Mid(pos+1),i+1);
1807 filters[i]=filters[i].Left(pos);
1808
1809 // autoreplace new filter in description with pattern:
1810 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1811 // cause split into:
1812 // C/C++ Files(*.cpp)|*.cpp
1813 // C/C++ Files(*.c;*.h)|*.c;*.h
1814 // and next iteration cause another split into:
1815 // C/C++ Files(*.cpp)|*.cpp
1816 // C/C++ Files(*.c)|*.c
1817 // C/C++ Files(*.h)|*.h
1818 for ( size_t k=i;k<i+2;k++ )
1819 {
1820 pos = descriptions[k].Find(filters[k]);
1821 if (pos != wxNOT_FOUND)
1822 {
1823 wxString before = descriptions[k].Left(pos);
1824 wxString after = descriptions[k].Mid(pos+filters[k].Len());
1825 pos = before.Find(_T('('),true);
1826 if (pos>before.Find(_T(')'),true))
1827 {
1828 before = before.Left(pos+1);
1829 before << filters[k];
1830 pos = after.Find(_T(')'));
1831 int pos1 = after.Find(_T('('));
1832 if (pos != wxNOT_FOUND && (pos<pos1 || pos1==wxNOT_FOUND))
1833 {
1834 before << after.Mid(pos);
1835 descriptions[k] = before;
1836 }
1837 }
1838 }
1839 }
1840 }
1841 }
1842 #endif
1843
1844 // autocompletion
1845 for( size_t j = 0 ; j < descriptions.GetCount() ; j++ )
1846 {
1847 if ( descriptions[j].empty() && !filters[j].empty() )
1848 {
1849 descriptions[j].Printf(_("Files (%s)"), filters[j].c_str());
1850 }
1851 }
1852
1853 return filters.GetCount();
1854 }
1855
1856 #if defined(__WINDOWS__) && !(defined(__UNIX__) || defined(__OS2__))
1857 static bool wxCheckWin32Permission(const wxString& path, DWORD access)
1858 {
1859 // quoting the MSDN: "To obtain a handle to a directory, call the
1860 // CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag", but this
1861 // doesn't work under Win9x/ME but then it's not needed there anyhow
1862 const DWORD dwAttr = ::GetFileAttributes(path.fn_str());
1863 if ( dwAttr == INVALID_FILE_ATTRIBUTES )
1864 {
1865 // file probably doesn't exist at all
1866 return false;
1867 }
1868
1869 if ( wxGetOsVersion() == wxOS_WINDOWS_9X )
1870 {
1871 // FAT directories always allow all access, even if they have the
1872 // readonly flag set, and FAT files can only be read-only
1873 return (dwAttr & FILE_ATTRIBUTE_DIRECTORY) ||
1874 (access != GENERIC_WRITE ||
1875 !(dwAttr & FILE_ATTRIBUTE_READONLY));
1876 }
1877
1878 HANDLE h = ::CreateFile
1879 (
1880 path.t_str(),
1881 access,
1882 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1883 NULL,
1884 OPEN_EXISTING,
1885 dwAttr & FILE_ATTRIBUTE_DIRECTORY
1886 ? FILE_FLAG_BACKUP_SEMANTICS
1887 : 0,
1888 NULL
1889 );
1890 if ( h != INVALID_HANDLE_VALUE )
1891 CloseHandle(h);
1892
1893 return h != INVALID_HANDLE_VALUE;
1894 }
1895 #endif // __WINDOWS__
1896
1897 bool wxIsWritable(const wxString &path)
1898 {
1899 #if defined( __UNIX__ ) || defined(__OS2__)
1900 // access() will take in count also symbolic links
1901 return wxAccess(path.c_str(), W_OK) == 0;
1902 #elif defined( __WINDOWS__ )
1903 return wxCheckWin32Permission(path, GENERIC_WRITE);
1904 #else
1905 wxUnusedVar(path);
1906 // TODO
1907 return false;
1908 #endif
1909 }
1910
1911 bool wxIsReadable(const wxString &path)
1912 {
1913 #if defined( __UNIX__ ) || defined(__OS2__)
1914 // access() will take in count also symbolic links
1915 return wxAccess(path.c_str(), R_OK) == 0;
1916 #elif defined( __WINDOWS__ )
1917 return wxCheckWin32Permission(path, GENERIC_READ);
1918 #else
1919 wxUnusedVar(path);
1920 // TODO
1921 return false;
1922 #endif
1923 }
1924
1925 bool wxIsExecutable(const wxString &path)
1926 {
1927 #if defined( __UNIX__ ) || defined(__OS2__)
1928 // access() will take in count also symbolic links
1929 return wxAccess(path.c_str(), X_OK) == 0;
1930 #elif defined( __WINDOWS__ )
1931 return wxCheckWin32Permission(path, GENERIC_EXECUTE);
1932 #else
1933 wxUnusedVar(path);
1934 // TODO
1935 return false;
1936 #endif
1937 }
1938
1939 // Return the type of an open file
1940 //
1941 // Some file types on some platforms seem seekable but in fact are not.
1942 // The main use of this function is to allow such cases to be detected
1943 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1944 //
1945 // This is important for the archive streams, which benefit greatly from
1946 // being able to seek on a stream, but which will produce corrupt archives
1947 // if they unknowingly seek on a non-seekable stream.
1948 //
1949 // wxFILE_KIND_DISK is a good catch all return value, since other values
1950 // disable features of the archive streams. Some other value must be returned
1951 // for a file type that appears seekable but isn't.
1952 //
1953 // Known examples:
1954 // * Pipes on Windows
1955 // * Files on VMS with a record format other than StreamLF
1956 //
1957 wxFileKind wxGetFileKind(int fd)
1958 {
1959 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1960 switch (::GetFileType(wxGetOSFHandle(fd)) & ~FILE_TYPE_REMOTE)
1961 {
1962 case FILE_TYPE_CHAR:
1963 return wxFILE_KIND_TERMINAL;
1964 case FILE_TYPE_DISK:
1965 return wxFILE_KIND_DISK;
1966 case FILE_TYPE_PIPE:
1967 return wxFILE_KIND_PIPE;
1968 }
1969
1970 return wxFILE_KIND_UNKNOWN;
1971
1972 #elif defined(__UNIX__)
1973 if (isatty(fd))
1974 return wxFILE_KIND_TERMINAL;
1975
1976 struct stat st;
1977 fstat(fd, &st);
1978
1979 if (S_ISFIFO(st.st_mode))
1980 return wxFILE_KIND_PIPE;
1981 if (!S_ISREG(st.st_mode))
1982 return wxFILE_KIND_UNKNOWN;
1983
1984 #if defined(__VMS__)
1985 if (st.st_fab_rfm != FAB$C_STMLF)
1986 return wxFILE_KIND_UNKNOWN;
1987 #endif
1988
1989 return wxFILE_KIND_DISK;
1990
1991 #else
1992 #define wxFILEKIND_STUB
1993 (void)fd;
1994 return wxFILE_KIND_DISK;
1995 #endif
1996 }
1997
1998 wxFileKind wxGetFileKind(FILE *fp)
1999 {
2000 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
2001 // Should be fixed in version 1.4.
2002 #if defined(wxFILEKIND_STUB) || wxONLY_WATCOM_EARLIER_THAN(1,4)
2003 (void)fp;
2004 return wxFILE_KIND_DISK;
2005 #elif defined(__WINDOWS__) && !defined(__CYGWIN__) && !defined(__WATCOMC__) && !defined(__WINE__)
2006 return fp ? wxGetFileKind(_fileno(fp)) : wxFILE_KIND_UNKNOWN;
2007 #else
2008 return fp ? wxGetFileKind(fileno(fp)) : wxFILE_KIND_UNKNOWN;
2009 #endif
2010 }
2011
2012
2013 //------------------------------------------------------------------------
2014 // wild character routines
2015 //------------------------------------------------------------------------
2016
2017 bool wxIsWild( const wxString& pattern )
2018 {
2019 for ( wxString::const_iterator p = pattern.begin(); p != pattern.end(); ++p )
2020 {
2021 switch ( (*p).GetValue() )
2022 {
2023 case wxT('?'):
2024 case wxT('*'):
2025 case wxT('['):
2026 case wxT('{'):
2027 return true;
2028
2029 case wxT('\\'):
2030 if ( ++p == pattern.end() )
2031 return false;
2032 }
2033 }
2034 return false;
2035 }
2036
2037 /*
2038 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
2039 *
2040 * The match procedure is public domain code (from ircII's reg.c)
2041 * but modified to suit our tastes (RN: No "%" syntax I guess)
2042 */
2043
2044 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
2045 {
2046 if (text.empty())
2047 {
2048 /* Match if both are empty. */
2049 return pat.empty();
2050 }
2051
2052 const wxChar *m = pat.c_str(),
2053 *n = text.c_str(),
2054 *ma = NULL,
2055 *na = NULL;
2056 int just = 0,
2057 acount = 0,
2058 count = 0;
2059
2060 if (dot_special && (*n == wxT('.')))
2061 {
2062 /* Never match so that hidden Unix files
2063 * are never found. */
2064 return false;
2065 }
2066
2067 for (;;)
2068 {
2069 if (*m == wxT('*'))
2070 {
2071 ma = ++m;
2072 na = n;
2073 just = 1;
2074 acount = count;
2075 }
2076 else if (*m == wxT('?'))
2077 {
2078 m++;
2079 if (!*n++)
2080 return false;
2081 }
2082 else
2083 {
2084 if (*m == wxT('\\'))
2085 {
2086 m++;
2087 /* Quoting "nothing" is a bad thing */
2088 if (!*m)
2089 return false;
2090 }
2091 if (!*m)
2092 {
2093 /*
2094 * If we are out of both strings or we just
2095 * saw a wildcard, then we can say we have a
2096 * match
2097 */
2098 if (!*n)
2099 return true;
2100 if (just)
2101 return true;
2102 just = 0;
2103 goto not_matched;
2104 }
2105 /*
2106 * We could check for *n == NULL at this point, but
2107 * since it's more common to have a character there,
2108 * check to see if they match first (m and n) and
2109 * then if they don't match, THEN we can check for
2110 * the NULL of n
2111 */
2112 just = 0;
2113 if (*m == *n)
2114 {
2115 m++;
2116 count++;
2117 n++;
2118 }
2119 else
2120 {
2121
2122 not_matched:
2123
2124 /*
2125 * If there are no more characters in the
2126 * string, but we still need to find another
2127 * character (*m != NULL), then it will be
2128 * impossible to match it
2129 */
2130 if (!*n)
2131 return false;
2132
2133 if (ma)
2134 {
2135 m = ma;
2136 n = ++na;
2137 count = acount;
2138 }
2139 else
2140 return false;
2141 }
2142 }
2143 }
2144 }
2145
2146 #ifdef __VISUALC__
2147 #pragma warning(default:4706) // assignment within conditional expression
2148 #endif // VC++