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"
55 #include "wx/mimetype.h"
57 // other standard headers
60 // in case we're compiling in non-GUI mode
61 class WXDLLEXPORT wxIcon
;
63 // ----------------------------------------------------------------------------
65 // ----------------------------------------------------------------------------
67 // implementation classes, platform dependent
70 // These classes use Windows registry to retrieve the required information.
72 // Keys used (not all of them are documented, so it might actually stop working
73 // in futur versions of Windows...):
74 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
75 // types, each key has a string value "Extension" which gives (dot preceded)
76 // extension for the files of this MIME type.
78 // 2. "HKCR\.ext" contains
79 // a) unnamed value containing the "filetype"
80 // b) value "Content Type" containing the MIME type
82 // 3. "HKCR\filetype" contains
83 // a) unnamed value containing the description
84 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
86 // c) shell\open\command and shell\open\print subkeys containing the commands
87 // to open/print the file (the positional parameters are introduced by %1,
88 // %2, ... in these strings, we change them to %s ourselves)
90 // although I don't know of any official documentation which mentions this
91 // location, uses it, so it isn't likely to change
92 static const wxChar
*MIME_DATABASE_KEY
= wxT("MIME\\Database\\Content Type\\");
98 wxFileTypeImpl() { m_info
= NULL
; }
100 // one of these Init() function must be called (ctor can't take any
101 // arguments because it's common)
103 // initialize us with our file type name and extension - in this case
104 // we will read all other data from the registry
105 void Init(const wxString
& strFileType
, const wxString
& ext
)
106 { m_strFileType
= strFileType
; m_ext
= ext
; }
108 // initialize us with a wxFileTypeInfo object - it contains all the
110 void Init(const wxFileTypeInfo
& info
)
113 // implement accessor functions
114 bool GetExtensions(wxArrayString
& extensions
);
115 bool GetMimeType(wxString
*mimeType
) const;
116 bool GetIcon(wxIcon
*icon
) const;
117 bool GetDescription(wxString
*desc
) const;
118 bool GetOpenCommand(wxString
*openCmd
,
119 const wxFileType::MessageParameters
& params
) const;
120 bool GetPrintCommand(wxString
*printCmd
,
121 const wxFileType::MessageParameters
& params
) const;
124 // helper function: reads the command corresponding to the specified verb
125 // from the registry (returns an empty string if not found)
126 wxString
GetCommand(const wxChar
*verb
) const;
128 // we use either m_info or read the data from the registry if m_info == NULL
129 const wxFileTypeInfo
*m_info
;
130 wxString m_strFileType
, // may be empty
134 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
135 #include "wx/arrimpl.cpp"
136 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
138 class wxMimeTypesManagerImpl
141 // nothing to do here, we don't load any data but just go and fetch it from
142 // the registry when asked for
143 wxMimeTypesManagerImpl() { }
145 // implement containing class functions
146 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
147 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
149 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
151 // this are NOPs under Windows
152 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
)
154 bool ReadMimeTypes(const wxString
& filename
)
157 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
160 wxArrayFileTypeInfo m_fallbacks
;
163 #elif defined( __WXMAC__ )
165 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
166 #include "wx/arrimpl.cpp"
167 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
169 class wxMimeTypesManagerImpl
172 wxMimeTypesManagerImpl() { }
174 // implement containing class functions
175 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
176 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
178 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
180 // this are NOPs under MacOS
181 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
) { return TRUE
; }
182 bool ReadMimeTypes(const wxString
& filename
) { return TRUE
; }
184 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
187 wxArrayFileTypeInfo m_fallbacks
;
193 // initialize us with our file type name
194 void SetFileType(const wxString
& strFileType
)
195 { m_strFileType
= strFileType
; }
196 void SetExt(const wxString
& ext
)
199 // implement accessor functions
200 bool GetExtensions(wxArrayString
& extensions
);
201 bool GetMimeType(wxString
*mimeType
) const;
202 bool GetIcon(wxIcon
*icon
) const;
203 bool GetDescription(wxString
*desc
) const;
204 bool GetOpenCommand(wxString
*openCmd
,
205 const wxFileType::MessageParameters
&) const
206 { return GetCommand(openCmd
, "open"); }
207 bool GetPrintCommand(wxString
*printCmd
,
208 const wxFileType::MessageParameters
&) const
209 { return GetCommand(printCmd
, "print"); }
213 bool GetCommand(wxString
*command
, const char *verb
) const;
215 wxString m_strFileType
, m_ext
;
220 // this class uses both mailcap and mime.types to gather information about file
223 // The information about mailcap file was extracted from metamail(1) sources and
226 // Format of mailcap file: spaces are ignored, each line is either a comment
227 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
228 // A backslash can be used to quote semicolons and newlines (and, in fact,
229 // anything else including itself).
231 // The first field is always the MIME type in the form of type/subtype (see RFC
232 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
233 // "type" which means the same as "type/*", although I'm not sure whether this
236 // The second field is always the command to run. It is subject to
237 // parameter/filename expansion described below.
239 // All the following fields are optional and may not be present at all. If
240 // they're present they may appear in any order, although each of them should
241 // appear only once. The optional fields are the following:
242 // * notes=xxx is an uninterpreted string which is silently ignored
243 // * test=xxx is the command to be used to determine whether this mailcap line
244 // applies to our data or not. The RHS of this field goes through the
245 // parameter/filename expansion (as the 2nd field) and the resulting string
246 // is executed. The line applies only if the command succeeds, i.e. returns 0
248 // * print=xxx is the command to be used to print (and not view) the data of
249 // this type (parameter/filename expansion is done here too)
250 // * edit=xxx is the command to open/edit the data of this type
251 // * needsterminal means that a new console must be created for the viewer
252 // * copiousoutput means that the viewer doesn't interact with the user but
253 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
254 // good example), thus it might be a good idea to use some kind of paging
256 // * textualnewlines means not to perform CR/LF translation (not honored)
257 // * compose and composetyped fields are used to determine the program to be
258 // called to create a new message pert in the specified format (unused).
260 // Parameter/filename xpansion:
261 // * %s is replaced with the (full) file name
262 // * %t is replaced with MIME type/subtype of the entry
263 // * for multipart type only %n is replaced with the nnumber of parts and %F is
264 // replaced by an array of (content-type, temporary file name) pairs for all
265 // message parts (TODO)
266 // * %{parameter} is replaced with the value of parameter taken from
267 // Content-type header line of the message.
269 // FIXME any docs with real descriptions of these files??
271 // There are 2 possible formats for mime.types file, one entry per line (used
272 // for global mime.types) and "expanded" format where an entry takes multiple
273 // lines (used for users mime.types).
275 // For both formats spaces are ignored and lines starting with a '#' are
276 // comments. Each record has one of two following forms:
277 // a) for "brief" format:
278 // <mime type> <space separated list of extensions>
279 // b) for "expanded" format:
280 // type=<mime type> \ desc="<description>" \ exts="ext"
282 // We try to autodetect the format of mime.types: if a non-comment line starts
283 // with "type=" we assume the second format, otherwise the first one.
285 // there may be more than one entry for one and the same mime type, to
286 // choose the right one we have to run the command specified in the test
287 // field on our data.
292 MailCapEntry(const wxString
& openCmd
,
293 const wxString
& printCmd
,
294 const wxString
& testCmd
)
295 : m_openCmd(openCmd
), m_printCmd(printCmd
), m_testCmd(testCmd
)
301 const wxString
& GetOpenCmd() const { return m_openCmd
; }
302 const wxString
& GetPrintCmd() const { return m_printCmd
; }
303 const wxString
& GetTestCmd() const { return m_testCmd
; }
305 MailCapEntry
*GetNext() const { return m_next
; }
308 // prepend this element to the list
309 void Prepend(MailCapEntry
*next
) { m_next
= next
; }
310 // insert into the list at given position
311 void Insert(MailCapEntry
*next
, size_t pos
)
316 for ( cur
= next
; cur
!= NULL
; cur
= cur
->m_next
, n
++ ) {
321 wxASSERT_MSG( n
== pos
, wxT("invalid position in MailCapEntry::Insert") );
323 m_next
= cur
->m_next
;
326 // append this element to the list
327 void Append(MailCapEntry
*next
)
329 wxCHECK_RET( next
!= NULL
, wxT("Append()ing to what?") );
333 for ( cur
= next
; cur
->m_next
!= NULL
; cur
= cur
->m_next
)
338 wxASSERT_MSG( !m_next
, wxT("Append()ing element already in the list?") );
342 wxString m_openCmd
, // command to use to open/view the file
344 m_testCmd
; // only apply this entry if test yields
345 // true (i.e. the command returns 0)
347 MailCapEntry
*m_next
; // in the linked list
350 WX_DEFINE_ARRAY(MailCapEntry
*, ArrayTypeEntries
);
352 // the base class which may be used to find an icon for the MIME type
353 class wxMimeTypeIconHandler
356 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
) = 0;
359 WX_DEFINE_ARRAY(wxMimeTypeIconHandler
*, ArrayIconHandlers
);
361 // the icon handler which uses GNOME MIME database
362 class wxGNOMEIconHandler
: public wxMimeTypeIconHandler
365 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
);
369 void LoadIconsFromKeyFile(const wxString
& filename
);
370 void LoadKeyFilesFromDir(const wxString
& dirbase
);
372 static bool m_inited
;
374 static wxSortedArrayString ms_mimetypes
;
375 static wxArrayString ms_icons
;
378 // the icon handler which uses KDE MIME database
379 class wxKDEIconHandler
: public wxMimeTypeIconHandler
382 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
);
385 void LoadLinksForMimeSubtype(const wxString
& dirbase
,
386 const wxString
& subdir
,
387 const wxString
& filename
);
388 void LoadLinksForMimeType(const wxString
& dirbase
,
389 const wxString
& subdir
);
390 void LoadLinkFilesFromDir(const wxString
& dirbase
);
393 static bool m_inited
;
395 static wxSortedArrayString ms_mimetypes
;
396 static wxArrayString ms_icons
;
399 // this is the real wxMimeTypesManager for Unix
400 class wxMimeTypesManagerImpl
402 friend class wxFileTypeImpl
; // give it access to m_aXXX variables
405 // ctor loads all info into memory for quicker access later on
406 // TODO it would be nice to load them all, but parse on demand only...
407 wxMimeTypesManagerImpl();
409 // implement containing class functions
410 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
411 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
413 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
415 bool ReadMailcap(const wxString
& filename
, bool fallback
= FALSE
);
416 bool ReadMimeTypes(const wxString
& filename
);
418 void AddFallback(const wxFileTypeInfo
& filetype
);
420 // add information about the given mimetype
421 void AddMimeTypeInfo(const wxString
& mimetype
,
422 const wxString
& extensions
,
423 const wxString
& description
);
424 void AddMailcapInfo(const wxString
& strType
,
425 const wxString
& strOpenCmd
,
426 const wxString
& strPrintCmd
,
427 const wxString
& strTest
,
428 const wxString
& strDesc
);
431 // get the string containing space separated extensions for the given
433 wxString
GetExtension(size_t index
) { return m_aExtensions
[index
]; }
435 // get the array of icon handlers
436 static ArrayIconHandlers
& GetIconHandlers();
439 wxArrayString m_aTypes
, // MIME types
440 m_aDescriptions
, // descriptions (just some text)
441 m_aExtensions
; // space separated list of extensions
442 ArrayTypeEntries m_aEntries
; // commands and tests for this file type
444 // head of the linked list of the icon handlers
445 static ArrayIconHandlers ms_iconHandlers
;
451 // initialization functions
452 void Init(wxMimeTypesManagerImpl
*manager
, size_t index
)
453 { m_manager
= manager
; m_index
= index
; }
456 bool GetExtensions(wxArrayString
& extensions
);
457 bool GetMimeType(wxString
*mimeType
) const
458 { *mimeType
= m_manager
->m_aTypes
[m_index
]; return TRUE
; }
459 bool GetIcon(wxIcon
*icon
) const;
460 bool GetDescription(wxString
*desc
) const
461 { *desc
= m_manager
->m_aDescriptions
[m_index
]; return TRUE
; }
463 bool GetOpenCommand(wxString
*openCmd
,
464 const wxFileType::MessageParameters
& params
) const
466 return GetExpandedCommand(openCmd
, params
, TRUE
);
469 bool GetPrintCommand(wxString
*printCmd
,
470 const wxFileType::MessageParameters
& params
) const
472 return GetExpandedCommand(printCmd
, params
, FALSE
);
476 // get the entry which passes the test (may return NULL)
477 MailCapEntry
*GetEntry(const wxFileType::MessageParameters
& params
) const;
479 // choose the correct entry to use and expand the command
480 bool GetExpandedCommand(wxString
*expandedCmd
,
481 const wxFileType::MessageParameters
& params
,
484 wxMimeTypesManagerImpl
*m_manager
;
485 size_t m_index
; // in the wxMimeTypesManagerImpl arrays
490 // ============================================================================
492 // ============================================================================
494 // ----------------------------------------------------------------------------
496 // ----------------------------------------------------------------------------
498 wxFileTypeInfo::wxFileTypeInfo(const char *mimeType
,
500 const char *printCmd
,
503 : m_mimeType(mimeType
),
505 m_printCmd(printCmd
),
509 va_start(argptr
, desc
);
513 const char *ext
= va_arg(argptr
, const char *);
516 // NULL terminates the list
526 // ============================================================================
527 // implementation of the wrapper classes
528 // ============================================================================
530 // ----------------------------------------------------------------------------
532 // ----------------------------------------------------------------------------
534 wxString
wxFileType::ExpandCommand(const wxString
& command
,
535 const wxFileType::MessageParameters
& params
)
537 bool hasFilename
= FALSE
;
540 for ( const wxChar
*pc
= command
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
541 if ( *pc
== wxT('%') ) {
544 // '%s' expands into file name (quoted because it might
545 // contain spaces) - except if there are already quotes
546 // there because otherwise some programs may get confused
547 // by double double quotes
549 if ( *(pc
- 2) == wxT('"') )
550 str
<< params
.GetFileName();
552 str
<< wxT('"') << params
.GetFileName() << wxT('"');
554 str
<< params
.GetFileName();
559 // '%t' expands into MIME type (quote it too just to be
561 str
<< wxT('\'') << params
.GetMimeType() << wxT('\'');
566 const wxChar
*pEnd
= wxStrchr(pc
, wxT('}'));
567 if ( pEnd
== NULL
) {
569 wxLogWarning(_("Unmatched '{' in an entry for "
571 params
.GetMimeType().c_str());
575 wxString
param(pc
+ 1, pEnd
- pc
- 1);
576 str
<< wxT('\'') << params
.GetParamValue(param
) << wxT('\'');
584 // TODO %n is the number of parts, %F is an array containing
585 // the names of temp files these parts were written to
586 // and their mime types.
590 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
591 *pc
, command
.c_str());
600 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
601 // the program will accept the data on stdin: so give it to it!
602 if ( !hasFilename
&& !str
.IsEmpty() ) {
603 str
<< wxT(" < '") << params
.GetFileName() << wxT('\'');
609 wxFileType::wxFileType()
611 m_impl
= new wxFileTypeImpl
;
614 wxFileType::~wxFileType()
619 bool wxFileType::GetExtensions(wxArrayString
& extensions
)
621 return m_impl
->GetExtensions(extensions
);
624 bool wxFileType::GetMimeType(wxString
*mimeType
) const
626 return m_impl
->GetMimeType(mimeType
);
629 bool wxFileType::GetIcon(wxIcon
*icon
) const
631 return m_impl
->GetIcon(icon
);
634 bool wxFileType::GetDescription(wxString
*desc
) const
636 return m_impl
->GetDescription(desc
);
640 wxFileType::GetOpenCommand(wxString
*openCmd
,
641 const wxFileType::MessageParameters
& params
) const
643 return m_impl
->GetOpenCommand(openCmd
, params
);
647 wxFileType::GetPrintCommand(wxString
*printCmd
,
648 const wxFileType::MessageParameters
& params
) const
650 return m_impl
->GetPrintCommand(printCmd
, params
);
653 // ----------------------------------------------------------------------------
654 // wxMimeTypesManager
655 // ----------------------------------------------------------------------------
657 bool wxMimeTypesManager::IsOfType(const wxString
& mimeType
,
658 const wxString
& wildcard
)
660 wxASSERT_MSG( mimeType
.Find(wxT('*')) == wxNOT_FOUND
,
661 wxT("first MIME type can't contain wildcards") );
663 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
664 if ( wildcard
.BeforeFirst(wxT('/')).IsSameAs(mimeType
.BeforeFirst(wxT('/')), FALSE
) )
666 wxString strSubtype
= wildcard
.AfterFirst(wxT('/'));
668 if ( strSubtype
== wxT("*") ||
669 strSubtype
.IsSameAs(mimeType
.AfterFirst(wxT('/')), FALSE
) )
671 // matches (either exactly or it's a wildcard)
679 wxMimeTypesManager::wxMimeTypesManager()
681 m_impl
= new wxMimeTypesManagerImpl
;
684 wxMimeTypesManager::~wxMimeTypesManager()
690 wxMimeTypesManager::GetFileTypeFromExtension(const wxString
& ext
)
692 return m_impl
->GetFileTypeFromExtension(ext
);
696 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString
& mimeType
)
698 return m_impl
->GetFileTypeFromMimeType(mimeType
);
701 bool wxMimeTypesManager::ReadMailcap(const wxString
& filename
, bool fallback
)
703 return m_impl
->ReadMailcap(filename
, fallback
);
706 bool wxMimeTypesManager::ReadMimeTypes(const wxString
& filename
)
708 return m_impl
->ReadMimeTypes(filename
);
711 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo
*filetypes
)
713 for ( const wxFileTypeInfo
*ft
= filetypes
; ft
->IsValid(); ft
++ ) {
714 m_impl
->AddFallback(*ft
);
718 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString
& mimetypes
)
720 return m_impl
->EnumAllFileTypes(mimetypes
);
723 // ============================================================================
724 // real (OS specific) implementation
725 // ============================================================================
729 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
731 // suppress possible error messages
735 if ( wxRegKey(wxRegKey::HKCR
, m_ext
+ _T("\\shell")).Exists() )
737 if ( wxRegKey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell")).Exists() )
738 strKey
= m_strFileType
;
743 return wxEmptyString
;
746 strKey
<< wxT("\\shell\\") << verb
<< wxT("\\command");
747 wxRegKey
key(wxRegKey::HKCR
, strKey
);
750 // it's the default value of the key
751 if ( key
.QueryValue(wxT(""), command
) ) {
752 // transform it from '%1' to '%s' style format string
754 // NB: we don't make any attempt to verify that the string is valid,
755 // i.e. doesn't contain %2, or second %1 or .... But we do make
756 // sure that we return a string with _exactly_ one '%s'!
757 bool foundFilename
= FALSE
;
758 size_t len
= command
.Len();
759 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
760 if ( command
[n
] == wxT('%') &&
761 (n
+ 1 < len
) && command
[n
+ 1] == wxT('1') ) {
762 // replace it with '%s'
763 command
[n
+ 1] = wxT('s');
765 foundFilename
= TRUE
;
769 if ( !foundFilename
) {
770 // we didn't find any '%1'!
771 // HACK: append the filename at the end, hope that it will do
772 command
<< wxT(" %s");
776 //else: no such file type or no value, will return empty string
782 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
783 const wxFileType::MessageParameters
& params
)
788 cmd
= m_info
->GetOpenCommand();
791 cmd
= GetCommand(wxT("open"));
794 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
796 return !openCmd
->IsEmpty();
800 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
801 const wxFileType::MessageParameters
& params
)
806 cmd
= m_info
->GetPrintCommand();
809 cmd
= GetCommand(wxT("print"));
812 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
814 return !printCmd
->IsEmpty();
817 // TODO this function is half implemented
818 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
821 extensions
= m_info
->GetExtensions();
825 else if ( m_ext
.IsEmpty() ) {
826 // the only way to get the list of extensions from the file type is to
827 // scan through all extensions in the registry - too slow...
832 extensions
.Add(m_ext
);
834 // it's a lie too, we don't return _all_ extensions...
839 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
842 // we already have it
843 *mimeType
= m_info
->GetMimeType();
848 // suppress possible error messages
850 wxRegKey
key(wxRegKey::HKCR
, wxT(".") + m_ext
);
851 if ( key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
) ) {
859 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
863 // we don't have icons in the fallback resources
868 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
870 // suppress possible error messages
872 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
876 // it's the default value of the key
877 if ( key
.QueryValue(wxT(""), strIcon
) ) {
878 // the format is the following: <full path to file>, <icon index>
879 // NB: icon index may be negative as well as positive and the full
880 // path may contain the environment variables inside '%'
881 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
882 strIndex
= strIcon
.AfterLast(wxT(','));
884 // index may be omitted, in which case BeforeLast(',') is empty and
885 // AfterLast(',') is the whole string
886 if ( strFullPath
.IsEmpty() ) {
887 strFullPath
= strIndex
;
891 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
892 int nIndex
= wxAtoi(strIndex
);
894 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
895 switch ( (int)hIcon
) {
896 case 0: // means no icons were found
897 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
898 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
899 key
.GetName().c_str());
903 icon
->SetHICON((WXHICON
)hIcon
);
909 // no such file type or no value or incorrect icon entry
915 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
918 // we already have it
919 *desc
= m_info
->GetDescription();
924 // suppress possible error messages
926 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
929 // it's the default value of the key
930 if ( key
.QueryValue(wxT(""), *desc
) ) {
938 // extension -> file type
940 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
942 // add the leading point if necessary
944 if ( ext
[0u] != wxT('.') ) {
949 // suppress possible error messages
952 bool knownExtension
= FALSE
;
954 wxString strFileType
;
955 wxRegKey
key(wxRegKey::HKCR
, str
);
957 // it's the default value of the key
958 if ( key
.QueryValue(wxT(""), strFileType
) ) {
959 // create the new wxFileType object
960 wxFileType
*fileType
= new wxFileType
;
961 fileType
->m_impl
->Init(strFileType
, ext
);
966 // this extension doesn't have a filetype, but it's known to the
967 // system and may be has some other useful keys (open command or
968 // content-type), so still return a file type object for it
969 knownExtension
= TRUE
;
973 // check the fallbacks
974 // TODO linear search is potentially slow, perhaps we should use a sorted
976 size_t count
= m_fallbacks
.GetCount();
977 for ( size_t n
= 0; n
< count
; n
++ ) {
978 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
979 wxFileType
*fileType
= new wxFileType
;
980 fileType
->m_impl
->Init(m_fallbacks
[n
]);
986 if ( knownExtension
)
988 wxFileType
*fileType
= new wxFileType
;
989 fileType
->m_impl
->Init(wxEmptyString
, ext
);
1000 // MIME type -> extension -> file type
1002 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1004 wxString strKey
= MIME_DATABASE_KEY
;
1007 // suppress possible error messages
1011 wxRegKey
key(wxRegKey::HKCR
, strKey
);
1013 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
1014 return GetFileTypeFromExtension(ext
);
1018 // check the fallbacks
1019 // TODO linear search is potentially slow, perhaps we should use a sorted
1021 size_t count
= m_fallbacks
.GetCount();
1022 for ( size_t n
= 0; n
< count
; n
++ ) {
1023 if ( wxMimeTypesManager::IsOfType(mimeType
,
1024 m_fallbacks
[n
].GetMimeType()) ) {
1025 wxFileType
*fileType
= new wxFileType
;
1026 fileType
->m_impl
->Init(m_fallbacks
[n
]);
1032 // unknown MIME type
1036 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1038 // enumerate all keys under MIME_DATABASE_KEY
1039 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
1043 bool cont
= key
.GetFirstKey(type
, cookie
);
1046 mimetypes
.Add(type
);
1048 cont
= key
.GetNextKey(type
, cookie
);
1051 return mimetypes
.GetCount();
1054 #elif defined ( __WXMAC__ )
1056 bool wxFileTypeImpl::GetCommand(wxString
*command
, const char *verb
) const
1061 // @@ this function is half implemented
1062 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1067 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
1069 if ( m_strFileType
.Length() > 0 )
1071 *mimeType
= m_strFileType
;
1078 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
1080 // no such file type or no value or incorrect icon entry
1084 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
1089 // extension -> file type
1091 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& e
)
1097 wxFileType
*fileType
= new wxFileType
;
1098 fileType
->m_impl
->SetFileType("text/text");
1099 fileType
->m_impl
->SetExt(ext
);
1102 else if ( ext
== "htm" || ext
== "html" )
1104 wxFileType
*fileType
= new wxFileType
;
1105 fileType
->m_impl
->SetFileType("text/html");
1106 fileType
->m_impl
->SetExt(ext
);
1109 else if ( ext
== "gif" )
1111 wxFileType
*fileType
= new wxFileType
;
1112 fileType
->m_impl
->SetFileType("image/gif");
1113 fileType
->m_impl
->SetExt(ext
);
1116 else if ( ext
== "png" )
1118 wxFileType
*fileType
= new wxFileType
;
1119 fileType
->m_impl
->SetFileType("image/png");
1120 fileType
->m_impl
->SetExt(ext
);
1123 else if ( ext
== "jpg" || ext
== "jpeg" )
1125 wxFileType
*fileType
= new wxFileType
;
1126 fileType
->m_impl
->SetFileType("image/jpeg");
1127 fileType
->m_impl
->SetExt(ext
);
1130 else if ( ext
== "bmp" )
1132 wxFileType
*fileType
= new wxFileType
;
1133 fileType
->m_impl
->SetFileType("image/bmp");
1134 fileType
->m_impl
->SetExt(ext
);
1137 else if ( ext
== "tif" || ext
== "tiff" )
1139 wxFileType
*fileType
= new wxFileType
;
1140 fileType
->m_impl
->SetFileType("image/tiff");
1141 fileType
->m_impl
->SetExt(ext
);
1144 else if ( ext
== "xpm" )
1146 wxFileType
*fileType
= new wxFileType
;
1147 fileType
->m_impl
->SetFileType("image/xpm");
1148 fileType
->m_impl
->SetExt(ext
);
1151 else if ( ext
== "xbm" )
1153 wxFileType
*fileType
= new wxFileType
;
1154 fileType
->m_impl
->SetFileType("image/xbm");
1155 fileType
->m_impl
->SetExt(ext
);
1159 // unknown extension
1163 // MIME type -> extension -> file type
1165 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1170 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1172 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1179 // ============================================================================
1180 // Unix implementation
1181 // ============================================================================
1183 // ----------------------------------------------------------------------------
1185 // ----------------------------------------------------------------------------
1187 static wxGNOMEIconHandler gs_iconHandlerGNOME
;
1188 static wxKDEIconHandler gs_iconHandlerKDE
;
1190 bool wxGNOMEIconHandler::m_inited
= FALSE
;
1191 wxSortedArrayString
wxGNOMEIconHandler::ms_mimetypes
;
1192 wxArrayString
wxGNOMEIconHandler::ms_icons
;
1194 bool wxKDEIconHandler::m_inited
= FALSE
;
1195 wxSortedArrayString
wxKDEIconHandler::ms_mimetypes
;
1196 wxArrayString
wxKDEIconHandler::ms_icons
;
1198 ArrayIconHandlers
wxMimeTypesManagerImpl::ms_iconHandlers
;
1200 // ----------------------------------------------------------------------------
1201 // wxGNOMEIconHandler
1202 // ----------------------------------------------------------------------------
1204 // GNOME stores the info we're interested in in several locations:
1205 // 1. xxx.keys files under /usr/share/mime-info
1206 // 2. xxx.keys files under ~/.gnome/mime-info
1208 // The format of xxx.keys file is the following:
1210 // mimetype/subtype:
1213 // with blank lines separating the entries and indented lines starting with
1214 // TABs. We're interested in the field icon-filename whose value is the path
1215 // containing the icon.
1217 void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString
& filename
)
1219 wxTextFile
textfile(filename
);
1220 if ( !textfile
.Open() )
1223 // values for the entry being parsed
1224 wxString curMimeType
, curIconFile
;
1227 size_t nLineCount
= textfile
.GetLineCount();
1228 for ( size_t nLine
= 0; ; nLine
++ )
1230 if ( nLine
< nLineCount
)
1232 pc
= textfile
[nLine
].c_str();
1233 if ( *pc
== _T('#') )
1241 // so that we will fall into the "if" below
1248 if ( !!curMimeType
&& !!curIconFile
)
1250 // do we already know this mimetype?
1251 int i
= ms_mimetypes
.Index(curMimeType
);
1252 if ( i
== wxNOT_FOUND
)
1255 size_t n
= ms_mimetypes
.Add(curMimeType
);
1256 ms_icons
.Insert(curIconFile
, n
);
1260 // replace the existing one (this means that the directories
1261 // should be searched in order of increased priority!)
1262 ms_icons
[(size_t)i
] = curIconFile
;
1268 // the end - this can only happen if nLine == nLineCount
1272 curIconFile
.Empty();
1277 // what do we have here?
1278 if ( *pc
== _T('\t') )
1280 // this is a field=value ling
1281 pc
++; // skip leading TAB
1283 static const int lenField
= 13; // strlen("icon-filename")
1284 if ( wxStrncmp(pc
, _T("icon-filename"), lenField
) == 0 )
1286 // skip '=' which follows and take everything left until the end
1288 curIconFile
= pc
+ lenField
+ 1;
1290 //else: some other field, we don't care
1294 // this is the start of the new section
1295 curMimeType
.Empty();
1297 while ( *pc
!= _T(':') && *pc
!= _T('\0') )
1299 curMimeType
+= *pc
++;
1304 // we reached the end of line without finding the colon,
1305 // something is wrong - ignore this line completely
1306 wxLogDebug(_T("Unreckognized line %d in file '%s' ignored"),
1307 nLine
+ 1, filename
.c_str());
1315 void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString
& dirbase
)
1317 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1318 _T("base directory shouldn't end with a slash") );
1320 wxString dirname
= dirbase
;
1321 dirname
<< _T("/mime-info");
1323 if ( !wxDir::Exists(dirname
) )
1327 if ( !dir
.IsOpened() )
1330 // we will concatenate it with filename to get the full path below
1334 bool cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
1337 LoadIconsFromKeyFile(dirname
+ filename
);
1339 cont
= dir
.GetNext(&filename
);
1343 void wxGNOMEIconHandler::Init()
1346 dirs
.Add(_T("/usr/share"));
1349 wxGetHomeDir( &gnomedir
);
1350 gnomedir
+= _T("/.gnome");
1351 dirs
.Add( gnomedir
);
1353 size_t nDirs
= dirs
.GetCount();
1354 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1356 LoadKeyFilesFromDir(dirs
[nDir
]);
1362 bool wxGNOMEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
1369 int index
= ms_mimetypes
.Index(mimetype
);
1370 if ( index
== wxNOT_FOUND
)
1373 wxString iconname
= ms_icons
[(size_t)index
];
1376 *icon
= wxIcon(iconname
);
1378 // helpful for testing in console mode
1379 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
1380 mimetype
.c_str(), iconname
.c_str());
1386 // ----------------------------------------------------------------------------
1388 // ----------------------------------------------------------------------------
1390 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
1391 // may be found in either of the following locations
1393 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
1394 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
1396 // The format of a .kdelnk file is almost the same as the one used by
1397 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
1398 // value for the entry "Type"
1400 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString
& dirbase
,
1401 const wxString
& subdir
,
1402 const wxString
& filename
)
1404 wxFFile
file(dirbase
+ filename
);
1405 if ( !file
.IsOpened() )
1408 // these files are small, slurp the entire file at once
1410 if ( !file
.ReadAll(&text
) )
1413 int pos
= text
.Find(_T("Icon="));
1414 if ( pos
== wxNOT_FOUND
)
1422 const wxChar
*pc
= text
.c_str() + pos
+ 5; // 5 == strlen("Icon=")
1423 while ( *pc
&& *pc
!= _T('\n') )
1430 // don't check that the file actually exists - would be too slow
1431 icon
.Prepend(_T("/usr/share/icons/"));
1433 // construct mimetype from the directory name and the basename of the
1434 // file (it always has .kdelnk extension)
1436 mimetype
<< subdir
<< _T('/') << filename
.BeforeLast(_T('.'));
1438 // do we already have this MIME type?
1439 int i
= ms_mimetypes
.Index(mimetype
);
1440 if ( i
== wxNOT_FOUND
)
1443 size_t n
= ms_mimetypes
.Add(mimetype
);
1444 ms_icons
.Insert(icon
, n
);
1448 // replace the old value
1449 ms_icons
[(size_t)i
] = icon
;
1454 void wxKDEIconHandler::LoadLinksForMimeType(const wxString
& dirbase
,
1455 const wxString
& subdir
)
1457 wxString dirname
= dirbase
;
1460 if ( !dir
.IsOpened() )
1466 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
1469 LoadLinksForMimeSubtype(dirname
, subdir
, filename
);
1471 cont
= dir
.GetNext(&filename
);
1475 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString
& dirbase
)
1477 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1478 _T("base directory shouldn't end with a slash") );
1480 wxString dirname
= dirbase
;
1481 dirname
<< _T("/mimelnk");
1483 if ( !wxDir::Exists(dirname
) )
1487 if ( !dir
.IsOpened() )
1490 // we will concatenate it with dir name to get the full path below
1494 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
1497 LoadLinksForMimeType(dirname
, subdir
);
1499 cont
= dir
.GetNext(&subdir
);
1503 void wxKDEIconHandler::Init()
1507 // the variable KDEDIR is set when KDE is running
1508 const char *kdedir
= getenv("KDEDIR");
1511 dirs
.Add(wxString(kdedir
) + _T("/share"));
1515 // try to guess KDEDIR
1516 dirs
.Add(_T("/usr/share"));
1517 dirs
.Add(_T("/opt/kde/share"));
1520 dirs
.Add(wxGetHomeDir() + _T("/.kde/share"));
1522 size_t nDirs
= dirs
.GetCount();
1523 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1525 LoadLinkFilesFromDir(dirs
[nDir
]);
1531 bool wxKDEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
1538 int index
= ms_mimetypes
.Index(mimetype
);
1539 if ( index
== wxNOT_FOUND
)
1542 wxString iconname
= ms_icons
[(size_t)index
];
1545 *icon
= wxIcon(iconname
);
1547 // helpful for testing in console mode
1548 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
1549 mimetype
.c_str(), iconname
.c_str());
1555 // ----------------------------------------------------------------------------
1556 // wxFileTypeImpl (Unix)
1557 // ----------------------------------------------------------------------------
1560 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
1563 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
1564 while ( entry
!= NULL
) {
1565 // notice that an empty command would always succeed (it's ok)
1566 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
1568 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
1570 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1571 command
.c_str(), params
.GetMimeType().c_str());
1575 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1576 command
.c_str(), params
.GetMimeType().c_str());
1579 entry
= entry
->GetNext();
1585 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
1588 (void)GetMimeType(&mimetype
);
1590 ArrayIconHandlers
& handlers
= m_manager
->GetIconHandlers();
1591 size_t count
= handlers
.GetCount();
1592 for ( size_t n
= 0; n
< count
; n
++ )
1594 if ( handlers
[n
]->GetIcon(mimetype
, icon
) )
1602 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
1603 const wxFileType::MessageParameters
& params
,
1606 MailCapEntry
*entry
= GetEntry(params
);
1607 if ( entry
== NULL
) {
1608 // all tests failed...
1612 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
1613 if ( cmd
.IsEmpty() ) {
1614 // may happen, especially for "print"
1618 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
1622 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1624 wxString strExtensions
= m_manager
->GetExtension(m_index
);
1627 // one extension in the space or comma delimitid list
1629 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
1630 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1631 if ( !strExt
.IsEmpty() ) {
1632 extensions
.Add(strExt
);
1635 //else: repeated spaces (shouldn't happen, but it's not that
1636 // important if it does happen)
1638 if ( *p
== wxT('\0') )
1641 else if ( *p
== wxT('.') ) {
1642 // remove the dot from extension (but only if it's the first char)
1643 if ( !strExt
.IsEmpty() ) {
1646 //else: no, don't append it
1656 // ----------------------------------------------------------------------------
1657 // wxMimeTypesManagerImpl (Unix)
1658 // ----------------------------------------------------------------------------
1661 ArrayIconHandlers
& wxMimeTypesManagerImpl::GetIconHandlers()
1663 if ( ms_iconHandlers
.GetCount() == 0 )
1665 ms_iconHandlers
.Add(&gs_iconHandlerGNOME
);
1666 ms_iconHandlers
.Add(&gs_iconHandlerKDE
);
1669 return ms_iconHandlers
;
1672 // read system and user mailcaps (TODO implement mime.types support)
1673 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1675 // directories where we look for mailcap and mime.types by default
1676 // (taken from metamail(1) sources)
1677 static const wxChar
*aStandardLocations
[] =
1681 wxT("/usr/local/etc"),
1683 wxT("/usr/public/lib")
1686 // first read the system wide file(s)
1687 for ( size_t n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
1688 wxString dir
= aStandardLocations
[n
];
1690 wxString file
= dir
+ wxT("/mailcap");
1691 if ( wxFile::Exists(file
) ) {
1695 file
= dir
+ wxT("/mime.types");
1696 if ( wxFile::Exists(file
) ) {
1697 ReadMimeTypes(file
);
1701 wxString strHome
= wxGetenv(wxT("HOME"));
1703 // and now the users mailcap
1704 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1705 if ( wxFile::Exists(strUserMailcap
) ) {
1706 ReadMailcap(strUserMailcap
);
1709 // read the users mime.types
1710 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
1711 if ( wxFile::Exists(strUserMimeTypes
) ) {
1712 ReadMimeTypes(strUserMimeTypes
);
1717 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1719 size_t count
= m_aExtensions
.GetCount();
1720 for ( size_t n
= 0; n
< count
; n
++ ) {
1721 wxString extensions
= m_aExtensions
[n
];
1722 while ( !extensions
.IsEmpty() ) {
1723 wxString field
= extensions
.BeforeFirst(wxT(' '));
1724 extensions
= extensions
.AfterFirst(wxT(' '));
1726 // consider extensions as not being case-sensitive
1727 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
1729 wxFileType
*fileType
= new wxFileType
;
1730 fileType
->m_impl
->Init(this, n
);
1742 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1744 // mime types are not case-sensitive
1745 wxString
mimetype(mimeType
);
1746 mimetype
.MakeLower();
1748 // first look for an exact match
1749 int index
= m_aTypes
.Index(mimetype
);
1750 if ( index
== wxNOT_FOUND
) {
1751 // then try to find "text/*" as match for "text/plain" (for example)
1752 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1753 // the whole string - ok.
1754 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1756 size_t nCount
= m_aTypes
.Count();
1757 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1758 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1759 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1766 if ( index
!= wxNOT_FOUND
) {
1767 wxFileType
*fileType
= new wxFileType
;
1768 fileType
->m_impl
->Init(this, index
);
1778 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1780 wxString extensions
;
1781 const wxArrayString
& exts
= filetype
.GetExtensions();
1782 size_t nExts
= exts
.GetCount();
1783 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1785 extensions
+= wxT(' ');
1787 extensions
+= exts
[nExt
];
1790 AddMimeTypeInfo(filetype
.GetMimeType(),
1792 filetype
.GetDescription());
1794 AddMailcapInfo(filetype
.GetMimeType(),
1795 filetype
.GetOpenCommand(),
1796 filetype
.GetPrintCommand(),
1798 filetype
.GetDescription());
1801 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
1802 const wxString
& strExtensions
,
1803 const wxString
& strDesc
)
1805 int index
= m_aTypes
.Index(strMimeType
);
1806 if ( index
== wxNOT_FOUND
) {
1808 m_aTypes
.Add(strMimeType
);
1809 m_aEntries
.Add(NULL
);
1810 m_aExtensions
.Add(strExtensions
);
1811 m_aDescriptions
.Add(strDesc
);
1814 // modify an existing one
1815 if ( !strDesc
.IsEmpty() ) {
1816 m_aDescriptions
[index
] = strDesc
; // replace old value
1818 m_aExtensions
[index
] += ' ' + strExtensions
;
1822 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
1823 const wxString
& strOpenCmd
,
1824 const wxString
& strPrintCmd
,
1825 const wxString
& strTest
,
1826 const wxString
& strDesc
)
1828 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1830 int nIndex
= m_aTypes
.Index(strType
);
1831 if ( nIndex
== wxNOT_FOUND
) {
1833 m_aTypes
.Add(strType
);
1835 m_aEntries
.Add(entry
);
1836 m_aExtensions
.Add(wxT(""));
1837 m_aDescriptions
.Add(strDesc
);
1840 // always append the entry in the tail of the list - info added with
1841 // this function can only come from AddFallbacks()
1842 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1844 entry
->Append(entryOld
);
1846 m_aEntries
[nIndex
] = entry
;
1850 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1852 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1854 wxTextFile
file(strFileName
);
1858 // the information we extract
1859 wxString strMimeType
, strDesc
, strExtensions
;
1861 size_t nLineCount
= file
.GetLineCount();
1862 const wxChar
*pc
= NULL
;
1863 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1865 // now we're at the start of the line
1866 pc
= file
[nLine
].c_str();
1869 // we didn't finish with the previous line yet
1874 while ( wxIsspace(*pc
) )
1877 // comment or blank line?
1878 if ( *pc
== wxT('#') || !*pc
) {
1879 // skip the whole line
1884 // detect file format
1885 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1886 if ( pEqualSign
== NULL
) {
1890 // first field is mime type
1891 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1896 while ( wxIsspace(*pc
) )
1899 // take all the rest of the string
1902 // no description...
1909 // the string on the left of '=' is the field name
1910 wxString
strLHS(pc
, pEqualSign
- pc
);
1913 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
1917 if ( *pc
== wxT('"') ) {
1918 // the string is quoted and ends at the matching quote
1919 pEnd
= wxStrchr(++pc
, wxT('"'));
1920 if ( pEnd
== NULL
) {
1921 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1923 strFileName
.c_str(), nLine
+ 1);
1927 // unquoted string ends at the first space
1928 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
1932 // now we have the RHS (field value)
1933 wxString
strRHS(pc
, pEnd
- pc
);
1935 // check what follows this entry
1936 if ( *pEnd
== wxT('"') ) {
1941 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
1944 // if there is something left, it may be either a '\\' to continue
1945 // the line or the next field of the same entry
1946 bool entryEnded
= *pc
== wxT('\0'),
1947 nextFieldOnSameLine
= FALSE
;
1948 if ( !entryEnded
) {
1949 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
1952 // now see what we got
1953 if ( strLHS
== wxT("type") ) {
1954 strMimeType
= strRHS
;
1956 else if ( strLHS
== wxT("desc") ) {
1959 else if ( strLHS
== wxT("exts") ) {
1960 strExtensions
= strRHS
;
1963 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1964 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
1967 if ( !entryEnded
) {
1968 if ( !nextFieldOnSameLine
)
1970 //else: don't reset it
1972 // as we don't reset strMimeType, the next field in this entry
1973 // will be interpreted correctly.
1979 // although it doesn't seem to be covered by RFCs, some programs
1980 // (notably Netscape) create their entries with several comma
1981 // separated extensions (RFC mention the spaces only)
1982 strExtensions
.Replace(wxT(","), wxT(" "));
1984 // also deal with the leading dot
1985 if ( !strExtensions
.IsEmpty() && strExtensions
[0u] == wxT('.') )
1987 strExtensions
.erase(0, 1);
1990 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
1992 // finished with this line
1996 // check our data integriry
1997 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1998 m_aTypes
.Count() == m_aExtensions
.Count() &&
1999 m_aTypes
.Count() == m_aDescriptions
.Count() );
2004 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2007 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
2009 wxTextFile
file(strFileName
);
2013 // see the comments near the end of function for the reason we need these
2014 // variables (search for the next occurence of them)
2015 // indices of MIME types (in m_aTypes) we already found in this file
2016 wxArrayInt aEntryIndices
;
2017 // aLastIndices[n] is the index of last element in
2018 // m_aEntries[aEntryIndices[n]] from this file
2019 wxArrayInt aLastIndices
;
2021 size_t nLineCount
= file
.GetLineCount();
2022 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
2023 // now we're at the start of the line
2024 const wxChar
*pc
= file
[nLine
].c_str();
2027 while ( wxIsspace(*pc
) )
2030 // comment or empty string?
2031 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2036 // what field are we currently in? The first 2 are fixed and there may
2037 // be an arbitrary number of other fields -- currently, we are not
2038 // interested in any of them, but we should parse them as well...
2044 } currentToken
= Field_Type
;
2046 // the flags and field values on the current line
2047 bool needsterminal
= FALSE
,
2048 copiousoutput
= FALSE
;
2054 curField
; // accumulator
2055 for ( bool cont
= TRUE
; cont
; pc
++ ) {
2058 // interpret the next character literally (notice that
2059 // backslash can be used for line continuation)
2060 if ( *++pc
== wxT('\0') ) {
2061 // fetch the next line.
2063 // pc currently points to nowhere, but after the next
2064 // pc++ in the for line it will point to the beginning
2065 // of the next line in the file
2066 pc
= file
[++nLine
].c_str() - 1;
2069 // just a normal character
2075 cont
= FALSE
; // end of line reached, exit the loop
2080 // store this field and start looking for the next one
2082 // trim whitespaces from both sides
2083 curField
.Trim(TRUE
).Trim(FALSE
);
2085 switch ( currentToken
) {
2088 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
2089 // we interpret "type" as "type/*"
2090 strType
+= wxT("/*");
2093 currentToken
= Field_OpenCmd
;
2097 strOpenCmd
= curField
;
2099 currentToken
= Field_Other
;
2104 // "good" mailcap entry?
2107 // is this something of the form foo=bar?
2108 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2109 if ( pEq
!= NULL
) {
2110 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2111 rhs
= curField
.AfterFirst(wxT('='));
2113 lhs
.Trim(TRUE
); // from right
2114 rhs
.Trim(FALSE
); // from left
2116 if ( lhs
== wxT("print") )
2118 else if ( lhs
== wxT("test") )
2120 else if ( lhs
== wxT("description") ) {
2121 // it might be quoted
2122 if ( rhs
[0u] == wxT('"') &&
2123 rhs
.Last() == wxT('"') ) {
2124 strDesc
= wxString(rhs
.c_str() + 1,
2131 else if ( lhs
== wxT("compose") ||
2132 lhs
== wxT("composetyped") ||
2133 lhs
== wxT("notes") ||
2134 lhs
== wxT("edit") )
2141 // no, it's a simple flag
2142 // TODO support the flags:
2143 // 1. create an xterm for 'needsterminal'
2144 // 2. append "| $PAGER" for 'copiousoutput'
2145 if ( curField
== wxT("needsterminal") )
2146 needsterminal
= TRUE
;
2147 else if ( curField
== wxT("copiousoutput") )
2148 copiousoutput
= TRUE
;
2149 else if ( curField
== wxT("textualnewlines") )
2157 // we don't understand this field, but
2158 // Netscape stores info in it, so don't warn
2160 if ( curField
.Left(16u) != "x-mozilla-flags=" )
2162 // don't flood the user with error
2163 // messages if we don't understand
2164 // something in his mailcap, but give
2165 // them in debug mode because this might
2166 // be useful for the programmer
2169 wxT("Mailcap file %s, line %d: "
2170 "unknown field '%s' for the "
2171 "MIME type '%s' ignored."),
2172 strFileName
.c_str(),
2181 // it already has this value
2182 //currentToken = Field_Other;
2186 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2189 // next token starts immediately after ';'
2198 // check that we really read something reasonable
2199 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
2200 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2202 strFileName
.c_str(), nLine
+ 1);
2205 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
2209 // NB: because of complications below (we must get entries priority
2210 // right), we can't use AddMailcapInfo() here, unfortunately.
2211 strType
.MakeLower();
2212 int nIndex
= m_aTypes
.Index(strType
);
2213 if ( nIndex
== wxNOT_FOUND
) {
2215 m_aTypes
.Add(strType
);
2217 m_aEntries
.Add(entry
);
2218 m_aExtensions
.Add(wxT(""));
2219 m_aDescriptions
.Add(strDesc
);
2222 // modify the existing entry: the entries in one and the same
2223 // file are read in top-to-bottom order, i.e. the entries read
2224 // first should be tried before the entries below. However,
2225 // the files read later should override the settings in the
2226 // files read before (except if fallback is TRUE), thus we
2227 // Insert() the new entry to the list if it has already
2228 // occured in _this_ file, but Prepend() it if it occured in
2229 // some of the previous ones and Append() to it in the
2233 // 'fallback' parameter prevents the entries from this
2234 // file from overriding the other ones - always append
2235 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
2237 entry
->Append(entryOld
);
2239 m_aEntries
[nIndex
] = entry
;
2242 int entryIndex
= aEntryIndices
.Index(nIndex
);
2243 if ( entryIndex
== wxNOT_FOUND
) {
2244 // first time in this file
2245 aEntryIndices
.Add(nIndex
);
2246 aLastIndices
.Add(0);
2248 entry
->Prepend(m_aEntries
[nIndex
]);
2249 m_aEntries
[nIndex
] = entry
;
2252 // not the first time in _this_ file
2253 size_t nEntryIndex
= (size_t)entryIndex
;
2254 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
2256 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
2258 m_aEntries
[nIndex
] = entry
;
2260 // the indices were shifted by 1
2261 aLastIndices
[nEntryIndex
]++;
2265 if ( !strDesc
.IsEmpty() ) {
2266 // replace the old one - what else can we do??
2267 m_aDescriptions
[nIndex
] = strDesc
;
2272 // check our data integriry
2273 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2274 m_aTypes
.Count() == m_aExtensions
.Count() &&
2275 m_aTypes
.Count() == m_aDescriptions
.Count() );
2281 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2286 size_t count
= m_aTypes
.GetCount();
2287 for ( size_t n
= 0; n
< count
; n
++ )
2289 // don't return template types from here (i.e. anything containg '*')
2291 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
2293 mimetypes
.Add(type
);
2297 return mimetypes
.GetCount();
2304 // wxUSE_FILE && wxUSE_TEXTFILE