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)
82 // although I don't know of any official documentation which mentions this
83 // location, uses it, so it isn't likely to change
84 static const wxChar
*MIME_DATABASE_KEY
= wxT("MIME\\Database\\Content Type\\");
90 wxFileTypeImpl() { m_info
= NULL
; }
92 // one of these Init() function must be called (ctor can't take any
93 // arguments because it's common)
95 // initialize us with our file type name and extension - in this case
96 // we will read all other data from the registry
97 void Init(const wxString
& strFileType
, const wxString
& ext
)
98 { m_strFileType
= strFileType
; m_ext
= ext
; }
100 // initialize us with a wxFileTypeInfo object - it contains all the
102 void Init(const wxFileTypeInfo
& info
)
105 // implement accessor functions
106 bool GetExtensions(wxArrayString
& extensions
);
107 bool GetMimeType(wxString
*mimeType
) const;
108 bool GetIcon(wxIcon
*icon
) const;
109 bool GetDescription(wxString
*desc
) const;
110 bool GetOpenCommand(wxString
*openCmd
,
111 const wxFileType::MessageParameters
& params
) const;
112 bool GetPrintCommand(wxString
*printCmd
,
113 const wxFileType::MessageParameters
& params
) const;
116 // helper function: reads the command corresponding to the specified verb
117 // from the registry (returns an empty string if not found)
118 wxString
GetCommand(const wxChar
*verb
) const;
120 // we use either m_info or read the data from the registry if m_info == NULL
121 const wxFileTypeInfo
*m_info
;
122 wxString m_strFileType
,
126 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
127 #include "wx/arrimpl.cpp"
128 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
130 class wxMimeTypesManagerImpl
133 // nothing to do here, we don't load any data but just go and fetch it from
134 // the registry when asked for
135 wxMimeTypesManagerImpl() { }
137 // implement containing class functions
138 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
139 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
141 size_t EnumAllFileTypes(wxFileType
**filetypes
);
143 // this are NOPs under Windows
144 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
)
146 bool ReadMimeTypes(const wxString
& filename
)
149 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
152 wxArrayFileTypeInfo m_fallbacks
;
155 #elif defined( __WXMAC__ )
157 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
158 #include "wx/arrimpl.cpp"
159 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
161 class wxMimeTypesManagerImpl
164 wxMimeTypesManagerImpl() { }
166 // implement containing class functions
167 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
168 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
170 size_t EnumAllFileTypes(wxFileType
**filetypes
);
172 // this are NOPs under MacOS
173 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
) { return TRUE
; }
174 bool ReadMimeTypes(const wxString
& filename
) { return TRUE
; }
176 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
179 wxArrayFileTypeInfo m_fallbacks
;
185 // initialize us with our file type name
186 void SetFileType(const wxString
& strFileType
)
187 { m_strFileType
= strFileType
; }
188 void SetExt(const wxString
& ext
)
191 // implement accessor functions
192 bool GetExtensions(wxArrayString
& extensions
);
193 bool GetMimeType(wxString
*mimeType
) const;
194 bool GetIcon(wxIcon
*icon
) const;
195 bool GetDescription(wxString
*desc
) const;
196 bool GetOpenCommand(wxString
*openCmd
,
197 const wxFileType::MessageParameters
&) const
198 { return GetCommand(openCmd
, "open"); }
199 bool GetPrintCommand(wxString
*printCmd
,
200 const wxFileType::MessageParameters
&) const
201 { return GetCommand(printCmd
, "print"); }
205 bool GetCommand(wxString
*command
, const char *verb
) const;
207 wxString m_strFileType
, m_ext
;
212 // this class uses both mailcap and mime.types to gather information about file
215 // The information about mailcap file was extracted from metamail(1) sources and
218 // Format of mailcap file: spaces are ignored, each line is either a comment
219 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
220 // A backslash can be used to quote semicolons and newlines (and, in fact,
221 // anything else including itself).
223 // The first field is always the MIME type in the form of type/subtype (see RFC
224 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
225 // "type" which means the same as "type/*", although I'm not sure whether this
228 // The second field is always the command to run. It is subject to
229 // parameter/filename expansion described below.
231 // All the following fields are optional and may not be present at all. If
232 // they're present they may appear in any order, although each of them should
233 // appear only once. The optional fields are the following:
234 // * notes=xxx is an uninterpreted string which is silently ignored
235 // * test=xxx is the command to be used to determine whether this mailcap line
236 // applies to our data or not. The RHS of this field goes through the
237 // parameter/filename expansion (as the 2nd field) and the resulting string
238 // is executed. The line applies only if the command succeeds, i.e. returns 0
240 // * print=xxx is the command to be used to print (and not view) the data of
241 // this type (parameter/filename expansion is done here too)
242 // * edit=xxx is the command to open/edit the data of this type
243 // * needsterminal means that a new console must be created for the viewer
244 // * copiousoutput means that the viewer doesn't interact with the user but
245 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
246 // good example), thus it might be a good idea to use some kind of paging
248 // * textualnewlines means not to perform CR/LF translation (not honored)
249 // * compose and composetyped fields are used to determine the program to be
250 // called to create a new message pert in the specified format (unused).
252 // Parameter/filename xpansion:
253 // * %s is replaced with the (full) file name
254 // * %t is replaced with MIME type/subtype of the entry
255 // * for multipart type only %n is replaced with the nnumber of parts and %F is
256 // replaced by an array of (content-type, temporary file name) pairs for all
257 // message parts (TODO)
258 // * %{parameter} is replaced with the value of parameter taken from
259 // Content-type header line of the message.
261 // FIXME any docs with real descriptions of these files??
263 // There are 2 possible formats for mime.types file, one entry per line (used
264 // for global mime.types) and "expanded" format where an entry takes multiple
265 // lines (used for users mime.types).
267 // For both formats spaces are ignored and lines starting with a '#' are
268 // comments. Each record has one of two following forms:
269 // a) for "brief" format:
270 // <mime type> <space separated list of extensions>
271 // b) for "expanded" format:
272 // type=<mime type> \ desc="<description>" \ exts="ext"
274 // We try to autodetect the format of mime.types: if a non-comment line starts
275 // with "type=" we assume the second format, otherwise the first one.
277 // there may be more than one entry for one and the same mime type, to
278 // choose the right one we have to run the command specified in the test
279 // field on our data.
284 MailCapEntry(const wxString
& openCmd
,
285 const wxString
& printCmd
,
286 const wxString
& testCmd
)
287 : m_openCmd(openCmd
), m_printCmd(printCmd
), m_testCmd(testCmd
)
293 const wxString
& GetOpenCmd() const { return m_openCmd
; }
294 const wxString
& GetPrintCmd() const { return m_printCmd
; }
295 const wxString
& GetTestCmd() const { return m_testCmd
; }
297 MailCapEntry
*GetNext() const { return m_next
; }
300 // prepend this element to the list
301 void Prepend(MailCapEntry
*next
) { m_next
= next
; }
302 // insert into the list at given position
303 void Insert(MailCapEntry
*next
, size_t pos
)
308 for ( cur
= next
; cur
!= NULL
; cur
= cur
->m_next
, n
++ ) {
313 wxASSERT_MSG( n
== pos
, wxT("invalid position in MailCapEntry::Insert") );
315 m_next
= cur
->m_next
;
318 // append this element to the list
319 void Append(MailCapEntry
*next
)
321 wxCHECK_RET( next
!= NULL
, wxT("Append()ing to what?") );
325 for ( cur
= next
; cur
->m_next
!= NULL
; cur
= cur
->m_next
)
330 wxASSERT_MSG( !m_next
, wxT("Append()ing element already in the list?") );
334 wxString m_openCmd
, // command to use to open/view the file
336 m_testCmd
; // only apply this entry if test yields
337 // true (i.e. the command returns 0)
339 MailCapEntry
*m_next
; // in the linked list
342 WX_DEFINE_ARRAY(MailCapEntry
*, ArrayTypeEntries
);
344 class wxMimeTypesManagerImpl
346 friend class wxFileTypeImpl
; // give it access to m_aXXX variables
349 // ctor loads all info into memory for quicker access later on
350 // TODO it would be nice to load them all, but parse on demand only...
351 wxMimeTypesManagerImpl();
353 // implement containing class functions
354 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
355 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
357 size_t EnumAllFileTypes(wxFileType
**filetypes
);
359 bool ReadMailcap(const wxString
& filename
, bool fallback
= FALSE
);
360 bool ReadMimeTypes(const wxString
& filename
);
362 void AddFallback(const wxFileTypeInfo
& filetype
);
364 // add information about the given mimetype
365 void AddMimeTypeInfo(const wxString
& mimetype
,
366 const wxString
& extensions
,
367 const wxString
& description
);
368 void AddMailcapInfo(const wxString
& strType
,
369 const wxString
& strOpenCmd
,
370 const wxString
& strPrintCmd
,
371 const wxString
& strTest
,
372 const wxString
& strDesc
);
375 // get the string containing space separated extensions for the given
377 wxString
GetExtension(size_t index
) { return m_aExtensions
[index
]; }
380 wxArrayString m_aTypes
, // MIME types
381 m_aDescriptions
, // descriptions (just some text)
382 m_aExtensions
; // space separated list of extensions
383 ArrayTypeEntries m_aEntries
; // commands and tests for this file type
389 // initialization functions
390 void Init(wxMimeTypesManagerImpl
*manager
, size_t index
)
391 { m_manager
= manager
; m_index
= index
; }
394 bool GetExtensions(wxArrayString
& extensions
);
395 bool GetMimeType(wxString
*mimeType
) const
396 { *mimeType
= m_manager
->m_aTypes
[m_index
]; return TRUE
; }
397 bool GetIcon(wxIcon
* WXUNUSED(icon
)) const
398 { return FALSE
; } // TODO maybe with Gnome/KDE integration...
399 bool GetDescription(wxString
*desc
) const
400 { *desc
= m_manager
->m_aDescriptions
[m_index
]; return TRUE
; }
402 bool GetOpenCommand(wxString
*openCmd
,
403 const wxFileType::MessageParameters
& params
) const
405 return GetExpandedCommand(openCmd
, params
, TRUE
);
408 bool GetPrintCommand(wxString
*printCmd
,
409 const wxFileType::MessageParameters
& params
) const
411 return GetExpandedCommand(printCmd
, params
, FALSE
);
415 // get the entry which passes the test (may return NULL)
416 MailCapEntry
*GetEntry(const wxFileType::MessageParameters
& params
) const;
418 // choose the correct entry to use and expand the command
419 bool GetExpandedCommand(wxString
*expandedCmd
,
420 const wxFileType::MessageParameters
& params
,
423 wxMimeTypesManagerImpl
*m_manager
;
424 size_t m_index
; // in the wxMimeTypesManagerImpl arrays
429 // ============================================================================
431 // ============================================================================
433 // ----------------------------------------------------------------------------
435 // ----------------------------------------------------------------------------
437 wxFileTypeInfo::wxFileTypeInfo(const char *mimeType
,
439 const char *printCmd
,
442 : m_mimeType(mimeType
),
444 m_printCmd(printCmd
),
448 va_start(argptr
, desc
);
452 const char *ext
= va_arg(argptr
, const char *);
455 // NULL terminates the list
465 // ============================================================================
466 // implementation of the wrapper classes
467 // ============================================================================
469 // ----------------------------------------------------------------------------
471 // ----------------------------------------------------------------------------
473 wxString
wxFileType::ExpandCommand(const wxString
& command
,
474 const wxFileType::MessageParameters
& params
)
476 bool hasFilename
= FALSE
;
479 for ( const wxChar
*pc
= command
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
480 if ( *pc
== wxT('%') ) {
483 // '%s' expands into file name (quoted because it might
484 // contain spaces) - except if there are already quotes
485 // there because otherwise some programs may get confused
486 // by double double quotes
488 if ( *(pc
- 2) == wxT('"') )
489 str
<< params
.GetFileName();
491 str
<< wxT('"') << params
.GetFileName() << wxT('"');
493 str
<< params
.GetFileName();
498 // '%t' expands into MIME type (quote it too just to be
500 str
<< wxT('\'') << params
.GetMimeType() << wxT('\'');
505 const wxChar
*pEnd
= wxStrchr(pc
, wxT('}'));
506 if ( pEnd
== NULL
) {
508 wxLogWarning(_("Unmatched '{' in an entry for "
510 params
.GetMimeType().c_str());
514 wxString
param(pc
+ 1, pEnd
- pc
- 1);
515 str
<< wxT('\'') << params
.GetParamValue(param
) << wxT('\'');
523 // TODO %n is the number of parts, %F is an array containing
524 // the names of temp files these parts were written to
525 // and their mime types.
529 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
530 *pc
, command
.c_str());
539 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
540 // the program will accept the data on stdin: so give it to it!
541 if ( !hasFilename
&& !str
.IsEmpty() ) {
542 str
<< wxT(" < '") << params
.GetFileName() << wxT('\'');
548 wxFileType::wxFileType()
550 m_impl
= new wxFileTypeImpl
;
553 wxFileType::~wxFileType()
558 bool wxFileType::GetExtensions(wxArrayString
& extensions
)
560 return m_impl
->GetExtensions(extensions
);
563 bool wxFileType::GetMimeType(wxString
*mimeType
) const
565 return m_impl
->GetMimeType(mimeType
);
568 bool wxFileType::GetIcon(wxIcon
*icon
) const
570 return m_impl
->GetIcon(icon
);
573 bool wxFileType::GetDescription(wxString
*desc
) const
575 return m_impl
->GetDescription(desc
);
579 wxFileType::GetOpenCommand(wxString
*openCmd
,
580 const wxFileType::MessageParameters
& params
) const
582 return m_impl
->GetOpenCommand(openCmd
, params
);
586 wxFileType::GetPrintCommand(wxString
*printCmd
,
587 const wxFileType::MessageParameters
& params
) const
589 return m_impl
->GetPrintCommand(printCmd
, params
);
592 // ----------------------------------------------------------------------------
593 // wxMimeTypesManager
594 // ----------------------------------------------------------------------------
596 bool wxMimeTypesManager::IsOfType(const wxString
& mimeType
,
597 const wxString
& wildcard
)
599 wxASSERT_MSG( mimeType
.Find(wxT('*')) == wxNOT_FOUND
,
600 wxT("first MIME type can't contain wildcards") );
602 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
603 if ( wildcard
.BeforeFirst(wxT('/')).IsSameAs(mimeType
.BeforeFirst(wxT('/')), FALSE
) )
605 wxString strSubtype
= wildcard
.AfterFirst(wxT('/'));
607 if ( strSubtype
== wxT("*") ||
608 strSubtype
.IsSameAs(mimeType
.AfterFirst(wxT('/')), FALSE
) )
610 // matches (either exactly or it's a wildcard)
618 wxMimeTypesManager::wxMimeTypesManager()
620 m_impl
= new wxMimeTypesManagerImpl
;
623 wxMimeTypesManager::~wxMimeTypesManager()
629 wxMimeTypesManager::GetFileTypeFromExtension(const wxString
& ext
)
631 return m_impl
->GetFileTypeFromExtension(ext
);
635 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString
& mimeType
)
637 return m_impl
->GetFileTypeFromMimeType(mimeType
);
640 bool wxMimeTypesManager::ReadMailcap(const wxString
& filename
, bool fallback
)
642 return m_impl
->ReadMailcap(filename
, fallback
);
645 bool wxMimeTypesManager::ReadMimeTypes(const wxString
& filename
)
647 return m_impl
->ReadMimeTypes(filename
);
650 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo
*filetypes
)
652 for ( const wxFileTypeInfo
*ft
= filetypes
; ft
->IsValid(); ft
++ ) {
653 m_impl
->AddFallback(*ft
);
657 size_t wxMimeTypesManager::EnumAllFileTypes(wxFileType
**filetypes
)
659 wxCHECK_MSG( filetypes
, 0u, _T("bad pointer in EnumAllFileTypes") );
661 return m_impl
->EnumAllFileTypes(filetypes
);
664 // ============================================================================
665 // real (OS specific) implementation
666 // ============================================================================
670 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
672 // suppress possible error messages
675 strKey
<< m_strFileType
<< wxT("\\shell\\") << verb
<< wxT("\\command");
676 wxRegKey
key(wxRegKey::HKCR
, strKey
);
680 // it's the default value of the key
681 if ( key
.QueryValue(wxT(""), command
) ) {
682 // transform it from '%1' to '%s' style format string
684 // NB: we don't make any attempt to verify that the string is valid,
685 // i.e. doesn't contain %2, or second %1 or .... But we do make
686 // sure that we return a string with _exactly_ one '%s'!
687 bool foundFilename
= FALSE
;
688 size_t len
= command
.Len();
689 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
690 if ( command
[n
] == wxT('%') &&
691 (n
+ 1 < len
) && command
[n
+ 1] == wxT('1') ) {
692 // replace it with '%s'
693 command
[n
+ 1] = wxT('s');
695 foundFilename
= TRUE
;
699 if ( !foundFilename
) {
700 // we didn't find any '%1'!
701 // HACK: append the filename at the end, hope that it will do
702 command
<< wxT(" %s");
707 // no such file type or no value
712 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
713 const wxFileType::MessageParameters
& params
)
718 cmd
= m_info
->GetOpenCommand();
721 cmd
= GetCommand(wxT("open"));
724 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
726 return !openCmd
->IsEmpty();
730 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
731 const wxFileType::MessageParameters
& params
)
736 cmd
= m_info
->GetPrintCommand();
739 cmd
= GetCommand(wxT("print"));
742 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
744 return !printCmd
->IsEmpty();
747 // TODO this function is half implemented
748 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
751 extensions
= m_info
->GetExtensions();
755 else if ( m_ext
.IsEmpty() ) {
756 // the only way to get the list of extensions from the file type is to
757 // scan through all extensions in the registry - too slow...
762 extensions
.Add(m_ext
);
764 // it's a lie too, we don't return _all_ extensions...
769 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
772 // we already have it
773 *mimeType
= m_info
->GetMimeType();
778 // suppress possible error messages
780 wxRegKey
key(wxRegKey::HKCR
, /*m_strFileType*/ wxT(".") + m_ext
);
781 if ( key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
) ) {
789 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
793 // we don't have icons in the fallback resources
798 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
800 // suppress possible error messages
802 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
806 // it's the default value of the key
807 if ( key
.QueryValue(wxT(""), strIcon
) ) {
808 // the format is the following: <full path to file>, <icon index>
809 // NB: icon index may be negative as well as positive and the full
810 // path may contain the environment variables inside '%'
811 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
812 strIndex
= strIcon
.AfterLast(wxT(','));
814 // index may be omitted, in which case BeforeLast(',') is empty and
815 // AfterLast(',') is the whole string
816 if ( strFullPath
.IsEmpty() ) {
817 strFullPath
= strIndex
;
821 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
822 int nIndex
= wxAtoi(strIndex
);
824 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
825 switch ( (int)hIcon
) {
826 case 0: // means no icons were found
827 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
828 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
829 key
.GetName().c_str());
833 icon
->SetHICON((WXHICON
)hIcon
);
839 // no such file type or no value or incorrect icon entry
845 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
848 // we already have it
849 *desc
= m_info
->GetDescription();
854 // suppress possible error messages
856 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
859 // it's the default value of the key
860 if ( key
.QueryValue(wxT(""), *desc
) ) {
868 // extension -> file type
870 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
872 // add the leading point if necessary
874 if ( ext
[0u] != wxT('.') ) {
879 // suppress possible error messages
882 wxString strFileType
;
883 wxRegKey
key(wxRegKey::HKCR
, str
);
885 // it's the default value of the key
886 if ( key
.QueryValue(wxT(""), strFileType
) ) {
887 // create the new wxFileType object
888 wxFileType
*fileType
= new wxFileType
;
889 fileType
->m_impl
->Init(strFileType
, ext
);
895 // check the fallbacks
896 // TODO linear search is potentially slow, perhaps we should use a sorted
898 size_t count
= m_fallbacks
.GetCount();
899 for ( size_t n
= 0; n
< count
; n
++ ) {
900 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
901 wxFileType
*fileType
= new wxFileType
;
902 fileType
->m_impl
->Init(m_fallbacks
[n
]);
912 // MIME type -> extension -> file type
914 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
916 wxString strKey
= MIME_DATABASE_KEY
;
919 // suppress possible error messages
923 wxRegKey
key(wxRegKey::HKCR
, strKey
);
925 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
926 return GetFileTypeFromExtension(ext
);
930 // check the fallbacks
931 // TODO linear search is potentially slow, perhaps we should use a sorted
933 size_t count
= m_fallbacks
.GetCount();
934 for ( size_t n
= 0; n
< count
; n
++ ) {
935 if ( wxMimeTypesManager::IsOfType(mimeType
,
936 m_fallbacks
[n
].GetMimeType()) ) {
937 wxFileType
*fileType
= new wxFileType
;
938 fileType
->m_impl
->Init(m_fallbacks
[n
]);
948 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxFileType
**filetypes
)
950 // enumerate all keys under MIME_DATABASE_KEY
951 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
956 #elif defined ( __WXMAC__ )
958 bool wxFileTypeImpl::GetCommand(wxString
*command
, const char *verb
) const
963 // @@ this function is half implemented
964 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
969 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
971 if ( m_strFileType
.Length() > 0 )
973 *mimeType
= m_strFileType
;
980 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
982 // no such file type or no value or incorrect icon entry
986 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
991 // extension -> file type
993 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& e
)
999 wxFileType
*fileType
= new wxFileType
;
1000 fileType
->m_impl
->SetFileType("text/text");
1001 fileType
->m_impl
->SetExt(ext
);
1004 else if ( ext
== "htm" || ext
== "html" )
1006 wxFileType
*fileType
= new wxFileType
;
1007 fileType
->m_impl
->SetFileType("text/html");
1008 fileType
->m_impl
->SetExt(ext
);
1011 else if ( ext
== "gif" )
1013 wxFileType
*fileType
= new wxFileType
;
1014 fileType
->m_impl
->SetFileType("image/gif");
1015 fileType
->m_impl
->SetExt(ext
);
1018 else if ( ext
== "png" )
1020 wxFileType
*fileType
= new wxFileType
;
1021 fileType
->m_impl
->SetFileType("image/png");
1022 fileType
->m_impl
->SetExt(ext
);
1025 else if ( ext
== "jpg" || ext
== "jpeg" )
1027 wxFileType
*fileType
= new wxFileType
;
1028 fileType
->m_impl
->SetFileType("image/jpeg");
1029 fileType
->m_impl
->SetExt(ext
);
1032 else if ( ext
== "bmp" )
1034 wxFileType
*fileType
= new wxFileType
;
1035 fileType
->m_impl
->SetFileType("image/bmp");
1036 fileType
->m_impl
->SetExt(ext
);
1039 else if ( ext
== "tif" || ext
== "tiff" )
1041 wxFileType
*fileType
= new wxFileType
;
1042 fileType
->m_impl
->SetFileType("image/tiff");
1043 fileType
->m_impl
->SetExt(ext
);
1046 else if ( ext
== "xpm" )
1048 wxFileType
*fileType
= new wxFileType
;
1049 fileType
->m_impl
->SetFileType("image/xpm");
1050 fileType
->m_impl
->SetExt(ext
);
1053 else if ( ext
== "xbm" )
1055 wxFileType
*fileType
= new wxFileType
;
1056 fileType
->m_impl
->SetFileType("image/xbm");
1057 fileType
->m_impl
->SetExt(ext
);
1061 // unknown extension
1065 // MIME type -> extension -> file type
1067 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1072 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxFileType
**filetypes
)
1074 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1082 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
1085 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
1086 while ( entry
!= NULL
) {
1087 // notice that an empty command would always succeed (it's ok)
1088 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
1090 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
1092 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1093 command
.c_str(), params
.GetMimeType().c_str());
1097 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1098 command
.c_str(), params
.GetMimeType().c_str());
1101 entry
= entry
->GetNext();
1108 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
1109 const wxFileType::MessageParameters
& params
,
1112 MailCapEntry
*entry
= GetEntry(params
);
1113 if ( entry
== NULL
) {
1114 // all tests failed...
1118 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
1119 if ( cmd
.IsEmpty() ) {
1120 // may happen, especially for "print"
1124 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
1128 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1130 wxString strExtensions
= m_manager
->GetExtension(m_index
);
1133 // one extension in the space or comma delimitid list
1135 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
1136 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1137 if ( !strExt
.IsEmpty() ) {
1138 extensions
.Add(strExt
);
1141 //else: repeated spaces (shouldn't happen, but it's not that
1142 // important if it does happen)
1144 if ( *p
== wxT('\0') )
1147 else if ( *p
== wxT('.') ) {
1148 // remove the dot from extension (but only if it's the first char)
1149 if ( !strExt
.IsEmpty() ) {
1152 //else: no, don't append it
1162 // read system and user mailcaps (TODO implement mime.types support)
1163 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1165 // directories where we look for mailcap and mime.types by default
1166 // (taken from metamail(1) sources)
1167 static const wxChar
*aStandardLocations
[] =
1171 wxT("/usr/local/etc"),
1173 wxT("/usr/public/lib")
1176 // first read the system wide file(s)
1177 for ( size_t n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
1178 wxString dir
= aStandardLocations
[n
];
1180 wxString file
= dir
+ wxT("/mailcap");
1181 if ( wxFile::Exists(file
) ) {
1185 file
= dir
+ wxT("/mime.types");
1186 if ( wxFile::Exists(file
) ) {
1187 ReadMimeTypes(file
);
1191 wxString strHome
= wxGetenv(wxT("HOME"));
1193 // and now the users mailcap
1194 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1195 if ( wxFile::Exists(strUserMailcap
) ) {
1196 ReadMailcap(strUserMailcap
);
1199 // read the users mime.types
1200 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
1201 if ( wxFile::Exists(strUserMimeTypes
) ) {
1202 ReadMimeTypes(strUserMimeTypes
);
1207 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1209 size_t count
= m_aExtensions
.GetCount();
1210 for ( size_t n
= 0; n
< count
; n
++ ) {
1211 wxString extensions
= m_aExtensions
[n
];
1212 while ( !extensions
.IsEmpty() ) {
1213 wxString field
= extensions
.BeforeFirst(wxT(' '));
1214 extensions
= extensions
.AfterFirst(wxT(' '));
1216 // consider extensions as not being case-sensitive
1217 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
1219 wxFileType
*fileType
= new wxFileType
;
1220 fileType
->m_impl
->Init(this, n
);
1232 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1234 // mime types are not case-sensitive
1235 wxString
mimetype(mimeType
);
1236 mimetype
.MakeLower();
1238 // first look for an exact match
1239 int index
= m_aTypes
.Index(mimetype
);
1240 if ( index
== wxNOT_FOUND
) {
1241 // then try to find "text/*" as match for "text/plain" (for example)
1242 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1243 // the whole string - ok.
1244 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1246 size_t nCount
= m_aTypes
.Count();
1247 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1248 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1249 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1256 if ( index
!= wxNOT_FOUND
) {
1257 wxFileType
*fileType
= new wxFileType
;
1258 fileType
->m_impl
->Init(this, index
);
1268 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1270 wxString extensions
;
1271 const wxArrayString
& exts
= filetype
.GetExtensions();
1272 size_t nExts
= exts
.GetCount();
1273 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1275 extensions
+= wxT(' ');
1277 extensions
+= exts
[nExt
];
1280 AddMimeTypeInfo(filetype
.GetMimeType(),
1282 filetype
.GetDescription());
1284 AddMailcapInfo(filetype
.GetMimeType(),
1285 filetype
.GetOpenCommand(),
1286 filetype
.GetPrintCommand(),
1288 filetype
.GetDescription());
1291 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
1292 const wxString
& strExtensions
,
1293 const wxString
& strDesc
)
1295 int index
= m_aTypes
.Index(strMimeType
);
1296 if ( index
== wxNOT_FOUND
) {
1298 m_aTypes
.Add(strMimeType
);
1299 m_aEntries
.Add(NULL
);
1300 m_aExtensions
.Add(strExtensions
);
1301 m_aDescriptions
.Add(strDesc
);
1304 // modify an existing one
1305 if ( !strDesc
.IsEmpty() ) {
1306 m_aDescriptions
[index
] = strDesc
; // replace old value
1308 m_aExtensions
[index
] += ' ' + strExtensions
;
1312 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
1313 const wxString
& strOpenCmd
,
1314 const wxString
& strPrintCmd
,
1315 const wxString
& strTest
,
1316 const wxString
& strDesc
)
1318 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1320 int nIndex
= m_aTypes
.Index(strType
);
1321 if ( nIndex
== wxNOT_FOUND
) {
1323 m_aTypes
.Add(strType
);
1325 m_aEntries
.Add(entry
);
1326 m_aExtensions
.Add(wxT(""));
1327 m_aDescriptions
.Add(strDesc
);
1330 // always append the entry in the tail of the list - info added with
1331 // this function can only come from AddFallbacks()
1332 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1334 entry
->Append(entryOld
);
1336 m_aEntries
[nIndex
] = entry
;
1340 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1342 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1344 wxTextFile
file(strFileName
);
1348 // the information we extract
1349 wxString strMimeType
, strDesc
, strExtensions
;
1351 size_t nLineCount
= file
.GetLineCount();
1352 const wxChar
*pc
= NULL
;
1353 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1355 // now we're at the start of the line
1356 pc
= file
[nLine
].c_str();
1359 // we didn't finish with the previous line yet
1364 while ( wxIsspace(*pc
) )
1368 if ( *pc
== wxT('#') ) {
1369 // skip the whole line
1374 // detect file format
1375 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1376 if ( pEqualSign
== NULL
) {
1380 // first field is mime type
1381 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1386 while ( wxIsspace(*pc
) )
1389 // take all the rest of the string
1392 // no description...
1399 // the string on the left of '=' is the field name
1400 wxString
strLHS(pc
, pEqualSign
- pc
);
1403 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
1407 if ( *pc
== wxT('"') ) {
1408 // the string is quoted and ends at the matching quote
1409 pEnd
= wxStrchr(++pc
, wxT('"'));
1410 if ( pEnd
== NULL
) {
1411 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1413 strFileName
.c_str(), nLine
+ 1);
1417 // unquoted string ends at the first space
1418 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
1422 // now we have the RHS (field value)
1423 wxString
strRHS(pc
, pEnd
- pc
);
1425 // check what follows this entry
1426 if ( *pEnd
== wxT('"') ) {
1431 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
1434 // if there is something left, it may be either a '\\' to continue
1435 // the line or the next field of the same entry
1436 bool entryEnded
= *pc
== wxT('\0'),
1437 nextFieldOnSameLine
= FALSE
;
1438 if ( !entryEnded
) {
1439 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
1442 // now see what we got
1443 if ( strLHS
== wxT("type") ) {
1444 strMimeType
= strRHS
;
1446 else if ( strLHS
== wxT("desc") ) {
1449 else if ( strLHS
== wxT("exts") ) {
1450 strExtensions
= strRHS
;
1453 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1454 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
1457 if ( !entryEnded
) {
1458 if ( !nextFieldOnSameLine
)
1460 //else: don't reset it
1462 // as we don't reset strMimeType, the next field in this entry
1463 // will be interpreted correctly.
1469 // although it doesn't seem to be covered by RFCs, some programs
1470 // (notably Netscape) create their entries with several comma
1471 // separated extensions (RFC mention the spaces only)
1472 strExtensions
.Replace(wxT(","), wxT(" "));
1474 // also deal with the leading dot
1475 if ( !strExtensions
.IsEmpty() && strExtensions
[0u] == wxT('.') )
1477 strExtensions
.erase(0, 1);
1480 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
1482 // finished with this line
1486 // check our data integriry
1487 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1488 m_aTypes
.Count() == m_aExtensions
.Count() &&
1489 m_aTypes
.Count() == m_aDescriptions
.Count() );
1494 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
1497 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
1499 wxTextFile
file(strFileName
);
1503 // see the comments near the end of function for the reason we need these
1504 // variables (search for the next occurence of them)
1505 // indices of MIME types (in m_aTypes) we already found in this file
1506 wxArrayInt aEntryIndices
;
1507 // aLastIndices[n] is the index of last element in
1508 // m_aEntries[aEntryIndices[n]] from this file
1509 wxArrayInt aLastIndices
;
1511 size_t nLineCount
= file
.GetLineCount();
1512 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1513 // now we're at the start of the line
1514 const wxChar
*pc
= file
[nLine
].c_str();
1517 while ( wxIsspace(*pc
) )
1520 // comment or empty string?
1521 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
1526 // what field are we currently in? The first 2 are fixed and there may
1527 // be an arbitrary number of other fields -- currently, we are not
1528 // interested in any of them, but we should parse them as well...
1534 } currentToken
= Field_Type
;
1536 // the flags and field values on the current line
1537 bool needsterminal
= FALSE
,
1538 copiousoutput
= FALSE
;
1544 curField
; // accumulator
1545 for ( bool cont
= TRUE
; cont
; pc
++ ) {
1548 // interpret the next character literally (notice that
1549 // backslash can be used for line continuation)
1550 if ( *++pc
== wxT('\0') ) {
1551 // fetch the next line.
1553 // pc currently points to nowhere, but after the next
1554 // pc++ in the for line it will point to the beginning
1555 // of the next line in the file
1556 pc
= file
[++nLine
].c_str() - 1;
1559 // just a normal character
1565 cont
= FALSE
; // end of line reached, exit the loop
1570 // store this field and start looking for the next one
1572 // trim whitespaces from both sides
1573 curField
.Trim(TRUE
).Trim(FALSE
);
1575 switch ( currentToken
) {
1578 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
1579 // we interpret "type" as "type/*"
1580 strType
+= wxT("/*");
1583 currentToken
= Field_OpenCmd
;
1587 strOpenCmd
= curField
;
1589 currentToken
= Field_Other
;
1594 // "good" mailcap entry?
1597 // is this something of the form foo=bar?
1598 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
1599 if ( pEq
!= NULL
) {
1600 wxString lhs
= curField
.BeforeFirst(wxT('=')),
1601 rhs
= curField
.AfterFirst(wxT('='));
1603 lhs
.Trim(TRUE
); // from right
1604 rhs
.Trim(FALSE
); // from left
1606 if ( lhs
== wxT("print") )
1608 else if ( lhs
== wxT("test") )
1610 else if ( lhs
== wxT("description") ) {
1611 // it might be quoted
1612 if ( rhs
[0u] == wxT('"') &&
1613 rhs
.Last() == wxT('"') ) {
1614 strDesc
= wxString(rhs
.c_str() + 1,
1621 else if ( lhs
== wxT("compose") ||
1622 lhs
== wxT("composetyped") ||
1623 lhs
== wxT("notes") ||
1624 lhs
== wxT("edit") )
1631 // no, it's a simple flag
1632 // TODO support the flags:
1633 // 1. create an xterm for 'needsterminal'
1634 // 2. append "| $PAGER" for 'copiousoutput'
1635 if ( curField
== wxT("needsterminal") )
1636 needsterminal
= TRUE
;
1637 else if ( curField
== wxT("copiousoutput") )
1638 copiousoutput
= TRUE
;
1639 else if ( curField
== wxT("textualnewlines") )
1647 // don't flood the user with error messages
1648 // if we don't understand something in his
1649 // mailcap, but give them in debug mode
1650 // because this might be useful for the
1654 wxT("Mailcap file %s, line %d: unknown "
1655 "field '%s' for the MIME type "
1657 strFileName
.c_str(),
1665 // it already has this value
1666 //currentToken = Field_Other;
1670 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1673 // next token starts immediately after ';'
1682 // check that we really read something reasonable
1683 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
1684 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1686 strFileName
.c_str(), nLine
+ 1);
1689 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
1693 // NB: because of complications below (we must get entries priority
1694 // right), we can't use AddMailcapInfo() here, unfortunately.
1695 strType
.MakeLower();
1696 int nIndex
= m_aTypes
.Index(strType
);
1697 if ( nIndex
== wxNOT_FOUND
) {
1699 m_aTypes
.Add(strType
);
1701 m_aEntries
.Add(entry
);
1702 m_aExtensions
.Add(wxT(""));
1703 m_aDescriptions
.Add(strDesc
);
1706 // modify the existing entry: the entries in one and the same
1707 // file are read in top-to-bottom order, i.e. the entries read
1708 // first should be tried before the entries below. However,
1709 // the files read later should override the settings in the
1710 // files read before (except if fallback is TRUE), thus we
1711 // Insert() the new entry to the list if it has already
1712 // occured in _this_ file, but Prepend() it if it occured in
1713 // some of the previous ones and Append() to it in the
1717 // 'fallback' parameter prevents the entries from this
1718 // file from overriding the other ones - always append
1719 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1721 entry
->Append(entryOld
);
1723 m_aEntries
[nIndex
] = entry
;
1726 int entryIndex
= aEntryIndices
.Index(nIndex
);
1727 if ( entryIndex
== wxNOT_FOUND
) {
1728 // first time in this file
1729 aEntryIndices
.Add(nIndex
);
1730 aLastIndices
.Add(0);
1732 entry
->Prepend(m_aEntries
[nIndex
]);
1733 m_aEntries
[nIndex
] = entry
;
1736 // not the first time in _this_ file
1737 size_t nEntryIndex
= (size_t)entryIndex
;
1738 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1740 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
1742 m_aEntries
[nIndex
] = entry
;
1744 // the indices were shifted by 1
1745 aLastIndices
[nEntryIndex
]++;
1749 if ( !strDesc
.IsEmpty() ) {
1750 // replace the old one - what else can we do??
1751 m_aDescriptions
[nIndex
] = strDesc
;
1756 // check our data integriry
1757 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1758 m_aTypes
.Count() == m_aExtensions
.Count() &&
1759 m_aTypes
.Count() == m_aDescriptions
.Count() );
1765 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxFileType
**filetypes
)
1767 size_t count
= m_aTypes
.GetCount();
1769 *filetypes
= new wxFileType
[count
];
1770 for ( size_t n
= 0; n
< count
; n
++ )
1772 (*filetypes
)[n
].m_impl
->Init(this, n
);
1782 // wxUSE_FILE && wxUSE_TEXTFILE