]> git.saurik.com Git - wxWidgets.git/blob - src/common/filesys.cpp
Fixed URL saving/loading
[wxWidgets.git] / src / common / filesys.cpp
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 // CVS-ID: $Id$
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 #include "wx/wxprec.h"
11
12 #ifdef __BORLANDC__
13 #pragma hdrstop
14 #endif
15
16
17 #if wxUSE_FILESYSTEM
18
19 #include "wx/filesys.h"
20
21 #ifndef WX_PRECOMP
22 #include "wx/log.h"
23 #include "wx/module.h"
24 #endif
25
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
37 const 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
52 IMPLEMENT_ABSTRACT_CLASS(wxFileSystemHandler, wxObject)
53
54
55 /* static */
56 wxString 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 if (!s_MinimalMimeEnsured)
81 {
82 static const wxFileTypeInfo fallbacks[] =
83 {
84 wxFileTypeInfo(_T("image/jpeg"),
85 wxEmptyString,
86 wxEmptyString,
87 _T("JPEG image (from fallback)"),
88 _T("jpg"), _T("jpeg"), _T("JPG"), _T("JPEG"), wxNullPtr),
89 wxFileTypeInfo(_T("image/gif"),
90 wxEmptyString,
91 wxEmptyString,
92 _T("GIF image (from fallback)"),
93 _T("gif"), _T("GIF"), wxNullPtr),
94 wxFileTypeInfo(_T("image/png"),
95 wxEmptyString,
96 wxEmptyString,
97 _T("PNG image (from fallback)"),
98 _T("png"), _T("PNG"), wxNullPtr),
99 wxFileTypeInfo(_T("image/bmp"),
100 wxEmptyString,
101 wxEmptyString,
102 _T("windows bitmap image (from fallback)"),
103 _T("bmp"), _T("BMP"), wxNullPtr),
104 wxFileTypeInfo(_T("text/html"),
105 wxEmptyString,
106 wxEmptyString,
107 _T("HTML document (from fallback)"),
108 _T("htm"), _T("html"), _T("HTM"), _T("HTML"), wxNullPtr),
109 // must terminate the table with this!
110 wxFileTypeInfo()
111 };
112 wxTheMimeTypesManager->AddFallbacks(fallbacks);
113 s_MinimalMimeEnsured = true;
114 }
115
116 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
117 if ( !ft || !ft -> GetMimeType(&mime) )
118 {
119 mime = wxEmptyString;
120 }
121
122 delete ft;
123
124 return mime;
125 #else
126 if ( ext.IsSameAs(wxT("htm"), false) || ext.IsSameAs(_T("html"), false) )
127 return wxT("text/html");
128 if ( ext.IsSameAs(wxT("jpg"), false) || ext.IsSameAs(_T("jpeg"), false) )
129 return wxT("image/jpeg");
130 if ( ext.IsSameAs(wxT("gif"), false) )
131 return wxT("image/gif");
132 if ( ext.IsSameAs(wxT("png"), false) )
133 return wxT("image/png");
134 if ( ext.IsSameAs(wxT("bmp"), false) )
135 return wxT("image/bmp");
136 return wxEmptyString;
137 #endif
138 }
139
140
141
142 /* static */
143 wxString wxFileSystemHandler::GetProtocol(const wxString& location)
144 {
145 wxString s = wxEmptyString;
146 int i, l = location.length();
147 bool fnd = false;
148
149 for (i = l-1; (i >= 0) && ((location[i] != wxT('#')) || (!fnd)); i--) {
150 if ((location[i] == wxT(':')) && (i != 1 /*win: C:\path*/)) fnd = true;
151 }
152 if (!fnd) return wxT("file");
153 for (++i; (i < l) && (location[i] != wxT(':')); i++) s << location[i];
154 return s;
155 }
156
157
158 /* static */
159 wxString wxFileSystemHandler::GetLeftLocation(const wxString& location)
160 {
161 int i;
162 bool fnd = false;
163
164 for (i = location.length()-1; i >= 0; i--) {
165 if ((location[i] == wxT(':')) && (i != 1 /*win: C:\path*/)) fnd = true;
166 else if (fnd && (location[i] == wxT('#'))) return location.Left(i);
167 }
168 return wxEmptyString;
169 }
170
171 /* static */
172 wxString wxFileSystemHandler::GetRightLocation(const wxString& location)
173 {
174 int i, l = location.length();
175 int l2 = l + 1;
176
177 for (i = l-1;
178 (i >= 0) &&
179 ((location[i] != wxT(':')) || (i == 1) || (location[i-2] == wxT(':')));
180 i--)
181 {
182 if (location[i] == wxT('#')) l2 = i + 1;
183 }
184 if (i == 0) return wxEmptyString;
185 else return location.Mid(i + 1, l2 - i - 2);
186 }
187
188 /* static */
189 wxString wxFileSystemHandler::GetAnchor(const wxString& location)
190 {
191 wxChar c;
192 int l = location.length();
193
194 for (int i = l-1; i >= 0; i--) {
195 c = location[i];
196 if (c == wxT('#')) return location.Right(l-i-1);
197 else if ((c == wxT('.')) || (c == wxT('/')) || (c == wxT('\\')) || (c == wxT(':'))) return wxEmptyString;
198 }
199 return wxEmptyString;
200 }
201
202
203 wxString wxFileSystemHandler::FindFirst(const wxString& WXUNUSED(spec),
204 int WXUNUSED(flags))
205 {
206 return wxEmptyString;
207 }
208
209 wxString wxFileSystemHandler::FindNext()
210 {
211 return wxEmptyString;
212 }
213
214 //--------------------------------------------------------------------------------
215 // wxLocalFSHandler
216 //--------------------------------------------------------------------------------
217
218
219 wxString wxLocalFSHandler::ms_root;
220
221 bool wxLocalFSHandler::CanOpen(const wxString& location)
222 {
223 return GetProtocol(location) == wxT("file");
224 }
225
226 wxFSFile* wxLocalFSHandler::OpenFile(wxFileSystem& WXUNUSED(fs), const wxString& location)
227 {
228 // location has Unix path separators
229 wxString right = GetRightLocation(location);
230 wxFileName fn = wxFileSystem::URLToFileName(right);
231 wxString fullpath = ms_root + fn.GetFullPath();
232
233 if (!wxFileExists(fullpath))
234 return (wxFSFile*) NULL;
235
236 // we need to check whether we can really read from this file, otherwise
237 // wxFSFile is not going to work
238 #if wxUSE_FFILE
239 wxFFileInputStream *is = new wxFFileInputStream(fullpath);
240 #elif wxUSE_FILE
241 wxFileInputStream *is = new wxFileInputStream(fullpath);
242 #else
243 #error One of wxUSE_FILE or wxUSE_FFILE must be set to 1 for wxFSHandler to work
244 #endif
245 if ( !is->Ok() )
246 {
247 delete is;
248 return (wxFSFile*) NULL;
249 }
250
251 return new wxFSFile(is,
252 right,
253 wxEmptyString,
254 GetAnchor(location)
255 #if wxUSE_DATETIME
256 ,wxDateTime(wxFileModificationTime(fullpath))
257 #endif // wxUSE_DATETIME
258 );
259 }
260
261 wxString wxLocalFSHandler::FindFirst(const wxString& spec, int flags)
262 {
263 wxFileName fn = wxFileSystem::URLToFileName(GetRightLocation(spec));
264 return wxFindFirstFile(ms_root + fn.GetFullPath(), flags);
265 }
266
267 wxString wxLocalFSHandler::FindNext()
268 {
269 return wxFindNextFile();
270 }
271
272
273
274 //-----------------------------------------------------------------------------
275 // wxFileSystem
276 //-----------------------------------------------------------------------------
277
278 IMPLEMENT_DYNAMIC_CLASS(wxFileSystem, wxObject)
279 IMPLEMENT_ABSTRACT_CLASS(wxFSFile, wxObject)
280
281
282 wxList wxFileSystem::m_Handlers;
283
284
285 wxFileSystem::~wxFileSystem()
286 {
287 WX_CLEAR_HASH_MAP(wxFSHandlerHash, m_LocalHandlers)
288 }
289
290
291 static wxString MakeCorrectPath(const wxString& path)
292 {
293 wxString p(path);
294 wxString r;
295 int i, j, cnt;
296
297 cnt = p.length();
298 for (i = 0; i < cnt; i++)
299 if (p.GetChar(i) == wxT('\\')) p.GetWritableChar(i) = wxT('/'); // Want to be windows-safe
300
301 if (p.Left(2) == wxT("./")) { p = p.Mid(2); cnt -= 2; }
302
303 if (cnt < 3) return p;
304
305 r << p.GetChar(0) << p.GetChar(1);
306
307 // skip trailing ../.., if any
308 for (i = 2; i < cnt && (p.GetChar(i) == wxT('/') || p.GetChar(i) == wxT('.')); i++) r << p.GetChar(i);
309
310 // remove back references: translate dir1/../dir2 to dir2
311 for (; i < cnt; i++)
312 {
313 r << p.GetChar(i);
314 if (p.GetChar(i) == wxT('/') && p.GetChar(i-1) == wxT('.') && p.GetChar(i-2) == wxT('.'))
315 {
316 for (j = r.length() - 2; j >= 0 && r.GetChar(j) != wxT('/') && r.GetChar(j) != wxT(':'); j--) {}
317 if (j >= 0 && r.GetChar(j) != wxT(':'))
318 {
319 for (j = j - 1; j >= 0 && r.GetChar(j) != wxT('/') && r.GetChar(j) != wxT(':'); j--) {}
320 r.Remove(j + 1);
321 }
322 }
323 }
324
325 for (; i < cnt; i++) r << p.GetChar(i);
326
327 return r;
328 }
329
330
331 void wxFileSystem::ChangePathTo(const wxString& location, bool is_dir)
332 {
333 int i, pathpos = -1;
334
335 m_Path = MakeCorrectPath(location);
336
337 if (is_dir)
338 {
339 if (m_Path.length() > 0 && m_Path.Last() != wxT('/') && m_Path.Last() != wxT(':'))
340 m_Path << wxT('/');
341 }
342
343 else
344 {
345 for (i = m_Path.length()-1; i >= 0; i--)
346 {
347 if (m_Path[(unsigned int) i] == wxT('/'))
348 {
349 if ((i > 1) && (m_Path[(unsigned int) (i-1)] == wxT('/')) && (m_Path[(unsigned int) (i-2)] == wxT(':')))
350 {
351 i -= 2;
352 continue;
353 }
354 else
355 {
356 pathpos = i;
357 break;
358 }
359 }
360 else if (m_Path[(unsigned int) i] == wxT(':')) {
361 pathpos = i;
362 break;
363 }
364 }
365 if (pathpos == -1)
366 {
367 for (i = 0; i < (int) m_Path.length(); i++)
368 {
369 if (m_Path[(unsigned int) i] == wxT(':'))
370 {
371 m_Path.Remove(i+1);
372 break;
373 }
374 }
375 if (i == (int) m_Path.length())
376 m_Path = wxEmptyString;
377 }
378 else
379 {
380 m_Path.Remove(pathpos+1);
381 }
382 }
383 }
384
385
386
387 wxFileSystemHandler *wxFileSystem::MakeLocal(wxFileSystemHandler *h)
388 {
389 wxClassInfo *classinfo = h->GetClassInfo();
390
391 if (classinfo->IsDynamic())
392 {
393 wxFileSystemHandler*& local = m_LocalHandlers[classinfo];
394 if (!local)
395 local = (wxFileSystemHandler*)classinfo->CreateObject();
396 return local;
397 }
398 else
399 {
400 return h;
401 }
402 }
403
404
405
406 wxFSFile* wxFileSystem::OpenFile(const wxString& location, int flags)
407 {
408 if ((flags & wxFS_READ) == 0)
409 return NULL;
410
411 wxString loc = MakeCorrectPath(location);
412 unsigned i, ln;
413 wxChar meta;
414 wxFSFile *s = NULL;
415 wxList::compatibility_iterator node;
416
417 ln = loc.length();
418 meta = 0;
419 for (i = 0; i < ln; i++)
420 {
421 switch ( loc[i].GetValue() )
422 {
423 case wxT('/') : case wxT(':') : case wxT('#') :
424 meta = loc[i];
425 break;
426 }
427 if (meta != 0) break;
428 }
429 m_LastName = wxEmptyString;
430
431 // try relative paths first :
432 if (meta != wxT(':'))
433 {
434 node = m_Handlers.GetFirst();
435 while (node)
436 {
437 wxFileSystemHandler *h = (wxFileSystemHandler*) node -> GetData();
438 if (h->CanOpen(m_Path + loc))
439 {
440 s = MakeLocal(h)->OpenFile(*this, m_Path + loc);
441 if (s) { m_LastName = m_Path + loc; break; }
442 }
443 node = node->GetNext();
444 }
445 }
446
447 // if failed, try absolute paths :
448 if (s == NULL)
449 {
450 node = m_Handlers.GetFirst();
451 while (node)
452 {
453 wxFileSystemHandler *h = (wxFileSystemHandler*) node->GetData();
454 if (h->CanOpen(loc))
455 {
456 s = MakeLocal(h)->OpenFile(*this, loc);
457 if (s) { m_LastName = loc; break; }
458 }
459 node = node->GetNext();
460 }
461 }
462
463 if (s && (flags & wxFS_SEEKABLE) != 0 && !s->GetStream()->IsSeekable())
464 {
465 wxBackedInputStream *stream;
466 stream = new wxBackedInputStream(s->DetachStream());
467 stream->FindLength();
468 s->SetStream(stream);
469 }
470
471 return (s);
472 }
473
474
475
476 wxString wxFileSystem::FindFirst(const wxString& spec, int flags)
477 {
478 wxList::compatibility_iterator node;
479 wxString spec2(spec);
480
481 m_FindFileHandler = NULL;
482
483 for (int i = spec2.length()-1; i >= 0; i--)
484 if (spec2[(unsigned int) i] == wxT('\\')) spec2.GetWritableChar(i) = wxT('/'); // Want to be windows-safe
485
486 node = m_Handlers.GetFirst();
487 while (node)
488 {
489 wxFileSystemHandler *h = (wxFileSystemHandler*) node -> GetData();
490 if (h -> CanOpen(m_Path + spec2))
491 {
492 m_FindFileHandler = MakeLocal(h);
493 return m_FindFileHandler -> FindFirst(m_Path + spec2, flags);
494 }
495 node = node->GetNext();
496 }
497
498 node = m_Handlers.GetFirst();
499 while (node)
500 {
501 wxFileSystemHandler *h = (wxFileSystemHandler*) node -> GetData();
502 if (h -> CanOpen(spec2))
503 {
504 m_FindFileHandler = MakeLocal(h);
505 return m_FindFileHandler -> FindFirst(spec2, flags);
506 }
507 node = node->GetNext();
508 }
509
510 return wxEmptyString;
511 }
512
513
514
515 wxString wxFileSystem::FindNext()
516 {
517 if (m_FindFileHandler == NULL) return wxEmptyString;
518 else return m_FindFileHandler -> FindNext();
519 }
520
521 bool wxFileSystem::FindFileInPath(wxString *pStr,
522 const wxString& path,
523 const wxString& basename)
524 {
525 // we assume that it's not empty
526 wxCHECK_MSG( !basename.empty(), false,
527 _T("empty file name in wxFileSystem::FindFileInPath"));
528
529 wxString name;
530 // skip path separator in the beginning of the file name if present
531 if ( wxIsPathSeparator(basename[0u]) )
532 name = basename.substr(1);
533 else
534 name = basename;
535
536 wxStringTokenizer tokenizer(path, wxPATH_SEP);
537 while ( tokenizer.HasMoreTokens() )
538 {
539 wxString strFile = tokenizer.GetNextToken();
540 if ( !wxEndsWithPathSeparator(strFile) )
541 strFile += wxFILE_SEP_PATH;
542 strFile += name;
543
544 wxFSFile *file = OpenFile(strFile);
545 if ( file )
546 {
547 delete file;
548 *pStr = strFile;
549 return true;
550 }
551 }
552
553 return false;
554 }
555
556 void wxFileSystem::AddHandler(wxFileSystemHandler *handler)
557 {
558 // prepend the handler to the beginning of the list because handlers added
559 // last should have the highest priority to allow overriding them
560 m_Handlers.Insert((size_t)0, handler);
561 }
562
563 wxFileSystemHandler* wxFileSystem::RemoveHandler(wxFileSystemHandler *handler)
564 {
565 // if handler has already been removed (or deleted)
566 // we return NULL. This is by design in case
567 // CleanUpHandlers() is called before RemoveHandler
568 // is called, as we cannot control the order
569 // which modules are unloaded
570 if (!m_Handlers.DeleteObject(handler))
571 return NULL;
572
573 return handler;
574 }
575
576
577 bool wxFileSystem::HasHandlerForPath(const wxString &location)
578 {
579 for ( wxList::compatibility_iterator node = m_Handlers.GetFirst();
580 node; node = node->GetNext() )
581 {
582 wxFileSystemHandler *h = (wxFileSystemHandler*) node->GetData();
583 if (h->CanOpen(location))
584 return true;
585 }
586
587 return false;
588 }
589
590 void wxFileSystem::CleanUpHandlers()
591 {
592 WX_CLEAR_LIST(wxList, m_Handlers);
593 }
594
595 static const wxString g_unixPathString(wxT("/"));
596 static const wxString g_nativePathString(wxFILE_SEP_PATH);
597
598 // Returns the native path for a file URL
599 wxFileName wxFileSystem::URLToFileName(const wxString& url)
600 {
601 wxString path = url;
602
603 if ( path.Find(wxT("file://")) == 0 )
604 {
605 path = path.Mid(7);
606 }
607 else if ( path.Find(wxT("file:")) == 0 )
608 {
609 path = path.Mid(5);
610 }
611 // Remove preceding double slash on Mac Classic
612 #if defined(__WXMAC__) && !defined(__UNIX__)
613 else if ( path.Find(wxT("//")) == 0 )
614 path = path.Mid(2);
615 #endif
616
617 path = wxURI::Unescape(path);
618
619 #ifdef __WXMSW__
620 // file urls either start with a forward slash (local harddisk),
621 // otherwise they have a servername/sharename notation,
622 // which only exists on msw and corresponds to a unc
623 if ( path[0u] == wxT('/') && path [1u] != wxT('/'))
624 {
625 path = path.Mid(1);
626 }
627 else if ( (url.Find(wxT("file://")) == 0) &&
628 (path.Find(wxT('/')) != wxNOT_FOUND) &&
629 (path.length() > 1) && (path[1u] != wxT(':')) )
630 {
631 path = wxT("//") + path;
632 }
633 #endif
634
635 path.Replace(g_unixPathString, g_nativePathString);
636
637 return wxFileName(path, wxPATH_NATIVE);
638 }
639
640 // Returns the file URL for a native path
641 wxString wxFileSystem::FileNameToURL(const wxFileName& filename)
642 {
643 wxFileName fn = filename;
644 fn.Normalize(wxPATH_NORM_DOTS | wxPATH_NORM_TILDE | wxPATH_NORM_ABSOLUTE);
645 wxString url = fn.GetFullPath(wxPATH_NATIVE);
646
647 #ifndef __UNIX__
648 // unc notation, wxMSW
649 if ( url.Find(wxT("\\\\")) == 0 )
650 {
651 url = wxT("//") + url.Mid(2);
652 }
653 else
654 {
655 url = wxT("/") + url;
656 #ifdef __WXMAC__
657 url = wxT("/") + url;
658 #endif
659
660 }
661 #endif
662
663 url.Replace(g_nativePathString, g_unixPathString);
664 url.Replace(wxT("%"), wxT("%25")); // '%'s must be replaced first!
665 url.Replace(wxT("#"), wxT("%23"));
666 url.Replace(wxT(":"), wxT("%3A"));
667 url = wxT("file:") + url;
668 return url;
669 }
670
671
672 ///// Module:
673
674 class wxFileSystemModule : public wxModule
675 {
676 DECLARE_DYNAMIC_CLASS(wxFileSystemModule)
677
678 public:
679 wxFileSystemModule() :
680 wxModule(),
681 m_handler(NULL)
682 {
683 }
684
685 virtual bool OnInit()
686 {
687 m_handler = new wxLocalFSHandler;
688 wxFileSystem::AddHandler(m_handler);
689 return true;
690 }
691 virtual void OnExit()
692 {
693 delete wxFileSystem::RemoveHandler(m_handler);
694
695 wxFileSystem::CleanUpHandlers();
696 }
697
698 private:
699 wxFileSystemHandler* m_handler;
700
701 };
702
703 IMPLEMENT_DYNAMIC_CLASS(wxFileSystemModule, wxModule)
704
705 #endif
706 // wxUSE_FILESYSTEM