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