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