]> git.saurik.com Git - wxWidgets.git/blob - src/common/filefn.cpp
fixed slider value rounding once again
[wxWidgets.git] / src / common / filefn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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 license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "filefn.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26 #include "wx/defs.h"
27
28 #ifdef __BORLANDC__
29 #pragma hdrstop
30 #endif
31
32 #include "wx/utils.h"
33 #include "wx/intl.h"
34 #include "wx/file.h"
35 #include "wx/filename.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 !defined(__WATCOMC__)
47 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
48 #include <errno.h>
49 #endif
50 #endif
51
52 #include <time.h>
53
54 #ifndef __MWERKS__
55 #include <sys/types.h>
56 #include <sys/stat.h>
57 #else
58 #include <stat.h>
59 #include <unistd.h>
60 #include <unix.h>
61 #endif
62
63 #ifdef __UNIX__
64 #include <unistd.h>
65 #include <dirent.h>
66 #endif
67
68 #ifdef __WXPM__
69 #include <process.h>
70 #include "wx/os2/private.h"
71 #endif
72 #ifdef __WINDOWS__
73 #if !defined( __GNUWIN32__ ) && !defined( __MWERKS__ ) && !defined(__SALFORDC__)
74 #include <direct.h>
75 #include <dos.h>
76 #include <io.h>
77 #endif // __WINDOWS__
78 #endif // native Win compiler
79
80 #ifdef __GNUWIN32__
81 #include <wchar.h>
82 #ifndef __TWIN32__
83 #include <sys/unistd.h>
84 #endif
85 #endif
86
87 #ifdef __BORLANDC__ // Please someone tell me which version of Borland needs
88 // this (3.1 I believe) and how to test for it.
89 // If this works for Borland 4.0 as well, then no worries.
90 #include <dir.h>
91 #endif
92
93 #ifdef __SALFORDC__
94 #include <dir.h>
95 #include <unix.h>
96 #endif
97
98 #include "wx/setup.h"
99 #include "wx/log.h"
100
101 // No, Cygwin doesn't appear to have fnmatch.h after all.
102 #if defined(HAVE_FNMATCH_H)
103 #include "fnmatch.h"
104 #endif
105
106 #ifdef __WINDOWS__
107 #include <windows.h>
108 #endif
109
110 // ----------------------------------------------------------------------------
111 // constants
112 // ----------------------------------------------------------------------------
113
114 #define _MAXPATHLEN 500
115
116 extern wxChar *wxBuffer;
117
118 #if defined(__WXMAC__) && !defined(__UNIX__)
119 #include "morefile.h"
120 #include "moreextr.h"
121 #include "fullpath.h"
122 #include "fspcompa.h"
123 #endif
124
125 IMPLEMENT_DYNAMIC_CLASS(wxPathList, wxStringList)
126
127 // ----------------------------------------------------------------------------
128 // private globals
129 // ----------------------------------------------------------------------------
130
131 static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
132
133 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
134 //
135 // VisualAge C++ V4.0 cannot have any external linkage const decs
136 // in headers included by more than one primary source
137 //
138 const off_t wxInvalidOffset = (off_t)-1;
139 #endif
140
141 // ----------------------------------------------------------------------------
142 // macros
143 // ----------------------------------------------------------------------------
144
145 // we need to translate Mac filenames before passing them to OS functions
146 #define OS_FILENAME(s) (s.fn_str())
147
148 // ============================================================================
149 // implementation
150 // ============================================================================
151
152 void wxPathList::Add (const wxString& path)
153 {
154 wxStringList::Add (WXSTRINGCAST path);
155 }
156
157 // Add paths e.g. from the PATH environment variable
158 void wxPathList::AddEnvList (const wxString& envVariable)
159 {
160 static const wxChar PATH_TOKS[] =
161 #ifdef __WINDOWS__
162 wxT(" ;"); // Don't seperate with colon in DOS (used for drive)
163 #else
164 wxT(" :;");
165 #endif
166
167 wxChar *val = wxGetenv (WXSTRINGCAST envVariable);
168 if (val && *val)
169 {
170 wxChar *s = copystring (val);
171 wxChar *save_ptr, *token = wxStrtok (s, PATH_TOKS, &save_ptr);
172
173 if (token)
174 {
175 Add (copystring (token));
176 while (token)
177 {
178 if ((token = wxStrtok ((wxChar *) NULL, PATH_TOKS, &save_ptr)) != NULL)
179 Add (wxString(token));
180 }
181 }
182
183 // suppress warning about unused variable save_ptr when wxStrtok() is a
184 // macro which throws away its third argument
185 save_ptr = token;
186
187 delete [] s;
188 }
189 }
190
191 // Given a full filename (with path), ensure that that file can
192 // be accessed again USING FILENAME ONLY by adding the path
193 // to the list if not already there.
194 void wxPathList::EnsureFileAccessible (const wxString& path)
195 {
196 wxString path_only(wxPathOnly(path));
197 if ( !path_only.IsEmpty() )
198 {
199 if ( !Member(path_only) )
200 Add(path_only);
201 }
202 }
203
204 bool wxPathList::Member (const wxString& path)
205 {
206 for (wxNode * node = First (); node != NULL; node = node->Next ())
207 {
208 wxString path2((wxChar *) node->Data ());
209 if (
210 #if defined(__WINDOWS__) || defined(__VMS__) || defined (__WXMAC__)
211 // Case INDEPENDENT
212 path.CompareTo (path2, wxString::ignoreCase) == 0
213 #else
214 // Case sensitive File System
215 path.CompareTo (path2) == 0
216 #endif
217 )
218 return TRUE;
219 }
220 return FALSE;
221 }
222
223 wxString wxPathList::FindValidPath (const wxString& file)
224 {
225 if (wxFileExists (wxExpandPath(wxFileFunctionsBuffer, file)))
226 return wxString(wxFileFunctionsBuffer);
227
228 wxChar buf[_MAXPATHLEN];
229 wxStrcpy(buf, wxFileFunctionsBuffer);
230
231 wxChar *filename = (wxChar*) NULL; /* shut up buggy egcs warning */
232 filename = IsAbsolutePath (buf) ? wxFileNameFromPath (buf) : (wxChar *)buf;
233
234 for (wxNode * node = First (); node; node = node->Next ())
235 {
236 wxChar *path = (wxChar *) node->Data ();
237 wxStrcpy (wxFileFunctionsBuffer, path);
238 wxChar ch = wxFileFunctionsBuffer[wxStrlen(wxFileFunctionsBuffer)-1];
239 if (ch != wxT('\\') && ch != wxT('/'))
240 wxStrcat (wxFileFunctionsBuffer, wxT("/"));
241 wxStrcat (wxFileFunctionsBuffer, filename);
242 #ifdef __WINDOWS__
243 Unix2DosFilename (wxFileFunctionsBuffer);
244 #endif
245 if (wxFileExists (wxFileFunctionsBuffer))
246 {
247 return wxString(wxFileFunctionsBuffer); // Found!
248 }
249 } // for()
250
251 return wxString(wxT("")); // Not found
252 }
253
254 wxString wxPathList::FindAbsoluteValidPath (const wxString& file)
255 {
256 wxString f = FindValidPath(file);
257 if ( wxIsAbsolutePath(f) )
258 return f;
259
260 wxString buf;
261 wxGetWorkingDirectory(buf.GetWriteBuf(_MAXPATHLEN), _MAXPATHLEN - 1);
262 buf.UngetWriteBuf();
263 if ( !wxEndsWithPathSeparator(buf) )
264 {
265 buf += wxFILE_SEP_PATH;
266 }
267 buf += f;
268
269 return buf;
270 }
271
272 bool
273 wxFileExists (const wxString& filename)
274 {
275 #ifdef __GNUWIN32__ // (fix a B20 bug)
276 return GetFileAttributes(filename) != 0xFFFFFFFF;
277 #else
278 wxStructStat stbuf;
279 if ( !filename.empty() && wxStat (OS_FILENAME(filename), &stbuf) == 0 )
280 return TRUE;
281
282 return FALSE;
283 #endif
284 }
285
286 bool
287 wxIsAbsolutePath (const wxString& filename)
288 {
289 #ifdef __WXMAC__
290 if (filename != wxT(""))
291 {
292 if( filename.Find(':') != wxNOT_FOUND && filename[0] != ':' )
293 return TRUE ;
294 }
295 return FALSE ;
296 #else
297 if (filename != wxT(""))
298 {
299 if (filename[0] == wxT('/')
300 #ifdef __VMS__
301 || (filename[0] == wxT('[') && filename[1] != wxT('.'))
302 #endif
303 #ifdef __WINDOWS__
304 /* MSDOS */
305 || filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':'))
306 #endif
307 )
308 return TRUE;
309 }
310 return FALSE;
311 #endif
312 }
313
314 /*
315 * Strip off any extension (dot something) from end of file,
316 * IF one exists. Inserts zero into buffer.
317 *
318 */
319
320 void wxStripExtension(wxChar *buffer)
321 {
322 int len = wxStrlen(buffer);
323 int i = len-1;
324 while (i > 0)
325 {
326 if (buffer[i] == wxT('.'))
327 {
328 buffer[i] = 0;
329 break;
330 }
331 i --;
332 }
333 }
334
335 void wxStripExtension(wxString& buffer)
336 {
337 size_t len = buffer.Length();
338 size_t i = len-1;
339 while (i > 0)
340 {
341 if (buffer.GetChar(i) == wxT('.'))
342 {
343 buffer = buffer.Left(i);
344 break;
345 }
346 i --;
347 }
348 }
349
350 // Destructive removal of /./ and /../ stuff
351 wxChar *wxRealPath (wxChar *path)
352 {
353 #ifdef __WXMSW__
354 static const wxChar SEP = wxT('\\');
355 Unix2DosFilename(path);
356 #else
357 static const wxChar SEP = wxT('/');
358 #endif
359 if (path[0] && path[1]) {
360 /* MATTHEW: special case "/./x" */
361 wxChar *p;
362 if (path[2] == SEP && path[1] == wxT('.'))
363 p = &path[0];
364 else
365 p = &path[2];
366 for (; *p; p++)
367 {
368 if (*p == SEP)
369 {
370 if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
371 {
372 wxChar *q;
373 for (q = p - 1; q >= path && *q != SEP; q--);
374 if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
375 && (q - 1 <= path || q[-1] != SEP))
376 {
377 wxStrcpy (q, p + 3);
378 if (path[0] == wxT('\0'))
379 {
380 path[0] = SEP;
381 path[1] = wxT('\0');
382 }
383 #ifdef __WXMSW__
384 /* Check that path[2] is NULL! */
385 else if (path[1] == wxT(':') && !path[2])
386 {
387 path[2] = SEP;
388 path[3] = wxT('\0');
389 }
390 #endif
391 p = q - 1;
392 }
393 }
394 else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
395 wxStrcpy (p, p + 2);
396 }
397 }
398 }
399 return path;
400 }
401
402 // Must be destroyed
403 wxChar *wxCopyAbsolutePath(const wxString& filename)
404 {
405 if (filename == wxT(""))
406 return (wxChar *) NULL;
407
408 if (! IsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename))) {
409 wxChar buf[_MAXPATHLEN];
410 buf[0] = wxT('\0');
411 wxGetWorkingDirectory(buf, WXSIZEOF(buf));
412 wxChar ch = buf[wxStrlen(buf) - 1];
413 #ifdef __WXMSW__
414 if (ch != wxT('\\') && ch != wxT('/'))
415 wxStrcat(buf, wxT("\\"));
416 #else
417 if (ch != wxT('/'))
418 wxStrcat(buf, wxT("/"));
419 #endif
420 wxStrcat(buf, wxFileFunctionsBuffer);
421 return copystring( wxRealPath(buf) );
422 }
423 return copystring( wxFileFunctionsBuffer );
424 }
425
426 /*-
427 Handles:
428 ~/ => home dir
429 ~user/ => user's home dir
430 If the environment variable a = "foo" and b = "bar" then:
431 Unix:
432 $a => foo
433 $a$b => foobar
434 $a.c => foo.c
435 xxx$a => xxxfoo
436 ${a}! => foo!
437 $(b)! => bar!
438 \$a => \$a
439 MSDOS:
440 $a ==> $a
441 $(a) ==> foo
442 $(a)$b ==> foo$b
443 $(a)$(b)==> foobar
444 test.$$ ==> test.$$
445 */
446
447 /* input name in name, pathname output to buf. */
448
449 wxChar *wxExpandPath(wxChar *buf, const wxChar *name)
450 {
451 register wxChar *d, *s, *nm;
452 wxChar lnm[_MAXPATHLEN];
453 int q;
454
455 // Some compilers don't like this line.
456 // const wxChar trimchars[] = wxT("\n \t");
457
458 wxChar trimchars[4];
459 trimchars[0] = wxT('\n');
460 trimchars[1] = wxT(' ');
461 trimchars[2] = wxT('\t');
462 trimchars[3] = 0;
463
464 #ifdef __WXMSW__
465 const wxChar SEP = wxT('\\');
466 #else
467 const wxChar SEP = wxT('/');
468 #endif
469 buf[0] = wxT('\0');
470 if (name == NULL || *name == wxT('\0'))
471 return buf;
472 nm = copystring(name); // Make a scratch copy
473 wxChar *nm_tmp = nm;
474
475 /* Skip leading whitespace and cr */
476 while (wxStrchr((wxChar *)trimchars, *nm) != NULL)
477 nm++;
478 /* And strip off trailing whitespace and cr */
479 s = nm + (q = wxStrlen(nm)) - 1;
480 while (q-- && wxStrchr((wxChar *)trimchars, *s) != NULL)
481 *s = wxT('\0');
482
483 s = nm;
484 d = lnm;
485 #ifdef __WXMSW__
486 q = FALSE;
487 #else
488 q = nm[0] == wxT('\\') && nm[1] == wxT('~');
489 #endif
490
491 /* Expand inline environment variables */
492 #ifdef __VISAGECPP__
493 while (*d)
494 {
495 *d++ = *s;
496 if(*s == wxT('\\'))
497 {
498 *(d - 1) = *++s;
499 if (*d)
500 {
501 s++;
502 continue;
503 }
504 else
505 break;
506 }
507 else
508 #else
509 while ((*d++ = *s) != 0) {
510 # ifndef __WXMSW__
511 if (*s == wxT('\\')) {
512 if ((*(d - 1) = *++s)) {
513 s++;
514 continue;
515 } else
516 break;
517 } else
518 # endif
519 #endif
520 #ifdef __WXMSW__
521 if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
522 #else
523 if (*s++ == wxT('$'))
524 #endif
525 {
526 register wxChar *start = d;
527 register int braces = (*s == wxT('{') || *s == wxT('('));
528 register wxChar *value;
529 while ((*d++ = *s) != 0)
530 if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
531 break;
532 else
533 s++;
534 *--d = 0;
535 value = wxGetenv(braces ? start + 1 : start);
536 if (value) {
537 for ((d = start - 1); (*d++ = *value++) != 0;);
538 d--;
539 if (braces && *s)
540 s++;
541 }
542 }
543 }
544
545 /* Expand ~ and ~user */
546 nm = lnm;
547 s = wxT("");
548 if (nm[0] == wxT('~') && !q)
549 {
550 /* prefix ~ */
551 if (nm[1] == SEP || nm[1] == 0)
552 { /* ~/filename */
553 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
554 if ((s = WXSTRINGCAST wxGetUserHome(wxT(""))) != NULL) {
555 if (*++nm)
556 nm++;
557 }
558 } else
559 { /* ~user/filename */
560 register wxChar *nnm;
561 register wxChar *home;
562 for (s = nm; *s && *s != SEP; s++);
563 int was_sep; /* MATTHEW: Was there a separator, or NULL? */
564 was_sep = (*s == SEP);
565 nnm = *s ? s + 1 : s;
566 *s = 0;
567 // FIXME: wxGetUserHome could return temporary storage in Unicode mode
568 if ((home = WXSTRINGCAST wxGetUserHome(wxString(nm + 1))) == NULL) {
569 if (was_sep) /* replace only if it was there: */
570 *s = SEP;
571 s = wxT("");
572 } else {
573 nm = nnm;
574 s = home;
575 }
576 }
577 }
578
579 d = buf;
580 if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
581 /* Copy home dir */
582 while (wxT('\0') != (*d++ = *s++))
583 /* loop */;
584 // Handle root home
585 if (d - 1 > buf && *(d - 2) != SEP)
586 *(d - 1) = SEP;
587 }
588 s = nm;
589 while ((*d++ = *s++) != 0);
590 delete[] nm_tmp; // clean up alloc
591 /* Now clean up the buffer */
592 return wxRealPath(buf);
593 }
594
595 /* Contract Paths to be build upon an environment variable
596 component:
597
598 example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
599
600 The call wxExpandPath can convert these back!
601 */
602 wxChar *
603 wxContractPath (const wxString& filename, const wxString& envname, const wxString& user)
604 {
605 static wxChar dest[_MAXPATHLEN];
606
607 if (filename == wxT(""))
608 return (wxChar *) NULL;
609
610 wxStrcpy (dest, WXSTRINGCAST filename);
611 #ifdef __WXMSW__
612 Unix2DosFilename(dest);
613 #endif
614
615 // Handle environment
616 const wxChar *val = (const wxChar *) NULL;
617 wxChar *tcp = (wxChar *) NULL;
618 if (envname != WXSTRINGCAST NULL && (val = wxGetenv (WXSTRINGCAST envname)) != NULL &&
619 (tcp = wxStrstr (dest, val)) != NULL)
620 {
621 wxStrcpy (wxFileFunctionsBuffer, tcp + wxStrlen (val));
622 *tcp++ = wxT('$');
623 *tcp++ = wxT('{');
624 wxStrcpy (tcp, WXSTRINGCAST envname);
625 wxStrcat (tcp, wxT("}"));
626 wxStrcat (tcp, wxFileFunctionsBuffer);
627 }
628
629 // Handle User's home (ignore root homes!)
630 size_t len = 0;
631 if ((val = wxGetUserHome (user)) != NULL &&
632 (len = wxStrlen(val)) > 2 &&
633 wxStrncmp(dest, val, len) == 0)
634 {
635 wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
636 if (user != wxT(""))
637 wxStrcat(wxFileFunctionsBuffer, (const wxChar*) user);
638 #ifdef __WXMSW__
639 // strcat(wxFileFunctionsBuffer, "\\");
640 #else
641 // strcat(wxFileFunctionsBuffer, "/");
642 #endif
643 wxStrcat(wxFileFunctionsBuffer, dest + len);
644 wxStrcpy (dest, wxFileFunctionsBuffer);
645 }
646
647 return dest;
648 }
649
650 // Return just the filename, not the path
651 // (basename)
652 wxChar *wxFileNameFromPath (wxChar *path)
653 {
654 if (path)
655 {
656 register wxChar *tcp;
657
658 tcp = path + wxStrlen (path);
659 while (--tcp >= path)
660 {
661 #ifdef __WXMAC__
662 if (*tcp == wxT(':') )
663 #else
664 if (*tcp == wxT('/') || *tcp == wxT('\\')
665 #ifdef __VMS__
666 || *tcp == wxT(':') || *tcp == wxT(']'))
667 #else
668 )
669 #endif
670 #endif
671 return tcp + 1;
672 } /* while */
673 #if defined(__WXMSW__) || defined(__WXPM__)
674 if (wxIsalpha (*path) && *(path + 1) == wxT(':'))
675 return path + 2;
676 #endif
677 }
678 return path;
679 }
680
681 wxString wxFileNameFromPath (const wxString& path1)
682 {
683 if (path1 != wxT(""))
684 {
685
686 wxChar *path = WXSTRINGCAST path1 ;
687 register wxChar *tcp;
688
689 tcp = path + wxStrlen (path);
690 while (--tcp >= path)
691 {
692 #ifdef __WXMAC__
693 if (*tcp == wxT(':') )
694 #else
695 if (*tcp == wxT('/') || *tcp == wxT('\\')
696 #ifdef __VMS__
697 || *tcp == wxT(':') || *tcp == wxT(']'))
698 #else
699 )
700 #endif
701 #endif
702 return wxString(tcp + 1);
703 } /* while */
704 #if defined(__WXMSW__) || defined(__WXPM__)
705 if (wxIsalpha (*path) && *(path + 1) == wxT(':'))
706 return wxString(path + 2);
707 #endif
708 }
709 // Yes, this should return the path, not an empty string, otherwise
710 // we get "thing.txt" -> "".
711 return path1;
712 }
713
714 // Return just the directory, or NULL if no directory
715 wxChar *
716 wxPathOnly (wxChar *path)
717 {
718 if (path && *path)
719 {
720 static wxChar buf[_MAXPATHLEN];
721
722 // Local copy
723 wxStrcpy (buf, path);
724
725 int l = wxStrlen(path);
726 bool done = FALSE;
727
728 int i = l - 1;
729
730 // Search backward for a backward or forward slash
731 while (!done && i > -1)
732 {
733 // ] is for VMS
734 #ifdef __WXMAC__
735 if (path[i] == wxT(':') )
736 #else
737 if (path[i] == wxT('/') || path[i] == wxT('\\') || path[i] == wxT(']'))
738 #endif
739 {
740 done = TRUE;
741 #ifdef __VMS__
742 if ( path[i] == wxT(']') )
743 buf[i+1] = 0;
744 else
745 #endif
746 buf[i] = 0;
747
748 return buf;
749 }
750 else i --;
751 }
752
753 #if defined(__WXMSW__) || defined(__WXPM__)
754 // Try Drive specifier
755 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
756 {
757 // A:junk --> A:. (since A:.\junk Not A:\junk)
758 buf[2] = wxT('.');
759 buf[3] = wxT('\0');
760 return buf;
761 }
762 #endif
763 }
764
765 return (wxChar *) NULL;
766 }
767
768 // Return just the directory, or NULL if no directory
769 wxString wxPathOnly (const wxString& path)
770 {
771 if (path != wxT(""))
772 {
773 wxChar buf[_MAXPATHLEN];
774
775 // Local copy
776 wxStrcpy (buf, WXSTRINGCAST path);
777
778 int l = path.Length();
779 bool done = FALSE;
780
781 int i = l - 1;
782
783 // Search backward for a backward or forward slash
784 while (!done && i > -1)
785 {
786 // ] is for VMS
787 #ifdef __WXMAC__
788 if (path[i] == wxT(':') )
789 #else
790 if (path[i] == wxT('/') || path[i] == wxT('\\') || path[i] == wxT(']'))
791 #endif
792 {
793 done = TRUE;
794 #ifdef __VMS__
795 if ( path[i] == wxT(']') )
796 buf[i+1] = 0;
797 else
798 #endif
799 buf[i] = 0;
800
801 return wxString(buf);
802 }
803 else i --;
804 }
805
806 #if defined(__WXMSW__) || defined(__WXPM__)
807 // Try Drive specifier
808 if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
809 {
810 // A:junk --> A:. (since A:.\junk Not A:\junk)
811 buf[2] = wxT('.');
812 buf[3] = wxT('\0');
813 return wxString(buf);
814 }
815 #endif
816 }
817
818 return wxString(wxT(""));
819 }
820
821 // Utility for converting delimiters in DOS filenames to UNIX style
822 // and back again - or we get nasty problems with delimiters.
823 // Also, convert to lower case, since case is significant in UNIX.
824
825 #if defined(__WXMAC__) && !defined(__UNIX__)
826 wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
827 {
828 Handle myPath ;
829 short length ;
830
831 FSpGetFullPath( spec , &length , &myPath ) ;
832 ::SetHandleSize( myPath , length + 1 ) ;
833 ::HLock( myPath ) ;
834 (*myPath)[length] = 0 ;
835 if ( length > 0 && (*myPath)[length-1] ==':' )
836 (*myPath)[length-1] = 0 ;
837
838 wxString result( (char*) *myPath ) ;
839 ::HUnlock( myPath ) ;
840 ::DisposeHandle( myPath ) ;
841 return result ;
842 }
843
844 void wxMacFilename2FSSpec( const char *path , FSSpec *spec )
845 {
846 FSpLocationFromFullPath( strlen(path ) , path , spec ) ;
847 }
848
849 /*
850 static char sMacFileNameConversion[ 1000 ] ;
851
852 wxString wxMac2UnixFilename (const char *str)
853 {
854 char *s = sMacFileNameConversion ;
855 strcpy( s , str ) ;
856 if (s)
857 {
858 memmove( s+1 , s ,strlen( s ) + 1) ;
859 if ( *s == ':' )
860 *s = '.' ;
861 else
862 *s = '/' ;
863
864 while (*s)
865 {
866 if (*s == ':')
867 *s = '/';
868 else
869 *s = wxTolower (*s); // Case INDEPENDENT
870 s++;
871 }
872 }
873 return wxString (sMacFileNameConversion) ;
874 }
875
876 wxString wxUnix2MacFilename (const char *str)
877 {
878 char *s = sMacFileNameConversion ;
879 strcpy( s , str ) ;
880 if (s)
881 {
882 if ( *s == '.' )
883 {
884 // relative path , since it goes on with slash which is translated to a :
885 memmove( s , s+1 ,strlen( s ) ) ;
886 }
887 else if ( *s == '/' )
888 {
889 // absolute path -> on mac just start with the drive name
890 memmove( s , s+1 ,strlen( s ) ) ;
891 }
892 else
893 {
894 wxASSERT_MSG( 1 , "unkown path beginning" ) ;
895 }
896 while (*s)
897 {
898 if (*s == '/' || *s == '\\')
899 {
900 // convert any back-directory situations
901 if ( *(s+1) == '.' && *(s+2) == '.' && ( (*(s+3) == '/' || *(s+3) == '\\') ) )
902 {
903 *s = ':';
904 memmove( s+1 , s+3 ,strlen( s+3 ) + 1 ) ;
905 }
906 else
907 *s = ':';
908 }
909
910 s++ ;
911 }
912 }
913 return wxString (sMacFileNameConversion) ;
914 }
915
916 wxString wxMacFSSpec2UnixFilename( const FSSpec *spec )
917 {
918 return wxMac2UnixFilename( wxMacFSSpec2MacFilename( spec) ) ;
919 }
920
921 void wxMacFilename2FSSpec( const char *path , FSSpec *spec )
922 {
923 FSpLocationFromFullPath( strlen(path ) , path , spec ) ;
924 }
925
926 void wxUnixFilename2FSSpec( const char *path , FSSpec *spec )
927 {
928 wxString var = wxUnix2MacFilename( path ) ;
929 wxMacFilename2FSSpec( var , spec ) ;
930 }
931 */
932 #endif
933 void
934 wxDos2UnixFilename (char *s)
935 {
936 if (s)
937 while (*s)
938 {
939 if (*s == '\\')
940 *s = '/';
941 #ifdef __WXMSW__
942 else
943 *s = wxTolower (*s); // Case INDEPENDENT
944 #endif
945 s++;
946 }
947 }
948
949 void
950 #if defined(__WXMSW__) || defined(__WXPM__)
951 wxUnix2DosFilename (wxChar *s)
952 #else
953 wxUnix2DosFilename (wxChar *WXUNUSED(s) )
954 #endif
955 {
956 // Yes, I really mean this to happen under DOS only! JACS
957 #if defined(__WXMSW__) || defined(__WXPM__)
958 if (s)
959 while (*s)
960 {
961 if (*s == wxT('/'))
962 *s = wxT('\\');
963 s++;
964 }
965 #endif
966 }
967
968 // Concatenate two files to form third
969 bool
970 wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
971 {
972 wxString outfile;
973 if ( !wxGetTempFileName("cat", outfile) )
974 return FALSE;
975
976 FILE *fp1 = (FILE *) NULL;
977 FILE *fp2 = (FILE *) NULL;
978 FILE *fp3 = (FILE *) NULL;
979 // Open the inputs and outputs
980 if ((fp1 = wxFopen (OS_FILENAME( file1 ), wxT("rb"))) == NULL ||
981 (fp2 = wxFopen (OS_FILENAME( file2 ), wxT("rb"))) == NULL ||
982 (fp3 = wxFopen (OS_FILENAME( outfile ), wxT("wb"))) == NULL)
983 {
984 if (fp1)
985 fclose (fp1);
986 if (fp2)
987 fclose (fp2);
988 if (fp3)
989 fclose (fp3);
990 return FALSE;
991 }
992
993 int ch;
994 while ((ch = getc (fp1)) != EOF)
995 (void) putc (ch, fp3);
996 fclose (fp1);
997
998 while ((ch = getc (fp2)) != EOF)
999 (void) putc (ch, fp3);
1000 fclose (fp2);
1001
1002 fclose (fp3);
1003 bool result = wxRenameFile(outfile, file3);
1004 return result;
1005 }
1006
1007 // Copy files
1008 bool
1009 wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
1010 {
1011 #if defined(__WIN32__)
1012 // CopyFile() copies file attributes and modification time too, so use it
1013 // instead of our code if available
1014 //
1015 // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
1016 return ::CopyFile(file1, file2, !overwrite) != 0;
1017 #else // !Win32
1018 wxStructStat fbuf;
1019
1020 // get permissions of file1
1021 if ( wxStat(OS_FILENAME(file1), &fbuf) != 0 )
1022 {
1023 // the file probably doesn't exist or we haven't the rights to read
1024 // from it anyhow
1025 wxLogSysError(_("Impossible to get permissions for file '%s'"),
1026 file1.c_str());
1027 return FALSE;
1028 }
1029
1030 // open file1 for reading
1031 wxFile fileIn(file1, wxFile::read);
1032 if ( !fileIn.IsOpened() )
1033 return FALSE;
1034
1035 // remove file2, if it exists. This is needed for creating
1036 // file2 with the correct permissions in the next step
1037 if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
1038 {
1039 wxLogSysError(_("Impossible to overwrite the file '%s'"),
1040 file2.c_str());
1041 return FALSE;
1042 }
1043
1044 #ifdef __UNIX__
1045 // reset the umask as we want to create the file with exactly the same
1046 // permissions as the original one
1047 mode_t oldUmask = umask( 0 );
1048 #endif // __UNIX__
1049
1050 // create file2 with the same permissions than file1 and open it for
1051 // writing
1052 wxFile fileOut;
1053 if ( !fileOut.Create(file2, overwrite, fbuf.st_mode & 0777) )
1054 return FALSE;
1055
1056 #ifdef __UNIX__
1057 /// restore the old umask
1058 umask(oldUmask);
1059 #endif // __UNIX__
1060
1061 // copy contents of file1 to file2
1062 char buf[4096];
1063 size_t count;
1064 for ( ;; )
1065 {
1066 count = fileIn.Read(buf, WXSIZEOF(buf));
1067 if ( fileIn.Error() )
1068 return FALSE;
1069
1070 // end of file?
1071 if ( !count )
1072 break;
1073
1074 if ( fileOut.Write(buf, count) < count )
1075 return FALSE;
1076 }
1077
1078 // we can expect fileIn to be closed successfully, but we should ensure
1079 // that fileOut was closed as some write errors (disk full) might not be
1080 // detected before doing this
1081 if ( !fileIn.Close() || !fileOut.Close() )
1082 return FALSE;
1083
1084 #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
1085 // no chmod in VA. Should be some permission API for HPFS386 partitions
1086 // however
1087 if ( chmod(OS_FILENAME(file2), fbuf.st_mode) != 0 )
1088 {
1089 wxLogSysError(_("Impossible to set permissions for the file '%s'"),
1090 file2.c_str());
1091 return FALSE;
1092 }
1093 #endif // OS/2 || Mac
1094
1095 return TRUE;
1096 #endif // __WXMSW__ && __WIN32__
1097 }
1098
1099 bool
1100 wxRenameFile (const wxString& file1, const wxString& file2)
1101 {
1102 // Normal system call
1103 if ( wxRename (file1, file2) == 0 )
1104 return TRUE;
1105
1106 // Try to copy
1107 if (wxCopyFile(file1, file2)) {
1108 wxRemoveFile(file1);
1109 return TRUE;
1110 }
1111 // Give up
1112 return FALSE;
1113 }
1114
1115 bool wxRemoveFile(const wxString& file)
1116 {
1117 #if defined(__VISUALC__) \
1118 || defined(__BORLANDC__) \
1119 || defined(__WATCOMC__) \
1120 || defined(__GNUWIN32__)
1121 int res = wxRemove(file);
1122 #else
1123 int res = unlink(OS_FILENAME(file));
1124 #endif
1125
1126 return res == 0;
1127 }
1128
1129 bool wxMkdir(const wxString& dir, int perm)
1130 {
1131 #if defined(__WXMAC__) && !defined(__UNIX__)
1132 return (mkdir( dir , 0 ) == 0);
1133 #else // !Mac
1134 const wxChar *dirname = dir.c_str();
1135
1136 // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
1137 // for the GNU compiler
1138 #if (!(defined(__WXMSW__) || defined(__WXPM__))) || (defined(__GNUWIN32__) && !defined(__MINGW32__)) || defined(__WXWINE__)
1139 if ( mkdir(wxFNCONV(dirname), perm) != 0 )
1140 #elif defined(__WXPM__)
1141 if (::DosCreateDir((PSZ)dirname, NULL) != 0) // enhance for EAB's??
1142 #else // !MSW and !OS/2 VAC++
1143 (void)perm;
1144 if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
1145 #endif // !MSW/MSW
1146 {
1147 wxLogSysError(_("Directory '%s' couldn't be created"), dirname);
1148
1149 return FALSE;
1150 }
1151
1152 return TRUE;
1153 #endif // Mac/!Mac
1154 }
1155
1156 bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
1157 {
1158 #ifdef __VMS__
1159 return FALSE; //to be changed since rmdir exists in VMS7.x
1160 #elif defined(__WXPM__)
1161 return (::DosDeleteDir((PSZ)dir.c_str()) == 0);
1162 #else
1163
1164 #ifdef __SALFORDC__
1165 return FALSE; // What to do?
1166 #else
1167 return (wxRmDir(OS_FILENAME(dir)) == 0);
1168 #endif
1169
1170 #endif
1171 }
1172
1173 // does the path exists? (may have or not '/' or '\\' at the end)
1174 bool wxPathExists(const wxChar *pszPathName)
1175 {
1176 wxString strPath(pszPathName);
1177 #ifdef __WINDOWS__
1178 // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
1179 // so remove all trailing backslashes from the path - but don't do this for
1180 // the pathes "d:\" (which are different from "d:") nor for just "\"
1181 while ( wxEndsWithPathSeparator(strPath) )
1182 {
1183 size_t len = strPath.length();
1184 if ( len == 1 || strPath[len - 1] == _T(':') )
1185 break;
1186
1187 strPath.Truncate(len - 1);
1188 }
1189 #endif // __WINDOWS__
1190
1191 wxStructStat st;
1192 #ifndef __VISAGECPP__
1193 return wxStat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 &&
1194 ((st.st_mode & S_IFMT) == S_IFDIR);
1195 #else
1196 // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
1197 return wxStat(wxFNSTRINGCAST strPath.fn_str(), &st) == 0 &&
1198 (st.st_mode == S_IFDIR);
1199 #endif
1200
1201 }
1202
1203 // Get a temporary filename, opening and closing the file.
1204 wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
1205 {
1206 #ifdef __WINDOWS__
1207
1208 #ifndef __WIN32__
1209 wxChar tmp[144];
1210 ::GetTempFileName(0, WXSTRINGCAST prefix, 0, tmp);
1211 #else
1212 wxChar tmp[MAX_PATH];
1213 wxChar tmpPath[MAX_PATH];
1214 ::GetTempPath(MAX_PATH, tmpPath);
1215 ::GetTempFileName(tmpPath, WXSTRINGCAST prefix, 0, tmp);
1216 #endif
1217 if (buf) wxStrcpy(buf, tmp);
1218 else buf = copystring(tmp);
1219 return buf;
1220
1221 #else
1222 static short last_temp = 0; // cache last to speed things a bit
1223 // At most 1000 temp files to a process! We use a ring count.
1224 wxChar tmp[100]; // FIXME static buffer
1225
1226 for (short suffix = last_temp + 1; suffix != last_temp; ++suffix %= 1000)
1227 {
1228 wxSprintf (tmp, wxT("/tmp/%s%d.%03x"), WXSTRINGCAST prefix, (int) getpid (), (int) suffix);
1229 if (!wxFileExists( tmp ))
1230 {
1231 // Touch the file to create it (reserve name)
1232 FILE *fd = fopen (wxFNCONV(tmp), "w");
1233 if (fd)
1234 fclose (fd);
1235 last_temp = suffix;
1236 if (buf)
1237 wxStrcpy( buf, tmp);
1238 else
1239 buf = copystring( tmp );
1240 return buf;
1241 }
1242 }
1243 wxLogError( _("wxWindows: error finding temporary file name.\n") );
1244 if (buf) buf[0] = 0;
1245 return (wxChar *) NULL;
1246 #endif
1247 }
1248
1249 bool wxGetTempFileName(const wxString& prefix, wxString& buf)
1250 {
1251 wxChar buf2[512];
1252 if (wxGetTempFileName(prefix, buf2) != (wxChar*) NULL)
1253 {
1254 buf = buf2;
1255 return TRUE;
1256 }
1257 else
1258 return FALSE;
1259 }
1260
1261 // Get first file name matching given wild card.
1262
1263 #ifdef __UNIX__
1264
1265 // Get first file name matching given wild card.
1266 // Flags are reserved for future use.
1267
1268 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1269 static DIR *gs_dirStream = (DIR *) NULL;
1270 static wxString gs_strFileSpec;
1271 static int gs_findFlags = 0;
1272 #endif
1273
1274 wxString wxFindFirstFile(const wxChar *spec, int flags)
1275 {
1276 wxString result;
1277 #ifdef __VMS
1278 wxChar *specvms = NULL;
1279 #endif
1280
1281 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1282 if (gs_dirStream)
1283 closedir(gs_dirStream); // edz 941103: better housekeping
1284
1285 gs_findFlags = flags;
1286
1287 gs_strFileSpec = spec;
1288
1289 // Find path only so we can concatenate
1290 // found file onto path
1291 wxString path(wxPathOnly(gs_strFileSpec));
1292
1293 // special case: path is really "/"
1294 if ( !path && gs_strFileSpec[0u] == wxT('/') )
1295 #ifdef __VMS
1296 {
1297 wxStrcpy( specvms , wxT( "[000000]" ) );
1298 gs_strFileSpec = specvms;
1299 wxString path_vms(wxPathOnly(gs_strFileSpec));
1300 path = path_vms;
1301 }
1302 #else
1303 path = wxT('/');
1304 #endif
1305 // path is empty => Local directory
1306 if ( !path )
1307 #ifdef __VMS
1308 {
1309 wxStrcpy( specvms , wxT( "[]" ) );
1310 gs_strFileSpec = specvms;
1311 wxString path_vms1(wxPathOnly(gs_strFileSpec));
1312 path = path_vms1;
1313 }
1314 #else
1315 path = wxT('.');
1316 #endif
1317
1318 gs_dirStream = opendir(path.fn_str());
1319 if ( !gs_dirStream )
1320 {
1321 wxLogSysError(_("Can not enumerate files in directory '%s'"),
1322 path.c_str());
1323 }
1324 else
1325 {
1326 result = wxFindNextFile();
1327 }
1328 #endif // !VMS6.x or earlier
1329
1330 return result;
1331 }
1332
1333 wxString wxFindNextFile()
1334 {
1335 wxString result;
1336
1337 #if !defined( __VMS__ ) || ( __VMS_VER >= 70000000 )
1338 wxCHECK_MSG( gs_dirStream, result, wxT("must call wxFindFirstFile first") );
1339
1340 // Find path only so we can concatenate
1341 // found file onto path
1342 wxString path(wxPathOnly(gs_strFileSpec));
1343 wxString name(wxFileNameFromPath(gs_strFileSpec));
1344
1345 /* MATTHEW: special case: path is really "/" */
1346 if ( !path && gs_strFileSpec[0u] == wxT('/'))
1347 path = wxT('/');
1348
1349 // Do the reading
1350 struct dirent *nextDir;
1351 for ( nextDir = readdir(gs_dirStream);
1352 nextDir != NULL;
1353 nextDir = readdir(gs_dirStream) )
1354 {
1355 if (wxMatchWild(name, nextDir->d_name, FALSE) && // RR: added FALSE to find hidden files
1356 strcmp(nextDir->d_name, ".") &&
1357 strcmp(nextDir->d_name, "..") )
1358 {
1359 result.Empty();
1360 if ( !path.IsEmpty() )
1361 {
1362 result = path;
1363 if ( path != wxT('/') )
1364 result += wxT('/');
1365 }
1366
1367 result += nextDir->d_name;
1368
1369 // Only return "." and ".." when they match
1370 bool isdir;
1371 if ( (strcmp(nextDir->d_name, ".") == 0) ||
1372 (strcmp(nextDir->d_name, "..") == 0))
1373 {
1374 if ( (gs_findFlags & wxDIR) != 0 )
1375 isdir = TRUE;
1376 else
1377 continue;
1378 }
1379 else
1380 isdir = wxDirExists(result);
1381
1382 // and only return directories when flags & wxDIR
1383 if ( !gs_findFlags ||
1384 ((gs_findFlags & wxDIR) && isdir) ||
1385 ((gs_findFlags & wxFILE) && !isdir) )
1386 {
1387 return result;
1388 }
1389 }
1390 }
1391
1392 result.Empty(); // not found
1393
1394 closedir(gs_dirStream);
1395 gs_dirStream = (DIR *) NULL;
1396 #endif // !VMS6.2 or earlier
1397
1398 return result;
1399 }
1400
1401 #elif defined(__WXMAC__)
1402
1403 struct MacDirectoryIterator
1404 {
1405 CInfoPBRec m_CPB ;
1406 wxInt16 m_index ;
1407 long m_dirId ;
1408 Str255 m_name ;
1409 } ;
1410
1411 static int g_iter_flags ;
1412
1413 static MacDirectoryIterator g_iter ;
1414
1415 wxString wxFindFirstFile(const wxChar *spec, int flags)
1416 {
1417 wxString result;
1418
1419 g_iter_flags = flags; /* MATTHEW: [5] Remember flags */
1420
1421 // Find path only so we can concatenate found file onto path
1422 wxString path(wxPathOnly(spec));
1423 if ( !path.IsEmpty() )
1424 result << path << wxT('\\');
1425
1426 FSSpec fsspec ;
1427
1428 wxMacFilename2FSSpec( result , &fsspec ) ;
1429 g_iter.m_CPB.hFileInfo.ioVRefNum = fsspec.vRefNum ;
1430 g_iter.m_CPB.hFileInfo.ioNamePtr = g_iter.m_name ;
1431 g_iter.m_index = 0 ;
1432
1433 Boolean isDir ;
1434 FSpGetDirectoryID( &fsspec , &g_iter.m_dirId , &isDir ) ;
1435 if ( !isDir )
1436 return wxEmptyString ;
1437
1438 return wxFindNextFile( ) ;
1439 }
1440
1441 wxString wxFindNextFile()
1442 {
1443 wxString result;
1444
1445 short err = noErr ;
1446
1447 while ( err == noErr )
1448 {
1449 g_iter.m_index++ ;
1450 g_iter.m_CPB.dirInfo.ioFDirIndex = g_iter.m_index;
1451 g_iter.m_CPB.dirInfo.ioDrDirID = g_iter.m_dirId; /* we need to do this every time */
1452 err = PBGetCatInfoSync((CInfoPBPtr)&g_iter.m_CPB);
1453 if ( err != noErr )
1454 break ;
1455
1456 if ( ( g_iter.m_CPB.dirInfo.ioFlAttrib & ioDirMask) != 0 && (g_iter_flags & wxDIR) ) // we have a directory
1457 break ;
1458
1459 if ( ( g_iter.m_CPB.dirInfo.ioFlAttrib & ioDirMask) == 0 && !(g_iter_flags & wxFILE ) )
1460 continue ;
1461
1462 // hit !
1463 break ;
1464 }
1465 if ( err != noErr )
1466 {
1467 return wxEmptyString ;
1468 }
1469 FSSpec spec ;
1470
1471 FSMakeFSSpecCompat(g_iter.m_CPB.hFileInfo.ioVRefNum,
1472 g_iter.m_dirId,
1473 g_iter.m_name,
1474 &spec) ;
1475
1476 return wxMacFSSpec2MacFilename( &spec ) ;
1477 }
1478
1479 #elif defined(__WXMSW__)
1480
1481 #ifdef __WIN32__
1482 static HANDLE gs_hFileStruct = INVALID_HANDLE_VALUE;
1483 static WIN32_FIND_DATA gs_findDataStruct;
1484 #else // Win16
1485 #ifdef __BORLANDC__
1486 static struct ffblk gs_findDataStruct;
1487 #else
1488 static struct _find_t gs_findDataStruct;
1489 #endif // Borland
1490 #endif // Win32/16
1491
1492 static wxString gs_strFileSpec;
1493 static int gs_findFlags = 0;
1494
1495 wxString wxFindFirstFile(const wxChar *spec, int flags)
1496 {
1497 wxString result;
1498
1499 gs_strFileSpec = spec;
1500 gs_findFlags = flags; /* MATTHEW: [5] Remember flags */
1501
1502 // Find path only so we can concatenate found file onto path
1503 wxString path(wxPathOnly(gs_strFileSpec));
1504 if ( !path.IsEmpty() )
1505 result << path << wxT('\\');
1506
1507 #ifdef __WIN32__
1508 if ( gs_hFileStruct != INVALID_HANDLE_VALUE )
1509 FindClose(gs_hFileStruct);
1510
1511 gs_hFileStruct = ::FindFirstFile(WXSTRINGCAST spec, &gs_findDataStruct);
1512
1513 if ( gs_hFileStruct == INVALID_HANDLE_VALUE )
1514 {
1515 result.Empty();
1516
1517 return result;
1518 }
1519
1520 bool isdir = !!(gs_findDataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1521
1522 if (isdir && !(flags & wxDIR))
1523 return wxFindNextFile();
1524 else if (!isdir && flags && !(flags & wxFILE))
1525 return wxFindNextFile();
1526
1527 result += gs_findDataStruct.cFileName;
1528
1529 return result;
1530 #else // !Win32
1531 int flag = _A_NORMAL;
1532 if (flags & wxDIR)
1533 flag = _A_SUBDIR;
1534
1535 #ifdef __BORLANDC__
1536 if (findfirst(WXSTRINGCAST spec, &gs_findDataStruct, flag) == 0)
1537 #else
1538 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1539 #endif
1540 {
1541 char attrib;
1542
1543 #ifdef __BORLANDC__
1544 attrib = gs_findDataStruct.ff_attrib;
1545 #else
1546 attrib = gs_findDataStruct.attrib;
1547 #endif
1548
1549 if (attrib & _A_SUBDIR) {
1550 if (!(gs_findFlags & wxDIR))
1551 return wxFindNextFile();
1552 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1553 return wxFindNextFile();
1554
1555 result +=
1556 #ifdef __BORLANDC__
1557 gs_findDataStruct.ff_name
1558 #else
1559 gs_findDataStruct.name
1560 #endif
1561 ;
1562 }
1563
1564 return result;
1565 #endif // __WIN32__
1566 }
1567
1568
1569 wxString wxFindNextFile()
1570 {
1571 wxString result;
1572
1573 // Find path only so we can concatenate found file onto path
1574 wxString path(wxPathOnly(gs_strFileSpec));
1575
1576 try_again:
1577
1578 #ifdef __WIN32__
1579 if (gs_hFileStruct == INVALID_HANDLE_VALUE)
1580 return result;
1581
1582 bool success = (FindNextFile(gs_hFileStruct, &gs_findDataStruct) != 0);
1583 if (!success)
1584 {
1585 FindClose(gs_hFileStruct);
1586 gs_hFileStruct = INVALID_HANDLE_VALUE;
1587 }
1588 else
1589 {
1590 bool isdir = !!(gs_findDataStruct.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1591
1592 if (isdir && !(gs_findFlags & wxDIR))
1593 goto try_again;
1594 else if (!isdir && gs_findFlags && !(gs_findFlags & wxFILE))
1595 goto try_again;
1596
1597 if ( !path.IsEmpty() )
1598 result << path << wxT('\\');
1599 result << gs_findDataStruct.cFileName;
1600 }
1601
1602 return result;
1603 #else // Win16
1604
1605 #ifdef __BORLANDC__
1606 if (findnext(&gs_findDataStruct) == 0)
1607 #else
1608 if (_dos_findnext(&gs_findDataStruct) == 0)
1609 #endif
1610 {
1611 /* MATTHEW: [5] Check directory flag */
1612 char attrib;
1613
1614 #ifdef __BORLANDC__
1615 attrib = gs_findDataStruct.ff_attrib;
1616 #else
1617 attrib = gs_findDataStruct.attrib;
1618 #endif
1619
1620 if (attrib & _A_SUBDIR) {
1621 if (!(gs_findFlags & wxDIR))
1622 goto try_again;
1623 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1624 goto try_again;
1625
1626
1627 result +=
1628 #ifdef __BORLANDC__
1629 gs_findDataStruct.ff_name
1630 #else
1631 gs_findDataStruct.name
1632 #endif
1633 ;
1634 }
1635
1636 return result;
1637 #endif // Win32/16
1638 }
1639
1640 #elif defined(__WXPM__)
1641
1642 wxString wxFindFirstFile(const wxChar *spec, int flags)
1643 {
1644 wxString result;
1645
1646 /*
1647 // TODO: figure something out here for OS/2
1648 gs_strFileSpec = spec;
1649 gs_findFlags = flags;
1650
1651 // Find path only so we can concatenate found file onto path
1652 wxString path(wxPathOnly(gs_strFileSpec));
1653 if ( !path.IsEmpty() )
1654 result << path << wxT('\\');
1655
1656 int flag = _A_NORMAL;
1657 if (flags & wxDIR)
1658 flag = _A_SUBDIR;
1659
1660 if (_dos_findfirst(WXSTRINGCAST spec, flag, &gs_findDataStruct) == 0)
1661 {
1662 char attrib;
1663 attrib = gs_findDataStruct.attrib;
1664
1665 if (attrib & _A_SUBDIR) {
1666 if (!(gs_findFlags & wxDIR))
1667 return wxFindNextFile();
1668 } else if (gs_findFlags && !(gs_findFlags & wxFILE))
1669 return wxFindNextFile();
1670
1671 result += gs_findDataStruct.name;
1672 }
1673 */
1674 return result;
1675 }
1676
1677 wxString wxFindNextFile()
1678 {
1679 wxString result;
1680 // TODO:
1681 return result;
1682 }
1683
1684 #endif // Unix/Windows/OS/2
1685
1686 // Get current working directory.
1687 // If buf is NULL, allocates space using new, else
1688 // copies into buf.
1689 wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
1690 {
1691 if (!buf)
1692 buf = new wxChar[sz+1];
1693 #if wxUSE_UNICODE
1694 char *cbuf = new char[sz+1];
1695 #ifdef _MSC_VER
1696 if (_getcwd(cbuf, sz) == NULL) {
1697 #elif defined(__WXMAC__) && !defined(__UNIX__)
1698 enum
1699 {
1700 SFSaveDisk = 0x214, CurDirStore = 0x398
1701 };
1702 FSSpec cwdSpec ;
1703
1704 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1705 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1706 strcpy( buf , res ) ;
1707 if (0) {
1708 #else
1709 if (getcwd(cbuf, sz) == NULL) {
1710 #endif
1711 delete [] cbuf;
1712 #else // wxUnicode
1713 #ifdef _MSC_VER
1714 if (_getcwd(buf, sz) == NULL) {
1715 #elif defined(__WXMAC__) && !defined(__UNIX__)
1716 FSSpec cwdSpec ;
1717 FCBPBRec pb;
1718 OSErr error;
1719 Str255 fileName ;
1720 pb.ioNamePtr = (StringPtr) &fileName;
1721 pb.ioVRefNum = 0;
1722 pb.ioRefNum = LMGetCurApRefNum();
1723 pb.ioFCBIndx = 0;
1724 error = PBGetFCBInfoSync(&pb);
1725 if ( error == noErr )
1726 {
1727 cwdSpec.vRefNum = pb.ioFCBVRefNum;
1728 cwdSpec.parID = pb.ioFCBParID;
1729 cwdSpec.name[0] = 0 ;
1730 wxString res = wxMacFSSpec2MacFilename( &cwdSpec ) ;
1731
1732 strcpy( buf , res ) ;
1733 buf[res.length()-1]=0 ;
1734 }
1735 else
1736 buf[0] = 0 ;
1737 /*
1738 this version will not always give back the application directory on mac
1739 enum
1740 {
1741 SFSaveDisk = 0x214, CurDirStore = 0x398
1742 };
1743 FSSpec cwdSpec ;
1744
1745 FSMakeFSSpec( - *(short *) SFSaveDisk , *(long *) CurDirStore , NULL , &cwdSpec ) ;
1746 wxString res = wxMacFSSpec2UnixFilename( &cwdSpec ) ;
1747 strcpy( buf , res ) ;
1748 */
1749 if (0) {
1750 #elif(__VISAGECPP__)
1751 APIRET rc;
1752 rc = ::DosQueryCurrentDir( 0 // current drive
1753 ,buf
1754 ,(PULONG)&sz
1755 );
1756 if (rc != 0) {
1757 #else
1758 if (getcwd(buf, sz) == NULL) {
1759 #endif
1760 #endif
1761 buf[0] = wxT('.');
1762 buf[1] = wxT('\0');
1763 }
1764 #if wxUSE_UNICODE
1765 else {
1766 wxConvFile.MB2WC(buf, cbuf, sz);
1767 delete [] cbuf;
1768 }
1769 #endif
1770 return buf;
1771 }
1772
1773 wxString wxGetCwd()
1774 {
1775 static const size_t maxPathLen = 1024;
1776
1777 wxString str;
1778 wxGetWorkingDirectory(str.GetWriteBuf(maxPathLen), maxPathLen);
1779 str.UngetWriteBuf();
1780
1781 return str;
1782 }
1783
1784 bool wxSetWorkingDirectory(const wxString& d)
1785 {
1786 #if defined( __UNIX__ ) || defined( __WXMAC__ )
1787 return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
1788 #elif defined(__WXPM__)
1789 return (::DosSetCurrentDir((PSZ)d.c_str()) == 0);
1790 #elif defined(__WINDOWS__)
1791
1792 #ifdef __WIN32__
1793 return (bool)(SetCurrentDirectory(d) != 0);
1794 #else
1795 // Must change drive, too.
1796 bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
1797 if (isDriveSpec)
1798 {
1799 wxChar firstChar = d[0];
1800
1801 // To upper case
1802 if (firstChar > 90)
1803 firstChar = firstChar - 32;
1804
1805 // To a drive number
1806 unsigned int driveNo = firstChar - 64;
1807 if (driveNo > 0)
1808 {
1809 unsigned int noDrives;
1810 _dos_setdrive(driveNo, &noDrives);
1811 }
1812 }
1813 bool success = (chdir(WXSTRINGCAST d) == 0);
1814
1815 return success;
1816 #endif
1817
1818 #endif
1819 }
1820
1821 // Get the OS directory if appropriate (such as the Windows directory).
1822 // On non-Windows platform, probably just return the empty string.
1823 wxString wxGetOSDirectory()
1824 {
1825 #ifdef __WINDOWS__
1826 wxChar buf[256];
1827 GetWindowsDirectory(buf, 256);
1828 return wxString(buf);
1829 #else
1830 return wxEmptyString;
1831 #endif
1832 }
1833
1834 bool wxEndsWithPathSeparator(const wxChar *pszFileName)
1835 {
1836 size_t len = wxStrlen(pszFileName);
1837 if ( len == 0 )
1838 return FALSE;
1839 else
1840 return wxIsPathSeparator(pszFileName[len - 1]);
1841 }
1842
1843 // find a file in a list of directories, returns false if not found
1844 bool wxFindFileInPath(wxString *pStr, const wxChar *pszPath, const wxChar *pszFile)
1845 {
1846 // we assume that it's not empty
1847 wxCHECK_MSG( !wxIsEmpty(pszFile), FALSE,
1848 _T("empty file name in wxFindFileInPath"));
1849
1850 // skip path separator in the beginning of the file name if present
1851 if ( wxIsPathSeparator(*pszFile) )
1852 pszFile++;
1853
1854 // copy the path (strtok will modify it)
1855 wxChar *szPath = new wxChar[wxStrlen(pszPath) + 1];
1856 wxStrcpy(szPath, pszPath);
1857
1858 wxString strFile;
1859 wxChar *pc, *save_ptr;
1860 for ( pc = wxStrtok(szPath, wxPATH_SEP, &save_ptr);
1861 pc != NULL;
1862 pc = wxStrtok((wxChar *) NULL, wxPATH_SEP, &save_ptr) )
1863 {
1864 // search for the file in this directory
1865 strFile = pc;
1866 if ( !wxEndsWithPathSeparator(pc) )
1867 strFile += wxFILE_SEP_PATH;
1868 strFile += pszFile;
1869
1870 if ( FileExists(strFile) ) {
1871 *pStr = strFile;
1872 break;
1873 }
1874 }
1875
1876 // suppress warning about unused variable save_ptr when wxStrtok() is a
1877 // macro which throws away its third argument
1878 save_ptr = pc;
1879
1880 delete [] szPath;
1881
1882 return pc != NULL; // if true => we breaked from the loop
1883 }
1884
1885 void WXDLLEXPORT wxSplitPath(const wxChar *pszFileName,
1886 wxString *pstrPath,
1887 wxString *pstrName,
1888 wxString *pstrExt)
1889 {
1890 // it can be empty, but it shouldn't be NULL
1891 wxCHECK_RET( pszFileName, wxT("NULL file name in wxSplitPath") );
1892
1893 wxFileName::SplitPath(pszFileName, pstrPath, pstrName, pstrExt);
1894 }
1895
1896 time_t WXDLLEXPORT wxFileModificationTime(const wxString& filename)
1897 {
1898 wxStructStat buf;
1899
1900 wxStat(filename.fn_str(), &buf);
1901 return buf.st_mtime;
1902 }
1903
1904
1905 //------------------------------------------------------------------------
1906 // wild character routines
1907 //------------------------------------------------------------------------
1908
1909 bool wxIsWild( const wxString& pattern )
1910 {
1911 wxString tmp = pattern;
1912 wxChar *pat = WXSTRINGCAST(tmp);
1913 while (*pat) {
1914 switch (*pat++) {
1915 case wxT('?'): case wxT('*'): case wxT('['): case wxT('{'):
1916 return TRUE;
1917 case wxT('\\'):
1918 if (!*pat++)
1919 return FALSE;
1920 }
1921 }
1922 return FALSE;
1923 };
1924
1925 bool wxMatchWild( const wxString& pat, const wxString& text, bool dot_special )
1926
1927 #if defined(HAVE_FNMATCH_H)
1928 {
1929 // this probably won't work well for multibyte chars in Unicode mode?
1930 if(dot_special)
1931 return fnmatch(pat.fn_str(), text.fn_str(), FNM_PERIOD) == 0;
1932 else
1933 return fnmatch(pat.fn_str(), text.fn_str(), 0) == 0;
1934 }
1935 #else
1936
1937 // #pragma error Broken implementation of wxMatchWild() -- needs fixing!
1938
1939 /*
1940 * WARNING: this code is broken!
1941 */
1942 {
1943 wxString tmp1 = pat;
1944 wxChar *pattern = WXSTRINGCAST(tmp1);
1945 wxString tmp2 = text;
1946 wxChar *str = WXSTRINGCAST(tmp2);
1947 wxChar c;
1948 wxChar *cp;
1949 bool done = FALSE, ret_code, ok;
1950 // Below is for vi fans
1951 const wxChar OB = wxT('{'), CB = wxT('}');
1952
1953 // dot_special means '.' only matches '.'
1954 if (dot_special && *str == wxT('.') && *pattern != *str)
1955 return FALSE;
1956
1957 while ((*pattern != wxT('\0')) && (!done)
1958 && (((*str==wxT('\0'))&&((*pattern==OB)||(*pattern==wxT('*'))))||(*str!=wxT('\0')))) {
1959 switch (*pattern) {
1960 case wxT('\\'):
1961 pattern++;
1962 if (*pattern != wxT('\0'))
1963 pattern++;
1964 break;
1965 case wxT('*'):
1966 pattern++;
1967 ret_code = FALSE;
1968 while ((*str!=wxT('\0'))
1969 && ((ret_code=wxMatchWild(pattern, str++, FALSE)) == 0))
1970 /*loop*/;
1971 if (ret_code) {
1972 while (*str != wxT('\0'))
1973 str++;
1974 while (*pattern != wxT('\0'))
1975 pattern++;
1976 }
1977 break;
1978 case wxT('['):
1979 pattern++;
1980 repeat:
1981 if ((*pattern == wxT('\0')) || (*pattern == wxT(']'))) {
1982 done = TRUE;
1983 break;
1984 }
1985 if (*pattern == wxT('\\')) {
1986 pattern++;
1987 if (*pattern == wxT('\0')) {
1988 done = TRUE;
1989 break;
1990 }
1991 }
1992 if (*(pattern + 1) == wxT('-')) {
1993 c = *pattern;
1994 pattern += 2;
1995 if (*pattern == wxT(']')) {
1996 done = TRUE;
1997 break;
1998 }
1999 if (*pattern == wxT('\\')) {
2000 pattern++;
2001 if (*pattern == wxT('\0')) {
2002 done = TRUE;
2003 break;
2004 }
2005 }
2006 if ((*str < c) || (*str > *pattern)) {
2007 pattern++;
2008 goto repeat;
2009 }
2010 } else if (*pattern != *str) {
2011 pattern++;
2012 goto repeat;
2013 }
2014 pattern++;
2015 while ((*pattern != wxT(']')) && (*pattern != wxT('\0'))) {
2016 if ((*pattern == wxT('\\')) && (*(pattern + 1) != wxT('\0')))
2017 pattern++;
2018 pattern++;
2019 }
2020 if (*pattern != wxT('\0')) {
2021 pattern++, str++;
2022 }
2023 break;
2024 case wxT('?'):
2025 pattern++;
2026 str++;
2027 break;
2028 case OB:
2029 pattern++;
2030 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
2031 cp = str;
2032 ok = TRUE;
2033 while (ok && (*cp != wxT('\0')) && (*pattern != wxT('\0'))
2034 && (*pattern != wxT(',')) && (*pattern != CB)) {
2035 if (*pattern == wxT('\\'))
2036 pattern++;
2037 ok = (*pattern++ == *cp++);
2038 }
2039 if (*pattern == wxT('\0')) {
2040 ok = FALSE;
2041 done = TRUE;
2042 break;
2043 } else if (ok) {
2044 str = cp;
2045 while ((*pattern != CB) && (*pattern != wxT('\0'))) {
2046 if (*++pattern == wxT('\\')) {
2047 if (*++pattern == CB)
2048 pattern++;
2049 }
2050 }
2051 } else {
2052 while (*pattern!=CB && *pattern!=wxT(',') && *pattern!=wxT('\0')) {
2053 if (*++pattern == wxT('\\')) {
2054 if (*++pattern == CB || *pattern == wxT(','))
2055 pattern++;
2056 }
2057 }
2058 }
2059 if (*pattern != wxT('\0'))
2060 pattern++;
2061 }
2062 break;
2063 default:
2064 if (*str == *pattern) {
2065 str++, pattern++;
2066 } else {
2067 done = TRUE;
2068 }
2069 }
2070 }
2071 while (*pattern == wxT('*'))
2072 pattern++;
2073 return ((*str == wxT('\0')) && (*pattern == wxT('\0')));
2074 };
2075
2076 #endif
2077
2078 #ifdef __VISUALC__
2079 #pragma warning(default:4706) // assignment within conditional expression
2080 #endif // VC++