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"
36 // Doesn't compile in WIN16 mode
42 #include "wx/dynarray.h"
43 #include "wx/confbase.h"
46 #include "wx/msw/registry.h"
48 #elif defined(__UNIX__) || defined(__WXPM__)
50 #include "wx/textfile.h"
53 #include "wx/tokenzr.h"
56 #include "wx/mimetype.h"
58 // other standard headers
61 // in case we're compiling in non-GUI mode
62 class WXDLLEXPORT wxIcon
;
64 // ----------------------------------------------------------------------------
66 // ----------------------------------------------------------------------------
68 // implementation classes, platform dependent
71 // These classes use Windows registry to retrieve the required information.
73 // Keys used (not all of them are documented, so it might actually stop working
74 // in futur versions of Windows...):
75 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
76 // types, each key has a string value "Extension" which gives (dot preceded)
77 // extension for the files of this MIME type.
79 // 2. "HKCR\.ext" contains
80 // a) unnamed value containing the "filetype"
81 // b) value "Content Type" containing the MIME type
83 // 3. "HKCR\filetype" contains
84 // a) unnamed value containing the description
85 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
87 // c) shell\open\command and shell\open\print subkeys containing the commands
88 // to open/print the file (the positional parameters are introduced by %1,
89 // %2, ... in these strings, we change them to %s ourselves)
91 // although I don't know of any official documentation which mentions this
92 // location, uses it, so it isn't likely to change
93 static const wxChar
*MIME_DATABASE_KEY
= wxT("MIME\\Database\\Content Type\\");
99 wxFileTypeImpl() { m_info
= NULL
; }
101 // one of these Init() function must be called (ctor can't take any
102 // arguments because it's common)
104 // initialize us with our file type name and extension - in this case
105 // we will read all other data from the registry
106 void Init(const wxString
& strFileType
, const wxString
& ext
)
107 { m_strFileType
= strFileType
; m_ext
= ext
; }
109 // initialize us with a wxFileTypeInfo object - it contains all the
111 void Init(const wxFileTypeInfo
& info
)
114 // implement accessor functions
115 bool GetExtensions(wxArrayString
& extensions
);
116 bool GetMimeType(wxString
*mimeType
) const;
117 bool GetIcon(wxIcon
*icon
) const;
118 bool GetDescription(wxString
*desc
) const;
119 bool GetOpenCommand(wxString
*openCmd
,
120 const wxFileType::MessageParameters
& params
) const;
121 bool GetPrintCommand(wxString
*printCmd
,
122 const wxFileType::MessageParameters
& params
) const;
125 // helper function: reads the command corresponding to the specified verb
126 // from the registry (returns an empty string if not found)
127 wxString
GetCommand(const wxChar
*verb
) const;
129 // we use either m_info or read the data from the registry if m_info == NULL
130 const wxFileTypeInfo
*m_info
;
131 wxString m_strFileType
, // may be empty
135 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
136 #include "wx/arrimpl.cpp"
137 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
139 class wxMimeTypesManagerImpl
142 // nothing to do here, we don't load any data but just go and fetch it from
143 // the registry when asked for
144 wxMimeTypesManagerImpl() { }
146 // implement containing class functions
147 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
148 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
150 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
152 // this are NOPs under Windows
153 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
)
155 bool ReadMimeTypes(const wxString
& filename
)
158 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
161 wxArrayFileTypeInfo m_fallbacks
;
164 #elif defined( __WXMAC__ )
166 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
167 #include "wx/arrimpl.cpp"
168 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
170 class wxMimeTypesManagerImpl
173 wxMimeTypesManagerImpl() { }
175 // implement containing class functions
176 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
177 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
179 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
181 // this are NOPs under MacOS
182 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
) { return TRUE
; }
183 bool ReadMimeTypes(const wxString
& filename
) { return TRUE
; }
185 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
188 wxArrayFileTypeInfo m_fallbacks
;
194 // initialize us with our file type name
195 void SetFileType(const wxString
& strFileType
)
196 { m_strFileType
= strFileType
; }
197 void SetExt(const wxString
& ext
)
200 // implement accessor functions
201 bool GetExtensions(wxArrayString
& extensions
);
202 bool GetMimeType(wxString
*mimeType
) const;
203 bool GetIcon(wxIcon
*icon
) const;
204 bool GetDescription(wxString
*desc
) const;
205 bool GetOpenCommand(wxString
*openCmd
,
206 const wxFileType::MessageParameters
&) const
207 { return GetCommand(openCmd
, "open"); }
208 bool GetPrintCommand(wxString
*printCmd
,
209 const wxFileType::MessageParameters
&) const
210 { return GetCommand(printCmd
, "print"); }
214 bool GetCommand(wxString
*command
, const char *verb
) const;
216 wxString m_strFileType
, m_ext
;
221 // this class uses both mailcap and mime.types to gather information about file
224 // The information about mailcap file was extracted from metamail(1) sources and
227 // Format of mailcap file: spaces are ignored, each line is either a comment
228 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
229 // A backslash can be used to quote semicolons and newlines (and, in fact,
230 // anything else including itself).
232 // The first field is always the MIME type in the form of type/subtype (see RFC
233 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
234 // "type" which means the same as "type/*", although I'm not sure whether this
237 // The second field is always the command to run. It is subject to
238 // parameter/filename expansion described below.
240 // All the following fields are optional and may not be present at all. If
241 // they're present they may appear in any order, although each of them should
242 // appear only once. The optional fields are the following:
243 // * notes=xxx is an uninterpreted string which is silently ignored
244 // * test=xxx is the command to be used to determine whether this mailcap line
245 // applies to our data or not. The RHS of this field goes through the
246 // parameter/filename expansion (as the 2nd field) and the resulting string
247 // is executed. The line applies only if the command succeeds, i.e. returns 0
249 // * print=xxx is the command to be used to print (and not view) the data of
250 // this type (parameter/filename expansion is done here too)
251 // * edit=xxx is the command to open/edit the data of this type
252 // * needsterminal means that a new console must be created for the viewer
253 // * copiousoutput means that the viewer doesn't interact with the user but
254 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
255 // good example), thus it might be a good idea to use some kind of paging
257 // * textualnewlines means not to perform CR/LF translation (not honored)
258 // * compose and composetyped fields are used to determine the program to be
259 // called to create a new message pert in the specified format (unused).
261 // Parameter/filename xpansion:
262 // * %s is replaced with the (full) file name
263 // * %t is replaced with MIME type/subtype of the entry
264 // * for multipart type only %n is replaced with the nnumber of parts and %F is
265 // replaced by an array of (content-type, temporary file name) pairs for all
266 // message parts (TODO)
267 // * %{parameter} is replaced with the value of parameter taken from
268 // Content-type header line of the message.
270 // FIXME any docs with real descriptions of these files??
272 // There are 2 possible formats for mime.types file, one entry per line (used
273 // for global mime.types) and "expanded" format where an entry takes multiple
274 // lines (used for users mime.types).
276 // For both formats spaces are ignored and lines starting with a '#' are
277 // comments. Each record has one of two following forms:
278 // a) for "brief" format:
279 // <mime type> <space separated list of extensions>
280 // b) for "expanded" format:
281 // type=<mime type> \ desc="<description>" \ exts="ext"
283 // We try to autodetect the format of mime.types: if a non-comment line starts
284 // with "type=" we assume the second format, otherwise the first one.
286 // there may be more than one entry for one and the same mime type, to
287 // choose the right one we have to run the command specified in the test
288 // field on our data.
293 MailCapEntry(const wxString
& openCmd
,
294 const wxString
& printCmd
,
295 const wxString
& testCmd
)
296 : m_openCmd(openCmd
), m_printCmd(printCmd
), m_testCmd(testCmd
)
302 const wxString
& GetOpenCmd() const { return m_openCmd
; }
303 const wxString
& GetPrintCmd() const { return m_printCmd
; }
304 const wxString
& GetTestCmd() const { return m_testCmd
; }
306 MailCapEntry
*GetNext() const { return m_next
; }
309 // prepend this element to the list
310 void Prepend(MailCapEntry
*next
) { m_next
= next
; }
311 // insert into the list at given position
312 void Insert(MailCapEntry
*next
, size_t pos
)
317 for ( cur
= next
; cur
!= NULL
; cur
= cur
->m_next
, n
++ ) {
322 wxASSERT_MSG( n
== pos
, wxT("invalid position in MailCapEntry::Insert") );
324 m_next
= cur
->m_next
;
327 // append this element to the list
328 void Append(MailCapEntry
*next
)
330 wxCHECK_RET( next
!= NULL
, wxT("Append()ing to what?") );
334 for ( cur
= next
; cur
->m_next
!= NULL
; cur
= cur
->m_next
)
339 wxASSERT_MSG( !m_next
, wxT("Append()ing element already in the list?") );
343 wxString m_openCmd
, // command to use to open/view the file
345 m_testCmd
; // only apply this entry if test yields
346 // true (i.e. the command returns 0)
348 MailCapEntry
*m_next
; // in the linked list
351 WX_DEFINE_ARRAY(MailCapEntry
*, ArrayTypeEntries
);
353 // the base class which may be used to find an icon for the MIME type
354 class wxMimeTypeIconHandler
357 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
) = 0;
359 // this function fills manager with MIME types information gathered
360 // (as side effect) when searching for icons. This may be particularly
361 // useful if mime.types is incomplete (e.g. RedHat distributions).
362 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
) = 0;
365 WX_DEFINE_ARRAY(wxMimeTypeIconHandler
*, ArrayIconHandlers
);
367 // the icon handler which uses GNOME MIME database
368 class wxGNOMEIconHandler
: public wxMimeTypeIconHandler
371 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
);
372 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
) {}
376 void LoadIconsFromKeyFile(const wxString
& filename
);
377 void LoadKeyFilesFromDir(const wxString
& dirbase
);
379 static bool m_inited
;
381 static wxSortedArrayString ms_mimetypes
;
382 static wxArrayString ms_icons
;
385 // the icon handler which uses KDE MIME database
386 class wxKDEIconHandler
: public wxMimeTypeIconHandler
389 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
);
390 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
);
393 void LoadLinksForMimeSubtype(const wxString
& dirbase
,
394 const wxString
& subdir
,
395 const wxString
& filename
,
396 const wxArrayString
& icondirs
);
397 void LoadLinksForMimeType(const wxString
& dirbase
,
398 const wxString
& subdir
,
399 const wxArrayString
& icondirs
);
400 void LoadLinkFilesFromDir(const wxString
& dirbase
,
401 const wxArrayString
& icondirs
);
404 static bool m_inited
;
406 static wxSortedArrayString ms_mimetypes
;
407 static wxArrayString ms_icons
;
409 static wxArrayString ms_infoTypes
;
410 static wxArrayString ms_infoDescriptions
;
411 static wxArrayString ms_infoExtensions
;
414 // this is the real wxMimeTypesManager for Unix
415 class wxMimeTypesManagerImpl
417 friend class wxFileTypeImpl
; // give it access to m_aXXX variables
420 // ctor loads all info into memory for quicker access later on
421 // TODO it would be nice to load them all, but parse on demand only...
422 wxMimeTypesManagerImpl();
424 // implement containing class functions
425 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
426 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
428 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
430 bool ReadMailcap(const wxString
& filename
, bool fallback
= FALSE
);
431 bool ReadMimeTypes(const wxString
& filename
);
433 void AddFallback(const wxFileTypeInfo
& filetype
);
435 // add information about the given mimetype
436 void AddMimeTypeInfo(const wxString
& mimetype
,
437 const wxString
& extensions
,
438 const wxString
& description
);
439 void AddMailcapInfo(const wxString
& strType
,
440 const wxString
& strOpenCmd
,
441 const wxString
& strPrintCmd
,
442 const wxString
& strTest
,
443 const wxString
& strDesc
);
446 // get the string containing space separated extensions for the given
448 wxString
GetExtension(size_t index
) { return m_aExtensions
[index
]; }
450 // get the array of icon handlers
451 static ArrayIconHandlers
& GetIconHandlers();
454 wxArrayString m_aTypes
, // MIME types
455 m_aDescriptions
, // descriptions (just some text)
456 m_aExtensions
; // space separated list of extensions
457 ArrayTypeEntries m_aEntries
; // commands and tests for this file type
459 // head of the linked list of the icon handlers
460 static ArrayIconHandlers ms_iconHandlers
;
466 // initialization functions
467 void Init(wxMimeTypesManagerImpl
*manager
, size_t index
)
468 { m_manager
= manager
; m_index
= index
; }
471 bool GetExtensions(wxArrayString
& extensions
);
472 bool GetMimeType(wxString
*mimeType
) const
473 { *mimeType
= m_manager
->m_aTypes
[m_index
]; return TRUE
; }
474 bool GetIcon(wxIcon
*icon
) const;
475 bool GetDescription(wxString
*desc
) const
476 { *desc
= m_manager
->m_aDescriptions
[m_index
]; return TRUE
; }
478 bool GetOpenCommand(wxString
*openCmd
,
479 const wxFileType::MessageParameters
& params
) const
481 return GetExpandedCommand(openCmd
, params
, TRUE
);
484 bool GetPrintCommand(wxString
*printCmd
,
485 const wxFileType::MessageParameters
& params
) const
487 return GetExpandedCommand(printCmd
, params
, FALSE
);
491 // get the entry which passes the test (may return NULL)
492 MailCapEntry
*GetEntry(const wxFileType::MessageParameters
& params
) const;
494 // choose the correct entry to use and expand the command
495 bool GetExpandedCommand(wxString
*expandedCmd
,
496 const wxFileType::MessageParameters
& params
,
499 wxMimeTypesManagerImpl
*m_manager
;
500 size_t m_index
; // in the wxMimeTypesManagerImpl arrays
505 // ============================================================================
507 // ============================================================================
509 // ----------------------------------------------------------------------------
511 // ----------------------------------------------------------------------------
513 wxFileTypeInfo::wxFileTypeInfo(const char *mimeType
,
515 const char *printCmd
,
518 : m_mimeType(mimeType
),
520 m_printCmd(printCmd
),
524 va_start(argptr
, desc
);
528 const char *ext
= va_arg(argptr
, const char *);
531 // NULL terminates the list
541 // ============================================================================
542 // implementation of the wrapper classes
543 // ============================================================================
545 // ----------------------------------------------------------------------------
547 // ----------------------------------------------------------------------------
549 wxString
wxFileType::ExpandCommand(const wxString
& command
,
550 const wxFileType::MessageParameters
& params
)
552 bool hasFilename
= FALSE
;
555 for ( const wxChar
*pc
= command
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
556 if ( *pc
== wxT('%') ) {
559 // '%s' expands into file name (quoted because it might
560 // contain spaces) - except if there are already quotes
561 // there because otherwise some programs may get confused
562 // by double double quotes
564 if ( *(pc
- 2) == wxT('"') )
565 str
<< params
.GetFileName();
567 str
<< wxT('"') << params
.GetFileName() << wxT('"');
569 str
<< params
.GetFileName();
574 // '%t' expands into MIME type (quote it too just to be
576 str
<< wxT('\'') << params
.GetMimeType() << wxT('\'');
581 const wxChar
*pEnd
= wxStrchr(pc
, wxT('}'));
582 if ( pEnd
== NULL
) {
584 wxLogWarning(_("Unmatched '{' in an entry for "
586 params
.GetMimeType().c_str());
590 wxString
param(pc
+ 1, pEnd
- pc
- 1);
591 str
<< wxT('\'') << params
.GetParamValue(param
) << wxT('\'');
599 // TODO %n is the number of parts, %F is an array containing
600 // the names of temp files these parts were written to
601 // and their mime types.
605 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
606 *pc
, command
.c_str());
615 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
616 // the program will accept the data on stdin: so give it to it!
617 if ( !hasFilename
&& !str
.IsEmpty() ) {
618 str
<< wxT(" < '") << params
.GetFileName() << wxT('\'');
624 wxFileType::wxFileType()
626 m_impl
= new wxFileTypeImpl
;
629 wxFileType::~wxFileType()
634 bool wxFileType::GetExtensions(wxArrayString
& extensions
)
636 return m_impl
->GetExtensions(extensions
);
639 bool wxFileType::GetMimeType(wxString
*mimeType
) const
641 return m_impl
->GetMimeType(mimeType
);
644 bool wxFileType::GetIcon(wxIcon
*icon
) const
646 return m_impl
->GetIcon(icon
);
649 bool wxFileType::GetDescription(wxString
*desc
) const
651 return m_impl
->GetDescription(desc
);
655 wxFileType::GetOpenCommand(wxString
*openCmd
,
656 const wxFileType::MessageParameters
& params
) const
658 return m_impl
->GetOpenCommand(openCmd
, params
);
662 wxFileType::GetPrintCommand(wxString
*printCmd
,
663 const wxFileType::MessageParameters
& params
) const
665 return m_impl
->GetPrintCommand(printCmd
, params
);
668 // ----------------------------------------------------------------------------
669 // wxMimeTypesManager
670 // ----------------------------------------------------------------------------
672 bool wxMimeTypesManager::IsOfType(const wxString
& mimeType
,
673 const wxString
& wildcard
)
675 wxASSERT_MSG( mimeType
.Find(wxT('*')) == wxNOT_FOUND
,
676 wxT("first MIME type can't contain wildcards") );
678 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
679 if ( wildcard
.BeforeFirst(wxT('/')).IsSameAs(mimeType
.BeforeFirst(wxT('/')), FALSE
) )
681 wxString strSubtype
= wildcard
.AfterFirst(wxT('/'));
683 if ( strSubtype
== wxT("*") ||
684 strSubtype
.IsSameAs(mimeType
.AfterFirst(wxT('/')), FALSE
) )
686 // matches (either exactly or it's a wildcard)
694 wxMimeTypesManager::wxMimeTypesManager()
696 m_impl
= new wxMimeTypesManagerImpl
;
699 wxMimeTypesManager::~wxMimeTypesManager()
705 wxMimeTypesManager::GetFileTypeFromExtension(const wxString
& ext
)
707 return m_impl
->GetFileTypeFromExtension(ext
);
711 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString
& mimeType
)
713 return m_impl
->GetFileTypeFromMimeType(mimeType
);
716 bool wxMimeTypesManager::ReadMailcap(const wxString
& filename
, bool fallback
)
718 return m_impl
->ReadMailcap(filename
, fallback
);
721 bool wxMimeTypesManager::ReadMimeTypes(const wxString
& filename
)
723 return m_impl
->ReadMimeTypes(filename
);
726 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo
*filetypes
)
728 for ( const wxFileTypeInfo
*ft
= filetypes
; ft
->IsValid(); ft
++ ) {
729 m_impl
->AddFallback(*ft
);
733 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString
& mimetypes
)
735 return m_impl
->EnumAllFileTypes(mimetypes
);
738 // ============================================================================
739 // real (OS specific) implementation
740 // ============================================================================
744 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
746 // suppress possible error messages
750 if ( wxRegKey(wxRegKey::HKCR
, m_ext
+ _T("\\shell")).Exists() )
752 if ( wxRegKey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell")).Exists() )
753 strKey
= m_strFileType
;
758 return wxEmptyString
;
761 strKey
<< wxT("\\shell\\") << verb
<< wxT("\\command");
762 wxRegKey
key(wxRegKey::HKCR
, strKey
);
765 // it's the default value of the key
766 if ( key
.QueryValue(wxT(""), command
) ) {
767 // transform it from '%1' to '%s' style format string
769 // NB: we don't make any attempt to verify that the string is valid,
770 // i.e. doesn't contain %2, or second %1 or .... But we do make
771 // sure that we return a string with _exactly_ one '%s'!
772 bool foundFilename
= FALSE
;
773 size_t len
= command
.Len();
774 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
775 if ( command
[n
] == wxT('%') &&
776 (n
+ 1 < len
) && command
[n
+ 1] == wxT('1') ) {
777 // replace it with '%s'
778 command
[n
+ 1] = wxT('s');
780 foundFilename
= TRUE
;
784 if ( !foundFilename
) {
785 // we didn't find any '%1'!
786 // HACK: append the filename at the end, hope that it will do
787 command
<< wxT(" %s");
791 //else: no such file type or no value, will return empty string
797 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
798 const wxFileType::MessageParameters
& params
)
803 cmd
= m_info
->GetOpenCommand();
806 cmd
= GetCommand(wxT("open"));
809 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
811 return !openCmd
->IsEmpty();
815 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
816 const wxFileType::MessageParameters
& params
)
821 cmd
= m_info
->GetPrintCommand();
824 cmd
= GetCommand(wxT("print"));
827 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
829 return !printCmd
->IsEmpty();
832 // TODO this function is half implemented
833 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
836 extensions
= m_info
->GetExtensions();
840 else if ( m_ext
.IsEmpty() ) {
841 // the only way to get the list of extensions from the file type is to
842 // scan through all extensions in the registry - too slow...
847 extensions
.Add(m_ext
);
849 // it's a lie too, we don't return _all_ extensions...
854 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
857 // we already have it
858 *mimeType
= m_info
->GetMimeType();
863 // suppress possible error messages
865 wxRegKey
key(wxRegKey::HKCR
, wxT(".") + m_ext
);
866 if ( key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
) ) {
874 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
878 // we don't have icons in the fallback resources
883 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
885 // suppress possible error messages
887 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
891 // it's the default value of the key
892 if ( key
.QueryValue(wxT(""), strIcon
) ) {
893 // the format is the following: <full path to file>, <icon index>
894 // NB: icon index may be negative as well as positive and the full
895 // path may contain the environment variables inside '%'
896 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
897 strIndex
= strIcon
.AfterLast(wxT(','));
899 // index may be omitted, in which case BeforeLast(',') is empty and
900 // AfterLast(',') is the whole string
901 if ( strFullPath
.IsEmpty() ) {
902 strFullPath
= strIndex
;
906 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
907 int nIndex
= wxAtoi(strIndex
);
909 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
910 switch ( (int)hIcon
) {
911 case 0: // means no icons were found
912 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
913 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
914 key
.GetName().c_str());
918 icon
->SetHICON((WXHICON
)hIcon
);
924 // no such file type or no value or incorrect icon entry
930 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
933 // we already have it
934 *desc
= m_info
->GetDescription();
939 // suppress possible error messages
941 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
944 // it's the default value of the key
945 if ( key
.QueryValue(wxT(""), *desc
) ) {
953 // extension -> file type
955 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
957 // add the leading point if necessary
959 if ( ext
[0u] != wxT('.') ) {
964 // suppress possible error messages
967 bool knownExtension
= FALSE
;
969 wxString strFileType
;
970 wxRegKey
key(wxRegKey::HKCR
, str
);
972 // it's the default value of the key
973 if ( key
.QueryValue(wxT(""), strFileType
) ) {
974 // create the new wxFileType object
975 wxFileType
*fileType
= new wxFileType
;
976 fileType
->m_impl
->Init(strFileType
, ext
);
981 // this extension doesn't have a filetype, but it's known to the
982 // system and may be has some other useful keys (open command or
983 // content-type), so still return a file type object for it
984 knownExtension
= TRUE
;
988 // check the fallbacks
989 // TODO linear search is potentially slow, perhaps we should use a sorted
991 size_t count
= m_fallbacks
.GetCount();
992 for ( size_t n
= 0; n
< count
; n
++ ) {
993 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
994 wxFileType
*fileType
= new wxFileType
;
995 fileType
->m_impl
->Init(m_fallbacks
[n
]);
1001 if ( knownExtension
)
1003 wxFileType
*fileType
= new wxFileType
;
1004 fileType
->m_impl
->Init(wxEmptyString
, ext
);
1010 // unknown extension
1015 // MIME type -> extension -> file type
1017 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1019 wxString strKey
= MIME_DATABASE_KEY
;
1022 // suppress possible error messages
1026 wxRegKey
key(wxRegKey::HKCR
, strKey
);
1028 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
1029 return GetFileTypeFromExtension(ext
);
1033 // check the fallbacks
1034 // TODO linear search is potentially slow, perhaps we should use a sorted
1036 size_t count
= m_fallbacks
.GetCount();
1037 for ( size_t n
= 0; n
< count
; n
++ ) {
1038 if ( wxMimeTypesManager::IsOfType(mimeType
,
1039 m_fallbacks
[n
].GetMimeType()) ) {
1040 wxFileType
*fileType
= new wxFileType
;
1041 fileType
->m_impl
->Init(m_fallbacks
[n
]);
1047 // unknown MIME type
1051 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1053 // enumerate all keys under MIME_DATABASE_KEY
1054 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
1058 bool cont
= key
.GetFirstKey(type
, cookie
);
1061 mimetypes
.Add(type
);
1063 cont
= key
.GetNextKey(type
, cookie
);
1066 return mimetypes
.GetCount();
1069 #elif defined ( __WXMAC__ )
1071 bool wxFileTypeImpl::GetCommand(wxString
*command
, const char *verb
) const
1076 // @@ this function is half implemented
1077 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1082 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
1084 if ( m_strFileType
.Length() > 0 )
1086 *mimeType
= m_strFileType
;
1093 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
1095 // no such file type or no value or incorrect icon entry
1099 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
1104 // extension -> file type
1106 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& e
)
1112 wxFileType
*fileType
= new wxFileType
;
1113 fileType
->m_impl
->SetFileType("text/text");
1114 fileType
->m_impl
->SetExt(ext
);
1117 else if ( ext
== "htm" || ext
== "html" )
1119 wxFileType
*fileType
= new wxFileType
;
1120 fileType
->m_impl
->SetFileType("text/html");
1121 fileType
->m_impl
->SetExt(ext
);
1124 else if ( ext
== "gif" )
1126 wxFileType
*fileType
= new wxFileType
;
1127 fileType
->m_impl
->SetFileType("image/gif");
1128 fileType
->m_impl
->SetExt(ext
);
1131 else if ( ext
== "png" )
1133 wxFileType
*fileType
= new wxFileType
;
1134 fileType
->m_impl
->SetFileType("image/png");
1135 fileType
->m_impl
->SetExt(ext
);
1138 else if ( ext
== "jpg" || ext
== "jpeg" )
1140 wxFileType
*fileType
= new wxFileType
;
1141 fileType
->m_impl
->SetFileType("image/jpeg");
1142 fileType
->m_impl
->SetExt(ext
);
1145 else if ( ext
== "bmp" )
1147 wxFileType
*fileType
= new wxFileType
;
1148 fileType
->m_impl
->SetFileType("image/bmp");
1149 fileType
->m_impl
->SetExt(ext
);
1152 else if ( ext
== "tif" || ext
== "tiff" )
1154 wxFileType
*fileType
= new wxFileType
;
1155 fileType
->m_impl
->SetFileType("image/tiff");
1156 fileType
->m_impl
->SetExt(ext
);
1159 else if ( ext
== "xpm" )
1161 wxFileType
*fileType
= new wxFileType
;
1162 fileType
->m_impl
->SetFileType("image/xpm");
1163 fileType
->m_impl
->SetExt(ext
);
1166 else if ( ext
== "xbm" )
1168 wxFileType
*fileType
= new wxFileType
;
1169 fileType
->m_impl
->SetFileType("image/xbm");
1170 fileType
->m_impl
->SetExt(ext
);
1174 // unknown extension
1178 // MIME type -> extension -> file type
1180 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1185 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1187 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1194 // ============================================================================
1195 // Unix implementation
1196 // ============================================================================
1198 // ----------------------------------------------------------------------------
1200 // ----------------------------------------------------------------------------
1202 static wxGNOMEIconHandler gs_iconHandlerGNOME
;
1203 static wxKDEIconHandler gs_iconHandlerKDE
;
1205 bool wxGNOMEIconHandler::m_inited
= FALSE
;
1206 wxSortedArrayString
wxGNOMEIconHandler::ms_mimetypes
;
1207 wxArrayString
wxGNOMEIconHandler::ms_icons
;
1209 bool wxKDEIconHandler::m_inited
= FALSE
;
1210 wxSortedArrayString
wxKDEIconHandler::ms_mimetypes
;
1211 wxArrayString
wxKDEIconHandler::ms_icons
;
1213 wxArrayString
wxKDEIconHandler::ms_infoTypes
;
1214 wxArrayString
wxKDEIconHandler::ms_infoDescriptions
;
1215 wxArrayString
wxKDEIconHandler::ms_infoExtensions
;
1218 ArrayIconHandlers
wxMimeTypesManagerImpl::ms_iconHandlers
;
1220 // ----------------------------------------------------------------------------
1221 // wxGNOMEIconHandler
1222 // ----------------------------------------------------------------------------
1224 // GNOME stores the info we're interested in in several locations:
1225 // 1. xxx.keys files under /usr/share/mime-info
1226 // 2. xxx.keys files under ~/.gnome/mime-info
1228 // The format of xxx.keys file is the following:
1230 // mimetype/subtype:
1233 // with blank lines separating the entries and indented lines starting with
1234 // TABs. We're interested in the field icon-filename whose value is the path
1235 // containing the icon.
1237 void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString
& filename
)
1239 wxTextFile
textfile(filename
);
1240 if ( !textfile
.Open() )
1243 // values for the entry being parsed
1244 wxString curMimeType
, curIconFile
;
1247 size_t nLineCount
= textfile
.GetLineCount();
1248 for ( size_t nLine
= 0; ; nLine
++ )
1250 if ( nLine
< nLineCount
)
1252 pc
= textfile
[nLine
].c_str();
1253 if ( *pc
== _T('#') )
1261 // so that we will fall into the "if" below
1268 if ( !!curMimeType
&& !!curIconFile
)
1270 // do we already know this mimetype?
1271 int i
= ms_mimetypes
.Index(curMimeType
);
1272 if ( i
== wxNOT_FOUND
)
1275 size_t n
= ms_mimetypes
.Add(curMimeType
);
1276 ms_icons
.Insert(curIconFile
, n
);
1280 // replace the existing one (this means that the directories
1281 // should be searched in order of increased priority!)
1282 ms_icons
[(size_t)i
] = curIconFile
;
1288 // the end - this can only happen if nLine == nLineCount
1292 curIconFile
.Empty();
1297 // what do we have here?
1298 if ( *pc
== _T('\t') )
1300 // this is a field=value ling
1301 pc
++; // skip leading TAB
1303 static const int lenField
= 13; // strlen("icon-filename")
1304 if ( wxStrncmp(pc
, _T("icon-filename"), lenField
) == 0 )
1306 // skip '=' which follows and take everything left until the end
1308 curIconFile
= pc
+ lenField
+ 1;
1310 //else: some other field, we don't care
1314 // this is the start of the new section
1315 curMimeType
.Empty();
1317 while ( *pc
!= _T(':') && *pc
!= _T('\0') )
1319 curMimeType
+= *pc
++;
1324 // we reached the end of line without finding the colon,
1325 // something is wrong - ignore this line completely
1326 wxLogDebug(_T("Unreckognized line %d in file '%s' ignored"),
1327 nLine
+ 1, filename
.c_str());
1335 void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString
& dirbase
)
1337 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1338 _T("base directory shouldn't end with a slash") );
1340 wxString dirname
= dirbase
;
1341 dirname
<< _T("/mime-info");
1343 if ( !wxDir::Exists(dirname
) )
1347 if ( !dir
.IsOpened() )
1350 // we will concatenate it with filename to get the full path below
1354 bool cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
1357 LoadIconsFromKeyFile(dirname
+ filename
);
1359 cont
= dir
.GetNext(&filename
);
1363 void wxGNOMEIconHandler::Init()
1366 dirs
.Add(_T("/usr/share"));
1369 wxGetHomeDir( &gnomedir
);
1370 gnomedir
+= _T("/.gnome");
1371 dirs
.Add( gnomedir
);
1373 size_t nDirs
= dirs
.GetCount();
1374 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1376 LoadKeyFilesFromDir(dirs
[nDir
]);
1382 bool wxGNOMEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
1389 int index
= ms_mimetypes
.Index(mimetype
);
1390 if ( index
== wxNOT_FOUND
)
1393 wxString iconname
= ms_icons
[(size_t)index
];
1396 *icon
= wxIcon(iconname
);
1398 // helpful for testing in console mode
1399 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
1400 mimetype
.c_str(), iconname
.c_str());
1406 // ----------------------------------------------------------------------------
1408 // ----------------------------------------------------------------------------
1410 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
1411 // may be found in either of the following locations
1413 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
1414 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
1416 // The format of a .kdelnk file is almost the same as the one used by
1417 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
1418 // value for the entry "Type"
1420 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString
& dirbase
,
1421 const wxString
& subdir
,
1422 const wxString
& filename
,
1423 const wxArrayString
& icondirs
)
1425 wxFFile
file(dirbase
+ filename
);
1426 if ( !file
.IsOpened() )
1429 // construct mimetype from the directory name and the basename of the
1430 // file (it always has .kdelnk extension)
1432 mimetype
<< subdir
<< _T('/') << filename
.BeforeLast(_T('.'));
1434 // these files are small, slurp the entire file at once
1436 if ( !file
.ReadAll(&text
) )
1442 // before trying to find an icon, grab mimetype information
1443 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
1444 // have edited it in control panel...)
1446 wxString mime_extension
, mime_desc
;
1449 if (wxGetLocale() != NULL
)
1450 mime_desc
= _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
1451 if (pos
== wxNOT_FOUND
) mime_desc
= _T("Comment=");
1452 pos
= text
.Find(mime_desc
);
1453 if (pos
== wxNOT_FOUND
) mime_desc
= wxEmptyString
;
1456 pc
= text
.c_str() + pos
+ mime_desc
.Length();
1457 mime_desc
= wxEmptyString
;
1458 while ( *pc
&& *pc
!= _T('\n') ) mime_desc
+= *pc
++;
1461 pos
= text
.Find(_T("Patterns="));
1462 if (pos
!= wxNOT_FOUND
)
1465 pc
= text
.c_str() + pos
+ 9;
1466 while ( *pc
&& *pc
!= _T('\n') ) exts
+= *pc
++;
1467 wxStringTokenizer
tokenizer(exts
, _T(";"));
1470 while (tokenizer
.HasMoreTokens())
1472 e
= tokenizer
.GetNextToken();
1473 if (e
.Left(2) != _T("*.")) continue; // don't support too difficult patterns
1474 mime_extension
<< e
.Mid(2);
1475 mime_extension
<< _T(' ');
1477 mime_extension
.RemoveLast();
1480 ms_infoTypes
.Add(mimetype
);
1481 ms_infoDescriptions
.Add(mime_desc
);
1482 ms_infoExtensions
.Add(mime_extension
);
1484 // ok, now we can take care of icon:
1486 pos
= text
.Find(_T("Icon="));
1487 if ( pos
== wxNOT_FOUND
)
1495 pc
= text
.c_str() + pos
+ 5; // 5 == strlen("Icon=")
1496 while ( *pc
&& *pc
!= _T('\n') )
1503 // we must check if the file exists because it may be stored
1504 // in many locations, at least ~/.kde and $KDEDIR
1505 size_t nDir
, nDirs
= icondirs
.GetCount();
1506 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
1507 if (wxFileExists(icondirs
[nDir
] + icon
))
1509 icon
.Prepend(icondirs
[nDir
]);
1512 if (nDir
== nDirs
) return; //does not exist
1514 // do we already have this MIME type?
1515 int i
= ms_mimetypes
.Index(mimetype
);
1516 if ( i
== wxNOT_FOUND
)
1519 size_t n
= ms_mimetypes
.Add(mimetype
);
1520 ms_icons
.Insert(icon
, n
);
1524 // replace the old value
1525 ms_icons
[(size_t)i
] = icon
;
1530 void wxKDEIconHandler::LoadLinksForMimeType(const wxString
& dirbase
,
1531 const wxString
& subdir
,
1532 const wxArrayString
& icondirs
)
1534 wxString dirname
= dirbase
;
1537 if ( !dir
.IsOpened() )
1543 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
1546 LoadLinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1548 cont
= dir
.GetNext(&filename
);
1552 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString
& dirbase
,
1553 const wxArrayString
& icondirs
)
1555 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1556 _T("base directory shouldn't end with a slash") );
1558 wxString dirname
= dirbase
;
1559 dirname
<< _T("/mimelnk");
1561 if ( !wxDir::Exists(dirname
) )
1565 if ( !dir
.IsOpened() )
1568 // we will concatenate it with dir name to get the full path below
1572 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
1575 LoadLinksForMimeType(dirname
, subdir
, icondirs
);
1577 cont
= dir
.GetNext(&subdir
);
1581 void wxKDEIconHandler::Init()
1584 wxArrayString icondirs
;
1586 // settings in ~/.kde have maximal priority
1587 dirs
.Add(wxGetHomeDir() + _T("/.kde/share"));
1588 icondirs
.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
1590 // the variable KDEDIR is set when KDE is running
1591 const char *kdedir
= getenv("KDEDIR");
1594 dirs
.Add(wxString(kdedir
) + _T("/share"));
1595 icondirs
.Add(wxString(kdedir
) + _T("/share/icons/"));
1599 // try to guess KDEDIR
1600 dirs
.Add(_T("/usr/share"));
1601 dirs
.Add(_T("/opt/kde/share"));
1602 icondirs
.Add(_T("/usr/share/icons/"));
1603 icondirs
.Add(_T("/opt/kde/share/icons/"));
1606 size_t nDirs
= dirs
.GetCount();
1607 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1609 LoadLinkFilesFromDir(dirs
[nDir
], icondirs
);
1615 bool wxKDEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
1622 int index
= ms_mimetypes
.Index(mimetype
);
1623 if ( index
== wxNOT_FOUND
)
1626 wxString iconname
= ms_icons
[(size_t)index
];
1629 *icon
= wxIcon(iconname
);
1631 // helpful for testing in console mode
1632 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
1633 mimetype
.c_str(), iconname
.c_str());
1640 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
)
1642 if ( !m_inited
) Init();
1644 size_t cnt
= ms_infoTypes
.GetCount();
1645 for (unsigned i
= 0; i
< cnt
; i
++)
1646 manager
-> AddMimeTypeInfo(ms_infoTypes
[i
], ms_infoExtensions
[i
], ms_infoDescriptions
[i
]);
1650 // ----------------------------------------------------------------------------
1651 // wxFileTypeImpl (Unix)
1652 // ----------------------------------------------------------------------------
1655 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
1658 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
1659 while ( entry
!= NULL
) {
1660 // notice that an empty command would always succeed (it's ok)
1661 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
1663 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
1665 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1666 command
.c_str(), params
.GetMimeType().c_str());
1670 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1671 command
.c_str(), params
.GetMimeType().c_str());
1674 entry
= entry
->GetNext();
1680 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
1683 (void)GetMimeType(&mimetype
);
1685 ArrayIconHandlers
& handlers
= m_manager
->GetIconHandlers();
1686 size_t count
= handlers
.GetCount();
1687 for ( size_t n
= 0; n
< count
; n
++ )
1689 if ( handlers
[n
]->GetIcon(mimetype
, icon
) )
1697 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
1698 const wxFileType::MessageParameters
& params
,
1701 MailCapEntry
*entry
= GetEntry(params
);
1702 if ( entry
== NULL
) {
1703 // all tests failed...
1707 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
1708 if ( cmd
.IsEmpty() ) {
1709 // may happen, especially for "print"
1713 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
1717 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1719 wxString strExtensions
= m_manager
->GetExtension(m_index
);
1722 // one extension in the space or comma delimitid list
1724 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
1725 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1726 if ( !strExt
.IsEmpty() ) {
1727 extensions
.Add(strExt
);
1730 //else: repeated spaces (shouldn't happen, but it's not that
1731 // important if it does happen)
1733 if ( *p
== wxT('\0') )
1736 else if ( *p
== wxT('.') ) {
1737 // remove the dot from extension (but only if it's the first char)
1738 if ( !strExt
.IsEmpty() ) {
1741 //else: no, don't append it
1751 // ----------------------------------------------------------------------------
1752 // wxMimeTypesManagerImpl (Unix)
1753 // ----------------------------------------------------------------------------
1756 ArrayIconHandlers
& wxMimeTypesManagerImpl::GetIconHandlers()
1758 if ( ms_iconHandlers
.GetCount() == 0 )
1760 ms_iconHandlers
.Add(&gs_iconHandlerGNOME
);
1761 ms_iconHandlers
.Add(&gs_iconHandlerKDE
);
1764 return ms_iconHandlers
;
1767 // read system and user mailcaps (TODO implement mime.types support)
1768 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1770 // directories where we look for mailcap and mime.types by default
1771 // (taken from metamail(1) sources)
1772 static const wxChar
*aStandardLocations
[] =
1776 wxT("/usr/local/etc"),
1778 wxT("/usr/public/lib")
1781 // first read the system wide file(s)
1782 for ( size_t n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
1783 wxString dir
= aStandardLocations
[n
];
1785 wxString file
= dir
+ wxT("/mailcap");
1786 if ( wxFile::Exists(file
) ) {
1790 file
= dir
+ wxT("/mime.types");
1791 if ( wxFile::Exists(file
) ) {
1792 ReadMimeTypes(file
);
1796 wxString strHome
= wxGetenv(wxT("HOME"));
1798 // and now the users mailcap
1799 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1800 if ( wxFile::Exists(strUserMailcap
) ) {
1801 ReadMailcap(strUserMailcap
);
1804 // read the users mime.types
1805 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
1806 if ( wxFile::Exists(strUserMimeTypes
) ) {
1807 ReadMimeTypes(strUserMimeTypes
);
1810 // read KDE/GNOME tables
1811 ArrayIconHandlers
& handlers
= GetIconHandlers();
1812 size_t count
= handlers
.GetCount();
1813 for ( size_t n
= 0; n
< count
; n
++ )
1814 handlers
[n
]->GetMimeInfoRecords(this);
1818 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1820 size_t count
= m_aExtensions
.GetCount();
1821 for ( size_t n
= 0; n
< count
; n
++ ) {
1822 wxString extensions
= m_aExtensions
[n
];
1823 while ( !extensions
.IsEmpty() ) {
1824 wxString field
= extensions
.BeforeFirst(wxT(' '));
1825 extensions
= extensions
.AfterFirst(wxT(' '));
1827 // consider extensions as not being case-sensitive
1828 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
1830 wxFileType
*fileType
= new wxFileType
;
1831 fileType
->m_impl
->Init(this, n
);
1843 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1845 // mime types are not case-sensitive
1846 wxString
mimetype(mimeType
);
1847 mimetype
.MakeLower();
1849 // first look for an exact match
1850 int index
= m_aTypes
.Index(mimetype
);
1851 if ( index
== wxNOT_FOUND
) {
1852 // then try to find "text/*" as match for "text/plain" (for example)
1853 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1854 // the whole string - ok.
1855 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1857 size_t nCount
= m_aTypes
.Count();
1858 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1859 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1860 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1867 if ( index
!= wxNOT_FOUND
) {
1868 wxFileType
*fileType
= new wxFileType
;
1869 fileType
->m_impl
->Init(this, index
);
1879 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1881 wxString extensions
;
1882 const wxArrayString
& exts
= filetype
.GetExtensions();
1883 size_t nExts
= exts
.GetCount();
1884 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1886 extensions
+= wxT(' ');
1888 extensions
+= exts
[nExt
];
1891 AddMimeTypeInfo(filetype
.GetMimeType(),
1893 filetype
.GetDescription());
1895 AddMailcapInfo(filetype
.GetMimeType(),
1896 filetype
.GetOpenCommand(),
1897 filetype
.GetPrintCommand(),
1899 filetype
.GetDescription());
1902 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
1903 const wxString
& strExtensions
,
1904 const wxString
& strDesc
)
1906 int index
= m_aTypes
.Index(strMimeType
);
1907 if ( index
== wxNOT_FOUND
) {
1909 m_aTypes
.Add(strMimeType
);
1910 m_aEntries
.Add(NULL
);
1911 m_aExtensions
.Add(strExtensions
);
1912 m_aDescriptions
.Add(strDesc
);
1915 // modify an existing one
1916 if ( !strDesc
.IsEmpty() ) {
1917 m_aDescriptions
[index
] = strDesc
; // replace old value
1919 m_aExtensions
[index
] += ' ' + strExtensions
;
1923 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
1924 const wxString
& strOpenCmd
,
1925 const wxString
& strPrintCmd
,
1926 const wxString
& strTest
,
1927 const wxString
& strDesc
)
1929 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1931 int nIndex
= m_aTypes
.Index(strType
);
1932 if ( nIndex
== wxNOT_FOUND
) {
1934 m_aTypes
.Add(strType
);
1936 m_aEntries
.Add(entry
);
1937 m_aExtensions
.Add(wxT(""));
1938 m_aDescriptions
.Add(strDesc
);
1941 // always append the entry in the tail of the list - info added with
1942 // this function can only come from AddFallbacks()
1943 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1945 entry
->Append(entryOld
);
1947 m_aEntries
[nIndex
] = entry
;
1951 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1953 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1955 wxTextFile
file(strFileName
);
1959 // the information we extract
1960 wxString strMimeType
, strDesc
, strExtensions
;
1962 size_t nLineCount
= file
.GetLineCount();
1963 const wxChar
*pc
= NULL
;
1964 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1966 // now we're at the start of the line
1967 pc
= file
[nLine
].c_str();
1970 // we didn't finish with the previous line yet
1975 while ( wxIsspace(*pc
) )
1978 // comment or blank line?
1979 if ( *pc
== wxT('#') || !*pc
) {
1980 // skip the whole line
1985 // detect file format
1986 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1987 if ( pEqualSign
== NULL
) {
1991 // first field is mime type
1992 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1997 while ( wxIsspace(*pc
) )
2000 // take all the rest of the string
2003 // no description...
2010 // the string on the left of '=' is the field name
2011 wxString
strLHS(pc
, pEqualSign
- pc
);
2014 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2018 if ( *pc
== wxT('"') ) {
2019 // the string is quoted and ends at the matching quote
2020 pEnd
= wxStrchr(++pc
, wxT('"'));
2021 if ( pEnd
== NULL
) {
2022 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2024 strFileName
.c_str(), nLine
+ 1);
2028 // unquoted string ends at the first space
2029 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
2033 // now we have the RHS (field value)
2034 wxString
strRHS(pc
, pEnd
- pc
);
2036 // check what follows this entry
2037 if ( *pEnd
== wxT('"') ) {
2042 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2045 // if there is something left, it may be either a '\\' to continue
2046 // the line or the next field of the same entry
2047 bool entryEnded
= *pc
== wxT('\0'),
2048 nextFieldOnSameLine
= FALSE
;
2049 if ( !entryEnded
) {
2050 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2053 // now see what we got
2054 if ( strLHS
== wxT("type") ) {
2055 strMimeType
= strRHS
;
2057 else if ( strLHS
== wxT("desc") ) {
2060 else if ( strLHS
== wxT("exts") ) {
2061 strExtensions
= strRHS
;
2064 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2065 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
2068 if ( !entryEnded
) {
2069 if ( !nextFieldOnSameLine
)
2071 //else: don't reset it
2073 // as we don't reset strMimeType, the next field in this entry
2074 // will be interpreted correctly.
2080 // although it doesn't seem to be covered by RFCs, some programs
2081 // (notably Netscape) create their entries with several comma
2082 // separated extensions (RFC mention the spaces only)
2083 strExtensions
.Replace(wxT(","), wxT(" "));
2085 // also deal with the leading dot
2086 if ( !strExtensions
.IsEmpty() && strExtensions
[0u] == wxT('.') )
2088 strExtensions
.erase(0, 1);
2091 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2093 // finished with this line
2097 // check our data integriry
2098 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2099 m_aTypes
.Count() == m_aExtensions
.Count() &&
2100 m_aTypes
.Count() == m_aDescriptions
.Count() );
2105 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2108 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
2110 wxTextFile
file(strFileName
);
2114 // see the comments near the end of function for the reason we need these
2115 // variables (search for the next occurence of them)
2116 // indices of MIME types (in m_aTypes) we already found in this file
2117 wxArrayInt aEntryIndices
;
2118 // aLastIndices[n] is the index of last element in
2119 // m_aEntries[aEntryIndices[n]] from this file
2120 wxArrayInt aLastIndices
;
2122 size_t nLineCount
= file
.GetLineCount();
2123 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
2124 // now we're at the start of the line
2125 const wxChar
*pc
= file
[nLine
].c_str();
2128 while ( wxIsspace(*pc
) )
2131 // comment or empty string?
2132 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2137 // what field are we currently in? The first 2 are fixed and there may
2138 // be an arbitrary number of other fields -- currently, we are not
2139 // interested in any of them, but we should parse them as well...
2145 } currentToken
= Field_Type
;
2147 // the flags and field values on the current line
2148 bool needsterminal
= FALSE
,
2149 copiousoutput
= FALSE
;
2155 curField
; // accumulator
2156 for ( bool cont
= TRUE
; cont
; pc
++ ) {
2159 // interpret the next character literally (notice that
2160 // backslash can be used for line continuation)
2161 if ( *++pc
== wxT('\0') ) {
2162 // fetch the next line.
2164 // pc currently points to nowhere, but after the next
2165 // pc++ in the for line it will point to the beginning
2166 // of the next line in the file
2167 pc
= file
[++nLine
].c_str() - 1;
2170 // just a normal character
2176 cont
= FALSE
; // end of line reached, exit the loop
2181 // store this field and start looking for the next one
2183 // trim whitespaces from both sides
2184 curField
.Trim(TRUE
).Trim(FALSE
);
2186 switch ( currentToken
) {
2189 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
2190 // we interpret "type" as "type/*"
2191 strType
+= wxT("/*");
2194 currentToken
= Field_OpenCmd
;
2198 strOpenCmd
= curField
;
2200 currentToken
= Field_Other
;
2205 // "good" mailcap entry?
2208 // is this something of the form foo=bar?
2209 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2210 if ( pEq
!= NULL
) {
2211 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2212 rhs
= curField
.AfterFirst(wxT('='));
2214 lhs
.Trim(TRUE
); // from right
2215 rhs
.Trim(FALSE
); // from left
2217 if ( lhs
== wxT("print") )
2219 else if ( lhs
== wxT("test") )
2221 else if ( lhs
== wxT("description") ) {
2222 // it might be quoted
2223 if ( rhs
[0u] == wxT('"') &&
2224 rhs
.Last() == wxT('"') ) {
2225 strDesc
= wxString(rhs
.c_str() + 1,
2232 else if ( lhs
== wxT("compose") ||
2233 lhs
== wxT("composetyped") ||
2234 lhs
== wxT("notes") ||
2235 lhs
== wxT("edit") )
2242 // no, it's a simple flag
2243 // TODO support the flags:
2244 // 1. create an xterm for 'needsterminal'
2245 // 2. append "| $PAGER" for 'copiousoutput'
2246 if ( curField
== wxT("needsterminal") )
2247 needsterminal
= TRUE
;
2248 else if ( curField
== wxT("copiousoutput") )
2249 copiousoutput
= TRUE
;
2250 else if ( curField
== wxT("textualnewlines") )
2258 // we don't understand this field, but
2259 // Netscape stores info in it, so don't warn
2261 if ( curField
.Left(16u) != "x-mozilla-flags=" )
2263 // don't flood the user with error
2264 // messages if we don't understand
2265 // something in his mailcap, but give
2266 // them in debug mode because this might
2267 // be useful for the programmer
2270 wxT("Mailcap file %s, line %d: "
2271 "unknown field '%s' for the "
2272 "MIME type '%s' ignored."),
2273 strFileName
.c_str(),
2282 // it already has this value
2283 //currentToken = Field_Other;
2287 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2290 // next token starts immediately after ';'
2299 // check that we really read something reasonable
2300 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
2301 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2303 strFileName
.c_str(), nLine
+ 1);
2306 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
2310 // NB: because of complications below (we must get entries priority
2311 // right), we can't use AddMailcapInfo() here, unfortunately.
2312 strType
.MakeLower();
2313 int nIndex
= m_aTypes
.Index(strType
);
2314 if ( nIndex
== wxNOT_FOUND
) {
2316 m_aTypes
.Add(strType
);
2318 m_aEntries
.Add(entry
);
2319 m_aExtensions
.Add(wxT(""));
2320 m_aDescriptions
.Add(strDesc
);
2323 // modify the existing entry: the entries in one and the same
2324 // file are read in top-to-bottom order, i.e. the entries read
2325 // first should be tried before the entries below. However,
2326 // the files read later should override the settings in the
2327 // files read before (except if fallback is TRUE), thus we
2328 // Insert() the new entry to the list if it has already
2329 // occured in _this_ file, but Prepend() it if it occured in
2330 // some of the previous ones and Append() to it in the
2334 // 'fallback' parameter prevents the entries from this
2335 // file from overriding the other ones - always append
2336 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
2338 entry
->Append(entryOld
);
2340 m_aEntries
[nIndex
] = entry
;
2343 int entryIndex
= aEntryIndices
.Index(nIndex
);
2344 if ( entryIndex
== wxNOT_FOUND
) {
2345 // first time in this file
2346 aEntryIndices
.Add(nIndex
);
2347 aLastIndices
.Add(0);
2349 entry
->Prepend(m_aEntries
[nIndex
]);
2350 m_aEntries
[nIndex
] = entry
;
2353 // not the first time in _this_ file
2354 size_t nEntryIndex
= (size_t)entryIndex
;
2355 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
2357 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
2359 m_aEntries
[nIndex
] = entry
;
2361 // the indices were shifted by 1
2362 aLastIndices
[nEntryIndex
]++;
2366 if ( !strDesc
.IsEmpty() ) {
2367 // replace the old one - what else can we do??
2368 m_aDescriptions
[nIndex
] = strDesc
;
2373 // check our data integriry
2374 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2375 m_aTypes
.Count() == m_aExtensions
.Count() &&
2376 m_aTypes
.Count() == m_aDescriptions
.Count() );
2382 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2387 size_t count
= m_aTypes
.GetCount();
2388 for ( size_t n
= 0; n
< count
; n
++ )
2390 // don't return template types from here (i.e. anything containg '*')
2392 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
2394 mimetypes
.Add(type
);
2398 return mimetypes
.GetCount();
2405 // wxUSE_FILE && wxUSE_TEXTFILE