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