]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/filesys.cpp
Misc validity fixes to samples/xrc/rc/*.xrc.
[wxWidgets.git] / src / common / filesys.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: src/common/filesys.cpp
3// Purpose: wxFileSystem class - interface for opening files
4// Author: Vaclav Slavik
5// Copyright: (c) 1999 Vaclav Slavik
6// Licence: wxWindows licence
7/////////////////////////////////////////////////////////////////////////////
8
9#include "wx/wxprec.h"
10
11#ifdef __BORLANDC__
12 #pragma hdrstop
13#endif
14
15
16#if wxUSE_FILESYSTEM
17
18#include "wx/filesys.h"
19
20#ifndef WX_PRECOMP
21 #include "wx/log.h"
22 #include "wx/module.h"
23#endif
24
25#include "wx/sysopt.h"
26#include "wx/wfstream.h"
27#include "wx/mimetype.h"
28#include "wx/filename.h"
29#include "wx/tokenzr.h"
30#include "wx/uri.h"
31#include "wx/private/fileback.h"
32
33// ----------------------------------------------------------------------------
34// wxFSFile
35// ----------------------------------------------------------------------------
36
37const wxString& wxFSFile::GetMimeType() const
38{
39 if ( m_MimeType.empty() && !m_Location.empty() )
40 {
41 wxConstCast(this, wxFSFile)->m_MimeType =
42 wxFileSystemHandler::GetMimeTypeFromExt(m_Location);
43 }
44
45 return m_MimeType;
46}
47
48// ----------------------------------------------------------------------------
49// wxFileSystemHandler
50// ----------------------------------------------------------------------------
51
52IMPLEMENT_ABSTRACT_CLASS(wxFileSystemHandler, wxObject)
53
54
55/* static */
56wxString wxFileSystemHandler::GetMimeTypeFromExt(const wxString& location)
57{
58 wxString ext, mime;
59 wxString loc = GetRightLocation(location);
60 wxChar c;
61 int l = loc.length(), l2;
62
63 l2 = l;
64 for (int i = l-1; i >= 0; i--)
65 {
66 c = loc[(unsigned int) i];
67 if ( c == wxT('#') )
68 l2 = i + 1;
69 if ( c == wxT('.') )
70 {
71 ext = loc.Right(l2-i-1);
72 break;
73 }
74 if ( (c == wxT('/')) || (c == wxT('\\')) || (c == wxT(':')) )
75 return wxEmptyString;
76 }
77
78#if wxUSE_MIMETYPE
79 static bool s_MinimalMimeEnsured = false;
80
81 // Don't use mime types manager if the application doesn't need it and it would be
82 // cause an unacceptable delay, especially on startup.
83#if wxUSE_SYSTEM_OPTIONS
84 if ( !wxSystemOptions::GetOptionInt(wxT("filesys.no-mimetypesmanager")) )
85#endif
86 {
87 if (!s_MinimalMimeEnsured)
88 {
89 static const wxFileTypeInfo fallbacks[] =
90 {
91 wxFileTypeInfo(wxT("image/jpeg"),
92 wxEmptyString,
93 wxEmptyString,
94 wxT("JPEG image (from fallback)"),
95 wxT("jpg"), wxT("jpeg"), wxT("JPG"), wxT("JPEG"), wxNullPtr),
96 wxFileTypeInfo(wxT("image/gif"),
97 wxEmptyString,
98 wxEmptyString,
99 wxT("GIF image (from fallback)"),
100 wxT("gif"), wxT("GIF"), wxNullPtr),
101 wxFileTypeInfo(wxT("image/png"),
102 wxEmptyString,
103 wxEmptyString,
104 wxT("PNG image (from fallback)"),
105 wxT("png"), wxT("PNG"), wxNullPtr),
106 wxFileTypeInfo(wxT("image/bmp"),
107 wxEmptyString,
108 wxEmptyString,
109 wxT("windows bitmap image (from fallback)"),
110 wxT("bmp"), wxT("BMP"), wxNullPtr),
111 wxFileTypeInfo(wxT("text/html"),
112 wxEmptyString,
113 wxEmptyString,
114 wxT("HTML document (from fallback)"),
115 wxT("htm"), wxT("html"), wxT("HTM"), wxT("HTML"), wxNullPtr),
116 // must terminate the table with this!
117 wxFileTypeInfo()
118 };
119 wxTheMimeTypesManager->AddFallbacks(fallbacks);
120 s_MinimalMimeEnsured = true;
121 }
122
123 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
124 if ( !ft || !ft -> GetMimeType(&mime) )
125 {
126 mime = wxEmptyString;
127 }
128
129 delete ft;
130
131 return mime;
132 }
133 else
134#endif
135 {
136 if ( ext.IsSameAs(wxT("htm"), false) || ext.IsSameAs(wxT("html"), false) )
137 return wxT("text/html");
138 if ( ext.IsSameAs(wxT("jpg"), false) || ext.IsSameAs(wxT("jpeg"), false) )
139 return wxT("image/jpeg");
140 if ( ext.IsSameAs(wxT("gif"), false) )
141 return wxT("image/gif");
142 if ( ext.IsSameAs(wxT("png"), false) )
143 return wxT("image/png");
144 if ( ext.IsSameAs(wxT("bmp"), false) )
145 return wxT("image/bmp");
146 return wxEmptyString;
147 }
148}
149
150
151
152/* static */
153wxString wxFileSystemHandler::GetProtocol(const wxString& location)
154{
155 wxString s = wxEmptyString;
156 int i, l = location.length();
157 bool fnd = false;
158
159 for (i = l-1; (i >= 0) && ((location[i] != wxT('#')) || (!fnd)); i--) {
160 if ((location[i] == wxT(':')) && (i != 1 /*win: C:\path*/)) fnd = true;
161 }
162 if (!fnd) return wxT("file");
163 for (++i; (i < l) && (location[i] != wxT(':')); i++) s << location[i];
164 return s;
165}
166
167
168/* static */
169wxString wxFileSystemHandler::GetLeftLocation(const wxString& location)
170{
171 int i;
172 bool fnd = false;
173
174 for (i = location.length()-1; i >= 0; i--) {
175 if ((location[i] == wxT(':')) && (i != 1 /*win: C:\path*/)) fnd = true;
176 else if (fnd && (location[i] == wxT('#'))) return location.Left(i);
177 }
178 return wxEmptyString;
179}
180
181/* static */
182wxString wxFileSystemHandler::GetRightLocation(const wxString& location)
183{
184 int i, l = location.length();
185 int l2 = l + 1;
186
187 for (i = l-1;
188 (i >= 0) &&
189 ((location[i] != wxT(':')) || (i == 1) || (location[i-2] == wxT(':')));
190 i--)
191 {
192 if (location[i] == wxT('#')) l2 = i + 1;
193 }
194 if (i == 0) return wxEmptyString;
195 else return location.Mid(i + 1, l2 - i - 2);
196}
197
198/* static */
199wxString wxFileSystemHandler::GetAnchor(const wxString& location)
200{
201 wxChar c;
202 int l = location.length();
203
204 for (int i = l-1; i >= 0; i--) {
205 c = location[i];
206 if (c == wxT('#'))
207 return location.Right(l-i-1);
208 else if ((c == wxT('/')) || (c == wxT('\\')) || (c == wxT(':')))
209 return wxEmptyString;
210 }
211 return wxEmptyString;
212}
213
214
215wxString wxFileSystemHandler::FindFirst(const wxString& WXUNUSED(spec),
216 int WXUNUSED(flags))
217{
218 return wxEmptyString;
219}
220
221wxString wxFileSystemHandler::FindNext()
222{
223 return wxEmptyString;
224}
225
226//--------------------------------------------------------------------------------
227// wxLocalFSHandler
228//--------------------------------------------------------------------------------
229
230
231wxString wxLocalFSHandler::ms_root;
232
233bool wxLocalFSHandler::CanOpen(const wxString& location)
234{
235 return GetProtocol(location) == wxT("file");
236}
237
238wxFSFile* wxLocalFSHandler::OpenFile(wxFileSystem& WXUNUSED(fs), const wxString& location)
239{
240 // location has Unix path separators
241 wxString right = GetRightLocation(location);
242 wxFileName fn = wxFileSystem::URLToFileName(right);
243 wxString fullpath = ms_root + fn.GetFullPath();
244
245 if (!wxFileExists(fullpath))
246 return NULL;
247
248 // we need to check whether we can really read from this file, otherwise
249 // wxFSFile is not going to work
250#if wxUSE_FFILE
251 wxFFileInputStream *is = new wxFFileInputStream(fullpath);
252#elif wxUSE_FILE
253 wxFileInputStream *is = new wxFileInputStream(fullpath);
254#else
255#error One of wxUSE_FILE or wxUSE_FFILE must be set to 1 for wxFSHandler to work
256#endif
257 if ( !is->IsOk() )
258 {
259 delete is;
260 return NULL;
261 }
262
263 return new wxFSFile(is,
264 location,
265 wxEmptyString,
266 GetAnchor(location)
267#if wxUSE_DATETIME
268 ,wxDateTime(wxFileModificationTime(fullpath))
269#endif // wxUSE_DATETIME
270 );
271}
272
273wxString wxLocalFSHandler::FindFirst(const wxString& spec, int flags)
274{
275 wxFileName fn = wxFileSystem::URLToFileName(GetRightLocation(spec));
276 const wxString found = wxFindFirstFile(ms_root + fn.GetFullPath(), flags);
277 if ( found.empty() )
278 return found;
279 return wxFileSystem::FileNameToURL(found);
280}
281
282wxString wxLocalFSHandler::FindNext()
283{
284 const wxString found = wxFindNextFile();
285 if ( found.empty() )
286 return found;
287 return wxFileSystem::FileNameToURL(found);
288}
289
290
291
292//-----------------------------------------------------------------------------
293// wxFileSystem
294//-----------------------------------------------------------------------------
295
296IMPLEMENT_DYNAMIC_CLASS(wxFileSystem, wxObject)
297IMPLEMENT_ABSTRACT_CLASS(wxFSFile, wxObject)
298
299
300wxList wxFileSystem::m_Handlers;
301
302
303wxFileSystem::~wxFileSystem()
304{
305 WX_CLEAR_HASH_MAP(wxFSHandlerHash, m_LocalHandlers)
306}
307
308
309static wxString MakeCorrectPath(const wxString& path)
310{
311 wxString p(path);
312 wxString r;
313 int i, j, cnt;
314
315 cnt = p.length();
316 for (i = 0; i < cnt; i++)
317 if (p.GetChar(i) == wxT('\\')) p.GetWritableChar(i) = wxT('/'); // Want to be windows-safe
318
319 if (p.Left(2) == wxT("./")) { p = p.Mid(2); cnt -= 2; }
320
321 if (cnt < 3) return p;
322
323 r << p.GetChar(0) << p.GetChar(1);
324
325 // skip trailing ../.., if any
326 for (i = 2; i < cnt && (p.GetChar(i) == wxT('/') || p.GetChar(i) == wxT('.')); i++) r << p.GetChar(i);
327
328 // remove back references: translate dir1/../dir2 to dir2
329 for (; i < cnt; i++)
330 {
331 r << p.GetChar(i);
332 if (p.GetChar(i) == wxT('/') && p.GetChar(i-1) == wxT('.') && p.GetChar(i-2) == wxT('.'))
333 {
334 for (j = r.length() - 2; j >= 0 && r.GetChar(j) != wxT('/') && r.GetChar(j) != wxT(':'); j--) {}
335 if (j >= 0 && r.GetChar(j) != wxT(':'))
336 {
337 for (j = j - 1; j >= 0 && r.GetChar(j) != wxT('/') && r.GetChar(j) != wxT(':'); j--) {}
338 r.Remove(j + 1);
339 }
340 }
341 }
342
343 for (; i < cnt; i++) r << p.GetChar(i);
344
345 return r;
346}
347
348
349void wxFileSystem::ChangePathTo(const wxString& location, bool is_dir)
350{
351 int i, pathpos = -1;
352
353 m_Path = MakeCorrectPath(location);
354
355 if (is_dir)
356 {
357 if (!m_Path.empty() && m_Path.Last() != wxT('/') && m_Path.Last() != wxT(':'))
358 m_Path << wxT('/');
359 }
360
361 else
362 {
363 for (i = m_Path.length()-1; i >= 0; i--)
364 {
365 if (m_Path[(unsigned int) i] == wxT('/'))
366 {
367 if ((i > 1) && (m_Path[(unsigned int) (i-1)] == wxT('/')) && (m_Path[(unsigned int) (i-2)] == wxT(':')))
368 {
369 i -= 2;
370 continue;
371 }
372 else
373 {
374 pathpos = i;
375 break;
376 }
377 }
378 else if (m_Path[(unsigned int) i] == wxT(':')) {
379 pathpos = i;
380 break;
381 }
382 }
383 if (pathpos == -1)
384 {
385 for (i = 0; i < (int) m_Path.length(); i++)
386 {
387 if (m_Path[(unsigned int) i] == wxT(':'))
388 {
389 m_Path.Remove(i+1);
390 break;
391 }
392 }
393 if (i == (int) m_Path.length())
394 m_Path = wxEmptyString;
395 }
396 else
397 {
398 m_Path.Remove(pathpos+1);
399 }
400 }
401}
402
403
404
405wxFileSystemHandler *wxFileSystem::MakeLocal(wxFileSystemHandler *h)
406{
407 wxClassInfo *classinfo = h->GetClassInfo();
408
409 if (classinfo->IsDynamic())
410 {
411 wxFileSystemHandler*& local = m_LocalHandlers[classinfo];
412 if (!local)
413 local = (wxFileSystemHandler*)classinfo->CreateObject();
414 return local;
415 }
416 else
417 {
418 return h;
419 }
420}
421
422
423
424wxFSFile* wxFileSystem::OpenFile(const wxString& location, int flags)
425{
426 if ((flags & wxFS_READ) == 0)
427 return NULL;
428
429 wxString loc = MakeCorrectPath(location);
430 unsigned i, ln;
431 wxChar meta;
432 wxFSFile *s = NULL;
433 wxList::compatibility_iterator node;
434
435 ln = loc.length();
436 meta = 0;
437 for (i = 0; i < ln; i++)
438 {
439 switch ( loc[i].GetValue() )
440 {
441 case wxT('/') : case wxT(':') : case wxT('#') :
442 meta = loc[i];
443 break;
444 }
445 if (meta != 0) break;
446 }
447 m_LastName = wxEmptyString;
448
449 // try relative paths first :
450 if (meta != wxT(':'))
451 {
452 node = m_Handlers.GetFirst();
453 while (node)
454 {
455 wxFileSystemHandler *h = (wxFileSystemHandler*) node -> GetData();
456 if (h->CanOpen(m_Path + loc))
457 {
458 s = MakeLocal(h)->OpenFile(*this, m_Path + loc);
459 if (s) { m_LastName = m_Path + loc; break; }
460 }
461 node = node->GetNext();
462 }
463 }
464
465 // if failed, try absolute paths :
466 if (s == NULL)
467 {
468 node = m_Handlers.GetFirst();
469 while (node)
470 {
471 wxFileSystemHandler *h = (wxFileSystemHandler*) node->GetData();
472 if (h->CanOpen(loc))
473 {
474 s = MakeLocal(h)->OpenFile(*this, loc);
475 if (s) { m_LastName = loc; break; }
476 }
477 node = node->GetNext();
478 }
479 }
480
481 if (s && (flags & wxFS_SEEKABLE) != 0 && !s->GetStream()->IsSeekable())
482 {
483 wxBackedInputStream *stream;
484 stream = new wxBackedInputStream(s->DetachStream());
485 stream->FindLength();
486 s->SetStream(stream);
487 }
488
489 return (s);
490}
491
492
493
494wxString wxFileSystem::FindFirst(const wxString& spec, int flags)
495{
496 wxList::compatibility_iterator node;
497 wxString spec2(spec);
498
499 m_FindFileHandler = NULL;
500
501 for (int i = spec2.length()-1; i >= 0; i--)
502 if (spec2[(unsigned int) i] == wxT('\\')) spec2.GetWritableChar(i) = wxT('/'); // Want to be windows-safe
503
504 node = m_Handlers.GetFirst();
505 while (node)
506 {
507 wxFileSystemHandler *h = (wxFileSystemHandler*) node -> GetData();
508 if (h -> CanOpen(m_Path + spec2))
509 {
510 m_FindFileHandler = MakeLocal(h);
511 return m_FindFileHandler -> FindFirst(m_Path + spec2, flags);
512 }
513 node = node->GetNext();
514 }
515
516 node = m_Handlers.GetFirst();
517 while (node)
518 {
519 wxFileSystemHandler *h = (wxFileSystemHandler*) node -> GetData();
520 if (h -> CanOpen(spec2))
521 {
522 m_FindFileHandler = MakeLocal(h);
523 return m_FindFileHandler -> FindFirst(spec2, flags);
524 }
525 node = node->GetNext();
526 }
527
528 return wxEmptyString;
529}
530
531
532
533wxString wxFileSystem::FindNext()
534{
535 if (m_FindFileHandler == NULL) return wxEmptyString;
536 else return m_FindFileHandler -> FindNext();
537}
538
539bool wxFileSystem::FindFileInPath(wxString *pStr,
540 const wxString& path,
541 const wxString& basename)
542{
543 // we assume that it's not empty
544 wxCHECK_MSG( !basename.empty(), false,
545 wxT("empty file name in wxFileSystem::FindFileInPath"));
546
547 wxString name;
548 // skip path separator in the beginning of the file name if present
549 if ( wxIsPathSeparator(basename[0u]) )
550 name = basename.substr(1);
551 else
552 name = basename;
553
554 wxStringTokenizer tokenizer(path, wxPATH_SEP);
555 while ( tokenizer.HasMoreTokens() )
556 {
557 wxString strFile = tokenizer.GetNextToken();
558 if ( !wxEndsWithPathSeparator(strFile) )
559 strFile += wxFILE_SEP_PATH;
560 strFile += name;
561
562 wxFSFile *file = OpenFile(strFile);
563 if ( file )
564 {
565 delete file;
566 *pStr = strFile;
567 return true;
568 }
569 }
570
571 return false;
572}
573
574void wxFileSystem::AddHandler(wxFileSystemHandler *handler)
575{
576 // prepend the handler to the beginning of the list because handlers added
577 // last should have the highest priority to allow overriding them
578 m_Handlers.Insert((size_t)0, handler);
579}
580
581wxFileSystemHandler* wxFileSystem::RemoveHandler(wxFileSystemHandler *handler)
582{
583 // if handler has already been removed (or deleted)
584 // we return NULL. This is by design in case
585 // CleanUpHandlers() is called before RemoveHandler
586 // is called, as we cannot control the order
587 // which modules are unloaded
588 if (!m_Handlers.DeleteObject(handler))
589 return NULL;
590
591 return handler;
592}
593
594
595bool wxFileSystem::HasHandlerForPath(const wxString &location)
596{
597 for ( wxList::compatibility_iterator node = m_Handlers.GetFirst();
598 node; node = node->GetNext() )
599 {
600 wxFileSystemHandler *h = (wxFileSystemHandler*) node->GetData();
601 if (h->CanOpen(location))
602 return true;
603 }
604
605 return false;
606}
607
608void wxFileSystem::CleanUpHandlers()
609{
610 WX_CLEAR_LIST(wxList, m_Handlers);
611}
612
613static const wxString g_unixPathString(wxT("/"));
614static const wxString g_nativePathString(wxFILE_SEP_PATH);
615
616// Returns the native path for a file URL
617wxFileName wxFileSystem::URLToFileName(const wxString& url)
618{
619 wxString path = url;
620
621 if ( path.Find(wxT("file://")) == 0 )
622 {
623 path = path.Mid(7);
624 }
625 else if ( path.Find(wxT("file:")) == 0 )
626 {
627 path = path.Mid(5);
628 }
629 // Remove preceding double slash on Mac Classic
630#if defined(__WXMAC__) && !defined(__UNIX__)
631 else if ( path.Find(wxT("//")) == 0 )
632 path = path.Mid(2);
633#endif
634
635 path = wxURI::Unescape(path);
636
637#ifdef __WINDOWS__
638 // file urls either start with a forward slash (local harddisk),
639 // otherwise they have a servername/sharename notation,
640 // which only exists on msw and corresponds to a unc
641 if ( path.length() > 1 && (path[0u] == wxT('/') && path [1u] != wxT('/')) )
642 {
643 path = path.Mid(1);
644 }
645 else if ( (url.Find(wxT("file://")) == 0) &&
646 (path.Find(wxT('/')) != wxNOT_FOUND) &&
647 (path.length() > 1) && (path[1u] != wxT(':')) )
648 {
649 path = wxT("//") + path;
650 }
651#endif
652
653 path.Replace(g_unixPathString, g_nativePathString);
654
655 return wxFileName(path, wxPATH_NATIVE);
656}
657
658// Escapes non-ASCII and others characters in file: URL to be valid URLs
659static wxString EscapeFileNameCharsInURL(const char *in)
660{
661 wxString s;
662
663 for ( const unsigned char *p = (const unsigned char*)in; *p; ++p )
664 {
665 const unsigned char c = *p;
666
667 // notice that all colons *must* be encoded in the paths used by
668 // wxFileSystem even though this makes URLs produced by this method
669 // unusable with IE under Windows as it requires "file:///c:/foo.bar"
670 // and doesn't accept "file:///c%3a/foo.bar" -- but then we never made
671 // any guarantees about general suitability of the strings returned by
672 // this method, they must work with wxFileSystem only and not encoding
673 // the colon breaks handling of
674 // "http://wherever/whatever.zip#zip:filename.ext" URLs so we really
675 // can't do this without heavy changes to the parsing code here, in
676 // particular in GetRightLocation()
677
678 if ( c == '/' || c == '-' || c == '.' || c == '_' || c == '~' ||
679 (c >= '0' && c <= '9') ||
680 (c >= 'a' && c <= 'z') ||
681 (c >= 'A' && c <= 'Z') )
682 {
683 s << c;
684 }
685 else
686 {
687 s << wxString::Format("%%%02x", c);
688 }
689 }
690
691 return s;
692}
693
694// Returns the file URL for a native path
695wxString wxFileSystem::FileNameToURL(const wxFileName& filename)
696{
697 wxFileName fn = filename;
698 fn.Normalize(wxPATH_NORM_DOTS | wxPATH_NORM_TILDE | wxPATH_NORM_ABSOLUTE);
699 wxString url = fn.GetFullPath(wxPATH_NATIVE);
700
701#ifndef __UNIX__
702 // unc notation, wxMSW
703 if ( url.Find(wxT("\\\\")) == 0 )
704 {
705 url = wxT("//") + url.Mid(2);
706 }
707 else
708 {
709 url = wxT("/") + url;
710#ifdef __WXMAC__
711 url = wxT("/") + url;
712#endif
713
714 }
715#endif
716
717 url.Replace(g_nativePathString, g_unixPathString);
718
719 // Do wxURI- and common practice-compatible escaping: encode the string
720 // into UTF-8, then escape anything non-ASCII:
721 return wxT("file:") + EscapeFileNameCharsInURL(url.utf8_str());
722}
723
724
725///// Module:
726
727class wxFileSystemModule : public wxModule
728{
729 DECLARE_DYNAMIC_CLASS(wxFileSystemModule)
730
731 public:
732 wxFileSystemModule() :
733 wxModule(),
734 m_handler(NULL)
735 {
736 }
737
738 virtual bool OnInit()
739 {
740 m_handler = new wxLocalFSHandler;
741 wxFileSystem::AddHandler(m_handler);
742 return true;
743 }
744 virtual void OnExit()
745 {
746 delete wxFileSystem::RemoveHandler(m_handler);
747
748 wxFileSystem::CleanUpHandlers();
749 }
750
751 private:
752 wxFileSystemHandler* m_handler;
753
754};
755
756IMPLEMENT_DYNAMIC_CLASS(wxFileSystemModule, wxModule)
757
758//// wxFSInputStream
759
760wxFSInputStream::wxFSInputStream(const wxString& filename, int flags)
761{
762 wxFileSystem fs;
763 m_file = fs.OpenFile(filename, flags | wxFS_READ);
764
765 if ( m_file )
766 {
767 wxInputStream* const stream = m_file->GetStream();
768 if ( stream )
769 {
770 // Notice that we pass the stream by reference: it shouldn't be
771 // deleted by us as it's owned by m_file already.
772 InitParentStream(*stream);
773 }
774 }
775}
776
777wxFSInputStream::~wxFSInputStream()
778{
779 delete m_file;
780}
781
782#endif
783 // wxUSE_FILESYSTEM