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