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