1 /////////////////////////////////////////////////////////////////////////////
2 // Name: common/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "mimetype.h"
16 // for compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
27 #if (wxUSE_FILE && wxUSE_TEXTFILE) || defined(__WXMSW__)
30 #include "wx/string.h"
34 // Doesn't compile in WIN16 mode
40 #include "wx/dynarray.h"
41 #include "wx/confbase.h"
44 #include "wx/msw/registry.h"
47 #include "wx/textfile.h"
50 #include "wx/mimetype.h"
52 // other standard headers
55 // ----------------------------------------------------------------------------
57 // ----------------------------------------------------------------------------
59 // implementation classes, platform dependent
62 // These classes use Windows registry to retrieve the required information.
64 // Keys used (not all of them are documented, so it might actually stop working
65 // in futur versions of Windows...):
66 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
67 // types, each key has a string value "Extension" which gives (dot preceded)
68 // extension for the files of this MIME type.
70 // 2. "HKCR\.ext" contains
71 // a) unnamed value containing the "filetype"
72 // b) value "Content Type" containing the MIME type
74 // 3. "HKCR\filetype" contains
75 // a) unnamed value containing the description
76 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
78 // c) shell\open\command and shell\open\print subkeys containing the commands
79 // to open/print the file (the positional parameters are introduced by %1,
80 // %2, ... in these strings, we change them to %s ourselves)
82 // although I don't know of any official documentation which mentions this
83 // location, uses it, so it isn't likely to change
84 static const wxChar
*MIME_DATABASE_KEY
= wxT("MIME\\Database\\Content Type\\");
90 wxFileTypeImpl() { m_info
= NULL
; }
92 // one of these Init() function must be called (ctor can't take any
93 // arguments because it's common)
95 // initialize us with our file type name and extension - in this case
96 // we will read all other data from the registry
97 void Init(const wxString
& strFileType
, const wxString
& ext
)
98 { m_strFileType
= strFileType
; m_ext
= ext
; }
100 // initialize us with a wxFileTypeInfo object - it contains all the
102 void Init(const wxFileTypeInfo
& info
)
105 // implement accessor functions
106 bool GetExtensions(wxArrayString
& extensions
);
107 bool GetMimeType(wxString
*mimeType
) const;
108 bool GetIcon(wxIcon
*icon
) const;
109 bool GetDescription(wxString
*desc
) const;
110 bool GetOpenCommand(wxString
*openCmd
,
111 const wxFileType::MessageParameters
& params
) const;
112 bool GetPrintCommand(wxString
*printCmd
,
113 const wxFileType::MessageParameters
& params
) const;
116 // helper function: reads the command corresponding to the specified verb
117 // from the registry (returns an empty string if not found)
118 wxString
GetCommand(const wxChar
*verb
) const;
120 // we use either m_info or read the data from the registry if m_info == NULL
121 const wxFileTypeInfo
*m_info
;
122 wxString m_strFileType
,
126 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
127 #include "wx/arrimpl.cpp"
128 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
130 class wxMimeTypesManagerImpl
133 // nothing to do here, we don't load any data but just go and fetch it from
134 // the registry when asked for
135 wxMimeTypesManagerImpl() { }
137 // implement containing class functions
138 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
139 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
141 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
143 // this are NOPs under Windows
144 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
)
146 bool ReadMimeTypes(const wxString
& filename
)
149 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
152 wxArrayFileTypeInfo m_fallbacks
;
155 #elif defined( __WXMAC__ )
157 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo
, wxArrayFileTypeInfo
);
158 #include "wx/arrimpl.cpp"
159 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo
);
161 class wxMimeTypesManagerImpl
164 wxMimeTypesManagerImpl() { }
166 // implement containing class functions
167 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
168 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
170 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
172 // this are NOPs under MacOS
173 bool ReadMailcap(const wxString
& filename
, bool fallback
= TRUE
) { return TRUE
; }
174 bool ReadMimeTypes(const wxString
& filename
) { return TRUE
; }
176 void AddFallback(const wxFileTypeInfo
& ft
) { m_fallbacks
.Add(ft
); }
179 wxArrayFileTypeInfo m_fallbacks
;
185 // initialize us with our file type name
186 void SetFileType(const wxString
& strFileType
)
187 { m_strFileType
= strFileType
; }
188 void SetExt(const wxString
& ext
)
191 // implement accessor functions
192 bool GetExtensions(wxArrayString
& extensions
);
193 bool GetMimeType(wxString
*mimeType
) const;
194 bool GetIcon(wxIcon
*icon
) const;
195 bool GetDescription(wxString
*desc
) const;
196 bool GetOpenCommand(wxString
*openCmd
,
197 const wxFileType::MessageParameters
&) const
198 { return GetCommand(openCmd
, "open"); }
199 bool GetPrintCommand(wxString
*printCmd
,
200 const wxFileType::MessageParameters
&) const
201 { return GetCommand(printCmd
, "print"); }
205 bool GetCommand(wxString
*command
, const char *verb
) const;
207 wxString m_strFileType
, m_ext
;
212 // this class uses both mailcap and mime.types to gather information about file
215 // The information about mailcap file was extracted from metamail(1) sources and
218 // Format of mailcap file: spaces are ignored, each line is either a comment
219 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
220 // A backslash can be used to quote semicolons and newlines (and, in fact,
221 // anything else including itself).
223 // The first field is always the MIME type in the form of type/subtype (see RFC
224 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
225 // "type" which means the same as "type/*", although I'm not sure whether this
228 // The second field is always the command to run. It is subject to
229 // parameter/filename expansion described below.
231 // All the following fields are optional and may not be present at all. If
232 // they're present they may appear in any order, although each of them should
233 // appear only once. The optional fields are the following:
234 // * notes=xxx is an uninterpreted string which is silently ignored
235 // * test=xxx is the command to be used to determine whether this mailcap line
236 // applies to our data or not. The RHS of this field goes through the
237 // parameter/filename expansion (as the 2nd field) and the resulting string
238 // is executed. The line applies only if the command succeeds, i.e. returns 0
240 // * print=xxx is the command to be used to print (and not view) the data of
241 // this type (parameter/filename expansion is done here too)
242 // * edit=xxx is the command to open/edit the data of this type
243 // * needsterminal means that a new console must be created for the viewer
244 // * copiousoutput means that the viewer doesn't interact with the user but
245 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
246 // good example), thus it might be a good idea to use some kind of paging
248 // * textualnewlines means not to perform CR/LF translation (not honored)
249 // * compose and composetyped fields are used to determine the program to be
250 // called to create a new message pert in the specified format (unused).
252 // Parameter/filename xpansion:
253 // * %s is replaced with the (full) file name
254 // * %t is replaced with MIME type/subtype of the entry
255 // * for multipart type only %n is replaced with the nnumber of parts and %F is
256 // replaced by an array of (content-type, temporary file name) pairs for all
257 // message parts (TODO)
258 // * %{parameter} is replaced with the value of parameter taken from
259 // Content-type header line of the message.
261 // FIXME any docs with real descriptions of these files??
263 // There are 2 possible formats for mime.types file, one entry per line (used
264 // for global mime.types) and "expanded" format where an entry takes multiple
265 // lines (used for users mime.types).
267 // For both formats spaces are ignored and lines starting with a '#' are
268 // comments. Each record has one of two following forms:
269 // a) for "brief" format:
270 // <mime type> <space separated list of extensions>
271 // b) for "expanded" format:
272 // type=<mime type> \ desc="<description>" \ exts="ext"
274 // We try to autodetect the format of mime.types: if a non-comment line starts
275 // with "type=" we assume the second format, otherwise the first one.
277 // there may be more than one entry for one and the same mime type, to
278 // choose the right one we have to run the command specified in the test
279 // field on our data.
284 MailCapEntry(const wxString
& openCmd
,
285 const wxString
& printCmd
,
286 const wxString
& testCmd
)
287 : m_openCmd(openCmd
), m_printCmd(printCmd
), m_testCmd(testCmd
)
293 const wxString
& GetOpenCmd() const { return m_openCmd
; }
294 const wxString
& GetPrintCmd() const { return m_printCmd
; }
295 const wxString
& GetTestCmd() const { return m_testCmd
; }
297 MailCapEntry
*GetNext() const { return m_next
; }
300 // prepend this element to the list
301 void Prepend(MailCapEntry
*next
) { m_next
= next
; }
302 // insert into the list at given position
303 void Insert(MailCapEntry
*next
, size_t pos
)
308 for ( cur
= next
; cur
!= NULL
; cur
= cur
->m_next
, n
++ ) {
313 wxASSERT_MSG( n
== pos
, wxT("invalid position in MailCapEntry::Insert") );
315 m_next
= cur
->m_next
;
318 // append this element to the list
319 void Append(MailCapEntry
*next
)
321 wxCHECK_RET( next
!= NULL
, wxT("Append()ing to what?") );
325 for ( cur
= next
; cur
->m_next
!= NULL
; cur
= cur
->m_next
)
330 wxASSERT_MSG( !m_next
, wxT("Append()ing element already in the list?") );
334 wxString m_openCmd
, // command to use to open/view the file
336 m_testCmd
; // only apply this entry if test yields
337 // true (i.e. the command returns 0)
339 MailCapEntry
*m_next
; // in the linked list
342 WX_DEFINE_ARRAY(MailCapEntry
*, ArrayTypeEntries
);
344 class wxMimeTypesManagerImpl
346 friend class wxFileTypeImpl
; // give it access to m_aXXX variables
349 // ctor loads all info into memory for quicker access later on
350 // TODO it would be nice to load them all, but parse on demand only...
351 wxMimeTypesManagerImpl();
353 // implement containing class functions
354 wxFileType
*GetFileTypeFromExtension(const wxString
& ext
);
355 wxFileType
*GetFileTypeFromMimeType(const wxString
& mimeType
);
357 size_t EnumAllFileTypes(wxArrayString
& mimetypes
);
359 bool ReadMailcap(const wxString
& filename
, bool fallback
= FALSE
);
360 bool ReadMimeTypes(const wxString
& filename
);
362 void AddFallback(const wxFileTypeInfo
& filetype
);
364 // add information about the given mimetype
365 void AddMimeTypeInfo(const wxString
& mimetype
,
366 const wxString
& extensions
,
367 const wxString
& description
);
368 void AddMailcapInfo(const wxString
& strType
,
369 const wxString
& strOpenCmd
,
370 const wxString
& strPrintCmd
,
371 const wxString
& strTest
,
372 const wxString
& strDesc
);
375 // get the string containing space separated extensions for the given
377 wxString
GetExtension(size_t index
) { return m_aExtensions
[index
]; }
380 wxArrayString m_aTypes
, // MIME types
381 m_aDescriptions
, // descriptions (just some text)
382 m_aExtensions
; // space separated list of extensions
383 ArrayTypeEntries m_aEntries
; // commands and tests for this file type
389 // initialization functions
390 void Init(wxMimeTypesManagerImpl
*manager
, size_t index
)
391 { m_manager
= manager
; m_index
= index
; }
394 bool GetExtensions(wxArrayString
& extensions
);
395 bool GetMimeType(wxString
*mimeType
) const
396 { *mimeType
= m_manager
->m_aTypes
[m_index
]; return TRUE
; }
397 bool GetIcon(wxIcon
* WXUNUSED(icon
)) const
398 { return FALSE
; } // TODO maybe with Gnome/KDE integration...
399 bool GetDescription(wxString
*desc
) const
400 { *desc
= m_manager
->m_aDescriptions
[m_index
]; return TRUE
; }
402 bool GetOpenCommand(wxString
*openCmd
,
403 const wxFileType::MessageParameters
& params
) const
405 return GetExpandedCommand(openCmd
, params
, TRUE
);
408 bool GetPrintCommand(wxString
*printCmd
,
409 const wxFileType::MessageParameters
& params
) const
411 return GetExpandedCommand(printCmd
, params
, FALSE
);
415 // get the entry which passes the test (may return NULL)
416 MailCapEntry
*GetEntry(const wxFileType::MessageParameters
& params
) const;
418 // choose the correct entry to use and expand the command
419 bool GetExpandedCommand(wxString
*expandedCmd
,
420 const wxFileType::MessageParameters
& params
,
423 wxMimeTypesManagerImpl
*m_manager
;
424 size_t m_index
; // in the wxMimeTypesManagerImpl arrays
429 // ============================================================================
431 // ============================================================================
433 // ----------------------------------------------------------------------------
435 // ----------------------------------------------------------------------------
437 wxFileTypeInfo::wxFileTypeInfo(const char *mimeType
,
439 const char *printCmd
,
442 : m_mimeType(mimeType
),
444 m_printCmd(printCmd
),
448 va_start(argptr
, desc
);
452 const char *ext
= va_arg(argptr
, const char *);
455 // NULL terminates the list
465 // ============================================================================
466 // implementation of the wrapper classes
467 // ============================================================================
469 // ----------------------------------------------------------------------------
471 // ----------------------------------------------------------------------------
473 wxString
wxFileType::ExpandCommand(const wxString
& command
,
474 const wxFileType::MessageParameters
& params
)
476 bool hasFilename
= FALSE
;
479 for ( const wxChar
*pc
= command
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
480 if ( *pc
== wxT('%') ) {
483 // '%s' expands into file name (quoted because it might
484 // contain spaces) - except if there are already quotes
485 // there because otherwise some programs may get confused
486 // by double double quotes
488 if ( *(pc
- 2) == wxT('"') )
489 str
<< params
.GetFileName();
491 str
<< wxT('"') << params
.GetFileName() << wxT('"');
493 str
<< params
.GetFileName();
498 // '%t' expands into MIME type (quote it too just to be
500 str
<< wxT('\'') << params
.GetMimeType() << wxT('\'');
505 const wxChar
*pEnd
= wxStrchr(pc
, wxT('}'));
506 if ( pEnd
== NULL
) {
508 wxLogWarning(_("Unmatched '{' in an entry for "
510 params
.GetMimeType().c_str());
514 wxString
param(pc
+ 1, pEnd
- pc
- 1);
515 str
<< wxT('\'') << params
.GetParamValue(param
) << wxT('\'');
523 // TODO %n is the number of parts, %F is an array containing
524 // the names of temp files these parts were written to
525 // and their mime types.
529 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
530 *pc
, command
.c_str());
539 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
540 // the program will accept the data on stdin: so give it to it!
541 if ( !hasFilename
&& !str
.IsEmpty() ) {
542 str
<< wxT(" < '") << params
.GetFileName() << wxT('\'');
548 wxFileType::wxFileType()
550 m_impl
= new wxFileTypeImpl
;
553 wxFileType::~wxFileType()
558 bool wxFileType::GetExtensions(wxArrayString
& extensions
)
560 return m_impl
->GetExtensions(extensions
);
563 bool wxFileType::GetMimeType(wxString
*mimeType
) const
565 return m_impl
->GetMimeType(mimeType
);
568 bool wxFileType::GetIcon(wxIcon
*icon
) const
570 return m_impl
->GetIcon(icon
);
573 bool wxFileType::GetDescription(wxString
*desc
) const
575 return m_impl
->GetDescription(desc
);
579 wxFileType::GetOpenCommand(wxString
*openCmd
,
580 const wxFileType::MessageParameters
& params
) const
582 return m_impl
->GetOpenCommand(openCmd
, params
);
586 wxFileType::GetPrintCommand(wxString
*printCmd
,
587 const wxFileType::MessageParameters
& params
) const
589 return m_impl
->GetPrintCommand(printCmd
, params
);
592 // ----------------------------------------------------------------------------
593 // wxMimeTypesManager
594 // ----------------------------------------------------------------------------
596 bool wxMimeTypesManager::IsOfType(const wxString
& mimeType
,
597 const wxString
& wildcard
)
599 wxASSERT_MSG( mimeType
.Find(wxT('*')) == wxNOT_FOUND
,
600 wxT("first MIME type can't contain wildcards") );
602 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
603 if ( wildcard
.BeforeFirst(wxT('/')).IsSameAs(mimeType
.BeforeFirst(wxT('/')), FALSE
) )
605 wxString strSubtype
= wildcard
.AfterFirst(wxT('/'));
607 if ( strSubtype
== wxT("*") ||
608 strSubtype
.IsSameAs(mimeType
.AfterFirst(wxT('/')), FALSE
) )
610 // matches (either exactly or it's a wildcard)
618 wxMimeTypesManager::wxMimeTypesManager()
620 m_impl
= new wxMimeTypesManagerImpl
;
623 wxMimeTypesManager::~wxMimeTypesManager()
629 wxMimeTypesManager::GetFileTypeFromExtension(const wxString
& ext
)
631 return m_impl
->GetFileTypeFromExtension(ext
);
635 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString
& mimeType
)
637 return m_impl
->GetFileTypeFromMimeType(mimeType
);
640 bool wxMimeTypesManager::ReadMailcap(const wxString
& filename
, bool fallback
)
642 return m_impl
->ReadMailcap(filename
, fallback
);
645 bool wxMimeTypesManager::ReadMimeTypes(const wxString
& filename
)
647 return m_impl
->ReadMimeTypes(filename
);
650 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo
*filetypes
)
652 for ( const wxFileTypeInfo
*ft
= filetypes
; ft
->IsValid(); ft
++ ) {
653 m_impl
->AddFallback(*ft
);
657 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString
& mimetypes
)
659 return m_impl
->EnumAllFileTypes(mimetypes
);
662 // ============================================================================
663 // real (OS specific) implementation
664 // ============================================================================
668 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
670 // suppress possible error messages
673 strKey
<< m_strFileType
<< wxT("\\shell\\") << verb
<< wxT("\\command");
674 wxRegKey
key(wxRegKey::HKCR
, strKey
);
678 // it's the default value of the key
679 if ( key
.QueryValue(wxT(""), command
) ) {
680 // transform it from '%1' to '%s' style format string
682 // NB: we don't make any attempt to verify that the string is valid,
683 // i.e. doesn't contain %2, or second %1 or .... But we do make
684 // sure that we return a string with _exactly_ one '%s'!
685 bool foundFilename
= FALSE
;
686 size_t len
= command
.Len();
687 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
688 if ( command
[n
] == wxT('%') &&
689 (n
+ 1 < len
) && command
[n
+ 1] == wxT('1') ) {
690 // replace it with '%s'
691 command
[n
+ 1] = wxT('s');
693 foundFilename
= TRUE
;
697 if ( !foundFilename
) {
698 // we didn't find any '%1'!
699 // HACK: append the filename at the end, hope that it will do
700 command
<< wxT(" %s");
705 // no such file type or no value
710 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
711 const wxFileType::MessageParameters
& params
)
716 cmd
= m_info
->GetOpenCommand();
719 cmd
= GetCommand(wxT("open"));
722 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
724 return !openCmd
->IsEmpty();
728 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
729 const wxFileType::MessageParameters
& params
)
734 cmd
= m_info
->GetPrintCommand();
737 cmd
= GetCommand(wxT("print"));
740 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
742 return !printCmd
->IsEmpty();
745 // TODO this function is half implemented
746 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
749 extensions
= m_info
->GetExtensions();
753 else if ( m_ext
.IsEmpty() ) {
754 // the only way to get the list of extensions from the file type is to
755 // scan through all extensions in the registry - too slow...
760 extensions
.Add(m_ext
);
762 // it's a lie too, we don't return _all_ extensions...
767 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
770 // we already have it
771 *mimeType
= m_info
->GetMimeType();
776 // suppress possible error messages
778 wxRegKey
key(wxRegKey::HKCR
, /*m_strFileType*/ wxT(".") + m_ext
);
779 if ( key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
) ) {
787 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
791 // we don't have icons in the fallback resources
796 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
798 // suppress possible error messages
800 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
804 // it's the default value of the key
805 if ( key
.QueryValue(wxT(""), strIcon
) ) {
806 // the format is the following: <full path to file>, <icon index>
807 // NB: icon index may be negative as well as positive and the full
808 // path may contain the environment variables inside '%'
809 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
810 strIndex
= strIcon
.AfterLast(wxT(','));
812 // index may be omitted, in which case BeforeLast(',') is empty and
813 // AfterLast(',') is the whole string
814 if ( strFullPath
.IsEmpty() ) {
815 strFullPath
= strIndex
;
819 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
820 int nIndex
= wxAtoi(strIndex
);
822 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
823 switch ( (int)hIcon
) {
824 case 0: // means no icons were found
825 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
826 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
827 key
.GetName().c_str());
831 icon
->SetHICON((WXHICON
)hIcon
);
837 // no such file type or no value or incorrect icon entry
843 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
846 // we already have it
847 *desc
= m_info
->GetDescription();
852 // suppress possible error messages
854 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
857 // it's the default value of the key
858 if ( key
.QueryValue(wxT(""), *desc
) ) {
866 // extension -> file type
868 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
870 // add the leading point if necessary
872 if ( ext
[0u] != wxT('.') ) {
877 // suppress possible error messages
880 wxString strFileType
;
881 wxRegKey
key(wxRegKey::HKCR
, str
);
883 // it's the default value of the key
884 if ( key
.QueryValue(wxT(""), strFileType
) ) {
885 // create the new wxFileType object
886 wxFileType
*fileType
= new wxFileType
;
887 fileType
->m_impl
->Init(strFileType
, ext
);
893 // check the fallbacks
894 // TODO linear search is potentially slow, perhaps we should use a sorted
896 size_t count
= m_fallbacks
.GetCount();
897 for ( size_t n
= 0; n
< count
; n
++ ) {
898 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
899 wxFileType
*fileType
= new wxFileType
;
900 fileType
->m_impl
->Init(m_fallbacks
[n
]);
910 // MIME type -> extension -> file type
912 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
914 wxString strKey
= MIME_DATABASE_KEY
;
917 // suppress possible error messages
921 wxRegKey
key(wxRegKey::HKCR
, strKey
);
923 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
924 return GetFileTypeFromExtension(ext
);
928 // check the fallbacks
929 // TODO linear search is potentially slow, perhaps we should use a sorted
931 size_t count
= m_fallbacks
.GetCount();
932 for ( size_t n
= 0; n
< count
; n
++ ) {
933 if ( wxMimeTypesManager::IsOfType(mimeType
,
934 m_fallbacks
[n
].GetMimeType()) ) {
935 wxFileType
*fileType
= new wxFileType
;
936 fileType
->m_impl
->Init(m_fallbacks
[n
]);
946 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
948 // enumerate all keys under MIME_DATABASE_KEY
949 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
953 bool cont
= key
.GetFirstKey(type
, cookie
);
958 cont
= key
.GetNextKey(type
, cookie
);
961 return mimetypes
.GetCount();
964 #elif defined ( __WXMAC__ )
966 bool wxFileTypeImpl::GetCommand(wxString
*command
, const char *verb
) const
971 // @@ this function is half implemented
972 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
977 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
979 if ( m_strFileType
.Length() > 0 )
981 *mimeType
= m_strFileType
;
988 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
990 // no such file type or no value or incorrect icon entry
994 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
999 // extension -> file type
1001 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& e
)
1007 wxFileType
*fileType
= new wxFileType
;
1008 fileType
->m_impl
->SetFileType("text/text");
1009 fileType
->m_impl
->SetExt(ext
);
1012 else if ( ext
== "htm" || ext
== "html" )
1014 wxFileType
*fileType
= new wxFileType
;
1015 fileType
->m_impl
->SetFileType("text/html");
1016 fileType
->m_impl
->SetExt(ext
);
1019 else if ( ext
== "gif" )
1021 wxFileType
*fileType
= new wxFileType
;
1022 fileType
->m_impl
->SetFileType("image/gif");
1023 fileType
->m_impl
->SetExt(ext
);
1026 else if ( ext
== "png" )
1028 wxFileType
*fileType
= new wxFileType
;
1029 fileType
->m_impl
->SetFileType("image/png");
1030 fileType
->m_impl
->SetExt(ext
);
1033 else if ( ext
== "jpg" || ext
== "jpeg" )
1035 wxFileType
*fileType
= new wxFileType
;
1036 fileType
->m_impl
->SetFileType("image/jpeg");
1037 fileType
->m_impl
->SetExt(ext
);
1040 else if ( ext
== "bmp" )
1042 wxFileType
*fileType
= new wxFileType
;
1043 fileType
->m_impl
->SetFileType("image/bmp");
1044 fileType
->m_impl
->SetExt(ext
);
1047 else if ( ext
== "tif" || ext
== "tiff" )
1049 wxFileType
*fileType
= new wxFileType
;
1050 fileType
->m_impl
->SetFileType("image/tiff");
1051 fileType
->m_impl
->SetExt(ext
);
1054 else if ( ext
== "xpm" )
1056 wxFileType
*fileType
= new wxFileType
;
1057 fileType
->m_impl
->SetFileType("image/xpm");
1058 fileType
->m_impl
->SetExt(ext
);
1061 else if ( ext
== "xbm" )
1063 wxFileType
*fileType
= new wxFileType
;
1064 fileType
->m_impl
->SetFileType("image/xbm");
1065 fileType
->m_impl
->SetExt(ext
);
1069 // unknown extension
1073 // MIME type -> extension -> file type
1075 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1080 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1082 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1090 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
1093 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
1094 while ( entry
!= NULL
) {
1095 // notice that an empty command would always succeed (it's ok)
1096 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
1098 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
1100 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1101 command
.c_str(), params
.GetMimeType().c_str());
1105 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1106 command
.c_str(), params
.GetMimeType().c_str());
1109 entry
= entry
->GetNext();
1116 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
1117 const wxFileType::MessageParameters
& params
,
1120 MailCapEntry
*entry
= GetEntry(params
);
1121 if ( entry
== NULL
) {
1122 // all tests failed...
1126 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
1127 if ( cmd
.IsEmpty() ) {
1128 // may happen, especially for "print"
1132 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
1136 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1138 wxString strExtensions
= m_manager
->GetExtension(m_index
);
1141 // one extension in the space or comma delimitid list
1143 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
1144 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1145 if ( !strExt
.IsEmpty() ) {
1146 extensions
.Add(strExt
);
1149 //else: repeated spaces (shouldn't happen, but it's not that
1150 // important if it does happen)
1152 if ( *p
== wxT('\0') )
1155 else if ( *p
== wxT('.') ) {
1156 // remove the dot from extension (but only if it's the first char)
1157 if ( !strExt
.IsEmpty() ) {
1160 //else: no, don't append it
1170 // read system and user mailcaps (TODO implement mime.types support)
1171 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1173 // directories where we look for mailcap and mime.types by default
1174 // (taken from metamail(1) sources)
1175 static const wxChar
*aStandardLocations
[] =
1179 wxT("/usr/local/etc"),
1181 wxT("/usr/public/lib")
1184 // first read the system wide file(s)
1185 for ( size_t n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
1186 wxString dir
= aStandardLocations
[n
];
1188 wxString file
= dir
+ wxT("/mailcap");
1189 if ( wxFile::Exists(file
) ) {
1193 file
= dir
+ wxT("/mime.types");
1194 if ( wxFile::Exists(file
) ) {
1195 ReadMimeTypes(file
);
1199 wxString strHome
= wxGetenv(wxT("HOME"));
1201 // and now the users mailcap
1202 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1203 if ( wxFile::Exists(strUserMailcap
) ) {
1204 ReadMailcap(strUserMailcap
);
1207 // read the users mime.types
1208 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
1209 if ( wxFile::Exists(strUserMimeTypes
) ) {
1210 ReadMimeTypes(strUserMimeTypes
);
1215 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1217 size_t count
= m_aExtensions
.GetCount();
1218 for ( size_t n
= 0; n
< count
; n
++ ) {
1219 wxString extensions
= m_aExtensions
[n
];
1220 while ( !extensions
.IsEmpty() ) {
1221 wxString field
= extensions
.BeforeFirst(wxT(' '));
1222 extensions
= extensions
.AfterFirst(wxT(' '));
1224 // consider extensions as not being case-sensitive
1225 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
1227 wxFileType
*fileType
= new wxFileType
;
1228 fileType
->m_impl
->Init(this, n
);
1240 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1242 // mime types are not case-sensitive
1243 wxString
mimetype(mimeType
);
1244 mimetype
.MakeLower();
1246 // first look for an exact match
1247 int index
= m_aTypes
.Index(mimetype
);
1248 if ( index
== wxNOT_FOUND
) {
1249 // then try to find "text/*" as match for "text/plain" (for example)
1250 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1251 // the whole string - ok.
1252 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1254 size_t nCount
= m_aTypes
.Count();
1255 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1256 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1257 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1264 if ( index
!= wxNOT_FOUND
) {
1265 wxFileType
*fileType
= new wxFileType
;
1266 fileType
->m_impl
->Init(this, index
);
1276 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1278 wxString extensions
;
1279 const wxArrayString
& exts
= filetype
.GetExtensions();
1280 size_t nExts
= exts
.GetCount();
1281 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1283 extensions
+= wxT(' ');
1285 extensions
+= exts
[nExt
];
1288 AddMimeTypeInfo(filetype
.GetMimeType(),
1290 filetype
.GetDescription());
1292 AddMailcapInfo(filetype
.GetMimeType(),
1293 filetype
.GetOpenCommand(),
1294 filetype
.GetPrintCommand(),
1296 filetype
.GetDescription());
1299 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
1300 const wxString
& strExtensions
,
1301 const wxString
& strDesc
)
1303 int index
= m_aTypes
.Index(strMimeType
);
1304 if ( index
== wxNOT_FOUND
) {
1306 m_aTypes
.Add(strMimeType
);
1307 m_aEntries
.Add(NULL
);
1308 m_aExtensions
.Add(strExtensions
);
1309 m_aDescriptions
.Add(strDesc
);
1312 // modify an existing one
1313 if ( !strDesc
.IsEmpty() ) {
1314 m_aDescriptions
[index
] = strDesc
; // replace old value
1316 m_aExtensions
[index
] += ' ' + strExtensions
;
1320 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
1321 const wxString
& strOpenCmd
,
1322 const wxString
& strPrintCmd
,
1323 const wxString
& strTest
,
1324 const wxString
& strDesc
)
1326 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1328 int nIndex
= m_aTypes
.Index(strType
);
1329 if ( nIndex
== wxNOT_FOUND
) {
1331 m_aTypes
.Add(strType
);
1333 m_aEntries
.Add(entry
);
1334 m_aExtensions
.Add(wxT(""));
1335 m_aDescriptions
.Add(strDesc
);
1338 // always append the entry in the tail of the list - info added with
1339 // this function can only come from AddFallbacks()
1340 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1342 entry
->Append(entryOld
);
1344 m_aEntries
[nIndex
] = entry
;
1348 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1350 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1352 wxTextFile
file(strFileName
);
1356 // the information we extract
1357 wxString strMimeType
, strDesc
, strExtensions
;
1359 size_t nLineCount
= file
.GetLineCount();
1360 const wxChar
*pc
= NULL
;
1361 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1363 // now we're at the start of the line
1364 pc
= file
[nLine
].c_str();
1367 // we didn't finish with the previous line yet
1372 while ( wxIsspace(*pc
) )
1376 if ( *pc
== wxT('#') ) {
1377 // skip the whole line
1382 // detect file format
1383 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1384 if ( pEqualSign
== NULL
) {
1388 // first field is mime type
1389 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1394 while ( wxIsspace(*pc
) )
1397 // take all the rest of the string
1400 // no description...
1407 // the string on the left of '=' is the field name
1408 wxString
strLHS(pc
, pEqualSign
- pc
);
1411 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
1415 if ( *pc
== wxT('"') ) {
1416 // the string is quoted and ends at the matching quote
1417 pEnd
= wxStrchr(++pc
, wxT('"'));
1418 if ( pEnd
== NULL
) {
1419 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1421 strFileName
.c_str(), nLine
+ 1);
1425 // unquoted string ends at the first space
1426 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
1430 // now we have the RHS (field value)
1431 wxString
strRHS(pc
, pEnd
- pc
);
1433 // check what follows this entry
1434 if ( *pEnd
== wxT('"') ) {
1439 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
1442 // if there is something left, it may be either a '\\' to continue
1443 // the line or the next field of the same entry
1444 bool entryEnded
= *pc
== wxT('\0'),
1445 nextFieldOnSameLine
= FALSE
;
1446 if ( !entryEnded
) {
1447 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
1450 // now see what we got
1451 if ( strLHS
== wxT("type") ) {
1452 strMimeType
= strRHS
;
1454 else if ( strLHS
== wxT("desc") ) {
1457 else if ( strLHS
== wxT("exts") ) {
1458 strExtensions
= strRHS
;
1461 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1462 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
1465 if ( !entryEnded
) {
1466 if ( !nextFieldOnSameLine
)
1468 //else: don't reset it
1470 // as we don't reset strMimeType, the next field in this entry
1471 // will be interpreted correctly.
1477 // although it doesn't seem to be covered by RFCs, some programs
1478 // (notably Netscape) create their entries with several comma
1479 // separated extensions (RFC mention the spaces only)
1480 strExtensions
.Replace(wxT(","), wxT(" "));
1482 // also deal with the leading dot
1483 if ( !strExtensions
.IsEmpty() && strExtensions
[0u] == wxT('.') )
1485 strExtensions
.erase(0, 1);
1488 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
1490 // finished with this line
1494 // check our data integriry
1495 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1496 m_aTypes
.Count() == m_aExtensions
.Count() &&
1497 m_aTypes
.Count() == m_aDescriptions
.Count() );
1502 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
1505 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
1507 wxTextFile
file(strFileName
);
1511 // see the comments near the end of function for the reason we need these
1512 // variables (search for the next occurence of them)
1513 // indices of MIME types (in m_aTypes) we already found in this file
1514 wxArrayInt aEntryIndices
;
1515 // aLastIndices[n] is the index of last element in
1516 // m_aEntries[aEntryIndices[n]] from this file
1517 wxArrayInt aLastIndices
;
1519 size_t nLineCount
= file
.GetLineCount();
1520 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1521 // now we're at the start of the line
1522 const wxChar
*pc
= file
[nLine
].c_str();
1525 while ( wxIsspace(*pc
) )
1528 // comment or empty string?
1529 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
1534 // what field are we currently in? The first 2 are fixed and there may
1535 // be an arbitrary number of other fields -- currently, we are not
1536 // interested in any of them, but we should parse them as well...
1542 } currentToken
= Field_Type
;
1544 // the flags and field values on the current line
1545 bool needsterminal
= FALSE
,
1546 copiousoutput
= FALSE
;
1552 curField
; // accumulator
1553 for ( bool cont
= TRUE
; cont
; pc
++ ) {
1556 // interpret the next character literally (notice that
1557 // backslash can be used for line continuation)
1558 if ( *++pc
== wxT('\0') ) {
1559 // fetch the next line.
1561 // pc currently points to nowhere, but after the next
1562 // pc++ in the for line it will point to the beginning
1563 // of the next line in the file
1564 pc
= file
[++nLine
].c_str() - 1;
1567 // just a normal character
1573 cont
= FALSE
; // end of line reached, exit the loop
1578 // store this field and start looking for the next one
1580 // trim whitespaces from both sides
1581 curField
.Trim(TRUE
).Trim(FALSE
);
1583 switch ( currentToken
) {
1586 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
1587 // we interpret "type" as "type/*"
1588 strType
+= wxT("/*");
1591 currentToken
= Field_OpenCmd
;
1595 strOpenCmd
= curField
;
1597 currentToken
= Field_Other
;
1602 // "good" mailcap entry?
1605 // is this something of the form foo=bar?
1606 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
1607 if ( pEq
!= NULL
) {
1608 wxString lhs
= curField
.BeforeFirst(wxT('=')),
1609 rhs
= curField
.AfterFirst(wxT('='));
1611 lhs
.Trim(TRUE
); // from right
1612 rhs
.Trim(FALSE
); // from left
1614 if ( lhs
== wxT("print") )
1616 else if ( lhs
== wxT("test") )
1618 else if ( lhs
== wxT("description") ) {
1619 // it might be quoted
1620 if ( rhs
[0u] == wxT('"') &&
1621 rhs
.Last() == wxT('"') ) {
1622 strDesc
= wxString(rhs
.c_str() + 1,
1629 else if ( lhs
== wxT("compose") ||
1630 lhs
== wxT("composetyped") ||
1631 lhs
== wxT("notes") ||
1632 lhs
== wxT("edit") )
1639 // no, it's a simple flag
1640 // TODO support the flags:
1641 // 1. create an xterm for 'needsterminal'
1642 // 2. append "| $PAGER" for 'copiousoutput'
1643 if ( curField
== wxT("needsterminal") )
1644 needsterminal
= TRUE
;
1645 else if ( curField
== wxT("copiousoutput") )
1646 copiousoutput
= TRUE
;
1647 else if ( curField
== wxT("textualnewlines") )
1655 // don't flood the user with error messages
1656 // if we don't understand something in his
1657 // mailcap, but give them in debug mode
1658 // because this might be useful for the
1662 wxT("Mailcap file %s, line %d: unknown "
1663 "field '%s' for the MIME type "
1665 strFileName
.c_str(),
1673 // it already has this value
1674 //currentToken = Field_Other;
1678 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1681 // next token starts immediately after ';'
1690 // check that we really read something reasonable
1691 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
1692 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1694 strFileName
.c_str(), nLine
+ 1);
1697 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
1701 // NB: because of complications below (we must get entries priority
1702 // right), we can't use AddMailcapInfo() here, unfortunately.
1703 strType
.MakeLower();
1704 int nIndex
= m_aTypes
.Index(strType
);
1705 if ( nIndex
== wxNOT_FOUND
) {
1707 m_aTypes
.Add(strType
);
1709 m_aEntries
.Add(entry
);
1710 m_aExtensions
.Add(wxT(""));
1711 m_aDescriptions
.Add(strDesc
);
1714 // modify the existing entry: the entries in one and the same
1715 // file are read in top-to-bottom order, i.e. the entries read
1716 // first should be tried before the entries below. However,
1717 // the files read later should override the settings in the
1718 // files read before (except if fallback is TRUE), thus we
1719 // Insert() the new entry to the list if it has already
1720 // occured in _this_ file, but Prepend() it if it occured in
1721 // some of the previous ones and Append() to it in the
1725 // 'fallback' parameter prevents the entries from this
1726 // file from overriding the other ones - always append
1727 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1729 entry
->Append(entryOld
);
1731 m_aEntries
[nIndex
] = entry
;
1734 int entryIndex
= aEntryIndices
.Index(nIndex
);
1735 if ( entryIndex
== wxNOT_FOUND
) {
1736 // first time in this file
1737 aEntryIndices
.Add(nIndex
);
1738 aLastIndices
.Add(0);
1740 entry
->Prepend(m_aEntries
[nIndex
]);
1741 m_aEntries
[nIndex
] = entry
;
1744 // not the first time in _this_ file
1745 size_t nEntryIndex
= (size_t)entryIndex
;
1746 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1748 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
1750 m_aEntries
[nIndex
] = entry
;
1752 // the indices were shifted by 1
1753 aLastIndices
[nEntryIndex
]++;
1757 if ( !strDesc
.IsEmpty() ) {
1758 // replace the old one - what else can we do??
1759 m_aDescriptions
[nIndex
] = strDesc
;
1764 // check our data integriry
1765 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1766 m_aTypes
.Count() == m_aExtensions
.Count() &&
1767 m_aTypes
.Count() == m_aDescriptions
.Count() );
1773 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1775 mimetypes
= m_aTypes
;
1777 return m_aTypes
.GetCount();
1784 // wxUSE_FILE && wxUSE_TEXTFILE