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