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"));
426 wxGetHomeDir( &gnomedir
);
427 gnomedir
+= _T("/.gnome");
428 dirs
.Add( gnomedir
);
430 size_t nDirs
= dirs
.GetCount();
431 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
433 LoadKeyFilesFromDir(dirs
[nDir
]);
439 bool wxGNOMEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
446 int index
= ms_mimetypes
.Index(mimetype
);
447 if ( index
== wxNOT_FOUND
)
450 wxString iconname
= ms_icons
[(size_t)index
];
453 *icon
= wxIcon(iconname
);
455 // helpful for testing in console mode
456 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
457 mimetype
.c_str(), iconname
.c_str());
463 // ----------------------------------------------------------------------------
465 // ----------------------------------------------------------------------------
467 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
468 // may be found in either of the following locations
470 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
471 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
473 // The format of a .kdelnk file is almost the same as the one used by
474 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
475 // value for the entry "Type"
477 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString
& dirbase
,
478 const wxString
& subdir
,
479 const wxString
& filename
,
480 const wxArrayString
& icondirs
)
482 wxFFile
file(dirbase
+ filename
);
483 if ( !file
.IsOpened() )
486 // construct mimetype from the directory name and the basename of the
487 // file (it always has .kdelnk extension)
489 mimetype
<< subdir
<< _T('/') << filename
.BeforeLast(_T('.'));
491 // these files are small, slurp the entire file at once
493 if ( !file
.ReadAll(&text
) )
499 // before trying to find an icon, grab mimetype information
500 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
501 // have edited it in control panel...)
503 wxString mime_extension
, mime_desc
;
506 if (wxGetLocale() != NULL
)
507 mime_desc
= _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
508 if (pos
== wxNOT_FOUND
) mime_desc
= _T("Comment=");
509 pos
= text
.Find(mime_desc
);
510 if (pos
== wxNOT_FOUND
) mime_desc
= wxEmptyString
;
513 pc
= text
.c_str() + pos
+ mime_desc
.Length();
514 mime_desc
= wxEmptyString
;
515 while ( *pc
&& *pc
!= _T('\n') ) mime_desc
+= *pc
++;
518 pos
= text
.Find(_T("Patterns="));
519 if (pos
!= wxNOT_FOUND
)
522 pc
= text
.c_str() + pos
+ 9;
523 while ( *pc
&& *pc
!= _T('\n') ) exts
+= *pc
++;
524 wxStringTokenizer
tokenizer(exts
, _T(";"));
527 while (tokenizer
.HasMoreTokens())
529 e
= tokenizer
.GetNextToken();
530 if (e
.Left(2) != _T("*.")) continue; // don't support too difficult patterns
531 mime_extension
<< e
.Mid(2);
532 mime_extension
<< _T(' ');
534 mime_extension
.RemoveLast();
537 ms_infoTypes
.Add(mimetype
);
538 ms_infoDescriptions
.Add(mime_desc
);
539 ms_infoExtensions
.Add(mime_extension
);
541 // ok, now we can take care of icon:
543 pos
= text
.Find(_T("Icon="));
544 if ( pos
== wxNOT_FOUND
)
552 pc
= text
.c_str() + pos
+ 5; // 5 == strlen("Icon=")
553 while ( *pc
&& *pc
!= _T('\n') )
560 // we must check if the file exists because it may be stored
561 // in many locations, at least ~/.kde and $KDEDIR
562 size_t nDir
, nDirs
= icondirs
.GetCount();
563 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
564 if (wxFileExists(icondirs
[nDir
] + icon
))
566 icon
.Prepend(icondirs
[nDir
]);
569 if (nDir
== nDirs
) return; //does not exist
571 // do we already have this MIME type?
572 int i
= ms_mimetypes
.Index(mimetype
);
573 if ( i
== wxNOT_FOUND
)
576 size_t n
= ms_mimetypes
.Add(mimetype
);
577 ms_icons
.Insert(icon
, n
);
581 // replace the old value
582 ms_icons
[(size_t)i
] = icon
;
587 void wxKDEIconHandler::LoadLinksForMimeType(const wxString
& dirbase
,
588 const wxString
& subdir
,
589 const wxArrayString
& icondirs
)
591 wxString dirname
= dirbase
;
594 if ( !dir
.IsOpened() )
600 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
603 LoadLinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
605 cont
= dir
.GetNext(&filename
);
609 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString
& dirbase
,
610 const wxArrayString
& icondirs
)
612 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
613 _T("base directory shouldn't end with a slash") );
615 wxString dirname
= dirbase
;
616 dirname
<< _T("/mimelnk");
618 if ( !wxDir::Exists(dirname
) )
622 if ( !dir
.IsOpened() )
625 // we will concatenate it with dir name to get the full path below
629 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
632 LoadLinksForMimeType(dirname
, subdir
, icondirs
);
634 cont
= dir
.GetNext(&subdir
);
638 void wxKDEIconHandler::Init()
641 wxArrayString icondirs
;
643 // settings in ~/.kde have maximal priority
644 dirs
.Add(wxGetHomeDir() + _T("/.kde/share"));
645 icondirs
.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
647 // the variable KDEDIR is set when KDE is running
648 const char *kdedir
= getenv("KDEDIR");
651 dirs
.Add(wxString(kdedir
) + _T("/share"));
652 icondirs
.Add(wxString(kdedir
) + _T("/share/icons/"));
656 // try to guess KDEDIR
657 dirs
.Add(_T("/usr/share"));
658 dirs
.Add(_T("/opt/kde/share"));
659 icondirs
.Add(_T("/usr/share/icons/"));
660 icondirs
.Add(_T("/opt/kde/share/icons/"));
663 size_t nDirs
= dirs
.GetCount();
664 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
666 LoadLinkFilesFromDir(dirs
[nDir
], icondirs
);
672 bool wxKDEIconHandler::GetIcon(const wxString
& mimetype
, wxIcon
*icon
)
679 int index
= ms_mimetypes
.Index(mimetype
);
680 if ( index
== wxNOT_FOUND
)
683 wxString iconname
= ms_icons
[(size_t)index
];
686 *icon
= wxIcon(iconname
);
688 // helpful for testing in console mode
689 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
690 mimetype
.c_str(), iconname
.c_str());
697 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl
*manager
)
699 if ( !m_inited
) Init();
701 size_t cnt
= ms_infoTypes
.GetCount();
702 for (unsigned i
= 0; i
< cnt
; i
++)
703 manager
-> AddMimeTypeInfo(ms_infoTypes
[i
], ms_infoExtensions
[i
], ms_infoDescriptions
[i
]);
707 // ----------------------------------------------------------------------------
708 // wxFileTypeImpl (Unix)
709 // ----------------------------------------------------------------------------
712 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters
& params
) const
715 MailCapEntry
*entry
= m_manager
->m_aEntries
[m_index
];
716 while ( entry
!= NULL
) {
717 // notice that an empty command would always succeed (it's ok)
718 command
= wxFileType::ExpandCommand(entry
->GetTestCmd(), params
);
720 if ( command
.IsEmpty() || (wxSystem(command
) == 0) ) {
722 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
723 command
.c_str(), params
.GetMimeType().c_str());
727 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
728 command
.c_str(), params
.GetMimeType().c_str());
731 entry
= entry
->GetNext();
737 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
) const
740 (void)GetMimeType(&mimetype
);
742 ArrayIconHandlers
& handlers
= m_manager
->GetIconHandlers();
743 size_t count
= handlers
.GetCount();
744 for ( size_t n
= 0; n
< count
; n
++ )
746 if ( handlers
[n
]->GetIcon(mimetype
, icon
) )
754 wxFileTypeImpl::GetExpandedCommand(wxString
*expandedCmd
,
755 const wxFileType::MessageParameters
& params
,
758 MailCapEntry
*entry
= GetEntry(params
);
759 if ( entry
== NULL
) {
760 // all tests failed...
764 wxString cmd
= open
? entry
->GetOpenCmd() : entry
->GetPrintCmd();
765 if ( cmd
.IsEmpty() ) {
766 // may happen, especially for "print"
770 *expandedCmd
= wxFileType::ExpandCommand(cmd
, params
);
774 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
776 wxString strExtensions
= m_manager
->GetExtension(m_index
);
779 // one extension in the space or comma delimitid list
781 for ( const wxChar
*p
= strExtensions
; ; p
++ ) {
782 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
783 if ( !strExt
.IsEmpty() ) {
784 extensions
.Add(strExt
);
787 //else: repeated spaces (shouldn't happen, but it's not that
788 // important if it does happen)
790 if ( *p
== wxT('\0') )
793 else if ( *p
== wxT('.') ) {
794 // remove the dot from extension (but only if it's the first char)
795 if ( !strExt
.IsEmpty() ) {
798 //else: no, don't append it
808 // ----------------------------------------------------------------------------
809 // wxMimeTypesManagerImpl (Unix)
810 // ----------------------------------------------------------------------------
813 ArrayIconHandlers
& wxMimeTypesManagerImpl::GetIconHandlers()
815 if ( ms_iconHandlers
.GetCount() == 0 )
817 ms_iconHandlers
.Add(&gs_iconHandlerGNOME
);
818 ms_iconHandlers
.Add(&gs_iconHandlerKDE
);
821 return ms_iconHandlers
;
824 // read system and user mailcaps (TODO implement mime.types support)
825 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
827 // directories where we look for mailcap and mime.types by default
828 // (taken from metamail(1) sources)
829 static const wxChar
*aStandardLocations
[] =
833 wxT("/usr/local/etc"),
835 wxT("/usr/public/lib")
838 // first read the system wide file(s)
840 for ( n
= 0; n
< WXSIZEOF(aStandardLocations
); n
++ ) {
841 wxString dir
= aStandardLocations
[n
];
843 wxString file
= dir
+ wxT("/mailcap");
844 if ( wxFile::Exists(file
) ) {
848 file
= dir
+ wxT("/mime.types");
849 if ( wxFile::Exists(file
) ) {
854 wxString strHome
= wxGetenv(wxT("HOME"));
856 // and now the users mailcap
857 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
858 if ( wxFile::Exists(strUserMailcap
) ) {
859 ReadMailcap(strUserMailcap
);
862 // read the users mime.types
863 wxString strUserMimeTypes
= strHome
+ wxT("/.mime.types");
864 if ( wxFile::Exists(strUserMimeTypes
) ) {
865 ReadMimeTypes(strUserMimeTypes
);
868 // read KDE/GNOME tables
869 ArrayIconHandlers
& handlers
= GetIconHandlers();
870 size_t count
= handlers
.GetCount();
871 for ( n
= 0; n
< count
; n
++ )
872 handlers
[n
]->GetMimeInfoRecords(this);
876 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
878 size_t count
= m_aExtensions
.GetCount();
879 for ( size_t n
= 0; n
< count
; n
++ ) {
880 wxString extensions
= m_aExtensions
[n
];
881 while ( !extensions
.IsEmpty() ) {
882 wxString field
= extensions
.BeforeFirst(wxT(' '));
883 extensions
= extensions
.AfterFirst(wxT(' '));
885 // consider extensions as not being case-sensitive
886 if ( field
.IsSameAs(ext
, FALSE
/* no case */) ) {
888 wxFileType
*fileType
= new wxFileType
;
889 fileType
->m_impl
->Init(this, n
);
901 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
903 // mime types are not case-sensitive
904 wxString
mimetype(mimeType
);
905 mimetype
.MakeLower();
907 // first look for an exact match
908 int index
= m_aTypes
.Index(mimetype
);
909 if ( index
== wxNOT_FOUND
) {
910 // then try to find "text/*" as match for "text/plain" (for example)
911 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
912 // the whole string - ok.
913 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
915 size_t nCount
= m_aTypes
.Count();
916 for ( size_t n
= 0; n
< nCount
; n
++ ) {
917 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
918 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
925 if ( index
!= wxNOT_FOUND
) {
926 wxFileType
*fileType
= new wxFileType
;
927 fileType
->m_impl
->Init(this, index
);
937 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
940 const wxArrayString
& exts
= filetype
.GetExtensions();
941 size_t nExts
= exts
.GetCount();
942 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
944 extensions
+= wxT(' ');
946 extensions
+= exts
[nExt
];
949 AddMimeTypeInfo(filetype
.GetMimeType(),
951 filetype
.GetDescription());
953 AddMailcapInfo(filetype
.GetMimeType(),
954 filetype
.GetOpenCommand(),
955 filetype
.GetPrintCommand(),
957 filetype
.GetDescription());
960 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
961 const wxString
& strExtensions
,
962 const wxString
& strDesc
)
964 int index
= m_aTypes
.Index(strMimeType
);
965 if ( index
== wxNOT_FOUND
) {
967 m_aTypes
.Add(strMimeType
);
968 m_aEntries
.Add(NULL
);
969 m_aExtensions
.Add(strExtensions
);
970 m_aDescriptions
.Add(strDesc
);
973 // modify an existing one
974 if ( !strDesc
.IsEmpty() ) {
975 m_aDescriptions
[index
] = strDesc
; // replace old value
977 m_aExtensions
[index
] += ' ' + strExtensions
;
981 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
982 const wxString
& strOpenCmd
,
983 const wxString
& strPrintCmd
,
984 const wxString
& strTest
,
985 const wxString
& strDesc
)
987 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
, strPrintCmd
, strTest
);
989 int nIndex
= m_aTypes
.Index(strType
);
990 if ( nIndex
== wxNOT_FOUND
) {
992 m_aTypes
.Add(strType
);
994 m_aEntries
.Add(entry
);
995 m_aExtensions
.Add(wxT(""));
996 m_aDescriptions
.Add(strDesc
);
999 // always append the entry in the tail of the list - info added with
1000 // this function can only come from AddFallbacks()
1001 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1003 entry
->Append(entryOld
);
1005 m_aEntries
[nIndex
] = entry
;
1009 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
1011 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName
.c_str());
1013 wxTextFile
file(strFileName
);
1017 // the information we extract
1018 wxString strMimeType
, strDesc
, strExtensions
;
1020 size_t nLineCount
= file
.GetLineCount();
1021 const wxChar
*pc
= NULL
;
1022 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1024 // now we're at the start of the line
1025 pc
= file
[nLine
].c_str();
1028 // we didn't finish with the previous line yet
1033 while ( wxIsspace(*pc
) )
1036 // comment or blank line?
1037 if ( *pc
== wxT('#') || !*pc
) {
1038 // skip the whole line
1043 // detect file format
1044 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
1045 if ( pEqualSign
== NULL
) {
1049 // first field is mime type
1050 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
1055 while ( wxIsspace(*pc
) )
1058 // take all the rest of the string
1061 // no description...
1068 // the string on the left of '=' is the field name
1069 wxString
strLHS(pc
, pEqualSign
- pc
);
1072 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
1076 if ( *pc
== wxT('"') ) {
1077 // the string is quoted and ends at the matching quote
1078 pEnd
= wxStrchr(++pc
, wxT('"'));
1079 if ( pEnd
== NULL
) {
1080 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1082 strFileName
.c_str(), nLine
+ 1);
1086 // unquoted string ends at the first space
1087 for ( pEnd
= pc
; !wxIsspace(*pEnd
); pEnd
++ )
1091 // now we have the RHS (field value)
1092 wxString
strRHS(pc
, pEnd
- pc
);
1094 // check what follows this entry
1095 if ( *pEnd
== wxT('"') ) {
1100 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
1103 // if there is something left, it may be either a '\\' to continue
1104 // the line or the next field of the same entry
1105 bool entryEnded
= *pc
== wxT('\0'),
1106 nextFieldOnSameLine
= FALSE
;
1107 if ( !entryEnded
) {
1108 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
1111 // now see what we got
1112 if ( strLHS
== wxT("type") ) {
1113 strMimeType
= strRHS
;
1115 else if ( strLHS
== wxT("desc") ) {
1118 else if ( strLHS
== wxT("exts") ) {
1119 strExtensions
= strRHS
;
1122 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1123 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
1126 if ( !entryEnded
) {
1127 if ( !nextFieldOnSameLine
)
1129 //else: don't reset it
1131 // as we don't reset strMimeType, the next field in this entry
1132 // will be interpreted correctly.
1138 // although it doesn't seem to be covered by RFCs, some programs
1139 // (notably Netscape) create their entries with several comma
1140 // separated extensions (RFC mention the spaces only)
1141 strExtensions
.Replace(wxT(","), wxT(" "));
1143 // also deal with the leading dot
1144 if ( !strExtensions
.IsEmpty() && strExtensions
[0u] == wxT('.') )
1146 strExtensions
.erase(0, 1);
1149 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
1151 // finished with this line
1155 // check our data integriry
1156 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1157 m_aTypes
.Count() == m_aExtensions
.Count() &&
1158 m_aTypes
.Count() == m_aDescriptions
.Count() );
1163 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
1166 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName
.c_str());
1168 wxTextFile
file(strFileName
);
1172 // see the comments near the end of function for the reason we need these
1173 // variables (search for the next occurence of them)
1174 // indices of MIME types (in m_aTypes) we already found in this file
1175 wxArrayInt aEntryIndices
;
1176 // aLastIndices[n] is the index of last element in
1177 // m_aEntries[aEntryIndices[n]] from this file
1178 wxArrayInt aLastIndices
;
1180 size_t nLineCount
= file
.GetLineCount();
1181 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ ) {
1182 // now we're at the start of the line
1183 const wxChar
*pc
= file
[nLine
].c_str();
1186 while ( wxIsspace(*pc
) )
1189 // comment or empty string?
1190 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
1195 // what field are we currently in? The first 2 are fixed and there may
1196 // be an arbitrary number of other fields -- currently, we are not
1197 // interested in any of them, but we should parse them as well...
1203 } currentToken
= Field_Type
;
1205 // the flags and field values on the current line
1206 bool needsterminal
= FALSE
,
1207 copiousoutput
= FALSE
;
1213 curField
; // accumulator
1214 for ( bool cont
= TRUE
; cont
; pc
++ ) {
1217 // interpret the next character literally (notice that
1218 // backslash can be used for line continuation)
1219 if ( *++pc
== wxT('\0') ) {
1220 // fetch the next line.
1222 // pc currently points to nowhere, but after the next
1223 // pc++ in the for line it will point to the beginning
1224 // of the next line in the file
1225 pc
= file
[++nLine
].c_str() - 1;
1228 // just a normal character
1234 cont
= FALSE
; // end of line reached, exit the loop
1239 // store this field and start looking for the next one
1241 // trim whitespaces from both sides
1242 curField
.Trim(TRUE
).Trim(FALSE
);
1244 switch ( currentToken
) {
1247 if ( strType
.Find(wxT('/')) == wxNOT_FOUND
) {
1248 // we interpret "type" as "type/*"
1249 strType
+= wxT("/*");
1252 currentToken
= Field_OpenCmd
;
1256 strOpenCmd
= curField
;
1258 currentToken
= Field_Other
;
1263 // "good" mailcap entry?
1266 // is this something of the form foo=bar?
1267 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
1268 if ( pEq
!= NULL
) {
1269 wxString lhs
= curField
.BeforeFirst(wxT('=')),
1270 rhs
= curField
.AfterFirst(wxT('='));
1272 lhs
.Trim(TRUE
); // from right
1273 rhs
.Trim(FALSE
); // from left
1275 if ( lhs
== wxT("print") )
1277 else if ( lhs
== wxT("test") )
1279 else if ( lhs
== wxT("description") ) {
1280 // it might be quoted
1281 if ( rhs
[0u] == wxT('"') &&
1282 rhs
.Last() == wxT('"') ) {
1283 strDesc
= wxString(rhs
.c_str() + 1,
1290 else if ( lhs
== wxT("compose") ||
1291 lhs
== wxT("composetyped") ||
1292 lhs
== wxT("notes") ||
1293 lhs
== wxT("edit") )
1300 // no, it's a simple flag
1301 // TODO support the flags:
1302 // 1. create an xterm for 'needsterminal'
1303 // 2. append "| $PAGER" for 'copiousoutput'
1304 if ( curField
== wxT("needsterminal") )
1305 needsterminal
= TRUE
;
1306 else if ( curField
== wxT("copiousoutput") )
1307 copiousoutput
= TRUE
;
1308 else if ( curField
== wxT("textualnewlines") )
1316 // we don't understand this field, but
1317 // Netscape stores info in it, so don't warn
1319 if ( curField
.Left(16u) != "x-mozilla-flags=" )
1321 // don't flood the user with error
1322 // messages if we don't understand
1323 // something in his mailcap, but give
1324 // them in debug mode because this might
1325 // be useful for the programmer
1328 wxT("Mailcap file %s, line %d: "
1329 "unknown field '%s' for the "
1330 "MIME type '%s' ignored."),
1331 strFileName
.c_str(),
1340 // it already has this value
1341 //currentToken = Field_Other;
1345 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1348 // next token starts immediately after ';'
1357 // check that we really read something reasonable
1358 if ( currentToken
== Field_Type
|| currentToken
== Field_OpenCmd
) {
1359 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1361 strFileName
.c_str(), nLine
+ 1);
1364 MailCapEntry
*entry
= new MailCapEntry(strOpenCmd
,
1368 // NB: because of complications below (we must get entries priority
1369 // right), we can't use AddMailcapInfo() here, unfortunately.
1370 strType
.MakeLower();
1371 int nIndex
= m_aTypes
.Index(strType
);
1372 if ( nIndex
== wxNOT_FOUND
) {
1374 m_aTypes
.Add(strType
);
1376 m_aEntries
.Add(entry
);
1377 m_aExtensions
.Add(wxT(""));
1378 m_aDescriptions
.Add(strDesc
);
1381 // modify the existing entry: the entries in one and the same
1382 // file are read in top-to-bottom order, i.e. the entries read
1383 // first should be tried before the entries below. However,
1384 // the files read later should override the settings in the
1385 // files read before (except if fallback is TRUE), thus we
1386 // Insert() the new entry to the list if it has already
1387 // occured in _this_ file, but Prepend() it if it occured in
1388 // some of the previous ones and Append() to it in the
1392 // 'fallback' parameter prevents the entries from this
1393 // file from overriding the other ones - always append
1394 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1396 entry
->Append(entryOld
);
1398 m_aEntries
[nIndex
] = entry
;
1401 int entryIndex
= aEntryIndices
.Index(nIndex
);
1402 if ( entryIndex
== wxNOT_FOUND
) {
1403 // first time in this file
1404 aEntryIndices
.Add(nIndex
);
1405 aLastIndices
.Add(0);
1407 entry
->Prepend(m_aEntries
[nIndex
]);
1408 m_aEntries
[nIndex
] = entry
;
1411 // not the first time in _this_ file
1412 size_t nEntryIndex
= (size_t)entryIndex
;
1413 MailCapEntry
*entryOld
= m_aEntries
[nIndex
];
1415 entry
->Insert(entryOld
, aLastIndices
[nEntryIndex
]);
1417 m_aEntries
[nIndex
] = entry
;
1419 // the indices were shifted by 1
1420 aLastIndices
[nEntryIndex
]++;
1424 if ( !strDesc
.IsEmpty() ) {
1425 // replace the old one - what else can we do??
1426 m_aDescriptions
[nIndex
] = strDesc
;
1431 // check our data integriry
1432 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1433 m_aTypes
.Count() == m_aExtensions
.Count() &&
1434 m_aTypes
.Count() == m_aDescriptions
.Count() );
1440 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
1445 size_t count
= m_aTypes
.GetCount();
1446 for ( size_t n
= 0; n
< count
; n
++ )
1448 // don't return template types from here (i.e. anything containg '*')
1450 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
1452 mimetypes
.Add(type
);
1456 return mimetypes
.GetCount();
1460 // wxUSE_FILE && wxUSE_TEXTFILE