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