PageRenderTime 71ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/src/common/filefn.cpp

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

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