1 /////////////////////////////////////////////////////////////////////////////
2 // Name: common/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "mimetype.h"
16 // for compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
27 #if (wxUSE_FILE && wxUSE_TEXTFILE) || defined(__WXMSW__)
30 #include "wx/string.h"
34 // Doesn't compile in WIN16 mode
40 #include "wx/dynarray.h"
41 #include "wx/confbase.h"
44 #include "wx/msw/registry.h"
47 #include "wx/textfile.h"
50 #include "wx/mimetype.h"
52 // other standard headers
55 // ----------------------------------------------------------------------------
57 // ----------------------------------------------------------------------------
59 // implementation classes, platform dependent
62 // These classes use Windows registry to retrieve the required information.
64 // Keys used (not all of them are documented, so it might actually stop working
65 // in futur versions of Windows...):
66 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
67 // types, each key has a string value "Extension" which gives (dot preceded)
68 // extension for the files of this MIME type.
70 // 2. "HKCR\.ext" contains
71 // a) unnamed value containing the "filetype"
72 // b) value "Content Type" containing the MIME type
74 // 3. "HKCR\filetype" contains
75 // a) unnamed value containing the description
76 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
78 // c) shell\open\command and shell\open\print subkeys containing the commands
79 // to open/print the file (the positional parameters are introduced by %1,
80 // %2, ... in these strings, we change them to %s ourselves)
86 wxFileTypeImpl() { m_info
= NULL
; }
88 // one of these Init() function must be called (ctor can't take any
89 // arguments because it's common)
91 // initialize us with our file type name and extension - in this case
92 // we will read all other data from the registry
93 void Init(const wxString
& strFileType
, const wxString
& ext
)
94 { m_strFileType
= strFileType
; m_ext
= ext
; }
96 // initialize us with a wxFileTypeInfo object - it contains all the
98 void Init(const wxFileTypeInfo
& info
)
101 // implement accessor functions
102 bool GetExtensions(wxArrayString
& extensions
);
103 bool GetMimeType(wxString
*mimeType
) const;
104 bool GetIcon(wxIcon
*icon
) const;
105 bool GetDescription(wxString
*desc
) const;
106 bool GetOpenCommand(wxString
*openCmd
,
107 const wxFileType::MessageParameters
& params
) const;
108 bool GetPrintCommand(wxString
*printCmd
,
109 const wxFileType::MessageParameters
& params
) const;
112 // helper function: reads the command corresponding to the specified verb
113 // from the registry (returns an empty string if not found)
114 wxString
GetCommand(const wxChar
*verb
) const;
116 // we use either m_info or read the data from the registry if m_info == NULL
117 const wxFileTypeInfo
*m_info
;
118 wxString m_strFileType
,
122 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
123 #include "wx/arrimpl.cpp"
124 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
126 class wxMimeTypesManagerImpl
129 // nothing to do here, we don't load any data but just go and fetch it from
130 // the registry when asked for
131 wxMimeTypesManagerImpl() { }
133 // implement containing class functions
134 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
135 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
137 // this are NOPs under Windows
138 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
)
140 bool ReadMimeTypes(const wxString
& filename
)
143 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
146 wxArrayFileTypeInfo m_fallbacks
;
149 #elif defined( __WXMAC__ )
151 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
152 #include "wx/arrimpl.cpp"
153 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
155 class wxMimeTypesManagerImpl
158 wxMimeTypesManagerImpl() { }
160 // implement containing class functions
161 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
162 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
164 // this are NOPs under MacOS
165 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
) { return TRUE
; }
166 bool ReadMimeTypes(const wxString
& filename
) { return TRUE
; }
168 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
171 wxArrayFileTypeInfo m_fallbacks
;
177 // initialize us with our file type name
178 void SetFileType(const wxString
& strFileType
)
179 { m_strFileType
= strFileType
; }
180 void SetExt(const wxString
& ext
)
183 // implement accessor functions
184 bool GetExtensions(wxArrayString
& extensions
);
185 bool GetMimeType(wxString
*mimeType
) const;
186 bool GetIcon(wxIcon
*icon
) const;
187 bool GetDescription(wxString
*desc
) const;
188 bool GetOpenCommand(wxString
*openCmd
,
189 const wxFileType::MessageParameters
&) const
190 { return GetCommand(openCmd
, "open"); }
191 bool GetPrintCommand(wxString
*printCmd
,
192 const wxFileType::MessageParameters
&) const
193 { return GetCommand(printCmd
, "print"); }
197 bool GetCommand(wxString
*command
, const char *verb
) const;
199 wxString m_strFileType
, m_ext
;
204 // this class uses both mailcap and mime.types to gather information about file
207 // The information about mailcap file was extracted from metamail(1) sources and
210 // Format of mailcap file: spaces are ignored, each line is either a comment
211 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
212 // A backslash can be used to quote semicolons and newlines (and, in fact,
213 // anything else including itself).
215 // The first field is always the MIME type in the form of type/subtype (see RFC
216 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
217 // "type" which means the same as "type/*", although I'm not sure whether this
220 // The second field is always the command to run. It is subject to
221 // parameter/filename expansion described below.
223 // All the following fields are optional and may not be present at all. If
224 // they're present they may appear in any order, although each of them should
225 // appear only once. The optional fields are the following:
226 // * notes=xxx is an uninterpreted string which is silently ignored
227 // * test=xxx is the command to be used to determine whether this mailcap line
228 // applies to our data or not. The RHS of this field goes through the
229 // parameter/filename expansion (as the 2nd field) and the resulting string
230 // is executed. The line applies only if the command succeeds, i.e. returns 0
232 // * print=xxx is the command to be used to print (and not view) the data of
233 // this type (parameter/filename expansion is done here too)
234 // * edit=xxx is the command to open/edit the data of this type
235 // * needsterminal means that a new console must be created for the viewer
236 // * copiousoutput means that the viewer doesn't interact with the user but
237 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
238 // good example), thus it might be a good idea to use some kind of paging
240 // * textualnewlines means not to perform CR/LF translation (not honored)
241 // * compose and composetyped fields are used to determine the program to be
242 // called to create a new message pert in the specified format (unused).
244 // Parameter/filename xpansion:
245 // * %s is replaced with the (full) file name
246 // * %t is replaced with MIME type/subtype of the entry
247 // * for multipart type only %n is replaced with the nnumber of parts and %F is
248 // replaced by an array of (content-type, temporary file name) pairs for all
249 // message parts (TODO)
250 // * %{parameter} is replaced with the value of parameter taken from
251 // Content-type header line of the message.
253 // FIXME any docs with real descriptions of these files??
255 // There are 2 possible formats for mime.types file, one entry per line (used
256 // for global mime.types) and "expanded" format where an entry takes multiple
257 // lines (used for users mime.types).
259 // For both formats spaces are ignored and lines starting with a '#' are
260 // comments. Each record has one of two following forms:
261 // a) for "brief" format:
262 // <mime type> <space separated list of extensions>
263 // b) for "expanded" format:
264 // type=<mime type> \ desc="<description>" \ exts="ext"
266 // We try to autodetect the format of mime.types: if a non-comment line starts
267 // with "type=" we assume the second format, otherwise the first one.
269 // there may be more than one entry for one and the same mime type, to
270 // choose the right one we have to run the command specified in the test
271 // field on our data.
276 MailCapEntry(const wxString
& openCmd
,
277 const wxString
& printCmd
,
278 const wxString
& testCmd
)
279 : m_openCmd(openCmd
), m_printCmd(printCmd
), m_testCmd(testCmd
)
285 const wxString
& GetOpenCmd() const { return m_openCmd
; }
286 const wxString
& GetPrintCmd() const { return m_printCmd
; }
287 const wxString
& GetTestCmd() const { return m_testCmd
; }
289 MailCapEntry
*GetNext() const { return m_next
; }
292 // prepend this element to the list
293 void Prepend(MailCapEntry
*next
) { m_next
= next
; }
294 // insert into the list at given position
295 void Insert(MailCapEntry
*next
, size_t pos
)
300 for ( cur
= next
; cur
!= NULL
; cur
= cur
->m_next
, n
++ ) {
305 wxASSERT_MSG( n
== pos
, wxT("invalid position in MailCapEntry::Insert") );
307 m_next
= cur
->m_next
;
310 // append this element to the list
311 void Append(MailCapEntry
*next
)
313 wxCHECK_RET( next
!= NULL
, wxT("Append()ing to what?") );
317 for ( cur
= next
; cur
->m_next
!= NULL
; cur
= cur
->m_next
)
322 wxASSERT_MSG( !m_next
, wxT("Append()ing element already in the list?") );
326 wxString m_openCmd
, // command to use to open/view the file
328 m_testCmd
; // only apply this entry if test yields
329 // true (i.e. the command returns 0)
331 MailCapEntry
*m_next
; // in the linked list
334 WX_DEFINE_ARRAY(MailCapEntry
*, ArrayTypeEntries
);
336 class wxMimeTypesManagerImpl
338 friend class wxFileTypeImpl
; // give it access to m_aXXX variables
341 // ctor loads all info into memory for quicker access later on
342 // TODO it would be nice to load them all, but parse on demand only...
343 wxMimeTypesManagerImpl();
345 // implement containing class functions
346 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
347 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
349 bool ReadMailcap(const wxString
& filename
, bool fallback
= FALSE
);
350 bool ReadMimeTypes(const wxString
& filename
);
352 void AddFallback(const wxFileTypeInfo
& filetype
);
354 // add information about the given mimetype
355 void AddMimeTypeInfo(const wxString
& mimetype
,
356 const wxString
& extensions
,
357 const wxString
& description
);
358 void AddMailcapInfo(const wxString
& strType
,
359 const wxString
& strOpenCmd
,
360 const wxString
& strPrintCmd
,
361 const wxString
& strTest
,
362 const wxString
& strDesc
);
365 // get the string containing space separated extensions for the given
367 wxString
GetExtension(size_t index
) { return m_aExtensions
[index
]; }
370 wxArrayString m_aTypes
, // MIME types
371 m_aDescriptions
, // descriptions (just some text)
372 m_aExtensions
; // space separated list of extensions
373 ArrayTypeEntries m_aEntries
; // commands and tests for this file type
379 // initialization functions
380 void Init(wxMimeTypesManagerImpl
*manager
, size_t index
)
381 { m_manager
= manager
; m_index
= index
; }
384 bool GetExtensions(wxArrayString
& extensions
);
385 bool GetMimeType(wxString
*mimeType
) const
386 { *mimeType
= m_manager
->m_aTypes
[m_index
]; return TRUE
; }
387 bool GetIcon(wxIcon
* WXUNUSED(icon
)) const
388 { return FALSE
; } // TODO maybe with Gnome/KDE integration...
389 bool GetDescription(wxString
*desc
) const
390 { *desc
= m_manager
->m_aDescriptions
[m_index
]; return TRUE
; }
392 bool GetOpenCommand(wxString
*openCmd
,
393 const wxFileType::MessageParameters
& params
) const
395 return GetExpandedCommand(openCmd
, params
, TRUE
);
398 bool GetPrintCommand(wxString
*printCmd
,
399 const wxFileType::MessageParameters
& params
) const
401 return GetExpandedCommand(printCmd
, params
, FALSE
);
405 // get the entry which passes the test (may return NULL)
406 MailCapEntry
*GetEntry(const wxFileType::MessageParameters
& params
) const;
408 // choose the correct entry to use and expand the command
409 bool GetExpandedCommand(wxString
*expandedCmd
,
410 const wxFileType::MessageParameters
& params
,
413 wxMimeTypesManagerImpl
*m_manager
;
414 size_t m_index
; // in the wxMimeTypesManagerImpl arrays
419 // ============================================================================
421 // ============================================================================
423 // ----------------------------------------------------------------------------
425 // ----------------------------------------------------------------------------
427 wxFileTypeInfo::wxFileTypeInfo(const char *mimeType
,
429 const char *printCmd
,
432 : m_mimeType(mimeType
),
434 m_printCmd(printCmd
),
438 va_start(argptr
, desc
);
442 const char *ext
= va_arg(argptr
, const char *);
445 // NULL terminates the list
455 // ============================================================================
456 // implementation of the wrapper classes
457 // ============================================================================
459 // ----------------------------------------------------------------------------
461 // ----------------------------------------------------------------------------
463 wxString
wxFileType::ExpandCommand(const wxString
& command
,
464 const wxFileType::MessageParameters
& params
)
466 bool hasFilename
= FALSE
;
469 for ( const wxChar
*pc
= command
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
470 if ( *pc
== wxT('%') ) {
473 // '%s' expands into file name (quoted because it might
474 // contain spaces) - except if there are already quotes
475 // there because otherwise some programs may get confused
476 // by double double quotes
478 if ( *(pc
- 2) == wxT('"') )
479 str
<< params
.GetFileName();
481 str
<< wxT('"') << params
.GetFileName() << wxT('"');
483 str
<< params
.GetFileName();
488 // '%t' expands into MIME type (quote it too just to be
490 str
<< wxT('\'') << params
.GetMimeType() << wxT('\'');
495 const wxChar
*pEnd
= wxStrchr(pc
, wxT('}'));
496 if ( pEnd
== NULL
) {
498 wxLogWarning(_("Unmatched '{' in an entry for "
500 params
.GetMimeType().c_str());
504 wxString
param(pc
+ 1, pEnd
- pc
- 1);
505 str
<< wxT('\'') << params
.GetParamValue(param
) << wxT('\'');
513 // TODO %n is the number of parts, %F is an array containing
514 // the names of temp files these parts were written to
515 // and their mime types.
519 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
520 *pc
, command
.c_str());
529 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
530 // the program will accept the data on stdin: so give it to it!
531 if ( !hasFilename
&& !str
.IsEmpty() ) {
532 str
<< wxT(" < '") << params
.GetFileName() << wxT('\'');
538 wxFileType::wxFileType()
540 m_impl
= new wxFileTypeImpl
;
543 wxFileType::~wxFileType()
548 bool wxFileType::GetExtensions(wxArrayString
& extensions
)
550 return m_impl
->GetExtensions(extensions
);
553 bool wxFileType::GetMimeType(wxString
*mimeType
) const
555 return m_impl
->GetMimeType(mimeType
);
558 bool wxFileType::GetIcon(wxIcon
*icon
) const
560 return m_impl
->GetIcon(icon
);
563 bool wxFileType::GetDescription(wxString
*desc
) const
565 return m_impl
->GetDescription(desc
);
569 wxFileType::GetOpenCommand(wxString
*openCmd
,
570 const wxFileType::MessageParameters
& params
) const
572 return m_impl
->GetOpenCommand(openCmd
, params
);
576 wxFileType::GetPrintCommand(wxString
*printCmd
,
577 const wxFileType::MessageParameters
& params
) const
579 return m_impl
->GetPrintCommand(printCmd
, params
);
582 // ----------------------------------------------------------------------------
583 // wxMimeTypesManager
584 // ----------------------------------------------------------------------------
586 bool wxMimeTypesManager::IsOfType(const wxString
& mimeType
,
587 const wxString
& wildcard
)
589 wxASSERT_MSG( mimeType
.Find(wxT('*')) == wxNOT_FOUND
,
590 wxT("first MIME type can't contain wildcards") );
592 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
593 if ( wildcard
.BeforeFirst(wxT('/')).IsSameAs(mimeType
.BeforeFirst(wxT('/')), FALSE
) )
595 wxString strSubtype
= wildcard
.AfterFirst(wxT('/'));
597 if ( strSubtype
== wxT("*") ||
598 strSubtype
.IsSameAs(mimeType
.AfterFirst(wxT('/')), FALSE
) )
600 // matches (either exactly or it's a wildcard)
608 wxMimeTypesManager::wxMimeTypesManager()
610 m_impl
= new wxMimeTypesManagerImpl
;
613 wxMimeTypesManager::~wxMimeTypesManager()
619 wxMimeTypesManager::GetFileTypeFromExtension(const wxString
& ext
)
621 return m_impl
->GetFileTypeFromExtension(ext
);
625 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString
& mimeType
)
627 return m_impl
->GetFileTypeFromMimeType(mimeType
);
630 bool wxMimeTypesManager::ReadMailcap(const wxString
& filename
, bool fallback
)
632 return m_impl
->ReadMailcap(filename
, fallback
);
635 bool wxMimeTypesManager::ReadMimeTypes(const wxString
& filename
)
637 return m_impl
->ReadMimeTypes(filename
);
640 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo
*filetypes
)
642 for ( const wxFileTypeInfo
*ft
= filetypes
; ft
->IsValid(); ft
++ ) {
643 m_impl
->AddFallback(*ft
);
647 // ============================================================================
648 // real (OS specific) implementation
649 // ============================================================================
653 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
655 // suppress possible error messages
658 strKey
<< m_strFileType
<< wxT("\\shell\\") << verb
<< wxT("\\command");
659 wxRegKey
key(wxRegKey::HKCR
, strKey
);
663 // it's the default value of the key
664 if ( key
.QueryValue(wxT(""), command
) ) {
665 // transform it from '%1' to '%s' style format string
667 // NB: we don't make any attempt to verify that the string is valid,
668 // i.e. doesn't contain %2, or second %1 or .... But we do make
669 // sure that we return a string with _exactly_ one '%s'!
670 bool foundFilename
= FALSE
;
671 size_t len
= command
.Len();
672 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
673 if ( command
[n
] == wxT('%') &&
674 (n
+ 1 < len
) && command
[n
+ 1] == wxT('1') ) {
675 // replace it with '%s'
676 command
[n
+ 1] = wxT('s');
678 foundFilename
= TRUE
;
682 if ( !foundFilename
) {
683 // we didn't find any '%1'!
684 // HACK: append the filename at the end, hope that it will do
685 command
<< wxT(" %s");
690 // no such file type or no value
695 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
696 const wxFileType::MessageParameters
& params
)
701 cmd
= m_info
->GetOpenCommand();
704 cmd
= GetCommand(wxT("open"));
707 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
709 return !openCmd
->IsEmpty();
713 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
714 const wxFileType::MessageParameters
& params
)
719 cmd
= m_info
->GetPrintCommand();
722 cmd
= GetCommand(wxT("print"));
725 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
727 return !printCmd
->IsEmpty();
730 // TODO this function is half implemented
731 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
734 extensions
= m_info
->GetExtensions();
738 else if ( m_ext
.IsEmpty() ) {
739 // the only way to get the list of extensions from the file type is to
740 // scan through all extensions in the registry - too slow...
745 extensions
.Add(m_ext
);
747 // it's a lie too, we don't return _all_ extensions...
752 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
755 // we already have it
756 *mimeType
= m_info
->GetMimeType();
761 // suppress possible error messages
763 wxRegKey
key(wxRegKey::HKCR
, /*m_strFileType*/ wxT(".") + m_ext
);
764 if ( key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
) ) {
772 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
775 // we don't have icons in the fallback resources
780 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
782 // suppress possible error messages
784 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
788 // it's the default value of the key
789 if ( key
.QueryValue(wxT(""), strIcon
) ) {
790 // the format is the following: <full path to file>, <icon index>
791 // NB: icon index may be negative as well as positive and the full
792 // path may contain the environment variables inside '%'
793 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
794 strIndex
= strIcon
.AfterLast(wxT(','));
796 // index may be omitted, in which case BeforeLast(',') is empty and
797 // AfterLast(',') is the whole string
798 if ( strFullPath
.IsEmpty() ) {
799 strFullPath
= strIndex
;
803 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
804 int nIndex
= wxAtoi(strIndex
);
806 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
807 switch ( (int)hIcon
) {
808 case 0: // means no icons were found
809 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
810 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
811 key
.GetName().c_str());
815 icon
->SetHICON((WXHICON
)hIcon
);
821 // no such file type or no value or incorrect icon entry
825 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
828 // we already have it
829 *desc
= m_info
->GetDescription();
834 // suppress possible error messages
836 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
839 // it's the default value of the key
840 if ( key
.QueryValue(wxT(""), *desc
) ) {
848 // extension -> file type
850 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
852 // add the leading point if necessary
854 if ( ext
[0u] != wxT('.') ) {
859 // suppress possible error messages
862 wxString strFileType
;
863 wxRegKey
key(wxRegKey::HKCR
, str
);
865 // it's the default value of the key
866 if ( key
.QueryValue(wxT(""), strFileType
) ) {
867 // create the new wxFileType object
868 wxFileType
*fileType
= new wxFileType
;
869 fileType
->m_impl
->Init(strFileType
, ext
);
875 // check the fallbacks
876 // TODO linear search is potentially slow, perhaps we should use a sorted
878 size_t count
= m_fallbacks
.GetCount();
879 for ( size_t n
= 0; n
< count
; n
++ ) {
880 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
881 wxFileType
*fileType
= new wxFileType
;
882 fileType
->m_impl
->Init(m_fallbacks
[n
]);
892 // MIME type -> extension -> file type
894 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
896 // HACK I don't know of any official documentation which mentions this
897 // location, but as a matter of fact IE uses it, so why not we?
898 static const wxChar
*szMimeDbase
= wxT("MIME\\Database\\Content Type\\");
900 wxString strKey
= szMimeDbase
;
903 // suppress possible error messages
907 wxRegKey
key(wxRegKey::HKCR
, strKey
);
909 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
910 return GetFileTypeFromExtension(ext
);
914 // check the fallbacks
915 // TODO linear search is potentially slow, perhaps we should use a sorted
917 size_t count
= m_fallbacks
.GetCount();
918 for ( size_t n
= 0; n
< count
; n
++ ) {
919 if ( wxMimeTypesManager::IsOfType(mimeType
,
920 m_fallbacks
[n
].GetMimeType()) ) {
921 wxFileType
*fileType
= new wxFileType
;
922 fileType
->m_impl
->Init(m_fallbacks
[n
]);
932 #elif defined ( __WXMAC__ )
935 bool wxFileTypeImpl::GetCommand(wxString
*command
, const char *verb
) const
940 // @@ this function is half implemented
941 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
946 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
948 if ( m_strFileType
.Length() > 0 )
950 *mimeType
= m_strFileType
;
957 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
959 // no such file type or no value or incorrect icon entry
963 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
968 // extension -> file type
970 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& e
)
976 wxFileType
*fileType
= new wxFileType
;
977 fileType
->m_impl
->SetFileType("text/text");
978 fileType
->m_impl
->SetExt(ext
);
981 else if ( ext
== "htm" || ext
== "html" )
983 wxFileType
*fileType
= new wxFileType
;
984 fileType
->m_impl
->SetFileType("text/html");
985 fileType
->m_impl
->SetExt(ext
);
988 else if ( ext
== "gif" )
990 wxFileType
*fileType
= new wxFileType
;
991 fileType
->m_impl
->SetFileType("image/gif");
992 fileType
->m_impl
->SetExt(ext
);
995 else if ( ext
== "png" )
997 wxFileType
*fileType
= new wxFileType
;
998 fileType
->m_impl
->SetFileType("image/png");
999 fileType
->m_impl
->SetExt(ext
);
1002 else if ( ext
== "jpg" || ext
== "jpeg" )
1004 wxFileType
*fileType
= new wxFileType
;
1005 fileType
->m_impl
->SetFileType("image/jpeg");
1006 fileType
->m_impl
->SetExt(ext
);
1009 else if ( ext
== "bmp" )
1011 wxFileType
*fileType
= new wxFileType
;
1012 fileType
->m_impl
->SetFileType("image/bmp");
1013 fileType
->m_impl
->SetExt(ext
);
1016 else if ( ext
== "tif" || ext
== "tiff" )
1018 wxFileType
*fileType
= new wxFileType
;
1019 fileType
->m_impl
->SetFileType("image/tiff");
1020 fileType
->m_impl
->SetExt(ext
);
1023 else if ( ext
== "xpm" )
1025 wxFileType
*fileType
= new wxFileType
;
1026 fileType
->m_impl
->SetFileType("image/xpm");
1027 fileType
->m_impl
->SetExt(ext
);
1030 else if ( ext
== "xbm" )
1032 wxFileType
*fileType
= new wxFileType
;
1033 fileType
->m_impl
->SetFileType("image/xbm");
1034 fileType
->m_impl
->SetExt(ext
);
1037 // unknown extension
1041 // MIME type -> extension -> file type
1043 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1050 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
1053 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
1054 while ( entry
!= NULL
) {
1055 // notice that an empty command would always succeed (it's ok)
1056 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
1058 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
1060 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1061 command
.c_str(), params
.GetMimeType().c_str());
1065 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1066 command
.c_str(), params
.GetMimeType().c_str());
1069 entry
= entry
->GetNext();
1076 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
1077 const wxFileType::MessageParameters
& params
,
1080 MailCapEntry
*entry
= GetEntry(params
);
1081 if ( entry
== NULL
) {
1082 // all tests failed...
1086 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
1087 if ( cmd
.IsEmpty() ) {
1088 // may happen, especially for "print"
1092 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
1096 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1098 wxString strExtensions
= m_manager
->GetExtension(m_index
);
1101 // one extension in the space or comma delimitid list
1103 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
1104 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1105 if ( !strExt
.IsEmpty() ) {
1106 extensions
.Add(strExt
);
1109 //else: repeated spaces (shouldn't happen, but it's not that
1110 // important if it does happen)
1112 if ( *p
== wxT('\0') )
1115 else if ( *p
== wxT('.') ) {
1116 // remove the dot from extension (but only if it's the first char)
1117 if ( !strExt
.IsEmpty() ) {
1120 //else: no, don't append it
1130 // read system and user mailcaps (TODO implement mime.types support)
1131 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1133 // directories where we look for mailcap and mime.types by default
1134 // (taken from metamail(1) sources)
1135 static const wxChar
*aStandardLocations
[] =
1139 wxT("/usr/local/etc"),
1141 wxT("/usr/public/lib")
1144 // first read the system wide file(s)
1145 for ( size_t n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
1146 wxString dir
= aStandardLocations
[n
];
1148 wxString file
= dir
+ wxT("/mailcap");
1149 if ( wxFile::Exists(file
) ) {
1153 file
= dir
+ wxT("/mime.types");
1154 if ( wxFile::Exists(file
) ) {
1155 ReadMimeTypes(file
);
1159 wxString strHome
= wxGetenv(wxT("HOME"));
1161 // and now the users mailcap
1162 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1163 if ( wxFile::Exists(strUserMailcap
) ) {
1164 ReadMailcap(strUserMailcap
);
1167 // read the users mime.types
1168 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
1169 if ( wxFile::Exists(strUserMimeTypes
) ) {
1170 ReadMimeTypes(strUserMimeTypes
);
1175 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1177 size_t count
= m_aExtensions
.GetCount();
1178 for ( size_t n
= 0; n
< count
; n
++ ) {
1179 wxString extensions
= m_aExtensions
[n
];
1180 while ( !extensions
.IsEmpty() ) {
1181 wxString field
= extensions
.BeforeFirst(wxT(' '));
1182 extensions
= extensions
.AfterFirst(wxT(' '));
1184 // consider extensions as not being case-sensitive
1185 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
1187 wxFileType
*fileType
= new wxFileType
;
1188 fileType
->m_impl
->Init(this, n
);
1200 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1202 // mime types are not case-sensitive
1203 wxString
mimetype(mimeType
);
1204 mimetype
.MakeLower();
1206 // first look for an exact match
1207 int index
= m_aTypes
.Index(mimetype
);
1208 if ( index
== wxNOT_FOUND
) {
1209 // then try to find "text/*" as match for "text/plain" (for example)
1210 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1211 // the whole string - ok.
1212 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1214 size_t nCount
= m_aTypes
.Count();
1215 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1216 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1217 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1224 if ( index
!= wxNOT_FOUND
) {
1225 wxFileType
*fileType
= new wxFileType
;
1226 fileType
->m_impl
->Init(this, index
);
1236 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1238 wxString extensions
;
1239 const wxArrayString
& exts
= filetype
.GetExtensions();
1240 size_t nExts
= exts
.GetCount();
1241 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1243 extensions
+= wxT(' ');
1245 extensions
+= exts
[nExt
];
1248 AddMimeTypeInfo(filetype
.GetMimeType(),
1250 filetype
.GetDescription());
1252 AddMailcapInfo(filetype
.GetMimeType(),
1253 filetype
.GetOpenCommand(),
1254 filetype
.GetPrintCommand(),
1256 filetype
.GetDescription());
1259 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
1260 const wxString
& strExtensions
,
1261 const wxString
& strDesc
)
1263 int index
= m_aTypes
.Index(strMimeType
);
1264 if ( index
== wxNOT_FOUND
) {
1266 m_aTypes
.Add(strMimeType
);
1267 m_aEntries
.Add(NULL
);
1268 m_aExtensions
.Add(strExtensions
);
1269 m_aDescriptions
.Add(strDesc
);
1272 // modify an existing one
1273 if ( !strDesc
.IsEmpty() ) {
1274 m_aDescriptions
[index
] = strDesc
; // replace old value
1276 m_aExtensions
[index
] += ' ' + strExtensions
;
1280 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
1281 const wxString
& strOpenCmd
,
1282 const wxString
& strPrintCmd
,
1283 const wxString
& strTest
,
1284 const wxString
& strDesc
)
1286 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1288 int nIndex
= m_aTypes
.Index(strType
);
1289 if ( nIndex
== wxNOT_FOUND
) {
1291 m_aTypes
.Add(strType
);
1293 m_aEntries
.Add(entry
);
1294 m_aExtensions
.Add(wxT(""));
1295 m_aDescriptions
.Add(strDesc
);
1298 // always append the entry in the tail of the list - info added with
1299 // this function can only come from AddFallbacks()
1300 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1302 entry
->Append(entryOld
);
1304 m_aEntries
[nIndex
] = entry
;
1308 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1310 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1312 wxTextFile
file(strFileName
);
1316 // the information we extract
1317 wxString strMimeType
, strDesc
, strExtensions
;
1319 size_t nLineCount
= file
.GetLineCount();
1320 const wxChar
*pc
= NULL
;
1321 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1323 // now we're at the start of the line
1324 pc
= file
[nLine
].c_str();
1327 // we didn't finish with the previous line yet
1332 while ( wxIsspace(*pc
) )
1336 if ( *pc
== wxT('#') ) {
1337 // skip the whole line
1342 // detect file format
1343 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1344 if ( pEqualSign
== NULL
) {
1348 // first field is mime type
1349 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1354 while ( wxIsspace(*pc
) )
1357 // take all the rest of the string
1360 // no description...
1367 // the string on the left of '=' is the field name
1368 wxString
strLHS(pc
, pEqualSign
- pc
);
1371 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
1375 if ( *pc
== wxT('"') ) {
1376 // the string is quoted and ends at the matching quote
1377 pEnd
= wxStrchr(++pc
, wxT('"'));
1378 if ( pEnd
== NULL
) {
1379 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1381 strFileName
.c_str(), nLine
+ 1);
1385 // unquoted string ends at the first space
1386 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
1390 // now we have the RHS (field value)
1391 wxString
strRHS(pc
, pEnd
- pc
);
1393 // check what follows this entry
1394 if ( *pEnd
== wxT('"') ) {
1399 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
1402 // if there is something left, it may be either a '\\' to continue
1403 // the line or the next field of the same entry
1404 bool entryEnded
= *pc
== wxT('\0'),
1405 nextFieldOnSameLine
= FALSE
;
1406 if ( !entryEnded
) {
1407 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
1410 // now see what we got
1411 if ( strLHS
== wxT("type") ) {
1412 strMimeType
= strRHS
;
1414 else if ( strLHS
== wxT("desc") ) {
1417 else if ( strLHS
== wxT("exts") ) {
1418 strExtensions
= strRHS
;
1421 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1422 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
1425 if ( !entryEnded
) {
1426 if ( !nextFieldOnSameLine
)
1428 //else: don't reset it
1430 // as we don't reset strMimeType, the next field in this entry
1431 // will be interpreted correctly.
1437 // although it doesn't seem to be covered by RFCs, some programs
1438 // (notably Netscape) create their entries with several comma
1439 // separated extensions (RFC mention the spaces only)
1440 strExtensions
.Replace(wxT(","), wxT(" "));
1442 // also deal with the leading dot
1443 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
1444 if ( !strExtensions
.IsEmpty() && strExtensions
[size_t(0)] == wxT('.') ) {
1446 if ( !strExtensions
.IsEmpty() && strExtensions
[0] == wxT('.') ) {
1448 strExtensions
.erase(0, 1);
1451 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
1453 // finished with this line
1457 // check our data integriry
1458 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1459 m_aTypes
.Count() == m_aExtensions
.Count() &&
1460 m_aTypes
.Count() == m_aDescriptions
.Count() );
1465 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
1468 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
1470 wxTextFile
file(strFileName
);
1474 // see the comments near the end of function for the reason we need these
1475 // variables (search for the next occurence of them)
1476 // indices of MIME types (in m_aTypes) we already found in this file
1477 wxArrayInt aEntryIndices
;
1478 // aLastIndices[n] is the index of last element in
1479 // m_aEntries[aEntryIndices[n]] from this file
1480 wxArrayInt aLastIndices
;
1482 size_t nLineCount
= file
.GetLineCount();
1483 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1484 // now we're at the start of the line
1485 const wxChar
*pc
= file
[nLine
].c_str();
1488 while ( wxIsspace(*pc
) )
1491 // comment or empty string?
1492 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
1497 // what field are we currently in? The first 2 are fixed and there may
1498 // be an arbitrary number of other fields -- currently, we are not
1499 // interested in any of them, but we should parse them as well...
1505 } currentToken
= Field_Type
;
1507 // the flags and field values on the current line
1508 bool needsterminal
= FALSE
,
1509 copiousoutput
= FALSE
;
1515 curField
; // accumulator
1516 for ( bool cont
= TRUE
; cont
; pc
++ ) {
1519 // interpret the next character literally (notice that
1520 // backslash can be used for line continuation)
1521 if ( *++pc
== wxT('\0') ) {
1522 // fetch the next line.
1524 // pc currently points to nowhere, but after the next
1525 // pc++ in the for line it will point to the beginning
1526 // of the next line in the file
1527 pc
= file
[++nLine
].c_str() - 1;
1530 // just a normal character
1536 cont
= FALSE
; // end of line reached, exit the loop
1541 // store this field and start looking for the next one
1543 // trim whitespaces from both sides
1544 curField
.Trim(TRUE
).Trim(FALSE
);
1546 switch ( currentToken
) {
1549 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
1550 // we interpret "type" as "type/*"
1551 strType
+= wxT("/*");
1554 currentToken
= Field_OpenCmd
;
1558 strOpenCmd
= curField
;
1560 currentToken
= Field_Other
;
1565 // "good" mailcap entry?
1568 // is this something of the form foo=bar?
1569 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
1570 if ( pEq
!= NULL
) {
1571 wxString lhs
= curField
.BeforeFirst(wxT('=')),
1572 rhs
= curField
.AfterFirst(wxT('='));
1574 lhs
.Trim(TRUE
); // from right
1575 rhs
.Trim(FALSE
); // from left
1577 if ( lhs
== wxT("print") )
1579 else if ( lhs
== wxT("test") )
1581 else if ( lhs
== wxT("description") ) {
1582 // it might be quoted
1583 if ( rhs
[0u] == wxT('"') &&
1584 rhs
.Last() == wxT('"') ) {
1585 strDesc
= wxString(rhs
.c_str() + 1,
1592 else if ( lhs
== wxT("compose") ||
1593 lhs
== wxT("composetyped") ||
1594 lhs
== wxT("notes") ||
1595 lhs
== wxT("edit") )
1602 // no, it's a simple flag
1603 // TODO support the flags:
1604 // 1. create an xterm for 'needsterminal'
1605 // 2. append "| $PAGER" for 'copiousoutput'
1606 if ( curField
== wxT("needsterminal") )
1607 needsterminal
= TRUE
;
1608 else if ( curField
== wxT("copiousoutput") )
1609 copiousoutput
= TRUE
;
1610 else if ( curField
== wxT("textualnewlines") )
1618 // don't flood the user with error messages
1619 // if we don't understand something in his
1620 // mailcap, but give them in debug mode
1621 // because this might be useful for the
1625 wxT("Mailcap file %s, line %d: unknown "
1626 "field '%s' for the MIME type "
1628 strFileName
.c_str(),
1636 // it already has this value
1637 //currentToken = Field_Other;
1641 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1644 // next token starts immediately after ';'
1653 // check that we really read something reasonable
1654 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
1655 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1657 strFileName
.c_str(), nLine
+ 1);
1660 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
1664 // NB: because of complications below (we must get entries priority
1665 // right), we can't use AddMailcapInfo() here, unfortunately.
1666 strType
.MakeLower();
1667 int nIndex
= m_aTypes
.Index(strType
);
1668 if ( nIndex
== wxNOT_FOUND
) {
1670 m_aTypes
.Add(strType
);
1672 m_aEntries
.Add(entry
);
1673 m_aExtensions
.Add(wxT(""));
1674 m_aDescriptions
.Add(strDesc
);
1677 // modify the existing entry: the entries in one and the same
1678 // file are read in top-to-bottom order, i.e. the entries read
1679 // first should be tried before the entries below. However,
1680 // the files read later should override the settings in the
1681 // files read before (except if fallback is TRUE), thus we
1682 // Insert() the new entry to the list if it has already
1683 // occured in _this_ file, but Prepend() it if it occured in
1684 // some of the previous ones and Append() to it in the
1688 // 'fallback' parameter prevents the entries from this
1689 // file from overriding the other ones - always append
1690 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1692 entry
->Append(entryOld
);
1694 m_aEntries
[nIndex
] = entry
;
1697 int entryIndex
= aEntryIndices
.Index(nIndex
);
1698 if ( entryIndex
== wxNOT_FOUND
) {
1699 // first time in this file
1700 aEntryIndices
.Add(nIndex
);
1701 aLastIndices
.Add(0);
1703 entry
->Prepend(m_aEntries
[nIndex
]);
1704 m_aEntries
[nIndex
] = entry
;
1707 // not the first time in _this_ file
1708 size_t nEntryIndex
= (size_t)entryIndex
;
1709 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1711 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
1713 m_aEntries
[nIndex
] = entry
;
1715 // the indices were shifted by 1
1716 aLastIndices
[nEntryIndex
]++;
1720 if ( !strDesc
.IsEmpty() ) {
1721 // replace the old one - what else can we do??
1722 m_aDescriptions
[nIndex
] = strDesc
;
1727 // check our data integriry
1728 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1729 m_aTypes
.Count() == m_aExtensions
.Count() &&
1730 m_aTypes
.Count() == m_aDescriptions
.Count() );
1740 // wxUSE_FILE && wxUSE_TEXTFILE