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