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
776 // we don't have icons in the fallback resources
781 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
783 // suppress possible error messages
785 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
789 // it's the default value of the key
790 if ( key
.QueryValue(wxT(""), strIcon
) ) {
791 // the format is the following: <full path to file>, <icon index>
792 // NB: icon index may be negative as well as positive and the full
793 // path may contain the environment variables inside '%'
794 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
795 strIndex
= strIcon
.AfterLast(wxT(','));
797 // index may be omitted, in which case BeforeLast(',') is empty and
798 // AfterLast(',') is the whole string
799 if ( strFullPath
.IsEmpty() ) {
800 strFullPath
= strIndex
;
804 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
805 int nIndex
= wxAtoi(strIndex
);
807 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
808 switch ( (int)hIcon
) {
809 case 0: // means no icons were found
810 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
811 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
812 key
.GetName().c_str());
816 icon
->SetHICON((WXHICON
)hIcon
);
822 // no such file type or no value or incorrect icon entry
828 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
831 // we already have it
832 *desc
= m_info
->GetDescription();
837 // suppress possible error messages
839 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
842 // it's the default value of the key
843 if ( key
.QueryValue(wxT(""), *desc
) ) {
851 // extension -> file type
853 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
855 // add the leading point if necessary
857 if ( ext
[0u] != wxT('.') ) {
862 // suppress possible error messages
865 wxString strFileType
;
866 wxRegKey
key(wxRegKey::HKCR
, str
);
868 // it's the default value of the key
869 if ( key
.QueryValue(wxT(""), strFileType
) ) {
870 // create the new wxFileType object
871 wxFileType
*fileType
= new wxFileType
;
872 fileType
->m_impl
->Init(strFileType
, ext
);
878 // check the fallbacks
879 // TODO linear search is potentially slow, perhaps we should use a sorted
881 size_t count
= m_fallbacks
.GetCount();
882 for ( size_t n
= 0; n
< count
; n
++ ) {
883 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
884 wxFileType
*fileType
= new wxFileType
;
885 fileType
->m_impl
->Init(m_fallbacks
[n
]);
895 // MIME type -> extension -> file type
897 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
899 // HACK I don't know of any official documentation which mentions this
900 // location, but as a matter of fact IE uses it, so why not we?
901 static const wxChar
*szMimeDbase
= wxT("MIME\\Database\\Content Type\\");
903 wxString strKey
= szMimeDbase
;
906 // suppress possible error messages
910 wxRegKey
key(wxRegKey::HKCR
, strKey
);
912 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
913 return GetFileTypeFromExtension(ext
);
917 // check the fallbacks
918 // TODO linear search is potentially slow, perhaps we should use a sorted
920 size_t count
= m_fallbacks
.GetCount();
921 for ( size_t n
= 0; n
< count
; n
++ ) {
922 if ( wxMimeTypesManager::IsOfType(mimeType
,
923 m_fallbacks
[n
].GetMimeType()) ) {
924 wxFileType
*fileType
= new wxFileType
;
925 fileType
->m_impl
->Init(m_fallbacks
[n
]);
935 #elif defined ( __WXMAC__ )
938 bool wxFileTypeImpl::GetCommand(wxString
*command
, const char *verb
) const
943 // @@ this function is half implemented
944 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
949 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
951 if ( m_strFileType
.Length() > 0 )
953 *mimeType
= m_strFileType
;
960 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
962 // no such file type or no value or incorrect icon entry
966 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
971 // extension -> file type
973 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& e
)
979 wxFileType
*fileType
= new wxFileType
;
980 fileType
->m_impl
->SetFileType("text/text");
981 fileType
->m_impl
->SetExt(ext
);
984 else if ( ext
== "htm" || ext
== "html" )
986 wxFileType
*fileType
= new wxFileType
;
987 fileType
->m_impl
->SetFileType("text/html");
988 fileType
->m_impl
->SetExt(ext
);
991 else if ( ext
== "gif" )
993 wxFileType
*fileType
= new wxFileType
;
994 fileType
->m_impl
->SetFileType("image/gif");
995 fileType
->m_impl
->SetExt(ext
);
998 else if ( ext
== "png" )
1000 wxFileType
*fileType
= new wxFileType
;
1001 fileType
->m_impl
->SetFileType("image/png");
1002 fileType
->m_impl
->SetExt(ext
);
1005 else if ( ext
== "jpg" || ext
== "jpeg" )
1007 wxFileType
*fileType
= new wxFileType
;
1008 fileType
->m_impl
->SetFileType("image/jpeg");
1009 fileType
->m_impl
->SetExt(ext
);
1012 else if ( ext
== "bmp" )
1014 wxFileType
*fileType
= new wxFileType
;
1015 fileType
->m_impl
->SetFileType("image/bmp");
1016 fileType
->m_impl
->SetExt(ext
);
1019 else if ( ext
== "tif" || ext
== "tiff" )
1021 wxFileType
*fileType
= new wxFileType
;
1022 fileType
->m_impl
->SetFileType("image/tiff");
1023 fileType
->m_impl
->SetExt(ext
);
1026 else if ( ext
== "xpm" )
1028 wxFileType
*fileType
= new wxFileType
;
1029 fileType
->m_impl
->SetFileType("image/xpm");
1030 fileType
->m_impl
->SetExt(ext
);
1033 else if ( ext
== "xbm" )
1035 wxFileType
*fileType
= new wxFileType
;
1036 fileType
->m_impl
->SetFileType("image/xbm");
1037 fileType
->m_impl
->SetExt(ext
);
1040 // unknown extension
1044 // MIME type -> extension -> file type
1046 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1053 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
1056 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
1057 while ( entry
!= NULL
) {
1058 // notice that an empty command would always succeed (it's ok)
1059 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
1061 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
1063 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1064 command
.c_str(), params
.GetMimeType().c_str());
1068 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1069 command
.c_str(), params
.GetMimeType().c_str());
1072 entry
= entry
->GetNext();
1079 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
1080 const wxFileType::MessageParameters
& params
,
1083 MailCapEntry
*entry
= GetEntry(params
);
1084 if ( entry
== NULL
) {
1085 // all tests failed...
1089 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
1090 if ( cmd
.IsEmpty() ) {
1091 // may happen, especially for "print"
1095 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
1099 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1101 wxString strExtensions
= m_manager
->GetExtension(m_index
);
1104 // one extension in the space or comma delimitid list
1106 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
1107 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1108 if ( !strExt
.IsEmpty() ) {
1109 extensions
.Add(strExt
);
1112 //else: repeated spaces (shouldn't happen, but it's not that
1113 // important if it does happen)
1115 if ( *p
== wxT('\0') )
1118 else if ( *p
== wxT('.') ) {
1119 // remove the dot from extension (but only if it's the first char)
1120 if ( !strExt
.IsEmpty() ) {
1123 //else: no, don't append it
1133 // read system and user mailcaps (TODO implement mime.types support)
1134 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1136 // directories where we look for mailcap and mime.types by default
1137 // (taken from metamail(1) sources)
1138 static const wxChar
*aStandardLocations
[] =
1142 wxT("/usr/local/etc"),
1144 wxT("/usr/public/lib")
1147 // first read the system wide file(s)
1148 for ( size_t n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
1149 wxString dir
= aStandardLocations
[n
];
1151 wxString file
= dir
+ wxT("/mailcap");
1152 if ( wxFile::Exists(file
) ) {
1156 file
= dir
+ wxT("/mime.types");
1157 if ( wxFile::Exists(file
) ) {
1158 ReadMimeTypes(file
);
1162 wxString strHome
= wxGetenv(wxT("HOME"));
1164 // and now the users mailcap
1165 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1166 if ( wxFile::Exists(strUserMailcap
) ) {
1167 ReadMailcap(strUserMailcap
);
1170 // read the users mime.types
1171 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
1172 if ( wxFile::Exists(strUserMimeTypes
) ) {
1173 ReadMimeTypes(strUserMimeTypes
);
1178 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1180 size_t count
= m_aExtensions
.GetCount();
1181 for ( size_t n
= 0; n
< count
; n
++ ) {
1182 wxString extensions
= m_aExtensions
[n
];
1183 while ( !extensions
.IsEmpty() ) {
1184 wxString field
= extensions
.BeforeFirst(wxT(' '));
1185 extensions
= extensions
.AfterFirst(wxT(' '));
1187 // consider extensions as not being case-sensitive
1188 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
1190 wxFileType
*fileType
= new wxFileType
;
1191 fileType
->m_impl
->Init(this, n
);
1203 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1205 // mime types are not case-sensitive
1206 wxString
mimetype(mimeType
);
1207 mimetype
.MakeLower();
1209 // first look for an exact match
1210 int index
= m_aTypes
.Index(mimetype
);
1211 if ( index
== wxNOT_FOUND
) {
1212 // then try to find "text/*" as match for "text/plain" (for example)
1213 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1214 // the whole string - ok.
1215 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1217 size_t nCount
= m_aTypes
.Count();
1218 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1219 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1220 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1227 if ( index
!= wxNOT_FOUND
) {
1228 wxFileType
*fileType
= new wxFileType
;
1229 fileType
->m_impl
->Init(this, index
);
1239 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1241 wxString extensions
;
1242 const wxArrayString
& exts
= filetype
.GetExtensions();
1243 size_t nExts
= exts
.GetCount();
1244 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1246 extensions
+= wxT(' ');
1248 extensions
+= exts
[nExt
];
1251 AddMimeTypeInfo(filetype
.GetMimeType(),
1253 filetype
.GetDescription());
1255 AddMailcapInfo(filetype
.GetMimeType(),
1256 filetype
.GetOpenCommand(),
1257 filetype
.GetPrintCommand(),
1259 filetype
.GetDescription());
1262 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
1263 const wxString
& strExtensions
,
1264 const wxString
& strDesc
)
1266 int index
= m_aTypes
.Index(strMimeType
);
1267 if ( index
== wxNOT_FOUND
) {
1269 m_aTypes
.Add(strMimeType
);
1270 m_aEntries
.Add(NULL
);
1271 m_aExtensions
.Add(strExtensions
);
1272 m_aDescriptions
.Add(strDesc
);
1275 // modify an existing one
1276 if ( !strDesc
.IsEmpty() ) {
1277 m_aDescriptions
[index
] = strDesc
; // replace old value
1279 m_aExtensions
[index
] += ' ' + strExtensions
;
1283 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
1284 const wxString
& strOpenCmd
,
1285 const wxString
& strPrintCmd
,
1286 const wxString
& strTest
,
1287 const wxString
& strDesc
)
1289 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1291 int nIndex
= m_aTypes
.Index(strType
);
1292 if ( nIndex
== wxNOT_FOUND
) {
1294 m_aTypes
.Add(strType
);
1296 m_aEntries
.Add(entry
);
1297 m_aExtensions
.Add(wxT(""));
1298 m_aDescriptions
.Add(strDesc
);
1301 // always append the entry in the tail of the list - info added with
1302 // this function can only come from AddFallbacks()
1303 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1305 entry
->Append(entryOld
);
1307 m_aEntries
[nIndex
] = entry
;
1311 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1313 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1315 wxTextFile
file(strFileName
);
1319 // the information we extract
1320 wxString strMimeType
, strDesc
, strExtensions
;
1322 size_t nLineCount
= file
.GetLineCount();
1323 const wxChar
*pc
= NULL
;
1324 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1326 // now we're at the start of the line
1327 pc
= file
[nLine
].c_str();
1330 // we didn't finish with the previous line yet
1335 while ( wxIsspace(*pc
) )
1339 if ( *pc
== wxT('#') ) {
1340 // skip the whole line
1345 // detect file format
1346 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1347 if ( pEqualSign
== NULL
) {
1351 // first field is mime type
1352 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1357 while ( wxIsspace(*pc
) )
1360 // take all the rest of the string
1363 // no description...
1370 // the string on the left of '=' is the field name
1371 wxString
strLHS(pc
, pEqualSign
- pc
);
1374 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
1378 if ( *pc
== wxT('"') ) {
1379 // the string is quoted and ends at the matching quote
1380 pEnd
= wxStrchr(++pc
, wxT('"'));
1381 if ( pEnd
== NULL
) {
1382 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1384 strFileName
.c_str(), nLine
+ 1);
1388 // unquoted string ends at the first space
1389 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
1393 // now we have the RHS (field value)
1394 wxString
strRHS(pc
, pEnd
- pc
);
1396 // check what follows this entry
1397 if ( *pEnd
== wxT('"') ) {
1402 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
1405 // if there is something left, it may be either a '\\' to continue
1406 // the line or the next field of the same entry
1407 bool entryEnded
= *pc
== wxT('\0'),
1408 nextFieldOnSameLine
= FALSE
;
1409 if ( !entryEnded
) {
1410 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
1413 // now see what we got
1414 if ( strLHS
== wxT("type") ) {
1415 strMimeType
= strRHS
;
1417 else if ( strLHS
== wxT("desc") ) {
1420 else if ( strLHS
== wxT("exts") ) {
1421 strExtensions
= strRHS
;
1424 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1425 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
1428 if ( !entryEnded
) {
1429 if ( !nextFieldOnSameLine
)
1431 //else: don't reset it
1433 // as we don't reset strMimeType, the next field in this entry
1434 // will be interpreted correctly.
1440 // although it doesn't seem to be covered by RFCs, some programs
1441 // (notably Netscape) create their entries with several comma
1442 // separated extensions (RFC mention the spaces only)
1443 strExtensions
.Replace(wxT(","), wxT(" "));
1445 // also deal with the leading dot
1446 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
1447 if ( !strExtensions
.IsEmpty() && strExtensions
[size_t(0)] == wxT('.') ) {
1449 if ( !strExtensions
.IsEmpty() && strExtensions
[0] == wxT('.') ) {
1451 strExtensions
.erase(0, 1);
1454 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
1456 // finished with this line
1460 // check our data integriry
1461 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1462 m_aTypes
.Count() == m_aExtensions
.Count() &&
1463 m_aTypes
.Count() == m_aDescriptions
.Count() );
1468 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
1471 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
1473 wxTextFile
file(strFileName
);
1477 // see the comments near the end of function for the reason we need these
1478 // variables (search for the next occurence of them)
1479 // indices of MIME types (in m_aTypes) we already found in this file
1480 wxArrayInt aEntryIndices
;
1481 // aLastIndices[n] is the index of last element in
1482 // m_aEntries[aEntryIndices[n]] from this file
1483 wxArrayInt aLastIndices
;
1485 size_t nLineCount
= file
.GetLineCount();
1486 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1487 // now we're at the start of the line
1488 const wxChar
*pc
= file
[nLine
].c_str();
1491 while ( wxIsspace(*pc
) )
1494 // comment or empty string?
1495 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
1500 // what field are we currently in? The first 2 are fixed and there may
1501 // be an arbitrary number of other fields -- currently, we are not
1502 // interested in any of them, but we should parse them as well...
1508 } currentToken
= Field_Type
;
1510 // the flags and field values on the current line
1511 bool needsterminal
= FALSE
,
1512 copiousoutput
= FALSE
;
1518 curField
; // accumulator
1519 for ( bool cont
= TRUE
; cont
; pc
++ ) {
1522 // interpret the next character literally (notice that
1523 // backslash can be used for line continuation)
1524 if ( *++pc
== wxT('\0') ) {
1525 // fetch the next line.
1527 // pc currently points to nowhere, but after the next
1528 // pc++ in the for line it will point to the beginning
1529 // of the next line in the file
1530 pc
= file
[++nLine
].c_str() - 1;
1533 // just a normal character
1539 cont
= FALSE
; // end of line reached, exit the loop
1544 // store this field and start looking for the next one
1546 // trim whitespaces from both sides
1547 curField
.Trim(TRUE
).Trim(FALSE
);
1549 switch ( currentToken
) {
1552 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
1553 // we interpret "type" as "type/*"
1554 strType
+= wxT("/*");
1557 currentToken
= Field_OpenCmd
;
1561 strOpenCmd
= curField
;
1563 currentToken
= Field_Other
;
1568 // "good" mailcap entry?
1571 // is this something of the form foo=bar?
1572 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
1573 if ( pEq
!= NULL
) {
1574 wxString lhs
= curField
.BeforeFirst(wxT('=')),
1575 rhs
= curField
.AfterFirst(wxT('='));
1577 lhs
.Trim(TRUE
); // from right
1578 rhs
.Trim(FALSE
); // from left
1580 if ( lhs
== wxT("print") )
1582 else if ( lhs
== wxT("test") )
1584 else if ( lhs
== wxT("description") ) {
1585 // it might be quoted
1586 if ( rhs
[0u] == wxT('"') &&
1587 rhs
.Last() == wxT('"') ) {
1588 strDesc
= wxString(rhs
.c_str() + 1,
1595 else if ( lhs
== wxT("compose") ||
1596 lhs
== wxT("composetyped") ||
1597 lhs
== wxT("notes") ||
1598 lhs
== wxT("edit") )
1605 // no, it's a simple flag
1606 // TODO support the flags:
1607 // 1. create an xterm for 'needsterminal'
1608 // 2. append "| $PAGER" for 'copiousoutput'
1609 if ( curField
== wxT("needsterminal") )
1610 needsterminal
= TRUE
;
1611 else if ( curField
== wxT("copiousoutput") )
1612 copiousoutput
= TRUE
;
1613 else if ( curField
== wxT("textualnewlines") )
1621 // don't flood the user with error messages
1622 // if we don't understand something in his
1623 // mailcap, but give them in debug mode
1624 // because this might be useful for the
1628 wxT("Mailcap file %s, line %d: unknown "
1629 "field '%s' for the MIME type "
1631 strFileName
.c_str(),
1639 // it already has this value
1640 //currentToken = Field_Other;
1644 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1647 // next token starts immediately after ';'
1656 // check that we really read something reasonable
1657 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
1658 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1660 strFileName
.c_str(), nLine
+ 1);
1663 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
1667 // NB: because of complications below (we must get entries priority
1668 // right), we can't use AddMailcapInfo() here, unfortunately.
1669 strType
.MakeLower();
1670 int nIndex
= m_aTypes
.Index(strType
);
1671 if ( nIndex
== wxNOT_FOUND
) {
1673 m_aTypes
.Add(strType
);
1675 m_aEntries
.Add(entry
);
1676 m_aExtensions
.Add(wxT(""));
1677 m_aDescriptions
.Add(strDesc
);
1680 // modify the existing entry: the entries in one and the same
1681 // file are read in top-to-bottom order, i.e. the entries read
1682 // first should be tried before the entries below. However,
1683 // the files read later should override the settings in the
1684 // files read before (except if fallback is TRUE), thus we
1685 // Insert() the new entry to the list if it has already
1686 // occured in _this_ file, but Prepend() it if it occured in
1687 // some of the previous ones and Append() to it in the
1691 // 'fallback' parameter prevents the entries from this
1692 // file from overriding the other ones - always append
1693 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1695 entry
->Append(entryOld
);
1697 m_aEntries
[nIndex
] = entry
;
1700 int entryIndex
= aEntryIndices
.Index(nIndex
);
1701 if ( entryIndex
== wxNOT_FOUND
) {
1702 // first time in this file
1703 aEntryIndices
.Add(nIndex
);
1704 aLastIndices
.Add(0);
1706 entry
->Prepend(m_aEntries
[nIndex
]);
1707 m_aEntries
[nIndex
] = entry
;
1710 // not the first time in _this_ file
1711 size_t nEntryIndex
= (size_t)entryIndex
;
1712 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1714 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
1716 m_aEntries
[nIndex
] = entry
;
1718 // the indices were shifted by 1
1719 aLastIndices
[nEntryIndex
]++;
1723 if ( !strDesc
.IsEmpty() ) {
1724 // replace the old one - what else can we do??
1725 m_aDescriptions
[nIndex
] = strDesc
;
1730 // check our data integriry
1731 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1732 m_aTypes
.Count() == m_aExtensions
.Count() &&
1733 m_aTypes
.Count() == m_aDescriptions
.Count() );
1743 // wxUSE_FILE && wxUSE_TEXTFILE