1 /////////////////////////////////////////////////////////////////////////////
2 // Name: unix/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"
40 #include "wx/dynarray.h"
41 #include "wx/confbase.h"
44 #include "wx/textfile.h"
47 #include "wx/tokenzr.h"
49 #include "wx/unix/mimetype.h"
51 // other standard headers
54 // in case we're compiling in non-GUI mode
55 class WXDLLEXPORT wxIcon
;
57 // ----------------------------------------------------------------------------
59 // ----------------------------------------------------------------------------
62 // this class uses both mailcap and mime.types to gather information about file
65 // The information about mailcap file was extracted from metamail(1) sources and
68 // Format of mailcap file: spaces are ignored, each line is either a comment
69 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
70 // A backslash can be used to quote semicolons and newlines (and, in fact,
71 // anything else including itself).
73 // The first field is always the MIME type in the form of type/subtype (see RFC
74 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
75 // "type" which means the same as "type/*", although I'm not sure whether this
78 // The second field is always the command to run. It is subject to
79 // parameter/filename expansion described below.
81 // All the following fields are optional and may not be present at all. If
82 // they're present they may appear in any order, although each of them should
83 // appear only once. The optional fields are the following:
84 // * notes=xxx is an uninterpreted string which is silently ignored
85 // * test=xxx is the command to be used to determine whether this mailcap line
86 // applies to our data or not. The RHS of this field goes through the
87 // parameter/filename expansion (as the 2nd field) and the resulting string
88 // is executed. The line applies only if the command succeeds, i.e. returns 0
90 // * print=xxx is the command to be used to print (and not view) the data of
91 // this type (parameter/filename expansion is done here too)
92 // * edit=xxx is the command to open/edit the data of this type
93 // * needsterminal means that a new console must be created for the viewer
94 // * copiousoutput means that the viewer doesn't interact with the user but
95 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
96 // good example), thus it might be a good idea to use some kind of paging
98 // * textualnewlines means not to perform CR/LF translation (not honored)
99 // * compose and composetyped fields are used to determine the program to be
100 // called to create a new message pert in the specified format (unused).
102 // Parameter/filename xpansion:
103 // * %s is replaced with the (full) file name
104 // * %t is replaced with MIME type/subtype of the entry
105 // * for multipart type only %n is replaced with the nnumber of parts and %F is
106 // replaced by an array of (content-type, temporary file name) pairs for all
107 // message parts (TODO)
108 // * %{parameter} is replaced with the value of parameter taken from
109 // Content-type header line of the message.
111 // FIXME any docs with real descriptions of these files??
113 // There are 2 possible formats for mime.types file, one entry per line (used
114 // for global mime.types) and "expanded" format where an entry takes multiple
115 // lines (used for users mime.types).
117 // For both formats spaces are ignored and lines starting with a '#' are
118 // comments. Each record has one of two following forms:
119 // a) for "brief" format:
120 // <mime type> <space separated list of extensions>
121 // b) for "expanded" format:
122 // type=<mime type> \ desc="<description>" \ exts="ext"
124 // We try to autodetect the format of mime.types: if a non-comment line starts
125 // with "type=" we assume the second format, otherwise the first one.
127 // there may be more than one entry for one and the same mime type, to
128 // choose the right one we have to run the command specified in the test
129 // field on our data.
134 MailCapEntry(const wxString
& openCmd
,
135 const wxString
& printCmd
,
136 const wxString
& testCmd
)
137 : m_openCmd(openCmd
), m_printCmd(printCmd
), m_testCmd(testCmd
)
143 const wxString
& GetOpenCmd() const { return m_openCmd
; }
144 const wxString
& GetPrintCmd() const { return m_printCmd
; }
145 const wxString
& GetTestCmd() const { return m_testCmd
; }
147 MailCapEntry
*GetNext() const { return m_next
; }
150 // prepend this element to the list
151 void Prepend(MailCapEntry
*next
) { m_next
= next
; }
152 // insert into the list at given position
153 void Insert(MailCapEntry
*next
, size_t pos
)
158 for ( cur
= next
; cur
!= NULL
; cur
= cur
->m_next
, n
++ ) {
163 wxASSERT_MSG( n
== pos
, wxT("invalid position in MailCapEntry::Insert") );
165 m_next
= cur
->m_next
;
168 // append this element to the list
169 void Append(MailCapEntry
*next
)
171 wxCHECK_RET( next
!= NULL
, wxT("Append()ing to what?") );
175 for ( cur
= next
; cur
->m_next
!= NULL
; cur
= cur
->m_next
)
180 wxASSERT_MSG( !m_next
, wxT("Append()ing element already in the list?") );
184 wxString m_openCmd
, // command to use to open/view the file
186 m_testCmd
; // only apply this entry if test yields
187 // true (i.e. the command returns 0)
189 MailCapEntry
*m_next
; // in the linked list
193 // the base class which may be used to find an icon for the MIME type
194 class wxMimeTypeIconHandler
197 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
) = 0;
199 // this function fills manager with MIME types information gathered
200 // (as side effect) when searching for icons. This may be particularly
201 // useful if mime.types is incomplete (e.g. RedHat distributions).
202 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
) = 0;
206 // the icon handler which uses GNOME MIME database
207 class wxGNOMEIconHandler
: public wxMimeTypeIconHandler
210 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
);
211 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
) {}
215 void LoadIconsFromKeyFile(const wxString
& filename
);
216 void LoadKeyFilesFromDir(const wxString
& dirbase
);
218 static bool m_inited
;
220 static wxSortedArrayString ms_mimetypes
;
221 static wxArrayString ms_icons
;
224 // the icon handler which uses KDE MIME database
225 class wxKDEIconHandler
: public wxMimeTypeIconHandler
228 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
);
229 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
);
232 void LoadLinksForMimeSubtype(const wxString
& dirbase
,
233 const wxString
& subdir
,
234 const wxString
& filename
,
235 const wxArrayString
& icondirs
);
236 void LoadLinksForMimeType(const wxString
& dirbase
,
237 const wxString
& subdir
,
238 const wxArrayString
& icondirs
);
239 void LoadLinkFilesFromDir(const wxString
& dirbase
,
240 const wxArrayString
& icondirs
);
243 static bool m_inited
;
245 static wxSortedArrayString ms_mimetypes
;
246 static wxArrayString ms_icons
;
248 static wxArrayString ms_infoTypes
;
249 static wxArrayString ms_infoDescriptions
;
250 static wxArrayString ms_infoExtensions
;
255 // ----------------------------------------------------------------------------
257 // ----------------------------------------------------------------------------
259 static wxGNOMEIconHandler gs_iconHandlerGNOME
;
260 static wxKDEIconHandler gs_iconHandlerKDE
;
262 bool wxGNOMEIconHandler::m_inited
= FALSE
;
263 wxSortedArrayString
wxGNOMEIconHandler::ms_mimetypes
;
264 wxArrayString
wxGNOMEIconHandler::ms_icons
;
266 bool wxKDEIconHandler::m_inited
= FALSE
;
267 wxSortedArrayString
wxKDEIconHandler::ms_mimetypes
;
268 wxArrayString
wxKDEIconHandler::ms_icons
;
270 wxArrayString
wxKDEIconHandler::ms_infoTypes
;
271 wxArrayString
wxKDEIconHandler::ms_infoDescriptions
;
272 wxArrayString
wxKDEIconHandler::ms_infoExtensions
;
275 ArrayIconHandlers
wxMimeTypesManagerImpl::ms_iconHandlers
;
277 // ----------------------------------------------------------------------------
278 // wxGNOMEIconHandler
279 // ----------------------------------------------------------------------------
281 // GNOME stores the info we're interested in in several locations:
282 // 1. xxx.keys files under /usr/share/mime-info
283 // 2. xxx.keys files under ~/.gnome/mime-info
285 // The format of xxx.keys file is the following:
290 // with blank lines separating the entries and indented lines starting with
291 // TABs. We're interested in the field icon-filename whose value is the path
292 // containing the icon.
294 void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString
& filename
)
296 wxTextFile
textfile(filename
);
297 if ( !textfile
.Open() )
300 // values for the entry being parsed
301 wxString curMimeType
, curIconFile
;
304 size_t nLineCount
= textfile
.GetLineCount();
305 for ( size_t nLine
= 0; ; nLine
++ )
307 if ( nLine
< nLineCount
)
309 pc
= textfile
[nLine
].c_str();
310 if ( *pc
== _T('#') )
318 // so that we will fall into the "if" below
325 if ( !!curMimeType
&& !!curIconFile
)
327 // do we already know this mimetype?
328 int i
= ms_mimetypes
.Index(curMimeType
);
329 if ( i
== wxNOT_FOUND
)
332 size_t n
= ms_mimetypes
.Add(curMimeType
);
333 ms_icons
.Insert(curIconFile
, n
);
337 // replace the existing one (this means that the directories
338 // should be searched in order of increased priority!)
339 ms_icons
[(size_t)i
] = curIconFile
;
345 // the end - this can only happen if nLine == nLineCount
354 // what do we have here?
355 if ( *pc
== _T('\t') )
357 // this is a field=value ling
358 pc
++; // skip leading TAB
360 static const int lenField
= 13; // strlen("icon-filename")
361 if ( wxStrncmp(pc
, _T("icon-filename"), lenField
) == 0 )
363 // skip '=' which follows and take everything left until the end
365 curIconFile
= pc
+ lenField
+ 1;
367 //else: some other field, we don't care
371 // this is the start of the new section
374 while ( *pc
!= _T(':') && *pc
!= _T('\0') )
376 curMimeType
+= *pc
++;
381 // we reached the end of line without finding the colon,
382 // something is wrong - ignore this line completely
383 wxLogDebug(_T("Unreckognized line %d in file '%s' ignored"),
384 nLine
+ 1, filename
.c_str());
392 void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString
& dirbase
)
394 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
395 _T("base directory shouldn't end with a slash") );
397 wxString dirname
= dirbase
;
398 dirname
<< _T("/mime-info");
400 if ( !wxDir::Exists(dirname
) )
404 if ( !dir
.IsOpened() )
407 // we will concatenate it with filename to get the full path below
411 bool cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
414 LoadIconsFromKeyFile(dirname
+ filename
);
416 cont
= dir
.GetNext(&filename
);
420 void wxGNOMEIconHandler::Init()
423 dirs
.Add(_T("/usr/share"));
424 dirs
.Add(_T("/usr/local/share"));
427 wxGetHomeDir( &gnomedir
);
428 gnomedir
+= _T("/.gnome");
429 dirs
.Add( gnomedir
);
431 size_t nDirs
= dirs
.GetCount();
432 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
434 LoadKeyFilesFromDir(dirs
[nDir
]);
440 bool wxGNOMEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
447 int index
= ms_mimetypes
.Index(mimetype
);
448 if ( index
== wxNOT_FOUND
)
451 wxString iconname
= ms_icons
[(size_t)index
];
456 if (iconname
.Right(4).MakeUpper() == _T(".XPM"))
457 icn
= wxIcon(iconname
);
459 icn
= wxIcon(iconname
, wxBITMAP_TYPE_ANY
);
460 if (icn
.Ok()) *icon
= icn
;
463 // helpful for testing in console mode
464 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
465 mimetype
.c_str(), iconname
.c_str());
471 // ----------------------------------------------------------------------------
473 // ----------------------------------------------------------------------------
475 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
476 // may be found in either of the following locations
478 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
479 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
481 // The format of a .kdelnk file is almost the same as the one used by
482 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
483 // value for the entry "Type"
485 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString
& dirbase
,
486 const wxString
& subdir
,
487 const wxString
& filename
,
488 const wxArrayString
& icondirs
)
490 wxFFile
file(dirbase
+ filename
);
491 if ( !file
.IsOpened() )
494 // construct mimetype from the directory name and the basename of the
495 // file (it always has .kdelnk extension)
497 mimetype
<< subdir
<< _T('/') << filename
.BeforeLast(_T('.'));
499 // these files are small, slurp the entire file at once
501 if ( !file
.ReadAll(&text
) )
507 // before trying to find an icon, grab mimetype information
508 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
509 // have edited it in control panel...)
511 wxString mime_extension
, mime_desc
;
514 if (wxGetLocale() != NULL
)
515 mime_desc
= _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
516 if (pos
== wxNOT_FOUND
) mime_desc
= _T("Comment=");
517 pos
= text
.Find(mime_desc
);
518 if (pos
== wxNOT_FOUND
) mime_desc
= wxEmptyString
;
521 pc
= text
.c_str() + pos
+ mime_desc
.Length();
522 mime_desc
= wxEmptyString
;
523 while ( *pc
&& *pc
!= _T('\n') ) mime_desc
+= *pc
++;
526 pos
= text
.Find(_T("Patterns="));
527 if (pos
!= wxNOT_FOUND
)
530 pc
= text
.c_str() + pos
+ 9;
531 while ( *pc
&& *pc
!= _T('\n') ) exts
+= *pc
++;
532 wxStringTokenizer
tokenizer(exts
, _T(";"));
535 while (tokenizer
.HasMoreTokens())
537 e
= tokenizer
.GetNextToken();
538 if (e
.Left(2) != _T("*.")) continue; // don't support too difficult patterns
539 mime_extension
<< e
.Mid(2);
540 mime_extension
<< _T(' ');
542 mime_extension
.RemoveLast();
545 ms_infoTypes
.Add(mimetype
);
546 ms_infoDescriptions
.Add(mime_desc
);
547 ms_infoExtensions
.Add(mime_extension
);
549 // ok, now we can take care of icon:
551 pos
= text
.Find(_T("Icon="));
552 if ( pos
== wxNOT_FOUND
)
560 pc
= text
.c_str() + pos
+ 5; // 5 == strlen("Icon=")
561 while ( *pc
&& *pc
!= _T('\n') )
568 // we must check if the file exists because it may be stored
569 // in many locations, at least ~/.kde and $KDEDIR
570 size_t nDir
, nDirs
= icondirs
.GetCount();
571 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
572 if (wxFileExists(icondirs
[nDir
] + icon
))
574 icon
.Prepend(icondirs
[nDir
]);
577 if (nDir
== nDirs
) return; //does not exist
579 // do we already have this MIME type?
580 int i
= ms_mimetypes
.Index(mimetype
);
581 if ( i
== wxNOT_FOUND
)
584 size_t n
= ms_mimetypes
.Add(mimetype
);
585 ms_icons
.Insert(icon
, n
);
589 // replace the old value
590 ms_icons
[(size_t)i
] = icon
;
595 void wxKDEIconHandler::LoadLinksForMimeType(const wxString
& dirbase
,
596 const wxString
& subdir
,
597 const wxArrayString
& icondirs
)
599 wxString dirname
= dirbase
;
602 if ( !dir
.IsOpened() )
608 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
611 LoadLinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
613 cont
= dir
.GetNext(&filename
);
617 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString
& dirbase
,
618 const wxArrayString
& icondirs
)
620 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
621 _T("base directory shouldn't end with a slash") );
623 wxString dirname
= dirbase
;
624 dirname
<< _T("/mimelnk");
626 if ( !wxDir::Exists(dirname
) )
630 if ( !dir
.IsOpened() )
633 // we will concatenate it with dir name to get the full path below
637 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
640 LoadLinksForMimeType(dirname
, subdir
, icondirs
);
642 cont
= dir
.GetNext(&subdir
);
646 void wxKDEIconHandler::Init()
649 wxArrayString icondirs
;
651 // settings in ~/.kde have maximal priority
652 dirs
.Add(wxGetHomeDir() + _T("/.kde/share"));
653 icondirs
.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
655 // the variable KDEDIR is set when KDE is running
656 const char *kdedir
= getenv("KDEDIR");
659 dirs
.Add(wxString(kdedir
) + _T("/share"));
660 icondirs
.Add(wxString(kdedir
) + _T("/share/icons/"));
664 // try to guess KDEDIR
665 dirs
.Add(_T("/usr/share"));
666 dirs
.Add(_T("/opt/kde/share"));
667 icondirs
.Add(_T("/usr/share/icons/"));
668 icondirs
.Add(_T("/opt/kde/share/icons/"));
671 size_t nDirs
= dirs
.GetCount();
672 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
674 LoadLinkFilesFromDir(dirs
[nDir
], icondirs
);
680 bool wxKDEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
687 int index
= ms_mimetypes
.Index(mimetype
);
688 if ( index
== wxNOT_FOUND
)
691 wxString iconname
= ms_icons
[(size_t)index
];
696 if (iconname
.Right(4).MakeUpper() == _T(".XPM"))
697 icn
= wxIcon(iconname
);
699 icn
= wxIcon(iconname
, wxBITMAP_TYPE_ANY
);
700 if (icn
.Ok()) *icon
= icn
;
703 // helpful for testing in console mode
704 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
705 mimetype
.c_str(), iconname
.c_str());
712 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
)
714 if ( !m_inited
) Init();
716 size_t cnt
= ms_infoTypes
.GetCount();
717 for (unsigned i
= 0; i
< cnt
; i
++)
718 manager
-> AddMimeTypeInfo(ms_infoTypes
[i
], ms_infoExtensions
[i
], ms_infoDescriptions
[i
]);
722 // ----------------------------------------------------------------------------
723 // wxFileTypeImpl (Unix)
724 // ----------------------------------------------------------------------------
727 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
730 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
731 while ( entry
!= NULL
) {
732 // notice that an empty command would always succeed (it's ok)
733 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
735 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
737 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
738 command
.c_str(), params
.GetMimeType().c_str());
742 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
743 command
.c_str(), params
.GetMimeType().c_str());
746 entry
= entry
->GetNext();
752 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
755 (void)GetMimeType(&mimetype
);
757 ArrayIconHandlers
& handlers
= m_manager
->GetIconHandlers();
758 size_t count
= handlers
.GetCount();
759 for ( size_t n
= 0; n
< count
; n
++ )
761 if ( handlers
[n
]->GetIcon(mimetype
, icon
) )
769 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
770 const wxFileType::MessageParameters
& params
,
773 MailCapEntry
*entry
= GetEntry(params
);
774 if ( entry
== NULL
) {
775 // all tests failed...
779 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
780 if ( cmd
.IsEmpty() ) {
781 // may happen, especially for "print"
785 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
789 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
791 wxString strExtensions
= m_manager
->GetExtension(m_index
);
794 // one extension in the space or comma delimitid list
796 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
797 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
798 if ( !strExt
.IsEmpty() ) {
799 extensions
.Add(strExt
);
802 //else: repeated spaces (shouldn't happen, but it's not that
803 // important if it does happen)
805 if ( *p
== wxT('\0') )
808 else if ( *p
== wxT('.') ) {
809 // remove the dot from extension (but only if it's the first char)
810 if ( !strExt
.IsEmpty() ) {
813 //else: no, don't append it
823 // ----------------------------------------------------------------------------
824 // wxMimeTypesManagerImpl (Unix)
825 // ----------------------------------------------------------------------------
828 ArrayIconHandlers
& wxMimeTypesManagerImpl::GetIconHandlers()
830 if ( ms_iconHandlers
.GetCount() == 0 )
832 ms_iconHandlers
.Add(&gs_iconHandlerKDE
);
833 ms_iconHandlers
.Add(&gs_iconHandlerGNOME
);
836 return ms_iconHandlers
;
839 // read system and user mailcaps (TODO implement mime.types support)
840 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
842 // read KDE/GNOME tables
843 ArrayIconHandlers
& handlers
= GetIconHandlers();
844 size_t count
= handlers
.GetCount();
845 for ( size_t hn
= 0; hn
< count
; hn
++ )
846 handlers
[hn
]->GetMimeInfoRecords(this);
848 // directories where we look for mailcap and mime.types by default
849 // (taken from metamail(1) sources)
850 static const wxChar
*aStandardLocations
[] =
854 wxT("/usr/local/etc"),
856 wxT("/usr/public/lib")
859 // first read the system wide file(s)
861 for ( n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
862 wxString dir
= aStandardLocations
[n
];
864 wxString file
= dir
+ wxT("/mailcap");
865 if ( wxFile::Exists(file
) ) {
869 file
= dir
+ wxT("/mime.types");
870 if ( wxFile::Exists(file
) ) {
875 wxString strHome
= wxGetenv(wxT("HOME"));
877 // and now the users mailcap
878 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
879 if ( wxFile::Exists(strUserMailcap
) ) {
880 ReadMailcap(strUserMailcap
);
883 // read the users mime.types
884 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
885 if ( wxFile::Exists(strUserMimeTypes
) ) {
886 ReadMimeTypes(strUserMimeTypes
);
891 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
893 size_t count
= m_aExtensions
.GetCount();
894 for ( size_t n
= 0; n
< count
; n
++ ) {
895 wxString extensions
= m_aExtensions
[n
];
896 while ( !extensions
.IsEmpty() ) {
897 wxString field
= extensions
.BeforeFirst(wxT(' '));
898 extensions
= extensions
.AfterFirst(wxT(' '));
900 // consider extensions as not being case-sensitive
901 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
903 wxFileType
*fileType
= new wxFileType
;
904 fileType
->m_impl
->Init(this, n
);
916 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
918 // mime types are not case-sensitive
919 wxString
mimetype(mimeType
);
920 mimetype
.MakeLower();
922 // first look for an exact match
923 int index
= m_aTypes
.Index(mimetype
);
924 if ( index
== wxNOT_FOUND
) {
925 // then try to find "text/*" as match for "text/plain" (for example)
926 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
927 // the whole string - ok.
928 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
930 size_t nCount
= m_aTypes
.Count();
931 for ( size_t n
= 0; n
< nCount
; n
++ ) {
932 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
933 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
940 if ( index
!= wxNOT_FOUND
) {
941 wxFileType
*fileType
= new wxFileType
;
942 fileType
->m_impl
->Init(this, index
);
952 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
955 const wxArrayString
& exts
= filetype
.GetExtensions();
956 size_t nExts
= exts
.GetCount();
957 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
959 extensions
+= wxT(' ');
961 extensions
+= exts
[nExt
];
964 AddMimeTypeInfo(filetype
.GetMimeType(),
966 filetype
.GetDescription());
968 AddMailcapInfo(filetype
.GetMimeType(),
969 filetype
.GetOpenCommand(),
970 filetype
.GetPrintCommand(),
972 filetype
.GetDescription());
975 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
976 const wxString
& strExtensions
,
977 const wxString
& strDesc
)
979 int index
= m_aTypes
.Index(strMimeType
);
980 if ( index
== wxNOT_FOUND
) {
982 m_aTypes
.Add(strMimeType
);
983 m_aEntries
.Add(NULL
);
984 m_aExtensions
.Add(strExtensions
);
985 m_aDescriptions
.Add(strDesc
);
988 // modify an existing one
989 if ( !strDesc
.IsEmpty() ) {
990 m_aDescriptions
[index
] = strDesc
; // replace old value
992 m_aExtensions
[index
] += ' ' + strExtensions
;
996 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
997 const wxString
& strOpenCmd
,
998 const wxString
& strPrintCmd
,
999 const wxString
& strTest
,
1000 const wxString
& strDesc
)
1002 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1004 int nIndex
= m_aTypes
.Index(strType
);
1005 if ( nIndex
== wxNOT_FOUND
) {
1007 m_aTypes
.Add(strType
);
1009 m_aEntries
.Add(entry
);
1010 m_aExtensions
.Add(wxT(""));
1011 m_aDescriptions
.Add(strDesc
);
1014 // always append the entry in the tail of the list - info added with
1015 // this function can only come from AddFallbacks()
1016 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1018 entry
->Append(entryOld
);
1020 m_aEntries
[nIndex
] = entry
;
1024 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1026 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1028 wxTextFile
file(strFileName
);
1032 // the information we extract
1033 wxString strMimeType
, strDesc
, strExtensions
;
1035 size_t nLineCount
= file
.GetLineCount();
1036 const wxChar
*pc
= NULL
;
1037 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1039 // now we're at the start of the line
1040 pc
= file
[nLine
].c_str();
1043 // we didn't finish with the previous line yet
1048 while ( wxIsspace(*pc
) )
1051 // comment or blank line?
1052 if ( *pc
== wxT('#') || !*pc
) {
1053 // skip the whole line
1058 // detect file format
1059 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1060 if ( pEqualSign
== NULL
) {
1064 // first field is mime type
1065 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1070 while ( wxIsspace(*pc
) )
1073 // take all the rest of the string
1076 // no description...
1083 // the string on the left of '=' is the field name
1084 wxString
strLHS(pc
, pEqualSign
- pc
);
1087 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
1091 if ( *pc
== wxT('"') ) {
1092 // the string is quoted and ends at the matching quote
1093 pEnd
= wxStrchr(++pc
, wxT('"'));
1094 if ( pEnd
== NULL
) {
1095 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1097 strFileName
.c_str(), nLine
+ 1);
1101 // unquoted string ends at the first space
1102 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
1106 // now we have the RHS (field value)
1107 wxString
strRHS(pc
, pEnd
- pc
);
1109 // check what follows this entry
1110 if ( *pEnd
== wxT('"') ) {
1115 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
1118 // if there is something left, it may be either a '\\' to continue
1119 // the line or the next field of the same entry
1120 bool entryEnded
= *pc
== wxT('\0'),
1121 nextFieldOnSameLine
= FALSE
;
1122 if ( !entryEnded
) {
1123 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
1126 // now see what we got
1127 if ( strLHS
== wxT("type") ) {
1128 strMimeType
= strRHS
;
1130 else if ( strLHS
== wxT("desc") ) {
1133 else if ( strLHS
== wxT("exts") ) {
1134 strExtensions
= strRHS
;
1137 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1138 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
1141 if ( !entryEnded
) {
1142 if ( !nextFieldOnSameLine
)
1144 //else: don't reset it
1146 // as we don't reset strMimeType, the next field in this entry
1147 // will be interpreted correctly.
1153 // although it doesn't seem to be covered by RFCs, some programs
1154 // (notably Netscape) create their entries with several comma
1155 // separated extensions (RFC mention the spaces only)
1156 strExtensions
.Replace(wxT(","), wxT(" "));
1158 // also deal with the leading dot
1159 if ( !strExtensions
.IsEmpty() && strExtensions
[0u] == wxT('.') )
1161 strExtensions
.erase(0, 1);
1164 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
1166 // finished with this line
1170 // check our data integriry
1171 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1172 m_aTypes
.Count() == m_aExtensions
.Count() &&
1173 m_aTypes
.Count() == m_aDescriptions
.Count() );
1178 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
1181 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
1183 wxTextFile
file(strFileName
);
1187 // see the comments near the end of function for the reason we need these
1188 // variables (search for the next occurence of them)
1189 // indices of MIME types (in m_aTypes) we already found in this file
1190 wxArrayInt aEntryIndices
;
1191 // aLastIndices[n] is the index of last element in
1192 // m_aEntries[aEntryIndices[n]] from this file
1193 wxArrayInt aLastIndices
;
1195 size_t nLineCount
= file
.GetLineCount();
1196 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1197 // now we're at the start of the line
1198 const wxChar
*pc
= file
[nLine
].c_str();
1201 while ( wxIsspace(*pc
) )
1204 // comment or empty string?
1205 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
1210 // what field are we currently in? The first 2 are fixed and there may
1211 // be an arbitrary number of other fields -- currently, we are not
1212 // interested in any of them, but we should parse them as well...
1218 } currentToken
= Field_Type
;
1220 // the flags and field values on the current line
1221 bool needsterminal
= FALSE
,
1222 copiousoutput
= FALSE
;
1228 curField
; // accumulator
1229 for ( bool cont
= TRUE
; cont
; pc
++ ) {
1232 // interpret the next character literally (notice that
1233 // backslash can be used for line continuation)
1234 if ( *++pc
== wxT('\0') ) {
1235 // fetch the next line.
1237 // pc currently points to nowhere, but after the next
1238 // pc++ in the for line it will point to the beginning
1239 // of the next line in the file
1240 pc
= file
[++nLine
].c_str() - 1;
1243 // just a normal character
1249 cont
= FALSE
; // end of line reached, exit the loop
1254 // store this field and start looking for the next one
1256 // trim whitespaces from both sides
1257 curField
.Trim(TRUE
).Trim(FALSE
);
1259 switch ( currentToken
) {
1262 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
1263 // we interpret "type" as "type/*"
1264 strType
+= wxT("/*");
1267 currentToken
= Field_OpenCmd
;
1271 strOpenCmd
= curField
;
1273 currentToken
= Field_Other
;
1278 // "good" mailcap entry?
1281 // is this something of the form foo=bar?
1282 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
1283 if ( pEq
!= NULL
) {
1284 wxString lhs
= curField
.BeforeFirst(wxT('=')),
1285 rhs
= curField
.AfterFirst(wxT('='));
1287 lhs
.Trim(TRUE
); // from right
1288 rhs
.Trim(FALSE
); // from left
1290 if ( lhs
== wxT("print") )
1292 else if ( lhs
== wxT("test") )
1294 else if ( lhs
== wxT("description") ) {
1295 // it might be quoted
1296 if ( rhs
[0u] == wxT('"') &&
1297 rhs
.Last() == wxT('"') ) {
1298 strDesc
= wxString(rhs
.c_str() + 1,
1305 else if ( lhs
== wxT("compose") ||
1306 lhs
== wxT("composetyped") ||
1307 lhs
== wxT("notes") ||
1308 lhs
== wxT("edit") )
1315 // no, it's a simple flag
1316 // TODO support the flags:
1317 // 1. create an xterm for 'needsterminal'
1318 // 2. append "| $PAGER" for 'copiousoutput'
1319 if ( curField
== wxT("needsterminal") )
1320 needsterminal
= TRUE
;
1321 else if ( curField
== wxT("copiousoutput") )
1322 copiousoutput
= TRUE
;
1323 else if ( curField
== wxT("textualnewlines") )
1331 // we don't understand this field, but
1332 // Netscape stores info in it, so don't warn
1334 if ( curField
.Left(16u) != "x-mozilla-flags=" )
1336 // don't flood the user with error
1337 // messages if we don't understand
1338 // something in his mailcap, but give
1339 // them in debug mode because this might
1340 // be useful for the programmer
1343 wxT("Mailcap file %s, line %d: "
1344 "unknown field '%s' for the "
1345 "MIME type '%s' ignored."),
1346 strFileName
.c_str(),
1355 // it already has this value
1356 //currentToken = Field_Other;
1360 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1363 // next token starts immediately after ';'
1372 // check that we really read something reasonable
1373 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
1374 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1376 strFileName
.c_str(), nLine
+ 1);
1379 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
1383 // NB: because of complications below (we must get entries priority
1384 // right), we can't use AddMailcapInfo() here, unfortunately.
1385 strType
.MakeLower();
1386 int nIndex
= m_aTypes
.Index(strType
);
1387 if ( nIndex
== wxNOT_FOUND
) {
1389 m_aTypes
.Add(strType
);
1391 m_aEntries
.Add(entry
);
1392 m_aExtensions
.Add(wxT(""));
1393 m_aDescriptions
.Add(strDesc
);
1396 // modify the existing entry: the entries in one and the same
1397 // file are read in top-to-bottom order, i.e. the entries read
1398 // first should be tried before the entries below. However,
1399 // the files read later should override the settings in the
1400 // files read before (except if fallback is TRUE), thus we
1401 // Insert() the new entry to the list if it has already
1402 // occured in _this_ file, but Prepend() it if it occured in
1403 // some of the previous ones and Append() to it in the
1407 // 'fallback' parameter prevents the entries from this
1408 // file from overriding the other ones - always append
1409 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1411 entry
->Append(entryOld
);
1413 m_aEntries
[nIndex
] = entry
;
1416 int entryIndex
= aEntryIndices
.Index(nIndex
);
1417 if ( entryIndex
== wxNOT_FOUND
) {
1418 // first time in this file
1419 aEntryIndices
.Add(nIndex
);
1420 aLastIndices
.Add(0);
1422 entry
->Prepend(m_aEntries
[nIndex
]);
1423 m_aEntries
[nIndex
] = entry
;
1426 // not the first time in _this_ file
1427 size_t nEntryIndex
= (size_t)entryIndex
;
1428 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1430 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
1432 m_aEntries
[nIndex
] = entry
;
1434 // the indices were shifted by 1
1435 aLastIndices
[nEntryIndex
]++;
1439 if ( !strDesc
.IsEmpty() ) {
1440 // replace the old one - what else can we do??
1441 m_aDescriptions
[nIndex
] = strDesc
;
1446 // check our data integriry
1447 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1448 m_aTypes
.Count() == m_aExtensions
.Count() &&
1449 m_aTypes
.Count() == m_aDescriptions
.Count() );
1455 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1460 size_t count
= m_aTypes
.GetCount();
1461 for ( size_t n
= 0; n
< count
; n
++ )
1463 // don't return template types from here (i.e. anything containg '*')
1465 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
1467 mimetypes
.Add(type
);
1471 return mimetypes
.GetCount();
1475 // wxUSE_FILE && wxUSE_TEXTFILE