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