blind compilation fix for cygwin Unicode build (bug 1296144)
[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)!=0) {
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 {
617 if (was_sep) /* replace only if it was there: */
618 *s = SEP;
619 s = NULL;
620 }
621 else
622 {
623 nm = nnm;
624 s = home;
625 }
626 }
627 }
628
629 d = buf;
630 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
631 /* Copy home dir */
632 while (wxT('\0') != (*d++ = *s++))
633 /* loop */;
634 // Handle root home
635 if (d - 1 > buf && *(d - 2) != SEP)
636 *(d - 1) = SEP;
637 }
638 s = nm;
639 while ((*d++ = *s++) != 0)
640 {
641 // Empty
642 }
643 delete[] nm_tmp; // clean up alloc
644 /* Now clean up the buffer */
645 return wxRealPath(buf);
646 }
647
648 /* Contract Paths to be build upon an environment variable
649 component:
650
651 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
652
653 The call wxExpandPath can convert these back!
654 */
655 wxChar *
656 wxContractPath (const wxString& filename,
657 const wxString& WXUNUSED_IN_WINCE(envname),
658 const wxString& user)
659 {
660 static wxChar dest[_MAXPATHLEN];
661
662 if (filename.empty())
663 return (wxChar *) NULL;
664
665 wxStrcpy (dest, WXSTRINGCAST filename);
666 #ifdef __WXMSW__
667 wxUnix2DosFilename(dest);
668 #endif
669
670 // Handle environment
671 const wxChar *val;
672 #ifndef __WXWINCE__
673 wxChar *tcp;
674 if (!envname.empty() && (val = wxGetenv (WXSTRINGCAST envname)) != NULL &&
675 (tcp = wxStrstr (dest, val)) != NULL)
676 {
677 wxStrcpy (wxFileFunctionsBuffer, tcp + wxStrlen (val));
678 *tcp++ = wxT('$');
679 *tcp++ = wxT('{');
680 wxStrcpy (tcp, WXSTRINGCAST envname);
681 wxStrcat (tcp, wxT("}"));
682 wxStrcat (tcp, wxFileFunctionsBuffer);
683 }
684 #endif
685
686 // Handle User's home (ignore root homes!)
687 val = wxGetUserHome (user);
688 if (!val)
689 return dest;
690
691 const size_t len = wxStrlen(val);
692 if (len <= 2)
693 return dest;
694
695 if (wxStrncmp(dest, val, len) == 0)
696 {
697 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
698 if (!user.empty())
699 wxStrcat(wxFileFunctionsBuffer, (const wxChar*) user);
700 wxStrcat(wxFileFunctionsBuffer, dest + len);
701 wxStrcpy (dest, wxFileFunctionsBuffer);
702 }
703
704 return dest;
705 }
706
707 // Return just the filename, not the path (basename)
708 wxChar *wxFileNameFromPath (wxChar *path)
709 {
710 wxString p = path;
711 wxString n = wxFileNameFromPath(p);
712
713 return path + p.length() - n.length();
714 }
715
716 wxString wxFileNameFromPath (const wxString& path)
717 {
718 wxString name, ext;
719 wxFileName::SplitPath(path, NULL, &name, &ext);
720
721 wxString fullname = name;
722 if ( !ext.empty() )
723 {
724 fullname << wxFILE_SEP_EXT << ext;
725 }
726
727 return fullname;
728 }
729
730 // Return just the directory, or NULL if no directory
731 wxChar *
732 wxPathOnly (wxChar *path)
733 {
734 if (path && *path)
735 {
736 static wxChar buf[_MAXPATHLEN];
737
738 // Local copy
739 wxStrcpy (buf, path);
740
741 int l = wxStrlen(path);
742 int i = l - 1;
743
744 // Search backward for a backward or forward slash
745 while (i > -1)
746 {
747 #if defined(__WXMAC__) && !defined(__DARWIN__)
748 // Classic or Carbon CodeWarrior like
749 // Carbon with Apple DevTools is Unix like
750 if (path[i] == wxT(':') )
751 {
752 buf[i] = 0;
753 return buf;
754 }
755 #else
756 // Unix like or Windows
757 if (path[i] == wxT('/') || path[i] == wxT('\\'))
758 {
759 buf[i] = 0;
760 return buf;
761 }
762 #endif
763 #ifdef __VMS__
764 if (path[i] == wxT(']'))
765 {
766 buf[i+1] = 0;
767 return buf;
768 }
769 #endif
770 i --;
771 }
772
773 #if defined(__WXMSW__) || defined(__OS2__)
774 // Try Drive specifier
775 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
776 {
777 // A:junk --> A:. (since A:.\junk Not A:\junk)
778 buf[2] = wxT('.');
779 buf[3] = wxT('\0');
780 return buf;
781 }
782 #endif
783 }
784 return (wxChar *) NULL;
785 }
786
787 // Return just the directory, or NULL if no directory
788 wxString wxPathOnly (const wxString& path)
789 {
790 if (!path.empty())
791 {
792 wxChar buf[_MAXPATHLEN];
793
794 // Local copy
795 wxStrcpy (buf, WXSTRINGCAST path);
796
797 int l = path.Length();
798 int i = l - 1;
799
800 // Search backward for a backward or forward slash
801 while (i > -1)
802 {
803 #if defined(__WXMAC__) && !defined(__DARWIN__)
804 // Classic or Carbon CodeWarrior like
805 // Carbon with Apple DevTools is Unix like
806 if (path[i] == wxT(':') )
807 {
808 buf[i] = 0;
809 return wxString(buf);
810 }
811 #else
812 // Unix like or Windows
813 if (path[i] == wxT('/') || path[i] == wxT('\\'))
814 {
815 // Don't return an empty string
816 if (i == 0)
817 i ++;
818 buf[i] = 0;
819 return wxString(buf);
820 }
821 #endif
822 #ifdef __VMS__
823 if (path[i] == wxT(']'))
824 {
825 buf[i+1] = 0;
826 return wxString(buf);
827 }
828 #endif
829 i --;
830 }
831
832 #if defined(__WXMSW__) || defined(__OS2__)
833 // Try Drive specifier
834 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
835 {
836 // A:junk --> A:. (since A:.\junk Not A:\junk)
837 buf[2] = wxT('.');
838 buf[3] = wxT('\0');
839 return wxString(buf);
840 }
841 #endif
842 }
843 return wxEmptyString;
844 }
845
846 // Utility for converting delimiters in DOS filenames to UNIX style
847 // and back again - or we get nasty problems with delimiters.
848 // Also, convert to lower case, since case is significant in UNIX.
849
850 #if defined(__WXMAC__)
851
852 #if TARGET_API_MAC_OSX
853 #define kDefaultPathStyle kCFURLPOSIXPathStyle
854 #else
855 #define kDefaultPathStyle kCFURLHFSPathStyle
856 #endif
857
858 wxString wxMacFSRefToPath( const FSRef *fsRef , CFStringRef additionalPathComponent )
859 {
860 CFURLRef fullURLRef;
861 fullURLRef = CFURLCreateFromFSRef(NULL, fsRef);
862 if ( additionalPathComponent )
863 {
864 CFURLRef parentURLRef = fullURLRef ;
865 fullURLRef = CFURLCreateCopyAppendingPathComponent(NULL, parentURLRef,
866 additionalPathComponent,false);
867 CFRelease( parentURLRef ) ;
868 }
869 CFStringRef cfString = CFURLCopyFileSystemPath(fullURLRef, kDefaultPathStyle);
870 CFRelease( fullURLRef ) ;
871 return wxMacCFStringHolder(cfString).AsString(wxLocale::GetSystemEncoding());
872 }
873
874 OSStatus wxMacPathToFSRef( const wxString&path , FSRef *fsRef )
875 {
876 OSStatus err = noErr ;
877 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, wxMacCFStringHolder(path ,wxLocale::GetSystemEncoding() ) , kDefaultPathStyle, false);
878 if ( NULL != url )
879 {
880 if ( CFURLGetFSRef(url, fsRef) == false )
881 err = fnfErr ;
882 CFRelease( url ) ;
883 }
884 else
885 {
886 err = fnfErr ;
887 }
888 return err ;
889 }
890
891 wxString wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname )
892 {
893 CFStringRef cfname = CFStringCreateWithCharacters( kCFAllocatorDefault,
894 uniname->unicode,
895 uniname->length );
896 return wxMacCFStringHolder(cfname).AsString() ;
897 }
898
899 wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
900 {
901 FSRef fsRef ;
902 if ( FSpMakeFSRef( spec , &fsRef) == noErr )
903 {
904 return wxMacFSRefToPath( &fsRef ) ;
905 }
906 return wxEmptyString ;
907 }
908
909 void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
910 {
911 OSStatus err = noErr ;
912 FSRef fsRef ;
913 wxMacPathToFSRef( path , &fsRef ) ;
914 err = FSRefMakeFSSpec( &fsRef , spec ) ;
915 }
916
917 #endif // __WXMAC__
918
919 void
920 wxDos2UnixFilename (wxChar *s)
921 {
922 if (s)
923 while (*s)
924 {
925 if (*s == _T('\\'))
926 *s = _T('/');
927 #ifdef __WXMSW__
928 else
929 *s = (wxChar)wxTolower (*s); // Case INDEPENDENT
930 #endif
931 s++;
932 }
933 }
934
935 void
936 #if defined(__WXMSW__) || defined(__OS2__)
937 wxUnix2DosFilename (wxChar *s)
938 #else
939 wxUnix2DosFilename (wxChar *WXUNUSED(s) )
940 #endif
941 {
942 // Yes, I really mean this to happen under DOS only! JACS
943 #if defined(__WXMSW__) || defined(__OS2__)
944 if (s)
945 while (*s)
946 {
947 if (*s == wxT('/'))
948 *s = wxT('\\');
949 s++;
950 }
951 #endif
952 }
953
954 // Concatenate two files to form third
955 bool
956 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
957 {
958 #if wxUSE_FILE
959
960 wxFile in1(file1), in2(file2);
961 wxTempFile out(file3);
962
963 if ( !in1.IsOpened() || !in2.IsOpened() || !out.IsOpened() )
964 return false;
965
966 ssize_t ofs;
967 unsigned char buf[1024];
968
969 for( int i=0; i<2; i++)
970 {
971 wxFile *in = i==0 ? &in1 : &in2;
972 do{
973 if ( (ofs = in->Read(buf,WXSIZEOF(buf))) == wxInvalidOffset ) return false;
974 if ( ofs > 0 )
975 if ( !out.Write(buf,ofs) )
976 return false;
977 } while ( ofs == (ssize_t)WXSIZEOF(buf) );
978 }
979
980 return out.Commit();
981
982 #else
983
984 wxUnusedVar(file1);
985 wxUnusedVar(file2);
986 wxUnusedVar(file3);
987 return false;
988
989 #endif
990 }
991
992 // Copy files
993 bool
994 wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
995 {
996 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
997 // CopyFile() copies file attributes and modification time too, so use it
998 // instead of our code if available
999 //
1000 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1001 if ( !::CopyFile(file1, file2, !overwrite) )
1002 {
1003 wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
1004 file1.c_str(), file2.c_str());
1005
1006 return false;
1007 }
1008 #elif defined(__OS2__)
1009 if ( ::DosCopy((PSZ)file1.c_str(), (PSZ)file2.c_str(), overwrite ? DCPY_EXISTING : 0) != 0 )
1010 return false;
1011 #elif defined(__PALMOS__)
1012 // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
1013 return false;
1014 #elif wxUSE_FILE // !Win32
1015
1016 wxStructStat fbuf;
1017 // get permissions of file1
1018 if ( wxStat( file1.c_str(), &fbuf) != 0 )
1019 {
1020 // the file probably doesn't exist or we haven't the rights to read
1021 // from it anyhow
1022 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1023 file1.c_str());
1024 return false;
1025 }
1026
1027 // open file1 for reading
1028 wxFile fileIn(file1, wxFile::read);
1029 if ( !fileIn.IsOpened() )
1030 return false;
1031
1032 // remove file2, if it exists. This is needed for creating
1033 // file2 with the correct permissions in the next step
1034 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
1035 {
1036 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1037 file2.c_str());
1038 return false;
1039 }
1040
1041 // reset the umask as we want to create the file with exactly the same
1042 // permissions as the original one
1043 wxCHANGE_UMASK(0);
1044
1045 // create file2 with the same permissions than file1 and open it for
1046 // writing
1047
1048 wxFile fileOut;
1049 if ( !fileOut.Create(file2, overwrite, fbuf.st_mode & 0777) )
1050 return false;
1051
1052 // copy contents of file1 to file2
1053 char buf[4096];
1054 size_t count;
1055 for ( ;; )
1056 {
1057 count = fileIn.Read(buf, WXSIZEOF(buf));
1058 if ( fileIn.Error() )
1059 return false;
1060
1061 // end of file?
1062 if ( !count )
1063 break;
1064
1065 if ( fileOut.Write(buf, count) < count )
1066 return false;
1067 }
1068
1069 // we can expect fileIn to be closed successfully, but we should ensure
1070 // that fileOut was closed as some write errors (disk full) might not be
1071 // detected before doing this
1072 if ( !fileIn.Close() || !fileOut.Close() )
1073 return false;
1074
1075 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1076 // no chmod in VA. Should be some permission API for HPFS386 partitions
1077 // however
1078 if ( chmod(OS_FILENAME(file2), fbuf.st_mode) != 0 )
1079 {
1080 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1081 file2.c_str());
1082 return false;
1083 }
1084 #endif // OS/2 || Mac
1085
1086 #else // !Win32 && ! wxUSE_FILE
1087
1088 // impossible to simulate with wxWidgets API
1089 wxUnusedVar(file1);
1090 wxUnusedVar(file2);
1091 wxUnusedVar(overwrite);
1092 return false;
1093
1094 #endif // __WXMSW__ && __WIN32__
1095
1096 return true;
1097 }
1098
1099 bool
1100 wxRenameFile (const wxString& file1, const wxString& file2)
1101 {
1102 #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
1103 // Normal system call
1104 if ( wxRename (file1, file2) == 0 )
1105 return true;
1106 #endif
1107
1108 // Try to copy
1109 if (wxCopyFile(file1, file2)) {
1110 wxRemoveFile(file1);
1111 return true;
1112 }
1113 // Give up
1114 return false;
1115 }
1116
1117 bool wxRemoveFile(const wxString& file)
1118 {
1119 #if defined(__VISUALC__) \
1120 || defined(__BORLANDC__) \
1121 || defined(__WATCOMC__) \
1122 || defined(__DMC__) \
1123 || defined(__GNUWIN32__) \
1124 || (defined(__MWERKS__) && defined(__MSL__))
1125 int res = wxRemove(file);
1126 #elif defined(__WXMAC__)
1127 int res = unlink(wxFNCONV(file));
1128 #elif defined(__WXPALMOS__)
1129 int res = 1;
1130 // TODO with VFSFileDelete()
1131 #else
1132 int res = unlink(OS_FILENAME(file));
1133 #endif
1134
1135 return res == 0;
1136 }
1137
1138 bool wxMkdir(const wxString& dir, int perm)
1139 {
1140 #if defined(__WXPALMOS__)
1141 return false;
1142 #elif defined(__WXMAC__) && !defined(__UNIX__)
1143 return (mkdir( wxFNCONV(dir) , 0 ) == 0);
1144 #else // !Mac
1145 const wxChar *dirname = dir.c_str();
1146
1147 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1148 // for the GNU compiler
1149 #if (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WINE__) || defined(__WXMICROWIN__)
1150 #if defined(MSVCRT)
1151 wxUnusedVar(perm);
1152 if ( mkdir(wxFNCONV(dirname)) != 0 )
1153 #else
1154 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1155 #endif
1156 #elif defined(__OS2__)
1157 wxUnusedVar(perm);
1158 if (::DosCreateDir((PSZ)dirname, NULL) != 0) // enhance for EAB's??
1159 #elif defined(__DOS__)
1160 #if defined(__WATCOMC__)
1161 (void)perm;
1162 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1163 #elif defined(__DJGPP__)
1164 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1165 #else
1166 #error "Unsupported DOS compiler!"
1167 #endif
1168 #else // !MSW, !DOS and !OS/2 VAC++
1169 wxUnusedVar(perm);
1170 #ifdef __WXWINCE__
1171 if ( !CreateDirectory(dirname, NULL) )
1172 #else
1173 if ( wxMkDir(dir.fn_str()) != 0 )
1174 #endif
1175 #endif // !MSW/MSW
1176 {
1177 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1178
1179 return false;
1180 }
1181
1182 return true;
1183 #endif // Mac/!Mac
1184 }
1185
1186 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1187 {
1188 #if defined(__VMS__)
1189 return false; //to be changed since rmdir exists in VMS7.x
1190 #elif defined(__OS2__)
1191 return (::DosDeleteDir((PSZ)dir.c_str()) == 0);
1192 #elif defined(__WXWINCE__)
1193 return (CreateDirectory(dir, NULL) != 0);
1194 #elif defined(__WXPALMOS__)
1195 // TODO with VFSFileRename()
1196 return false;
1197 #else
1198 return (wxRmDir(OS_FILENAME(dir)) == 0);
1199 #endif
1200 }
1201
1202 // does the path exists? (may have or not '/' or '\\' at the end)
1203 bool wxDirExists(const wxChar *pszPathName)
1204 {
1205 wxString strPath(pszPathName);
1206
1207 #if defined(__WINDOWS__) || defined(__OS2__)
1208 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1209 // so remove all trailing backslashes from the path - but don't do this for
1210 // the pathes "d:\" (which are different from "d:") nor for just "\"
1211 while ( wxEndsWithPathSeparator(strPath) )
1212 {
1213 size_t len = strPath.length();
1214 if ( len == 1 || (len == 3 && strPath[len - 2] == _T(':')) )
1215 break;
1216
1217 strPath.Truncate(len - 1);
1218 }
1219 #endif // __WINDOWS__
1220
1221 #ifdef __OS2__
1222 // OS/2 can't handle "d:", it wants either "d:\" or "d:."
1223 if (strPath.length() == 2 && strPath[1u] == _T(':'))
1224 strPath << _T('.');
1225 #endif
1226
1227 #if defined(__WXPALMOS__)
1228 return false;
1229 #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
1230 // stat() can't cope with network paths
1231 DWORD ret = ::GetFileAttributes(strPath);
1232
1233 return (ret != (DWORD)-1) && (ret & FILE_ATTRIBUTE_DIRECTORY);
1234 #elif defined(__OS2__)
1235 return (bool)(::DosSetCurrentDir((PSZ)(WXSTRINGCAST strPath)));
1236 #else // !__WIN32__
1237
1238 wxStructStat st;
1239 #ifndef __VISAGECPP__
1240 return wxStat(strPath.c_str(), &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR);
1241 #else
1242 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1243 return wxStat(pszPathName, &st) == 0 && (st.st_mode == S_IFDIR);
1244 #endif
1245
1246 #endif // __WIN32__/!__WIN32__
1247 }
1248
1249 // Get a temporary filename, opening and closing the file.
1250 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1251 {
1252 #if wxUSE_FILE
1253 wxString filename = wxFileName::CreateTempFileName(prefix);
1254 if ( filename.empty() )
1255 return NULL;
1256
1257 if ( buf )
1258 wxStrcpy(buf, filename);
1259 else
1260 buf = MYcopystring(filename);
1261
1262 return buf;
1263 #else
1264 wxUnusedVar(prefix);
1265 wxUnusedVar(buf);
1266 // wxFileName::CreateTempFileName needs wxFile class enabled
1267 return NULL;
1268 #endif
1269 }
1270
1271 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1272 {
1273 buf = wxGetTempFileName(prefix);
1274
1275 return !buf.empty();
1276 }
1277
1278 // Get first file name matching given wild card.
1279
1280 static wxDir *gs_dir = NULL;
1281 static wxString gs_dirPath;
1282
1283 wxString wxFindFirstFile(const wxChar *spec, int flags)
1284 {
1285 wxSplitPath(spec, &gs_dirPath, NULL, NULL);
1286 if ( gs_dirPath.empty() )
1287 gs_dirPath = wxT(".");
1288 if ( !wxEndsWithPathSeparator(gs_dirPath ) )
1289 gs_dirPath << wxFILE_SEP_PATH;
1290
1291 if (gs_dir)
1292 delete gs_dir;
1293 gs_dir = new wxDir(gs_dirPath);
1294
1295 if ( !gs_dir->IsOpened() )
1296 {
1297 wxLogSysError(_("Can not enumerate files '%s'"), spec);
1298 return wxEmptyString;
1299 }
1300
1301 int dirFlags;
1302 switch (flags)
1303 {
1304 case wxDIR: dirFlags = wxDIR_DIRS; break;
1305 case wxFILE: dirFlags = wxDIR_FILES; break;
1306 default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
1307 }
1308
1309 wxString result;
1310 gs_dir->GetFirst(&result, wxFileNameFromPath(wxString(spec)), dirFlags);
1311 if ( result.empty() )
1312 {
1313 wxDELETE(gs_dir);
1314 return result;
1315 }
1316
1317 return gs_dirPath + result;
1318 }
1319
1320 wxString wxFindNextFile()
1321 {
1322 wxASSERT_MSG( gs_dir, wxT("You must call wxFindFirstFile before!") );
1323
1324 wxString result;
1325 gs_dir->GetNext(&result);
1326
1327 if ( result.empty() )
1328 {
1329 wxDELETE(gs_dir);
1330 return result;
1331 }
1332
1333 return gs_dirPath + result;
1334 }
1335
1336
1337 // Get current working directory.
1338 // If buf is NULL, allocates space using new, else
1339 // copies into buf.
1340 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1341 {
1342 #if defined(__WXPALMOS__)
1343 // TODO ?
1344 return NULL;
1345 #elif defined(__WXWINCE__)
1346 // TODO
1347 wxUnusedVar(buf);
1348 wxUnusedVar(sz);
1349 return NULL;
1350 #else
1351 if ( !buf )
1352 {
1353 buf = new wxChar[sz + 1];
1354 }
1355
1356 bool ok wxDUMMY_INITIALIZE(false);
1357
1358 // for the compilers which have Unicode version of _getcwd(), call it
1359 // directly, for the others call the ANSI version and do the translation
1360 #if !wxUSE_UNICODE
1361 #define cbuf buf
1362 #else // wxUSE_UNICODE
1363 bool needsANSI = true;
1364
1365 #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
1366 char cbuf[_MAXPATHLEN];
1367 #endif
1368
1369 #ifdef HAVE_WGETCWD
1370 #if wxUSE_UNICODE_MSLU
1371 if ( wxGetOsVersion() != wxWIN95 )
1372 #else
1373 char *cbuf = NULL; // never really used because needsANSI will always be false
1374 #endif
1375 {
1376 ok = _wgetcwd(buf, sz) != NULL;
1377 needsANSI = false;
1378 }
1379 #endif
1380
1381 if ( needsANSI )
1382 #endif // wxUSE_UNICODE
1383 {
1384 #if defined(_MSC_VER) || defined(__MINGW32__)
1385 ok = _getcwd(cbuf, sz) != NULL;
1386 #elif defined(__WXMAC__) && !defined(__DARWIN__)
1387 char lbuf[1024] ;
1388 if ( getcwd( lbuf , sizeof( lbuf ) ) )
1389 {
1390 wxString res( lbuf , *wxConvCurrent ) ;
1391 wxStrcpy( buf , res ) ;
1392 ok = true;
1393 }
1394 else
1395 ok = false ;
1396 #elif defined(__OS2__)
1397 APIRET rc;
1398 ULONG ulDriveNum = 0;
1399 ULONG ulDriveMap = 0;
1400 rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
1401 ok = rc == 0;
1402 if (ok)
1403 {
1404 sz -= 3;
1405 rc = ::DosQueryCurrentDir( 0 // current drive
1406 ,cbuf + 3
1407 ,(PULONG)&sz
1408 );
1409 cbuf[0] = char('A' + (ulDriveNum - 1));
1410 cbuf[1] = ':';
1411 cbuf[2] = '\\';
1412 ok = rc == 0;
1413 }
1414 #else // !Win32/VC++ !Mac !OS2
1415 ok = getcwd(cbuf, sz) != NULL;
1416 #endif // platform
1417
1418 #if wxUSE_UNICODE && !(defined(__WXMAC__) && !defined(__DARWIN__))
1419 // finally convert the result to Unicode if needed
1420 wxConvFile.MB2WC(buf, cbuf, sz);
1421 #endif // wxUSE_UNICODE
1422 }
1423
1424 if ( !ok )
1425 {
1426 wxLogSysError(_("Failed to get the working directory"));
1427
1428 // VZ: the old code used to return "." on error which didn't make any
1429 // sense at all to me - empty string is a better error indicator
1430 // (NULL might be even better but I'm afraid this could lead to
1431 // problems with the old code assuming the return is never NULL)
1432 buf[0] = _T('\0');
1433 }
1434 else // ok, but we might need to massage the path into the right format
1435 {
1436 #ifdef __DJGPP__
1437 // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
1438 // with / deliminers. We don't like that.
1439 for (wxChar *ch = buf; *ch; ch++)
1440 {
1441 if (*ch == wxT('/'))
1442 *ch = wxT('\\');
1443 }
1444 #endif // __DJGPP__
1445
1446 // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
1447 // he needs Unix as opposed to Win32 pathnames
1448 #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
1449 // another example of DOS/Unix mix (Cygwin)
1450 wxString pathUnix = buf;
1451 #if wxUSE_UNICODE
1452 char bufA[_MAXPATHLEN];
1453 cygwin_conv_to_full_win32_path(pathUnix.mb_str(wxConvFile), bufA);
1454 wxConvFile.MB2WC(buf, bufA, sz);
1455 #else
1456 cygwin_conv_to_full_win32_path(pathUnix, buf);
1457 #endif // wxUSE_UNICODE
1458 #endif // __CYGWIN__
1459 }
1460
1461 return buf;
1462
1463 #if !wxUSE_UNICODE
1464 #undef cbuf
1465 #endif
1466
1467 #endif
1468 // __WXWINCE__
1469 }
1470
1471 wxString wxGetCwd()
1472 {
1473 wxChar *buffer = new wxChar[_MAXPATHLEN];
1474 wxGetWorkingDirectory(buffer, _MAXPATHLEN);
1475 wxString str( buffer );
1476 delete [] buffer;
1477
1478 return str;
1479 }
1480
1481 bool wxSetWorkingDirectory(const wxString& d)
1482 {
1483 #if defined(__OS2__)
1484 return (::DosSetCurrentDir((PSZ)d.c_str()) == 0);
1485 #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
1486 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1487 #elif defined(__WINDOWS__)
1488
1489 #ifdef __WIN32__
1490 #ifdef __WXWINCE__
1491 // No equivalent in WinCE
1492 wxUnusedVar(d);
1493 return false;
1494 #else
1495 return (bool)(SetCurrentDirectory(d) != 0);
1496 #endif
1497 #else
1498 // Must change drive, too.
1499 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1500 if (isDriveSpec)
1501 {
1502 wxChar firstChar = d[0];
1503
1504 // To upper case
1505 if (firstChar > 90)
1506 firstChar = firstChar - 32;
1507
1508 // To a drive number
1509 unsigned int driveNo = firstChar - 64;
1510 if (driveNo > 0)
1511 {
1512 unsigned int noDrives;
1513 _dos_setdrive(driveNo, &noDrives);
1514 }
1515 }
1516 bool success = (chdir(WXSTRINGCAST d) == 0);
1517
1518 return success;
1519 #endif
1520
1521 #endif
1522 }
1523
1524 // Get the OS directory if appropriate (such as the Windows directory).
1525 // On non-Windows platform, probably just return the empty string.
1526 wxString wxGetOSDirectory()
1527 {
1528 #ifdef __WXWINCE__
1529 return wxString(wxT("\\Windows"));
1530 #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1531 wxChar buf[256];
1532 GetWindowsDirectory(buf, 256);
1533 return wxString(buf);
1534 #elif defined(__WXMAC__)
1535 return wxMacFindFolder(kOnSystemDisk, 'macs', false);
1536 #else
1537 return wxEmptyString;
1538 #endif
1539 }
1540
1541 bool wxEndsWithPathSeparator(const wxChar *pszFileName)
1542 {
1543 size_t len = wxStrlen(pszFileName);
1544
1545 return len && wxIsPathSeparator(pszFileName[len - 1]);
1546 }
1547
1548 // find a file in a list of directories, returns false if not found
1549 bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
1550 {
1551 // we assume that it's not empty
1552 wxCHECK_MSG( !wxIsEmpty(pszFile), false,
1553 _T("empty file name in wxFindFileInPath"));
1554
1555 // skip path separator in the beginning of the file name if present
1556 if ( wxIsPathSeparator(*pszFile) )
1557 pszFile++;
1558
1559 // copy the path (strtok will modify it)
1560 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1561 wxStrcpy(szPath, pszPath);
1562
1563 wxString strFile;
1564 wxChar *pc, *save_ptr;
1565 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1566 pc != NULL;
1567 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1568 {
1569 // search for the file in this directory
1570 strFile = pc;
1571 if ( !wxEndsWithPathSeparator(pc) )
1572 strFile += wxFILE_SEP_PATH;
1573 strFile += pszFile;
1574
1575 if ( wxFileExists(strFile) ) {
1576 *pStr = strFile;
1577 break;
1578 }
1579 }
1580
1581 // suppress warning about unused variable save_ptr when wxStrtok() is a
1582 // macro which throws away its third argument
1583 save_ptr = pc;
1584
1585 delete [] szPath;
1586
1587 return pc != NULL; // if true => we breaked from the loop
1588 }
1589
1590 void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
1591 wxString *pstrPath,
1592 wxString *pstrName,
1593 wxString *pstrExt)
1594 {
1595 // it can be empty, but it shouldn't be NULL
1596 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
1597
1598 wxFileName::SplitPath(pszFileName, pstrPath, pstrName, pstrExt);
1599 }
1600
1601 time_t WXDLLEXPORT wxFileModificationTime(const wxString& filename)
1602 {
1603 #if defined(__WXPALMOS__)
1604 return 0;
1605 #elif defined(__WXWINCE__)
1606 FILETIME ftLastWrite;
1607 AutoHANDLE hFile(::CreateFile(filename, GENERIC_READ, FILE_SHARE_READ,
1608 NULL, 0, FILE_ATTRIBUTE_NORMAL, 0));
1609
1610 if ( !hFile.IsOk() )
1611 return 0;
1612
1613 if ( !::GetFileTime(hFile, NULL, NULL, &ftLastWrite) )
1614 return 0;
1615
1616 // sure we want to translate to local time here?
1617 FILETIME ftLocal;
1618 if ( !::FileTimeToLocalFileTime(&ftLastWrite, &ftLocal) )
1619 {
1620 wxLogLastError(_T("FileTimeToLocalFileTime"));
1621 }
1622
1623 // FILETIME is a counted in 100-ns since 1601-01-01, convert it to
1624 // number of seconds since 1970-01-01
1625 ULARGE_INTEGER uli;
1626 uli.LowPart = ftLocal.dwLowDateTime;
1627 uli.HighPart = ftLocal.dwHighDateTime;
1628
1629 ULONGLONG ull = uli.QuadPart;
1630 ull /= wxULL(10000000); // number of 100ns intervals in 1s
1631 ull -= wxULL(11644473600); // 1970-01-01 - 1601-01-01 in seconds
1632
1633 return wx_static_cast(time_t, ull);
1634 #else
1635 wxStructStat buf;
1636 if ( wxStat( filename, &buf) != 0 )
1637 return 0;
1638
1639 return buf.st_mtime;
1640 #endif
1641 }
1642
1643
1644 // Parses the filterStr, returning the number of filters.
1645 // Returns 0 if none or if there's a problem.
1646 // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
1647
1648 int WXDLLEXPORT wxParseCommonDialogsFilter(const wxString& filterStr,
1649 wxArrayString& descriptions,
1650 wxArrayString& filters)
1651 {
1652 descriptions.Clear();
1653 filters.Clear();
1654
1655 wxString str(filterStr);
1656
1657 wxString description, filter;
1658 int pos = 0;
1659 while( pos != wxNOT_FOUND )
1660 {
1661 pos = str.Find(wxT('|'));
1662 if ( pos == wxNOT_FOUND )
1663 {
1664 // if there are no '|'s at all in the string just take the entire
1665 // string as filter and make description empty for later autocompletion
1666 if ( filters.IsEmpty() )
1667 {
1668 descriptions.Add(wxEmptyString);
1669 filters.Add(filterStr);
1670 }
1671 else
1672 {
1673 wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
1674 }
1675
1676 break;
1677 }
1678
1679 description = str.Left(pos);
1680 str = str.Mid(pos + 1);
1681 pos = str.Find(wxT('|'));
1682 if ( pos == wxNOT_FOUND )
1683 {
1684 filter = str;
1685 }
1686 else
1687 {
1688 filter = str.Left(pos);
1689 str = str.Mid(pos + 1);
1690 }
1691
1692 descriptions.Add(description);
1693 filters.Add(filter);
1694 }
1695
1696 #if defined(__WXMOTIF__)
1697 // split it so there is one wildcard per entry
1698 for( size_t i = 0 ; i < descriptions.GetCount() ; i++ )
1699 {
1700 pos = filters[i].Find(wxT(';'));
1701 if (pos != wxNOT_FOUND)
1702 {
1703 // first split only filters
1704 descriptions.Insert(descriptions[i],i+1);
1705 filters.Insert(filters[i].Mid(pos+1),i+1);
1706 filters[i]=filters[i].Left(pos);
1707
1708 // autoreplace new filter in description with pattern:
1709 // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
1710 // cause split into:
1711 // C/C++ Files(*.cpp)|*.cpp
1712 // C/C++ Files(*.c;*.h)|*.c;*.h
1713 // and next iteration cause another split into:
1714 // C/C++ Files(*.cpp)|*.cpp
1715 // C/C++ Files(*.c)|*.c
1716 // C/C++ Files(*.h)|*.h
1717 for ( size_t k=i;k<i+2;k++ )
1718 {
1719 pos = descriptions[k].Find(filters[k]);
1720 if (pos != wxNOT_FOUND)
1721 {
1722 wxString before = descriptions[k].Left(pos);
1723 wxString after = descriptions[k].Mid(pos+filters[k].Len());
1724 pos = before.Find(_T('('),true);
1725 if (pos>before.Find(_T(')'),true))
1726 {
1727 before = before.Left(pos+1);
1728 before << filters[k];
1729 pos = after.Find(_T(')'));
1730 int pos1 = after.Find(_T('('));
1731 if (pos != wxNOT_FOUND && (pos<pos1 || pos1==wxNOT_FOUND))
1732 {
1733 before << after.Mid(pos);
1734 descriptions[k] = before;
1735 }
1736 }
1737 }
1738 }
1739 }
1740 }
1741 #endif
1742
1743 // autocompletion
1744 for( size_t j = 0 ; j < descriptions.GetCount() ; j++ )
1745 {
1746 if ( descriptions[j].empty() && !filters[j].empty() )
1747 {
1748 descriptions[j].Printf(_("Files (%s)"), filters[j].c_str());
1749 }
1750 }
1751
1752 return filters.GetCount();
1753 }
1754
1755
1756 //------------------------------------------------------------------------
1757 // wild character routines
1758 //------------------------------------------------------------------------
1759
1760 bool wxIsWild( const wxString& pattern )
1761 {
1762 wxString tmp = pattern;
1763 wxChar *pat = WXSTRINGCAST(tmp);
1764 while (*pat)
1765 {
1766 switch (*pat++)
1767 {
1768 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1769 return true;
1770 case wxT('\\'):
1771 if (!*pat++)
1772 return false;
1773 }
1774 }
1775 return false;
1776 }
1777
1778 /*
1779 * Written By Douglas A. Lewis <dalewis@cs.Buffalo.EDU>
1780 *
1781 * The match procedure is public domain code (from ircII's reg.c)
1782 */
1783
1784 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1785 {
1786 if (text.empty())
1787 {
1788 /* Match if both are empty. */
1789 return pat.empty();
1790 }
1791
1792 const wxChar *m = pat.c_str(),
1793 *n = text.c_str(),
1794 *ma = NULL,
1795 *na = NULL,
1796 *mp = NULL,
1797 *np = NULL;
1798 int just = 0,
1799 pcount = 0,
1800 acount = 0,
1801 count = 0;
1802
1803 if (dot_special && (*n == wxT('.')))
1804 {
1805 /* Never match so that hidden Unix files
1806 * are never found. */
1807 return false;
1808 }
1809
1810 for (;;)
1811 {
1812 if (*m == wxT('*'))
1813 {
1814 ma = ++m;
1815 na = n;
1816 just = 1;
1817 mp = NULL;
1818 acount = count;
1819 }
1820 else if (*m == wxT('?'))
1821 {
1822 m++;
1823 if (!*n++)
1824 return false;
1825 }
1826 else
1827 {
1828 if (*m == wxT('\\'))
1829 {
1830 m++;
1831 /* Quoting "nothing" is a bad thing */
1832 if (!*m)
1833 return false;
1834 }
1835 if (!*m)
1836 {
1837 /*
1838 * If we are out of both strings or we just
1839 * saw a wildcard, then we can say we have a
1840 * match
1841 */
1842 if (!*n)
1843 return true;
1844 if (just)
1845 return true;
1846 just = 0;
1847 goto not_matched;
1848 }
1849 /*
1850 * We could check for *n == NULL at this point, but
1851 * since it's more common to have a character there,
1852 * check to see if they match first (m and n) and
1853 * then if they don't match, THEN we can check for
1854 * the NULL of n
1855 */
1856 just = 0;
1857 if (*m == *n)
1858 {
1859 m++;
1860 if (*n == wxT(' '))
1861 mp = NULL;
1862 count++;
1863 n++;
1864 }
1865 else
1866 {
1867
1868 not_matched:
1869
1870 /*
1871 * If there are no more characters in the
1872 * string, but we still need to find another
1873 * character (*m != NULL), then it will be
1874 * impossible to match it
1875 */
1876 if (!*n)
1877 return false;
1878 if (mp)
1879 {
1880 m = mp;
1881 if (*np == wxT(' '))
1882 {
1883 mp = NULL;
1884 goto check_percent;
1885 }
1886 n = ++np;
1887 count = pcount;
1888 }
1889 else
1890 check_percent:
1891
1892 if (ma)
1893 {
1894 m = ma;
1895 n = ++na;
1896 count = acount;
1897 }
1898 else
1899 return false;
1900 }
1901 }
1902 }
1903 }
1904
1905 // Return the type of an open file
1906 //
1907 // Some file types on some platforms seem seekable but in fact are not.
1908 // The main use of this function is to allow such cases to be detected
1909 // (IsSeekable() is implemented as wxGetFileKind() == wxFILE_KIND_DISK).
1910 //
1911 // This is important for the archive streams, which benefit greatly from
1912 // being able to seek on a stream, but which will produce corrupt archives
1913 // if they unknowingly seek on a non-seekable stream.
1914 //
1915 // wxFILE_KIND_DISK is a good catch all return value, since other values
1916 // disable features of the archive streams. Some other value must be returned
1917 // for a file type that appears seekable but isn't.
1918 //
1919 // Known examples:
1920 // * Pipes on Windows
1921 // * Files on VMS with a record format other than StreamLF
1922 //
1923 wxFileKind wxGetFileKind(int fd)
1924 {
1925 #if defined __WXMSW__ && !defined __WXWINCE__ && defined wxGetOSFHandle
1926 switch (::GetFileType(wxGetOSFHandle(fd)) & ~FILE_TYPE_REMOTE)
1927 {
1928 case FILE_TYPE_CHAR:
1929 return wxFILE_KIND_TERMINAL;
1930 case FILE_TYPE_DISK:
1931 return wxFILE_KIND_DISK;
1932 case FILE_TYPE_PIPE:
1933 return wxFILE_KIND_PIPE;
1934 }
1935
1936 return wxFILE_KIND_UNKNOWN;
1937
1938 #elif defined(__UNIX__)
1939 if (isatty(fd))
1940 return wxFILE_KIND_TERMINAL;
1941
1942 struct stat st;
1943 fstat(fd, &st);
1944
1945 if (S_ISFIFO(st.st_mode))
1946 return wxFILE_KIND_PIPE;
1947 if (!S_ISREG(st.st_mode))
1948 return wxFILE_KIND_UNKNOWN;
1949
1950 #if defined(__VMS__)
1951 if (st.st_fab_rfm != FAB$C_STMLF)
1952 return wxFILE_KIND_UNKNOWN;
1953 #endif
1954
1955 return wxFILE_KIND_DISK;
1956
1957 #else
1958 #define wxFILEKIND_STUB
1959 (void)fd;
1960 return wxFILE_KIND_DISK;
1961 #endif
1962 }
1963
1964 wxFileKind wxGetFileKind(FILE *fp)
1965 {
1966 // Note: The watcom rtl dll doesn't have fileno (the static lib does).
1967 // Should be fixed in version 1.4.
1968 #if defined(wxFILEKIND_STUB) || \
1969 (defined(__WATCOMC__) && __WATCOMC__ <= 1230 && defined(__SW_BR))
1970 (void)fp;
1971 return wxFILE_KIND_DISK;
1972 #else
1973 return fp ? wxGetFileKind(fileno(fp)) : wxFILE_KIND_UNKNOWN;
1974 #endif
1975 }
1976
1977 #ifdef __VISUALC__
1978 #pragma warning(default:4706) // assignment within conditional expression
1979 #endif // VC++