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 extends wxTextFile
74 class wxMimeTextFile
: public wxTextFile
78 wxMimeTextFile () : wxTextFile () {};
79 wxMimeTextFile(const wxString
& strFile
) : wxTextFile(strFile
) {};
81 int pIndexOf(const wxString
& sSearch
, bool bIncludeComments
= false, int iStart
= 0)
83 wxString sTest
= sSearch
;
85 for(size_t i
= iStart
; i
< GetLineCount(); i
++)
87 wxString sLine
= GetLine(i
).Trim(false);
88 if(bIncludeComments
|| ! sLine
.StartsWith(wxT("#")))
91 if(sLine
.StartsWith(sTest
))
98 bool CommentLine(int nIndex
)
102 if (nIndex
>= (int)GetLineCount() )
105 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
109 bool CommentLine(const wxString
& sTest
)
111 int nIndex
= pIndexOf(sTest
);
114 if (nIndex
>= (int)GetLineCount() )
117 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
121 wxString
GetVerb(size_t i
)
123 if (i
> GetLineCount() )
124 return wxEmptyString
;
126 wxString sTmp
= GetLine(i
).BeforeFirst(wxT('='));
130 wxString
GetCmd(size_t i
)
132 if (i
> GetLineCount() )
133 return wxEmptyString
;
135 wxString sTmp
= GetLine(i
).AfterFirst(wxT('='));
140 // in case we're compiling in non-GUI mode
141 class WXDLLEXPORT wxIcon
;
143 // ----------------------------------------------------------------------------
145 // ----------------------------------------------------------------------------
147 // MIME code tracing mask
148 #define TRACE_MIME wxT("mime")
150 // give trace messages about the results of mailcap tests
151 #define TRACE_MIME_TEST wxT("mimetest")
153 // ----------------------------------------------------------------------------
155 // ----------------------------------------------------------------------------
157 // there are some fields which we don't understand but for which we don't give
158 // warnings as we know that they're not important - this function is used to
160 static bool IsKnownUnimportantField(const wxString
& field
);
162 // ----------------------------------------------------------------------------
164 // ----------------------------------------------------------------------------
167 // This class uses both mailcap and mime.types to gather information about file
170 // The information about mailcap file was extracted from metamail(1) sources
171 // and documentation and subsequently revised when I found the RFC 1524
174 // Format of mailcap file: spaces are ignored, each line is either a comment
175 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
176 // A backslash can be used to quote semicolons and newlines (and, in fact,
177 // anything else including itself).
179 // The first field is always the MIME type in the form of type/subtype (see RFC
180 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
181 // "type" which means the same as "type/*", although I'm not sure whether this
184 // The second field is always the command to run. It is subject to
185 // parameter/filename expansion described below.
187 // All the following fields are optional and may not be present at all. If
188 // they're present they may appear in any order, although each of them should
189 // appear only once. The optional fields are the following:
190 // * notes=xxx is an uninterpreted string which is silently ignored
191 // * test=xxx is the command to be used to determine whether this mailcap line
192 // applies to our data or not. The RHS of this field goes through the
193 // parameter/filename expansion (as the 2nd field) and the resulting string
194 // is executed. The line applies only if the command succeeds, i.e. returns 0
196 // * print=xxx is the command to be used to print (and not view) the data of
197 // this type (parameter/filename expansion is done here too)
198 // * edit=xxx is the command to open/edit the data of this type
199 // * needsterminal means that a new interactive console must be created for
201 // * copiousoutput means that the viewer doesn't interact with the user but
202 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
203 // good example), thus it might be a good idea to use some kind of paging
205 // * textualnewlines means not to perform CR/LF translation (not honored)
206 // * compose and composetyped fields are used to determine the program to be
207 // called to create a new message pert in the specified format (unused).
209 // Parameter/filename expansion:
210 // * %s is replaced with the (full) file name
211 // * %t is replaced with MIME type/subtype of the entry
212 // * for multipart type only %n is replaced with the nnumber of parts and %F is
213 // replaced by an array of (content-type, temporary file name) pairs for all
214 // message parts (TODO)
215 // * %{parameter} is replaced with the value of parameter taken from
216 // Content-type header line of the message.
219 // There are 2 possible formats for mime.types file, one entry per line (used
220 // for global mime.types and called Mosaic format) and "expanded" format where
221 // an entry takes multiple lines (used for users mime.types and called
224 // For both formats spaces are ignored and lines starting with a '#' are
225 // comments. Each record has one of two following forms:
226 // a) for "brief" format:
227 // <mime type> <space separated list of extensions>
228 // b) for "expanded" format:
229 // type=<mime type> BACKSLASH
230 // desc="<description>" BACKSLASH
231 // exts="<comma separated list of extensions>"
233 // (where BACKSLASH is a literal '\\' which we can't put here because cpp
236 // We try to autodetect the format of mime.types: if a non-comment line starts
237 // with "type=" we assume the second format, otherwise the first one.
239 // there may be more than one entry for one and the same mime type, to
240 // choose the right one we have to run the command specified in the test
241 // field on our data.
243 // ----------------------------------------------------------------------------
245 // ----------------------------------------------------------------------------
247 // GNOME stores the info we're interested in in several locations:
248 // 1. xxx.keys files under /usr/share/mime-info
249 // 2. xxx.keys files under ~/.gnome/mime-info
251 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
252 // just before the field name.
255 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString
& filename
,
256 const wxArrayString
& dirs
)
258 wxTextFile
textfile(filename
);
259 #if defined(__WXGTK20__) && wxUSE_UNICODE
260 if ( !textfile
.Open(wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_OCTAL
)) )
262 if ( !textfile
.Open() )
266 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
269 wxArrayString
search_dirs( dirs
);
271 // values for the entry being parsed
272 wxString curMimeType
, curIconFile
;
273 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
275 wxArrayString strExtensions
;
279 size_t nLineCount
= textfile
.GetLineCount();
281 while ( nLine
< nLineCount
)
283 pc
= textfile
[nLine
].c_str();
284 if ( *pc
!= wxT('#') )
287 wxLogTrace(TRACE_MIME
, wxT("--- Reading from Gnome file %s '%s' ---"),
288 filename
.c_str(), pc
);
290 // trim trailing space and tab
291 while ((*pc
== wxT(' ')) || (*pc
== wxT('\t')))
295 int equal_pos
= sTmp
.Find( wxT('=') );
298 wxString left_of_equal
= sTmp
.Left( equal_pos
);
299 const wxChar
*right_of_equal
= pc
;
300 right_of_equal
+= equal_pos
+1;
302 if (left_of_equal
== wxT("icon_filename"))
305 curIconFile
= right_of_equal
;
307 wxFileName
newFile( curIconFile
);
308 if (newFile
.IsRelative() || newFile
.FileExists())
310 size_t nDirs
= search_dirs
.GetCount();
312 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
314 newFile
.SetPath( search_dirs
[nDir
] );
315 newFile
.AppendDir( wxT("pixmaps") );
316 newFile
.AppendDir( wxT("document-icons") );
317 newFile
.SetExt( wxT("png") );
318 if (newFile
.FileExists())
320 curIconFile
= newFile
.GetFullPath();
321 // reorder search_dirs for speedup (fewer
322 // calls to FileExist() required)
325 const wxString
&tmp
= search_dirs
[nDir
];
326 search_dirs
.RemoveAt( nDir
);
327 search_dirs
.Insert( tmp
, 0 );
334 else if (left_of_equal
== wxT("open"))
336 sTmp
= right_of_equal
;
337 sTmp
.Replace( wxT("%f"), wxT("%s") );
338 sTmp
.Prepend( wxT("open=") );
341 else if (left_of_equal
== wxT("view"))
343 sTmp
= right_of_equal
;
344 sTmp
.Replace( wxT("%f"), wxT("%s") );
345 sTmp
.Prepend( wxT("view=") );
348 else if (left_of_equal
== wxT("print"))
350 sTmp
= right_of_equal
;
351 sTmp
.Replace( wxT("%f"), wxT("%s") );
352 sTmp
.Prepend( wxT("print=") );
355 else if (left_of_equal
== wxT("description"))
357 strDesc
= right_of_equal
;
359 else if (left_of_equal
== wxT("short_list_application_ids_for_novice_user_level"))
361 sTmp
= right_of_equal
;
362 if (sTmp
.Contains( wxT(",") ))
363 sTmp
= sTmp
.BeforeFirst( wxT(',') );
364 sTmp
.Prepend( wxT("open=") );
365 sTmp
.Append( wxT(" %s") );
369 } // emd of has an equals sign
372 // not a comment and not an equals sign
373 if (sTmp
.Contains(wxT('/')))
375 // this is the start of the new mimetype
376 // overwrite any existing data
377 if (! curMimeType
.empty())
379 AddToMimeData( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
381 // now get ready for next bit
382 entry
= new wxMimeTypeCommands
;
385 curMimeType
= sTmp
.BeforeFirst(wxT(':'));
388 } // end of not a comment
390 // ignore blank lines
392 } // end of while, save any data
394 if ( curMimeType
.empty() )
397 AddToMimeData( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
400 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString
& filename
)
402 wxTextFile
textfile(filename
);
403 if ( !textfile
.Open() )
406 wxLogTrace(TRACE_MIME
,
407 wxT("--- Opened Gnome file %s ---"),
410 // values for the entry being parsed
411 wxString curMimeType
, curExtList
;
414 size_t nLineCount
= textfile
.GetLineCount();
415 for ( size_t nLine
= 0; /* nothing */; nLine
++ )
417 if ( nLine
< nLineCount
)
419 pc
= textfile
[nLine
].c_str();
420 if ( *pc
== wxT('#') )
428 // so that we will fall into the "if" below
435 if ( !curMimeType
.empty() && !curExtList
.empty() )
437 wxLogTrace(TRACE_MIME
,
438 wxT("--- At end of Gnome file finding mimetype %s ---"),
439 curMimeType
.c_str());
441 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
446 // the end: this can only happen if nLine == nLineCount
455 // what do we have here?
456 if ( *pc
== wxT('\t') )
458 // this is a field=value ling
459 pc
++; // skip leading TAB
461 static const int lenField
= 5; // strlen("ext: ")
462 if ( wxStrncmp(pc
, wxT("ext: "), lenField
) == 0 )
464 // skip it and take everything left until the end of line
465 curExtList
= pc
+ lenField
;
467 //else: some other field, we don't care
471 // this is the start of the new section
472 wxLogTrace(TRACE_MIME
,
473 wxT("--- In Gnome file finding mimetype %s ---"),
474 curMimeType
.c_str());
476 if (! curMimeType
.empty())
477 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
481 while ( *pc
!= wxT(':') && *pc
!= wxT('\0') )
483 curMimeType
+= *pc
++;
490 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
491 const wxString
& dirbase
, const wxArrayString
& dirs
)
493 wxASSERT_MSG( !dirbase
.empty() && !wxEndsWithPathSeparator(dirbase
),
494 wxT("base directory shouldn't end with a slash") );
496 wxString dirname
= dirbase
;
497 dirname
<< wxT("/mime-info");
499 if ( !wxDir::Exists(dirname
) )
503 if ( !dir
.IsOpened() )
506 // we will concatenate it with filename to get the full path below
512 cont
= dir
.GetFirst(&filename
, wxT("*.mime"), wxDIR_FILES
);
515 LoadGnomeMimeTypesFromMimeFile(dirname
+ filename
);
517 cont
= dir
.GetNext(&filename
);
520 cont
= dir
.GetFirst(&filename
, wxT("*.keys"), wxDIR_FILES
);
523 LoadGnomeDataFromKeyFile(dirname
+ filename
, dirs
);
525 cont
= dir
.GetNext(&filename
);
528 // FIXME: Hack alert: We scan all icons and deduce the
529 // mime-type from the file name.
531 dirname
<< wxT("/pixmaps/document-icons");
533 // these are always empty in this file
534 wxArrayString strExtensions
;
537 if ( !wxDir::Exists(dirname
) )
539 // Just test for default GPE dir also
540 dirname
= wxT("/usr/share/gpe/pixmaps/default/filemanager/document-icons");
542 if ( !wxDir::Exists(dirname
) )
546 wxDir
dir2( dirname
);
548 cont
= dir2
.GetFirst(&filename
, wxT("gnome-*.png"), wxDIR_FILES
);
551 wxString mimeType
= filename
;
552 mimeType
.Remove( 0, 6 ); // remove "gnome-"
553 mimeType
.Remove( mimeType
.Len() - 4, 4 ); // remove ".png"
554 int pos
= mimeType
.Find( wxT("-") );
555 if (pos
!= wxNOT_FOUND
)
557 mimeType
.SetChar( pos
, wxT('/') );
558 wxString iconFile
= dirname
;
559 iconFile
<< wxT("/");
560 iconFile
<< filename
;
561 AddToMimeData( mimeType
, iconFile
, NULL
, strExtensions
, strDesc
, true );
564 cont
= dir2
.GetNext(&filename
);
568 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString
& sExtraDir
)
572 wxString gnomedir
= wxGetenv( wxT("GNOMEDIR") );
573 if (!gnomedir
.empty())
575 gnomedir
<< wxT("/share");
576 dirs
.Add( gnomedir
);
579 dirs
.Add(wxT("/usr/share"));
580 dirs
.Add(wxT("/usr/local/share"));
582 gnomedir
= wxGetHomeDir();
583 gnomedir
<< wxT("/.gnome");
584 dirs
.Add( gnomedir
);
586 if (!sExtraDir
.empty())
587 dirs
.Add( sExtraDir
);
589 size_t nDirs
= dirs
.GetCount();
590 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
592 LoadGnomeMimeFilesFromDir(dirs
[nDir
], dirs
);
596 // ----------------------------------------------------------------------------
598 // ----------------------------------------------------------------------------
601 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
602 // may be found in either of the following locations
604 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
605 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
607 // The format of a .kdelnk file is almost the same as the one used by
608 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
609 // value for the entry "Type"
611 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
612 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
614 bool wxMimeTypesManagerImpl::CheckKDEDirsExist( const wxString
&sOK
, const wxString
&sTest
)
618 return wxDir::Exists(sOK
);
622 wxString sStart
= sOK
+ wxT("/") + sTest
.BeforeFirst(wxT('/'));
623 if (!wxDir::Exists(sStart
))
625 wxString sEnd
= sTest
.AfterFirst(wxT('/'));
626 return CheckKDEDirsExist(sStart
, sEnd
);
630 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index
, bool delete_index
)
632 wxMimeTextFile appoutfile
, mimeoutfile
;
633 wxString sHome
= wxGetHomeDir();
634 wxString sTmp
= wxT(".kde/share/mimelnk/");
635 wxString sMime
= m_aTypes
[index
];
636 CheckKDEDirsExist(sHome
, sTmp
+ sMime
.BeforeFirst(wxT('/')) );
637 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
+ wxT(".kdelnk");
640 bool bMimeExists
= mimeoutfile
.Open(sTmp
);
643 bTemp
= mimeoutfile
.Create(sTmp
);
644 // some unknown error eg out of disk space
649 sTmp
= wxT(".kde/share/applnk/");
650 CheckKDEDirsExist(sHome
, sTmp
+ sMime
.AfterFirst(wxT('/')) );
651 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
.AfterFirst(wxT('/')) + wxT(".kdelnk");
654 bAppExists
= appoutfile
.Open(sTmp
);
657 bTemp
= appoutfile
.Create(sTmp
);
658 // some unknown error eg out of disk space
663 // fixed data; write if new file
666 mimeoutfile
.AddLine(wxT("#KDE Config File"));
667 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
668 mimeoutfile
.AddLine(wxT("Version=1.0"));
669 mimeoutfile
.AddLine(wxT("Type=MimeType"));
670 mimeoutfile
.AddLine(wxT("MimeType=") + sMime
);
675 mimeoutfile
.AddLine(wxT("#KDE Config File"));
676 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
677 appoutfile
.AddLine(wxT("Version=1.0"));
678 appoutfile
.AddLine(wxT("Type=Application"));
679 appoutfile
.AddLine(wxT("MimeType=") + sMime
+ wxT(';'));
684 mimeoutfile
.CommentLine(wxT("Comment="));
686 mimeoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
687 appoutfile
.CommentLine(wxT("Name="));
689 appoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
691 sTmp
= m_aIcons
[index
];
692 // we can either give the full path, or the shortfilename if its in
693 // one of the directories we search
694 mimeoutfile
.CommentLine(wxT("Icon=") );
696 mimeoutfile
.AddLine(wxT("Icon=") + sTmp
);
697 appoutfile
.CommentLine(wxT("Icon=") );
699 appoutfile
.AddLine(wxT("Icon=") + sTmp
);
701 sTmp
= wxT(" ") + m_aExtensions
[index
];
703 wxStringTokenizer
tokenizer(sTmp
, wxT(" "));
704 sTmp
= wxT("Patterns=");
705 mimeoutfile
.CommentLine(sTmp
);
706 while ( tokenizer
.HasMoreTokens() )
708 // holds an extension; need to change it to *.ext;
709 wxString e
= wxT("*.") + tokenizer
.GetNextToken() + wxT(";");
714 mimeoutfile
.AddLine(sTmp
);
716 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
717 // if we don't find open just have an empty string ... FIX this
718 sTmp
= entries
->GetCommandForVerb(wxT("open"));
719 sTmp
.Replace( wxT("%s"), wxT("%f") );
721 mimeoutfile
.CommentLine(wxT("DefaultApp=") );
723 mimeoutfile
.AddLine(wxT("DefaultApp=") + sTmp
);
725 sTmp
.Replace( wxT("%f"), wxT("") );
726 appoutfile
.CommentLine(wxT("Exec="));
728 appoutfile
.AddLine(wxT("Exec=") + sTmp
);
730 if (entries
->GetCount() > 1)
732 //other actions as well as open
736 if (mimeoutfile
.Write())
739 if (appoutfile
.Write())
746 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString
& dirbase
,
747 const wxString
& subdir
,
748 const wxString
& filename
,
749 const wxArrayString
& icondirs
)
751 wxFileName
fullname(dirbase
, filename
);
753 if(! file
.Open( fullname
.GetFullPath() )) return;
755 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
756 fullname
.GetFullPath().c_str());
758 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
760 wxString mimetype
, mime_desc
, strIcon
;
762 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
763 if (nIndex
== wxNOT_FOUND
)
765 // construct mimetype from the directory name and the basename of the
766 // file (it always has .kdelnk extension)
767 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
770 mimetype
= file
.GetCmd(nIndex
);
772 // first find the description string: it is the value in either "Comment="
773 // line or "Comment[<locale_name>]=" one
774 nIndex
= wxNOT_FOUND
;
779 wxLocale
*locale
= wxGetLocale();
782 // try "Comment[locale name]" first
783 comment
<< wxT("Comment[") + locale
->GetName() + wxT("]=");
784 nIndex
= file
.pIndexOf(comment
);
788 if ( nIndex
== wxNOT_FOUND
)
790 comment
= wxT("Comment=");
791 nIndex
= file
.pIndexOf(comment
);
794 if ( nIndex
!= wxNOT_FOUND
)
795 mime_desc
= file
.GetCmd(nIndex
);
796 //else: no description
798 // next find the extensions
799 wxString mime_extension
;
801 nIndex
= file
.pIndexOf(wxT("Patterns="));
802 if ( nIndex
!= wxNOT_FOUND
)
804 wxString exts
= file
.GetCmd(nIndex
);
806 wxStringTokenizer
tokenizer(exts
, wxT(";"));
807 while ( tokenizer
.HasMoreTokens() )
809 wxString e
= tokenizer
.GetNextToken();
811 // don't support too difficult patterns
812 if ( e
.Left(2) != wxT("*.") )
815 if ( !mime_extension
.empty() )
817 // separate from the previous ext
818 mime_extension
<< wxT(' ');
821 mime_extension
<< e
.Mid(2);
825 sExts
.Add(mime_extension
);
827 // ok, now we can take care of icon:
829 nIndex
= file
.pIndexOf(wxT("Icon="));
830 if ( nIndex
!= wxNOT_FOUND
)
832 strIcon
= file
.GetCmd(nIndex
);
834 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
836 // it could be the real path, but more often a short name
837 if (!wxFileExists(strIcon
))
839 // icon is just the short name
840 if ( !strIcon
.empty() )
842 // we must check if the file exists because it may be stored
843 // in many locations, at least ~/.kde and $KDEDIR
844 size_t nDir
, nDirs
= icondirs
.GetCount();
845 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
847 wxFileName
fnameIcon( strIcon
);
848 wxFileName
fname( icondirs
[nDir
], fnameIcon
.GetName() );
849 fname
.SetExt( wxT("png") );
850 if (fname
.FileExists())
852 strIcon
= fname
.GetFullPath();
853 wxLogTrace(TRACE_MIME
, wxT(" iconfile %s"), strIcon
.c_str());
861 // now look for lines which know about the application
862 // exec= or DefaultApp=
864 nIndex
= file
.pIndexOf(wxT("DefaultApp"));
866 if ( nIndex
== wxNOT_FOUND
)
869 nIndex
= file
.pIndexOf(wxT("Exec"));
872 if ( nIndex
!= wxNOT_FOUND
)
874 // we expect %f; others including %F and %U and %u are possible
875 wxString sTmp
= file
.GetCmd(nIndex
);
876 if (0 == sTmp
.Replace( wxT("%f"), wxT("%s") ))
878 entry
->AddOrReplaceVerb(wxString(wxT("open")), sTmp
);
881 AddToMimeData(mimetype
, strIcon
, entry
, sExts
, mime_desc
);
884 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString
& dirbase
,
885 const wxString
& subdir
,
886 const wxArrayString
& icondirs
)
888 wxFileName
dirname(dirbase
, wxEmptyString
);
889 dirname
.AppendDir(subdir
);
890 wxDir
dir(dirname
.GetPath());
894 wxLogTrace(TRACE_MIME
, wxT("--- Loading from KDE directory %s ---"),
895 dirname
.GetPath().c_str());
898 bool cont
= dir
.GetFirst(&filename
, wxT("*.kdelnk"), wxDIR_FILES
);
900 LoadKDELinksForMimeSubtype(dirname
.GetPath(), subdir
,
902 cont
= dir
.GetNext(&filename
);
905 // new standard for Gnome and KDE
906 cont
= dir
.GetFirst(&filename
, wxT("*.desktop"), wxDIR_FILES
);
908 LoadKDELinksForMimeSubtype(dirname
.GetPath(), subdir
,
910 cont
= dir
.GetNext(&filename
);
914 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString
& dirname
,
915 const wxArrayString
& icondirs
)
917 if(! wxDir::Exists(dirname
))
921 if ( !dir
.IsOpened() )
925 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
928 LoadKDELinksForMimeType(dirname
, subdir
, icondirs
);
930 cont
= dir
.GetNext(&subdir
);
934 // Read a KDE .desktop file of type 'Application'
935 void wxMimeTypesManagerImpl::LoadKDEApp(const wxString
& filename
)
938 if ( !file
.Open(filename
) ) return;
939 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"), filename
.c_str());
941 // Here, only type 'Application' should be considered.
942 int nIndex
= file
.pIndexOf( wxT("Type=") );
943 if (nIndex
!= wxNOT_FOUND
&&
944 file
.GetCmd(nIndex
).Lower() != wxT("application"))
947 // The hidden entry specifies a file to be ignored.
948 nIndex
= file
.pIndexOf( wxT("Hidden=") );
949 if (nIndex
!= wxNOT_FOUND
&& file
.GetCmd(nIndex
).Lower() == wxT("true"))
952 // Semicolon separated list of mime types handled by the application.
953 nIndex
= file
.pIndexOf( wxT("MimeType=") );
954 if (nIndex
== wxNOT_FOUND
)
956 wxString mimetypes
= file
.GetCmd (nIndex
);
958 // Name of the application
960 nIndex
= wxNOT_FOUND
;
961 #if wxUSE_INTL // try "Name[locale name]" first
962 wxLocale
*locale
= wxGetLocale();
964 nIndex
= file
.pIndexOf(_T("Name[")+locale
->GetName()+_T("]="));
966 if(nIndex
== wxNOT_FOUND
)
967 nIndex
= file
.pIndexOf( wxT("Name=") );
968 if(nIndex
!= wxNOT_FOUND
)
969 nameapp
= file
.GetCmd(nIndex
);
971 // Icon of the application.
972 wxString nameicon
, namemini
;
973 nIndex
= wxNOT_FOUND
;
974 #if wxUSE_INTL // try "Icon[locale name]" first
976 nIndex
= file
.pIndexOf(_T("Icon[")+locale
->GetName()+_T("]="));
978 if(nIndex
== wxNOT_FOUND
)
979 nIndex
= file
.pIndexOf( wxT("Icon=") );
980 if(nIndex
!= wxNOT_FOUND
) {
981 nameicon
= wxString(wxT("--icon ")) + file
.GetCmd(nIndex
);
982 namemini
= wxString(wxT("--miniicon ")) + file
.GetCmd(nIndex
);
985 // Replace some of the field code in the 'Exec' entry.
986 // TODO: deal with %d, %D, %n, %N, %k and %v (but last one is deprecated)
987 nIndex
= file
.pIndexOf( wxT("Exec=") );
988 if (nIndex
== wxNOT_FOUND
)
990 wxString sCmd
= file
.GetCmd(nIndex
);
991 // we expect %f; others including %F and %U and %u are possible
992 sCmd
.Replace(wxT("%F"), wxT("%f"));
993 sCmd
.Replace(wxT("%U"), wxT("%f"));
994 sCmd
.Replace(wxT("%u"), wxT("%f"));
995 if (0 == sCmd
.Replace ( wxT("%f"), wxT("%s") ))
996 sCmd
= sCmd
+ wxT(" %s");
997 sCmd
.Replace(wxT("%c"), nameapp
);
998 sCmd
.Replace(wxT("%i"), nameicon
);
999 sCmd
.Replace(wxT("%m"), namemini
);
1001 wxStringTokenizer
tokenizer(mimetypes
, _T(";"));
1002 while(tokenizer
.HasMoreTokens()) {
1003 wxString mimetype
= tokenizer
.GetNextToken().Lower();
1004 int nIndex
= m_aTypes
.Index(mimetype
);
1005 if(nIndex
!= wxNOT_FOUND
) { // is this a known MIME type?
1006 wxMimeTypeCommands
* entry
= m_aEntries
[nIndex
];
1007 entry
->AddOrReplaceVerb(wxT("open"), sCmd
);
1012 void wxMimeTypesManagerImpl::LoadKDEAppsFilesFromDir(const wxString
& dirname
)
1014 if(! wxDir::Exists(dirname
))
1017 if ( !dir
.IsOpened() )
1021 // Look into .desktop files
1022 bool cont
= dir
.GetFirst(&filename
, _T("*.desktop"), wxDIR_FILES
);
1024 wxFileName
p(dirname
, filename
);
1025 LoadKDEApp( p
.GetFullPath() );
1026 cont
= dir
.GetNext(&filename
);
1028 // Look recursively into subdirs
1029 cont
= dir
.GetFirst(&filename
, wxEmptyString
, wxDIR_DIRS
);
1031 wxFileName
p(dirname
, wxEmptyString
);
1032 p
.AppendDir(filename
);
1033 LoadKDEAppsFilesFromDir( p
.GetPath() );
1034 cont
= dir
.GetNext(&filename
);
1038 // Return base KDE directories.
1039 // 1) Environment variable $KDEHOME, or "~/.kde" if not set.
1040 // 2) List of directories in colon separated environment variable $KDEDIRS.
1041 // 3) Environment variable $KDEDIR in case $KDEDIRS is not set.
1042 // Notice at least the local kde directory is added to the list. If it is the
1043 // only one, use later the application 'kde-config' to get additional paths.
1044 static void GetKDEBaseDirs(wxArrayString
& basedirs
)
1046 wxString env
= wxGetenv( wxT("KDEHOME") );
1048 env
= wxGetHomeDir() + wxT("/.kde");
1051 env
= wxGetenv( wxT("KDEDIRS") );
1053 env
= wxGetenv( wxT("KDEDIR") );
1057 wxStringTokenizer
tokenizer(env
, wxT(":"));
1058 while(tokenizer
.HasMoreTokens())
1059 basedirs
.Add( tokenizer
.GetNextToken() );
1063 static wxString
ReadPathFromKDEConfig(const wxString
& request
)
1066 wxArrayString output
;
1067 if(wxExecute(wxT("kde-config --path ")+request
, output
) == 0 &&
1069 str
= output
.Item(0);
1073 // Try to find the "Theme" entry in the configuration file, provided it exists.
1074 static wxString
GetKDEThemeInFile(const wxFileName
& filename
)
1078 if(filename
.FileExists() && config
.Open( filename
.GetFullPath() )) {
1079 size_t cnt
= config
.GetLineCount();
1080 for(size_t i
= 0; i
< cnt
; i
++)
1081 if(config
[i
].StartsWith(wxT("Theme="), &theme
))
1087 // Try to find a file "kdeglobals" in one of the directories and read the
1088 // "Theme" entry there.
1089 static wxString
GetKDETheme(const wxArrayString
& basedirs
)
1092 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1093 wxFileName
filename(basedirs
.Item(i
), wxEmptyString
);
1094 filename
.AppendDir( wxT("share") );
1095 filename
.AppendDir( wxT("config") );
1096 filename
.SetName( wxT("kdeglobals") );
1097 theme
= GetKDEThemeInFile(filename
);
1098 if(! theme
.IsEmpty())
1101 // If $KDEDIRS and $KDEDIR were set, we try nothing more. Otherwise, we
1102 // try to get the configuration file with 'kde-config'.
1103 if(basedirs
.Count() > 1)
1105 wxString paths
= ReadPathFromKDEConfig(wxT("config"));
1106 if(! paths
.IsEmpty()) {
1107 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1108 while( tokenizer
.HasMoreTokens() ) {
1109 wxFileName
filename(tokenizer
.GetNextToken(), wxT("kdeglobals"));
1110 theme
= GetKDEThemeInFile(filename
);
1111 if(! theme
.IsEmpty())
1118 // Get list of directories of icons.
1119 static void GetKDEIconDirs(const wxArrayString
& basedirs
,
1120 wxArrayString
& icondirs
)
1122 wxString theme
= GetKDETheme(basedirs
);
1124 theme
= wxT("default.kde");
1126 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1127 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1128 dirname
.AppendDir( wxT("share") );
1129 dirname
.AppendDir( wxT("icons") );
1130 dirname
.AppendDir(theme
);
1131 dirname
.AppendDir( wxT("32x32") );
1132 dirname
.AppendDir( wxT("mimetypes") );
1133 if( wxDir::Exists( dirname
.GetPath() ) )
1134 icondirs
.Add( dirname
.GetPath() );
1137 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1138 if(basedirs
.Count() > 1)
1140 wxString paths
= ReadPathFromKDEConfig(wxT("icon"));
1141 if(! paths
.IsEmpty()) {
1142 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1143 while( tokenizer
.HasMoreTokens() ) {
1144 wxFileName
dirname(tokenizer
.GetNextToken(), wxEmptyString
);
1145 dirname
.AppendDir(theme
);
1146 dirname
.AppendDir( wxT("32x32") );
1147 dirname
.AppendDir( wxT("mimetypes") );
1148 if(icondirs
.Index(dirname
.GetPath()) == wxNOT_FOUND
&&
1149 wxDir::Exists( dirname
.GetPath() ) )
1150 icondirs
.Add( dirname
.GetPath() );
1155 // Get list of directories of mime types.
1156 static void GetKDEMimeDirs(const wxArrayString
& basedirs
,
1157 wxArrayString
& mimedirs
)
1159 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1160 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1161 dirname
.AppendDir( wxT("share") );
1162 dirname
.AppendDir( wxT("mimelnk") );
1163 if( wxDir::Exists( dirname
.GetPath() ) )
1164 mimedirs
.Add( dirname
.GetPath() );
1167 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1168 if(basedirs
.Count() > 1)
1170 wxString paths
= ReadPathFromKDEConfig(wxT("mime"));
1171 if(! paths
.IsEmpty()) {
1172 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1173 while( tokenizer
.HasMoreTokens() ) {
1174 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1175 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1176 if(mimedirs
.Index(dirname
) == wxNOT_FOUND
&&
1177 wxDir::Exists(dirname
) )
1178 mimedirs
.Add(dirname
);
1183 // Get list of directories of application desktop files.
1184 static void GetKDEAppsDirs(const wxArrayString
& basedirs
,
1185 wxArrayString
& appsdirs
)
1187 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1188 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1189 dirname
.AppendDir( wxT("share") );
1190 dirname
.AppendDir( wxT("applnk") );
1191 if( wxDir::Exists( dirname
.GetPath() ) )
1192 appsdirs
.Add( dirname
.GetPath() );
1195 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1196 if(basedirs
.Count() > 1)
1198 wxString paths
= ReadPathFromKDEConfig(wxT("apps"));
1199 if(! paths
.IsEmpty()) {
1200 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1201 while( tokenizer
.HasMoreTokens() ) {
1202 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1203 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1204 if(appsdirs
.Index(dirname
) == wxNOT_FOUND
&&
1205 wxDir::Exists(dirname
) )
1206 appsdirs
.Add(dirname
);
1209 paths
= ReadPathFromKDEConfig(wxT("xdgdata-apps"));
1210 if(! paths
.IsEmpty()) {
1211 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1212 while( tokenizer
.HasMoreTokens() ) {
1213 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1214 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1215 if(appsdirs
.Index(dirname
) == wxNOT_FOUND
&&
1216 wxDir::Exists(dirname
) )
1217 appsdirs
.Add(dirname
);
1222 // Fill database with all mime types.
1223 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString
& sExtraDir
)
1225 wxArrayString basedirs
;
1226 GetKDEBaseDirs(basedirs
);
1228 wxArrayString icondirs
;
1229 GetKDEIconDirs(basedirs
, icondirs
);
1230 wxArrayString mimedirs
;
1231 GetKDEMimeDirs(basedirs
, mimedirs
);
1232 wxArrayString appsdirs
;
1233 GetKDEAppsDirs(basedirs
, appsdirs
);
1235 if(! sExtraDir
.IsEmpty()) {
1236 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1237 mimedirs
.Add(sExtraDir
+ wxT("/mimelnk"));
1238 appsdirs
.Add(sExtraDir
+ wxT("/applnk"));
1242 size_t nDirs
= mimedirs
.GetCount(), nDir
;
1243 for(nDir
= 0; nDir
< nDirs
; nDir
++)
1244 LoadKDELinkFilesFromDir(mimedirs
[nDir
], icondirs
);
1246 // Load application files and associate them to corresponding mime types.
1247 nDirs
= appsdirs
.GetCount();
1248 for(nDir
= 0; nDir
< nDirs
; nDir
++)
1249 LoadKDEAppsFilesFromDir(appsdirs
[nDir
]);
1252 // ----------------------------------------------------------------------------
1253 // wxFileTypeImpl (Unix)
1254 // ----------------------------------------------------------------------------
1256 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1260 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1262 sTmp
= m_manager
->GetCommand( verb
, m_index
[i
] );
1266 return wxFileType::ExpandCommand(sTmp
, params
);
1269 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
1273 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1275 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1284 iconLoc
->SetFileName(sTmp
);
1290 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1293 size_t nCount
= m_index
.GetCount();
1294 for (size_t i
= 0; i
< nCount
; i
++)
1295 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1300 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1301 wxArrayString
*commands
,
1302 const wxFileType::MessageParameters
& params
) const
1304 wxString vrb
, cmd
, sTmp
;
1306 wxMimeTypeCommands
* sPairs
;
1308 // verbs and commands have been cleared already in mimecmn.cpp...
1309 // if we find no entries in the exact match, try the inexact match
1310 for (size_t n
= 0; ((count
== 0) && (n
< m_index
.GetCount())); n
++)
1312 // list of verb = command pairs for this mimetype
1313 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1315 for ( i
= 0; i
< sPairs
->GetCount(); i
++ )
1317 vrb
= sPairs
->GetVerb(i
);
1318 // some gnome entries have "." inside
1319 vrb
= vrb
.AfterLast(wxT('.'));
1320 cmd
= sPairs
->GetCmd(i
);
1323 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1325 if ( vrb
.IsSameAs(wxT("open")))
1328 verbs
->Insert(vrb
, 0u);
1330 commands
->Insert(cmd
, 0u);
1346 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1348 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1351 // one extension in the space or comma-delimited list
1353 for ( const wxChar
*p
= strExtensions
; /* nothing */; p
++ )
1355 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') )
1357 if ( !strExt
.empty() )
1359 extensions
.Add(strExt
);
1362 //else: repeated spaces
1363 // (shouldn't happen, but it's not that important if it does happen)
1365 if ( *p
== wxT('\0') )
1368 else if ( *p
== wxT('.') )
1370 // remove the dot from extension (but only if it's the first char)
1371 if ( !strExt
.empty() )
1375 //else: no, don't append it
1386 // set an arbitrary command:
1387 // could adjust the code to ask confirmation if it already exists and
1388 // overwriteprompt is true, but this is currently ignored as *Associate* has
1389 // no overwrite prompt
1391 wxFileTypeImpl::SetCommand(const wxString
& cmd
,
1392 const wxString
& verb
,
1393 bool WXUNUSED(overwriteprompt
))
1395 wxArrayString strExtensions
;
1396 wxString strDesc
, strIcon
;
1398 wxArrayString strTypes
;
1399 GetMimeTypes(strTypes
);
1400 if ( strTypes
.IsEmpty() )
1403 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1404 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1407 size_t nCount
= strTypes
.GetCount();
1408 for ( size_t i
= 0; i
< nCount
; i
++ )
1410 if (!m_manager
->DoAssociation(strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1417 // ignore index on the grounds that we only have one icon in a Unix file
1418 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
, int WXUNUSED(index
))
1420 if (strIcon
.empty())
1423 wxArrayString strExtensions
;
1426 wxArrayString strTypes
;
1427 GetMimeTypes(strTypes
);
1428 if ( strTypes
.IsEmpty() )
1431 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1433 size_t nCount
= strTypes
.GetCount();
1434 for ( size_t i
= 0; i
< nCount
; i
++ )
1436 if ( !m_manager
->DoAssociation
1452 // ----------------------------------------------------------------------------
1453 // wxMimeTypesManagerImpl (Unix)
1454 // ----------------------------------------------------------------------------
1456 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1458 m_initialized
= false;
1459 m_mailcapStylesInited
= 0;
1462 void wxMimeTypesManagerImpl::InitIfNeeded()
1464 if ( !m_initialized
)
1466 // set the flag first to prevent recursion
1467 m_initialized
= true;
1469 wxString wm
= wxTheApp
->GetTraits()->GetDesktopEnvironment();
1471 if (wm
== wxT("KDE"))
1472 Initialize( wxMAILCAP_KDE
);
1473 else if (wm
== wxT("GNOME"))
1474 Initialize( wxMAILCAP_GNOME
);
1480 // read system and user mailcaps and other files
1481 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1482 const wxString
& sExtraDir
)
1484 // read mimecap amd mime.types
1485 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1486 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1487 GetMimeInfo(sExtraDir
);
1489 // read GNOME tables
1490 if (mailcapStyles
& wxMAILCAP_GNOME
)
1491 GetGnomeMimeInfo(sExtraDir
);
1494 if (mailcapStyles
& wxMAILCAP_KDE
)
1495 GetKDEMimeInfo(sExtraDir
);
1497 m_mailcapStylesInited
|= mailcapStyles
;
1500 // clear data so you can read another group of WM files
1501 void wxMimeTypesManagerImpl::ClearData()
1505 m_aExtensions
.Clear();
1506 m_aDescriptions
.Clear();
1508 WX_CLEAR_ARRAY(m_aEntries
);
1511 m_mailcapStylesInited
= 0;
1514 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1519 void wxMimeTypesManagerImpl::GetMimeInfo(const wxString
& sExtraDir
)
1521 // read this for netscape or Metamail formats
1523 // directories where we look for mailcap and mime.types by default
1524 // used by netscape and pine and other mailers, using 2 different formats!
1526 // (taken from metamail(1) sources)
1528 // although RFC 1524 specifies the search path of
1529 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1530 // places - OTOH, the RFC also says that this path can be changed with
1531 // MAILCAPS environment variable (containing the colon separated full
1532 // filenames to try) which is not done yet (TODO?)
1534 wxString strHome
= wxGetenv(wxT("HOME"));
1537 dirs
.Add( strHome
+ wxT("/.") );
1538 dirs
.Add( wxT("/etc/") );
1539 dirs
.Add( wxT("/usr/etc/") );
1540 dirs
.Add( wxT("/usr/local/etc/") );
1541 dirs
.Add( wxT("/etc/mail/") );
1542 dirs
.Add( wxT("/usr/public/lib/") );
1543 if (!sExtraDir
.empty())
1544 dirs
.Add( sExtraDir
+ wxT("/") );
1547 size_t nDirs
= dirs
.GetCount();
1548 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1551 file
+= wxT("mailcap");
1552 if ( wxFile::Exists(file
) )
1558 file
+= wxT("mime.types");
1559 if ( wxFile::Exists(file
) )
1560 ReadMimeTypes(file
);
1564 bool wxMimeTypesManagerImpl::WriteToMimeTypes(int index
, bool delete_index
)
1566 // check we have the right manager
1567 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1571 wxString strHome
= wxGetenv(wxT("HOME"));
1573 // and now the users mailcap
1574 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1576 wxMimeTextFile file
;
1577 if ( wxFile::Exists(strUserMailcap
) )
1579 bTemp
= file
.Open(strUserMailcap
);
1586 bTemp
= file
.Create(strUserMailcap
);
1592 // test for netscape's header and return false if its found
1593 nIndex
= file
.pIndexOf(wxT("#--Netscape"));
1594 if (nIndex
!= wxNOT_FOUND
)
1596 wxFAIL_MSG(wxT("Error in .mime.types\nTrying to mix Netscape and Metamail formats\nFile not modified"));
1600 // write it in alternative format
1601 // get rid of unwanted entries
1602 wxString strType
= m_aTypes
[index
];
1603 nIndex
= file
.pIndexOf(strType
);
1605 // get rid of all the unwanted entries...
1606 if (nIndex
!= wxNOT_FOUND
)
1607 file
.CommentLine(nIndex
);
1611 // add the new entries in
1612 wxString sTmp
= strType
.Append( wxT(' '), 40 - strType
.Len() );
1613 sTmp
+= m_aExtensions
[index
];
1617 bTemp
= file
.Write();
1624 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes(int index
, bool delete_index
)
1626 //check we have the right managers
1627 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1631 wxString strHome
= wxGetenv(wxT("HOME"));
1633 // and now the users mailcap
1634 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1636 wxMimeTextFile file
;
1637 if ( wxFile::Exists(strUserMailcap
) )
1639 bTemp
= file
.Open(strUserMailcap
);
1646 bTemp
= file
.Create(strUserMailcap
);
1651 // write it in the format that Netscape uses
1653 // test for netscape's header and insert if required...
1654 // this is a comment so use true
1655 nIndex
= file
.pIndexOf(wxT("#--Netscape"), true);
1656 if (nIndex
== wxNOT_FOUND
)
1658 // either empty file or metamail format
1659 // at present we can't cope with mixed formats, so exit to preseve
1660 // metamail entreies
1661 if (file
.GetLineCount() > 0)
1663 wxFAIL_MSG(wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1667 file
.InsertLine(wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1671 wxString strType
= wxT("type=") + m_aTypes
[index
];
1672 nIndex
= file
.pIndexOf(strType
);
1674 // get rid of all the unwanted entries...
1675 if (nIndex
!= wxNOT_FOUND
)
1677 wxString sOld
= file
[nIndex
];
1678 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1680 file
.CommentLine(nIndex
);
1681 sOld
= file
[nIndex
];
1683 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1688 if (nIndex
< (int) file
.GetLineCount())
1689 file
.CommentLine(nIndex
);
1692 nIndex
= (int) file
.GetLineCount();
1694 wxString sTmp
= strType
+ wxT(" \\");
1696 file
.InsertLine(sTmp
, nIndex
);
1698 if ( ! m_aDescriptions
.Item(index
).empty() )
1700 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1704 file
.InsertLine(sTmp
, nIndex
);
1708 wxString sExts
= m_aExtensions
.Item(index
);
1709 sTmp
= wxT("exts=\"") + sExts
.Trim(false).Trim() + wxT("\"");
1713 file
.InsertLine(sTmp
, nIndex
);
1716 bTemp
= file
.Write();
1723 bool wxMimeTypesManagerImpl::WriteToMailCap(int index
, bool delete_index
)
1725 //check we have the right managers
1726 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1727 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1731 wxString strHome
= wxGetenv(wxT("HOME"));
1733 // and now the users mailcap
1734 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1736 wxMimeTextFile file
;
1737 if ( wxFile::Exists(strUserMailcap
) )
1739 bTemp
= file
.Open(strUserMailcap
);
1746 bTemp
= file
.Create(strUserMailcap
);
1751 // now got a file we can write to ....
1752 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1754 wxString sCmd
= entries
->GetCommandForVerb(wxT("open"), &iOpen
);
1757 sTmp
= m_aTypes
[index
];
1759 int nIndex
= file
.pIndexOf(sTmp
);
1761 // get rid of all the unwanted entries...
1762 if (nIndex
== wxNOT_FOUND
)
1764 nIndex
= (int) file
.GetLineCount();
1768 sOld
= file
[nIndex
];
1769 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1771 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1773 file
.CommentLine(nIndex
);
1774 if (nIndex
< (int) file
.GetLineCount())
1775 sOld
= sOld
+ file
[nIndex
];
1779 file
.GetLineCount()) file
.CommentLine(nIndex
);
1782 sTmp
+= wxT(";") + sCmd
; //includes wxT(" %s ");
1784 // write it in the format that Netscape uses (default)
1785 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1788 file
.InsertLine(sTmp
, nIndex
);
1793 // write extended format
1795 // TODO - FIX this code:
1797 // sOld holds all the entries, but our data store only has some
1798 // eg test= is not stored
1800 // so far we have written the mimetype and command out
1801 wxStringTokenizer
sT(sOld
, wxT(";\\"));
1802 if (sT
.CountTokens() > 2)
1804 // first one mimetype; second one command, rest unknown...
1806 s
= sT
.GetNextToken();
1807 s
= sT
.GetNextToken();
1810 s
= sT
.GetNextToken();
1811 while ( ! s
.empty() )
1813 bool bKnownToken
= false;
1814 if (s
.Contains(wxT("description=")))
1816 if (s
.Contains(wxT("x11-bitmap=")))
1820 size_t nCount
= entries
->GetCount();
1821 for (i
=0; i
< nCount
; i
++)
1823 if (s
.Contains(entries
->GetVerb(i
)))
1829 sTmp
+= wxT("; \\");
1830 file
.InsertLine(sTmp
, nIndex
);
1834 s
= sT
.GetNextToken();
1838 if (! m_aDescriptions
[index
].empty() )
1840 sTmp
+= wxT("; \\");
1841 file
.InsertLine(sTmp
, nIndex
);
1843 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1846 if (! m_aIcons
[index
].empty() )
1848 sTmp
+= wxT("; \\");
1849 file
.InsertLine(sTmp
, nIndex
);
1851 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1854 if ( entries
->GetCount() > 1 )
1857 for (i
=0; i
< entries
->GetCount(); i
++)
1860 sTmp
+= wxT("; \\");
1861 file
.InsertLine(sTmp
, nIndex
);
1863 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1867 file
.InsertLine(sTmp
, nIndex
);
1871 bTemp
= file
.Write();
1878 wxFileType
* wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1882 wxString strType
= ftInfo
.GetMimeType();
1883 wxString strDesc
= ftInfo
.GetDescription();
1884 wxString strIcon
= ftInfo
.GetIconFile();
1886 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1888 if ( ! ftInfo
.GetOpenCommand().empty())
1889 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand() + wxT(" %s "));
1890 if ( ! ftInfo
.GetPrintCommand().empty())
1891 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand() + wxT(" %s "));
1893 // now find where these extensions are in the data store and remove them
1894 wxArrayString sA_Exts
= ftInfo
.GetExtensions();
1895 wxString sExt
, sExtStore
;
1897 size_t nExtCount
= sA_Exts
.GetCount();
1898 for (i
=0; i
< nExtCount
; i
++)
1900 sExt
= sA_Exts
.Item(i
);
1902 // clean up to just a space before and after
1903 sExt
.Trim().Trim(false);
1904 sExt
= wxT(' ') + sExt
+ wxT(' ');
1905 size_t nCount
= m_aExtensions
.GetCount();
1906 for (nIndex
= 0; nIndex
< nCount
; nIndex
++)
1908 sExtStore
= m_aExtensions
.Item(nIndex
);
1909 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0)
1910 m_aExtensions
.Item(nIndex
) = sExtStore
;
1914 if ( !DoAssociation(strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1917 return GetFileTypeFromMimeType(strType
);
1920 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1921 const wxString
& strIcon
,
1922 wxMimeTypeCommands
*entry
,
1923 const wxArrayString
& strExtensions
,
1924 const wxString
& strDesc
)
1926 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
1928 if ( nIndex
== wxNOT_FOUND
)
1931 return WriteMimeInfo(nIndex
, false);
1934 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
1938 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
1940 // write in metamail format;
1941 if (WriteToMimeTypes(nIndex
, delete_mime
) )
1942 if ( WriteToMailCap(nIndex
, delete_mime
) )
1946 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
1948 // write in netsacpe format;
1949 if (WriteToNSMimeTypes(nIndex
, delete_mime
) )
1950 if ( WriteToMailCap(nIndex
, delete_mime
) )
1954 // Don't write GNOME files here as this is not
1955 // allowed and simply doesn't work
1957 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
1959 // write in KDE format;
1960 if (WriteKDEMimeFile(nIndex
, delete_mime
) )
1967 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
1968 const wxString
& strIcon
,
1969 wxMimeTypeCommands
*entry
,
1970 const wxArrayString
& strExtensions
,
1971 const wxString
& strDesc
,
1972 bool replaceExisting
)
1976 // ensure mimetype is always lower case
1977 wxString mimeType
= strType
.Lower();
1979 // is this a known MIME type?
1980 int nIndex
= m_aTypes
.Index(mimeType
);
1981 if ( nIndex
== wxNOT_FOUND
)
1984 m_aTypes
.Add(mimeType
);
1985 m_aIcons
.Add(strIcon
);
1986 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
1988 // change nIndex so we can use it below to add the extensions
1989 m_aExtensions
.Add(wxEmptyString
);
1990 nIndex
= m_aExtensions
.size() - 1;
1992 m_aDescriptions
.Add(strDesc
);
1994 else // yes, we already have it
1996 if ( replaceExisting
)
1998 // if new description change it
1999 if ( !strDesc
.empty())
2000 m_aDescriptions
[nIndex
] = strDesc
;
2002 // if new icon change it
2003 if ( !strIcon
.empty())
2004 m_aIcons
[nIndex
] = strIcon
;
2008 delete m_aEntries
[nIndex
];
2009 m_aEntries
[nIndex
] = entry
;
2012 else // add data we don't already have ...
2014 // if new description add only if none
2015 if ( m_aDescriptions
[nIndex
].empty() )
2016 m_aDescriptions
[nIndex
] = strDesc
;
2018 // if new icon and no existing icon
2019 if ( m_aIcons
[nIndex
].empty() )
2020 m_aIcons
[nIndex
] = strIcon
;
2022 // add any new entries...
2025 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
2027 size_t count
= entry
->GetCount();
2028 for ( size_t i
= 0; i
< count
; i
++ )
2030 const wxString
& verb
= entry
->GetVerb(i
);
2031 if ( !entryOld
->HasVerb(verb
) )
2033 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
2037 // as we don't store it anywhere, it won't be deleted later as
2038 // usual -- do it immediately instead
2044 // always add the extensions to this mimetype
2045 wxString
& exts
= m_aExtensions
[nIndex
];
2047 // add all extensions we don't have yet
2049 size_t count
= strExtensions
.GetCount();
2050 for ( size_t i
= 0; i
< count
; i
++ )
2052 ext
= strExtensions
[i
];
2055 if ( exts
.Find(ext
) == wxNOT_FOUND
)
2061 // check data integrity
2062 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2063 m_aTypes
.Count() == m_aExtensions
.Count() &&
2064 m_aTypes
.Count() == m_aIcons
.Count() &&
2065 m_aTypes
.Count() == m_aDescriptions
.Count() );
2070 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
2077 size_t count
= m_aExtensions
.GetCount();
2078 for ( size_t n
= 0; n
< count
; n
++ )
2080 wxStringTokenizer
tk(m_aExtensions
[n
], wxT(' '));
2082 while ( tk
.HasMoreTokens() )
2084 // consider extensions as not being case-sensitive
2085 if ( tk
.GetNextToken().IsSameAs(ext
, false /* no case */) )
2088 wxFileType
*fileType
= new wxFileType
;
2089 fileType
->m_impl
->Init(this, n
);
2099 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
2103 wxFileType
* fileType
= NULL
;
2104 // mime types are not case-sensitive
2105 wxString
mimetype(mimeType
);
2106 mimetype
.MakeLower();
2108 // first look for an exact match
2109 int index
= m_aTypes
.Index(mimetype
);
2110 if ( index
!= wxNOT_FOUND
)
2112 fileType
= new wxFileType
;
2113 fileType
->m_impl
->Init(this, index
);
2116 // then try to find "text/*" as match for "text/plain" (for example)
2117 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
2118 // the whole string - ok.
2120 index
= wxNOT_FOUND
;
2121 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
2123 size_t nCount
= m_aTypes
.Count();
2124 for ( size_t n
= 0; n
< nCount
; n
++ )
2126 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
2127 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") )
2134 if ( index
!= wxNOT_FOUND
)
2136 // don't throw away fileType that was already found
2138 fileType
= new wxFileType
;
2139 fileType
->m_impl
->Init(this, index
);
2145 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
2147 wxString command
, testcmd
, sV
, sTmp
;
2148 sV
= verb
+ wxT("=");
2150 // list of verb = command pairs for this mimetype
2151 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
2154 size_t nCount
= sPairs
->GetCount();
2155 for ( i
= 0; i
< nCount
; i
++ )
2157 sTmp
= sPairs
->GetVerbCmd (i
);
2158 if ( sTmp
.Contains(sV
) )
2159 command
= sTmp
.AfterFirst(wxT('='));
2165 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
2169 wxString extensions
;
2170 const wxArrayString
& exts
= filetype
.GetExtensions();
2171 size_t nExts
= exts
.GetCount();
2172 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ )
2175 extensions
+= wxT(' ');
2177 extensions
+= exts
[nExt
];
2180 AddMimeTypeInfo(filetype
.GetMimeType(),
2182 filetype
.GetDescription());
2184 AddMailcapInfo(filetype
.GetMimeType(),
2185 filetype
.GetOpenCommand(),
2186 filetype
.GetPrintCommand(),
2188 filetype
.GetDescription());
2191 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2192 const wxString
& strExtensions
,
2193 const wxString
& strDesc
)
2195 // reading mailcap may find image/* , while
2196 // reading mime.types finds image/gif and no match is made
2197 // this means all the get functions don't work fix this
2199 wxString sTmp
= strExtensions
;
2201 wxArrayString sExts
;
2202 sTmp
.Trim().Trim(false);
2204 while (!sTmp
.empty())
2206 sExts
.Add(sTmp
.AfterLast(wxT(' ')));
2207 sTmp
= sTmp
.BeforeLast(wxT(' '));
2210 AddToMimeData(strMimeType
, strIcon
, NULL
, sExts
, strDesc
, true);
2213 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2214 const wxString
& strOpenCmd
,
2215 const wxString
& strPrintCmd
,
2216 const wxString
& strTest
,
2217 const wxString
& strDesc
)
2221 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2222 entry
->Add(wxT("open=") + strOpenCmd
);
2223 entry
->Add(wxT("print=") + strPrintCmd
);
2224 entry
->Add(wxT("test=") + strTest
);
2227 wxArrayString strExtensions
;
2229 AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
2232 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2234 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2235 strFileName
.c_str());
2237 wxTextFile
file(strFileName
);
2238 #if defined(__WXGTK20__) && wxUSE_UNICODE
2239 if ( !file
.Open(wxConvUTF8
) )
2245 // the information we extract
2246 wxString strMimeType
, strDesc
, strExtensions
;
2248 size_t nLineCount
= file
.GetLineCount();
2249 const wxChar
*pc
= NULL
;
2250 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2254 // now we're at the start of the line
2255 pc
= file
[nLine
].c_str();
2259 // we didn't finish with the previous line yet
2264 while ( wxIsspace(*pc
) )
2267 // comment or blank line?
2268 if ( *pc
== wxT('#') || !*pc
)
2270 // skip the whole line
2275 // detect file format
2276 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2277 if ( pEqualSign
== NULL
)
2282 // first field is mime type
2283 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ )
2289 while ( wxIsspace(*pc
) )
2292 // take all the rest of the string
2295 // no description...
2303 // the string on the left of '=' is the field name
2304 wxString
strLHS(pc
, pEqualSign
- pc
);
2307 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2311 if ( *pc
== wxT('"') )
2313 // the string is quoted and ends at the matching quote
2314 pEnd
= wxStrchr(++pc
, wxT('"'));
2317 wxLogWarning(wxT("Mime.types file %s, line %lu: unterminated quoted string."),
2318 strFileName
.c_str(), nLine
+ 1L);
2323 // unquoted string ends at the first space or at the end of
2325 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2329 // now we have the RHS (field value)
2330 wxString
strRHS(pc
, pEnd
- pc
);
2332 // check what follows this entry
2333 if ( *pEnd
== wxT('"') )
2339 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2342 // if there is something left, it may be either a '\\' to continue
2343 // the line or the next field of the same entry
2344 bool entryEnded
= *pc
== wxT('\0');
2345 bool nextFieldOnSameLine
= false;
2348 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2351 // now see what we got
2352 if ( strLHS
== wxT("type") )
2354 strMimeType
= strRHS
;
2356 else if ( strLHS
.StartsWith(wxT("desc")) )
2360 else if ( strLHS
== wxT("exts") )
2362 strExtensions
= strRHS
;
2364 else if ( strLHS
== wxT("icon") )
2366 // this one is simply ignored: it usually refers to Netscape
2367 // built in icons which are useless for us anyhow
2369 else if ( !strLHS
.StartsWith(wxT("x-")) )
2371 // we suppose that all fields starting with "X-" are
2372 // unregistered extensions according to the standard practice,
2373 // but it may be worth telling the user about other junk in
2374 // his mime.types file
2375 wxLogWarning(wxT("Unknown field in file %s, line %lu: '%s'."),
2376 strFileName
.c_str(), nLine
+ 1L, strLHS
.c_str());
2381 if ( !nextFieldOnSameLine
)
2383 //else: don't reset it
2385 // as we don't reset strMimeType, the next field in this entry
2386 // will be interpreted correctly.
2392 // depending on the format (Mosaic or Netscape) either space or comma
2393 // is used to separate the extensions
2394 strExtensions
.Replace(wxT(","), wxT(" "));
2396 // also deal with the leading dot
2397 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2399 strExtensions
.erase(0, 1);
2402 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2403 strExtensions
.c_str(),
2404 strMimeType
.c_str(),
2407 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2409 // finished with this line
2416 // ----------------------------------------------------------------------------
2417 // UNIX mailcap files parsing
2418 // ----------------------------------------------------------------------------
2420 // the data for a single MIME type
2421 struct MailcapLineData
2430 wxArrayString verbs
,
2438 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= false; }
2441 // process a non-standard (i.e. not the first or second one) mailcap field
2443 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2444 const wxString
& curField
)
2446 if ( curField
.empty() )
2452 // is this something of the form foo=bar?
2453 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2456 // split "LHS = RHS" in 2
2457 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2458 rhs
= curField
.AfterFirst(wxT('='));
2460 lhs
.Trim(true); // from right
2461 rhs
.Trim(false); // from left
2463 // it might be quoted
2464 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2466 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2469 // is it a command verb or something else?
2470 if ( lhs
== wxT("test") )
2472 if ( wxSystem(rhs
) == 0 )
2475 wxLogTrace(TRACE_MIME_TEST
,
2476 wxT("Test '%s' for mime type '%s' succeeded."),
2477 rhs
.c_str(), data
.type
.c_str());
2481 wxLogTrace(TRACE_MIME_TEST
,
2482 wxT("Test '%s' for mime type '%s' failed, skipping."),
2483 rhs
.c_str(), data
.type
.c_str());
2485 data
.testfailed
= true;
2488 else if ( lhs
== wxT("desc") )
2492 else if ( lhs
== wxT("x11-bitmap") )
2496 else if ( lhs
== wxT("notes") )
2500 else // not a (recognized) special case, must be a verb (e.g. "print")
2502 data
.verbs
.Add(lhs
);
2503 data
.commands
.Add(rhs
);
2506 else // '=' not found
2508 // so it must be a simple flag
2509 if ( curField
== wxT("needsterminal") )
2511 data
.needsterminal
= true;
2513 else if ( curField
== wxT("copiousoutput"))
2515 // copiousoutput impies that the viewer is a console program
2516 data
.needsterminal
=
2517 data
.copiousoutput
= true;
2519 else if ( !IsKnownUnimportantField(curField
) )
2528 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2531 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2532 strFileName
.c_str());
2534 wxTextFile
file(strFileName
);
2535 #if defined(__WXGTK20__) && wxUSE_UNICODE
2536 if ( !file
.Open(wxConvUTF8
) )
2542 // indices of MIME types (in m_aTypes) we already found in this file
2544 // (see the comments near the end of function for the reason we need this)
2545 wxArrayInt aIndicesSeenHere
;
2547 // accumulator for the current field
2549 curField
.reserve(1024);
2551 const wxChar
*pPagerEnv
= wxGetenv(wxT("PAGER"));
2553 const wxArrayString empty_extensions_list
;
2555 size_t nLineCount
= file
.GetLineCount();
2556 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2558 // now we're at the start of the line
2559 const wxChar
*pc
= file
[nLine
].c_str();
2562 while ( wxIsspace(*pc
) )
2565 // comment or empty string?
2566 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2572 // what field are we currently in? The first 2 are fixed and there may
2573 // be an arbitrary number of other fields parsed by
2574 // ProcessOtherMailcapField()
2576 // the first field is the MIME type
2583 currentToken
= Field_Type
;
2585 // the flags and field values on the current line
2586 MailcapLineData data
;
2594 // interpret the next character literally (notice that
2595 // backslash can be used for line continuation)
2596 if ( *++pc
== wxT('\0') )
2598 // fetch the next line if there is one
2599 if ( nLine
== nLineCount
- 1 )
2601 // something is wrong, bail out
2604 wxLogDebug(wxT("Mailcap file %s, line %lu: '\\' on the end of the last line ignored."),
2605 strFileName
.c_str(),
2610 // pass to the beginning of the next line
2611 pc
= file
[++nLine
].c_str();
2613 // skip pc++ at the end of the loop
2619 // just a normal character
2625 cont
= false; // end of line reached, exit the loop
2627 // fall through to still process this field
2630 // trim whitespaces from both sides
2631 curField
.Trim(true).Trim(false);
2633 switch ( currentToken
)
2636 data
.type
= curField
.Lower();
2637 if ( data
.type
.empty() )
2639 // I don't think that this is a valid mailcap
2640 // entry, but try to interpret it somehow
2641 data
.type
= wxT('*');
2644 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2646 // we interpret "type" as "type/*"
2647 data
.type
+= wxT("/*");
2650 currentToken
= Field_OpenCmd
;
2654 data
.cmdOpen
= curField
;
2656 currentToken
= Field_Other
;
2660 if ( !ProcessOtherMailcapField(data
, curField
) )
2662 // don't flood the user with error messages if
2663 // we don't understand something in his
2664 // mailcap, but give them in debug mode because
2665 // this might be useful for the programmer
2668 wxT("Mailcap file %s, line %lu: unknown field '%s' for the MIME type '%s' ignored."),
2669 strFileName
.c_str(),
2675 else if ( data
.testfailed
)
2677 // skip this entry entirely
2681 // it already has this value
2682 //currentToken = Field_Other;
2686 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2689 // next token starts immediately after ';'
2697 // continue in the same line
2701 // we read the entire entry, check what have we got
2702 // ------------------------------------------------
2704 // check that we really read something reasonable
2705 if ( currentToken
< Field_Other
)
2707 wxLogWarning(wxT("Mailcap file %s, line %lu: incomplete entry ignored."),
2708 strFileName
.c_str(), nLine
+ 1L);
2713 // if the test command failed, it's as if the entry were not there at all
2714 if ( data
.testfailed
)
2719 // support for flags:
2720 // 1. create an xterm for 'needsterminal'
2721 // 2. append "| $PAGER" for 'copiousoutput'
2723 // Note that the RFC says that having both needsterminal and
2724 // copiousoutput is probably a mistake, so it seems that running
2725 // programs with copiousoutput inside an xterm as it is done now
2726 // is a bad idea (FIXME)
2727 if ( data
.copiousoutput
)
2729 data
.cmdOpen
<< wxT(" | ") << (pPagerEnv
? pPagerEnv
: wxT("more"));
2732 if ( data
.needsterminal
)
2734 data
.cmdOpen
.Printf(wxT("xterm -e sh -c '%s'"),
2735 data
.cmdOpen
.c_str());
2738 if ( !data
.cmdOpen
.empty() )
2740 data
.verbs
.Insert(wxT("open"), 0);
2741 data
.commands
.Insert(data
.cmdOpen
, 0);
2744 // we have to decide whether the new entry should replace any entries
2745 // for the same MIME type we had previously found or not
2748 // the fall back entries have the lowest priority, by definition
2755 // have we seen this one before?
2756 int nIndex
= m_aTypes
.Index(data
.type
);
2758 // and if we have, was it in this file? if not, we should
2759 // overwrite the previously seen one
2760 overwrite
= nIndex
== wxNOT_FOUND
||
2761 aIndicesSeenHere
.Index(nIndex
) == wxNOT_FOUND
;
2764 wxLogTrace(TRACE_MIME
, wxT("mailcap %s: %s [%s]"),
2765 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2766 overwrite
? wxT("replace") : wxT("add"));
2768 int n
= AddToMimeData
2772 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2773 empty_extensions_list
,
2780 aIndicesSeenHere
.Add(n
);
2787 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2793 size_t count
= m_aTypes
.GetCount();
2794 for ( size_t n
= 0; n
< count
; n
++ )
2796 // don't return template types from here (i.e. anything containg '*')
2797 const wxString
&type
= m_aTypes
[n
];
2798 if ( type
.Find(wxT('*')) == wxNOT_FOUND
)
2800 mimetypes
.Add(type
);
2804 return mimetypes
.GetCount();
2807 // ----------------------------------------------------------------------------
2808 // writing to MIME type files
2809 // ----------------------------------------------------------------------------
2811 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2815 wxArrayString sMimeTypes
;
2816 ft
->GetMimeTypes(sMimeTypes
);
2819 size_t nCount
= sMimeTypes
.GetCount();
2820 for (i
= 0; i
< nCount
; i
++)
2822 const wxString
&sMime
= sMimeTypes
.Item(i
);
2823 int nIndex
= m_aTypes
.Index(sMime
);
2824 if ( nIndex
== wxNOT_FOUND
)
2826 // error if we get here ??
2831 WriteMimeInfo(nIndex
, true);
2832 m_aTypes
.RemoveAt(nIndex
);
2833 m_aEntries
.RemoveAt(nIndex
);
2834 m_aExtensions
.RemoveAt(nIndex
);
2835 m_aDescriptions
.RemoveAt(nIndex
);
2836 m_aIcons
.RemoveAt(nIndex
);
2839 // check data integrity
2840 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2841 m_aTypes
.Count() == m_aExtensions
.Count() &&
2842 m_aTypes
.Count() == m_aIcons
.Count() &&
2843 m_aTypes
.Count() == m_aDescriptions
.Count() );
2848 // ----------------------------------------------------------------------------
2849 // private functions
2850 // ----------------------------------------------------------------------------
2852 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2854 static const wxChar
* const knownFields
[] =
2856 wxT("x-mozilla-flags"),
2857 wxT("nametemplate"),
2858 wxT("textualnewlines"),
2861 wxString field
= fieldAll
.BeforeFirst(wxT('='));
2862 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2864 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2872 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE