PageRenderTime 58ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/wxWidgets-2.9.1/src/common/filefn.cpp

http://gamekit.googlecode.com/
C++ | 2074 lines | 1822 code | 99 blank | 153 comment | 159 complexity | e8805ec4b78667f4fff42b073ca2b457 MD5 | raw file
Possible License(s): BSD-2-Clause, LGPL-2.0, AGPL-3.0, BSD-3-Clause, GPL-2.0, LGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-2.1, MIT

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

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