PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/Extras/wxWidgets-2.9.0/src/common/filefn.cpp

http://dynamica.googlecode.com/
C++ | 2144 lines | 1753 code | 176 blank | 215 comment | 267 complexity | 0ae02624f1a78f3a3d226df51a3de0e9 MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  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: filefn.cpp 59868 2009-03-26 15:55:01Z VZ $
  8. // Copyright: (c) 1998 Julian Smart
  9. // Licence: wxWindows licence
  10. /////////////////////////////////////////////////////////////////////////////
  11. // ============================================================================
  12. // declarations
  13. // ============================================================================
  14. // ----------------------------------------------------------------------------
  15. // headers
  16. // ----------------------------------------------------------------------------
  17. // For compilers that support precompilation, includes "wx.h".
  18. #include "wx/wxprec.h"
  19. #ifdef __BORLANDC__
  20. #pragma hdrstop
  21. #endif
  22. #include "wx/filefn.h"
  23. #ifndef WX_PRECOMP
  24. #include "wx/intl.h"
  25. #include "wx/log.h"
  26. #include "wx/utils.h"
  27. #include "wx/crt.h"
  28. #endif
  29. #include "wx/dynarray.h"
  30. #include "wx/file.h"
  31. #include "wx/filename.h"
  32. #include "wx/dir.h"
  33. #include "wx/tokenzr.h"
  34. // there are just too many of those...
  35. #ifdef __VISUALC__
  36. #pragma warning(disable:4706) // assignment within conditional expression
  37. #endif // VC++
  38. #include <ctype.h>
  39. #include <stdio.h>
  40. #include <stdlib.h>
  41. #include <string.h>
  42. #if !wxONLY_WATCOM_EARLIER_THAN(1,4)
  43. #if !(defined(_MSC_VER) && (_MSC_VER > 800))
  44. #include <errno.h>
  45. #endif
  46. #endif
  47. #if defined(__WXMAC__)
  48. #include "wx/osx/private.h" // includes mac headers
  49. #endif
  50. #ifdef __WINDOWS__
  51. #include "wx/msw/private.h"
  52. #include "wx/msw/mslu.h"
  53. // sys/cygwin.h is needed for cygwin_conv_to_full_win32_path()
  54. //
  55. // note that it must be included after <windows.h>
  56. #ifdef __GNUWIN32__
  57. #ifdef __CYGWIN__
  58. #include <sys/cygwin.h>
  59. #endif
  60. #endif // __GNUWIN32__
  61. // io.h is needed for _get_osfhandle()
  62. // Already included by filefn.h for many Windows compilers
  63. #if defined __MWERKS__ || defined __CYGWIN__
  64. #include <io.h>
  65. #endif
  66. #endif // __WINDOWS__
  67. #if defined(__VMS__)
  68. #include <fab.h>
  69. #endif
  70. // TODO: Borland probably has _wgetcwd as well?
  71. #ifdef _MSC_VER
  72. #define HAVE_WGETCWD
  73. #endif
  74. // ----------------------------------------------------------------------------
  75. // constants
  76. // ----------------------------------------------------------------------------
  77. #ifndef _MAXPATHLEN
  78. #define _MAXPATHLEN 1024
  79. #endif
  80. #ifndef INVALID_FILE_ATTRIBUTES
  81. #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  82. #endif
  83. // ----------------------------------------------------------------------------
  84. // private globals
  85. // ----------------------------------------------------------------------------
  86. #if WXWIN_COMPATIBILITY_2_8
  87. static wxChar wxFileFunctionsBuffer[4*_MAXPATHLEN];
  88. #endif
  89. #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
  90. //
  91. // VisualAge C++ V4.0 cannot have any external linkage const decs
  92. // in headers included by more than one primary source
  93. //
  94. const int wxInvalidOffset = -1;
  95. #endif
  96. // ============================================================================
  97. // implementation
  98. // ============================================================================
  99. // ----------------------------------------------------------------------------
  100. // wrappers around standard POSIX functions
  101. // ----------------------------------------------------------------------------
  102. #if wxUSE_UNICODE && defined __BORLANDC__ \
  103. && __BORLANDC__ >= 0x550 && __BORLANDC__ <= 0x551
  104. // BCC 5.5 and 5.5.1 have a bug in _wopen where files are created read only
  105. // regardless of the mode parameter. This hack works around the problem by
  106. // setting the mode with _wchmod.
  107. //
  108. int wxCRT_Open(const wchar_t *pathname, int flags, mode_t mode)
  109. {
  110. int moreflags = 0;
  111. // we only want to fix the mode when the file is actually created, so
  112. // when creating first try doing it O_EXCL so we can tell if the file
  113. // was already there.
  114. if ((flags & O_CREAT) && !(flags & O_EXCL) && (mode & wxS_IWUSR) != 0)
  115. moreflags = O_EXCL;
  116. int fd = _wopen(pathname, flags | moreflags, mode);
  117. // the file was actually created and needs fixing
  118. if (fd != -1 && (flags & O_CREAT) != 0 && (mode & wxS_IWUSR) != 0)
  119. {
  120. close(fd);
  121. _wchmod(pathname, mode);
  122. fd = _wopen(pathname, flags & ~(O_EXCL | O_CREAT));
  123. }
  124. // the open failed, but it may have been because the added O_EXCL stopped
  125. // the opening of an existing file, so try again without.
  126. else if (fd == -1 && moreflags != 0)
  127. {
  128. fd = _wopen(pathname, flags & ~O_CREAT);
  129. }
  130. return fd;
  131. }
  132. #endif
  133. // ----------------------------------------------------------------------------
  134. // wxPathList
  135. // ----------------------------------------------------------------------------
  136. bool wxPathList::Add(const wxString& path)
  137. {
  138. // add a path separator to force wxFileName to interpret it always as a directory
  139. // (i.e. if we are called with '/home/user' we want to consider it a folder and
  140. // not, as wxFileName would consider, a filename).
  141. wxFileName fn(path + wxFileName::GetPathSeparator());
  142. // add only normalized relative/absolute paths
  143. // NB: we won't do wxPATH_NORM_DOTS in order to avoid problems when trying to
  144. // normalize paths which starts with ".." (which can be normalized only if
  145. // we use also wxPATH_NORM_ABSOLUTE - which we don't want to use).
  146. if (!fn.Normalize(wxPATH_NORM_TILDE|wxPATH_NORM_LONG|wxPATH_NORM_ENV_VARS))
  147. return false;
  148. wxString toadd = fn.GetPath();
  149. if (Index(toadd) == wxNOT_FOUND)
  150. wxArrayString::Add(toadd); // do not add duplicates
  151. return true;
  152. }
  153. void wxPathList::Add(const wxArrayString &arr)
  154. {
  155. for (size_t j=0; j < arr.GetCount(); j++)
  156. Add(arr[j]);
  157. }
  158. // Add paths e.g. from the PATH environment variable
  159. void wxPathList::AddEnvList (const wxString& WXUNUSED_IN_WINCE(envVariable))
  160. {
  161. // No environment variables on WinCE
  162. #ifndef __WXWINCE__
  163. // The space has been removed from the tokenizers, otherwise a
  164. // path such as "C:\Program Files" would be split into 2 paths:
  165. // "C:\Program" and "Files"; this is true for both Windows and Unix.
  166. static const wxChar PATH_TOKS[] =
  167. #if defined(__WINDOWS__) || defined(__OS2__)
  168. wxT(";"); // Don't separate with colon in DOS (used for drive)
  169. #else
  170. wxT(":;");
  171. #endif
  172. wxString val;
  173. if ( wxGetEnv(envVariable, &val) )
  174. {
  175. // split into an array of string the value of the env var
  176. wxArrayString arr = wxStringTokenize(val, PATH_TOKS);
  177. WX_APPEND_ARRAY(*this, arr);
  178. }
  179. #endif // !__WXWINCE__
  180. }
  181. // Given a full filename (with path), ensure that that file can
  182. // be accessed again USING FILENAME ONLY by adding the path
  183. // to the list if not already there.
  184. bool wxPathList::EnsureFileAccessible (const wxString& path)
  185. {
  186. return Add(wxPathOnly(path));
  187. }
  188. #if WXWIN_COMPATIBILITY_2_6
  189. bool wxPathList::Member (const wxString& path) const
  190. {
  191. return Index(path) != wxNOT_FOUND;
  192. }
  193. #endif
  194. wxString wxPathList::FindValidPath (const wxString& file) const
  195. {
  196. // normalize the given string as it could be a path + a filename
  197. // and not only a filename
  198. wxFileName fn(file);
  199. wxString strend;
  200. // NB: normalize without making absolute otherwise calling this function with
  201. // e.g. "b/c.txt" would result in removing the directory 'b' and the for loop
  202. // below would only add to the paths of this list the 'c.txt' part when doing
  203. // the existence checks...
  204. // NB: we don't use wxPATH_NORM_DOTS here, too (see wxPathList::Add for more info)
  205. if (!fn.Normalize(wxPATH_NORM_TILDE|wxPATH_NORM_LONG|wxPATH_NORM_ENV_VARS))
  206. return wxEmptyString;
  207. wxASSERT_MSG(!fn.IsDir(), wxT("Cannot search for directories; only for files"));
  208. if (fn.IsAbsolute())
  209. strend = fn.GetFullName(); // search for the file name and ignore the path part
  210. else
  211. strend = fn.GetFullPath();
  212. for (size_t i=0; i<GetCount(); i++)
  213. {
  214. wxString strstart = Item(i);
  215. if (!strstart.IsEmpty() && strstart.Last() != wxFileName::GetPathSeparator())
  216. strstart += wxFileName::GetPathSeparator();
  217. if (wxFileExists(strstart + strend))
  218. return strstart + strend; // Found!
  219. }
  220. return wxEmptyString; // Not found
  221. }
  222. wxString wxPathList::FindAbsoluteValidPath (const wxString& file) const
  223. {
  224. wxString f = FindValidPath(file);
  225. if ( f.empty() || wxIsAbsolutePath(f) )
  226. return f;
  227. wxString buf = ::wxGetCwd();
  228. if ( !wxEndsWithPathSeparator(buf) )
  229. {
  230. buf += wxFILE_SEP_PATH;
  231. }
  232. buf += f;
  233. return buf;
  234. }
  235. // ----------------------------------------------------------------------------
  236. // miscellaneous global functions
  237. // ----------------------------------------------------------------------------
  238. #if WXWIN_COMPATIBILITY_2_8
  239. static inline wxChar* MYcopystring(const wxString& s)
  240. {
  241. wxChar* copy = new wxChar[s.length() + 1];
  242. return wxStrcpy(copy, s.c_str());
  243. }
  244. template<typename CharType>
  245. static inline CharType* MYcopystring(const CharType* s)
  246. {
  247. CharType* copy = new CharType[wxStrlen(s) + 1];
  248. return wxStrcpy(copy, s);
  249. }
  250. #endif
  251. bool
  252. wxFileExists (const wxString& filename)
  253. {
  254. #if defined(__WXPALMOS__)
  255. return false;
  256. #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
  257. // we must use GetFileAttributes() instead of the ANSI C functions because
  258. // it can cope with network (UNC) paths unlike them
  259. DWORD ret = ::GetFileAttributes(filename.fn_str());
  260. return (ret != INVALID_FILE_ATTRIBUTES) && !(ret & FILE_ATTRIBUTE_DIRECTORY);
  261. #else // !__WIN32__
  262. #ifndef S_ISREG
  263. #define S_ISREG(mode) ((mode) & S_IFREG)
  264. #endif
  265. wxStructStat st;
  266. #ifndef wxNEED_WX_UNISTD_H
  267. return (wxStat( filename.fn_str() , &st) == 0 && S_ISREG(st.st_mode))
  268. #ifdef __OS2__
  269. || (errno == EACCES) // if access is denied something with that name
  270. // exists and is opened in exclusive mode.
  271. #endif
  272. ;
  273. #else
  274. return wxStat( filename , &st) == 0 && S_ISREG(st.st_mode);
  275. #endif
  276. #endif // __WIN32__/!__WIN32__
  277. }
  278. bool
  279. wxIsAbsolutePath (const wxString& filename)
  280. {
  281. if (!filename.empty())
  282. {
  283. // Unix like or Windows
  284. if (filename[0] == wxT('/'))
  285. return true;
  286. #ifdef __VMS__
  287. if ((filename[0] == wxT('[') && filename[1] != wxT('.')))
  288. return true;
  289. #endif
  290. #if defined(__WINDOWS__) || defined(__OS2__)
  291. // MSDOS like
  292. if (filename[0] == wxT('\\') || (wxIsalpha (filename[0]) && filename[1] == wxT(':')))
  293. return true;
  294. #endif
  295. }
  296. return false ;
  297. }
  298. #if WXWIN_COMPATIBILITY_2_8
  299. /*
  300. * Strip off any extension (dot something) from end of file,
  301. * IF one exists. Inserts zero into buffer.
  302. *
  303. */
  304. template<typename T>
  305. static void wxDoStripExtension(T *buffer)
  306. {
  307. int len = wxStrlen(buffer);
  308. int i = len-1;
  309. while (i > 0)
  310. {
  311. if (buffer[i] == wxT('.'))
  312. {
  313. buffer[i] = 0;
  314. break;
  315. }
  316. i --;
  317. }
  318. }
  319. void wxStripExtension(char *buffer) { wxDoStripExtension(buffer); }
  320. void wxStripExtension(wchar_t *buffer) { wxDoStripExtension(buffer); }
  321. void wxStripExtension(wxString& buffer)
  322. {
  323. buffer = wxFileName::StripExtension(buffer);
  324. }
  325. // Destructive removal of /./ and /../ stuff
  326. template<typename CharType>
  327. static CharType *wxDoRealPath (CharType *path)
  328. {
  329. static const CharType SEP = wxFILE_SEP_PATH;
  330. #ifdef __WXMSW__
  331. wxUnix2DosFilename(path);
  332. #endif
  333. if (path[0] && path[1]) {
  334. /* MATTHEW: special case "/./x" */
  335. CharType *p;
  336. if (path[2] == SEP && path[1] == wxT('.'))
  337. p = &path[0];
  338. else
  339. p = &path[2];
  340. for (; *p; p++)
  341. {
  342. if (*p == SEP)
  343. {
  344. if (p[1] == wxT('.') && p[2] == wxT('.') && (p[3] == SEP || p[3] == wxT('\0')))
  345. {
  346. CharType *q;
  347. for (q = p - 1; q >= path && *q != SEP; q--)
  348. {
  349. // Empty
  350. }
  351. if (q[0] == SEP && (q[1] != wxT('.') || q[2] != wxT('.') || q[3] != SEP)
  352. && (q - 1 <= path || q[-1] != SEP))
  353. {
  354. wxStrcpy (q, p + 3);
  355. if (path[0] == wxT('\0'))
  356. {
  357. path[0] = SEP;
  358. path[1] = wxT('\0');
  359. }
  360. #if defined(__WXMSW__) || defined(__OS2__)
  361. /* Check that path[2] is NULL! */
  362. else if (path[1] == wxT(':') && !path[2])
  363. {
  364. path[2] = SEP;
  365. path[3] = wxT('\0');
  366. }
  367. #endif
  368. p = q - 1;
  369. }
  370. }
  371. else if (p[1] == wxT('.') && (p[2] == SEP || p[2] == wxT('\0')))
  372. wxStrcpy (p, p + 2);
  373. }
  374. }
  375. }
  376. return path;
  377. }
  378. char *wxRealPath(char *path)
  379. {
  380. return wxDoRealPath(path);
  381. }
  382. wchar_t *wxRealPath(wchar_t *path)
  383. {
  384. return wxDoRealPath(path);
  385. }
  386. wxString wxRealPath(const wxString& path)
  387. {
  388. wxChar *buf1=MYcopystring(path);
  389. wxChar *buf2=wxRealPath(buf1);
  390. wxString buf(buf2);
  391. delete [] buf1;
  392. return buf;
  393. }
  394. // Must be destroyed
  395. wxChar *wxCopyAbsolutePath(const wxString& filename)
  396. {
  397. if (filename.empty())
  398. return NULL;
  399. if (! wxIsAbsolutePath(wxExpandPath(wxFileFunctionsBuffer, filename)))
  400. {
  401. wxString buf = ::wxGetCwd();
  402. wxChar ch = buf.Last();
  403. #ifdef __WXMSW__
  404. if (ch != wxT('\\') && ch != wxT('/'))
  405. buf << wxT("\\");
  406. #else
  407. if (ch != wxT('/'))
  408. buf << wxT("/");
  409. #endif
  410. buf << wxFileFunctionsBuffer;
  411. buf = wxRealPath( buf );
  412. return MYcopystring( buf );
  413. }
  414. return MYcopystring( wxFileFunctionsBuffer );
  415. }
  416. /*-
  417. Handles:
  418. ~/ => home dir
  419. ~user/ => user's home dir
  420. If the environment variable a = "foo" and b = "bar" then:
  421. Unix:
  422. $a => foo
  423. $a$b => foobar
  424. $a.c => foo.c
  425. xxx$a => xxxfoo
  426. ${a}! => foo!
  427. $(b)! => bar!
  428. \$a => \$a
  429. MSDOS:
  430. $a ==> $a
  431. $(a) ==> foo
  432. $(a)$b ==> foo$b
  433. $(a)$(b)==> foobar
  434. test.$$ ==> test.$$
  435. */
  436. /* input name in name, pathname output to buf. */
  437. template<typename CharType>
  438. static CharType *wxDoExpandPath(CharType *buf, const wxString& name)
  439. {
  440. register CharType *d, *s, *nm;
  441. CharType lnm[_MAXPATHLEN];
  442. int q;
  443. // Some compilers don't like this line.
  444. // const CharType trimchars[] = wxT("\n \t");
  445. CharType trimchars[4];
  446. trimchars[0] = wxT('\n');
  447. trimchars[1] = wxT(' ');
  448. trimchars[2] = wxT('\t');
  449. trimchars[3] = 0;
  450. static const CharType SEP = wxFILE_SEP_PATH;
  451. #ifdef __WXMSW__
  452. //wxUnix2DosFilename(path);
  453. #endif
  454. buf[0] = wxT('\0');
  455. if (name.empty())
  456. return buf;
  457. nm = ::MYcopystring(static_cast<const CharType*>(name.c_str())); // Make a scratch copy
  458. CharType *nm_tmp = nm;
  459. /* Skip leading whitespace and cr */
  460. while (wxStrchr(trimchars, *nm) != NULL)
  461. nm++;
  462. /* And strip off trailing whitespace and cr */
  463. s = nm + (q = wxStrlen(nm)) - 1;
  464. while (q-- && wxStrchr(trimchars, *s) != NULL)
  465. *s = wxT('\0');
  466. s = nm;
  467. d = lnm;
  468. #ifdef __WXMSW__
  469. q = FALSE;
  470. #else
  471. q = nm[0] == wxT('\\') && nm[1] == wxT('~');
  472. #endif
  473. /* Expand inline environment variables */
  474. #ifdef __VISAGECPP__
  475. while (*d)
  476. {
  477. *d++ = *s;
  478. if(*s == wxT('\\'))
  479. {
  480. *(d - 1) = *++s;
  481. if (*d)
  482. {
  483. s++;
  484. continue;
  485. }
  486. else
  487. break;
  488. }
  489. else
  490. #else
  491. while ((*d++ = *s) != 0) {
  492. # ifndef __WXMSW__
  493. if (*s == wxT('\\')) {
  494. if ((*(d - 1) = *++s)!=0) {
  495. s++;
  496. continue;
  497. } else
  498. break;
  499. } else
  500. # endif
  501. #endif
  502. // No env variables on WinCE
  503. #ifndef __WXWINCE__
  504. #ifdef __WXMSW__
  505. if (*s++ == wxT('$') && (*s == wxT('{') || *s == wxT(')')))
  506. #else
  507. if (*s++ == wxT('$'))
  508. #endif
  509. {
  510. register CharType *start = d;
  511. register int braces = (*s == wxT('{') || *s == wxT('('));
  512. register CharType *value;
  513. while ((*d++ = *s) != 0)
  514. if (braces ? (*s == wxT('}') || *s == wxT(')')) : !(wxIsalnum(*s) || *s == wxT('_')) )
  515. break;
  516. else
  517. s++;
  518. *--d = 0;
  519. value = wxGetenv(braces ? start + 1 : start);
  520. if (value) {
  521. for ((d = start - 1); (*d++ = *value++) != 0;)
  522. {
  523. // Empty
  524. }
  525. d--;
  526. if (braces && *s)
  527. s++;
  528. }
  529. }
  530. #endif
  531. // __WXWINCE__
  532. }
  533. /* Expand ~ and ~user */
  534. wxString homepath;
  535. nm = lnm;
  536. if (nm[0] == wxT('~') && !q)
  537. {
  538. /* prefix ~ */
  539. if (nm[1] == SEP || nm[1] == 0)
  540. { /* ~/filename */
  541. homepath = wxGetUserHome(wxEmptyString);
  542. if (!homepath.empty()) {
  543. s = (CharType*)(const CharType*)homepath.c_str();
  544. if (*++nm)
  545. nm++;
  546. }
  547. } else
  548. { /* ~user/filename */
  549. register CharType *nnm;
  550. for (s = nm; *s && *s != SEP; s++)
  551. {
  552. // Empty
  553. }
  554. int was_sep; /* MATTHEW: Was there a separator, or NULL? */
  555. was_sep = (*s == SEP);
  556. nnm = *s ? s + 1 : s;
  557. *s = 0;
  558. homepath = wxGetUserHome(wxString(nm + 1));
  559. if (homepath.empty())
  560. {
  561. if (was_sep) /* replace only if it was there: */
  562. *s = SEP;
  563. s = NULL;
  564. }
  565. else
  566. {
  567. nm = nnm;
  568. s = (CharType*)(const CharType*)homepath.c_str();
  569. }
  570. }
  571. }
  572. d = buf;
  573. if (s && *s) { /* MATTHEW: s could be NULL if user '~' didn't exist */
  574. /* Copy home dir */
  575. while (wxT('\0') != (*d++ = *s++))
  576. /* loop */;
  577. // Handle root home
  578. if (d - 1 > buf && *(d - 2) != SEP)
  579. *(d - 1) = SEP;
  580. }
  581. s = nm;
  582. while ((*d++ = *s++) != 0)
  583. {
  584. // Empty
  585. }
  586. delete[] nm_tmp; // clean up alloc
  587. /* Now clean up the buffer */
  588. return wxRealPath(buf);
  589. }
  590. char *wxExpandPath(char *buf, const wxString& name)
  591. {
  592. return wxDoExpandPath(buf, name);
  593. }
  594. wchar_t *wxExpandPath(wchar_t *buf, const wxString& name)
  595. {
  596. return wxDoExpandPath(buf, name);
  597. }
  598. /* Contract Paths to be build upon an environment variable
  599. component:
  600. example: "/usr/openwin/lib", OPENWINHOME --> ${OPENWINHOME}/lib
  601. The call wxExpandPath can convert these back!
  602. */
  603. wxChar *
  604. wxContractPath (const wxString& filename,
  605. const wxString& WXUNUSED_IN_WINCE(envname),
  606. const wxString& user)
  607. {
  608. static wxChar dest[_MAXPATHLEN];
  609. if (filename.empty())
  610. return NULL;
  611. wxStrcpy (dest, filename);
  612. #ifdef __WXMSW__
  613. wxUnix2DosFilename(dest);
  614. #endif
  615. // Handle environment
  616. wxString val;
  617. #ifndef __WXWINCE__
  618. wxChar *tcp;
  619. if (!envname.empty() && !(val = wxGetenv (envname)).empty() &&
  620. (tcp = wxStrstr (dest, val)) != NULL)
  621. {
  622. wxStrcpy (wxFileFunctionsBuffer, tcp + val.length());
  623. *tcp++ = wxT('$');
  624. *tcp++ = wxT('{');
  625. wxStrcpy (tcp, envname);
  626. wxStrcat (tcp, wxT("}"));
  627. wxStrcat (tcp, wxFileFunctionsBuffer);
  628. }
  629. #endif
  630. // Handle User's home (ignore root homes!)
  631. val = wxGetUserHome (user);
  632. if (val.empty())
  633. return dest;
  634. const size_t len = val.length();
  635. if (len <= 2)
  636. return dest;
  637. if (wxStrncmp(dest, val, len) == 0)
  638. {
  639. wxStrcpy(wxFileFunctionsBuffer, wxT("~"));
  640. if (!user.empty())
  641. wxStrcat(wxFileFunctionsBuffer, user);
  642. wxStrcat(wxFileFunctionsBuffer, dest + len);
  643. wxStrcpy (dest, wxFileFunctionsBuffer);
  644. }
  645. return dest;
  646. }
  647. #endif // #if WXWIN_COMPATIBILITY_2_8
  648. // Return just the filename, not the path (basename)
  649. wxChar *wxFileNameFromPath (wxChar *path)
  650. {
  651. wxString p = path;
  652. wxString n = wxFileNameFromPath(p);
  653. return path + p.length() - n.length();
  654. }
  655. wxString wxFileNameFromPath (const wxString& path)
  656. {
  657. wxString name, ext;
  658. wxFileName::SplitPath(path, NULL, &name, &ext);
  659. wxString fullname = name;
  660. if ( !ext.empty() )
  661. {
  662. fullname << wxFILE_SEP_EXT << ext;
  663. }
  664. return fullname;
  665. }
  666. // Return just the directory, or NULL if no directory
  667. wxChar *
  668. wxPathOnly (wxChar *path)
  669. {
  670. if (path && *path)
  671. {
  672. static wxChar buf[_MAXPATHLEN];
  673. // Local copy
  674. wxStrcpy (buf, path);
  675. int l = wxStrlen(path);
  676. int i = l - 1;
  677. // Search backward for a backward or forward slash
  678. while (i > -1)
  679. {
  680. // Unix like or Windows
  681. if (path[i] == wxT('/') || path[i] == wxT('\\'))
  682. {
  683. buf[i] = 0;
  684. return buf;
  685. }
  686. #ifdef __VMS__
  687. if (path[i] == wxT(']'))
  688. {
  689. buf[i+1] = 0;
  690. return buf;
  691. }
  692. #endif
  693. i --;
  694. }
  695. #if defined(__WXMSW__) || defined(__OS2__)
  696. // Try Drive specifier
  697. if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
  698. {
  699. // A:junk --> A:. (since A:.\junk Not A:\junk)
  700. buf[2] = wxT('.');
  701. buf[3] = wxT('\0');
  702. return buf;
  703. }
  704. #endif
  705. }
  706. return NULL;
  707. }
  708. // Return just the directory, or NULL if no directory
  709. wxString wxPathOnly (const wxString& path)
  710. {
  711. if (!path.empty())
  712. {
  713. wxChar buf[_MAXPATHLEN];
  714. // Local copy
  715. wxStrcpy(buf, path);
  716. int l = path.length();
  717. int i = l - 1;
  718. // Search backward for a backward or forward slash
  719. while (i > -1)
  720. {
  721. // Unix like or Windows
  722. if (path[i] == wxT('/') || path[i] == wxT('\\'))
  723. {
  724. // Don't return an empty string
  725. if (i == 0)
  726. i ++;
  727. buf[i] = 0;
  728. return wxString(buf);
  729. }
  730. #ifdef __VMS__
  731. if (path[i] == wxT(']'))
  732. {
  733. buf[i+1] = 0;
  734. return wxString(buf);
  735. }
  736. #endif
  737. i --;
  738. }
  739. #if defined(__WXMSW__) || defined(__OS2__)
  740. // Try Drive specifier
  741. if (wxIsalpha (buf[0]) && buf[1] == wxT(':'))
  742. {
  743. // A:junk --> A:. (since A:.\junk Not A:\junk)
  744. buf[2] = wxT('.');
  745. buf[3] = wxT('\0');
  746. return wxString(buf);
  747. }
  748. #endif
  749. }
  750. return wxEmptyString;
  751. }
  752. // Utility for converting delimiters in DOS filenames to UNIX style
  753. // and back again - or we get nasty problems with delimiters.
  754. // Also, convert to lower case, since case is significant in UNIX.
  755. #if defined(__WXMAC__) && !defined(__WXOSX_IPHONE__)
  756. #define kDefaultPathStyle kCFURLPOSIXPathStyle
  757. wxString wxMacFSRefToPath( const FSRef *fsRef , CFStringRef additionalPathComponent )
  758. {
  759. CFURLRef fullURLRef;
  760. fullURLRef = CFURLCreateFromFSRef(NULL, fsRef);
  761. if ( additionalPathComponent )
  762. {
  763. CFURLRef parentURLRef = fullURLRef ;
  764. fullURLRef = CFURLCreateCopyAppendingPathComponent(NULL, parentURLRef,
  765. additionalPathComponent,false);
  766. CFRelease( parentURLRef ) ;
  767. }
  768. CFStringRef cfString = CFURLCopyFileSystemPath(fullURLRef, kDefaultPathStyle);
  769. CFRelease( fullURLRef ) ;
  770. CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfString);
  771. CFRelease( cfString );
  772. CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
  773. return wxCFStringRef(cfMutableString).AsString();
  774. }
  775. OSStatus wxMacPathToFSRef( const wxString&path , FSRef *fsRef )
  776. {
  777. OSStatus err = noErr ;
  778. CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, wxCFStringRef(path));
  779. CFStringNormalize(cfMutableString,kCFStringNormalizationFormD);
  780. CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfMutableString , kDefaultPathStyle, false);
  781. CFRelease( cfMutableString );
  782. if ( NULL != url )
  783. {
  784. if ( CFURLGetFSRef(url, fsRef) == false )
  785. err = fnfErr ;
  786. CFRelease( url ) ;
  787. }
  788. else
  789. {
  790. err = fnfErr ;
  791. }
  792. return err ;
  793. }
  794. wxString wxMacHFSUniStrToString( ConstHFSUniStr255Param uniname )
  795. {
  796. CFStringRef cfname = CFStringCreateWithCharacters( kCFAllocatorDefault,
  797. uniname->unicode,
  798. uniname->length );
  799. CFMutableStringRef cfMutableString = CFStringCreateMutableCopy(NULL, 0, cfname);
  800. CFRelease( cfname );
  801. CFStringNormalize(cfMutableString,kCFStringNormalizationFormC);
  802. return wxCFStringRef(cfMutableString).AsString() ;
  803. }
  804. #ifndef __LP64__
  805. wxString wxMacFSSpec2MacFilename( const FSSpec *spec )
  806. {
  807. FSRef fsRef ;
  808. if ( FSpMakeFSRef( spec , &fsRef) == noErr )
  809. {
  810. return wxMacFSRefToPath( &fsRef ) ;
  811. }
  812. return wxEmptyString ;
  813. }
  814. void wxMacFilename2FSSpec( const wxString& path , FSSpec *spec )
  815. {
  816. OSStatus err = noErr;
  817. FSRef fsRef;
  818. wxMacPathToFSRef( path , &fsRef );
  819. err = FSGetCatalogInfo(&fsRef, kFSCatInfoNone, NULL, NULL, spec, NULL);
  820. verify_noerr( err );
  821. }
  822. #endif
  823. #endif // __WXMAC__
  824. #if WXWIN_COMPATIBILITY_2_8
  825. template<typename T>
  826. static void wxDoDos2UnixFilename(T *s)
  827. {
  828. if (s)
  829. while (*s)
  830. {
  831. if (*s == _T('\\'))
  832. *s = _T('/');
  833. #ifdef __WXMSW__
  834. else
  835. *s = wxTolower(*s); // Case INDEPENDENT
  836. #endif
  837. s++;
  838. }
  839. }
  840. void wxDos2UnixFilename(char *s) { wxDoDos2UnixFilename(s); }
  841. void wxDos2UnixFilename(wchar_t *s) { wxDoDos2UnixFilename(s); }
  842. template<typename T>
  843. static void
  844. #if defined(__WXMSW__) || defined(__OS2__)
  845. wxDoUnix2DosFilename(T *s)
  846. #else
  847. wxDoUnix2DosFilename(T *WXUNUSED(s) )
  848. #endif
  849. {
  850. // Yes, I really mean this to happen under DOS only! JACS
  851. #if defined(__WXMSW__) || defined(__OS2__)
  852. if (s)
  853. while (*s)
  854. {
  855. if (*s == wxT('/'))
  856. *s = wxT('\\');
  857. s++;
  858. }
  859. #endif
  860. }
  861. void wxUnix2DosFilename(char *s) { wxDoUnix2DosFilename(s); }
  862. void wxUnix2DosFilename(wchar_t *s) { wxDoUnix2DosFilename(s); }
  863. #endif // #if WXWIN_COMPATIBILITY_2_8
  864. // Concatenate two files to form third
  865. bool
  866. wxConcatFiles (const wxString& file1, const wxString& file2, const wxString& file3)
  867. {
  868. #if wxUSE_FILE
  869. wxFile in1(file1), in2(file2);
  870. wxTempFile out(file3);
  871. if ( !in1.IsOpened() || !in2.IsOpened() || !out.IsOpened() )
  872. return false;
  873. ssize_t ofs;
  874. unsigned char buf[1024];
  875. for( int i=0; i<2; i++)
  876. {
  877. wxFile *in = i==0 ? &in1 : &in2;
  878. do{
  879. if ( (ofs = in->Read(buf,WXSIZEOF(buf))) == wxInvalidOffset ) return false;
  880. if ( ofs > 0 )
  881. if ( !out.Write(buf,ofs) )
  882. return false;
  883. } while ( ofs == (ssize_t)WXSIZEOF(buf) );
  884. }
  885. return out.Commit();
  886. #else
  887. wxUnusedVar(file1);
  888. wxUnusedVar(file2);
  889. wxUnusedVar(file3);
  890. return false;
  891. #endif
  892. }
  893. // helper of generic implementation of wxCopyFile()
  894. #if !(defined(__WIN32__) || defined(__OS2__) || defined(__PALMOS__)) && \
  895. wxUSE_FILE
  896. static bool
  897. wxDoCopyFile(wxFile& fileIn,
  898. const wxStructStat& fbuf,
  899. const wxString& filenameDst,
  900. bool overwrite)
  901. {
  902. // reset the umask as we want to create the file with exactly the same
  903. // permissions as the original one
  904. wxCHANGE_UMASK(0);
  905. // create file2 with the same permissions than file1 and open it for
  906. // writing
  907. wxFile fileOut;
  908. if ( !fileOut.Create(filenameDst, overwrite, fbuf.st_mode & 0777) )
  909. return false;
  910. // copy contents of file1 to file2
  911. char buf[4096];
  912. for ( ;; )
  913. {
  914. ssize_t count = fileIn.Read(buf, WXSIZEOF(buf));
  915. if ( count == wxInvalidOffset )
  916. return false;
  917. // end of file?
  918. if ( !count )
  919. break;
  920. if ( fileOut.Write(buf, count) < (size_t)count )
  921. return false;
  922. }
  923. // we can expect fileIn to be closed successfully, but we should ensure
  924. // that fileOut was closed as some write errors (disk full) might not be
  925. // detected before doing this
  926. return fileIn.Close() && fileOut.Close();
  927. }
  928. #endif // generic implementation of wxCopyFile
  929. // Copy files
  930. bool
  931. wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
  932. {
  933. #if defined(__WIN32__) && !defined(__WXMICROWIN__)
  934. // CopyFile() copies file attributes and modification time too, so use it
  935. // instead of our code if available
  936. //
  937. // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
  938. if ( !::CopyFile(file1.fn_str(), file2.fn_str(), !overwrite) )
  939. {
  940. wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
  941. file1.c_str(), file2.c_str());
  942. return false;
  943. }
  944. #elif defined(__OS2__)
  945. if ( ::DosCopy(file1.c_str(), file2.c_str(), overwrite ? DCPY_EXISTING : 0) != 0 )
  946. return false;
  947. #elif defined(__PALMOS__)
  948. // TODO with http://www.palmos.com/dev/support/docs/protein_books/Memory_Databases_Files/
  949. return false;
  950. #elif wxUSE_FILE // !Win32
  951. wxStructStat fbuf;
  952. // get permissions of file1
  953. if ( wxStat( file1.c_str(), &fbuf) != 0 )
  954. {
  955. // the file probably doesn't exist or we haven't the rights to read
  956. // from it anyhow
  957. wxLogSysError(_("Impossible to get permissions for file '%s'"),
  958. file1.c_str());
  959. return false;
  960. }
  961. // open file1 for reading
  962. wxFile fileIn(file1, wxFile::read);
  963. if ( !fileIn.IsOpened() )
  964. return false;
  965. // remove file2, if it exists. This is needed for creating
  966. // file2 with the correct permissions in the next step
  967. if ( wxFileExists(file2) && (!overwrite || !wxRemoveFile(file2)))
  968. {
  969. wxLogSysError(_("Impossible to overwrite the file '%s'"),
  970. file2.c_str());
  971. return false;
  972. }
  973. wxDoCopyFile(fileIn, fbuf, file2, overwrite);
  974. #if defined(__WXMAC__) || defined(__WXCOCOA__)
  975. // copy the resource fork of the file too if it's present
  976. wxString pathRsrcOut;
  977. wxFile fileRsrcIn;
  978. {
  979. // suppress error messages from this block as resource forks don't have
  980. // to exist
  981. wxLogNull noLog;
  982. // it's not enough to check for file existence: it always does on HFS
  983. // but is empty for files without resources
  984. if ( fileRsrcIn.Open(file1 + wxT("/..namedfork/rsrc")) &&
  985. fileRsrcIn.Length() > 0 )
  986. {
  987. // we must be using HFS or another filesystem with resource fork
  988. // support, suppose that destination file system also is HFS[-like]
  989. pathRsrcOut = file2 + wxT("/..namedfork/rsrc");
  990. }
  991. else // check if we have resource fork in separate file (non-HFS case)
  992. {
  993. wxFileName fnRsrc(file1);
  994. fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
  995. fileRsrcIn.Close();
  996. if ( fileRsrcIn.Open( fnRsrc.GetFullPath() ) )
  997. {
  998. fnRsrc = file2;
  999. fnRsrc.SetName(wxT("._") + fnRsrc.GetName());
  1000. pathRsrcOut = fnRsrc.GetFullPath();
  1001. }
  1002. }
  1003. }
  1004. if ( !pathRsrcOut.empty() )
  1005. {
  1006. if ( !wxDoCopyFile(fileRsrcIn, fbuf, pathRsrcOut, overwrite) )
  1007. return false;
  1008. }
  1009. #endif // wxMac || wxCocoa
  1010. #if !defined(__VISAGECPP__) && !defined(__WXMAC__) || defined(__UNIX__)
  1011. // no chmod in VA. Should be some permission API for HPFS386 partitions
  1012. // however
  1013. if ( chmod(file2.fn_str(), fbuf.st_mode) != 0 )
  1014. {
  1015. wxLogSysError(_("Impossible to set permissions for the file '%s'"),
  1016. file2.c_str());
  1017. return false;
  1018. }
  1019. #endif // OS/2 || Mac
  1020. #else // !Win32 && ! wxUSE_FILE
  1021. // impossible to simulate with wxWidgets API
  1022. wxUnusedVar(file1);
  1023. wxUnusedVar(file2);
  1024. wxUnusedVar(overwrite);
  1025. return false;
  1026. #endif // __WXMSW__ && __WIN32__
  1027. return true;
  1028. }
  1029. bool
  1030. wxRenameFile(const wxString& file1, const wxString& file2, bool overwrite)
  1031. {
  1032. if ( !overwrite && wxFileExists(file2) )
  1033. {
  1034. wxLogSysError
  1035. (
  1036. _("Failed to rename the file '%s' to '%s' because the destination file already exists."),
  1037. file1.c_str(), file2.c_str()
  1038. );
  1039. return false;
  1040. }
  1041. #if !defined(__WXWINCE__) && !defined(__WXPALMOS__)
  1042. // Normal system call
  1043. if ( wxRename (file1, file2) == 0 )
  1044. return true;
  1045. #endif
  1046. // Try to copy
  1047. if (wxCopyFile(file1, file2, overwrite)) {
  1048. wxRemoveFile(file1);
  1049. return true;
  1050. }
  1051. // Give up
  1052. return false;
  1053. }
  1054. bool wxRemoveFile(const wxString& file)
  1055. {
  1056. #if defined(__VISUALC__) \
  1057. || defined(__BORLANDC__) \
  1058. || defined(__WATCOMC__) \
  1059. || defined(__DMC__) \
  1060. || defined(__GNUWIN32__) \
  1061. || (defined(__MWERKS__) && defined(__MSL__))
  1062. int res = wxRemove(file);
  1063. #elif defined(__WXMAC__)
  1064. int res = unlink(file.fn_str());
  1065. #elif defined(__WXPALMOS__)
  1066. int res = 1;
  1067. // TODO with VFSFileDelete()
  1068. #else
  1069. int res = unlink(file.fn_str());
  1070. #endif
  1071. return res == 0;
  1072. }
  1073. bool wxMkdir(const wxString& dir, int perm)
  1074. {
  1075. #if defined(__WXPALMOS__)
  1076. return false;
  1077. #else
  1078. #if defined(__WXMAC__) && !defined(__UNIX__)
  1079. if ( mkdir(dir.fn_str(), 0) != 0 )
  1080. // assume mkdir() has 2 args on non Windows-OS/2 platforms and on Windows too
  1081. // for the GNU compiler
  1082. #elif (!(defined(__WXMSW__) || defined(__OS2__) || defined(__DOS__))) || \
  1083. (defined(__GNUWIN32__) && !defined(__MINGW32__)) || \
  1084. defined(__WINE__) || defined(__WXMICROWIN__)
  1085. const wxChar *dirname = dir.c_str();
  1086. #if defined(MSVCRT)
  1087. wxUnusedVar(perm);
  1088. if ( mkdir(wxFNCONV(dirname)) != 0 )
  1089. #else
  1090. if ( mkdir(wxFNCONV(dirname), perm) != 0 )
  1091. #endif
  1092. #elif defined(__OS2__)
  1093. wxUnusedVar(perm);
  1094. if (::DosCreateDir(dir.c_str(), NULL) != 0) // enhance for EAB's??
  1095. #elif defined(__DOS__)
  1096. const wxChar *dirname = dir.c_str();
  1097. #if defined(__WATCOMC__)
  1098. (void)perm;
  1099. if ( wxMkDir(wxFNSTRINGCAST wxFNCONV(dirname)) != 0 )
  1100. #elif defined(__DJGPP__)
  1101. if ( mkdir(wxFNCONV(dirname), perm) != 0 )
  1102. #else
  1103. #error "Unsupported DOS compiler!"
  1104. #endif
  1105. #else // !MSW, !DOS and !OS/2 VAC++
  1106. wxUnusedVar(perm);
  1107. #ifdef __WXWINCE__
  1108. if ( CreateDirectory(dir, NULL) == 0 )
  1109. #else
  1110. if ( wxMkDir(dir.fn_str()) != 0 )
  1111. #endif
  1112. #endif // !MSW/MSW
  1113. {
  1114. wxLogSysError(_("Directory '%s' couldn't be created"), dir);
  1115. return false;
  1116. }
  1117. return true;
  1118. #endif // PALMOS/!PALMOS
  1119. }
  1120. bool wxRmdir(const wxString& dir, int WXUNUSED(flags))
  1121. {
  1122. #if defined(__VMS__)
  1123. return false; //to be changed since rmdir exists in VMS7.x
  1124. #elif defined(__WXPALMOS__)
  1125. // TODO with VFSFileRename()
  1126. return false;
  1127. #else
  1128. #if defined(__OS2__)
  1129. if ( ::DosDeleteDir(dir.c_str()) != 0 )
  1130. #elif defined(__WXWINCE__)
  1131. if ( RemoveDirectory(dir) == 0 )
  1132. #else
  1133. if ( wxRmDir(dir.fn_str()) != 0 )
  1134. #endif
  1135. {
  1136. wxLogSysError(_("Directory '%s' couldn't be deleted"), dir);
  1137. return false;
  1138. }
  1139. return true;
  1140. #endif // PALMOS/!PALMOS
  1141. }
  1142. // does the path exists? (may have or not '/' or '\\' at the end)
  1143. bool wxDirExists(const wxString& pathName)
  1144. {
  1145. wxString strPath(pathName);
  1146. #if defined(__WINDOWS__) || defined(__OS2__)
  1147. // Windows fails to find directory named "c:\dir\" even if "c:\dir" exists,
  1148. // so remove all trailing backslashes from the path - but don't do this for
  1149. // the paths "d:\" (which are different from "d:") nor for just "\"
  1150. while ( wxEndsWithPathSeparator(strPath) )
  1151. {
  1152. size_t len = strPath.length();
  1153. if ( len == 1 || (len == 3 && strPath[len - 2] == _T(':')) )
  1154. break;
  1155. strPath.Truncate(len - 1);
  1156. }
  1157. #endif // __WINDOWS__
  1158. #ifdef __OS2__
  1159. // OS/2 can't handle "d:", it wants either "d:\" or "d:."
  1160. if (strPath.length() == 2 && strPath[1u] == _T(':'))
  1161. strPath << _T('.');
  1162. #endif
  1163. #if defined(__WXPALMOS__)
  1164. return false;
  1165. #elif defined(__WIN32__) && !defined(__WXMICROWIN__)
  1166. // stat() can't cope with network paths
  1167. DWORD ret = ::GetFileAttributes(strPath.fn_str());
  1168. return (ret != INVALID_FILE_ATTRIBUTES) && (ret & FILE_ATTRIBUTE_DIRECTORY);
  1169. #elif defined(__OS2__)
  1170. FILESTATUS3 Info = {{0}};
  1171. APIRET rc = ::DosQueryPathInfo((PSZ)(WXSTRINGCAST strPath), FIL_STANDARD,
  1172. (void*) &Info, sizeof(FILESTATUS3));
  1173. return ((rc == NO_ERROR) && (Info.attrFile & FILE_DIRECTORY)) ||
  1174. (rc == ERROR_SHARING_VIOLATION);
  1175. // If we got a sharing violation, there must be something with this name.
  1176. #else // !__WIN32__
  1177. wxStructStat st;
  1178. #ifndef __VISAGECPP__
  1179. return wxStat(strPath.c_str(), &st) == 0 && ((st.st_mode & S_IFMT) == S_IFDIR);
  1180. #else
  1181. // S_IFMT not supported in VA compilers.. st_mode is a 2byte value only
  1182. return wxStat(strPath.c_str(), &st) == 0 && (st.st_mode == S_IFDIR);
  1183. #endif
  1184. #endif // __WIN32__/!__WIN32__
  1185. }
  1186. #if WXWIN_COMPATIBILITY_2_8
  1187. // Get a temporary filename, opening and closing the file.
  1188. wxChar *wxGetTempFileName(const wxString& prefix, wxChar *buf)
  1189. {
  1190. wxString filename;
  1191. if ( !wxGetTempFileName(prefix, filename) )
  1192. return NULL;
  1193. if ( buf )
  1194. #ifdef _PACC_VER
  1195. // work around the PalmOS pacc compiler bug
  1196. wxStrcpy(buf, filename.data());
  1197. #else
  1198. wxStrcpy(buf, filename);
  1199. #endif
  1200. else
  1201. buf = MYcopystring(filename);
  1202. return buf;
  1203. }
  1204. bool wxGetTempFileName(const wxString& prefix, wxString& buf)
  1205. {
  1206. #if wxUSE_FILE
  1207. buf = wxFileName::CreateTempFileName(prefix);
  1208. return !buf.empty();
  1209. #else // !wxUSE_FILE
  1210. wxUnusedVar(prefix);
  1211. wxUnusedVar(buf);
  1212. return false;
  1213. #endif // wxUSE_FILE/!wxUSE_FILE
  1214. }
  1215. #endif // #if WXWIN_COMPATIBILITY_2_8
  1216. // Get first file name matching given wild card.
  1217. static wxDir *gs_dir = NULL;
  1218. static wxString gs_dirPath;
  1219. wxString wxFindFirstFile(const wxString& spec, int flags)
  1220. {
  1221. wxFileName::SplitPath(spec, &gs_dirPath, NULL, NULL);
  1222. if ( gs_dirPath.empty() )
  1223. gs_dirPath = wxT(".");
  1224. if ( !wxEndsWithPathSeparator(gs_dirPath ) )
  1225. gs_dirPath << wxFILE_SEP_PATH;
  1226. delete gs_dir; // can be NULL, this is ok
  1227. gs_dir = new wxDir(gs_dirPath);
  1228. if ( !gs_dir->IsOpened() )
  1229. {
  1230. wxLogSysError(_("Can not enumerate files '%s'"), spec);
  1231. return wxEmptyString;
  1232. }
  1233. int dirFlags;
  1234. switch (flags)
  1235. {
  1236. case wxDIR: dirFlags = wxDIR_DIRS; break;
  1237. case wxFILE: dirFlags = wxDIR_FILES; break;
  1238. default: dirFlags = wxDIR_DIRS | wxDIR_FILES; break;
  1239. }
  1240. wxString result;
  1241. gs_dir->GetFirst(&result, wxFileNameFromPath(spec), dirFlags);
  1242. if ( result.empty() )
  1243. {
  1244. wxDELETE(gs_dir);
  1245. return result;
  1246. }
  1247. return gs_dirPath + result;
  1248. }
  1249. wxString wxFindNextFile()
  1250. {
  1251. wxCHECK_MSG( gs_dir, "", "You must call wxFindFirstFile before!" );
  1252. wxString result;
  1253. gs_dir->GetNext(&result);
  1254. if ( result.empty() )
  1255. {
  1256. wxDELETE(gs_dir);
  1257. return result;
  1258. }
  1259. return gs_dirPath + result;
  1260. }
  1261. // Get current working directory.
  1262. // If buf is NULL, allocates space using new, else copies into buf.
  1263. // wxGetWorkingDirectory() is obsolete, use wxGetCwd()
  1264. // wxDoGetCwd() is their common core to be moved
  1265. // to wxGetCwd() once wxGetWorkingDirectory() will be removed.
  1266. // Do not expose wxDoGetCwd in headers!
  1267. wxChar *wxDoGetCwd(wxChar *buf, int sz)
  1268. {
  1269. #if defined(__WXPALMOS__)
  1270. // TODO
  1271. if(buf && sz>0) buf[0] = _T('\0');
  1272. return buf;
  1273. #elif defined(__WXWINCE__)
  1274. // TODO
  1275. if(buf && sz>0) buf[0] = _T('\0');
  1276. return buf;
  1277. #else
  1278. if ( !buf )
  1279. {
  1280. buf = new wxChar[sz + 1];
  1281. }
  1282. bool ok wxDUMMY_INITIALIZE(false);
  1283. // for the compilers which have Unicode version of _getcwd(), call it
  1284. // directly, for the others call the ANSI version and do the translation
  1285. #if !wxUSE_UNICODE
  1286. #define cbuf buf
  1287. #else // wxUSE_UNICODE
  1288. bool needsANSI = true;
  1289. #if !defined(HAVE_WGETCWD) || wxUSE_UNICODE_MSLU
  1290. char cbuf[_MAXPATHLEN];
  1291. #endif
  1292. #ifdef HAVE_WGETCWD
  1293. #if wxUSE_UNICODE_MSLU
  1294. if ( wxGetOsVersion() != wxOS_WINDOWS_9X )
  1295. #else
  1296. char *cbuf = NULL; // never really used because needsANSI will always be false
  1297. #endif
  1298. {
  1299. ok = _wgetcwd(buf, sz) != NULL;
  1300. needsANSI = false;
  1301. }
  1302. #endif
  1303. if ( needsANSI )
  1304. #endif // wxUSE_UNICODE
  1305. {
  1306. #if defined(_MSC_VER) || defined(__MINGW32__)
  1307. ok = _getcwd(cbuf, sz) != NULL;
  1308. #elif defined(__OS2__)
  1309. APIRET rc;
  1310. ULONG ulDriveNum = 0;
  1311. ULONG ulDriveMap = 0;
  1312. rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
  1313. ok = rc == 0;
  1314. if (ok)
  1315. {
  1316. sz -= 3;
  1317. rc = ::DosQueryCurrentDir( 0 // current drive
  1318. ,(PBYTE)cbuf + 3
  1319. ,(PULONG)&sz
  1320. );
  1321. cbuf[0] = char('A' + (ulDriveNum - 1));
  1322. cbuf[1] = ':';
  1323. cbuf[2] = '\\';
  1324. ok = rc == 0;
  1325. }
  1326. #else // !Win32/VC++ !Mac !OS2
  1327. ok = getcwd(cbuf, sz) != NULL;
  1328. #endif // platform
  1329. #if wxUSE_UNICODE
  1330. // finally convert the result to Unicode if needed
  1331. wxConvFile.MB2WC(buf, cbuf, sz);
  1332. #endif // wxUSE_UNICODE
  1333. }
  1334. if ( !ok )
  1335. {
  1336. wxLogSysError(_("Failed to get the working directory"));
  1337. // VZ: the old code used to return "." on error which didn't make any
  1338. // sense at all to me - empty string is a better error indicator
  1339. // (NULL might be even better but I'm afraid this could lead to
  1340. // problems with the old code assuming the return is never NULL)
  1341. buf[0] = _T('\0');
  1342. }
  1343. else // ok, but we might need to massage the path into the right format
  1344. {
  1345. #ifdef __DJGPP__
  1346. // VS: DJGPP is a strange mix of DOS and UNIX API and returns paths
  1347. // with / deliminers. We don't like that.
  1348. for (wxChar *ch = buf; *ch; ch++)
  1349. {
  1350. if (*ch == wxT('/'))
  1351. *ch = wxT('\\');
  1352. }
  1353. #endif // __DJGPP__
  1354. // MBN: we hope that in the case the user is compiling a GTK+/Motif app,
  1355. // he needs Unix as opposed to Win32 pathnames
  1356. #if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
  1357. // another example of DOS/Unix mix (Cygwin)
  1358. wxString pathUnix = buf;
  1359. #if wxUSE_UNICODE
  1360. char bufA[_MAXPATHLEN];
  1361. cygwin_conv_to_full_win32_path(pathUnix.mb_str(wxConvFile), bufA);
  1362. wxConvFile.MB2WC(buf, bufA, sz);
  1363. #else
  1364. cygwin_conv_to_full_win32_path(pathUnix, buf);
  1365. #endif // wxUSE_UNICODE
  1366. #endif // __CYGWIN__
  1367. }
  1368. return buf;
  1369. #if !wxUSE_UNICODE
  1370. #undef cbuf
  1371. #endif
  1372. #endif
  1373. // __WXWINCE__
  1374. }
  1375. #if WXWIN_COMPATIBILITY_2_6
  1376. wxChar *wxGetWorkingDirectory(wxChar *buf, int sz)
  1377. {
  1378. return wxDoGetCwd(buf,sz);
  1379. }
  1380. #endif // WXWIN_COMPATIBILITY_2_6
  1381. wxString wxGetCwd()
  1382. {
  1383. wxString str;
  1384. wxDoGetCwd(wxStringBuffer(str, _MAXPATHLEN), _MAXPATHLEN);
  1385. return str;
  1386. }
  1387. bool wxSetWorkingDirectory(const wxString& d)
  1388. {
  1389. #if defined(__OS2__)
  1390. if (d[1] == ':')
  1391. {
  1392. ::DosSetDefaultDisk(wxToupper(d[0]) - _T('A') + 1);
  1393. // do not call DosSetCurrentDir when just changing drive,
  1394. // since it requires e.g. "d:." instead of "d:"!
  1395. if (d.length() == 2)
  1396. return true;
  1397. }
  1398. return (::DosSetCurrentDir(d.c_str()) == 0);
  1399. #elif defined(__UNIX__) || defined(__WXMAC__) || defined(__DOS__)
  1400. return (chdir(wxFNSTRINGCAST d.fn_str()) == 0);
  1401. #elif defined(__WINDOWS__)
  1402. #ifdef __WIN32__
  1403. #ifdef __WXWINCE__
  1404. // No equivalent in WinCE
  1405. wxUnusedVar(d);
  1406. return false;
  1407. #else
  1408. return (bool)(SetCurrentDirectory(d.fn_str()) != 0);
  1409. #endif
  1410. #else
  1411. // Must change drive, too.
  1412. bool isDriveSpec = ((strlen(d) > 1) && (d[1] == ':'));
  1413. if (isDriveSpec)
  1414. {
  1415. wxChar firstChar = d[0];
  1416. // To upper case
  1417. if (firstChar > 90)
  1418. firstChar = firstChar - 32;
  1419. // To a drive number
  1420. unsigned int driveNo = firstChar - 64;
  1421. if (driveNo > 0)
  1422. {
  1423. unsigned int noDrives;
  1424. _dos_setdrive(driveNo, &noDrives);
  1425. }
  1426. }
  1427. bool success = (chdir(WXSTRINGCAST d) == 0);
  1428. return success;
  1429. #endif
  1430. #endif
  1431. }
  1432. // Get the OS directory if appropriate (such as the Windows directory).
  1433. // On non-Windows platform, probably just return the empty string.
  1434. wxString wxGetOSDirectory()
  1435. {
  1436. #ifdef __WXWINCE__
  1437. return wxString(wxT("\\Windows"));
  1438. #elif defined(__WINDOWS__) && !defined(__WXMICROWIN__)
  1439. wxChar buf[256];
  1440. GetWindowsDirectory(buf, 256);
  1441. return wxString(buf);
  1442. #elif defined(__WXMAC__) && wxOSX_USE_CARBON
  1443. return wxMacFindFolder(kOnSystemDisk, 'macs', false);
  1444. #else
  1445. return wxEmptyString;
  1446. #endif
  1447. }
  1448. bool wxEndsWithPathSeparator(const wxString& filename)
  1449. {
  1450. return !filename.empty() && wxIsPathSeparator(filename.Last());
  1451. }
  1452. // find a file in a list of directories, returns false if not found
  1453. bool wxFindFileInPath(wxString *pStr, const wxString& szPath, const wxString& szFile)
  1454. {
  1455. // we assume that it's not empty
  1456. wxCHECK_MSG( !szFile.empty(), false,
  1457. _T("empty file name in wxFindFileInPath"));
  1458. // skip path separator in the beginning of the file name if present
  1459. wxString szFile2;
  1460. if ( wxIsPathSeparator(szFile[0u]) )
  1461. szFile2 = szFile.Mid(1);
  1462. else
  1463. szFile2 = szFile;
  1464. wxStringTokenizer tkn(szPath, wxPATH_SEP);
  1465. while ( tkn.HasMoreTokens() )
  1466. {
  1467. wxString strFile = tkn.GetNextToken();
  1468. if ( !wxEndsWithPathSeparator(strFile) )
  1469. strFile += wxFILE_SEP_PATH;
  1470. strFile += szFile2;
  1471. if ( wxFileExists(strFile) )
  1472. {
  1473. *pStr = strFile;
  1474. return true;
  1475. }
  1476. }
  1477. return false;
  1478. }
  1479. #if WXWIN_COMPATIBILITY_2_8
  1480. void WXDLLIMPEXP_BASE wxSplitPath(const wxString& fileName,
  1481. wxString *pstrPath,
  1482. wxString *pstrName,
  1483. wxString *pstrExt)
  1484. {
  1485. wxFileName::SplitPath(fileName, pstrPath, pstrName, pstrExt);
  1486. }
  1487. #endif // #if WXWIN_COMPATIBILITY_2_8
  1488. #if wxUSE_DATETIME
  1489. time_t WXDLLIMPEXP_BASE wxFileModificationTime(const wxString& filename)
  1490. {
  1491. wxDateTime mtime;
  1492. if ( !wxFileName(filename).GetTimes(NULL, &mtime, NULL) )
  1493. return (time_t)-1;
  1494. return mtime.GetTicks();
  1495. }
  1496. #endif // wxUSE_DATETIME
  1497. // Parses the filterStr, returning the number of filters.
  1498. // Returns 0 if none or if there's a problem.
  1499. // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpeg"
  1500. int WXDLLIMPEXP_BASE wxParseCommonDialogsFilter(const wxString& filterStr,
  1501. wxArrayString& descriptions,
  1502. wxArrayString& filters)
  1503. {
  1504. descriptions.Clear();
  1505. filters.Clear();
  1506. wxString str(filterStr);
  1507. wxString description, filter;
  1508. int pos = 0;
  1509. while( pos != wxNOT_FOUND )
  1510. {
  1511. pos = str.Find(wxT('|'));
  1512. if ( pos == wxNOT_FOUND )
  1513. {
  1514. // if there are no '|'s at all in the string just take the entire
  1515. // string as filter and make description empty for later autocompletion
  1516. if ( filters.IsEmpty() )
  1517. {
  1518. descriptions.Add(wxEmptyString);
  1519. filters.Add(filterStr);
  1520. }
  1521. else
  1522. {
  1523. wxFAIL_MSG( _T("missing '|' in the wildcard string!") );
  1524. }
  1525. break;
  1526. }
  1527. description = str.Left(pos);
  1528. str = str.Mid(pos + 1);
  1529. pos = str.Find(wxT('|'));
  1530. if ( pos == wxNOT_FOUND )
  1531. {
  1532. filter = str;
  1533. }
  1534. else
  1535. {
  1536. filter = str.Left(pos);
  1537. str = str.Mid(pos + 1);
  1538. }
  1539. descriptions.Add(description);
  1540. filters.Add(filter);
  1541. }
  1542. #if defined(__WXMOTIF__)
  1543. // split it so there is one wildcard per entry
  1544. for( size_t i = 0 ; i < descriptions.GetCount() ; i++ )
  1545. {
  1546. pos = filters[i].Find(wxT(';'));
  1547. if (pos != wxNOT_FOUND)
  1548. {
  1549. // first split only filters
  1550. descriptions.Insert(descriptions[i],i+1);
  1551. filters.Insert(filters[i].Mid(pos+1),i+1);
  1552. filters[i]=filters[i].Left(pos);
  1553. // autoreplace new filter in description with pattern:
  1554. // C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
  1555. // cause split into:
  1556. // C/C++ Files(*.cpp)|*.cpp
  1557. // C/C++ Files(*.c;*.h)|*.c;*.h
  1558. // and next iteration cause another split into:
  1559. // C/C++ Files(*.cpp)|*.cpp
  1560. // C/C++ Files(*.c)|*.c
  1561. // C/C++ Files(*.h)|*.h
  1562. for ( size_t k=i;k<i+2;k++ )
  1563. {
  1564. pos = descriptions[k].Find(filters[k]);
  1565. if (pos != wxNOT_FOUND)
  1566. {
  1567. wxString before = descriptions[k].Left(pos);
  1568. wxString after = descriptions[k].Mid(pos+filters[k].Len());
  1569. pos = before.Find(_T('('),true);
  1570. if (pos>before.Find(_T(')'),true))
  1571. {
  1572. before =

Large files files are truncated, but you can click here to view the full file