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 #if wxUSE_SYSTEM_OPTIONS
85 if ( !wxSystemOptions::GetOptionInt(wxT("filesys.no-mimetypesmanager")) )
88 if (!s_MinimalMimeEnsured
)
90 static const wxFileTypeInfo fallbacks
[] =
92 wxFileTypeInfo(_T("image/jpeg"),
95 _T("JPEG image (from fallback)"),
96 _T("jpg"), _T("jpeg"), _T("JPG"), _T("JPEG"), wxNullPtr
),
97 wxFileTypeInfo(_T("image/gif"),
100 _T("GIF image (from fallback)"),
101 _T("gif"), _T("GIF"), wxNullPtr
),
102 wxFileTypeInfo(_T("image/png"),
105 _T("PNG image (from fallback)"),
106 _T("png"), _T("PNG"), wxNullPtr
),
107 wxFileTypeInfo(_T("image/bmp"),
110 _T("windows bitmap image (from fallback)"),
111 _T("bmp"), _T("BMP"), wxNullPtr
),
112 wxFileTypeInfo(_T("text/html"),
115 _T("HTML document (from fallback)"),
116 _T("htm"), _T("html"), _T("HTM"), _T("HTML"), wxNullPtr
),
117 // must terminate the table with this!
120 wxTheMimeTypesManager
->AddFallbacks(fallbacks
);
121 s_MinimalMimeEnsured
= true;
124 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
125 if ( !ft
|| !ft
-> GetMimeType(&mime
) )
127 mime
= wxEmptyString
;
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
;
154 wxString
wxFileSystemHandler::GetProtocol(const wxString
& location
)
156 wxString s
= wxEmptyString
;
157 int i
, l
= location
.length();
160 for (i
= l
-1; (i
>= 0) && ((location
[i
] != wxT('#')) || (!fnd
)); i
--) {
161 if ((location
[i
] == wxT(':')) && (i
!= 1 /*win: C:\path*/)) fnd
= true;
163 if (!fnd
) return wxT("file");
164 for (++i
; (i
< l
) && (location
[i
] != wxT(':')); i
++) s
<< location
[i
];
170 wxString
wxFileSystemHandler::GetLeftLocation(const wxString
& location
)
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
);
179 return wxEmptyString
;
183 wxString
wxFileSystemHandler::GetRightLocation(const wxString
& location
)
185 int i
, l
= location
.length();
190 ((location
[i
] != wxT(':')) || (i
== 1) || (location
[i
-2] == wxT(':')));
193 if (location
[i
] == wxT('#')) l2
= i
+ 1;
195 if (i
== 0) return wxEmptyString
;
196 else return location
.Mid(i
+ 1, l2
- i
- 2);
200 wxString
wxFileSystemHandler::GetAnchor(const wxString
& location
)
203 int l
= location
.length();
205 for (int i
= l
-1; i
>= 0; i
--) {
208 return location
.Right(l
-i
-1);
209 else if ((c
== wxT('/')) || (c
== wxT('\\')) || (c
== wxT(':')))
210 return wxEmptyString
;
212 return wxEmptyString
;
216 wxString
wxFileSystemHandler::FindFirst(const wxString
& WXUNUSED(spec
),
219 return wxEmptyString
;
222 wxString
wxFileSystemHandler::FindNext()
224 return wxEmptyString
;
227 //--------------------------------------------------------------------------------
229 //--------------------------------------------------------------------------------
232 wxString
wxLocalFSHandler::ms_root
;
234 bool wxLocalFSHandler::CanOpen(const wxString
& location
)
236 return GetProtocol(location
) == wxT("file");
239 wxFSFile
* wxLocalFSHandler::OpenFile(wxFileSystem
& WXUNUSED(fs
), const wxString
& location
)
241 // location has Unix path separators
242 wxString right
= GetRightLocation(location
);
243 wxFileName fn
= wxFileSystem::URLToFileName(right
);
244 wxString fullpath
= ms_root
+ fn
.GetFullPath();
246 if (!wxFileExists(fullpath
))
249 // we need to check whether we can really read from this file, otherwise
250 // wxFSFile is not going to work
252 wxFFileInputStream
*is
= new wxFFileInputStream(fullpath
);
254 wxFileInputStream
*is
= new wxFileInputStream(fullpath
);
256 #error One of wxUSE_FILE or wxUSE_FFILE must be set to 1 for wxFSHandler to work
264 return new wxFSFile(is
,
269 ,wxDateTime(wxFileModificationTime(fullpath
))
270 #endif // wxUSE_DATETIME
274 wxString
wxLocalFSHandler::FindFirst(const wxString
& spec
, int flags
)
276 wxFileName fn
= wxFileSystem::URLToFileName(GetRightLocation(spec
));
277 return wxFindFirstFile(ms_root
+ fn
.GetFullPath(), flags
);
280 wxString
wxLocalFSHandler::FindNext()
282 return wxFindNextFile();
287 //-----------------------------------------------------------------------------
289 //-----------------------------------------------------------------------------
291 IMPLEMENT_DYNAMIC_CLASS(wxFileSystem
, wxObject
)
292 IMPLEMENT_ABSTRACT_CLASS(wxFSFile
, wxObject
)
295 wxList
wxFileSystem::m_Handlers
;
298 wxFileSystem::~wxFileSystem()
300 WX_CLEAR_HASH_MAP(wxFSHandlerHash
, m_LocalHandlers
)
304 static wxString
MakeCorrectPath(const wxString
& path
)
311 for (i
= 0; i
< cnt
; i
++)
312 if (p
.GetChar(i
) == wxT('\\')) p
.GetWritableChar(i
) = wxT('/'); // Want to be windows-safe
314 if (p
.Left(2) == wxT("./")) { p
= p
.Mid(2); cnt
-= 2; }
316 if (cnt
< 3) return p
;
318 r
<< p
.GetChar(0) << p
.GetChar(1);
320 // skip trailing ../.., if any
321 for (i
= 2; i
< cnt
&& (p
.GetChar(i
) == wxT('/') || p
.GetChar(i
) == wxT('.')); i
++) r
<< p
.GetChar(i
);
323 // remove back references: translate dir1/../dir2 to dir2
327 if (p
.GetChar(i
) == wxT('/') && p
.GetChar(i
-1) == wxT('.') && p
.GetChar(i
-2) == wxT('.'))
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(':'))
332 for (j
= j
- 1; j
>= 0 && r
.GetChar(j
) != wxT('/') && r
.GetChar(j
) != wxT(':'); j
--) {}
338 for (; i
< cnt
; i
++) r
<< p
.GetChar(i
);
344 void wxFileSystem::ChangePathTo(const wxString
& location
, bool is_dir
)
348 m_Path
= MakeCorrectPath(location
);
352 if (m_Path
.length() > 0 && m_Path
.Last() != wxT('/') && m_Path
.Last() != wxT(':'))
358 for (i
= m_Path
.length()-1; i
>= 0; i
--)
360 if (m_Path
[(unsigned int) i
] == wxT('/'))
362 if ((i
> 1) && (m_Path
[(unsigned int) (i
-1)] == wxT('/')) && (m_Path
[(unsigned int) (i
-2)] == wxT(':')))
373 else if (m_Path
[(unsigned int) i
] == wxT(':')) {
380 for (i
= 0; i
< (int) m_Path
.length(); i
++)
382 if (m_Path
[(unsigned int) i
] == wxT(':'))
388 if (i
== (int) m_Path
.length())
389 m_Path
= wxEmptyString
;
393 m_Path
.Remove(pathpos
+1);
400 wxFileSystemHandler
*wxFileSystem::MakeLocal(wxFileSystemHandler
*h
)
402 wxClassInfo
*classinfo
= h
->GetClassInfo();
404 if (classinfo
->IsDynamic())
406 wxFileSystemHandler
*& local
= m_LocalHandlers
[classinfo
];
408 local
= (wxFileSystemHandler
*)classinfo
->CreateObject();
419 wxFSFile
* wxFileSystem::OpenFile(const wxString
& location
, int flags
)
421 if ((flags
& wxFS_READ
) == 0)
424 wxString loc
= MakeCorrectPath(location
);
428 wxList::compatibility_iterator node
;
432 for (i
= 0; i
< ln
; i
++)
434 switch ( loc
[i
].GetValue() )
436 case wxT('/') : case wxT(':') : case wxT('#') :
440 if (meta
!= 0) break;
442 m_LastName
= wxEmptyString
;
444 // try relative paths first :
445 if (meta
!= wxT(':'))
447 node
= m_Handlers
.GetFirst();
450 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
451 if (h
->CanOpen(m_Path
+ loc
))
453 s
= MakeLocal(h
)->OpenFile(*this, m_Path
+ loc
);
454 if (s
) { m_LastName
= m_Path
+ loc
; break; }
456 node
= node
->GetNext();
460 // if failed, try absolute paths :
463 node
= m_Handlers
.GetFirst();
466 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
->GetData();
469 s
= MakeLocal(h
)->OpenFile(*this, loc
);
470 if (s
) { m_LastName
= loc
; break; }
472 node
= node
->GetNext();
476 if (s
&& (flags
& wxFS_SEEKABLE
) != 0 && !s
->GetStream()->IsSeekable())
478 wxBackedInputStream
*stream
;
479 stream
= new wxBackedInputStream(s
->DetachStream());
480 stream
->FindLength();
481 s
->SetStream(stream
);
489 wxString
wxFileSystem::FindFirst(const wxString
& spec
, int flags
)
491 wxList::compatibility_iterator node
;
492 wxString
spec2(spec
);
494 m_FindFileHandler
= NULL
;
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
499 node
= m_Handlers
.GetFirst();
502 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
503 if (h
-> CanOpen(m_Path
+ spec2
))
505 m_FindFileHandler
= MakeLocal(h
);
506 return m_FindFileHandler
-> FindFirst(m_Path
+ spec2
, flags
);
508 node
= node
->GetNext();
511 node
= m_Handlers
.GetFirst();
514 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
-> GetData();
515 if (h
-> CanOpen(spec2
))
517 m_FindFileHandler
= MakeLocal(h
);
518 return m_FindFileHandler
-> FindFirst(spec2
, flags
);
520 node
= node
->GetNext();
523 return wxEmptyString
;
528 wxString
wxFileSystem::FindNext()
530 if (m_FindFileHandler
== NULL
) return wxEmptyString
;
531 else return m_FindFileHandler
-> FindNext();
534 bool wxFileSystem::FindFileInPath(wxString
*pStr
,
535 const wxString
& path
,
536 const wxString
& basename
)
538 // we assume that it's not empty
539 wxCHECK_MSG( !basename
.empty(), false,
540 _T("empty file name in wxFileSystem::FindFileInPath"));
543 // skip path separator in the beginning of the file name if present
544 if ( wxIsPathSeparator(basename
[0u]) )
545 name
= basename
.substr(1);
549 wxStringTokenizer
tokenizer(path
, wxPATH_SEP
);
550 while ( tokenizer
.HasMoreTokens() )
552 wxString strFile
= tokenizer
.GetNextToken();
553 if ( !wxEndsWithPathSeparator(strFile
) )
554 strFile
+= wxFILE_SEP_PATH
;
557 wxFSFile
*file
= OpenFile(strFile
);
569 void wxFileSystem::AddHandler(wxFileSystemHandler
*handler
)
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
);
576 wxFileSystemHandler
* wxFileSystem::RemoveHandler(wxFileSystemHandler
*handler
)
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
))
590 bool wxFileSystem::HasHandlerForPath(const wxString
&location
)
592 for ( wxList::compatibility_iterator node
= m_Handlers
.GetFirst();
593 node
; node
= node
->GetNext() )
595 wxFileSystemHandler
*h
= (wxFileSystemHandler
*) node
->GetData();
596 if (h
->CanOpen(location
))
603 void wxFileSystem::CleanUpHandlers()
605 WX_CLEAR_LIST(wxList
, m_Handlers
);
608 static const wxString
g_unixPathString(wxT("/"));
609 static const wxString
g_nativePathString(wxFILE_SEP_PATH
);
611 // Returns the native path for a file URL
612 wxFileName
wxFileSystem::URLToFileName(const wxString
& url
)
616 if ( path
.Find(wxT("file://")) == 0 )
620 else if ( path
.Find(wxT("file:")) == 0 )
624 // Remove preceding double slash on Mac Classic
625 #if defined(__WXMAC__) && !defined(__UNIX__)
626 else if ( path
.Find(wxT("//")) == 0 )
630 path
= wxURI::Unescape(path
);
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('/'))
640 else if ( (url
.Find(wxT("file://")) == 0) &&
641 (path
.Find(wxT('/')) != wxNOT_FOUND
) &&
642 (path
.length() > 1) && (path
[1u] != wxT(':')) )
644 path
= wxT("//") + path
;
648 path
.Replace(g_unixPathString
, g_nativePathString
);
650 return wxFileName(path
, wxPATH_NATIVE
);
653 // Returns the file URL for a native path
654 wxString
wxFileSystem::FileNameToURL(const wxFileName
& filename
)
656 wxFileName fn
= filename
;
657 fn
.Normalize(wxPATH_NORM_DOTS
| wxPATH_NORM_TILDE
| wxPATH_NORM_ABSOLUTE
);
658 wxString url
= fn
.GetFullPath(wxPATH_NATIVE
);
661 // unc notation, wxMSW
662 if ( url
.Find(wxT("\\\\")) == 0 )
664 url
= wxT("//") + url
.Mid(2);
668 url
= wxT("/") + url
;
670 url
= wxT("/") + url
;
676 url
.Replace(g_nativePathString
, g_unixPathString
);
677 url
.Replace(wxT("%"), wxT("%25")); // '%'s must be replaced first!
678 url
.Replace(wxT("#"), wxT("%23"));
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
;
697 class wxFileSystemModule
: public wxModule
699 DECLARE_DYNAMIC_CLASS(wxFileSystemModule
)
702 wxFileSystemModule() :
708 virtual bool OnInit()
710 m_handler
= new wxLocalFSHandler
;
711 wxFileSystem::AddHandler(m_handler
);
714 virtual void OnExit()
716 delete wxFileSystem::RemoveHandler(m_handler
);
718 wxFileSystem::CleanUpHandlers();
722 wxFileSystemHandler
* m_handler
;
726 IMPLEMENT_DYNAMIC_CLASS(wxFileSystemModule
, wxModule
)