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
;
762 wxRegKey
key(wxRegKey::HKCR
, strKey
+ _T("\\command"));
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 (now also
768 // test for %L - apparently MS started using it as well for the
771 // NB: we don't make any attempt to verify that the string is valid,
772 // i.e. doesn't contain %2, or second %1 or .... But we do make
773 // sure that we return a string with _exactly_ one '%s'!
774 bool foundFilename
= FALSE
;
775 size_t len
= command
.Len();
776 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
777 if ( command
[n
] == wxT('%') &&
779 (command
[n
+ 1] == wxT('1') ||
780 command
[n
+ 1] == wxT('L')) ) {
781 // replace it with '%s'
782 command
[n
+ 1] = wxT('s');
784 foundFilename
= TRUE
;
788 // look whether we must issue some DDE requests to the application
789 // (and not just launch it)
790 strKey
+= _T("\\DDEExec");
791 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
792 if ( keyDDE
.Open() ) {
793 wxString ddeCommand
, ddeServer
, ddeTopic
;
794 keyDDE
.QueryValue(_T(""), ddeCommand
);
795 ddeCommand
.Replace(_T("%1"), _T("%s"));
797 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Application")).
798 QueryValue(_T(""), ddeServer
);
799 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Topic")).
800 QueryValue(_T(""), ddeTopic
);
802 // HACK: we use a special feature of wxExecute which exists
803 // just because we need it here: it will establish DDE
804 // conversation with the program it just launched
805 command
.Prepend(_T("WX_DDE#"));
806 command
<< _T('#') << ddeServer
807 << _T('#') << ddeTopic
808 << _T('#') << ddeCommand
;
810 else if ( !foundFilename
) {
811 // we didn't find any '%1' - the application doesn't know which
812 // file to open (note that we only do it if there is no DDEExec
815 // HACK: append the filename at the end, hope that it will do
816 command
<< wxT(" %s");
820 //else: no such file type or no value, will return empty string
826 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
827 const wxFileType::MessageParameters
& params
)
832 cmd
= m_info
->GetOpenCommand();
835 cmd
= GetCommand(wxT("open"));
838 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
840 return !openCmd
->IsEmpty();
844 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
845 const wxFileType::MessageParameters
& params
)
850 cmd
= m_info
->GetPrintCommand();
853 cmd
= GetCommand(wxT("print"));
856 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
858 return !printCmd
->IsEmpty();
861 // TODO this function is half implemented
862 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
865 extensions
= m_info
->GetExtensions();
869 else if ( m_ext
.IsEmpty() ) {
870 // the only way to get the list of extensions from the file type is to
871 // scan through all extensions in the registry - too slow...
876 extensions
.Add(m_ext
);
878 // it's a lie too, we don't return _all_ extensions...
883 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
886 // we already have it
887 *mimeType
= m_info
->GetMimeType();
892 // suppress possible error messages
894 wxRegKey
key(wxRegKey::HKCR
, wxT(".") + m_ext
);
895 if ( key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
) ) {
903 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
907 // we don't have icons in the fallback resources
912 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
914 // suppress possible error messages
916 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
920 // it's the default value of the key
921 if ( key
.QueryValue(wxT(""), strIcon
) ) {
922 // the format is the following: <full path to file>, <icon index>
923 // NB: icon index may be negative as well as positive and the full
924 // path may contain the environment variables inside '%'
925 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
926 strIndex
= strIcon
.AfterLast(wxT(','));
928 // index may be omitted, in which case BeforeLast(',') is empty and
929 // AfterLast(',') is the whole string
930 if ( strFullPath
.IsEmpty() ) {
931 strFullPath
= strIndex
;
935 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
936 int nIndex
= wxAtoi(strIndex
);
938 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
939 switch ( (int)hIcon
) {
940 case 0: // means no icons were found
941 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
942 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
943 key
.GetName().c_str());
947 icon
->SetHICON((WXHICON
)hIcon
);
953 // no such file type or no value or incorrect icon entry
959 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
962 // we already have it
963 *desc
= m_info
->GetDescription();
968 // suppress possible error messages
970 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
973 // it's the default value of the key
974 if ( key
.QueryValue(wxT(""), *desc
) ) {
982 // extension -> file type
984 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
986 // add the leading point if necessary
988 if ( ext
[0u] != wxT('.') ) {
993 // suppress possible error messages
996 bool knownExtension
= FALSE
;
998 wxString strFileType
;
999 wxRegKey
key(wxRegKey::HKCR
, str
);
1001 // it's the default value of the key
1002 if ( key
.QueryValue(wxT(""), strFileType
) ) {
1003 // create the new wxFileType object
1004 wxFileType
*fileType
= new wxFileType
;
1005 fileType
->m_impl
->Init(strFileType
, ext
);
1010 // this extension doesn't have a filetype, but it's known to the
1011 // system and may be has some other useful keys (open command or
1012 // content-type), so still return a file type object for it
1013 knownExtension
= TRUE
;
1017 // check the fallbacks
1018 // TODO linear search is potentially slow, perhaps we should use a sorted
1020 size_t count
= m_fallbacks
.GetCount();
1021 for ( size_t n
= 0; n
< count
; n
++ ) {
1022 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
1023 wxFileType
*fileType
= new wxFileType
;
1024 fileType
->m_impl
->Init(m_fallbacks
[n
]);
1030 if ( knownExtension
)
1032 wxFileType
*fileType
= new wxFileType
;
1033 fileType
->m_impl
->Init(wxEmptyString
, ext
);
1039 // unknown extension
1044 // MIME type -> extension -> file type
1046 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1048 wxString strKey
= MIME_DATABASE_KEY
;
1051 // suppress possible error messages
1055 wxRegKey
key(wxRegKey::HKCR
, strKey
);
1057 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
1058 return GetFileTypeFromExtension(ext
);
1062 // check the fallbacks
1063 // TODO linear search is potentially slow, perhaps we should use a sorted
1065 size_t count
= m_fallbacks
.GetCount();
1066 for ( size_t n
= 0; n
< count
; n
++ ) {
1067 if ( wxMimeTypesManager::IsOfType(mimeType
,
1068 m_fallbacks
[n
].GetMimeType()) ) {
1069 wxFileType
*fileType
= new wxFileType
;
1070 fileType
->m_impl
->Init(m_fallbacks
[n
]);
1076 // unknown MIME type
1080 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1082 // enumerate all keys under MIME_DATABASE_KEY
1083 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
1087 bool cont
= key
.GetFirstKey(type
, cookie
);
1090 mimetypes
.Add(type
);
1092 cont
= key
.GetNextKey(type
, cookie
);
1095 return mimetypes
.GetCount();
1098 #elif defined ( __WXMAC__ )
1100 bool wxFileTypeImpl::GetCommand(wxString
*command
, const char *verb
) const
1105 // @@ this function is half implemented
1106 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1111 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
1113 if ( m_strFileType
.Length() > 0 )
1115 *mimeType
= m_strFileType
;
1122 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
1124 // no such file type or no value or incorrect icon entry
1128 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
1133 // extension -> file type
1135 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& e
)
1141 wxFileType
*fileType
= new wxFileType
;
1142 fileType
->m_impl
->SetFileType("text/text");
1143 fileType
->m_impl
->SetExt(ext
);
1146 else if ( ext
== "htm" || ext
== "html" )
1148 wxFileType
*fileType
= new wxFileType
;
1149 fileType
->m_impl
->SetFileType("text/html");
1150 fileType
->m_impl
->SetExt(ext
);
1153 else if ( ext
== "gif" )
1155 wxFileType
*fileType
= new wxFileType
;
1156 fileType
->m_impl
->SetFileType("image/gif");
1157 fileType
->m_impl
->SetExt(ext
);
1160 else if ( ext
== "png" )
1162 wxFileType
*fileType
= new wxFileType
;
1163 fileType
->m_impl
->SetFileType("image/png");
1164 fileType
->m_impl
->SetExt(ext
);
1167 else if ( ext
== "jpg" || ext
== "jpeg" )
1169 wxFileType
*fileType
= new wxFileType
;
1170 fileType
->m_impl
->SetFileType("image/jpeg");
1171 fileType
->m_impl
->SetExt(ext
);
1174 else if ( ext
== "bmp" )
1176 wxFileType
*fileType
= new wxFileType
;
1177 fileType
->m_impl
->SetFileType("image/bmp");
1178 fileType
->m_impl
->SetExt(ext
);
1181 else if ( ext
== "tif" || ext
== "tiff" )
1183 wxFileType
*fileType
= new wxFileType
;
1184 fileType
->m_impl
->SetFileType("image/tiff");
1185 fileType
->m_impl
->SetExt(ext
);
1188 else if ( ext
== "xpm" )
1190 wxFileType
*fileType
= new wxFileType
;
1191 fileType
->m_impl
->SetFileType("image/xpm");
1192 fileType
->m_impl
->SetExt(ext
);
1195 else if ( ext
== "xbm" )
1197 wxFileType
*fileType
= new wxFileType
;
1198 fileType
->m_impl
->SetFileType("image/xbm");
1199 fileType
->m_impl
->SetExt(ext
);
1203 // unknown extension
1207 // MIME type -> extension -> file type
1209 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1214 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1216 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1223 // ============================================================================
1224 // Unix implementation
1225 // ============================================================================
1227 // ----------------------------------------------------------------------------
1229 // ----------------------------------------------------------------------------
1231 static wxGNOMEIconHandler gs_iconHandlerGNOME
;
1232 static wxKDEIconHandler gs_iconHandlerKDE
;
1234 bool wxGNOMEIconHandler::m_inited
= FALSE
;
1235 wxSortedArrayString
wxGNOMEIconHandler::ms_mimetypes
;
1236 wxArrayString
wxGNOMEIconHandler::ms_icons
;
1238 bool wxKDEIconHandler::m_inited
= FALSE
;
1239 wxSortedArrayString
wxKDEIconHandler::ms_mimetypes
;
1240 wxArrayString
wxKDEIconHandler::ms_icons
;
1242 wxArrayString
wxKDEIconHandler::ms_infoTypes
;
1243 wxArrayString
wxKDEIconHandler::ms_infoDescriptions
;
1244 wxArrayString
wxKDEIconHandler::ms_infoExtensions
;
1247 ArrayIconHandlers
wxMimeTypesManagerImpl::ms_iconHandlers
;
1249 // ----------------------------------------------------------------------------
1250 // wxGNOMEIconHandler
1251 // ----------------------------------------------------------------------------
1253 // GNOME stores the info we're interested in in several locations:
1254 // 1. xxx.keys files under /usr/share/mime-info
1255 // 2. xxx.keys files under ~/.gnome/mime-info
1257 // The format of xxx.keys file is the following:
1259 // mimetype/subtype:
1262 // with blank lines separating the entries and indented lines starting with
1263 // TABs. We're interested in the field icon-filename whose value is the path
1264 // containing the icon.
1266 void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString
& filename
)
1268 wxTextFile
textfile(filename
);
1269 if ( !textfile
.Open() )
1272 // values for the entry being parsed
1273 wxString curMimeType
, curIconFile
;
1276 size_t nLineCount
= textfile
.GetLineCount();
1277 for ( size_t nLine
= 0; ; nLine
++ )
1279 if ( nLine
< nLineCount
)
1281 pc
= textfile
[nLine
].c_str();
1282 if ( *pc
== _T('#') )
1290 // so that we will fall into the "if" below
1297 if ( !!curMimeType
&& !!curIconFile
)
1299 // do we already know this mimetype?
1300 int i
= ms_mimetypes
.Index(curMimeType
);
1301 if ( i
== wxNOT_FOUND
)
1304 size_t n
= ms_mimetypes
.Add(curMimeType
);
1305 ms_icons
.Insert(curIconFile
, n
);
1309 // replace the existing one (this means that the directories
1310 // should be searched in order of increased priority!)
1311 ms_icons
[(size_t)i
] = curIconFile
;
1317 // the end - this can only happen if nLine == nLineCount
1321 curIconFile
.Empty();
1326 // what do we have here?
1327 if ( *pc
== _T('\t') )
1329 // this is a field=value ling
1330 pc
++; // skip leading TAB
1332 static const int lenField
= 13; // strlen("icon-filename")
1333 if ( wxStrncmp(pc
, _T("icon-filename"), lenField
) == 0 )
1335 // skip '=' which follows and take everything left until the end
1337 curIconFile
= pc
+ lenField
+ 1;
1339 //else: some other field, we don't care
1343 // this is the start of the new section
1344 curMimeType
.Empty();
1346 while ( *pc
!= _T(':') && *pc
!= _T('\0') )
1348 curMimeType
+= *pc
++;
1353 // we reached the end of line without finding the colon,
1354 // something is wrong - ignore this line completely
1355 wxLogDebug(_T("Unreckognized line %d in file '%s' ignored"),
1356 nLine
+ 1, filename
.c_str());
1364 void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString
& dirbase
)
1366 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1367 _T("base directory shouldn't end with a slash") );
1369 wxString dirname
= dirbase
;
1370 dirname
<< _T("/mime-info");
1372 if ( !wxDir::Exists(dirname
) )
1376 if ( !dir
.IsOpened() )
1379 // we will concatenate it with filename to get the full path below
1383 bool cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
1386 LoadIconsFromKeyFile(dirname
+ filename
);
1388 cont
= dir
.GetNext(&filename
);
1392 void wxGNOMEIconHandler::Init()
1395 dirs
.Add(_T("/usr/share"));
1398 wxGetHomeDir( &gnomedir
);
1399 gnomedir
+= _T("/.gnome");
1400 dirs
.Add( gnomedir
);
1402 size_t nDirs
= dirs
.GetCount();
1403 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1405 LoadKeyFilesFromDir(dirs
[nDir
]);
1411 bool wxGNOMEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
1418 int index
= ms_mimetypes
.Index(mimetype
);
1419 if ( index
== wxNOT_FOUND
)
1422 wxString iconname
= ms_icons
[(size_t)index
];
1425 *icon
= wxIcon(iconname
);
1427 // helpful for testing in console mode
1428 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
1429 mimetype
.c_str(), iconname
.c_str());
1435 // ----------------------------------------------------------------------------
1437 // ----------------------------------------------------------------------------
1439 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
1440 // may be found in either of the following locations
1442 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
1443 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
1445 // The format of a .kdelnk file is almost the same as the one used by
1446 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
1447 // value for the entry "Type"
1449 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString
& dirbase
,
1450 const wxString
& subdir
,
1451 const wxString
& filename
,
1452 const wxArrayString
& icondirs
)
1454 wxFFile
file(dirbase
+ filename
);
1455 if ( !file
.IsOpened() )
1458 // construct mimetype from the directory name and the basename of the
1459 // file (it always has .kdelnk extension)
1461 mimetype
<< subdir
<< _T('/') << filename
.BeforeLast(_T('.'));
1463 // these files are small, slurp the entire file at once
1465 if ( !file
.ReadAll(&text
) )
1471 // before trying to find an icon, grab mimetype information
1472 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
1473 // have edited it in control panel...)
1475 wxString mime_extension
, mime_desc
;
1478 if (wxGetLocale() != NULL
)
1479 mime_desc
= _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
1480 if (pos
== wxNOT_FOUND
) mime_desc
= _T("Comment=");
1481 pos
= text
.Find(mime_desc
);
1482 if (pos
== wxNOT_FOUND
) mime_desc
= wxEmptyString
;
1485 pc
= text
.c_str() + pos
+ mime_desc
.Length();
1486 mime_desc
= wxEmptyString
;
1487 while ( *pc
&& *pc
!= _T('\n') ) mime_desc
+= *pc
++;
1490 pos
= text
.Find(_T("Patterns="));
1491 if (pos
!= wxNOT_FOUND
)
1494 pc
= text
.c_str() + pos
+ 9;
1495 while ( *pc
&& *pc
!= _T('\n') ) exts
+= *pc
++;
1496 wxStringTokenizer
tokenizer(exts
, _T(";"));
1499 while (tokenizer
.HasMoreTokens())
1501 e
= tokenizer
.GetNextToken();
1502 if (e
.Left(2) != _T("*.")) continue; // don't support too difficult patterns
1503 mime_extension
<< e
.Mid(2);
1504 mime_extension
<< _T(' ');
1506 mime_extension
.RemoveLast();
1509 ms_infoTypes
.Add(mimetype
);
1510 ms_infoDescriptions
.Add(mime_desc
);
1511 ms_infoExtensions
.Add(mime_extension
);
1513 // ok, now we can take care of icon:
1515 pos
= text
.Find(_T("Icon="));
1516 if ( pos
== wxNOT_FOUND
)
1524 pc
= text
.c_str() + pos
+ 5; // 5 == strlen("Icon=")
1525 while ( *pc
&& *pc
!= _T('\n') )
1532 // we must check if the file exists because it may be stored
1533 // in many locations, at least ~/.kde and $KDEDIR
1534 size_t nDir
, nDirs
= icondirs
.GetCount();
1535 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
1536 if (wxFileExists(icondirs
[nDir
] + icon
))
1538 icon
.Prepend(icondirs
[nDir
]);
1541 if (nDir
== nDirs
) return; //does not exist
1543 // do we already have this MIME type?
1544 int i
= ms_mimetypes
.Index(mimetype
);
1545 if ( i
== wxNOT_FOUND
)
1548 size_t n
= ms_mimetypes
.Add(mimetype
);
1549 ms_icons
.Insert(icon
, n
);
1553 // replace the old value
1554 ms_icons
[(size_t)i
] = icon
;
1559 void wxKDEIconHandler::LoadLinksForMimeType(const wxString
& dirbase
,
1560 const wxString
& subdir
,
1561 const wxArrayString
& icondirs
)
1563 wxString dirname
= dirbase
;
1566 if ( !dir
.IsOpened() )
1572 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
1575 LoadLinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1577 cont
= dir
.GetNext(&filename
);
1581 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString
& dirbase
,
1582 const wxArrayString
& icondirs
)
1584 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1585 _T("base directory shouldn't end with a slash") );
1587 wxString dirname
= dirbase
;
1588 dirname
<< _T("/mimelnk");
1590 if ( !wxDir::Exists(dirname
) )
1594 if ( !dir
.IsOpened() )
1597 // we will concatenate it with dir name to get the full path below
1601 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
1604 LoadLinksForMimeType(dirname
, subdir
, icondirs
);
1606 cont
= dir
.GetNext(&subdir
);
1610 void wxKDEIconHandler::Init()
1613 wxArrayString icondirs
;
1615 // settings in ~/.kde have maximal priority
1616 dirs
.Add(wxGetHomeDir() + _T("/.kde/share"));
1617 icondirs
.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
1619 // the variable KDEDIR is set when KDE is running
1620 const char *kdedir
= getenv("KDEDIR");
1623 dirs
.Add(wxString(kdedir
) + _T("/share"));
1624 icondirs
.Add(wxString(kdedir
) + _T("/share/icons/"));
1628 // try to guess KDEDIR
1629 dirs
.Add(_T("/usr/share"));
1630 dirs
.Add(_T("/opt/kde/share"));
1631 icondirs
.Add(_T("/usr/share/icons/"));
1632 icondirs
.Add(_T("/opt/kde/share/icons/"));
1635 size_t nDirs
= dirs
.GetCount();
1636 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1638 LoadLinkFilesFromDir(dirs
[nDir
], icondirs
);
1644 bool wxKDEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
1651 int index
= ms_mimetypes
.Index(mimetype
);
1652 if ( index
== wxNOT_FOUND
)
1655 wxString iconname
= ms_icons
[(size_t)index
];
1658 *icon
= wxIcon(iconname
);
1660 // helpful for testing in console mode
1661 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
1662 mimetype
.c_str(), iconname
.c_str());
1669 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
)
1671 if ( !m_inited
) Init();
1673 size_t cnt
= ms_infoTypes
.GetCount();
1674 for (unsigned i
= 0; i
< cnt
; i
++)
1675 manager
-> AddMimeTypeInfo(ms_infoTypes
[i
], ms_infoExtensions
[i
], ms_infoDescriptions
[i
]);
1679 // ----------------------------------------------------------------------------
1680 // wxFileTypeImpl (Unix)
1681 // ----------------------------------------------------------------------------
1684 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
1687 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
1688 while ( entry
!= NULL
) {
1689 // notice that an empty command would always succeed (it's ok)
1690 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
1692 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
1694 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1695 command
.c_str(), params
.GetMimeType().c_str());
1699 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1700 command
.c_str(), params
.GetMimeType().c_str());
1703 entry
= entry
->GetNext();
1709 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
1712 (void)GetMimeType(&mimetype
);
1714 ArrayIconHandlers
& handlers
= m_manager
->GetIconHandlers();
1715 size_t count
= handlers
.GetCount();
1716 for ( size_t n
= 0; n
< count
; n
++ )
1718 if ( handlers
[n
]->GetIcon(mimetype
, icon
) )
1726 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
1727 const wxFileType::MessageParameters
& params
,
1730 MailCapEntry
*entry
= GetEntry(params
);
1731 if ( entry
== NULL
) {
1732 // all tests failed...
1736 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
1737 if ( cmd
.IsEmpty() ) {
1738 // may happen, especially for "print"
1742 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
1746 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1748 wxString strExtensions
= m_manager
->GetExtension(m_index
);
1751 // one extension in the space or comma delimitid list
1753 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
1754 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1755 if ( !strExt
.IsEmpty() ) {
1756 extensions
.Add(strExt
);
1759 //else: repeated spaces (shouldn't happen, but it's not that
1760 // important if it does happen)
1762 if ( *p
== wxT('\0') )
1765 else if ( *p
== wxT('.') ) {
1766 // remove the dot from extension (but only if it's the first char)
1767 if ( !strExt
.IsEmpty() ) {
1770 //else: no, don't append it
1780 // ----------------------------------------------------------------------------
1781 // wxMimeTypesManagerImpl (Unix)
1782 // ----------------------------------------------------------------------------
1785 ArrayIconHandlers
& wxMimeTypesManagerImpl::GetIconHandlers()
1787 if ( ms_iconHandlers
.GetCount() == 0 )
1789 ms_iconHandlers
.Add(&gs_iconHandlerGNOME
);
1790 ms_iconHandlers
.Add(&gs_iconHandlerKDE
);
1793 return ms_iconHandlers
;
1796 // read system and user mailcaps (TODO implement mime.types support)
1797 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1799 // directories where we look for mailcap and mime.types by default
1800 // (taken from metamail(1) sources)
1801 static const wxChar
*aStandardLocations
[] =
1805 wxT("/usr/local/etc"),
1807 wxT("/usr/public/lib")
1810 // first read the system wide file(s)
1812 for ( n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
1813 wxString dir
= aStandardLocations
[n
];
1815 wxString file
= dir
+ wxT("/mailcap");
1816 if ( wxFile::Exists(file
) ) {
1820 file
= dir
+ wxT("/mime.types");
1821 if ( wxFile::Exists(file
) ) {
1822 ReadMimeTypes(file
);
1826 wxString strHome
= wxGetenv(wxT("HOME"));
1828 // and now the users mailcap
1829 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1830 if ( wxFile::Exists(strUserMailcap
) ) {
1831 ReadMailcap(strUserMailcap
);
1834 // read the users mime.types
1835 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
1836 if ( wxFile::Exists(strUserMimeTypes
) ) {
1837 ReadMimeTypes(strUserMimeTypes
);
1840 // read KDE/GNOME tables
1841 ArrayIconHandlers
& handlers
= GetIconHandlers();
1842 size_t count
= handlers
.GetCount();
1843 for ( n
= 0; n
< count
; n
++ )
1844 handlers
[n
]->GetMimeInfoRecords(this);
1848 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1850 size_t count
= m_aExtensions
.GetCount();
1851 for ( size_t n
= 0; n
< count
; n
++ ) {
1852 wxString extensions
= m_aExtensions
[n
];
1853 while ( !extensions
.IsEmpty() ) {
1854 wxString field
= extensions
.BeforeFirst(wxT(' '));
1855 extensions
= extensions
.AfterFirst(wxT(' '));
1857 // consider extensions as not being case-sensitive
1858 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
1860 wxFileType
*fileType
= new wxFileType
;
1861 fileType
->m_impl
->Init(this, n
);
1873 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1875 // mime types are not case-sensitive
1876 wxString
mimetype(mimeType
);
1877 mimetype
.MakeLower();
1879 // first look for an exact match
1880 int index
= m_aTypes
.Index(mimetype
);
1881 if ( index
== wxNOT_FOUND
) {
1882 // then try to find "text/*" as match for "text/plain" (for example)
1883 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1884 // the whole string - ok.
1885 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1887 size_t nCount
= m_aTypes
.Count();
1888 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1889 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1890 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1897 if ( index
!= wxNOT_FOUND
) {
1898 wxFileType
*fileType
= new wxFileType
;
1899 fileType
->m_impl
->Init(this, index
);
1909 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1911 wxString extensions
;
1912 const wxArrayString
& exts
= filetype
.GetExtensions();
1913 size_t nExts
= exts
.GetCount();
1914 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1916 extensions
+= wxT(' ');
1918 extensions
+= exts
[nExt
];
1921 AddMimeTypeInfo(filetype
.GetMimeType(),
1923 filetype
.GetDescription());
1925 AddMailcapInfo(filetype
.GetMimeType(),
1926 filetype
.GetOpenCommand(),
1927 filetype
.GetPrintCommand(),
1929 filetype
.GetDescription());
1932 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
1933 const wxString
& strExtensions
,
1934 const wxString
& strDesc
)
1936 int index
= m_aTypes
.Index(strMimeType
);
1937 if ( index
== wxNOT_FOUND
) {
1939 m_aTypes
.Add(strMimeType
);
1940 m_aEntries
.Add(NULL
);
1941 m_aExtensions
.Add(strExtensions
);
1942 m_aDescriptions
.Add(strDesc
);
1945 // modify an existing one
1946 if ( !strDesc
.IsEmpty() ) {
1947 m_aDescriptions
[index
] = strDesc
; // replace old value
1949 m_aExtensions
[index
] += ' ' + strExtensions
;
1953 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
1954 const wxString
& strOpenCmd
,
1955 const wxString
& strPrintCmd
,
1956 const wxString
& strTest
,
1957 const wxString
& strDesc
)
1959 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1961 int nIndex
= m_aTypes
.Index(strType
);
1962 if ( nIndex
== wxNOT_FOUND
) {
1964 m_aTypes
.Add(strType
);
1966 m_aEntries
.Add(entry
);
1967 m_aExtensions
.Add(wxT(""));
1968 m_aDescriptions
.Add(strDesc
);
1971 // always append the entry in the tail of the list - info added with
1972 // this function can only come from AddFallbacks()
1973 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1975 entry
->Append(entryOld
);
1977 m_aEntries
[nIndex
] = entry
;
1981 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1983 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1985 wxTextFile
file(strFileName
);
1989 // the information we extract
1990 wxString strMimeType
, strDesc
, strExtensions
;
1992 size_t nLineCount
= file
.GetLineCount();
1993 const wxChar
*pc
= NULL
;
1994 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1996 // now we're at the start of the line
1997 pc
= file
[nLine
].c_str();
2000 // we didn't finish with the previous line yet
2005 while ( wxIsspace(*pc
) )
2008 // comment or blank line?
2009 if ( *pc
== wxT('#') || !*pc
) {
2010 // skip the whole line
2015 // detect file format
2016 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2017 if ( pEqualSign
== NULL
) {
2021 // first field is mime type
2022 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
2027 while ( wxIsspace(*pc
) )
2030 // take all the rest of the string
2033 // no description...
2040 // the string on the left of '=' is the field name
2041 wxString
strLHS(pc
, pEqualSign
- pc
);
2044 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2048 if ( *pc
== wxT('"') ) {
2049 // the string is quoted and ends at the matching quote
2050 pEnd
= wxStrchr(++pc
, wxT('"'));
2051 if ( pEnd
== NULL
) {
2052 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2054 strFileName
.c_str(), nLine
+ 1);
2058 // unquoted string ends at the first space
2059 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
2063 // now we have the RHS (field value)
2064 wxString
strRHS(pc
, pEnd
- pc
);
2066 // check what follows this entry
2067 if ( *pEnd
== wxT('"') ) {
2072 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2075 // if there is something left, it may be either a '\\' to continue
2076 // the line or the next field of the same entry
2077 bool entryEnded
= *pc
== wxT('\0'),
2078 nextFieldOnSameLine
= FALSE
;
2079 if ( !entryEnded
) {
2080 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2083 // now see what we got
2084 if ( strLHS
== wxT("type") ) {
2085 strMimeType
= strRHS
;
2087 else if ( strLHS
== wxT("desc") ) {
2090 else if ( strLHS
== wxT("exts") ) {
2091 strExtensions
= strRHS
;
2094 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2095 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
2098 if ( !entryEnded
) {
2099 if ( !nextFieldOnSameLine
)
2101 //else: don't reset it
2103 // as we don't reset strMimeType, the next field in this entry
2104 // will be interpreted correctly.
2110 // although it doesn't seem to be covered by RFCs, some programs
2111 // (notably Netscape) create their entries with several comma
2112 // separated extensions (RFC mention the spaces only)
2113 strExtensions
.Replace(wxT(","), wxT(" "));
2115 // also deal with the leading dot
2116 if ( !strExtensions
.IsEmpty() && strExtensions
[0u] == wxT('.') )
2118 strExtensions
.erase(0, 1);
2121 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2123 // finished with this line
2127 // check our data integriry
2128 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2129 m_aTypes
.Count() == m_aExtensions
.Count() &&
2130 m_aTypes
.Count() == m_aDescriptions
.Count() );
2135 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2138 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
2140 wxTextFile
file(strFileName
);
2144 // see the comments near the end of function for the reason we need these
2145 // variables (search for the next occurence of them)
2146 // indices of MIME types (in m_aTypes) we already found in this file
2147 wxArrayInt aEntryIndices
;
2148 // aLastIndices[n] is the index of last element in
2149 // m_aEntries[aEntryIndices[n]] from this file
2150 wxArrayInt aLastIndices
;
2152 size_t nLineCount
= file
.GetLineCount();
2153 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
2154 // now we're at the start of the line
2155 const wxChar
*pc
= file
[nLine
].c_str();
2158 while ( wxIsspace(*pc
) )
2161 // comment or empty string?
2162 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2167 // what field are we currently in? The first 2 are fixed and there may
2168 // be an arbitrary number of other fields -- currently, we are not
2169 // interested in any of them, but we should parse them as well...
2175 } currentToken
= Field_Type
;
2177 // the flags and field values on the current line
2178 bool needsterminal
= FALSE
,
2179 copiousoutput
= FALSE
;
2185 curField
; // accumulator
2186 for ( bool cont
= TRUE
; cont
; pc
++ ) {
2189 // interpret the next character literally (notice that
2190 // backslash can be used for line continuation)
2191 if ( *++pc
== wxT('\0') ) {
2192 // fetch the next line.
2194 // pc currently points to nowhere, but after the next
2195 // pc++ in the for line it will point to the beginning
2196 // of the next line in the file
2197 pc
= file
[++nLine
].c_str() - 1;
2200 // just a normal character
2206 cont
= FALSE
; // end of line reached, exit the loop
2211 // store this field and start looking for the next one
2213 // trim whitespaces from both sides
2214 curField
.Trim(TRUE
).Trim(FALSE
);
2216 switch ( currentToken
) {
2219 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
2220 // we interpret "type" as "type/*"
2221 strType
+= wxT("/*");
2224 currentToken
= Field_OpenCmd
;
2228 strOpenCmd
= curField
;
2230 currentToken
= Field_Other
;
2235 // "good" mailcap entry?
2238 // is this something of the form foo=bar?
2239 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2240 if ( pEq
!= NULL
) {
2241 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2242 rhs
= curField
.AfterFirst(wxT('='));
2244 lhs
.Trim(TRUE
); // from right
2245 rhs
.Trim(FALSE
); // from left
2247 if ( lhs
== wxT("print") )
2249 else if ( lhs
== wxT("test") )
2251 else if ( lhs
== wxT("description") ) {
2252 // it might be quoted
2253 if ( rhs
[0u] == wxT('"') &&
2254 rhs
.Last() == wxT('"') ) {
2255 strDesc
= wxString(rhs
.c_str() + 1,
2262 else if ( lhs
== wxT("compose") ||
2263 lhs
== wxT("composetyped") ||
2264 lhs
== wxT("notes") ||
2265 lhs
== wxT("edit") )
2272 // no, it's a simple flag
2273 // TODO support the flags:
2274 // 1. create an xterm for 'needsterminal'
2275 // 2. append "| $PAGER" for 'copiousoutput'
2276 if ( curField
== wxT("needsterminal") )
2277 needsterminal
= TRUE
;
2278 else if ( curField
== wxT("copiousoutput") )
2279 copiousoutput
= TRUE
;
2280 else if ( curField
== wxT("textualnewlines") )
2288 // we don't understand this field, but
2289 // Netscape stores info in it, so don't warn
2291 if ( curField
.Left(16u) != "x-mozilla-flags=" )
2293 // don't flood the user with error
2294 // messages if we don't understand
2295 // something in his mailcap, but give
2296 // them in debug mode because this might
2297 // be useful for the programmer
2300 wxT("Mailcap file %s, line %d: "
2301 "unknown field '%s' for the "
2302 "MIME type '%s' ignored."),
2303 strFileName
.c_str(),
2312 // it already has this value
2313 //currentToken = Field_Other;
2317 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2320 // next token starts immediately after ';'
2329 // check that we really read something reasonable
2330 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
2331 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2333 strFileName
.c_str(), nLine
+ 1);
2336 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
2340 // NB: because of complications below (we must get entries priority
2341 // right), we can't use AddMailcapInfo() here, unfortunately.
2342 strType
.MakeLower();
2343 int nIndex
= m_aTypes
.Index(strType
);
2344 if ( nIndex
== wxNOT_FOUND
) {
2346 m_aTypes
.Add(strType
);
2348 m_aEntries
.Add(entry
);
2349 m_aExtensions
.Add(wxT(""));
2350 m_aDescriptions
.Add(strDesc
);
2353 // modify the existing entry: the entries in one and the same
2354 // file are read in top-to-bottom order, i.e. the entries read
2355 // first should be tried before the entries below. However,
2356 // the files read later should override the settings in the
2357 // files read before (except if fallback is TRUE), thus we
2358 // Insert() the new entry to the list if it has already
2359 // occured in _this_ file, but Prepend() it if it occured in
2360 // some of the previous ones and Append() to it in the
2364 // 'fallback' parameter prevents the entries from this
2365 // file from overriding the other ones - always append
2366 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
2368 entry
->Append(entryOld
);
2370 m_aEntries
[nIndex
] = entry
;
2373 int entryIndex
= aEntryIndices
.Index(nIndex
);
2374 if ( entryIndex
== wxNOT_FOUND
) {
2375 // first time in this file
2376 aEntryIndices
.Add(nIndex
);
2377 aLastIndices
.Add(0);
2379 entry
->Prepend(m_aEntries
[nIndex
]);
2380 m_aEntries
[nIndex
] = entry
;
2383 // not the first time in _this_ file
2384 size_t nEntryIndex
= (size_t)entryIndex
;
2385 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
2387 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
2389 m_aEntries
[nIndex
] = entry
;
2391 // the indices were shifted by 1
2392 aLastIndices
[nEntryIndex
]++;
2396 if ( !strDesc
.IsEmpty() ) {
2397 // replace the old one - what else can we do??
2398 m_aDescriptions
[nIndex
] = strDesc
;
2403 // check our data integriry
2404 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2405 m_aTypes
.Count() == m_aExtensions
.Count() &&
2406 m_aTypes
.Count() == m_aDescriptions
.Count() );
2412 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2417 size_t count
= m_aTypes
.GetCount();
2418 for ( size_t n
= 0; n
< count
; n
++ )
2420 // don't return template types from here (i.e. anything containg '*')
2422 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
2424 mimetypes
.Add(type
);
2428 return mimetypes
.GetCount();
2435 // wxUSE_FILE && wxUSE_TEXTFILE