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 // Licence: wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
18 #include "wx/filesys.h"
22 #include "wx/module.h"
25 #include "wx/sysopt.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;
81 // Don't use mime types manager if the application doesn't need it and it would be
82 // cause an unacceptable delay, especially on startup.
83 #if wxUSE_SYSTEM_OPTIONS
84 if ( !wxSystemOptions::GetOptionInt(wxT("filesys.no-mimetypesmanager")) )
87 if (!s_MinimalMimeEnsured
)
89 static const wxFileTypeInfo fallbacks
[] =
91 wxFileTypeInfo(wxT("image/jpeg"),
94 wxT("JPEG image (from fallback)"),
95 wxT("jpg"), wxT("jpeg"), wxT("JPG"), wxT("JPEG"), wxNullPtr
),
96 wxFileTypeInfo(wxT("image/gif"),
99 wxT("GIF image (from fallback)"),
100 wxT("gif"), wxT("GIF"), wxNullPtr
),
101 wxFileTypeInfo(wxT("image/png"),
104 wxT("PNG image (from fallback)"),
105 wxT("png"), wxT("PNG"), wxNullPtr
),
106 wxFileTypeInfo(wxT("image/bmp"),
109 wxT("windows bitmap image (from fallback)"),
110 wxT("bmp"), wxT("BMP"), wxNullPtr
),
111 wxFileTypeInfo(wxT("text/html"),
114 wxT("HTML document (from fallback)"),
115 wxT("htm"), wxT("html"), wxT("HTM"), wxT("HTML"), wxNullPtr
),
116 // must terminate the table with this!
119 wxTheMimeTypesManager
->AddFallbacks(fallbacks
);
120 s_MinimalMimeEnsured
= true;
123 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
124 if ( !ft
|| !ft
-> GetMimeType(&mime
) )
126 mime
= wxEmptyString
;
136 if ( ext
.IsSameAs(wxT("htm"), false) || ext
.IsSameAs(wxT("html"), false) )
137 return wxT("text/html");
138 if ( ext
.IsSameAs(wxT("jpg"), false) || ext
.IsSameAs(wxT("jpeg"), false) )
139 return wxT("image/jpeg");
140 if ( ext
.IsSameAs(wxT("gif"), false) )
141 return wxT("image/gif");
142 if ( ext
.IsSameAs(wxT("png"), false) )
143 return wxT("image/png");
144 if ( ext
.IsSameAs(wxT("bmp"), false) )
145 return wxT("image/bmp");
146 return wxEmptyString
;
153 wxString
wxFileSystemHandler::GetProtocol(const wxString
& location
)
155 wxString s
= wxEmptyString
;
156 int i
, l
= location
.length();
159 for (i
= l
-1; (i
>= 0) && ((location
[i
] != wxT('#')) || (!fnd
)); i
--) {
160 if ((location
[i
] == wxT(':')) && (i
!= 1 /*win: C:\path*/)) fnd
= true;
162 if (!fnd
) return wxT("file");
163 for (++i
; (i
< l
) && (location
[i
] != wxT(':')); i
++) s
<< location
[i
];
169 wxString
wxFileSystemHandler::GetLeftLocation(const wxString
& location
)
174 for (i
= location
.length()-1; i
>= 0; i
--) {
175 if ((location
[i
] == wxT(':')) && (i
!= 1 /*win: C:\path*/)) fnd
= true;
176 else if (fnd
&& (location
[i
] == wxT('#'))) return location
.Left(i
);
178 return wxEmptyString
;
182 wxString
wxFileSystemHandler::GetRightLocation(const wxString
& location
)
184 int i
, l
= location
.length();
189 ((location
[i
] != wxT(':')) || (i
== 1) || (location
[i
-2] == wxT(':')));
192 if (location
[i
] == wxT('#')) l2
= i
+ 1;
194 if (i
== 0) return wxEmptyString
;
195 else return location
.Mid(i
+ 1, l2
- i
- 2);
199 wxString
wxFileSystemHandler::GetAnchor(const wxString
& location
)
202 int l
= location
.length();
204 for (int i
= l
-1; i
>= 0; i
--) {
207 return location
.Right(l
-i
-1);
208 else if ((c
== wxT('/')) || (c
== wxT('\\')) || (c
== wxT(':')))
209 return wxEmptyString
;
211 return wxEmptyString
;
215 wxString
wxFileSystemHandler::FindFirst(const wxString
& WXUNUSED(spec
),
218 return wxEmptyString
;
221 wxString
wxFileSystemHandler::FindNext()
223 return wxEmptyString
;
226 //--------------------------------------------------------------------------------
228 //--------------------------------------------------------------------------------
231 wxString
wxLocalFSHandler::ms_root
;
233 bool wxLocalFSHandler::CanOpen(const wxString
& location
)
235 return GetProtocol(location
) == wxT("file");
238 wxFSFile
* wxLocalFSHandler::OpenFile(wxFileSystem
& WXUNUSED(fs
), const wxString
& location
)
240 // location has Unix path separators
241 wxString right
= GetRightLocation(location
);
242 wxFileName fn
= wxFileSystem::URLToFileName(right
);
243 wxString fullpath
= ms_root
+ fn
.GetFullPath();
245 if (!wxFileExists(fullpath
))
248 // we need to check whether we can really read from this file, otherwise
249 // wxFSFile is not going to work
251 wxFFileInputStream
*is
= new wxFFileInputStream(fullpath
);
253 wxFileInputStream
*is
= new wxFileInputStream(fullpath
);
255 #error One of wxUSE_FILE or wxUSE_FFILE must be set to 1 for wxFSHandler to work
263 return new wxFSFile(is
,
268 ,wxDateTime(wxFileModificationTime(fullpath
))
269 #endif // wxUSE_DATETIME
273 wxString
wxLocalFSHandler::FindFirst(const wxString
& spec
, int flags
)
275 wxFileName fn
= wxFileSystem::URLToFileName(GetRightLocation(spec
));
276 const wxString found
= wxFindFirstFile(ms_root
+ fn
.GetFullPath(), flags
);
279 return wxFileSystem::FileNameToURL(found
);
282 wxString
wxLocalFSHandler::FindNext()
284 const wxString found
= wxFindNextFile();
287 return wxFileSystem::FileNameToURL(found
);
292 //-----------------------------------------------------------------------------
294 //-----------------------------------------------------------------------------
296 IMPLEMENT_DYNAMIC_CLASS(wxFileSystem
, wxObject
)
297 IMPLEMENT_ABSTRACT_CLASS(wxFSFile
, wxObject
)
300 wxList
wxFileSystem::m_Handlers
;
303 wxFileSystem::~wxFileSystem()
305 WX_CLEAR_HASH_MAP(wxFSHandlerHash
, m_LocalHandlers
)
309 static wxString
MakeCorrectPath(const wxString
& path
)
316 for (i
= 0; i
< cnt
; i
++)
317 if (p
.GetChar(i
) == wxT('\\')) p
.GetWritableChar(i
) = wxT('/'); // Want to be windows-safe
319 if (p
.Left(2) == wxT("./")) { p
= p
.Mid(2); cnt
-= 2; }
321 if (cnt
< 3) return p
;
323 r
<< p
.GetChar(0) << p
.GetChar(1);
325 // skip trailing ../.., if any
326 for (i
= 2; i
< cnt
&& (p
.GetChar(i
) == wxT('/') || p
.GetChar(i
) == wxT('.')); i
++) r
<< p
.GetChar(i
);
328 // remove back references: translate dir1/../dir2 to dir2
332 if (p
.GetChar(i
) == wxT('/') && p
.GetChar(i
-1) == wxT('.') && p
.GetChar(i
-2) == wxT('.'))
334 for (j
= r
.length() - 2; j
>= 0 && r
.GetChar(j
) != wxT('/') && r
.GetChar(j
) != wxT(':'); j
--) {}
335 if (j
>= 0 && r
.GetChar(j
) != wxT(':'))
337 for (j
= j
- 1; j
>= 0 && r
.GetChar(j
) != wxT('/') && r
.GetChar(j
) != wxT(':'); j
--) {}
343 for (; i
< cnt
; i
++) r
<< p
.GetChar(i
);
349 void wxFileSystem::ChangePathTo(const wxString
& location
, bool is_dir
)
353 m_Path
= MakeCorrectPath(location
);
357 if (!m_Path
.empty() && m_Path
.Last() != wxT('/') && m_Path
.Last() != wxT(':'))
363 for (i
= m_Path
.length()-1; i
>= 0; i
--)
365 if (m_Path
[(unsigned int) i
] == wxT('/'))
367 if ((i
> 1) && (m_Path
[(unsigned int) (i
-1)] == wxT('/')) && (m_Path
[(unsigned int) (i
-2)] == wxT(':')))
378 else if (m_Path
[(unsigned int) i
] == wxT(':')) {
385 for (i
= 0; i
< (int) m_Path
.length(); i
++)
387 if (m_Path
[(unsigned int) i
] == wxT(':'))
393 if (i
== (int) m_Path
.length())
394 m_Path
= wxEmptyString
;
398 m_Path
.Remove(pathpos
+1);
405 wxFileSystemHandler
*wxFileSystem::MakeLocal(wxFileSystemHandler
*h
)
407 wxClassInfo
*classinfo
= h
->GetClassInfo();
409 if (classinfo
->IsDynamic())
411 wxFileSystemHandler
*& local
= m_LocalHandlers
[classinfo
];
413 local
= (wxFileSystemHandler
*)classinfo
->CreateObject();
424 wxFSFile
* wxFileSystem::OpenFile(const wxString
& location
, int flags
)
426 if ((flags
& wxFS_READ
) == 0)
429 wxString loc
= MakeCorrectPath(location
);
433 wxList::compatibility_iterator node
;
437 for (i
= 0; i
< ln
; i
++)
439 switch ( loc
[i
].GetValue() )
441 case wxT('/') : case wxT(':') : case wxT('#') :
445 if (meta
!= 0) break;
447 m_LastName
= wxEmptyString
;
449 // try relative paths first :
450 if (meta
!= wxT(':'))
452 node
= m_Handlers
.GetFirst();
455 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
456 if (h
->CanOpen(m_Path
+ loc
))
458 s
= MakeLocal(h
)->OpenFile(*this, m_Path
+ loc
);
459 if (s
) { m_LastName
= m_Path
+ loc
; break; }
461 node
= node
->GetNext();
465 // if failed, try absolute paths :
468 node
= m_Handlers
.GetFirst();
471 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
->GetData();
474 s
= MakeLocal(h
)->OpenFile(*this, loc
);
475 if (s
) { m_LastName
= loc
; break; }
477 node
= node
->GetNext();
481 if (s
&& (flags
& wxFS_SEEKABLE
) != 0 && !s
->GetStream()->IsSeekable())
483 wxBackedInputStream
*stream
;
484 stream
= new wxBackedInputStream(s
->DetachStream());
485 stream
->FindLength();
486 s
->SetStream(stream
);
494 wxString
wxFileSystem::FindFirst(const wxString
& spec
, int flags
)
496 wxList::compatibility_iterator node
;
497 wxString
spec2(spec
);
499 m_FindFileHandler
= NULL
;
501 for (int i
= spec2
.length()-1; i
>= 0; i
--)
502 if (spec2
[(unsigned int) i
] == wxT('\\')) spec2
.GetWritableChar(i
) = wxT('/'); // Want to be windows-safe
504 node
= m_Handlers
.GetFirst();
507 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
508 if (h
-> CanOpen(m_Path
+ spec2
))
510 m_FindFileHandler
= MakeLocal(h
);
511 return m_FindFileHandler
-> FindFirst(m_Path
+ spec2
, flags
);
513 node
= node
->GetNext();
516 node
= m_Handlers
.GetFirst();
519 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
520 if (h
-> CanOpen(spec2
))
522 m_FindFileHandler
= MakeLocal(h
);
523 return m_FindFileHandler
-> FindFirst(spec2
, flags
);
525 node
= node
->GetNext();
528 return wxEmptyString
;
533 wxString
wxFileSystem::FindNext()
535 if (m_FindFileHandler
== NULL
) return wxEmptyString
;
536 else return m_FindFileHandler
-> FindNext();
539 bool wxFileSystem::FindFileInPath(wxString
*pStr
,
540 const wxString
& path
,
541 const wxString
& basename
)
543 // we assume that it's not empty
544 wxCHECK_MSG( !basename
.empty(), false,
545 wxT("empty file name in wxFileSystem::FindFileInPath"));
548 // skip path separator in the beginning of the file name if present
549 if ( wxIsPathSeparator(basename
[0u]) )
550 name
= basename
.substr(1);
554 wxStringTokenizer
tokenizer(path
, wxPATH_SEP
);
555 while ( tokenizer
.HasMoreTokens() )
557 wxString strFile
= tokenizer
.GetNextToken();
558 if ( !wxEndsWithPathSeparator(strFile
) )
559 strFile
+= wxFILE_SEP_PATH
;
562 wxFSFile
*file
= OpenFile(strFile
);
574 void wxFileSystem::AddHandler(wxFileSystemHandler
*handler
)
576 // prepend the handler to the beginning of the list because handlers added
577 // last should have the highest priority to allow overriding them
578 m_Handlers
.Insert((size_t)0, handler
);
581 wxFileSystemHandler
* wxFileSystem::RemoveHandler(wxFileSystemHandler
*handler
)
583 // if handler has already been removed (or deleted)
584 // we return NULL. This is by design in case
585 // CleanUpHandlers() is called before RemoveHandler
586 // is called, as we cannot control the order
587 // which modules are unloaded
588 if (!m_Handlers
.DeleteObject(handler
))
595 bool wxFileSystem::HasHandlerForPath(const wxString
&location
)
597 for ( wxList::compatibility_iterator node
= m_Handlers
.GetFirst();
598 node
; node
= node
->GetNext() )
600 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
->GetData();
601 if (h
->CanOpen(location
))
608 void wxFileSystem::CleanUpHandlers()
610 WX_CLEAR_LIST(wxList
, m_Handlers
);
613 static const wxString
g_unixPathString(wxT("/"));
614 static const wxString
g_nativePathString(wxFILE_SEP_PATH
);
616 // Returns the native path for a file URL
617 wxFileName
wxFileSystem::URLToFileName(const wxString
& url
)
621 if ( path
.Find(wxT("file://")) == 0 )
625 else if ( path
.Find(wxT("file:")) == 0 )
629 // Remove preceding double slash on Mac Classic
630 #if defined(__WXMAC__) && !defined(__UNIX__)
631 else if ( path
.Find(wxT("//")) == 0 )
635 path
= wxURI::Unescape(path
);
638 // file urls either start with a forward slash (local harddisk),
639 // otherwise they have a servername/sharename notation,
640 // which only exists on msw and corresponds to a unc
641 if ( path
.length() > 1 && (path
[0u] == wxT('/') && path
[1u] != wxT('/')) )
645 else if ( (url
.Find(wxT("file://")) == 0) &&
646 (path
.Find(wxT('/')) != wxNOT_FOUND
) &&
647 (path
.length() > 1) && (path
[1u] != wxT(':')) )
649 path
= wxT("//") + path
;
653 path
.Replace(g_unixPathString
, g_nativePathString
);
655 return wxFileName(path
, wxPATH_NATIVE
);
658 // Escapes non-ASCII and others characters in file: URL to be valid URLs
659 static wxString
EscapeFileNameCharsInURL(const char *in
)
663 for ( const unsigned char *p
= (const unsigned char*)in
; *p
; ++p
)
665 const unsigned char c
= *p
;
667 // notice that all colons *must* be encoded in the paths used by
668 // wxFileSystem even though this makes URLs produced by this method
669 // unusable with IE under Windows as it requires "file:///c:/foo.bar"
670 // and doesn't accept "file:///c%3a/foo.bar" -- but then we never made
671 // any guarantees about general suitability of the strings returned by
672 // this method, they must work with wxFileSystem only and not encoding
673 // the colon breaks handling of
674 // "http://wherever/whatever.zip#zip:filename.ext" URLs so we really
675 // can't do this without heavy changes to the parsing code here, in
676 // particular in GetRightLocation()
678 if ( c
== '/' || c
== '-' || c
== '.' || c
== '_' || c
== '~' ||
679 (c
>= '0' && c
<= '9') ||
680 (c
>= 'a' && c
<= 'z') ||
681 (c
>= 'A' && c
<= 'Z') )
687 s
<< wxString::Format("%%%02x", c
);
694 // Returns the file URL for a native path
695 wxString
wxFileSystem::FileNameToURL(const wxFileName
& filename
)
697 wxFileName fn
= filename
;
698 fn
.Normalize(wxPATH_NORM_DOTS
| wxPATH_NORM_TILDE
| wxPATH_NORM_ABSOLUTE
);
699 wxString url
= fn
.GetFullPath(wxPATH_NATIVE
);
702 // unc notation, wxMSW
703 if ( url
.Find(wxT("\\\\")) == 0 )
705 url
= wxT("//") + url
.Mid(2);
709 url
= wxT("/") + url
;
711 url
= wxT("/") + url
;
717 url
.Replace(g_nativePathString
, g_unixPathString
);
719 // Do wxURI- and common practice-compatible escaping: encode the string
720 // into UTF-8, then escape anything non-ASCII:
721 return wxT("file:") + EscapeFileNameCharsInURL(url
.utf8_str());
727 class wxFileSystemModule
: public wxModule
729 DECLARE_DYNAMIC_CLASS(wxFileSystemModule
)
732 wxFileSystemModule() :
738 virtual bool OnInit()
740 m_handler
= new wxLocalFSHandler
;
741 wxFileSystem::AddHandler(m_handler
);
744 virtual void OnExit()
746 delete wxFileSystem::RemoveHandler(m_handler
);
748 wxFileSystem::CleanUpHandlers();
752 wxFileSystemHandler
* m_handler
;
756 IMPLEMENT_DYNAMIC_CLASS(wxFileSystemModule
, wxModule
)
760 wxFSInputStream::wxFSInputStream(const wxString
& filename
, int flags
)
763 m_file
= fs
.OpenFile(filename
, flags
| wxFS_READ
);
767 wxInputStream
* const stream
= m_file
->GetStream();
770 // Notice that we pass the stream by reference: it shouldn't be
771 // deleted by us as it's owned by m_file already.
772 InitParentStream(*stream
);
777 wxFSInputStream::~wxFSInputStream()