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