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 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "mimetype.h"
24 // for compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
35 #if wxUSE_FILE && wxUSE_TEXTFILE
38 #include "wx/string.h"
48 #include "wx/dynarray.h"
49 #include "wx/confbase.h"
52 #include "wx/textfile.h"
55 #include "wx/tokenzr.h"
57 #include "wx/unix/mimetype.h"
59 // other standard headers
62 // in case we're compiling in non-GUI mode
63 class WXDLLEXPORT wxIcon
;
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
69 // MIME code tracing mask
70 #define TRACE_MIME _T("mime")
72 // ----------------------------------------------------------------------------
74 // ----------------------------------------------------------------------------
76 // there are some fields which we don't understand but for which we don't give
77 // warnings as we know that they're not important - this function is used to
79 static bool IsKnownUnimportantField(const wxString
& field
);
81 // ----------------------------------------------------------------------------
83 // ----------------------------------------------------------------------------
86 // this class uses both mailcap and mime.types to gather information about file
89 // The information about mailcap file was extracted from metamail(1) sources and
92 // Format of mailcap file: spaces are ignored, each line is either a comment
93 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
94 // A backslash can be used to quote semicolons and newlines (and, in fact,
95 // anything else including itself).
97 // The first field is always the MIME type in the form of type/subtype (see RFC
98 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
99 // "type" which means the same as "type/*", although I'm not sure whether this
102 // The second field is always the command to run. It is subject to
103 // parameter/filename expansion described below.
105 // All the following fields are optional and may not be present at all. If
106 // they're present they may appear in any order, although each of them should
107 // appear only once. The optional fields are the following:
108 // * notes=xxx is an uninterpreted string which is silently ignored
109 // * test=xxx is the command to be used to determine whether this mailcap line
110 // applies to our data or not. The RHS of this field goes through the
111 // parameter/filename expansion (as the 2nd field) and the resulting string
112 // is executed. The line applies only if the command succeeds, i.e. returns 0
114 // * print=xxx is the command to be used to print (and not view) the data of
115 // this type (parameter/filename expansion is done here too)
116 // * edit=xxx is the command to open/edit the data of this type
117 // * needsterminal means that a new console must be created for the viewer
118 // * copiousoutput means that the viewer doesn't interact with the user but
119 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
120 // good example), thus it might be a good idea to use some kind of paging
122 // * textualnewlines means not to perform CR/LF translation (not honored)
123 // * compose and composetyped fields are used to determine the program to be
124 // called to create a new message pert in the specified format (unused).
126 // Parameter/filename xpansion:
127 // * %s is replaced with the (full) file name
128 // * %t is replaced with MIME type/subtype of the entry
129 // * for multipart type only %n is replaced with the nnumber of parts and %F is
130 // replaced by an array of (content-type, temporary file name) pairs for all
131 // message parts (TODO)
132 // * %{parameter} is replaced with the value of parameter taken from
133 // Content-type header line of the message.
135 // FIXME any docs with real descriptions of these files??
137 // There are 2 possible formats for mime.types file, one entry per line (used
138 // for global mime.types) and "expanded" format where an entry takes multiple
139 // lines (used for users mime.types).
141 // For both formats spaces are ignored and lines starting with a '#' are
142 // comments. Each record has one of two following forms:
143 // a) for "brief" format:
144 // <mime type> <space separated list of extensions>
145 // b) for "expanded" format:
146 // type=<mime type> \ desc="<description>" \ exts="ext"
148 // We try to autodetect the format of mime.types: if a non-comment line starts
149 // with "type=" we assume the second format, otherwise the first one.
151 // there may be more than one entry for one and the same mime type, to
152 // choose the right one we have to run the command specified in the test
153 // field on our data.
158 MailCapEntry(const wxString
& openCmd
,
159 const wxString
& printCmd
,
160 const wxString
& testCmd
)
161 : m_openCmd(openCmd
), m_printCmd(printCmd
), m_testCmd(testCmd
)
168 if (m_next
) delete m_next
;
172 const wxString
& GetOpenCmd() const { return m_openCmd
; }
173 const wxString
& GetPrintCmd() const { return m_printCmd
; }
174 const wxString
& GetTestCmd() const { return m_testCmd
; }
176 MailCapEntry
*GetNext() const { return m_next
; }
179 // prepend this element to the list
180 void Prepend(MailCapEntry
*next
) { m_next
= next
; }
181 // insert into the list at given position
182 void Insert(MailCapEntry
*next
, size_t pos
)
187 for ( cur
= next
; cur
!= NULL
; cur
= cur
->m_next
, n
++ ) {
192 wxASSERT_MSG( n
== pos
, wxT("invalid position in MailCapEntry::Insert") );
194 m_next
= cur
->m_next
;
197 // append this element to the list
198 void Append(MailCapEntry
*next
)
200 wxCHECK_RET( next
!= NULL
, wxT("Append()ing to what?") );
204 for ( cur
= next
; cur
->m_next
!= NULL
; cur
= cur
->m_next
)
209 wxASSERT_MSG( !m_next
, wxT("Append()ing element already in the list?") );
213 wxString m_openCmd
, // command to use to open/view the file
215 m_testCmd
; // only apply this entry if test yields
216 // true (i.e. the command returns 0)
218 MailCapEntry
*m_next
; // in the linked list
222 // the base class which may be used to find an icon for the MIME type
223 class wxMimeTypeIconHandler
226 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
) = 0;
228 // this function fills manager with MIME types information gathered
229 // (as side effect) when searching for icons. This may be particularly
230 // useful if mime.types is incomplete (e.g. RedHat distributions).
231 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
) = 0;
235 // the icon handler which uses GNOME MIME database
236 class wxGNOMEIconHandler
: public wxMimeTypeIconHandler
239 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
);
240 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
);
244 void LoadIconsFromKeyFile(const wxString
& filename
);
245 void LoadKeyFilesFromDir(const wxString
& dirbase
);
247 void LoadMimeTypesFromMimeFile(const wxString
& filename
, wxMimeTypesManagerImpl
*manager
);
248 void LoadMimeFilesFromDir(const wxString
& dirbase
, wxMimeTypesManagerImpl
*manager
);
250 static bool m_inited
;
252 static wxSortedArrayString ms_mimetypes
;
253 static wxArrayString ms_icons
;
256 // the icon handler which uses KDE MIME database
257 class wxKDEIconHandler
: public wxMimeTypeIconHandler
260 virtual bool GetIcon(const wxString
& mimetype
, wxIcon
*icon
);
261 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
);
264 void LoadLinksForMimeSubtype(const wxString
& dirbase
,
265 const wxString
& subdir
,
266 const wxString
& filename
,
267 const wxArrayString
& icondirs
);
268 void LoadLinksForMimeType(const wxString
& dirbase
,
269 const wxString
& subdir
,
270 const wxArrayString
& icondirs
);
271 void LoadLinkFilesFromDir(const wxString
& dirbase
,
272 const wxArrayString
& icondirs
);
275 static bool m_inited
;
277 static wxSortedArrayString ms_mimetypes
;
278 static wxArrayString ms_icons
;
280 static wxArrayString ms_infoTypes
;
281 static wxArrayString ms_infoDescriptions
;
282 static wxArrayString ms_infoExtensions
;
287 // ----------------------------------------------------------------------------
289 // ----------------------------------------------------------------------------
291 static wxGNOMEIconHandler gs_iconHandlerGNOME
;
292 static wxKDEIconHandler gs_iconHandlerKDE
;
294 bool wxGNOMEIconHandler::m_inited
= FALSE
;
295 wxSortedArrayString
wxGNOMEIconHandler::ms_mimetypes
;
296 wxArrayString
wxGNOMEIconHandler::ms_icons
;
298 bool wxKDEIconHandler::m_inited
= FALSE
;
299 wxSortedArrayString
wxKDEIconHandler::ms_mimetypes
;
300 wxArrayString
wxKDEIconHandler::ms_icons
;
302 wxArrayString
wxKDEIconHandler::ms_infoTypes
;
303 wxArrayString
wxKDEIconHandler::ms_infoDescriptions
;
304 wxArrayString
wxKDEIconHandler::ms_infoExtensions
;
307 ArrayIconHandlers
wxMimeTypesManagerImpl::ms_iconHandlers
;
309 // ----------------------------------------------------------------------------
310 // wxGNOMEIconHandler
311 // ----------------------------------------------------------------------------
313 // GNOME stores the info we're interested in in several locations:
314 // 1. xxx.keys files under /usr/share/mime-info
315 // 2. xxx.keys files under ~/.gnome/mime-info
317 // The format of xxx.keys file is the following:
322 // with blank lines separating the entries and indented lines starting with
323 // TABs. We're interested in the field icon-filename whose value is the path
324 // containing the icon.
326 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
327 // just before the field name.
329 void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString
& filename
)
331 wxTextFile
textfile(filename
);
332 if ( !textfile
.Open() )
335 // values for the entry being parsed
336 wxString curMimeType
, curIconFile
;
339 size_t nLineCount
= textfile
.GetLineCount();
340 for ( size_t nLine
= 0; ; nLine
++ )
342 if ( nLine
< nLineCount
)
344 pc
= textfile
[nLine
].c_str();
345 if ( *pc
== _T('#') )
353 // so that we will fall into the "if" below
360 if ( !!curMimeType
&& !!curIconFile
)
362 // do we already know this mimetype?
363 int i
= ms_mimetypes
.Index(curMimeType
);
364 if ( i
== wxNOT_FOUND
)
367 size_t n
= ms_mimetypes
.Add(curMimeType
);
368 ms_icons
.Insert(curIconFile
, n
);
372 // replace the existing one (this means that the directories
373 // should be searched in order of increased priority!)
374 ms_icons
[(size_t)i
] = curIconFile
;
380 // the end - this can only happen if nLine == nLineCount
389 // what do we have here?
390 if ( *pc
== _T('\t') )
392 // this is a field=value ling
393 pc
++; // skip leading TAB
395 // skip optional "[lang]"
396 if ( *pc
== _T('[') )
400 if ( *pc
++ == _T(']') )
405 static const int lenField
= 13; // strlen("icon-filename")
406 if ( wxStrncmp(pc
, _T("icon-filename"), lenField
) == 0 )
408 // skip '=' which follows and take everything left until the end
410 curIconFile
= pc
+ lenField
+ 1;
412 //else: some other field, we don't care
416 // this is the start of the new section
419 while ( *pc
!= _T(':') && *pc
!= _T('\0') )
421 curMimeType
+= *pc
++;
427 void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString
& dirbase
)
429 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
430 _T("base directory shouldn't end with a slash") );
432 wxString dirname
= dirbase
;
433 dirname
<< _T("/mime-info");
435 if ( !wxDir::Exists(dirname
) )
439 if ( !dir
.IsOpened() )
442 // we will concatenate it with filename to get the full path below
446 bool cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
449 LoadIconsFromKeyFile(dirname
+ filename
);
451 cont
= dir
.GetNext(&filename
);
456 void wxGNOMEIconHandler::LoadMimeTypesFromMimeFile(const wxString
& filename
, wxMimeTypesManagerImpl
*manager
)
458 wxTextFile
textfile(filename
);
459 if ( !textfile
.Open() )
462 // values for the entry being parsed
463 wxString curMimeType
, curExtList
;
466 size_t nLineCount
= textfile
.GetLineCount();
467 for ( size_t nLine
= 0; ; nLine
++ )
469 if ( nLine
< nLineCount
)
471 pc
= textfile
[nLine
].c_str();
472 if ( *pc
== _T('#') )
480 // so that we will fall into the "if" below
487 if ( !!curMimeType
&& !!curExtList
)
489 manager
-> AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
494 // the end - this can only happen if nLine == nLineCount
503 // what do we have here?
504 if ( *pc
== _T('\t') )
506 // this is a field=value ling
507 pc
++; // skip leading TAB
509 static const int lenField
= 4; // strlen("ext:")
510 if ( wxStrncmp(pc
, _T("ext:"), lenField
) == 0 )
512 // skip ' ' which follows and take everything left until the end
514 curExtList
= pc
+ lenField
+ 1;
516 //else: some other field, we don't care
520 // this is the start of the new section
523 while ( *pc
!= _T(':') && *pc
!= _T('\0') )
525 curMimeType
+= *pc
++;
532 void wxGNOMEIconHandler::LoadMimeFilesFromDir(const wxString
& dirbase
, wxMimeTypesManagerImpl
*manager
)
534 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
535 _T("base directory shouldn't end with a slash") );
537 wxString dirname
= dirbase
;
538 dirname
<< _T("/mime-info");
540 if ( !wxDir::Exists(dirname
) )
544 if ( !dir
.IsOpened() )
547 // we will concatenate it with filename to get the full path below
551 bool cont
= dir
.GetFirst(&filename
, _T("*.mime"), wxDIR_FILES
);
554 LoadMimeTypesFromMimeFile(dirname
+ filename
, manager
);
556 cont
= dir
.GetNext(&filename
);
561 void wxGNOMEIconHandler::Init()
564 dirs
.Add(_T("/usr/share"));
565 dirs
.Add(_T("/usr/local/share"));
568 wxGetHomeDir( &gnomedir
);
569 gnomedir
+= _T("/.gnome");
570 dirs
.Add( gnomedir
);
572 size_t nDirs
= dirs
.GetCount();
573 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
575 LoadKeyFilesFromDir(dirs
[nDir
]);
582 void wxGNOMEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
)
590 dirs
.Add(_T("/usr/share"));
591 dirs
.Add(_T("/usr/local/share"));
594 wxGetHomeDir( &gnomedir
);
595 gnomedir
+= _T("/.gnome");
596 dirs
.Add( gnomedir
);
598 size_t nDirs
= dirs
.GetCount();
599 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
601 LoadMimeFilesFromDir(dirs
[nDir
], manager
);
606 #define WXUNUSED_UNLESS_GUI(p) p
608 #define WXUNUSED_UNLESS_GUI(p)
611 bool wxGNOMEIconHandler::GetIcon(const wxString
& mimetype
,
612 wxIcon
* WXUNUSED_UNLESS_GUI(icon
))
619 int index
= ms_mimetypes
.Index(mimetype
);
620 if ( index
== wxNOT_FOUND
)
623 wxString iconname
= ms_icons
[(size_t)index
];
628 if (iconname
.Right(4).MakeUpper() == _T(".XPM"))
629 icn
= wxIcon(iconname
);
631 icn
= wxIcon(iconname
, wxBITMAP_TYPE_ANY
);
638 // helpful for testing in console mode
639 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
640 mimetype
.c_str(), iconname
.c_str());
646 // ----------------------------------------------------------------------------
648 // ----------------------------------------------------------------------------
650 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
651 // may be found in either of the following locations
653 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
654 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
656 // The format of a .kdelnk file is almost the same as the one used by
657 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
658 // value for the entry "Type"
660 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString
& dirbase
,
661 const wxString
& subdir
,
662 const wxString
& filename
,
663 const wxArrayString
& icondirs
)
665 wxFFile
file(dirbase
+ filename
);
666 if ( !file
.IsOpened() )
669 // construct mimetype from the directory name and the basename of the
670 // file (it always has .kdelnk extension)
672 mimetype
<< subdir
<< _T('/') << filename
.BeforeLast(_T('.'));
674 // these files are small, slurp the entire file at once
676 if ( !file
.ReadAll(&text
) )
682 // before trying to find an icon, grab mimetype information
683 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
684 // have edited it in control panel...)
686 wxString mime_extension
, mime_desc
;
689 if (wxGetLocale() != NULL
)
690 mime_desc
= _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
691 if (pos
== wxNOT_FOUND
) mime_desc
= _T("Comment=");
692 pos
= text
.Find(mime_desc
);
693 if (pos
== wxNOT_FOUND
) mime_desc
= wxEmptyString
;
696 pc
= text
.c_str() + pos
+ mime_desc
.Length();
697 mime_desc
= wxEmptyString
;
698 while ( *pc
&& *pc
!= _T('\n') ) mime_desc
+= *pc
++;
701 pos
= text
.Find(_T("Patterns="));
702 if (pos
!= wxNOT_FOUND
)
705 pc
= text
.c_str() + pos
+ 9;
706 while ( *pc
&& *pc
!= _T('\n') ) exts
+= *pc
++;
707 wxStringTokenizer
tokenizer(exts
, _T(";"));
710 while (tokenizer
.HasMoreTokens())
712 e
= tokenizer
.GetNextToken();
713 if (e
.Left(2) != _T("*.")) continue; // don't support too difficult patterns
714 mime_extension
<< e
.Mid(2);
715 mime_extension
<< _T(' ');
717 mime_extension
.RemoveLast();
720 ms_infoTypes
.Add(mimetype
);
721 ms_infoDescriptions
.Add(mime_desc
);
722 ms_infoExtensions
.Add(mime_extension
);
724 // ok, now we can take care of icon:
726 pos
= text
.Find(_T("Icon="));
727 if ( pos
== wxNOT_FOUND
)
735 pc
= text
.c_str() + pos
+ 5; // 5 == strlen("Icon=")
736 while ( *pc
&& *pc
!= _T('\n') )
743 // we must check if the file exists because it may be stored
744 // in many locations, at least ~/.kde and $KDEDIR
745 size_t nDir
, nDirs
= icondirs
.GetCount();
746 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
747 if (wxFileExists(icondirs
[nDir
] + icon
))
749 icon
.Prepend(icondirs
[nDir
]);
752 if (nDir
== nDirs
) return; //does not exist
754 // do we already have this MIME type?
755 int i
= ms_mimetypes
.Index(mimetype
);
756 if ( i
== wxNOT_FOUND
)
759 size_t n
= ms_mimetypes
.Add(mimetype
);
760 ms_icons
.Insert(icon
, n
);
764 // replace the old value
765 ms_icons
[(size_t)i
] = icon
;
770 void wxKDEIconHandler::LoadLinksForMimeType(const wxString
& dirbase
,
771 const wxString
& subdir
,
772 const wxArrayString
& icondirs
)
774 wxString dirname
= dirbase
;
777 if ( !dir
.IsOpened() )
783 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
786 LoadLinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
788 cont
= dir
.GetNext(&filename
);
792 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString
& dirbase
,
793 const wxArrayString
& icondirs
)
795 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
796 _T("base directory shouldn't end with a slash") );
798 wxString dirname
= dirbase
;
799 dirname
<< _T("/mimelnk");
801 if ( !wxDir::Exists(dirname
) )
805 if ( !dir
.IsOpened() )
808 // we will concatenate it with dir name to get the full path below
812 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
815 LoadLinksForMimeType(dirname
, subdir
, icondirs
);
817 cont
= dir
.GetNext(&subdir
);
821 void wxKDEIconHandler::Init()
824 wxArrayString icondirs
;
826 // settings in ~/.kde have maximal priority
827 dirs
.Add(wxGetHomeDir() + _T("/.kde/share"));
828 icondirs
.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
830 // the variable KDEDIR is set when KDE is running
831 const char *kdedir
= getenv("KDEDIR");
834 dirs
.Add(wxString(kdedir
) + _T("/share"));
835 icondirs
.Add(wxString(kdedir
) + _T("/share/icons/"));
839 // try to guess KDEDIR
840 dirs
.Add(_T("/usr/share"));
841 dirs
.Add(_T("/opt/kde/share"));
842 icondirs
.Add(_T("/usr/share/icons/"));
843 icondirs
.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
844 icondirs
.Add(_T("/opt/kde/share/icons/"));
847 size_t nDirs
= dirs
.GetCount();
848 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
850 LoadLinkFilesFromDir(dirs
[nDir
], icondirs
);
856 bool wxKDEIconHandler::GetIcon(const wxString
& mimetype
,
857 wxIcon
* WXUNUSED_UNLESS_GUI(icon
))
864 int index
= ms_mimetypes
.Index(mimetype
);
865 if ( index
== wxNOT_FOUND
)
868 wxString iconname
= ms_icons
[(size_t)index
];
873 if (iconname
.Right(4).MakeUpper() == _T(".XPM"))
874 icn
= wxIcon(iconname
);
876 icn
= wxIcon(iconname
, wxBITMAP_TYPE_ANY
);
884 // helpful for testing in console mode
885 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
886 mimetype
.c_str(), iconname
.c_str());
893 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
)
895 if ( !m_inited
) Init();
897 size_t cnt
= ms_infoTypes
.GetCount();
898 for (unsigned i
= 0; i
< cnt
; i
++)
899 manager
-> AddMimeTypeInfo(ms_infoTypes
[i
], ms_infoExtensions
[i
], ms_infoDescriptions
[i
]);
903 // ----------------------------------------------------------------------------
904 // wxFileTypeImpl (Unix)
905 // ----------------------------------------------------------------------------
908 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
911 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
[0]];
912 while ( entry
!= NULL
) {
913 // get the command to run as the test for this entry
914 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
916 // don't trace the test result if there is no test at all
917 if ( command
.IsEmpty() )
919 // no test at all, ok
923 if ( wxSystem(command
) == 0 ) {
925 wxLogTrace(TRACE_MIME
,
926 wxT("Test '%s' for mime type '%s' succeeded."),
927 command
.c_str(), params
.GetMimeType().c_str());
931 wxLogTrace(TRACE_MIME
,
932 wxT("Test '%s' for mime type '%s' failed."),
933 command
.c_str(), params
.GetMimeType().c_str());
936 entry
= entry
->GetNext();
942 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
944 wxArrayString mimetypes
;
945 GetMimeTypes(mimetypes
);
947 ArrayIconHandlers
& handlers
= m_manager
->GetIconHandlers();
948 size_t count
= handlers
.GetCount();
949 size_t counttypes
= mimetypes
.GetCount();
950 for ( size_t n
= 0; n
< count
; n
++ )
952 for ( size_t n2
= 0; n2
< counttypes
; n2
++ )
954 if ( handlers
[n
]->GetIcon(mimetypes
[n2
], icon
) )
964 wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
967 for (size_t i
= 0; i
< m_index
.GetCount(); i
++)
968 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
974 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
975 const wxFileType::MessageParameters
& params
,
978 MailCapEntry
*entry
= GetEntry(params
);
979 if ( entry
== NULL
) {
980 // all tests failed...
984 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
985 if ( cmd
.IsEmpty() ) {
986 // may happen, especially for "print"
990 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
994 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
996 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
999 // one extension in the space or comma delimitid list
1001 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
1002 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1003 if ( !strExt
.IsEmpty() ) {
1004 extensions
.Add(strExt
);
1007 //else: repeated spaces (shouldn't happen, but it's not that
1008 // important if it does happen)
1010 if ( *p
== wxT('\0') )
1013 else if ( *p
== wxT('.') ) {
1014 // remove the dot from extension (but only if it's the first char)
1015 if ( !strExt
.IsEmpty() ) {
1018 //else: no, don't append it
1028 // ----------------------------------------------------------------------------
1029 // wxMimeTypesManagerImpl (Unix)
1030 // ----------------------------------------------------------------------------
1033 ArrayIconHandlers
& wxMimeTypesManagerImpl::GetIconHandlers()
1035 if ( ms_iconHandlers
.GetCount() == 0 )
1037 ms_iconHandlers
.Add(&gs_iconHandlerGNOME
);
1038 ms_iconHandlers
.Add(&gs_iconHandlerKDE
);
1041 return ms_iconHandlers
;
1044 // read system and user mailcaps (TODO implement mime.types support)
1045 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1047 // directories where we look for mailcap and mime.types by default
1048 // (taken from metamail(1) sources)
1049 static const wxChar
*aStandardLocations
[] =
1053 wxT("/usr/local/etc"),
1055 wxT("/usr/public/lib")
1058 // first read the system wide file(s)
1060 for ( n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
1061 wxString dir
= aStandardLocations
[n
];
1063 wxString file
= dir
+ wxT("/mailcap");
1064 if ( wxFile::Exists(file
) ) {
1068 file
= dir
+ wxT("/mime.types");
1069 if ( wxFile::Exists(file
) ) {
1070 ReadMimeTypes(file
);
1074 wxString strHome
= wxGetenv(wxT("HOME"));
1076 // and now the users mailcap
1077 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1078 if ( wxFile::Exists(strUserMailcap
) ) {
1079 ReadMailcap(strUserMailcap
);
1082 // read the users mime.types
1083 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
1084 if ( wxFile::Exists(strUserMimeTypes
) ) {
1085 ReadMimeTypes(strUserMimeTypes
);
1088 // read KDE/GNOME tables
1089 ArrayIconHandlers
& handlers
= GetIconHandlers();
1090 size_t count
= handlers
.GetCount();
1091 for ( size_t hn
= 0; hn
< count
; hn
++ )
1092 handlers
[hn
]->GetMimeInfoRecords(this);
1096 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1098 size_t cnt
= m_aEntries
.GetCount();
1099 for (size_t i
= 0; i
< cnt
; i
++) delete m_aEntries
[i
];
1104 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1106 wxFileType
*fileType
= NULL
;
1107 size_t count
= m_aExtensions
.GetCount();
1108 for ( size_t n
= 0; n
< count
; n
++ ) {
1109 wxString extensions
= m_aExtensions
[n
];
1110 while ( !extensions
.IsEmpty() ) {
1111 wxString field
= extensions
.BeforeFirst(wxT(' '));
1112 extensions
= extensions
.AfterFirst(wxT(' '));
1114 // consider extensions as not being case-sensitive
1115 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
1117 if (fileType
== NULL
) fileType
= new wxFileType
;
1118 fileType
->m_impl
->Init(this, n
);
1119 // adds this mime type to _list_ of mime types with this extension
1128 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1130 // mime types are not case-sensitive
1131 wxString
mimetype(mimeType
);
1132 mimetype
.MakeLower();
1134 // first look for an exact match
1135 int index
= m_aTypes
.Index(mimetype
);
1136 if ( index
== wxNOT_FOUND
) {
1137 // then try to find "text/*" as match for "text/plain" (for example)
1138 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1139 // the whole string - ok.
1140 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1142 size_t nCount
= m_aTypes
.Count();
1143 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1144 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1145 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1152 if ( index
!= wxNOT_FOUND
) {
1153 wxFileType
*fileType
= new wxFileType
;
1154 fileType
->m_impl
->Init(this, index
);
1164 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1166 wxString extensions
;
1167 const wxArrayString
& exts
= filetype
.GetExtensions();
1168 size_t nExts
= exts
.GetCount();
1169 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1171 extensions
+= wxT(' ');
1173 extensions
+= exts
[nExt
];
1176 AddMimeTypeInfo(filetype
.GetMimeType(),
1178 filetype
.GetDescription());
1180 AddMailcapInfo(filetype
.GetMimeType(),
1181 filetype
.GetOpenCommand(),
1182 filetype
.GetPrintCommand(),
1184 filetype
.GetDescription());
1187 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
1188 const wxString
& strExtensions
,
1189 const wxString
& strDesc
)
1191 int index
= m_aTypes
.Index(strMimeType
);
1192 if ( index
== wxNOT_FOUND
) {
1194 m_aTypes
.Add(strMimeType
);
1195 m_aEntries
.Add(NULL
);
1196 m_aExtensions
.Add(strExtensions
);
1197 m_aDescriptions
.Add(strDesc
);
1200 // modify an existing one
1201 if ( !strDesc
.IsEmpty() ) {
1202 m_aDescriptions
[index
] = strDesc
; // replace old value
1204 m_aExtensions
[index
] += ' ' + strExtensions
;
1208 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
1209 const wxString
& strOpenCmd
,
1210 const wxString
& strPrintCmd
,
1211 const wxString
& strTest
,
1212 const wxString
& strDesc
)
1214 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
1216 int nIndex
= m_aTypes
.Index(strType
);
1217 if ( nIndex
== wxNOT_FOUND
) {
1219 m_aTypes
.Add(strType
);
1221 m_aEntries
.Add(entry
);
1222 m_aExtensions
.Add(wxT(""));
1223 m_aDescriptions
.Add(strDesc
);
1226 // always append the entry in the tail of the list - info added with
1227 // this function can only come from AddFallbacks()
1228 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1230 entry
->Append(entryOld
);
1232 m_aEntries
[nIndex
] = entry
;
1236 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1238 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
1239 strFileName
.c_str());
1241 wxTextFile
file(strFileName
);
1245 // the information we extract
1246 wxString strMimeType
, strDesc
, strExtensions
;
1248 size_t nLineCount
= file
.GetLineCount();
1249 const wxChar
*pc
= NULL
;
1250 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1252 // now we're at the start of the line
1253 pc
= file
[nLine
].c_str();
1256 // we didn't finish with the previous line yet
1261 while ( wxIsspace(*pc
) )
1264 // comment or blank line?
1265 if ( *pc
== wxT('#') || !*pc
) {
1266 // skip the whole line
1271 // detect file format
1272 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1273 if ( pEqualSign
== NULL
) {
1277 // first field is mime type
1278 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1283 while ( wxIsspace(*pc
) )
1286 // take all the rest of the string
1289 // no description...
1296 // the string on the left of '=' is the field name
1297 wxString
strLHS(pc
, pEqualSign
- pc
);
1300 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
1304 if ( *pc
== wxT('"') ) {
1305 // the string is quoted and ends at the matching quote
1306 pEnd
= wxStrchr(++pc
, wxT('"'));
1307 if ( pEnd
== NULL
) {
1308 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1310 strFileName
.c_str(), nLine
+ 1);
1314 // unquoted string ends at the first space or at the end of
1316 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
1320 // now we have the RHS (field value)
1321 wxString
strRHS(pc
, pEnd
- pc
);
1323 // check what follows this entry
1324 if ( *pEnd
== wxT('"') ) {
1329 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
1332 // if there is something left, it may be either a '\\' to continue
1333 // the line or the next field of the same entry
1334 bool entryEnded
= *pc
== wxT('\0'),
1335 nextFieldOnSameLine
= FALSE
;
1336 if ( !entryEnded
) {
1337 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
1340 // now see what we got
1341 if ( strLHS
== wxT("type") ) {
1342 strMimeType
= strRHS
;
1344 else if ( strLHS
== wxT("desc") ) {
1347 else if ( strLHS
== wxT("exts") ) {
1348 strExtensions
= strRHS
;
1351 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1352 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
1355 if ( !entryEnded
) {
1356 if ( !nextFieldOnSameLine
)
1358 //else: don't reset it
1360 // as we don't reset strMimeType, the next field in this entry
1361 // will be interpreted correctly.
1367 // although it doesn't seem to be covered by RFCs, some programs
1368 // (notably Netscape) create their entries with several comma
1369 // separated extensions (RFC mention the spaces only)
1370 strExtensions
.Replace(wxT(","), wxT(" "));
1372 // also deal with the leading dot
1373 if ( !strExtensions
.IsEmpty() && strExtensions
[0u] == wxT('.') )
1375 strExtensions
.erase(0, 1);
1378 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
1380 // finished with this line
1384 // check our data integriry
1385 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1386 m_aTypes
.Count() == m_aExtensions
.Count() &&
1387 m_aTypes
.Count() == m_aDescriptions
.Count() );
1392 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
1395 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
1396 strFileName
.c_str());
1398 wxTextFile
file(strFileName
);
1402 // see the comments near the end of function for the reason we need these
1403 // variables (search for the next occurence of them)
1404 // indices of MIME types (in m_aTypes) we already found in this file
1405 wxArrayInt aEntryIndices
;
1406 // aLastIndices[n] is the index of last element in
1407 // m_aEntries[aEntryIndices[n]] from this file
1408 wxArrayInt aLastIndices
;
1410 size_t nLineCount
= file
.GetLineCount();
1411 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1412 // now we're at the start of the line
1413 const wxChar
*pc
= file
[nLine
].c_str();
1416 while ( wxIsspace(*pc
) )
1419 // comment or empty string?
1420 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
1425 // what field are we currently in? The first 2 are fixed and there may
1426 // be an arbitrary number of other fields -- currently, we are not
1427 // interested in any of them, but we should parse them as well...
1433 } currentToken
= Field_Type
;
1435 // the flags and field values on the current line
1436 bool needsterminal
= FALSE
,
1437 copiousoutput
= FALSE
;
1443 curField
; // accumulator
1444 for ( bool cont
= TRUE
; cont
; pc
++ ) {
1447 // interpret the next character literally (notice that
1448 // backslash can be used for line continuation)
1449 if ( *++pc
== wxT('\0') ) {
1450 // fetch the next line.
1452 // pc currently points to nowhere, but after the next
1453 // pc++ in the for line it will point to the beginning
1454 // of the next line in the file
1455 pc
= file
[++nLine
].c_str() - 1;
1458 // just a normal character
1464 cont
= FALSE
; // end of line reached, exit the loop
1469 // store this field and start looking for the next one
1471 // trim whitespaces from both sides
1472 curField
.Trim(TRUE
).Trim(FALSE
);
1474 switch ( currentToken
) {
1477 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
1478 // we interpret "type" as "type/*"
1479 strType
+= wxT("/*");
1482 currentToken
= Field_OpenCmd
;
1486 strOpenCmd
= curField
;
1488 currentToken
= Field_Other
;
1493 // "good" mailcap entry?
1496 // is this something of the form foo=bar?
1497 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
1498 if ( pEq
!= NULL
) {
1499 wxString lhs
= curField
.BeforeFirst(wxT('=')),
1500 rhs
= curField
.AfterFirst(wxT('='));
1502 lhs
.Trim(TRUE
); // from right
1503 rhs
.Trim(FALSE
); // from left
1505 if ( lhs
== wxT("print") )
1507 else if ( lhs
== wxT("test") )
1509 else if ( lhs
== wxT("description") ) {
1510 // it might be quoted
1511 if ( rhs
[0u] == wxT('"') &&
1512 rhs
.Last() == wxT('"') ) {
1513 strDesc
= wxString(rhs
.c_str() + 1,
1520 else if ( lhs
== wxT("compose") ||
1521 lhs
== wxT("composetyped") ||
1522 lhs
== wxT("notes") ||
1523 lhs
== wxT("edit") )
1530 // no, it's a simple flag
1531 if ( curField
== wxT("needsterminal") )
1532 needsterminal
= TRUE
;
1533 else if ( curField
== wxT("copiousoutput")) {
1534 // copiousoutput impies that the
1535 // viewer is a console program
1537 copiousoutput
= TRUE
;
1547 if ( !IsKnownUnimportantField(curField
) )
1549 // don't flood the user with error
1550 // messages if we don't understand
1551 // something in his mailcap, but give
1552 // them in debug mode because this might
1553 // be useful for the programmer
1556 wxT("Mailcap file %s, line %d: "
1557 "unknown field '%s' for the "
1558 "MIME type '%s' ignored."),
1559 strFileName
.c_str(),
1568 // it already has this value
1569 //currentToken = Field_Other;
1573 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1576 // next token starts immediately after ';'
1585 // check that we really read something reasonable
1586 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
1587 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1589 strFileName
.c_str(), nLine
+ 1);
1592 // support for flags:
1593 // 1. create an xterm for 'needsterminal'
1594 // 2. append "| $PAGER" for 'copiousoutput'
1595 if ( copiousoutput
) {
1596 const wxChar
*p
= wxGetenv(_T("PAGER"));
1597 strOpenCmd
<< _T(" | ") << (p
? p
: _T("more"));
1600 if ( needsterminal
) {
1601 strOpenCmd
.Printf(_T("xterm -e sh -c '%s'"),
1602 strOpenCmd
.c_str());
1605 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
1609 // NB: because of complications below (we must get entries priority
1610 // right), we can't use AddMailcapInfo() here, unfortunately.
1611 strType
.MakeLower();
1612 int nIndex
= m_aTypes
.Index(strType
);
1613 if ( nIndex
== wxNOT_FOUND
) {
1615 m_aTypes
.Add(strType
);
1617 m_aEntries
.Add(entry
);
1618 m_aExtensions
.Add(wxT(""));
1619 m_aDescriptions
.Add(strDesc
);
1622 // modify the existing entry: the entries in one and the same
1623 // file are read in top-to-bottom order, i.e. the entries read
1624 // first should be tried before the entries below. However,
1625 // the files read later should override the settings in the
1626 // files read before (except if fallback is TRUE), thus we
1627 // Insert() the new entry to the list if it has already
1628 // occured in _this_ file, but Prepend() it if it occured in
1629 // some of the previous ones and Append() to it in the
1633 // 'fallback' parameter prevents the entries from this
1634 // file from overriding the other ones - always append
1635 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1637 entry
->Append(entryOld
);
1639 m_aEntries
[nIndex
] = entry
;
1642 int entryIndex
= aEntryIndices
.Index(nIndex
);
1643 if ( entryIndex
== wxNOT_FOUND
) {
1644 // first time in this file
1645 aEntryIndices
.Add(nIndex
);
1646 aLastIndices
.Add(0);
1648 entry
->Prepend(m_aEntries
[nIndex
]);
1649 m_aEntries
[nIndex
] = entry
;
1652 // not the first time in _this_ file
1653 size_t nEntryIndex
= (size_t)entryIndex
;
1654 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1656 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
1658 m_aEntries
[nIndex
] = entry
;
1660 // the indices were shifted by 1
1661 aLastIndices
[nEntryIndex
]++;
1665 if ( !strDesc
.IsEmpty() ) {
1666 // replace the old one - what else can we do??
1667 m_aDescriptions
[nIndex
] = strDesc
;
1672 // check our data integriry
1673 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1674 m_aTypes
.Count() == m_aExtensions
.Count() &&
1675 m_aTypes
.Count() == m_aDescriptions
.Count() );
1681 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1686 size_t count
= m_aTypes
.GetCount();
1687 for ( size_t n
= 0; n
< count
; n
++ )
1689 // don't return template types from here (i.e. anything containg '*')
1691 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
1693 mimetypes
.Add(type
);
1697 return mimetypes
.GetCount();
1700 // ----------------------------------------------------------------------------
1701 // private functions
1702 // ----------------------------------------------------------------------------
1704 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
1706 static const wxChar
*knownFields
[] =
1708 _T("x-mozilla-flags"),
1710 _T("textualnewlines"),
1713 wxString field
= fieldAll
.BeforeFirst(_T('='));
1714 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
1716 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
1724 // wxUSE_FILE && wxUSE_TEXTFILE