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