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