1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/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 licence (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
12 // known bugs; there may be others!! chris elliott, biol75@york.ac.uk 27 Mar 01
14 // 1) .mailcap and .mimetypes can be either in a netscape or metamail format
15 // and entries may get confused during writing (I've tried to fix this; please let me know
16 // any files that fail)
17 // 2) KDE and Gnome do not yet fully support international read/write
18 // 3) Gnome key lines like open.latex."LaTeX this file"=latex %f will have odd results
19 // 4) writing to files comments out the existing data; I hope this avoids losing
20 // any data which we could not read, and data which we did not store like test=
21 // 5) results from reading files with multiple entries (especially matches with type/* )
22 // may (or may not) work for getXXX commands
23 // 6) Loading the png icons in Gnome doesn't work for me...
24 // 7) In Gnome, if keys.mime exists but keys.users does not, there is
25 // an error message in debug mode, but the file is still written OK
26 // 8) Deleting entries is only allowed from the user file; sytem wide entries
27 // will be preserved during unassociate
28 // 9) KDE does not yet handle multiple actions; Netscape mode never will
30 // TODO: this file is a mess, we need to split it and review everything (VZ)
32 // for compilers that support precompilation, includes "wx.h".
33 #include "wx/wxprec.h"
39 #if wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE
41 #include "wx/unix/mimetype.h"
44 #include "wx/dynarray.h"
45 #include "wx/string.h"
52 #include "wx/confbase.h"
55 #include "wx/textfile.h"
57 #include "wx/tokenzr.h"
58 #include "wx/iconloc.h"
59 #include "wx/filename.h"
61 #include "wx/apptrait.h"
65 #include "wx/gtk/gnome/gvfs.h"
68 // other standard headers
71 // this class is a wxTextFile specialization for dealing with files storing
72 // various MIME-related information
74 // it should be used instead of wxTextFile even if none of its additional
75 // methods are used just because it handles files with mixed encodings (often
76 // the case for MIME files which contain strings for different languages)
77 // correctly, see OnRead()
78 class wxMimeTextFile
: public wxTextFile
82 wxMimeTextFile () : wxTextFile () { }
83 wxMimeTextFile(const wxString
& strFile
) : wxTextFile(strFile
) { }
85 int pIndexOf(const wxString
& sSearch
,
86 bool bIncludeComments
= false,
89 wxString sTest
= sSearch
;
91 for(size_t i
= iStart
; i
< GetLineCount(); i
++)
93 wxString sLine
= GetLine(i
).Trim(false);
94 if(bIncludeComments
|| ! sLine
.StartsWith(wxT("#")))
97 if(sLine
.StartsWith(sTest
))
104 bool CommentLine(int nIndex
)
108 if (nIndex
>= (int)GetLineCount() )
111 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
115 bool CommentLine(const wxString
& sTest
)
117 int nIndex
= pIndexOf(sTest
);
120 if (nIndex
>= (int)GetLineCount() )
123 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
127 wxString
GetVerb(size_t i
)
129 if (i
> GetLineCount() )
130 return wxEmptyString
;
132 wxString sTmp
= GetLine(i
).BeforeFirst(wxT('='));
136 wxString
GetCmd(size_t i
)
138 if (i
> GetLineCount() )
139 return wxEmptyString
;
141 wxString sTmp
= GetLine(i
).AfterFirst(wxT('='));
146 // we override this virtual method because we want to always use UTF-8
147 // conversion allowing for invalid characters as MIME information files
148 // often contain lines in different encodings and can't be read using any
149 // single conversion in Unicode build, so we just try to read what we can
150 // suing the most common encoding (UTF-8 is almost ubiquitous nowadays) and
152 virtual bool OnRead(const wxMBConv
& WXUNUSED(conv
))
154 return wxTextFile::OnRead(
155 wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_OCTAL
));
159 // in case we're compiling in non-GUI mode
160 class WXDLLEXPORT wxIcon
;
162 // ----------------------------------------------------------------------------
164 // ----------------------------------------------------------------------------
166 // MIME code tracing mask
167 #define TRACE_MIME wxT("mime")
169 // give trace messages about the results of mailcap tests
170 #define TRACE_MIME_TEST wxT("mimetest")
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
176 // there are some fields which we don't understand but for which we don't give
177 // warnings as we know that they're not important - this function is used to
179 static bool IsKnownUnimportantField(const wxString
& field
);
181 // ----------------------------------------------------------------------------
183 // ----------------------------------------------------------------------------
186 // This class uses both mailcap and mime.types to gather information about file
189 // The information about mailcap file was extracted from metamail(1) sources
190 // and documentation and subsequently revised when I found the RFC 1524
193 // Format of mailcap file: spaces are ignored, each line is either a comment
194 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
195 // A backslash can be used to quote semicolons and newlines (and, in fact,
196 // anything else including itself).
198 // The first field is always the MIME type in the form of type/subtype (see RFC
199 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
200 // "type" which means the same as "type/*", although I'm not sure whether this
203 // The second field is always the command to run. It is subject to
204 // parameter/filename expansion described below.
206 // All the following fields are optional and may not be present at all. If
207 // they're present they may appear in any order, although each of them should
208 // appear only once. The optional fields are the following:
209 // * notes=xxx is an uninterpreted string which is silently ignored
210 // * test=xxx is the command to be used to determine whether this mailcap line
211 // applies to our data or not. The RHS of this field goes through the
212 // parameter/filename expansion (as the 2nd field) and the resulting string
213 // is executed. The line applies only if the command succeeds, i.e. returns 0
215 // * print=xxx is the command to be used to print (and not view) the data of
216 // this type (parameter/filename expansion is done here too)
217 // * edit=xxx is the command to open/edit the data of this type
218 // * needsterminal means that a new interactive console must be created for
220 // * copiousoutput means that the viewer doesn't interact with the user but
221 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
222 // good example), thus it might be a good idea to use some kind of paging
224 // * textualnewlines means not to perform CR/LF translation (not honored)
225 // * compose and composetyped fields are used to determine the program to be
226 // called to create a new message pert in the specified format (unused).
228 // Parameter/filename expansion:
229 // * %s is replaced with the (full) file name
230 // * %t is replaced with MIME type/subtype of the entry
231 // * for multipart type only %n is replaced with the nnumber of parts and %F is
232 // replaced by an array of (content-type, temporary file name) pairs for all
233 // message parts (TODO)
234 // * %{parameter} is replaced with the value of parameter taken from
235 // Content-type header line of the message.
238 // There are 2 possible formats for mime.types file, one entry per line (used
239 // for global mime.types and called Mosaic format) and "expanded" format where
240 // an entry takes multiple lines (used for users mime.types and called
243 // For both formats spaces are ignored and lines starting with a '#' are
244 // comments. Each record has one of two following forms:
245 // a) for "brief" format:
246 // <mime type> <space separated list of extensions>
247 // b) for "expanded" format:
248 // type=<mime type> BACKSLASH
249 // desc="<description>" BACKSLASH
250 // exts="<comma separated list of extensions>"
252 // (where BACKSLASH is a literal '\\' which we can't put here because cpp
255 // We try to autodetect the format of mime.types: if a non-comment line starts
256 // with "type=" we assume the second format, otherwise the first one.
258 // there may be more than one entry for one and the same mime type, to
259 // choose the right one we have to run the command specified in the test
260 // field on our data.
262 // ----------------------------------------------------------------------------
264 // ----------------------------------------------------------------------------
266 // GNOME stores the info we're interested in in several locations:
267 // 1. xxx.keys files under /usr/share/mime-info
268 // 2. xxx.keys files under ~/.gnome/mime-info
270 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
271 // just before the field name.
274 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString
& filename
,
275 const wxArrayString
& dirs
)
277 wxMimeTextFile
textfile(filename
);
278 if ( !textfile
.Open() )
281 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
284 wxArrayString
search_dirs( dirs
);
286 // values for the entry being parsed
287 wxString curMimeType
, curIconFile
;
288 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
290 wxArrayString strExtensions
;
294 size_t nLineCount
= textfile
.GetLineCount();
296 while ( nLine
< nLineCount
)
298 pc
= textfile
[nLine
].c_str();
299 if ( *pc
!= wxT('#') )
302 wxLogTrace(TRACE_MIME
, wxT("--- Reading from Gnome file %s '%s' ---"),
303 filename
.c_str(), pc
);
305 // trim trailing space and tab
306 while ((*pc
== wxT(' ')) || (*pc
== wxT('\t')))
310 int equal_pos
= sTmp
.Find( wxT('=') );
313 wxString left_of_equal
= sTmp
.Left( equal_pos
);
314 const wxChar
*right_of_equal
= pc
;
315 right_of_equal
+= equal_pos
+1;
317 if (left_of_equal
== wxT("icon_filename"))
320 curIconFile
= right_of_equal
;
322 wxFileName
newFile( curIconFile
);
323 if (newFile
.IsRelative() || newFile
.FileExists())
325 size_t nDirs
= search_dirs
.GetCount();
327 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
329 newFile
.SetPath( search_dirs
[nDir
] );
330 newFile
.AppendDir( wxT("pixmaps") );
331 newFile
.AppendDir( wxT("document-icons") );
332 newFile
.SetExt( wxT("png") );
333 if (newFile
.FileExists())
335 curIconFile
= newFile
.GetFullPath();
336 // reorder search_dirs for speedup (fewer
337 // calls to FileExist() required)
340 const wxString
&tmp
= search_dirs
[nDir
];
341 search_dirs
.RemoveAt( nDir
);
342 search_dirs
.Insert( tmp
, 0 );
349 else if (left_of_equal
== wxT("open"))
351 sTmp
= right_of_equal
;
352 sTmp
.Replace( wxT("%f"), wxT("%s") );
353 sTmp
.Prepend( wxT("open=") );
356 else if (left_of_equal
== wxT("view"))
358 sTmp
= right_of_equal
;
359 sTmp
.Replace( wxT("%f"), wxT("%s") );
360 sTmp
.Prepend( wxT("view=") );
363 else if (left_of_equal
== wxT("print"))
365 sTmp
= right_of_equal
;
366 sTmp
.Replace( wxT("%f"), wxT("%s") );
367 sTmp
.Prepend( wxT("print=") );
370 else if (left_of_equal
== wxT("description"))
372 strDesc
= right_of_equal
;
374 else if (left_of_equal
== wxT("short_list_application_ids_for_novice_user_level"))
376 sTmp
= right_of_equal
;
377 if (sTmp
.Contains( wxT(",") ))
378 sTmp
= sTmp
.BeforeFirst( wxT(',') );
379 sTmp
.Prepend( wxT("open=") );
380 sTmp
.Append( wxT(" %s") );
384 } // emd of has an equals sign
387 // not a comment and not an equals sign
388 if (sTmp
.Contains(wxT('/')))
390 // this is the start of the new mimetype
391 // overwrite any existing data
392 if (! curMimeType
.empty())
394 AddToMimeData( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
396 // now get ready for next bit
397 entry
= new wxMimeTypeCommands
;
400 curMimeType
= sTmp
.BeforeFirst(wxT(':'));
403 } // end of not a comment
405 // ignore blank lines
407 } // end of while, save any data
409 if ( curMimeType
.empty() )
412 AddToMimeData( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
415 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString
& filename
)
417 wxMimeTextFile
textfile(filename
);
418 if ( !textfile
.Open() )
421 wxLogTrace(TRACE_MIME
,
422 wxT("--- Opened Gnome file %s ---"),
425 // values for the entry being parsed
426 wxString curMimeType
, curExtList
;
429 size_t nLineCount
= textfile
.GetLineCount();
430 for ( size_t nLine
= 0; /* nothing */; nLine
++ )
432 if ( nLine
< nLineCount
)
434 pc
= textfile
[nLine
].c_str();
435 if ( *pc
== wxT('#') )
443 // so that we will fall into the "if" below
450 if ( !curMimeType
.empty() && !curExtList
.empty() )
452 wxLogTrace(TRACE_MIME
,
453 wxT("--- At end of Gnome file finding mimetype %s ---"),
454 curMimeType
.c_str());
456 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
461 // the end: this can only happen if nLine == nLineCount
470 // what do we have here?
471 if ( *pc
== wxT('\t') )
473 // this is a field=value ling
474 pc
++; // skip leading TAB
476 static const int lenField
= 5; // strlen("ext: ")
477 if ( wxStrncmp(pc
, wxT("ext: "), lenField
) == 0 )
479 // skip it and take everything left until the end of line
480 curExtList
= pc
+ lenField
;
482 //else: some other field, we don't care
486 // this is the start of the new section
487 wxLogTrace(TRACE_MIME
,
488 wxT("--- In Gnome file finding mimetype %s ---"),
489 curMimeType
.c_str());
491 if (! curMimeType
.empty())
492 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
496 while ( *pc
!= wxT(':') && *pc
!= wxT('\0') )
498 curMimeType
+= *pc
++;
505 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
506 const wxString
& dirbase
, const wxArrayString
& dirs
)
508 wxASSERT_MSG( !dirbase
.empty() && !wxEndsWithPathSeparator(dirbase
),
509 wxT("base directory shouldn't end with a slash") );
511 wxString dirname
= dirbase
;
512 dirname
<< wxT("/mime-info");
514 if ( !wxDir::Exists(dirname
) )
518 if ( !dir
.IsOpened() )
521 // we will concatenate it with filename to get the full path below
527 cont
= dir
.GetFirst(&filename
, wxT("*.mime"), wxDIR_FILES
);
530 LoadGnomeMimeTypesFromMimeFile(dirname
+ filename
);
532 cont
= dir
.GetNext(&filename
);
535 cont
= dir
.GetFirst(&filename
, wxT("*.keys"), wxDIR_FILES
);
538 LoadGnomeDataFromKeyFile(dirname
+ filename
, dirs
);
540 cont
= dir
.GetNext(&filename
);
543 // FIXME: Hack alert: We scan all icons and deduce the
544 // mime-type from the file name.
546 dirname
<< wxT("/pixmaps/document-icons");
548 // these are always empty in this file
549 wxArrayString strExtensions
;
552 if ( !wxDir::Exists(dirname
) )
554 // Just test for default GPE dir also
555 dirname
= wxT("/usr/share/gpe/pixmaps/default/filemanager/document-icons");
557 if ( !wxDir::Exists(dirname
) )
561 wxDir
dir2( dirname
);
563 cont
= dir2
.GetFirst(&filename
, wxT("gnome-*.png"), wxDIR_FILES
);
566 wxString mimeType
= filename
;
567 mimeType
.Remove( 0, 6 ); // remove "gnome-"
568 mimeType
.Remove( mimeType
.Len() - 4, 4 ); // remove ".png"
569 int pos
= mimeType
.Find( wxT("-") );
570 if (pos
!= wxNOT_FOUND
)
572 mimeType
.SetChar( pos
, wxT('/') );
573 wxString iconFile
= dirname
;
574 iconFile
<< wxT("/");
575 iconFile
<< filename
;
576 AddToMimeData( mimeType
, iconFile
, NULL
, strExtensions
, strDesc
, true );
579 cont
= dir2
.GetNext(&filename
);
583 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString
& sExtraDir
)
587 wxString gnomedir
= wxGetenv( wxT("GNOMEDIR") );
588 if (!gnomedir
.empty())
590 gnomedir
<< wxT("/share");
591 dirs
.Add( gnomedir
);
594 dirs
.Add(wxT("/usr/share"));
595 dirs
.Add(wxT("/usr/local/share"));
597 gnomedir
= wxGetHomeDir();
598 gnomedir
<< wxT("/.gnome");
599 dirs
.Add( gnomedir
);
601 if (!sExtraDir
.empty())
602 dirs
.Add( sExtraDir
);
604 size_t nDirs
= dirs
.GetCount();
605 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
607 LoadGnomeMimeFilesFromDir(dirs
[nDir
], dirs
);
611 // ----------------------------------------------------------------------------
613 // ----------------------------------------------------------------------------
616 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
617 // may be found in either of the following locations
619 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
620 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
622 // The format of a .kdelnk file is almost the same as the one used by
623 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
624 // value for the entry "Type"
626 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
627 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
629 bool wxMimeTypesManagerImpl::CheckKDEDirsExist( const wxString
&sOK
, const wxString
&sTest
)
633 return wxDir::Exists(sOK
);
637 wxString sStart
= sOK
+ wxT("/") + sTest
.BeforeFirst(wxT('/'));
638 if (!wxDir::Exists(sStart
))
640 wxString sEnd
= sTest
.AfterFirst(wxT('/'));
641 return CheckKDEDirsExist(sStart
, sEnd
);
645 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index
, bool delete_index
)
647 wxMimeTextFile appoutfile
, mimeoutfile
;
648 wxString sHome
= wxGetHomeDir();
649 wxString sTmp
= wxT(".kde/share/mimelnk/");
650 wxString sMime
= m_aTypes
[index
];
651 CheckKDEDirsExist(sHome
, sTmp
+ sMime
.BeforeFirst(wxT('/')) );
652 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
+ wxT(".kdelnk");
655 bool bMimeExists
= mimeoutfile
.Open(sTmp
);
658 bTemp
= mimeoutfile
.Create(sTmp
);
659 // some unknown error eg out of disk space
664 sTmp
= wxT(".kde/share/applnk/");
665 CheckKDEDirsExist(sHome
, sTmp
+ sMime
.AfterFirst(wxT('/')) );
666 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
.AfterFirst(wxT('/')) + wxT(".kdelnk");
669 bAppExists
= appoutfile
.Open(sTmp
);
672 bTemp
= appoutfile
.Create(sTmp
);
673 // some unknown error eg out of disk space
678 // fixed data; write if new file
681 mimeoutfile
.AddLine(wxT("#KDE Config File"));
682 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
683 mimeoutfile
.AddLine(wxT("Version=1.0"));
684 mimeoutfile
.AddLine(wxT("Type=MimeType"));
685 mimeoutfile
.AddLine(wxT("MimeType=") + sMime
);
690 mimeoutfile
.AddLine(wxT("#KDE Config File"));
691 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
692 appoutfile
.AddLine(wxT("Version=1.0"));
693 appoutfile
.AddLine(wxT("Type=Application"));
694 appoutfile
.AddLine(wxT("MimeType=") + sMime
+ wxT(';'));
699 mimeoutfile
.CommentLine(wxT("Comment="));
701 mimeoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
702 appoutfile
.CommentLine(wxT("Name="));
704 appoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
706 sTmp
= m_aIcons
[index
];
707 // we can either give the full path, or the shortfilename if its in
708 // one of the directories we search
709 mimeoutfile
.CommentLine(wxT("Icon=") );
711 mimeoutfile
.AddLine(wxT("Icon=") + sTmp
);
712 appoutfile
.CommentLine(wxT("Icon=") );
714 appoutfile
.AddLine(wxT("Icon=") + sTmp
);
716 sTmp
= wxT(" ") + m_aExtensions
[index
];
718 wxStringTokenizer
tokenizer(sTmp
, wxT(" "));
719 sTmp
= wxT("Patterns=");
720 mimeoutfile
.CommentLine(sTmp
);
721 while ( tokenizer
.HasMoreTokens() )
723 // holds an extension; need to change it to *.ext;
724 wxString e
= wxT("*.") + tokenizer
.GetNextToken() + wxT(";");
729 mimeoutfile
.AddLine(sTmp
);
731 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
732 // if we don't find open just have an empty string ... FIX this
733 sTmp
= entries
->GetCommandForVerb(wxT("open"));
734 sTmp
.Replace( wxT("%s"), wxT("%f") );
736 mimeoutfile
.CommentLine(wxT("DefaultApp=") );
738 mimeoutfile
.AddLine(wxT("DefaultApp=") + sTmp
);
740 sTmp
.Replace( wxT("%f"), wxT("") );
741 appoutfile
.CommentLine(wxT("Exec="));
743 appoutfile
.AddLine(wxT("Exec=") + sTmp
);
745 if (entries
->GetCount() > 1)
747 //other actions as well as open
751 if (mimeoutfile
.Write())
754 if (appoutfile
.Write())
761 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString
& dirbase
,
762 const wxString
& subdir
,
763 const wxString
& filename
,
764 const wxArrayString
& icondirs
)
766 wxFileName
fullname(dirbase
, filename
);
767 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
768 fullname
.GetFullPath().c_str());
771 if ( !file
.Open(fullname
.GetFullPath()) )
774 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
776 wxString mimetype
, mime_desc
, strIcon
;
778 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
779 if (nIndex
== wxNOT_FOUND
)
781 // construct mimetype from the directory name and the basename of the
782 // file (it always has .kdelnk extension)
783 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
786 mimetype
= file
.GetCmd(nIndex
);
788 // first find the description string: it is the value in either "Comment="
789 // line or "Comment[<locale_name>]=" one
790 nIndex
= wxNOT_FOUND
;
795 wxLocale
*locale
= wxGetLocale();
798 // try "Comment[locale name]" first
799 comment
<< wxT("Comment[") + locale
->GetName() + wxT("]=");
800 nIndex
= file
.pIndexOf(comment
);
804 if ( nIndex
== wxNOT_FOUND
)
806 comment
= wxT("Comment=");
807 nIndex
= file
.pIndexOf(comment
);
810 if ( nIndex
!= wxNOT_FOUND
)
811 mime_desc
= file
.GetCmd(nIndex
);
812 //else: no description
814 // next find the extensions
815 wxString mime_extension
;
817 nIndex
= file
.pIndexOf(wxT("Patterns="));
818 if ( nIndex
!= wxNOT_FOUND
)
820 wxString exts
= file
.GetCmd(nIndex
);
822 wxStringTokenizer
tokenizer(exts
, wxT(";"));
823 while ( tokenizer
.HasMoreTokens() )
825 wxString e
= tokenizer
.GetNextToken();
827 // don't support too difficult patterns
828 if ( e
.Left(2) != wxT("*.") )
831 if ( !mime_extension
.empty() )
833 // separate from the previous ext
834 mime_extension
<< wxT(' ');
837 mime_extension
<< e
.Mid(2);
841 sExts
.Add(mime_extension
);
843 // ok, now we can take care of icon:
845 nIndex
= file
.pIndexOf(wxT("Icon="));
846 if ( nIndex
!= wxNOT_FOUND
)
848 strIcon
= file
.GetCmd(nIndex
);
850 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
852 // it could be the real path, but more often a short name
853 if (!wxFileExists(strIcon
))
855 // icon is just the short name
856 if ( !strIcon
.empty() )
858 // we must check if the file exists because it may be stored
859 // in many locations, at least ~/.kde and $KDEDIR
860 size_t nDir
, nDirs
= icondirs
.GetCount();
861 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
863 wxFileName
fnameIcon( strIcon
);
864 wxFileName
fname( icondirs
[nDir
], fnameIcon
.GetName() );
865 fname
.SetExt( wxT("png") );
866 if (fname
.FileExists())
868 strIcon
= fname
.GetFullPath();
869 wxLogTrace(TRACE_MIME
, wxT(" iconfile %s"), strIcon
.c_str());
877 // now look for lines which know about the application
878 // exec= or DefaultApp=
880 nIndex
= file
.pIndexOf(wxT("DefaultApp"));
882 if ( nIndex
== wxNOT_FOUND
)
885 nIndex
= file
.pIndexOf(wxT("Exec"));
888 if ( nIndex
!= wxNOT_FOUND
)
890 // we expect %f; others including %F and %U and %u are possible
891 wxString sTmp
= file
.GetCmd(nIndex
);
892 if (0 == sTmp
.Replace( wxT("%f"), wxT("%s") ))
894 entry
->AddOrReplaceVerb(wxString(wxT("open")), sTmp
);
897 AddToMimeData(mimetype
, strIcon
, entry
, sExts
, mime_desc
);
900 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString
& dirbase
,
901 const wxString
& subdir
,
902 const wxArrayString
& icondirs
)
904 wxFileName
dirname(dirbase
, wxEmptyString
);
905 dirname
.AppendDir(subdir
);
906 wxDir
dir(dirname
.GetPath());
910 wxLogTrace(TRACE_MIME
, wxT("--- Loading from KDE directory %s ---"),
911 dirname
.GetPath().c_str());
914 bool cont
= dir
.GetFirst(&filename
, wxT("*.kdelnk"), wxDIR_FILES
);
916 LoadKDELinksForMimeSubtype(dirname
.GetPath(), subdir
,
918 cont
= dir
.GetNext(&filename
);
921 // new standard for Gnome and KDE
922 cont
= dir
.GetFirst(&filename
, wxT("*.desktop"), wxDIR_FILES
);
924 LoadKDELinksForMimeSubtype(dirname
.GetPath(), subdir
,
926 cont
= dir
.GetNext(&filename
);
930 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString
& dirname
,
931 const wxArrayString
& icondirs
)
933 if(! wxDir::Exists(dirname
))
937 if ( !dir
.IsOpened() )
941 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
944 LoadKDELinksForMimeType(dirname
, subdir
, icondirs
);
946 cont
= dir
.GetNext(&subdir
);
950 // Read a KDE .desktop file of type 'Application'
951 void wxMimeTypesManagerImpl::LoadKDEApp(const wxString
& filename
)
953 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"), filename
.c_str());
956 if ( !file
.Open(filename
) )
959 // Here, only type 'Application' should be considered.
960 int nIndex
= file
.pIndexOf( wxT("Type=") );
961 if (nIndex
!= wxNOT_FOUND
&&
962 file
.GetCmd(nIndex
).Lower() != wxT("application"))
965 // The hidden entry specifies a file to be ignored.
966 nIndex
= file
.pIndexOf( wxT("Hidden=") );
967 if (nIndex
!= wxNOT_FOUND
&& file
.GetCmd(nIndex
).Lower() == wxT("true"))
970 // Semicolon separated list of mime types handled by the application.
971 nIndex
= file
.pIndexOf( wxT("MimeType=") );
972 if (nIndex
== wxNOT_FOUND
)
974 wxString mimetypes
= file
.GetCmd (nIndex
);
976 // Name of the application
978 nIndex
= wxNOT_FOUND
;
979 #if wxUSE_INTL // try "Name[locale name]" first
980 wxLocale
*locale
= wxGetLocale();
982 nIndex
= file
.pIndexOf(_T("Name[")+locale
->GetName()+_T("]="));
984 if(nIndex
== wxNOT_FOUND
)
985 nIndex
= file
.pIndexOf( wxT("Name=") );
986 if(nIndex
!= wxNOT_FOUND
)
987 nameapp
= file
.GetCmd(nIndex
);
989 // Icon of the application.
990 wxString nameicon
, namemini
;
991 nIndex
= wxNOT_FOUND
;
992 #if wxUSE_INTL // try "Icon[locale name]" first
994 nIndex
= file
.pIndexOf(_T("Icon[")+locale
->GetName()+_T("]="));
996 if(nIndex
== wxNOT_FOUND
)
997 nIndex
= file
.pIndexOf( wxT("Icon=") );
998 if(nIndex
!= wxNOT_FOUND
) {
999 nameicon
= wxString(wxT("--icon ")) + file
.GetCmd(nIndex
);
1000 namemini
= wxString(wxT("--miniicon ")) + file
.GetCmd(nIndex
);
1003 // Replace some of the field code in the 'Exec' entry.
1004 // TODO: deal with %d, %D, %n, %N, %k and %v (but last one is deprecated)
1005 nIndex
= file
.pIndexOf( wxT("Exec=") );
1006 if (nIndex
== wxNOT_FOUND
)
1008 wxString sCmd
= file
.GetCmd(nIndex
);
1009 // we expect %f; others including %F and %U and %u are possible
1010 sCmd
.Replace(wxT("%F"), wxT("%f"));
1011 sCmd
.Replace(wxT("%U"), wxT("%f"));
1012 sCmd
.Replace(wxT("%u"), wxT("%f"));
1013 if (0 == sCmd
.Replace ( wxT("%f"), wxT("%s") ))
1014 sCmd
= sCmd
+ wxT(" %s");
1015 sCmd
.Replace(wxT("%c"), nameapp
);
1016 sCmd
.Replace(wxT("%i"), nameicon
);
1017 sCmd
.Replace(wxT("%m"), namemini
);
1019 wxStringTokenizer
tokenizer(mimetypes
, _T(";"));
1020 while(tokenizer
.HasMoreTokens()) {
1021 wxString mimetype
= tokenizer
.GetNextToken().Lower();
1022 int nIndex
= m_aTypes
.Index(mimetype
);
1023 if(nIndex
!= wxNOT_FOUND
) { // is this a known MIME type?
1024 wxMimeTypeCommands
* entry
= m_aEntries
[nIndex
];
1025 entry
->AddOrReplaceVerb(wxT("open"), sCmd
);
1030 void wxMimeTypesManagerImpl::LoadKDEAppsFilesFromDir(const wxString
& dirname
)
1032 if(! wxDir::Exists(dirname
))
1035 if ( !dir
.IsOpened() )
1039 // Look into .desktop files
1040 bool cont
= dir
.GetFirst(&filename
, _T("*.desktop"), wxDIR_FILES
);
1042 wxFileName
p(dirname
, filename
);
1043 LoadKDEApp( p
.GetFullPath() );
1044 cont
= dir
.GetNext(&filename
);
1046 // Look recursively into subdirs
1047 cont
= dir
.GetFirst(&filename
, wxEmptyString
, wxDIR_DIRS
);
1049 wxFileName
p(dirname
, wxEmptyString
);
1050 p
.AppendDir(filename
);
1051 LoadKDEAppsFilesFromDir( p
.GetPath() );
1052 cont
= dir
.GetNext(&filename
);
1056 // Return base KDE directories.
1057 // 1) Environment variable $KDEHOME, or "~/.kde" if not set.
1058 // 2) List of directories in colon separated environment variable $KDEDIRS.
1059 // 3) Environment variable $KDEDIR in case $KDEDIRS is not set.
1060 // Notice at least the local kde directory is added to the list. If it is the
1061 // only one, use later the application 'kde-config' to get additional paths.
1062 static void GetKDEBaseDirs(wxArrayString
& basedirs
)
1064 wxString env
= wxGetenv( wxT("KDEHOME") );
1066 env
= wxGetHomeDir() + wxT("/.kde");
1069 env
= wxGetenv( wxT("KDEDIRS") );
1071 env
= wxGetenv( wxT("KDEDIR") );
1075 wxStringTokenizer
tokenizer(env
, wxT(":"));
1076 while(tokenizer
.HasMoreTokens())
1077 basedirs
.Add( tokenizer
.GetNextToken() );
1081 static wxString
ReadPathFromKDEConfig(const wxString
& request
)
1084 wxArrayString output
;
1085 if(wxExecute(wxT("kde-config --path ")+request
, output
) == 0 &&
1087 str
= output
.Item(0);
1091 // Try to find the "Theme" entry in the configuration file, provided it exists.
1092 static wxString
GetKDEThemeInFile(const wxFileName
& filename
)
1095 wxMimeTextFile config
;
1096 if ( filename
.FileExists() && config
.Open(filename
.GetFullPath()) )
1098 size_t cnt
= config
.GetLineCount();
1099 for ( size_t i
= 0; i
< cnt
; i
++ )
1101 if ( config
[i
].StartsWith(wxT("Theme="), &theme
) )
1109 // Try to find a file "kdeglobals" in one of the directories and read the
1110 // "Theme" entry there.
1111 static wxString
GetKDETheme(const wxArrayString
& basedirs
)
1114 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1115 wxFileName
filename(basedirs
.Item(i
), wxEmptyString
);
1116 filename
.AppendDir( wxT("share") );
1117 filename
.AppendDir( wxT("config") );
1118 filename
.SetName( wxT("kdeglobals") );
1119 theme
= GetKDEThemeInFile(filename
);
1120 if(! theme
.IsEmpty())
1123 // If $KDEDIRS and $KDEDIR were set, we try nothing more. Otherwise, we
1124 // try to get the configuration file with 'kde-config'.
1125 if(basedirs
.Count() > 1)
1127 wxString paths
= ReadPathFromKDEConfig(wxT("config"));
1128 if(! paths
.IsEmpty()) {
1129 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1130 while( tokenizer
.HasMoreTokens() ) {
1131 wxFileName
filename(tokenizer
.GetNextToken(), wxT("kdeglobals"));
1132 theme
= GetKDEThemeInFile(filename
);
1133 if(! theme
.IsEmpty())
1140 // Get list of directories of icons.
1141 static void GetKDEIconDirs(const wxArrayString
& basedirs
,
1142 wxArrayString
& icondirs
)
1144 wxString theme
= GetKDETheme(basedirs
);
1146 theme
= wxT("default.kde");
1148 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1149 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1150 dirname
.AppendDir( wxT("share") );
1151 dirname
.AppendDir( wxT("icons") );
1152 dirname
.AppendDir(theme
);
1153 dirname
.AppendDir( wxT("32x32") );
1154 dirname
.AppendDir( wxT("mimetypes") );
1155 if( wxDir::Exists( dirname
.GetPath() ) )
1156 icondirs
.Add( dirname
.GetPath() );
1159 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1160 if(basedirs
.Count() > 1)
1162 wxString paths
= ReadPathFromKDEConfig(wxT("icon"));
1163 if(! paths
.IsEmpty()) {
1164 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1165 while( tokenizer
.HasMoreTokens() ) {
1166 wxFileName
dirname(tokenizer
.GetNextToken(), wxEmptyString
);
1167 dirname
.AppendDir(theme
);
1168 dirname
.AppendDir( wxT("32x32") );
1169 dirname
.AppendDir( wxT("mimetypes") );
1170 if(icondirs
.Index(dirname
.GetPath()) == wxNOT_FOUND
&&
1171 wxDir::Exists( dirname
.GetPath() ) )
1172 icondirs
.Add( dirname
.GetPath() );
1177 // Get list of directories of mime types.
1178 static void GetKDEMimeDirs(const wxArrayString
& basedirs
,
1179 wxArrayString
& mimedirs
)
1181 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1182 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1183 dirname
.AppendDir( wxT("share") );
1184 dirname
.AppendDir( wxT("mimelnk") );
1185 if( wxDir::Exists( dirname
.GetPath() ) )
1186 mimedirs
.Add( dirname
.GetPath() );
1189 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1190 if(basedirs
.Count() > 1)
1192 wxString paths
= ReadPathFromKDEConfig(wxT("mime"));
1193 if(! paths
.IsEmpty()) {
1194 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1195 while( tokenizer
.HasMoreTokens() ) {
1196 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1197 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1198 if(mimedirs
.Index(dirname
) == wxNOT_FOUND
&&
1199 wxDir::Exists(dirname
) )
1200 mimedirs
.Add(dirname
);
1205 // Get list of directories of application desktop files.
1206 static void GetKDEAppsDirs(const wxArrayString
& basedirs
,
1207 wxArrayString
& appsdirs
)
1209 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1210 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1211 dirname
.AppendDir( wxT("share") );
1212 dirname
.AppendDir( wxT("applnk") );
1213 if( wxDir::Exists( dirname
.GetPath() ) )
1214 appsdirs
.Add( dirname
.GetPath() );
1217 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1218 if(basedirs
.Count() > 1)
1220 wxString paths
= ReadPathFromKDEConfig(wxT("apps"));
1221 if(! paths
.IsEmpty()) {
1222 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1223 while( tokenizer
.HasMoreTokens() ) {
1224 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1225 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1226 if(appsdirs
.Index(dirname
) == wxNOT_FOUND
&&
1227 wxDir::Exists(dirname
) )
1228 appsdirs
.Add(dirname
);
1231 paths
= ReadPathFromKDEConfig(wxT("xdgdata-apps"));
1232 if(! paths
.IsEmpty()) {
1233 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1234 while( tokenizer
.HasMoreTokens() ) {
1235 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1236 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1237 if(appsdirs
.Index(dirname
) == wxNOT_FOUND
&&
1238 wxDir::Exists(dirname
) )
1239 appsdirs
.Add(dirname
);
1244 // Fill database with all mime types.
1245 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString
& sExtraDir
)
1247 wxArrayString basedirs
;
1248 GetKDEBaseDirs(basedirs
);
1250 wxArrayString icondirs
;
1251 GetKDEIconDirs(basedirs
, icondirs
);
1252 wxArrayString mimedirs
;
1253 GetKDEMimeDirs(basedirs
, mimedirs
);
1254 wxArrayString appsdirs
;
1255 GetKDEAppsDirs(basedirs
, appsdirs
);
1257 if(! sExtraDir
.IsEmpty()) {
1258 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1259 mimedirs
.Add(sExtraDir
+ wxT("/mimelnk"));
1260 appsdirs
.Add(sExtraDir
+ wxT("/applnk"));
1264 size_t nDirs
= mimedirs
.GetCount(), nDir
;
1265 for(nDir
= 0; nDir
< nDirs
; nDir
++)
1266 LoadKDELinkFilesFromDir(mimedirs
[nDir
], icondirs
);
1268 // Load application files and associate them to corresponding mime types.
1269 nDirs
= appsdirs
.GetCount();
1270 for(nDir
= 0; nDir
< nDirs
; nDir
++)
1271 LoadKDEAppsFilesFromDir(appsdirs
[nDir
]);
1274 // ----------------------------------------------------------------------------
1275 // wxFileTypeImpl (Unix)
1276 // ----------------------------------------------------------------------------
1278 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1282 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1284 sTmp
= m_manager
->GetCommand( verb
, m_index
[i
] );
1288 return wxFileType::ExpandCommand(sTmp
, params
);
1291 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
1295 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1297 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1306 iconLoc
->SetFileName(sTmp
);
1312 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1315 size_t nCount
= m_index
.GetCount();
1316 for (size_t i
= 0; i
< nCount
; i
++)
1317 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1322 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1323 wxArrayString
*commands
,
1324 const wxFileType::MessageParameters
& params
) const
1326 wxString vrb
, cmd
, sTmp
;
1328 wxMimeTypeCommands
* sPairs
;
1330 // verbs and commands have been cleared already in mimecmn.cpp...
1331 // if we find no entries in the exact match, try the inexact match
1332 for (size_t n
= 0; ((count
== 0) && (n
< m_index
.GetCount())); n
++)
1334 // list of verb = command pairs for this mimetype
1335 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1337 for ( i
= 0; i
< sPairs
->GetCount(); i
++ )
1339 vrb
= sPairs
->GetVerb(i
);
1340 // some gnome entries have "." inside
1341 vrb
= vrb
.AfterLast(wxT('.'));
1342 cmd
= sPairs
->GetCmd(i
);
1345 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1347 if ( vrb
.IsSameAs(wxT("open")))
1350 verbs
->Insert(vrb
, 0u);
1352 commands
->Insert(cmd
, 0u);
1368 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1370 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1373 // one extension in the space or comma-delimited list
1375 for ( const wxChar
*p
= strExtensions
; /* nothing */; p
++ )
1377 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') )
1379 if ( !strExt
.empty() )
1381 extensions
.Add(strExt
);
1384 //else: repeated spaces
1385 // (shouldn't happen, but it's not that important if it does happen)
1387 if ( *p
== wxT('\0') )
1390 else if ( *p
== wxT('.') )
1392 // remove the dot from extension (but only if it's the first char)
1393 if ( !strExt
.empty() )
1397 //else: no, don't append it
1408 // set an arbitrary command:
1409 // could adjust the code to ask confirmation if it already exists and
1410 // overwriteprompt is true, but this is currently ignored as *Associate* has
1411 // no overwrite prompt
1413 wxFileTypeImpl::SetCommand(const wxString
& cmd
,
1414 const wxString
& verb
,
1415 bool WXUNUSED(overwriteprompt
))
1417 wxArrayString strExtensions
;
1418 wxString strDesc
, strIcon
;
1420 wxArrayString strTypes
;
1421 GetMimeTypes(strTypes
);
1422 if ( strTypes
.IsEmpty() )
1425 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1426 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1429 size_t nCount
= strTypes
.GetCount();
1430 for ( size_t i
= 0; i
< nCount
; i
++ )
1432 if (!m_manager
->DoAssociation(strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1439 // ignore index on the grounds that we only have one icon in a Unix file
1440 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
, int WXUNUSED(index
))
1442 if (strIcon
.empty())
1445 wxArrayString strExtensions
;
1448 wxArrayString strTypes
;
1449 GetMimeTypes(strTypes
);
1450 if ( strTypes
.IsEmpty() )
1453 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1455 size_t nCount
= strTypes
.GetCount();
1456 for ( size_t i
= 0; i
< nCount
; i
++ )
1458 if ( !m_manager
->DoAssociation
1474 // ----------------------------------------------------------------------------
1475 // wxMimeTypesManagerImpl (Unix)
1476 // ----------------------------------------------------------------------------
1478 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1480 m_initialized
= false;
1481 m_mailcapStylesInited
= 0;
1484 void wxMimeTypesManagerImpl::InitIfNeeded()
1486 if ( !m_initialized
)
1488 // set the flag first to prevent recursion
1489 m_initialized
= true;
1491 wxString wm
= wxTheApp
->GetTraits()->GetDesktopEnvironment();
1493 if (wm
== wxT("KDE"))
1494 Initialize( wxMAILCAP_KDE
);
1495 else if (wm
== wxT("GNOME"))
1496 Initialize( wxMAILCAP_GNOME
);
1502 // read system and user mailcaps and other files
1503 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1504 const wxString
& sExtraDir
)
1506 // read mimecap amd mime.types
1507 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1508 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1509 GetMimeInfo(sExtraDir
);
1511 // read GNOME tables
1512 if (mailcapStyles
& wxMAILCAP_GNOME
)
1513 GetGnomeMimeInfo(sExtraDir
);
1516 if (mailcapStyles
& wxMAILCAP_KDE
)
1517 GetKDEMimeInfo(sExtraDir
);
1519 m_mailcapStylesInited
|= mailcapStyles
;
1522 // clear data so you can read another group of WM files
1523 void wxMimeTypesManagerImpl::ClearData()
1527 m_aExtensions
.Clear();
1528 m_aDescriptions
.Clear();
1530 WX_CLEAR_ARRAY(m_aEntries
);
1533 m_mailcapStylesInited
= 0;
1536 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1541 void wxMimeTypesManagerImpl::GetMimeInfo(const wxString
& sExtraDir
)
1543 // read this for netscape or Metamail formats
1545 // directories where we look for mailcap and mime.types by default
1546 // used by netscape and pine and other mailers, using 2 different formats!
1548 // (taken from metamail(1) sources)
1550 // although RFC 1524 specifies the search path of
1551 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1552 // places - OTOH, the RFC also says that this path can be changed with
1553 // MAILCAPS environment variable (containing the colon separated full
1554 // filenames to try) which is not done yet (TODO?)
1556 wxString strHome
= wxGetenv(wxT("HOME"));
1559 dirs
.Add( strHome
+ wxT("/.") );
1560 dirs
.Add( wxT("/etc/") );
1561 dirs
.Add( wxT("/usr/etc/") );
1562 dirs
.Add( wxT("/usr/local/etc/") );
1563 dirs
.Add( wxT("/etc/mail/") );
1564 dirs
.Add( wxT("/usr/public/lib/") );
1565 if (!sExtraDir
.empty())
1566 dirs
.Add( sExtraDir
+ wxT("/") );
1569 size_t nDirs
= dirs
.GetCount();
1570 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1573 file
+= wxT("mailcap");
1574 if ( wxFile::Exists(file
) )
1580 file
+= wxT("mime.types");
1581 if ( wxFile::Exists(file
) )
1582 ReadMimeTypes(file
);
1586 bool wxMimeTypesManagerImpl::WriteToMimeTypes(int index
, bool delete_index
)
1588 // check we have the right manager
1589 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1593 wxString strHome
= wxGetenv(wxT("HOME"));
1595 // and now the users mailcap
1596 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1598 wxMimeTextFile file
;
1599 if ( wxFile::Exists(strUserMailcap
) )
1601 bTemp
= file
.Open(strUserMailcap
);
1608 bTemp
= file
.Create(strUserMailcap
);
1614 // test for netscape's header and return false if its found
1615 nIndex
= file
.pIndexOf(wxT("#--Netscape"));
1616 if (nIndex
!= wxNOT_FOUND
)
1618 wxFAIL_MSG(wxT("Error in .mime.types\nTrying to mix Netscape and Metamail formats\nFile not modified"));
1622 // write it in alternative format
1623 // get rid of unwanted entries
1624 wxString strType
= m_aTypes
[index
];
1625 nIndex
= file
.pIndexOf(strType
);
1627 // get rid of all the unwanted entries...
1628 if (nIndex
!= wxNOT_FOUND
)
1629 file
.CommentLine(nIndex
);
1633 // add the new entries in
1634 wxString sTmp
= strType
.Append( wxT(' '), 40 - strType
.Len() );
1635 sTmp
+= m_aExtensions
[index
];
1639 bTemp
= file
.Write();
1646 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes(int index
, bool delete_index
)
1648 //check we have the right managers
1649 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1653 wxString strHome
= wxGetenv(wxT("HOME"));
1655 // and now the users mailcap
1656 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1658 wxMimeTextFile file
;
1659 if ( wxFile::Exists(strUserMailcap
) )
1661 bTemp
= file
.Open(strUserMailcap
);
1668 bTemp
= file
.Create(strUserMailcap
);
1673 // write it in the format that Netscape uses
1675 // test for netscape's header and insert if required...
1676 // this is a comment so use true
1677 nIndex
= file
.pIndexOf(wxT("#--Netscape"), true);
1678 if (nIndex
== wxNOT_FOUND
)
1680 // either empty file or metamail format
1681 // at present we can't cope with mixed formats, so exit to preseve
1682 // metamail entreies
1683 if (file
.GetLineCount() > 0)
1685 wxFAIL_MSG(wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1689 file
.InsertLine(wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1693 wxString strType
= wxT("type=") + m_aTypes
[index
];
1694 nIndex
= file
.pIndexOf(strType
);
1696 // get rid of all the unwanted entries...
1697 if (nIndex
!= wxNOT_FOUND
)
1699 wxString sOld
= file
[nIndex
];
1700 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1702 file
.CommentLine(nIndex
);
1703 sOld
= file
[nIndex
];
1705 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1710 if (nIndex
< (int) file
.GetLineCount())
1711 file
.CommentLine(nIndex
);
1714 nIndex
= (int) file
.GetLineCount();
1716 wxString sTmp
= strType
+ wxT(" \\");
1718 file
.InsertLine(sTmp
, nIndex
);
1720 if ( ! m_aDescriptions
.Item(index
).empty() )
1722 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1726 file
.InsertLine(sTmp
, nIndex
);
1730 wxString sExts
= m_aExtensions
.Item(index
);
1731 sTmp
= wxT("exts=\"") + sExts
.Trim(false).Trim() + wxT("\"");
1735 file
.InsertLine(sTmp
, nIndex
);
1738 bTemp
= file
.Write();
1745 bool wxMimeTypesManagerImpl::WriteToMailCap(int index
, bool delete_index
)
1747 //check we have the right managers
1748 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1749 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1753 wxString strHome
= wxGetenv(wxT("HOME"));
1755 // and now the users mailcap
1756 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1758 wxMimeTextFile file
;
1759 if ( wxFile::Exists(strUserMailcap
) )
1761 bTemp
= file
.Open(strUserMailcap
);
1768 bTemp
= file
.Create(strUserMailcap
);
1773 // now got a file we can write to ....
1774 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1776 wxString sCmd
= entries
->GetCommandForVerb(wxT("open"), &iOpen
);
1779 sTmp
= m_aTypes
[index
];
1781 int nIndex
= file
.pIndexOf(sTmp
);
1783 // get rid of all the unwanted entries...
1784 if (nIndex
== wxNOT_FOUND
)
1786 nIndex
= (int) file
.GetLineCount();
1790 sOld
= file
[nIndex
];
1791 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1793 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1795 file
.CommentLine(nIndex
);
1796 if (nIndex
< (int) file
.GetLineCount())
1797 sOld
= sOld
+ file
[nIndex
];
1801 file
.GetLineCount()) file
.CommentLine(nIndex
);
1804 sTmp
+= wxT(";") + sCmd
; //includes wxT(" %s ");
1806 // write it in the format that Netscape uses (default)
1807 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1810 file
.InsertLine(sTmp
, nIndex
);
1815 // write extended format
1817 // TODO - FIX this code:
1819 // sOld holds all the entries, but our data store only has some
1820 // eg test= is not stored
1822 // so far we have written the mimetype and command out
1823 wxStringTokenizer
sT(sOld
, wxT(";\\"));
1824 if (sT
.CountTokens() > 2)
1826 // first one mimetype; second one command, rest unknown...
1828 s
= sT
.GetNextToken();
1829 s
= sT
.GetNextToken();
1832 s
= sT
.GetNextToken();
1833 while ( ! s
.empty() )
1835 bool bKnownToken
= false;
1836 if (s
.Contains(wxT("description=")))
1838 if (s
.Contains(wxT("x11-bitmap=")))
1842 size_t nCount
= entries
->GetCount();
1843 for (i
=0; i
< nCount
; i
++)
1845 if (s
.Contains(entries
->GetVerb(i
)))
1851 sTmp
+= wxT("; \\");
1852 file
.InsertLine(sTmp
, nIndex
);
1856 s
= sT
.GetNextToken();
1860 if (! m_aDescriptions
[index
].empty() )
1862 sTmp
+= wxT("; \\");
1863 file
.InsertLine(sTmp
, nIndex
);
1865 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1868 if (! m_aIcons
[index
].empty() )
1870 sTmp
+= wxT("; \\");
1871 file
.InsertLine(sTmp
, nIndex
);
1873 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1876 if ( entries
->GetCount() > 1 )
1879 for (i
=0; i
< entries
->GetCount(); i
++)
1882 sTmp
+= wxT("; \\");
1883 file
.InsertLine(sTmp
, nIndex
);
1885 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1889 file
.InsertLine(sTmp
, nIndex
);
1893 bTemp
= file
.Write();
1900 wxFileType
* wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1904 wxString strType
= ftInfo
.GetMimeType();
1905 wxString strDesc
= ftInfo
.GetDescription();
1906 wxString strIcon
= ftInfo
.GetIconFile();
1908 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1910 if ( ! ftInfo
.GetOpenCommand().empty())
1911 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand() + wxT(" %s "));
1912 if ( ! ftInfo
.GetPrintCommand().empty())
1913 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand() + wxT(" %s "));
1915 // now find where these extensions are in the data store and remove them
1916 wxArrayString sA_Exts
= ftInfo
.GetExtensions();
1917 wxString sExt
, sExtStore
;
1919 size_t nExtCount
= sA_Exts
.GetCount();
1920 for (i
=0; i
< nExtCount
; i
++)
1922 sExt
= sA_Exts
.Item(i
);
1924 // clean up to just a space before and after
1925 sExt
.Trim().Trim(false);
1926 sExt
= wxT(' ') + sExt
+ wxT(' ');
1927 size_t nCount
= m_aExtensions
.GetCount();
1928 for (nIndex
= 0; nIndex
< nCount
; nIndex
++)
1930 sExtStore
= m_aExtensions
.Item(nIndex
);
1931 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0)
1932 m_aExtensions
.Item(nIndex
) = sExtStore
;
1936 if ( !DoAssociation(strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1939 return GetFileTypeFromMimeType(strType
);
1942 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1943 const wxString
& strIcon
,
1944 wxMimeTypeCommands
*entry
,
1945 const wxArrayString
& strExtensions
,
1946 const wxString
& strDesc
)
1948 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
1950 if ( nIndex
== wxNOT_FOUND
)
1953 return WriteMimeInfo(nIndex
, false);
1956 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
1960 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
1962 // write in metamail format;
1963 if (WriteToMimeTypes(nIndex
, delete_mime
) )
1964 if ( WriteToMailCap(nIndex
, delete_mime
) )
1968 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
1970 // write in netsacpe format;
1971 if (WriteToNSMimeTypes(nIndex
, delete_mime
) )
1972 if ( WriteToMailCap(nIndex
, delete_mime
) )
1976 // Don't write GNOME files here as this is not
1977 // allowed and simply doesn't work
1979 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
1981 // write in KDE format;
1982 if (WriteKDEMimeFile(nIndex
, delete_mime
) )
1989 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
1990 const wxString
& strIcon
,
1991 wxMimeTypeCommands
*entry
,
1992 const wxArrayString
& strExtensions
,
1993 const wxString
& strDesc
,
1994 bool replaceExisting
)
1998 // ensure mimetype is always lower case
1999 wxString mimeType
= strType
.Lower();
2001 // is this a known MIME type?
2002 int nIndex
= m_aTypes
.Index(mimeType
);
2003 if ( nIndex
== wxNOT_FOUND
)
2006 m_aTypes
.Add(mimeType
);
2007 m_aIcons
.Add(strIcon
);
2008 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
2010 // change nIndex so we can use it below to add the extensions
2011 m_aExtensions
.Add(wxEmptyString
);
2012 nIndex
= m_aExtensions
.size() - 1;
2014 m_aDescriptions
.Add(strDesc
);
2016 else // yes, we already have it
2018 if ( replaceExisting
)
2020 // if new description change it
2021 if ( !strDesc
.empty())
2022 m_aDescriptions
[nIndex
] = strDesc
;
2024 // if new icon change it
2025 if ( !strIcon
.empty())
2026 m_aIcons
[nIndex
] = strIcon
;
2030 delete m_aEntries
[nIndex
];
2031 m_aEntries
[nIndex
] = entry
;
2034 else // add data we don't already have ...
2036 // if new description add only if none
2037 if ( m_aDescriptions
[nIndex
].empty() )
2038 m_aDescriptions
[nIndex
] = strDesc
;
2040 // if new icon and no existing icon
2041 if ( m_aIcons
[nIndex
].empty() )
2042 m_aIcons
[nIndex
] = strIcon
;
2044 // add any new entries...
2047 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
2049 size_t count
= entry
->GetCount();
2050 for ( size_t i
= 0; i
< count
; i
++ )
2052 const wxString
& verb
= entry
->GetVerb(i
);
2053 if ( !entryOld
->HasVerb(verb
) )
2055 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
2059 // as we don't store it anywhere, it won't be deleted later as
2060 // usual -- do it immediately instead
2066 // always add the extensions to this mimetype
2067 wxString
& exts
= m_aExtensions
[nIndex
];
2069 // add all extensions we don't have yet
2071 size_t count
= strExtensions
.GetCount();
2072 for ( size_t i
= 0; i
< count
; i
++ )
2074 ext
= strExtensions
[i
];
2077 if ( exts
.Find(ext
) == wxNOT_FOUND
)
2083 // check data integrity
2084 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2085 m_aTypes
.Count() == m_aExtensions
.Count() &&
2086 m_aTypes
.Count() == m_aIcons
.Count() &&
2087 m_aTypes
.Count() == m_aDescriptions
.Count() );
2092 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
2099 size_t count
= m_aExtensions
.GetCount();
2100 for ( size_t n
= 0; n
< count
; n
++ )
2102 wxStringTokenizer
tk(m_aExtensions
[n
], wxT(' '));
2104 while ( tk
.HasMoreTokens() )
2106 // consider extensions as not being case-sensitive
2107 if ( tk
.GetNextToken().IsSameAs(ext
, false /* no case */) )
2110 wxFileType
*fileType
= new wxFileType
;
2111 fileType
->m_impl
->Init(this, n
);
2121 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
2125 wxFileType
* fileType
= NULL
;
2126 // mime types are not case-sensitive
2127 wxString
mimetype(mimeType
);
2128 mimetype
.MakeLower();
2130 // first look for an exact match
2131 int index
= m_aTypes
.Index(mimetype
);
2132 if ( index
!= wxNOT_FOUND
)
2134 fileType
= new wxFileType
;
2135 fileType
->m_impl
->Init(this, index
);
2138 // then try to find "text/*" as match for "text/plain" (for example)
2139 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
2140 // the whole string - ok.
2142 index
= wxNOT_FOUND
;
2143 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
2145 size_t nCount
= m_aTypes
.Count();
2146 for ( size_t n
= 0; n
< nCount
; n
++ )
2148 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
2149 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") )
2156 if ( index
!= wxNOT_FOUND
)
2158 // don't throw away fileType that was already found
2160 fileType
= new wxFileType
;
2161 fileType
->m_impl
->Init(this, index
);
2167 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
2169 wxString command
, testcmd
, sV
, sTmp
;
2170 sV
= verb
+ wxT("=");
2172 // list of verb = command pairs for this mimetype
2173 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
2176 size_t nCount
= sPairs
->GetCount();
2177 for ( i
= 0; i
< nCount
; i
++ )
2179 sTmp
= sPairs
->GetVerbCmd (i
);
2180 if ( sTmp
.Contains(sV
) )
2181 command
= sTmp
.AfterFirst(wxT('='));
2187 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
2191 wxString extensions
;
2192 const wxArrayString
& exts
= filetype
.GetExtensions();
2193 size_t nExts
= exts
.GetCount();
2194 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ )
2197 extensions
+= wxT(' ');
2199 extensions
+= exts
[nExt
];
2202 AddMimeTypeInfo(filetype
.GetMimeType(),
2204 filetype
.GetDescription());
2206 AddMailcapInfo(filetype
.GetMimeType(),
2207 filetype
.GetOpenCommand(),
2208 filetype
.GetPrintCommand(),
2210 filetype
.GetDescription());
2213 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2214 const wxString
& strExtensions
,
2215 const wxString
& strDesc
)
2217 // reading mailcap may find image/* , while
2218 // reading mime.types finds image/gif and no match is made
2219 // this means all the get functions don't work fix this
2221 wxString sTmp
= strExtensions
;
2223 wxArrayString sExts
;
2224 sTmp
.Trim().Trim(false);
2226 while (!sTmp
.empty())
2228 sExts
.Add(sTmp
.AfterLast(wxT(' ')));
2229 sTmp
= sTmp
.BeforeLast(wxT(' '));
2232 AddToMimeData(strMimeType
, strIcon
, NULL
, sExts
, strDesc
, true);
2235 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2236 const wxString
& strOpenCmd
,
2237 const wxString
& strPrintCmd
,
2238 const wxString
& strTest
,
2239 const wxString
& strDesc
)
2243 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2244 entry
->Add(wxT("open=") + strOpenCmd
);
2245 entry
->Add(wxT("print=") + strPrintCmd
);
2246 entry
->Add(wxT("test=") + strTest
);
2249 wxArrayString strExtensions
;
2251 AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
2254 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2256 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2257 strFileName
.c_str());
2259 wxMimeTextFile
file(strFileName
);
2263 // the information we extract
2264 wxString strMimeType
, strDesc
, strExtensions
;
2266 size_t nLineCount
= file
.GetLineCount();
2267 const wxChar
*pc
= NULL
;
2268 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2272 // now we're at the start of the line
2273 pc
= file
[nLine
].c_str();
2277 // we didn't finish with the previous line yet
2282 while ( wxIsspace(*pc
) )
2285 // comment or blank line?
2286 if ( *pc
== wxT('#') || !*pc
)
2288 // skip the whole line
2293 // detect file format
2294 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2295 if ( pEqualSign
== NULL
)
2300 // first field is mime type
2301 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ )
2307 while ( wxIsspace(*pc
) )
2310 // take all the rest of the string
2313 // no description...
2321 // the string on the left of '=' is the field name
2322 wxString
strLHS(pc
, pEqualSign
- pc
);
2325 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2329 if ( *pc
== wxT('"') )
2331 // the string is quoted and ends at the matching quote
2332 pEnd
= wxStrchr(++pc
, wxT('"'));
2335 wxLogWarning(wxT("Mime.types file %s, line %lu: unterminated quoted string."),
2336 strFileName
.c_str(), nLine
+ 1L);
2341 // unquoted string ends at the first space or at the end of
2343 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2347 // now we have the RHS (field value)
2348 wxString
strRHS(pc
, pEnd
- pc
);
2350 // check what follows this entry
2351 if ( *pEnd
== wxT('"') )
2357 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2360 // if there is something left, it may be either a '\\' to continue
2361 // the line or the next field of the same entry
2362 bool entryEnded
= *pc
== wxT('\0');
2363 bool nextFieldOnSameLine
= false;
2366 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2369 // now see what we got
2370 if ( strLHS
== wxT("type") )
2372 strMimeType
= strRHS
;
2374 else if ( strLHS
.StartsWith(wxT("desc")) )
2378 else if ( strLHS
== wxT("exts") )
2380 strExtensions
= strRHS
;
2382 else if ( strLHS
== wxT("icon") )
2384 // this one is simply ignored: it usually refers to Netscape
2385 // built in icons which are useless for us anyhow
2387 else if ( !strLHS
.StartsWith(wxT("x-")) )
2389 // we suppose that all fields starting with "X-" are
2390 // unregistered extensions according to the standard practice,
2391 // but it may be worth telling the user about other junk in
2392 // his mime.types file
2393 wxLogWarning(wxT("Unknown field in file %s, line %lu: '%s'."),
2394 strFileName
.c_str(), nLine
+ 1L, strLHS
.c_str());
2399 if ( !nextFieldOnSameLine
)
2401 //else: don't reset it
2403 // as we don't reset strMimeType, the next field in this entry
2404 // will be interpreted correctly.
2410 // depending on the format (Mosaic or Netscape) either space or comma
2411 // is used to separate the extensions
2412 strExtensions
.Replace(wxT(","), wxT(" "));
2414 // also deal with the leading dot
2415 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2417 strExtensions
.erase(0, 1);
2420 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2421 strExtensions
.c_str(),
2422 strMimeType
.c_str(),
2425 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2427 // finished with this line
2434 // ----------------------------------------------------------------------------
2435 // UNIX mailcap files parsing
2436 // ----------------------------------------------------------------------------
2438 // the data for a single MIME type
2439 struct MailcapLineData
2448 wxArrayString verbs
,
2456 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= false; }
2459 // process a non-standard (i.e. not the first or second one) mailcap field
2461 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2462 const wxString
& curField
)
2464 if ( curField
.empty() )
2470 // is this something of the form foo=bar?
2471 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2474 // split "LHS = RHS" in 2
2475 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2476 rhs
= curField
.AfterFirst(wxT('='));
2478 lhs
.Trim(true); // from right
2479 rhs
.Trim(false); // from left
2481 // it might be quoted
2482 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2484 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2487 // is it a command verb or something else?
2488 if ( lhs
== wxT("test") )
2490 if ( wxSystem(rhs
) == 0 )
2493 wxLogTrace(TRACE_MIME_TEST
,
2494 wxT("Test '%s' for mime type '%s' succeeded."),
2495 rhs
.c_str(), data
.type
.c_str());
2499 wxLogTrace(TRACE_MIME_TEST
,
2500 wxT("Test '%s' for mime type '%s' failed, skipping."),
2501 rhs
.c_str(), data
.type
.c_str());
2503 data
.testfailed
= true;
2506 else if ( lhs
== wxT("desc") )
2510 else if ( lhs
== wxT("x11-bitmap") )
2514 else if ( lhs
== wxT("notes") )
2518 else // not a (recognized) special case, must be a verb (e.g. "print")
2520 data
.verbs
.Add(lhs
);
2521 data
.commands
.Add(rhs
);
2524 else // '=' not found
2526 // so it must be a simple flag
2527 if ( curField
== wxT("needsterminal") )
2529 data
.needsterminal
= true;
2531 else if ( curField
== wxT("copiousoutput"))
2533 // copiousoutput impies that the viewer is a console program
2534 data
.needsterminal
=
2535 data
.copiousoutput
= true;
2537 else if ( !IsKnownUnimportantField(curField
) )
2546 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2549 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2550 strFileName
.c_str());
2552 wxMimeTextFile
file(strFileName
);
2556 // indices of MIME types (in m_aTypes) we already found in this file
2558 // (see the comments near the end of function for the reason we need this)
2559 wxArrayInt aIndicesSeenHere
;
2561 // accumulator for the current field
2563 curField
.reserve(1024);
2565 const wxChar
*pPagerEnv
= wxGetenv(wxT("PAGER"));
2567 const wxArrayString empty_extensions_list
;
2569 size_t nLineCount
= file
.GetLineCount();
2570 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2572 // now we're at the start of the line
2573 const wxChar
*pc
= file
[nLine
].c_str();
2576 while ( wxIsspace(*pc
) )
2579 // comment or empty string?
2580 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2586 // what field are we currently in? The first 2 are fixed and there may
2587 // be an arbitrary number of other fields parsed by
2588 // ProcessOtherMailcapField()
2590 // the first field is the MIME type
2597 currentToken
= Field_Type
;
2599 // the flags and field values on the current line
2600 MailcapLineData data
;
2608 // interpret the next character literally (notice that
2609 // backslash can be used for line continuation)
2610 if ( *++pc
== wxT('\0') )
2612 // fetch the next line if there is one
2613 if ( nLine
== nLineCount
- 1 )
2615 // something is wrong, bail out
2618 wxLogDebug(wxT("Mailcap file %s, line %lu: '\\' on the end of the last line ignored."),
2619 strFileName
.c_str(),
2624 // pass to the beginning of the next line
2625 pc
= file
[++nLine
].c_str();
2627 // skip pc++ at the end of the loop
2633 // just a normal character
2639 cont
= false; // end of line reached, exit the loop
2641 // fall through to still process this field
2644 // trim whitespaces from both sides
2645 curField
.Trim(true).Trim(false);
2647 switch ( currentToken
)
2650 data
.type
= curField
.Lower();
2651 if ( data
.type
.empty() )
2653 // I don't think that this is a valid mailcap
2654 // entry, but try to interpret it somehow
2655 data
.type
= wxT('*');
2658 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2660 // we interpret "type" as "type/*"
2661 data
.type
+= wxT("/*");
2664 currentToken
= Field_OpenCmd
;
2668 data
.cmdOpen
= curField
;
2670 currentToken
= Field_Other
;
2674 if ( !ProcessOtherMailcapField(data
, curField
) )
2676 // don't flood the user with error messages if
2677 // we don't understand something in his
2678 // mailcap, but give them in debug mode because
2679 // this might be useful for the programmer
2682 wxT("Mailcap file %s, line %lu: unknown field '%s' for the MIME type '%s' ignored."),
2683 strFileName
.c_str(),
2689 else if ( data
.testfailed
)
2691 // skip this entry entirely
2695 // it already has this value
2696 //currentToken = Field_Other;
2700 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2703 // next token starts immediately after ';'
2711 // continue in the same line
2715 // we read the entire entry, check what have we got
2716 // ------------------------------------------------
2718 // check that we really read something reasonable
2719 if ( currentToken
< Field_Other
)
2721 wxLogWarning(wxT("Mailcap file %s, line %lu: incomplete entry ignored."),
2722 strFileName
.c_str(), nLine
+ 1L);
2727 // if the test command failed, it's as if the entry were not there at all
2728 if ( data
.testfailed
)
2733 // support for flags:
2734 // 1. create an xterm for 'needsterminal'
2735 // 2. append "| $PAGER" for 'copiousoutput'
2737 // Note that the RFC says that having both needsterminal and
2738 // copiousoutput is probably a mistake, so it seems that running
2739 // programs with copiousoutput inside an xterm as it is done now
2740 // is a bad idea (FIXME)
2741 if ( data
.copiousoutput
)
2743 data
.cmdOpen
<< wxT(" | ") << (pPagerEnv
? pPagerEnv
: wxT("more"));
2746 if ( data
.needsterminal
)
2748 data
.cmdOpen
.Printf(wxT("xterm -e sh -c '%s'"),
2749 data
.cmdOpen
.c_str());
2752 if ( !data
.cmdOpen
.empty() )
2754 data
.verbs
.Insert(wxT("open"), 0);
2755 data
.commands
.Insert(data
.cmdOpen
, 0);
2758 // we have to decide whether the new entry should replace any entries
2759 // for the same MIME type we had previously found or not
2762 // the fall back entries have the lowest priority, by definition
2769 // have we seen this one before?
2770 int nIndex
= m_aTypes
.Index(data
.type
);
2772 // and if we have, was it in this file? if not, we should
2773 // overwrite the previously seen one
2774 overwrite
= nIndex
== wxNOT_FOUND
||
2775 aIndicesSeenHere
.Index(nIndex
) == wxNOT_FOUND
;
2778 wxLogTrace(TRACE_MIME
, wxT("mailcap %s: %s [%s]"),
2779 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2780 overwrite
? wxT("replace") : wxT("add"));
2782 int n
= AddToMimeData
2786 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2787 empty_extensions_list
,
2794 aIndicesSeenHere
.Add(n
);
2801 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2807 size_t count
= m_aTypes
.GetCount();
2808 for ( size_t n
= 0; n
< count
; n
++ )
2810 // don't return template types from here (i.e. anything containg '*')
2811 const wxString
&type
= m_aTypes
[n
];
2812 if ( type
.Find(wxT('*')) == wxNOT_FOUND
)
2814 mimetypes
.Add(type
);
2818 return mimetypes
.GetCount();
2821 // ----------------------------------------------------------------------------
2822 // writing to MIME type files
2823 // ----------------------------------------------------------------------------
2825 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2829 wxArrayString sMimeTypes
;
2830 ft
->GetMimeTypes(sMimeTypes
);
2833 size_t nCount
= sMimeTypes
.GetCount();
2834 for (i
= 0; i
< nCount
; i
++)
2836 const wxString
&sMime
= sMimeTypes
.Item(i
);
2837 int nIndex
= m_aTypes
.Index(sMime
);
2838 if ( nIndex
== wxNOT_FOUND
)
2840 // error if we get here ??
2845 WriteMimeInfo(nIndex
, true);
2846 m_aTypes
.RemoveAt(nIndex
);
2847 m_aEntries
.RemoveAt(nIndex
);
2848 m_aExtensions
.RemoveAt(nIndex
);
2849 m_aDescriptions
.RemoveAt(nIndex
);
2850 m_aIcons
.RemoveAt(nIndex
);
2853 // check data integrity
2854 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2855 m_aTypes
.Count() == m_aExtensions
.Count() &&
2856 m_aTypes
.Count() == m_aIcons
.Count() &&
2857 m_aTypes
.Count() == m_aDescriptions
.Count() );
2862 // ----------------------------------------------------------------------------
2863 // private functions
2864 // ----------------------------------------------------------------------------
2866 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2868 static const wxChar
* const knownFields
[] =
2870 wxT("x-mozilla-flags"),
2871 wxT("nametemplate"),
2872 wxT("textualnewlines"),
2875 wxString field
= fieldAll
.BeforeFirst(wxT('='));
2876 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2878 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2886 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE