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