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