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