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