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
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 #include "wx/wxprec.h"
19 #include "wx/filesys.h"
23 #include "wx/module.h"
26 #include "wx/wfstream.h"
27 #include "wx/mimetype.h"
28 #include "wx/filename.h"
29 #include "wx/tokenzr.h"
31 #include "wx/private/fileback.h"
33 // ----------------------------------------------------------------------------
35 // ----------------------------------------------------------------------------
37 const wxString
& wxFSFile::GetMimeType() const
39 if ( m_MimeType
.empty() && !m_Location
.empty() )
41 wxConstCast(this, wxFSFile
)->m_MimeType
=
42 wxFileSystemHandler::GetMimeTypeFromExt(m_Location
);
48 // ----------------------------------------------------------------------------
49 // wxFileSystemHandler
50 // ----------------------------------------------------------------------------
52 IMPLEMENT_ABSTRACT_CLASS(wxFileSystemHandler
, wxObject
)
56 wxString
wxFileSystemHandler::GetMimeTypeFromExt(const wxString
& location
)
59 wxString loc
= GetRightLocation(location
);
61 int l
= loc
.length(), l2
;
64 for (int i
= l
-1; i
>= 0; i
--)
66 c
= loc
[(unsigned int) i
];
71 ext
= loc
.Right(l2
-i
-1);
74 if ( (c
== wxT('/')) || (c
== wxT('\\')) || (c
== wxT(':')) )
79 static bool s_MinimalMimeEnsured
= false;
80 if (!s_MinimalMimeEnsured
)
82 static const wxFileTypeInfo fallbacks
[] =
84 wxFileTypeInfo(_T("image/jpeg"),
87 _T("JPEG image (from fallback)"),
88 _T("jpg"), _T("jpeg"), _T("JPG"), _T("JPEG"), wxNullPtr
),
89 wxFileTypeInfo(_T("image/gif"),
92 _T("GIF image (from fallback)"),
93 _T("gif"), _T("GIF"), wxNullPtr
),
94 wxFileTypeInfo(_T("image/png"),
97 _T("PNG image (from fallback)"),
98 _T("png"), _T("PNG"), wxNullPtr
),
99 wxFileTypeInfo(_T("image/bmp"),
102 _T("windows bitmap image (from fallback)"),
103 _T("bmp"), _T("BMP"), wxNullPtr
),
104 wxFileTypeInfo(_T("text/html"),
107 _T("HTML document (from fallback)"),
108 _T("htm"), _T("html"), _T("HTM"), _T("HTML"), wxNullPtr
),
109 // must terminate the table with this!
112 wxTheMimeTypesManager
->AddFallbacks(fallbacks
);
113 s_MinimalMimeEnsured
= true;
116 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
117 if ( !ft
|| !ft
-> GetMimeType(&mime
) )
119 mime
= wxEmptyString
;
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
;
143 wxString
wxFileSystemHandler::GetProtocol(const wxString
& location
)
145 wxString s
= wxEmptyString
;
146 int i
, l
= location
.length();
149 for (i
= l
-1; (i
>= 0) && ((location
[i
] != wxT('#')) || (!fnd
)); i
--) {
150 if ((location
[i
] == wxT(':')) && (i
!= 1 /*win: C:\path*/)) fnd
= true;
152 if (!fnd
) return wxT("file");
153 for (++i
; (i
< l
) && (location
[i
] != wxT(':')); i
++) s
<< location
[i
];
159 wxString
wxFileSystemHandler::GetLeftLocation(const wxString
& location
)
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
);
168 return wxEmptyString
;
172 wxString
wxFileSystemHandler::GetRightLocation(const wxString
& location
)
174 int i
, l
= location
.length();
179 ((location
[i
] != wxT(':')) || (i
== 1) || (location
[i
-2] == wxT(':')));
182 if (location
[i
] == wxT('#')) l2
= i
+ 1;
184 if (i
== 0) return wxEmptyString
;
185 else return location
.Mid(i
+ 1, l2
- i
- 2);
189 wxString
wxFileSystemHandler::GetAnchor(const wxString
& location
)
192 int l
= location
.length();
194 for (int i
= l
-1; i
>= 0; i
--) {
197 return location
.Right(l
-i
-1);
198 else if ((c
== wxT('/')) || (c
== wxT('\\')) || (c
== wxT(':')))
199 return wxEmptyString
;
201 return wxEmptyString
;
205 wxString
wxFileSystemHandler::FindFirst(const wxString
& WXUNUSED(spec
),
208 return wxEmptyString
;
211 wxString
wxFileSystemHandler::FindNext()
213 return wxEmptyString
;
216 //--------------------------------------------------------------------------------
218 //--------------------------------------------------------------------------------
221 wxString
wxLocalFSHandler::ms_root
;
223 bool wxLocalFSHandler::CanOpen(const wxString
& location
)
225 return GetProtocol(location
) == wxT("file");
228 wxFSFile
* wxLocalFSHandler::OpenFile(wxFileSystem
& WXUNUSED(fs
), const wxString
& location
)
230 // location has Unix path separators
231 wxString right
= GetRightLocation(location
);
232 wxFileName fn
= wxFileSystem::URLToFileName(right
);
233 wxString fullpath
= ms_root
+ fn
.GetFullPath();
235 if (!wxFileExists(fullpath
))
236 return (wxFSFile
*) NULL
;
238 // we need to check whether we can really read from this file, otherwise
239 // wxFSFile is not going to work
241 wxFFileInputStream
*is
= new wxFFileInputStream(fullpath
);
243 wxFileInputStream
*is
= new wxFileInputStream(fullpath
);
245 #error One of wxUSE_FILE or wxUSE_FFILE must be set to 1 for wxFSHandler to work
250 return (wxFSFile
*) NULL
;
253 return new wxFSFile(is
,
258 ,wxDateTime(wxFileModificationTime(fullpath
))
259 #endif // wxUSE_DATETIME
263 wxString
wxLocalFSHandler::FindFirst(const wxString
& spec
, int flags
)
265 wxFileName fn
= wxFileSystem::URLToFileName(GetRightLocation(spec
));
266 return wxFindFirstFile(ms_root
+ fn
.GetFullPath(), flags
);
269 wxString
wxLocalFSHandler::FindNext()
271 return wxFindNextFile();
276 //-----------------------------------------------------------------------------
278 //-----------------------------------------------------------------------------
280 IMPLEMENT_DYNAMIC_CLASS(wxFileSystem
, wxObject
)
281 IMPLEMENT_ABSTRACT_CLASS(wxFSFile
, wxObject
)
284 wxList
wxFileSystem::m_Handlers
;
287 wxFileSystem::~wxFileSystem()
289 WX_CLEAR_HASH_MAP(wxFSHandlerHash
, m_LocalHandlers
)
293 static wxString
MakeCorrectPath(const wxString
& path
)
300 for (i
= 0; i
< cnt
; i
++)
301 if (p
.GetChar(i
) == wxT('\\')) p
.GetWritableChar(i
) = wxT('/'); // Want to be windows-safe
303 if (p
.Left(2) == wxT("./")) { p
= p
.Mid(2); cnt
-= 2; }
305 if (cnt
< 3) return p
;
307 r
<< p
.GetChar(0) << p
.GetChar(1);
309 // skip trailing ../.., if any
310 for (i
= 2; i
< cnt
&& (p
.GetChar(i
) == wxT('/') || p
.GetChar(i
) == wxT('.')); i
++) r
<< p
.GetChar(i
);
312 // remove back references: translate dir1/../dir2 to dir2
316 if (p
.GetChar(i
) == wxT('/') && p
.GetChar(i
-1) == wxT('.') && p
.GetChar(i
-2) == wxT('.'))
318 for (j
= r
.length() - 2; j
>= 0 && r
.GetChar(j
) != wxT('/') && r
.GetChar(j
) != wxT(':'); j
--) {}
319 if (j
>= 0 && r
.GetChar(j
) != wxT(':'))
321 for (j
= j
- 1; j
>= 0 && r
.GetChar(j
) != wxT('/') && r
.GetChar(j
) != wxT(':'); j
--) {}
327 for (; i
< cnt
; i
++) r
<< p
.GetChar(i
);
333 void wxFileSystem::ChangePathTo(const wxString
& location
, bool is_dir
)
337 m_Path
= MakeCorrectPath(location
);
341 if (m_Path
.length() > 0 && m_Path
.Last() != wxT('/') && m_Path
.Last() != wxT(':'))
347 for (i
= m_Path
.length()-1; i
>= 0; i
--)
349 if (m_Path
[(unsigned int) i
] == wxT('/'))
351 if ((i
> 1) && (m_Path
[(unsigned int) (i
-1)] == wxT('/')) && (m_Path
[(unsigned int) (i
-2)] == wxT(':')))
362 else if (m_Path
[(unsigned int) i
] == wxT(':')) {
369 for (i
= 0; i
< (int) m_Path
.length(); i
++)
371 if (m_Path
[(unsigned int) i
] == wxT(':'))
377 if (i
== (int) m_Path
.length())
378 m_Path
= wxEmptyString
;
382 m_Path
.Remove(pathpos
+1);
389 wxFileSystemHandler
*wxFileSystem::MakeLocal(wxFileSystemHandler
*h
)
391 wxClassInfo
*classinfo
= h
->GetClassInfo();
393 if (classinfo
->IsDynamic())
395 wxFileSystemHandler
*& local
= m_LocalHandlers
[classinfo
];
397 local
= (wxFileSystemHandler
*)classinfo
->CreateObject();
408 wxFSFile
* wxFileSystem::OpenFile(const wxString
& location
, int flags
)
410 if ((flags
& wxFS_READ
) == 0)
413 wxString loc
= MakeCorrectPath(location
);
417 wxList::compatibility_iterator node
;
421 for (i
= 0; i
< ln
; i
++)
423 switch ( loc
[i
].GetValue() )
425 case wxT('/') : case wxT(':') : case wxT('#') :
429 if (meta
!= 0) break;
431 m_LastName
= wxEmptyString
;
433 // try relative paths first :
434 if (meta
!= wxT(':'))
436 node
= m_Handlers
.GetFirst();
439 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
440 if (h
->CanOpen(m_Path
+ loc
))
442 s
= MakeLocal(h
)->OpenFile(*this, m_Path
+ loc
);
443 if (s
) { m_LastName
= m_Path
+ loc
; break; }
445 node
= node
->GetNext();
449 // if failed, try absolute paths :
452 node
= m_Handlers
.GetFirst();
455 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
->GetData();
458 s
= MakeLocal(h
)->OpenFile(*this, loc
);
459 if (s
) { m_LastName
= loc
; break; }
461 node
= node
->GetNext();
465 if (s
&& (flags
& wxFS_SEEKABLE
) != 0 && !s
->GetStream()->IsSeekable())
467 wxBackedInputStream
*stream
;
468 stream
= new wxBackedInputStream(s
->DetachStream());
469 stream
->FindLength();
470 s
->SetStream(stream
);
478 wxString
wxFileSystem::FindFirst(const wxString
& spec
, int flags
)
480 wxList::compatibility_iterator node
;
481 wxString
spec2(spec
);
483 m_FindFileHandler
= NULL
;
485 for (int i
= spec2
.length()-1; i
>= 0; i
--)
486 if (spec2
[(unsigned int) i
] == wxT('\\')) spec2
.GetWritableChar(i
) = wxT('/'); // Want to be windows-safe
488 node
= m_Handlers
.GetFirst();
491 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
492 if (h
-> CanOpen(m_Path
+ spec2
))
494 m_FindFileHandler
= MakeLocal(h
);
495 return m_FindFileHandler
-> FindFirst(m_Path
+ spec2
, flags
);
497 node
= node
->GetNext();
500 node
= m_Handlers
.GetFirst();
503 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
504 if (h
-> CanOpen(spec2
))
506 m_FindFileHandler
= MakeLocal(h
);
507 return m_FindFileHandler
-> FindFirst(spec2
, flags
);
509 node
= node
->GetNext();
512 return wxEmptyString
;
517 wxString
wxFileSystem::FindNext()
519 if (m_FindFileHandler
== NULL
) return wxEmptyString
;
520 else return m_FindFileHandler
-> FindNext();
523 bool wxFileSystem::FindFileInPath(wxString
*pStr
,
524 const wxString
& path
,
525 const wxString
& basename
)
527 // we assume that it's not empty
528 wxCHECK_MSG( !basename
.empty(), false,
529 _T("empty file name in wxFileSystem::FindFileInPath"));
532 // skip path separator in the beginning of the file name if present
533 if ( wxIsPathSeparator(basename
[0u]) )
534 name
= basename
.substr(1);
538 wxStringTokenizer
tokenizer(path
, wxPATH_SEP
);
539 while ( tokenizer
.HasMoreTokens() )
541 wxString strFile
= tokenizer
.GetNextToken();
542 if ( !wxEndsWithPathSeparator(strFile
) )
543 strFile
+= wxFILE_SEP_PATH
;
546 wxFSFile
*file
= OpenFile(strFile
);
558 void wxFileSystem::AddHandler(wxFileSystemHandler
*handler
)
560 // prepend the handler to the beginning of the list because handlers added
561 // last should have the highest priority to allow overriding them
562 m_Handlers
.Insert((size_t)0, handler
);
565 wxFileSystemHandler
* wxFileSystem::RemoveHandler(wxFileSystemHandler
*handler
)
567 // if handler has already been removed (or deleted)
568 // we return NULL. This is by design in case
569 // CleanUpHandlers() is called before RemoveHandler
570 // is called, as we cannot control the order
571 // which modules are unloaded
572 if (!m_Handlers
.DeleteObject(handler
))
579 bool wxFileSystem::HasHandlerForPath(const wxString
&location
)
581 for ( wxList::compatibility_iterator node
= m_Handlers
.GetFirst();
582 node
; node
= node
->GetNext() )
584 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
->GetData();
585 if (h
->CanOpen(location
))
592 void wxFileSystem::CleanUpHandlers()
594 WX_CLEAR_LIST(wxList
, m_Handlers
);
597 static const wxString
g_unixPathString(wxT("/"));
598 static const wxString
g_nativePathString(wxFILE_SEP_PATH
);
600 // Returns the native path for a file URL
601 wxFileName
wxFileSystem::URLToFileName(const wxString
& url
)
605 if ( path
.Find(wxT("file://")) == 0 )
609 else if ( path
.Find(wxT("file:")) == 0 )
613 // Remove preceding double slash on Mac Classic
614 #if defined(__WXMAC__) && !defined(__UNIX__)
615 else if ( path
.Find(wxT("//")) == 0 )
619 path
= wxURI::Unescape(path
);
622 // file urls either start with a forward slash (local harddisk),
623 // otherwise they have a servername/sharename notation,
624 // which only exists on msw and corresponds to a unc
625 if ( path
[0u] == wxT('/') && path
[1u] != wxT('/'))
629 else if ( (url
.Find(wxT("file://")) == 0) &&
630 (path
.Find(wxT('/')) != wxNOT_FOUND
) &&
631 (path
.length() > 1) && (path
[1u] != wxT(':')) )
633 path
= wxT("//") + path
;
637 path
.Replace(g_unixPathString
, g_nativePathString
);
639 return wxFileName(path
, wxPATH_NATIVE
);
642 // Returns the file URL for a native path
643 wxString
wxFileSystem::FileNameToURL(const wxFileName
& filename
)
645 wxFileName fn
= filename
;
646 fn
.Normalize(wxPATH_NORM_DOTS
| wxPATH_NORM_TILDE
| wxPATH_NORM_ABSOLUTE
);
647 wxString url
= fn
.GetFullPath(wxPATH_NATIVE
);
650 // unc notation, wxMSW
651 if ( url
.Find(wxT("\\\\")) == 0 )
653 url
= wxT("//") + url
.Mid(2);
657 url
= wxT("/") + url
;
659 url
= wxT("/") + url
;
665 url
.Replace(g_nativePathString
, g_unixPathString
);
666 url
.Replace(wxT("%"), wxT("%25")); // '%'s must be replaced first!
667 url
.Replace(wxT("#"), wxT("%23"));
669 // notice that all colons *must* be encoded in the paths used by
670 // wxFileSystem even though this makes URLs produced by this method
671 // unusable with IE under Windows as it requires "file:///c:/foo.bar" and
672 // doesn't accept "file:///c%3a/foo.bar" -- but then we never made any
673 // guarantees about general suitability of the strings returned by this
674 // method, they must work with wxFileSystem only and not encoding the colon
675 // breaks handling of "http://wherever/whatever.zip#zip:filename.ext" URLs
676 // so we really can't do this without heavy changes to the parsing code
677 // here, in particular in GetRightLocation()
678 url
.Replace(wxT(":"), wxT("%3A"));
679 url
= wxT("file:") + url
;
686 class wxFileSystemModule
: public wxModule
688 DECLARE_DYNAMIC_CLASS(wxFileSystemModule
)
691 wxFileSystemModule() :
697 virtual bool OnInit()
699 m_handler
= new wxLocalFSHandler
;
700 wxFileSystem::AddHandler(m_handler
);
703 virtual void OnExit()
705 delete wxFileSystem::RemoveHandler(m_handler
);
707 wxFileSystem::CleanUpHandlers();
711 wxFileSystemHandler
* m_handler
;
715 IMPLEMENT_DYNAMIC_CLASS(wxFileSystemModule
, wxModule
)