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/sysopt.h"
27 #include "wx/wfstream.h"
28 #include "wx/mimetype.h"
29 #include "wx/filename.h"
30 #include "wx/tokenzr.h"
32 #include "wx/private/fileback.h"
34 // ----------------------------------------------------------------------------
36 // ----------------------------------------------------------------------------
38 const wxString
& wxFSFile::GetMimeType() const
40 if ( m_MimeType
.empty() && !m_Location
.empty() )
42 wxConstCast(this, wxFSFile
)->m_MimeType
=
43 wxFileSystemHandler::GetMimeTypeFromExt(m_Location
);
49 // ----------------------------------------------------------------------------
50 // wxFileSystemHandler
51 // ----------------------------------------------------------------------------
53 IMPLEMENT_ABSTRACT_CLASS(wxFileSystemHandler
, wxObject
)
57 wxString
wxFileSystemHandler::GetMimeTypeFromExt(const wxString
& location
)
60 wxString loc
= GetRightLocation(location
);
62 int l
= loc
.length(), l2
;
65 for (int i
= l
-1; i
>= 0; i
--)
67 c
= loc
[(unsigned int) i
];
72 ext
= loc
.Right(l2
-i
-1);
75 if ( (c
== wxT('/')) || (c
== wxT('\\')) || (c
== wxT(':')) )
80 static bool s_MinimalMimeEnsured
= false;
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 bool useMimeTypesManager
= true;
85 #if wxUSE_SYSTEM_OPTIONS
86 useMimeTypesManager
= (wxSystemOptions::GetOptionInt(wxT("filesys.no-mimetypesmanager")) == 0);
89 if (useMimeTypesManager
)
91 if (!s_MinimalMimeEnsured
)
93 static const wxFileTypeInfo fallbacks
[] =
95 wxFileTypeInfo(_T("image/jpeg"),
98 _T("JPEG image (from fallback)"),
99 _T("jpg"), _T("jpeg"), _T("JPG"), _T("JPEG"), wxNullPtr
),
100 wxFileTypeInfo(_T("image/gif"),
103 _T("GIF image (from fallback)"),
104 _T("gif"), _T("GIF"), wxNullPtr
),
105 wxFileTypeInfo(_T("image/png"),
108 _T("PNG image (from fallback)"),
109 _T("png"), _T("PNG"), wxNullPtr
),
110 wxFileTypeInfo(_T("image/bmp"),
113 _T("windows bitmap image (from fallback)"),
114 _T("bmp"), _T("BMP"), wxNullPtr
),
115 wxFileTypeInfo(_T("text/html"),
118 _T("HTML document (from fallback)"),
119 _T("htm"), _T("html"), _T("HTM"), _T("HTML"), wxNullPtr
),
120 // must terminate the table with this!
123 wxTheMimeTypesManager
->AddFallbacks(fallbacks
);
124 s_MinimalMimeEnsured
= true;
127 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
128 if ( !ft
|| !ft
-> GetMimeType(&mime
) )
130 mime
= wxEmptyString
;
140 if ( ext
.IsSameAs(wxT("htm"), false) || ext
.IsSameAs(_T("html"), false) )
141 return wxT("text/html");
142 if ( ext
.IsSameAs(wxT("jpg"), false) || ext
.IsSameAs(_T("jpeg"), false) )
143 return wxT("image/jpeg");
144 if ( ext
.IsSameAs(wxT("gif"), false) )
145 return wxT("image/gif");
146 if ( ext
.IsSameAs(wxT("png"), false) )
147 return wxT("image/png");
148 if ( ext
.IsSameAs(wxT("bmp"), false) )
149 return wxT("image/bmp");
150 return wxEmptyString
;
157 wxString
wxFileSystemHandler::GetProtocol(const wxString
& location
)
159 wxString s
= wxEmptyString
;
160 int i
, l
= location
.length();
163 for (i
= l
-1; (i
>= 0) && ((location
[i
] != wxT('#')) || (!fnd
)); i
--) {
164 if ((location
[i
] == wxT(':')) && (i
!= 1 /*win: C:\path*/)) fnd
= true;
166 if (!fnd
) return wxT("file");
167 for (++i
; (i
< l
) && (location
[i
] != wxT(':')); i
++) s
<< location
[i
];
173 wxString
wxFileSystemHandler::GetLeftLocation(const wxString
& location
)
178 for (i
= location
.length()-1; i
>= 0; i
--) {
179 if ((location
[i
] == wxT(':')) && (i
!= 1 /*win: C:\path*/)) fnd
= true;
180 else if (fnd
&& (location
[i
] == wxT('#'))) return location
.Left(i
);
182 return wxEmptyString
;
186 wxString
wxFileSystemHandler::GetRightLocation(const wxString
& location
)
188 int i
, l
= location
.length();
193 ((location
[i
] != wxT(':')) || (i
== 1) || (location
[i
-2] == wxT(':')));
196 if (location
[i
] == wxT('#')) l2
= i
+ 1;
198 if (i
== 0) return wxEmptyString
;
199 else return location
.Mid(i
+ 1, l2
- i
- 2);
203 wxString
wxFileSystemHandler::GetAnchor(const wxString
& location
)
206 int l
= location
.length();
208 for (int i
= l
-1; i
>= 0; i
--) {
211 return location
.Right(l
-i
-1);
212 else if ((c
== wxT('/')) || (c
== wxT('\\')) || (c
== wxT(':')))
213 return wxEmptyString
;
215 return wxEmptyString
;
219 wxString
wxFileSystemHandler::FindFirst(const wxString
& WXUNUSED(spec
),
222 return wxEmptyString
;
225 wxString
wxFileSystemHandler::FindNext()
227 return wxEmptyString
;
230 //--------------------------------------------------------------------------------
232 //--------------------------------------------------------------------------------
235 wxString
wxLocalFSHandler::ms_root
;
237 bool wxLocalFSHandler::CanOpen(const wxString
& location
)
239 return GetProtocol(location
) == wxT("file");
242 wxFSFile
* wxLocalFSHandler::OpenFile(wxFileSystem
& WXUNUSED(fs
), const wxString
& location
)
244 // location has Unix path separators
245 wxString right
= GetRightLocation(location
);
246 wxFileName fn
= wxFileSystem::URLToFileName(right
);
247 wxString fullpath
= ms_root
+ fn
.GetFullPath();
249 if (!wxFileExists(fullpath
))
250 return (wxFSFile
*) NULL
;
252 // we need to check whether we can really read from this file, otherwise
253 // wxFSFile is not going to work
255 wxFFileInputStream
*is
= new wxFFileInputStream(fullpath
);
257 wxFileInputStream
*is
= new wxFileInputStream(fullpath
);
259 #error One of wxUSE_FILE or wxUSE_FFILE must be set to 1 for wxFSHandler to work
264 return (wxFSFile
*) NULL
;
267 return new wxFSFile(is
,
272 ,wxDateTime(wxFileModificationTime(fullpath
))
273 #endif // wxUSE_DATETIME
277 wxString
wxLocalFSHandler::FindFirst(const wxString
& spec
, int flags
)
279 wxFileName fn
= wxFileSystem::URLToFileName(GetRightLocation(spec
));
280 return wxFindFirstFile(ms_root
+ fn
.GetFullPath(), flags
);
283 wxString
wxLocalFSHandler::FindNext()
285 return wxFindNextFile();
290 //-----------------------------------------------------------------------------
292 //-----------------------------------------------------------------------------
294 IMPLEMENT_DYNAMIC_CLASS(wxFileSystem
, wxObject
)
295 IMPLEMENT_ABSTRACT_CLASS(wxFSFile
, wxObject
)
298 wxList
wxFileSystem::m_Handlers
;
301 wxFileSystem::~wxFileSystem()
303 WX_CLEAR_HASH_MAP(wxFSHandlerHash
, m_LocalHandlers
)
307 static wxString
MakeCorrectPath(const wxString
& path
)
314 for (i
= 0; i
< cnt
; i
++)
315 if (p
.GetChar(i
) == wxT('\\')) p
.GetWritableChar(i
) = wxT('/'); // Want to be windows-safe
317 if (p
.Left(2) == wxT("./")) { p
= p
.Mid(2); cnt
-= 2; }
319 if (cnt
< 3) return p
;
321 r
<< p
.GetChar(0) << p
.GetChar(1);
323 // skip trailing ../.., if any
324 for (i
= 2; i
< cnt
&& (p
.GetChar(i
) == wxT('/') || p
.GetChar(i
) == wxT('.')); i
++) r
<< p
.GetChar(i
);
326 // remove back references: translate dir1/../dir2 to dir2
330 if (p
.GetChar(i
) == wxT('/') && p
.GetChar(i
-1) == wxT('.') && p
.GetChar(i
-2) == wxT('.'))
332 for (j
= r
.length() - 2; j
>= 0 && r
.GetChar(j
) != wxT('/') && r
.GetChar(j
) != wxT(':'); j
--) {}
333 if (j
>= 0 && r
.GetChar(j
) != wxT(':'))
335 for (j
= j
- 1; j
>= 0 && r
.GetChar(j
) != wxT('/') && r
.GetChar(j
) != wxT(':'); j
--) {}
341 for (; i
< cnt
; i
++) r
<< p
.GetChar(i
);
347 void wxFileSystem::ChangePathTo(const wxString
& location
, bool is_dir
)
351 m_Path
= MakeCorrectPath(location
);
355 if (m_Path
.length() > 0 && m_Path
.Last() != wxT('/') && m_Path
.Last() != wxT(':'))
361 for (i
= m_Path
.length()-1; i
>= 0; i
--)
363 if (m_Path
[(unsigned int) i
] == wxT('/'))
365 if ((i
> 1) && (m_Path
[(unsigned int) (i
-1)] == wxT('/')) && (m_Path
[(unsigned int) (i
-2)] == wxT(':')))
376 else if (m_Path
[(unsigned int) i
] == wxT(':')) {
383 for (i
= 0; i
< (int) m_Path
.length(); i
++)
385 if (m_Path
[(unsigned int) i
] == wxT(':'))
391 if (i
== (int) m_Path
.length())
392 m_Path
= wxEmptyString
;
396 m_Path
.Remove(pathpos
+1);
403 wxFileSystemHandler
*wxFileSystem::MakeLocal(wxFileSystemHandler
*h
)
405 wxClassInfo
*classinfo
= h
->GetClassInfo();
407 if (classinfo
->IsDynamic())
409 wxFileSystemHandler
*& local
= m_LocalHandlers
[classinfo
];
411 local
= (wxFileSystemHandler
*)classinfo
->CreateObject();
422 wxFSFile
* wxFileSystem::OpenFile(const wxString
& location
, int flags
)
424 if ((flags
& wxFS_READ
) == 0)
427 wxString loc
= MakeCorrectPath(location
);
431 wxList::compatibility_iterator node
;
435 for (i
= 0; i
< ln
; i
++)
437 switch ( loc
[i
].GetValue() )
439 case wxT('/') : case wxT(':') : case wxT('#') :
443 if (meta
!= 0) break;
445 m_LastName
= wxEmptyString
;
447 // try relative paths first :
448 if (meta
!= wxT(':'))
450 node
= m_Handlers
.GetFirst();
453 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
454 if (h
->CanOpen(m_Path
+ loc
))
456 s
= MakeLocal(h
)->OpenFile(*this, m_Path
+ loc
);
457 if (s
) { m_LastName
= m_Path
+ loc
; break; }
459 node
= node
->GetNext();
463 // if failed, try absolute paths :
466 node
= m_Handlers
.GetFirst();
469 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
->GetData();
472 s
= MakeLocal(h
)->OpenFile(*this, loc
);
473 if (s
) { m_LastName
= loc
; break; }
475 node
= node
->GetNext();
479 if (s
&& (flags
& wxFS_SEEKABLE
) != 0 && !s
->GetStream()->IsSeekable())
481 wxBackedInputStream
*stream
;
482 stream
= new wxBackedInputStream(s
->DetachStream());
483 stream
->FindLength();
484 s
->SetStream(stream
);
492 wxString
wxFileSystem::FindFirst(const wxString
& spec
, int flags
)
494 wxList::compatibility_iterator node
;
495 wxString
spec2(spec
);
497 m_FindFileHandler
= NULL
;
499 for (int i
= spec2
.length()-1; i
>= 0; i
--)
500 if (spec2
[(unsigned int) i
] == wxT('\\')) spec2
.GetWritableChar(i
) = wxT('/'); // Want to be windows-safe
502 node
= m_Handlers
.GetFirst();
505 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
506 if (h
-> CanOpen(m_Path
+ spec2
))
508 m_FindFileHandler
= MakeLocal(h
);
509 return m_FindFileHandler
-> FindFirst(m_Path
+ spec2
, flags
);
511 node
= node
->GetNext();
514 node
= m_Handlers
.GetFirst();
517 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
518 if (h
-> CanOpen(spec2
))
520 m_FindFileHandler
= MakeLocal(h
);
521 return m_FindFileHandler
-> FindFirst(spec2
, flags
);
523 node
= node
->GetNext();
526 return wxEmptyString
;
531 wxString
wxFileSystem::FindNext()
533 if (m_FindFileHandler
== NULL
) return wxEmptyString
;
534 else return m_FindFileHandler
-> FindNext();
537 bool wxFileSystem::FindFileInPath(wxString
*pStr
,
538 const wxString
& path
,
539 const wxString
& basename
)
541 // we assume that it's not empty
542 wxCHECK_MSG( !basename
.empty(), false,
543 _T("empty file name in wxFileSystem::FindFileInPath"));
546 // skip path separator in the beginning of the file name if present
547 if ( wxIsPathSeparator(basename
[0u]) )
548 name
= basename
.substr(1);
552 wxStringTokenizer
tokenizer(path
, wxPATH_SEP
);
553 while ( tokenizer
.HasMoreTokens() )
555 wxString strFile
= tokenizer
.GetNextToken();
556 if ( !wxEndsWithPathSeparator(strFile
) )
557 strFile
+= wxFILE_SEP_PATH
;
560 wxFSFile
*file
= OpenFile(strFile
);
572 void wxFileSystem::AddHandler(wxFileSystemHandler
*handler
)
574 // prepend the handler to the beginning of the list because handlers added
575 // last should have the highest priority to allow overriding them
576 m_Handlers
.Insert((size_t)0, handler
);
579 wxFileSystemHandler
* wxFileSystem::RemoveHandler(wxFileSystemHandler
*handler
)
581 // if handler has already been removed (or deleted)
582 // we return NULL. This is by design in case
583 // CleanUpHandlers() is called before RemoveHandler
584 // is called, as we cannot control the order
585 // which modules are unloaded
586 if (!m_Handlers
.DeleteObject(handler
))
593 bool wxFileSystem::HasHandlerForPath(const wxString
&location
)
595 for ( wxList::compatibility_iterator node
= m_Handlers
.GetFirst();
596 node
; node
= node
->GetNext() )
598 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
->GetData();
599 if (h
->CanOpen(location
))
606 void wxFileSystem::CleanUpHandlers()
608 WX_CLEAR_LIST(wxList
, m_Handlers
);
611 static const wxString
g_unixPathString(wxT("/"));
612 static const wxString
g_nativePathString(wxFILE_SEP_PATH
);
614 // Returns the native path for a file URL
615 wxFileName
wxFileSystem::URLToFileName(const wxString
& url
)
619 if ( path
.Find(wxT("file://")) == 0 )
623 else if ( path
.Find(wxT("file:")) == 0 )
627 // Remove preceding double slash on Mac Classic
628 #if defined(__WXMAC__) && !defined(__UNIX__)
629 else if ( path
.Find(wxT("//")) == 0 )
633 path
= wxURI::Unescape(path
);
636 // file urls either start with a forward slash (local harddisk),
637 // otherwise they have a servername/sharename notation,
638 // which only exists on msw and corresponds to a unc
639 if ( path
[0u] == wxT('/') && path
[1u] != wxT('/'))
643 else if ( (url
.Find(wxT("file://")) == 0) &&
644 (path
.Find(wxT('/')) != wxNOT_FOUND
) &&
645 (path
.length() > 1) && (path
[1u] != wxT(':')) )
647 path
= wxT("//") + path
;
651 path
.Replace(g_unixPathString
, g_nativePathString
);
653 return wxFileName(path
, wxPATH_NATIVE
);
656 // Returns the file URL for a native path
657 wxString
wxFileSystem::FileNameToURL(const wxFileName
& filename
)
659 wxFileName fn
= filename
;
660 fn
.Normalize(wxPATH_NORM_DOTS
| wxPATH_NORM_TILDE
| wxPATH_NORM_ABSOLUTE
);
661 wxString url
= fn
.GetFullPath(wxPATH_NATIVE
);
664 // unc notation, wxMSW
665 if ( url
.Find(wxT("\\\\")) == 0 )
667 url
= wxT("//") + url
.Mid(2);
671 url
= wxT("/") + url
;
673 url
= wxT("/") + url
;
679 url
.Replace(g_nativePathString
, g_unixPathString
);
680 url
.Replace(wxT("%"), wxT("%25")); // '%'s must be replaced first!
681 url
.Replace(wxT("#"), wxT("%23"));
683 // notice that all colons *must* be encoded in the paths used by
684 // wxFileSystem even though this makes URLs produced by this method
685 // unusable with IE under Windows as it requires "file:///c:/foo.bar" and
686 // doesn't accept "file:///c%3a/foo.bar" -- but then we never made any
687 // guarantees about general suitability of the strings returned by this
688 // method, they must work with wxFileSystem only and not encoding the colon
689 // breaks handling of "http://wherever/whatever.zip#zip:filename.ext" URLs
690 // so we really can't do this without heavy changes to the parsing code
691 // here, in particular in GetRightLocation()
692 url
.Replace(wxT(":"), wxT("%3A"));
693 url
= wxT("file:") + url
;
700 class wxFileSystemModule
: public wxModule
702 DECLARE_DYNAMIC_CLASS(wxFileSystemModule
)
705 wxFileSystemModule() :
711 virtual bool OnInit()
713 m_handler
= new wxLocalFSHandler
;
714 wxFileSystem::AddHandler(m_handler
);
717 virtual void OnExit()
719 delete wxFileSystem::RemoveHandler(m_handler
);
721 wxFileSystem::CleanUpHandlers();
725 wxFileSystemHandler
* m_handler
;
729 IMPLEMENT_DYNAMIC_CLASS(wxFileSystemModule
, wxModule
)