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