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