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
);
755 if ( !file
.Open(fullname
.GetFullPath()) )
756 if ( !file
.Open(fullname
.GetFullPath(), wxConvISO8859_1
) )
760 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
761 fullname
.GetFullPath().c_str());
763 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
765 wxString mimetype
, mime_desc
, strIcon
;
767 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
768 if (nIndex
== wxNOT_FOUND
)
770 // construct mimetype from the directory name and the basename of the
771 // file (it always has .kdelnk extension)
772 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
775 mimetype
= file
.GetCmd(nIndex
);
777 // first find the description string: it is the value in either "Comment="
778 // line or "Comment[<locale_name>]=" one
779 nIndex
= wxNOT_FOUND
;
784 wxLocale
*locale
= wxGetLocale();
787 // try "Comment[locale name]" first
788 comment
<< wxT("Comment[") + locale
->GetName() + wxT("]=");
789 nIndex
= file
.pIndexOf(comment
);
793 if ( nIndex
== wxNOT_FOUND
)
795 comment
= wxT("Comment=");
796 nIndex
= file
.pIndexOf(comment
);
799 if ( nIndex
!= wxNOT_FOUND
)
800 mime_desc
= file
.GetCmd(nIndex
);
801 //else: no description
803 // next find the extensions
804 wxString mime_extension
;
806 nIndex
= file
.pIndexOf(wxT("Patterns="));
807 if ( nIndex
!= wxNOT_FOUND
)
809 wxString exts
= file
.GetCmd(nIndex
);
811 wxStringTokenizer
tokenizer(exts
, wxT(";"));
812 while ( tokenizer
.HasMoreTokens() )
814 wxString e
= tokenizer
.GetNextToken();
816 // don't support too difficult patterns
817 if ( e
.Left(2) != wxT("*.") )
820 if ( !mime_extension
.empty() )
822 // separate from the previous ext
823 mime_extension
<< wxT(' ');
826 mime_extension
<< e
.Mid(2);
830 sExts
.Add(mime_extension
);
832 // ok, now we can take care of icon:
834 nIndex
= file
.pIndexOf(wxT("Icon="));
835 if ( nIndex
!= wxNOT_FOUND
)
837 strIcon
= file
.GetCmd(nIndex
);
839 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
841 // it could be the real path, but more often a short name
842 if (!wxFileExists(strIcon
))
844 // icon is just the short name
845 if ( !strIcon
.empty() )
847 // we must check if the file exists because it may be stored
848 // in many locations, at least ~/.kde and $KDEDIR
849 size_t nDir
, nDirs
= icondirs
.GetCount();
850 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
852 wxFileName
fnameIcon( strIcon
);
853 wxFileName
fname( icondirs
[nDir
], fnameIcon
.GetName() );
854 fname
.SetExt( wxT("png") );
855 if (fname
.FileExists())
857 strIcon
= fname
.GetFullPath();
858 wxLogTrace(TRACE_MIME
, wxT(" iconfile %s"), strIcon
.c_str());
866 // now look for lines which know about the application
867 // exec= or DefaultApp=
869 nIndex
= file
.pIndexOf(wxT("DefaultApp"));
871 if ( nIndex
== wxNOT_FOUND
)
874 nIndex
= file
.pIndexOf(wxT("Exec"));
877 if ( nIndex
!= wxNOT_FOUND
)
879 // we expect %f; others including %F and %U and %u are possible
880 wxString sTmp
= file
.GetCmd(nIndex
);
881 if (0 == sTmp
.Replace( wxT("%f"), wxT("%s") ))
883 entry
->AddOrReplaceVerb(wxString(wxT("open")), sTmp
);
886 AddToMimeData(mimetype
, strIcon
, entry
, sExts
, mime_desc
);
889 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString
& dirbase
,
890 const wxString
& subdir
,
891 const wxArrayString
& icondirs
)
893 wxFileName
dirname(dirbase
, wxEmptyString
);
894 dirname
.AppendDir(subdir
);
895 wxDir
dir(dirname
.GetPath());
899 wxLogTrace(TRACE_MIME
, wxT("--- Loading from KDE directory %s ---"),
900 dirname
.GetPath().c_str());
903 bool cont
= dir
.GetFirst(&filename
, wxT("*.kdelnk"), wxDIR_FILES
);
905 LoadKDELinksForMimeSubtype(dirname
.GetPath(), subdir
,
907 cont
= dir
.GetNext(&filename
);
910 // new standard for Gnome and KDE
911 cont
= dir
.GetFirst(&filename
, wxT("*.desktop"), wxDIR_FILES
);
913 LoadKDELinksForMimeSubtype(dirname
.GetPath(), subdir
,
915 cont
= dir
.GetNext(&filename
);
919 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString
& dirname
,
920 const wxArrayString
& icondirs
)
922 if(! wxDir::Exists(dirname
))
926 if ( !dir
.IsOpened() )
930 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
933 LoadKDELinksForMimeType(dirname
, subdir
, icondirs
);
935 cont
= dir
.GetNext(&subdir
);
939 // Read a KDE .desktop file of type 'Application'
940 void wxMimeTypesManagerImpl::LoadKDEApp(const wxString
& filename
)
946 if ( !file
.Open(filename
) )
947 if ( !file
.Open(filename
, wxConvISO8859_1
) )
951 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"), filename
.c_str());
953 // Here, only type 'Application' should be considered.
954 int nIndex
= file
.pIndexOf( wxT("Type=") );
955 if (nIndex
!= wxNOT_FOUND
&&
956 file
.GetCmd(nIndex
).Lower() != wxT("application"))
959 // The hidden entry specifies a file to be ignored.
960 nIndex
= file
.pIndexOf( wxT("Hidden=") );
961 if (nIndex
!= wxNOT_FOUND
&& file
.GetCmd(nIndex
).Lower() == wxT("true"))
964 // Semicolon separated list of mime types handled by the application.
965 nIndex
= file
.pIndexOf( wxT("MimeType=") );
966 if (nIndex
== wxNOT_FOUND
)
968 wxString mimetypes
= file
.GetCmd (nIndex
);
970 // Name of the application
972 nIndex
= wxNOT_FOUND
;
973 #if wxUSE_INTL // try "Name[locale name]" first
974 wxLocale
*locale
= wxGetLocale();
976 nIndex
= file
.pIndexOf(_T("Name[")+locale
->GetName()+_T("]="));
978 if(nIndex
== wxNOT_FOUND
)
979 nIndex
= file
.pIndexOf( wxT("Name=") );
980 if(nIndex
!= wxNOT_FOUND
)
981 nameapp
= file
.GetCmd(nIndex
);
983 // Icon of the application.
984 wxString nameicon
, namemini
;
985 nIndex
= wxNOT_FOUND
;
986 #if wxUSE_INTL // try "Icon[locale name]" first
988 nIndex
= file
.pIndexOf(_T("Icon[")+locale
->GetName()+_T("]="));
990 if(nIndex
== wxNOT_FOUND
)
991 nIndex
= file
.pIndexOf( wxT("Icon=") );
992 if(nIndex
!= wxNOT_FOUND
) {
993 nameicon
= wxString(wxT("--icon ")) + file
.GetCmd(nIndex
);
994 namemini
= wxString(wxT("--miniicon ")) + file
.GetCmd(nIndex
);
997 // Replace some of the field code in the 'Exec' entry.
998 // TODO: deal with %d, %D, %n, %N, %k and %v (but last one is deprecated)
999 nIndex
= file
.pIndexOf( wxT("Exec=") );
1000 if (nIndex
== wxNOT_FOUND
)
1002 wxString sCmd
= file
.GetCmd(nIndex
);
1003 // we expect %f; others including %F and %U and %u are possible
1004 sCmd
.Replace(wxT("%F"), wxT("%f"));
1005 sCmd
.Replace(wxT("%U"), wxT("%f"));
1006 sCmd
.Replace(wxT("%u"), wxT("%f"));
1007 if (0 == sCmd
.Replace ( wxT("%f"), wxT("%s") ))
1008 sCmd
= sCmd
+ wxT(" %s");
1009 sCmd
.Replace(wxT("%c"), nameapp
);
1010 sCmd
.Replace(wxT("%i"), nameicon
);
1011 sCmd
.Replace(wxT("%m"), namemini
);
1013 wxStringTokenizer
tokenizer(mimetypes
, _T(";"));
1014 while(tokenizer
.HasMoreTokens()) {
1015 wxString mimetype
= tokenizer
.GetNextToken().Lower();
1016 int nIndex
= m_aTypes
.Index(mimetype
);
1017 if(nIndex
!= wxNOT_FOUND
) { // is this a known MIME type?
1018 wxMimeTypeCommands
* entry
= m_aEntries
[nIndex
];
1019 entry
->AddOrReplaceVerb(wxT("open"), sCmd
);
1024 void wxMimeTypesManagerImpl::LoadKDEAppsFilesFromDir(const wxString
& dirname
)
1026 if(! wxDir::Exists(dirname
))
1029 if ( !dir
.IsOpened() )
1033 // Look into .desktop files
1034 bool cont
= dir
.GetFirst(&filename
, _T("*.desktop"), wxDIR_FILES
);
1036 wxFileName
p(dirname
, filename
);
1037 LoadKDEApp( p
.GetFullPath() );
1038 cont
= dir
.GetNext(&filename
);
1040 // Look recursively into subdirs
1041 cont
= dir
.GetFirst(&filename
, wxEmptyString
, wxDIR_DIRS
);
1043 wxFileName
p(dirname
, wxEmptyString
);
1044 p
.AppendDir(filename
);
1045 LoadKDEAppsFilesFromDir( p
.GetPath() );
1046 cont
= dir
.GetNext(&filename
);
1050 // Return base KDE directories.
1051 // 1) Environment variable $KDEHOME, or "~/.kde" if not set.
1052 // 2) List of directories in colon separated environment variable $KDEDIRS.
1053 // 3) Environment variable $KDEDIR in case $KDEDIRS is not set.
1054 // Notice at least the local kde directory is added to the list. If it is the
1055 // only one, use later the application 'kde-config' to get additional paths.
1056 static void GetKDEBaseDirs(wxArrayString
& basedirs
)
1058 wxString env
= wxGetenv( wxT("KDEHOME") );
1060 env
= wxGetHomeDir() + wxT("/.kde");
1063 env
= wxGetenv( wxT("KDEDIRS") );
1065 env
= wxGetenv( wxT("KDEDIR") );
1069 wxStringTokenizer
tokenizer(env
, wxT(":"));
1070 while(tokenizer
.HasMoreTokens())
1071 basedirs
.Add( tokenizer
.GetNextToken() );
1075 static wxString
ReadPathFromKDEConfig(const wxString
& request
)
1078 wxArrayString output
;
1079 if(wxExecute(wxT("kde-config --path ")+request
, output
) == 0 &&
1081 str
= output
.Item(0);
1085 // Try to find the "Theme" entry in the configuration file, provided it exists.
1086 static wxString
GetKDEThemeInFile(const wxFileName
& filename
)
1090 if(filename
.FileExists() && config
.Open( filename
.GetFullPath() )) {
1091 size_t cnt
= config
.GetLineCount();
1092 for(size_t i
= 0; i
< cnt
; i
++)
1093 if(config
[i
].StartsWith(wxT("Theme="), &theme
))
1099 // Try to find a file "kdeglobals" in one of the directories and read the
1100 // "Theme" entry there.
1101 static wxString
GetKDETheme(const wxArrayString
& basedirs
)
1104 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1105 wxFileName
filename(basedirs
.Item(i
), wxEmptyString
);
1106 filename
.AppendDir( wxT("share") );
1107 filename
.AppendDir( wxT("config") );
1108 filename
.SetName( wxT("kdeglobals") );
1109 theme
= GetKDEThemeInFile(filename
);
1110 if(! theme
.IsEmpty())
1113 // If $KDEDIRS and $KDEDIR were set, we try nothing more. Otherwise, we
1114 // try to get the configuration file with 'kde-config'.
1115 if(basedirs
.Count() > 1)
1117 wxString paths
= ReadPathFromKDEConfig(wxT("config"));
1118 if(! paths
.IsEmpty()) {
1119 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1120 while( tokenizer
.HasMoreTokens() ) {
1121 wxFileName
filename(tokenizer
.GetNextToken(), wxT("kdeglobals"));
1122 theme
= GetKDEThemeInFile(filename
);
1123 if(! theme
.IsEmpty())
1130 // Get list of directories of icons.
1131 static void GetKDEIconDirs(const wxArrayString
& basedirs
,
1132 wxArrayString
& icondirs
)
1134 wxString theme
= GetKDETheme(basedirs
);
1136 theme
= wxT("default.kde");
1138 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1139 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1140 dirname
.AppendDir( wxT("share") );
1141 dirname
.AppendDir( wxT("icons") );
1142 dirname
.AppendDir(theme
);
1143 dirname
.AppendDir( wxT("32x32") );
1144 dirname
.AppendDir( wxT("mimetypes") );
1145 if( wxDir::Exists( dirname
.GetPath() ) )
1146 icondirs
.Add( dirname
.GetPath() );
1149 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1150 if(basedirs
.Count() > 1)
1152 wxString paths
= ReadPathFromKDEConfig(wxT("icon"));
1153 if(! paths
.IsEmpty()) {
1154 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1155 while( tokenizer
.HasMoreTokens() ) {
1156 wxFileName
dirname(tokenizer
.GetNextToken(), wxEmptyString
);
1157 dirname
.AppendDir(theme
);
1158 dirname
.AppendDir( wxT("32x32") );
1159 dirname
.AppendDir( wxT("mimetypes") );
1160 if(icondirs
.Index(dirname
.GetPath()) == wxNOT_FOUND
&&
1161 wxDir::Exists( dirname
.GetPath() ) )
1162 icondirs
.Add( dirname
.GetPath() );
1167 // Get list of directories of mime types.
1168 static void GetKDEMimeDirs(const wxArrayString
& basedirs
,
1169 wxArrayString
& mimedirs
)
1171 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1172 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1173 dirname
.AppendDir( wxT("share") );
1174 dirname
.AppendDir( wxT("mimelnk") );
1175 if( wxDir::Exists( dirname
.GetPath() ) )
1176 mimedirs
.Add( dirname
.GetPath() );
1179 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1180 if(basedirs
.Count() > 1)
1182 wxString paths
= ReadPathFromKDEConfig(wxT("mime"));
1183 if(! paths
.IsEmpty()) {
1184 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1185 while( tokenizer
.HasMoreTokens() ) {
1186 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1187 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1188 if(mimedirs
.Index(dirname
) == wxNOT_FOUND
&&
1189 wxDir::Exists(dirname
) )
1190 mimedirs
.Add(dirname
);
1195 // Get list of directories of application desktop files.
1196 static void GetKDEAppsDirs(const wxArrayString
& basedirs
,
1197 wxArrayString
& appsdirs
)
1199 for(size_t i
= 0; i
< basedirs
.Count(); i
++) {
1200 wxFileName
dirname(basedirs
.Item(i
), wxEmptyString
);
1201 dirname
.AppendDir( wxT("share") );
1202 dirname
.AppendDir( wxT("applnk") );
1203 if( wxDir::Exists( dirname
.GetPath() ) )
1204 appsdirs
.Add( dirname
.GetPath() );
1207 // If $KDEDIRS and $KDEDIR were not set, use 'kde-config'
1208 if(basedirs
.Count() > 1)
1210 wxString paths
= ReadPathFromKDEConfig(wxT("apps"));
1211 if(! paths
.IsEmpty()) {
1212 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1213 while( tokenizer
.HasMoreTokens() ) {
1214 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1215 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1216 if(appsdirs
.Index(dirname
) == wxNOT_FOUND
&&
1217 wxDir::Exists(dirname
) )
1218 appsdirs
.Add(dirname
);
1221 paths
= ReadPathFromKDEConfig(wxT("xdgdata-apps"));
1222 if(! paths
.IsEmpty()) {
1223 wxStringTokenizer
tokenizer(paths
, wxT(":"));
1224 while( tokenizer
.HasMoreTokens() ) {
1225 wxFileName
p(tokenizer
.GetNextToken(), wxEmptyString
);
1226 wxString dirname
= p
.GetPath(); // To remove possible trailing '/'
1227 if(appsdirs
.Index(dirname
) == wxNOT_FOUND
&&
1228 wxDir::Exists(dirname
) )
1229 appsdirs
.Add(dirname
);
1234 // Fill database with all mime types.
1235 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString
& sExtraDir
)
1237 wxArrayString basedirs
;
1238 GetKDEBaseDirs(basedirs
);
1240 wxArrayString icondirs
;
1241 GetKDEIconDirs(basedirs
, icondirs
);
1242 wxArrayString mimedirs
;
1243 GetKDEMimeDirs(basedirs
, mimedirs
);
1244 wxArrayString appsdirs
;
1245 GetKDEAppsDirs(basedirs
, appsdirs
);
1247 if(! sExtraDir
.IsEmpty()) {
1248 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1249 mimedirs
.Add(sExtraDir
+ wxT("/mimelnk"));
1250 appsdirs
.Add(sExtraDir
+ wxT("/applnk"));
1254 size_t nDirs
= mimedirs
.GetCount(), nDir
;
1255 for(nDir
= 0; nDir
< nDirs
; nDir
++)
1256 LoadKDELinkFilesFromDir(mimedirs
[nDir
], icondirs
);
1258 // Load application files and associate them to corresponding mime types.
1259 nDirs
= appsdirs
.GetCount();
1260 for(nDir
= 0; nDir
< nDirs
; nDir
++)
1261 LoadKDEAppsFilesFromDir(appsdirs
[nDir
]);
1264 // ----------------------------------------------------------------------------
1265 // wxFileTypeImpl (Unix)
1266 // ----------------------------------------------------------------------------
1268 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1272 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1274 sTmp
= m_manager
->GetCommand( verb
, m_index
[i
] );
1278 return wxFileType::ExpandCommand(sTmp
, params
);
1281 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
1285 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1287 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1296 iconLoc
->SetFileName(sTmp
);
1302 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1305 size_t nCount
= m_index
.GetCount();
1306 for (size_t i
= 0; i
< nCount
; i
++)
1307 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1312 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1313 wxArrayString
*commands
,
1314 const wxFileType::MessageParameters
& params
) const
1316 wxString vrb
, cmd
, sTmp
;
1318 wxMimeTypeCommands
* sPairs
;
1320 // verbs and commands have been cleared already in mimecmn.cpp...
1321 // if we find no entries in the exact match, try the inexact match
1322 for (size_t n
= 0; ((count
== 0) && (n
< m_index
.GetCount())); n
++)
1324 // list of verb = command pairs for this mimetype
1325 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1327 for ( i
= 0; i
< sPairs
->GetCount(); i
++ )
1329 vrb
= sPairs
->GetVerb(i
);
1330 // some gnome entries have "." inside
1331 vrb
= vrb
.AfterLast(wxT('.'));
1332 cmd
= sPairs
->GetCmd(i
);
1335 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1337 if ( vrb
.IsSameAs(wxT("open")))
1340 verbs
->Insert(vrb
, 0u);
1342 commands
->Insert(cmd
, 0u);
1358 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1360 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1363 // one extension in the space or comma-delimited list
1365 for ( const wxChar
*p
= strExtensions
; /* nothing */; p
++ )
1367 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') )
1369 if ( !strExt
.empty() )
1371 extensions
.Add(strExt
);
1374 //else: repeated spaces
1375 // (shouldn't happen, but it's not that important if it does happen)
1377 if ( *p
== wxT('\0') )
1380 else if ( *p
== wxT('.') )
1382 // remove the dot from extension (but only if it's the first char)
1383 if ( !strExt
.empty() )
1387 //else: no, don't append it
1398 // set an arbitrary command:
1399 // could adjust the code to ask confirmation if it already exists and
1400 // overwriteprompt is true, but this is currently ignored as *Associate* has
1401 // no overwrite prompt
1403 wxFileTypeImpl::SetCommand(const wxString
& cmd
,
1404 const wxString
& verb
,
1405 bool WXUNUSED(overwriteprompt
))
1407 wxArrayString strExtensions
;
1408 wxString strDesc
, strIcon
;
1410 wxArrayString strTypes
;
1411 GetMimeTypes(strTypes
);
1412 if ( strTypes
.IsEmpty() )
1415 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1416 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1419 size_t nCount
= strTypes
.GetCount();
1420 for ( size_t i
= 0; i
< nCount
; i
++ )
1422 if (!m_manager
->DoAssociation(strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1429 // ignore index on the grounds that we only have one icon in a Unix file
1430 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
, int WXUNUSED(index
))
1432 if (strIcon
.empty())
1435 wxArrayString strExtensions
;
1438 wxArrayString strTypes
;
1439 GetMimeTypes(strTypes
);
1440 if ( strTypes
.IsEmpty() )
1443 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1445 size_t nCount
= strTypes
.GetCount();
1446 for ( size_t i
= 0; i
< nCount
; i
++ )
1448 if ( !m_manager
->DoAssociation
1464 // ----------------------------------------------------------------------------
1465 // wxMimeTypesManagerImpl (Unix)
1466 // ----------------------------------------------------------------------------
1468 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1470 m_initialized
= false;
1471 m_mailcapStylesInited
= 0;
1474 void wxMimeTypesManagerImpl::InitIfNeeded()
1476 if ( !m_initialized
)
1478 // set the flag first to prevent recursion
1479 m_initialized
= true;
1481 wxString wm
= wxTheApp
->GetTraits()->GetDesktopEnvironment();
1483 if (wm
== wxT("KDE"))
1484 Initialize( wxMAILCAP_KDE
);
1485 else if (wm
== wxT("GNOME"))
1486 Initialize( wxMAILCAP_GNOME
);
1492 // read system and user mailcaps and other files
1493 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1494 const wxString
& sExtraDir
)
1496 // read mimecap amd mime.types
1497 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1498 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1499 GetMimeInfo(sExtraDir
);
1501 // read GNOME tables
1502 if (mailcapStyles
& wxMAILCAP_GNOME
)
1503 GetGnomeMimeInfo(sExtraDir
);
1506 if (mailcapStyles
& wxMAILCAP_KDE
)
1507 GetKDEMimeInfo(sExtraDir
);
1509 m_mailcapStylesInited
|= mailcapStyles
;
1512 // clear data so you can read another group of WM files
1513 void wxMimeTypesManagerImpl::ClearData()
1517 m_aExtensions
.Clear();
1518 m_aDescriptions
.Clear();
1520 WX_CLEAR_ARRAY(m_aEntries
);
1523 m_mailcapStylesInited
= 0;
1526 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1531 void wxMimeTypesManagerImpl::GetMimeInfo(const wxString
& sExtraDir
)
1533 // read this for netscape or Metamail formats
1535 // directories where we look for mailcap and mime.types by default
1536 // used by netscape and pine and other mailers, using 2 different formats!
1538 // (taken from metamail(1) sources)
1540 // although RFC 1524 specifies the search path of
1541 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1542 // places - OTOH, the RFC also says that this path can be changed with
1543 // MAILCAPS environment variable (containing the colon separated full
1544 // filenames to try) which is not done yet (TODO?)
1546 wxString strHome
= wxGetenv(wxT("HOME"));
1549 dirs
.Add( strHome
+ wxT("/.") );
1550 dirs
.Add( wxT("/etc/") );
1551 dirs
.Add( wxT("/usr/etc/") );
1552 dirs
.Add( wxT("/usr/local/etc/") );
1553 dirs
.Add( wxT("/etc/mail/") );
1554 dirs
.Add( wxT("/usr/public/lib/") );
1555 if (!sExtraDir
.empty())
1556 dirs
.Add( sExtraDir
+ wxT("/") );
1559 size_t nDirs
= dirs
.GetCount();
1560 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1563 file
+= wxT("mailcap");
1564 if ( wxFile::Exists(file
) )
1570 file
+= wxT("mime.types");
1571 if ( wxFile::Exists(file
) )
1572 ReadMimeTypes(file
);
1576 bool wxMimeTypesManagerImpl::WriteToMimeTypes(int index
, bool delete_index
)
1578 // check we have the right manager
1579 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1583 wxString strHome
= wxGetenv(wxT("HOME"));
1585 // and now the users mailcap
1586 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1588 wxMimeTextFile file
;
1589 if ( wxFile::Exists(strUserMailcap
) )
1591 bTemp
= file
.Open(strUserMailcap
);
1598 bTemp
= file
.Create(strUserMailcap
);
1604 // test for netscape's header and return false if its found
1605 nIndex
= file
.pIndexOf(wxT("#--Netscape"));
1606 if (nIndex
!= wxNOT_FOUND
)
1608 wxFAIL_MSG(wxT("Error in .mime.types\nTrying to mix Netscape and Metamail formats\nFile not modified"));
1612 // write it in alternative format
1613 // get rid of unwanted entries
1614 wxString strType
= m_aTypes
[index
];
1615 nIndex
= file
.pIndexOf(strType
);
1617 // get rid of all the unwanted entries...
1618 if (nIndex
!= wxNOT_FOUND
)
1619 file
.CommentLine(nIndex
);
1623 // add the new entries in
1624 wxString sTmp
= strType
.Append( wxT(' '), 40 - strType
.Len() );
1625 sTmp
+= m_aExtensions
[index
];
1629 bTemp
= file
.Write();
1636 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes(int index
, bool delete_index
)
1638 //check we have the right managers
1639 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1643 wxString strHome
= wxGetenv(wxT("HOME"));
1645 // and now the users mailcap
1646 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1648 wxMimeTextFile file
;
1649 if ( wxFile::Exists(strUserMailcap
) )
1651 bTemp
= file
.Open(strUserMailcap
);
1658 bTemp
= file
.Create(strUserMailcap
);
1663 // write it in the format that Netscape uses
1665 // test for netscape's header and insert if required...
1666 // this is a comment so use true
1667 nIndex
= file
.pIndexOf(wxT("#--Netscape"), true);
1668 if (nIndex
== wxNOT_FOUND
)
1670 // either empty file or metamail format
1671 // at present we can't cope with mixed formats, so exit to preseve
1672 // metamail entreies
1673 if (file
.GetLineCount() > 0)
1675 wxFAIL_MSG(wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1679 file
.InsertLine(wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1683 wxString strType
= wxT("type=") + m_aTypes
[index
];
1684 nIndex
= file
.pIndexOf(strType
);
1686 // get rid of all the unwanted entries...
1687 if (nIndex
!= wxNOT_FOUND
)
1689 wxString sOld
= file
[nIndex
];
1690 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1692 file
.CommentLine(nIndex
);
1693 sOld
= file
[nIndex
];
1695 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1700 if (nIndex
< (int) file
.GetLineCount())
1701 file
.CommentLine(nIndex
);
1704 nIndex
= (int) file
.GetLineCount();
1706 wxString sTmp
= strType
+ wxT(" \\");
1708 file
.InsertLine(sTmp
, nIndex
);
1710 if ( ! m_aDescriptions
.Item(index
).empty() )
1712 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1716 file
.InsertLine(sTmp
, nIndex
);
1720 wxString sExts
= m_aExtensions
.Item(index
);
1721 sTmp
= wxT("exts=\"") + sExts
.Trim(false).Trim() + wxT("\"");
1725 file
.InsertLine(sTmp
, nIndex
);
1728 bTemp
= file
.Write();
1735 bool wxMimeTypesManagerImpl::WriteToMailCap(int index
, bool delete_index
)
1737 //check we have the right managers
1738 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1739 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1743 wxString strHome
= wxGetenv(wxT("HOME"));
1745 // and now the users mailcap
1746 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1748 wxMimeTextFile file
;
1749 if ( wxFile::Exists(strUserMailcap
) )
1751 bTemp
= file
.Open(strUserMailcap
);
1758 bTemp
= file
.Create(strUserMailcap
);
1763 // now got a file we can write to ....
1764 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1766 wxString sCmd
= entries
->GetCommandForVerb(wxT("open"), &iOpen
);
1769 sTmp
= m_aTypes
[index
];
1771 int nIndex
= file
.pIndexOf(sTmp
);
1773 // get rid of all the unwanted entries...
1774 if (nIndex
== wxNOT_FOUND
)
1776 nIndex
= (int) file
.GetLineCount();
1780 sOld
= file
[nIndex
];
1781 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1783 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1785 file
.CommentLine(nIndex
);
1786 if (nIndex
< (int) file
.GetLineCount())
1787 sOld
= sOld
+ file
[nIndex
];
1791 file
.GetLineCount()) file
.CommentLine(nIndex
);
1794 sTmp
+= wxT(";") + sCmd
; //includes wxT(" %s ");
1796 // write it in the format that Netscape uses (default)
1797 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1800 file
.InsertLine(sTmp
, nIndex
);
1805 // write extended format
1807 // TODO - FIX this code:
1809 // sOld holds all the entries, but our data store only has some
1810 // eg test= is not stored
1812 // so far we have written the mimetype and command out
1813 wxStringTokenizer
sT(sOld
, wxT(";\\"));
1814 if (sT
.CountTokens() > 2)
1816 // first one mimetype; second one command, rest unknown...
1818 s
= sT
.GetNextToken();
1819 s
= sT
.GetNextToken();
1822 s
= sT
.GetNextToken();
1823 while ( ! s
.empty() )
1825 bool bKnownToken
= false;
1826 if (s
.Contains(wxT("description=")))
1828 if (s
.Contains(wxT("x11-bitmap=")))
1832 size_t nCount
= entries
->GetCount();
1833 for (i
=0; i
< nCount
; i
++)
1835 if (s
.Contains(entries
->GetVerb(i
)))
1841 sTmp
+= wxT("; \\");
1842 file
.InsertLine(sTmp
, nIndex
);
1846 s
= sT
.GetNextToken();
1850 if (! m_aDescriptions
[index
].empty() )
1852 sTmp
+= wxT("; \\");
1853 file
.InsertLine(sTmp
, nIndex
);
1855 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1858 if (! m_aIcons
[index
].empty() )
1860 sTmp
+= wxT("; \\");
1861 file
.InsertLine(sTmp
, nIndex
);
1863 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1866 if ( entries
->GetCount() > 1 )
1869 for (i
=0; i
< entries
->GetCount(); i
++)
1872 sTmp
+= wxT("; \\");
1873 file
.InsertLine(sTmp
, nIndex
);
1875 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1879 file
.InsertLine(sTmp
, nIndex
);
1883 bTemp
= file
.Write();
1890 wxFileType
* wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1894 wxString strType
= ftInfo
.GetMimeType();
1895 wxString strDesc
= ftInfo
.GetDescription();
1896 wxString strIcon
= ftInfo
.GetIconFile();
1898 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1900 if ( ! ftInfo
.GetOpenCommand().empty())
1901 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand() + wxT(" %s "));
1902 if ( ! ftInfo
.GetPrintCommand().empty())
1903 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand() + wxT(" %s "));
1905 // now find where these extensions are in the data store and remove them
1906 wxArrayString sA_Exts
= ftInfo
.GetExtensions();
1907 wxString sExt
, sExtStore
;
1909 size_t nExtCount
= sA_Exts
.GetCount();
1910 for (i
=0; i
< nExtCount
; i
++)
1912 sExt
= sA_Exts
.Item(i
);
1914 // clean up to just a space before and after
1915 sExt
.Trim().Trim(false);
1916 sExt
= wxT(' ') + sExt
+ wxT(' ');
1917 size_t nCount
= m_aExtensions
.GetCount();
1918 for (nIndex
= 0; nIndex
< nCount
; nIndex
++)
1920 sExtStore
= m_aExtensions
.Item(nIndex
);
1921 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0)
1922 m_aExtensions
.Item(nIndex
) = sExtStore
;
1926 if ( !DoAssociation(strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1929 return GetFileTypeFromMimeType(strType
);
1932 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1933 const wxString
& strIcon
,
1934 wxMimeTypeCommands
*entry
,
1935 const wxArrayString
& strExtensions
,
1936 const wxString
& strDesc
)
1938 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
1940 if ( nIndex
== wxNOT_FOUND
)
1943 return WriteMimeInfo(nIndex
, false);
1946 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
1950 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
1952 // write in metamail format;
1953 if (WriteToMimeTypes(nIndex
, delete_mime
) )
1954 if ( WriteToMailCap(nIndex
, delete_mime
) )
1958 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
1960 // write in netsacpe format;
1961 if (WriteToNSMimeTypes(nIndex
, delete_mime
) )
1962 if ( WriteToMailCap(nIndex
, delete_mime
) )
1966 // Don't write GNOME files here as this is not
1967 // allowed and simply doesn't work
1969 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
1971 // write in KDE format;
1972 if (WriteKDEMimeFile(nIndex
, delete_mime
) )
1979 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
1980 const wxString
& strIcon
,
1981 wxMimeTypeCommands
*entry
,
1982 const wxArrayString
& strExtensions
,
1983 const wxString
& strDesc
,
1984 bool replaceExisting
)
1988 // ensure mimetype is always lower case
1989 wxString mimeType
= strType
.Lower();
1991 // is this a known MIME type?
1992 int nIndex
= m_aTypes
.Index(mimeType
);
1993 if ( nIndex
== wxNOT_FOUND
)
1996 m_aTypes
.Add(mimeType
);
1997 m_aIcons
.Add(strIcon
);
1998 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
2000 // change nIndex so we can use it below to add the extensions
2001 m_aExtensions
.Add(wxEmptyString
);
2002 nIndex
= m_aExtensions
.size() - 1;
2004 m_aDescriptions
.Add(strDesc
);
2006 else // yes, we already have it
2008 if ( replaceExisting
)
2010 // if new description change it
2011 if ( !strDesc
.empty())
2012 m_aDescriptions
[nIndex
] = strDesc
;
2014 // if new icon change it
2015 if ( !strIcon
.empty())
2016 m_aIcons
[nIndex
] = strIcon
;
2020 delete m_aEntries
[nIndex
];
2021 m_aEntries
[nIndex
] = entry
;
2024 else // add data we don't already have ...
2026 // if new description add only if none
2027 if ( m_aDescriptions
[nIndex
].empty() )
2028 m_aDescriptions
[nIndex
] = strDesc
;
2030 // if new icon and no existing icon
2031 if ( m_aIcons
[nIndex
].empty() )
2032 m_aIcons
[nIndex
] = strIcon
;
2034 // add any new entries...
2037 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
2039 size_t count
= entry
->GetCount();
2040 for ( size_t i
= 0; i
< count
; i
++ )
2042 const wxString
& verb
= entry
->GetVerb(i
);
2043 if ( !entryOld
->HasVerb(verb
) )
2045 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
2049 // as we don't store it anywhere, it won't be deleted later as
2050 // usual -- do it immediately instead
2056 // always add the extensions to this mimetype
2057 wxString
& exts
= m_aExtensions
[nIndex
];
2059 // add all extensions we don't have yet
2061 size_t count
= strExtensions
.GetCount();
2062 for ( size_t i
= 0; i
< count
; i
++ )
2064 ext
= strExtensions
[i
];
2067 if ( exts
.Find(ext
) == wxNOT_FOUND
)
2073 // check data integrity
2074 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2075 m_aTypes
.Count() == m_aExtensions
.Count() &&
2076 m_aTypes
.Count() == m_aIcons
.Count() &&
2077 m_aTypes
.Count() == m_aDescriptions
.Count() );
2082 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
2089 size_t count
= m_aExtensions
.GetCount();
2090 for ( size_t n
= 0; n
< count
; n
++ )
2092 wxStringTokenizer
tk(m_aExtensions
[n
], wxT(' '));
2094 while ( tk
.HasMoreTokens() )
2096 // consider extensions as not being case-sensitive
2097 if ( tk
.GetNextToken().IsSameAs(ext
, false /* no case */) )
2100 wxFileType
*fileType
= new wxFileType
;
2101 fileType
->m_impl
->Init(this, n
);
2111 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
2115 wxFileType
* fileType
= NULL
;
2116 // mime types are not case-sensitive
2117 wxString
mimetype(mimeType
);
2118 mimetype
.MakeLower();
2120 // first look for an exact match
2121 int index
= m_aTypes
.Index(mimetype
);
2122 if ( index
!= wxNOT_FOUND
)
2124 fileType
= new wxFileType
;
2125 fileType
->m_impl
->Init(this, index
);
2128 // then try to find "text/*" as match for "text/plain" (for example)
2129 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
2130 // the whole string - ok.
2132 index
= wxNOT_FOUND
;
2133 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
2135 size_t nCount
= m_aTypes
.Count();
2136 for ( size_t n
= 0; n
< nCount
; n
++ )
2138 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
2139 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") )
2146 if ( index
!= wxNOT_FOUND
)
2148 // don't throw away fileType that was already found
2150 fileType
= new wxFileType
;
2151 fileType
->m_impl
->Init(this, index
);
2157 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
2159 wxString command
, testcmd
, sV
, sTmp
;
2160 sV
= verb
+ wxT("=");
2162 // list of verb = command pairs for this mimetype
2163 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
2166 size_t nCount
= sPairs
->GetCount();
2167 for ( i
= 0; i
< nCount
; i
++ )
2169 sTmp
= sPairs
->GetVerbCmd (i
);
2170 if ( sTmp
.Contains(sV
) )
2171 command
= sTmp
.AfterFirst(wxT('='));
2177 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
2181 wxString extensions
;
2182 const wxArrayString
& exts
= filetype
.GetExtensions();
2183 size_t nExts
= exts
.GetCount();
2184 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ )
2187 extensions
+= wxT(' ');
2189 extensions
+= exts
[nExt
];
2192 AddMimeTypeInfo(filetype
.GetMimeType(),
2194 filetype
.GetDescription());
2196 AddMailcapInfo(filetype
.GetMimeType(),
2197 filetype
.GetOpenCommand(),
2198 filetype
.GetPrintCommand(),
2200 filetype
.GetDescription());
2203 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2204 const wxString
& strExtensions
,
2205 const wxString
& strDesc
)
2207 // reading mailcap may find image/* , while
2208 // reading mime.types finds image/gif and no match is made
2209 // this means all the get functions don't work fix this
2211 wxString sTmp
= strExtensions
;
2213 wxArrayString sExts
;
2214 sTmp
.Trim().Trim(false);
2216 while (!sTmp
.empty())
2218 sExts
.Add(sTmp
.AfterLast(wxT(' ')));
2219 sTmp
= sTmp
.BeforeLast(wxT(' '));
2222 AddToMimeData(strMimeType
, strIcon
, NULL
, sExts
, strDesc
, true);
2225 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2226 const wxString
& strOpenCmd
,
2227 const wxString
& strPrintCmd
,
2228 const wxString
& strTest
,
2229 const wxString
& strDesc
)
2233 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2234 entry
->Add(wxT("open=") + strOpenCmd
);
2235 entry
->Add(wxT("print=") + strPrintCmd
);
2236 entry
->Add(wxT("test=") + strTest
);
2239 wxArrayString strExtensions
;
2241 AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
2244 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2246 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2247 strFileName
.c_str());
2249 wxTextFile
file(strFileName
);
2250 #if defined(__WXGTK20__) && wxUSE_UNICODE
2251 if ( !file
.Open(wxConvUTF8
) )
2257 // the information we extract
2258 wxString strMimeType
, strDesc
, strExtensions
;
2260 size_t nLineCount
= file
.GetLineCount();
2261 const wxChar
*pc
= NULL
;
2262 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2266 // now we're at the start of the line
2267 pc
= file
[nLine
].c_str();
2271 // we didn't finish with the previous line yet
2276 while ( wxIsspace(*pc
) )
2279 // comment or blank line?
2280 if ( *pc
== wxT('#') || !*pc
)
2282 // skip the whole line
2287 // detect file format
2288 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2289 if ( pEqualSign
== NULL
)
2294 // first field is mime type
2295 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ )
2301 while ( wxIsspace(*pc
) )
2304 // take all the rest of the string
2307 // no description...
2315 // the string on the left of '=' is the field name
2316 wxString
strLHS(pc
, pEqualSign
- pc
);
2319 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2323 if ( *pc
== wxT('"') )
2325 // the string is quoted and ends at the matching quote
2326 pEnd
= wxStrchr(++pc
, wxT('"'));
2329 wxLogWarning(wxT("Mime.types file %s, line %lu: unterminated quoted string."),
2330 strFileName
.c_str(), nLine
+ 1L);
2335 // unquoted string ends at the first space or at the end of
2337 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2341 // now we have the RHS (field value)
2342 wxString
strRHS(pc
, pEnd
- pc
);
2344 // check what follows this entry
2345 if ( *pEnd
== wxT('"') )
2351 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2354 // if there is something left, it may be either a '\\' to continue
2355 // the line or the next field of the same entry
2356 bool entryEnded
= *pc
== wxT('\0');
2357 bool nextFieldOnSameLine
= false;
2360 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2363 // now see what we got
2364 if ( strLHS
== wxT("type") )
2366 strMimeType
= strRHS
;
2368 else if ( strLHS
.StartsWith(wxT("desc")) )
2372 else if ( strLHS
== wxT("exts") )
2374 strExtensions
= strRHS
;
2376 else if ( strLHS
== wxT("icon") )
2378 // this one is simply ignored: it usually refers to Netscape
2379 // built in icons which are useless for us anyhow
2381 else if ( !strLHS
.StartsWith(wxT("x-")) )
2383 // we suppose that all fields starting with "X-" are
2384 // unregistered extensions according to the standard practice,
2385 // but it may be worth telling the user about other junk in
2386 // his mime.types file
2387 wxLogWarning(wxT("Unknown field in file %s, line %lu: '%s'."),
2388 strFileName
.c_str(), nLine
+ 1L, strLHS
.c_str());
2393 if ( !nextFieldOnSameLine
)
2395 //else: don't reset it
2397 // as we don't reset strMimeType, the next field in this entry
2398 // will be interpreted correctly.
2404 // depending on the format (Mosaic or Netscape) either space or comma
2405 // is used to separate the extensions
2406 strExtensions
.Replace(wxT(","), wxT(" "));
2408 // also deal with the leading dot
2409 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2411 strExtensions
.erase(0, 1);
2414 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2415 strExtensions
.c_str(),
2416 strMimeType
.c_str(),
2419 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2421 // finished with this line
2428 // ----------------------------------------------------------------------------
2429 // UNIX mailcap files parsing
2430 // ----------------------------------------------------------------------------
2432 // the data for a single MIME type
2433 struct MailcapLineData
2442 wxArrayString verbs
,
2450 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= false; }
2453 // process a non-standard (i.e. not the first or second one) mailcap field
2455 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2456 const wxString
& curField
)
2458 if ( curField
.empty() )
2464 // is this something of the form foo=bar?
2465 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2468 // split "LHS = RHS" in 2
2469 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2470 rhs
= curField
.AfterFirst(wxT('='));
2472 lhs
.Trim(true); // from right
2473 rhs
.Trim(false); // from left
2475 // it might be quoted
2476 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2478 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2481 // is it a command verb or something else?
2482 if ( lhs
== wxT("test") )
2484 if ( wxSystem(rhs
) == 0 )
2487 wxLogTrace(TRACE_MIME_TEST
,
2488 wxT("Test '%s' for mime type '%s' succeeded."),
2489 rhs
.c_str(), data
.type
.c_str());
2493 wxLogTrace(TRACE_MIME_TEST
,
2494 wxT("Test '%s' for mime type '%s' failed, skipping."),
2495 rhs
.c_str(), data
.type
.c_str());
2497 data
.testfailed
= true;
2500 else if ( lhs
== wxT("desc") )
2504 else if ( lhs
== wxT("x11-bitmap") )
2508 else if ( lhs
== wxT("notes") )
2512 else // not a (recognized) special case, must be a verb (e.g. "print")
2514 data
.verbs
.Add(lhs
);
2515 data
.commands
.Add(rhs
);
2518 else // '=' not found
2520 // so it must be a simple flag
2521 if ( curField
== wxT("needsterminal") )
2523 data
.needsterminal
= true;
2525 else if ( curField
== wxT("copiousoutput"))
2527 // copiousoutput impies that the viewer is a console program
2528 data
.needsterminal
=
2529 data
.copiousoutput
= true;
2531 else if ( !IsKnownUnimportantField(curField
) )
2540 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2543 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2544 strFileName
.c_str());
2546 wxTextFile
file(strFileName
);
2547 #if defined(__WXGTK20__) && wxUSE_UNICODE
2548 if ( !file
.Open(wxConvUTF8
) )
2554 // indices of MIME types (in m_aTypes) we already found in this file
2556 // (see the comments near the end of function for the reason we need this)
2557 wxArrayInt aIndicesSeenHere
;
2559 // accumulator for the current field
2561 curField
.reserve(1024);
2563 const wxChar
*pPagerEnv
= wxGetenv(wxT("PAGER"));
2565 const wxArrayString empty_extensions_list
;
2567 size_t nLineCount
= file
.GetLineCount();
2568 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2570 // now we're at the start of the line
2571 const wxChar
*pc
= file
[nLine
].c_str();
2574 while ( wxIsspace(*pc
) )
2577 // comment or empty string?
2578 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2584 // what field are we currently in? The first 2 are fixed and there may
2585 // be an arbitrary number of other fields parsed by
2586 // ProcessOtherMailcapField()
2588 // the first field is the MIME type
2595 currentToken
= Field_Type
;
2597 // the flags and field values on the current line
2598 MailcapLineData data
;
2606 // interpret the next character literally (notice that
2607 // backslash can be used for line continuation)
2608 if ( *++pc
== wxT('\0') )
2610 // fetch the next line if there is one
2611 if ( nLine
== nLineCount
- 1 )
2613 // something is wrong, bail out
2616 wxLogDebug(wxT("Mailcap file %s, line %lu: '\\' on the end of the last line ignored."),
2617 strFileName
.c_str(),
2622 // pass to the beginning of the next line
2623 pc
= file
[++nLine
].c_str();
2625 // skip pc++ at the end of the loop
2631 // just a normal character
2637 cont
= false; // end of line reached, exit the loop
2639 // fall through to still process this field
2642 // trim whitespaces from both sides
2643 curField
.Trim(true).Trim(false);
2645 switch ( currentToken
)
2648 data
.type
= curField
.Lower();
2649 if ( data
.type
.empty() )
2651 // I don't think that this is a valid mailcap
2652 // entry, but try to interpret it somehow
2653 data
.type
= wxT('*');
2656 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2658 // we interpret "type" as "type/*"
2659 data
.type
+= wxT("/*");
2662 currentToken
= Field_OpenCmd
;
2666 data
.cmdOpen
= curField
;
2668 currentToken
= Field_Other
;
2672 if ( !ProcessOtherMailcapField(data
, curField
) )
2674 // don't flood the user with error messages if
2675 // we don't understand something in his
2676 // mailcap, but give them in debug mode because
2677 // this might be useful for the programmer
2680 wxT("Mailcap file %s, line %lu: unknown field '%s' for the MIME type '%s' ignored."),
2681 strFileName
.c_str(),
2687 else if ( data
.testfailed
)
2689 // skip this entry entirely
2693 // it already has this value
2694 //currentToken = Field_Other;
2698 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2701 // next token starts immediately after ';'
2709 // continue in the same line
2713 // we read the entire entry, check what have we got
2714 // ------------------------------------------------
2716 // check that we really read something reasonable
2717 if ( currentToken
< Field_Other
)
2719 wxLogWarning(wxT("Mailcap file %s, line %lu: incomplete entry ignored."),
2720 strFileName
.c_str(), nLine
+ 1L);
2725 // if the test command failed, it's as if the entry were not there at all
2726 if ( data
.testfailed
)
2731 // support for flags:
2732 // 1. create an xterm for 'needsterminal'
2733 // 2. append "| $PAGER" for 'copiousoutput'
2735 // Note that the RFC says that having both needsterminal and
2736 // copiousoutput is probably a mistake, so it seems that running
2737 // programs with copiousoutput inside an xterm as it is done now
2738 // is a bad idea (FIXME)
2739 if ( data
.copiousoutput
)
2741 data
.cmdOpen
<< wxT(" | ") << (pPagerEnv
? pPagerEnv
: wxT("more"));
2744 if ( data
.needsterminal
)
2746 data
.cmdOpen
.Printf(wxT("xterm -e sh -c '%s'"),
2747 data
.cmdOpen
.c_str());
2750 if ( !data
.cmdOpen
.empty() )
2752 data
.verbs
.Insert(wxT("open"), 0);
2753 data
.commands
.Insert(data
.cmdOpen
, 0);
2756 // we have to decide whether the new entry should replace any entries
2757 // for the same MIME type we had previously found or not
2760 // the fall back entries have the lowest priority, by definition
2767 // have we seen this one before?
2768 int nIndex
= m_aTypes
.Index(data
.type
);
2770 // and if we have, was it in this file? if not, we should
2771 // overwrite the previously seen one
2772 overwrite
= nIndex
== wxNOT_FOUND
||
2773 aIndicesSeenHere
.Index(nIndex
) == wxNOT_FOUND
;
2776 wxLogTrace(TRACE_MIME
, wxT("mailcap %s: %s [%s]"),
2777 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2778 overwrite
? wxT("replace") : wxT("add"));
2780 int n
= AddToMimeData
2784 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2785 empty_extensions_list
,
2792 aIndicesSeenHere
.Add(n
);
2799 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2805 size_t count
= m_aTypes
.GetCount();
2806 for ( size_t n
= 0; n
< count
; n
++ )
2808 // don't return template types from here (i.e. anything containg '*')
2809 const wxString
&type
= m_aTypes
[n
];
2810 if ( type
.Find(wxT('*')) == wxNOT_FOUND
)
2812 mimetypes
.Add(type
);
2816 return mimetypes
.GetCount();
2819 // ----------------------------------------------------------------------------
2820 // writing to MIME type files
2821 // ----------------------------------------------------------------------------
2823 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2827 wxArrayString sMimeTypes
;
2828 ft
->GetMimeTypes(sMimeTypes
);
2831 size_t nCount
= sMimeTypes
.GetCount();
2832 for (i
= 0; i
< nCount
; i
++)
2834 const wxString
&sMime
= sMimeTypes
.Item(i
);
2835 int nIndex
= m_aTypes
.Index(sMime
);
2836 if ( nIndex
== wxNOT_FOUND
)
2838 // error if we get here ??
2843 WriteMimeInfo(nIndex
, true);
2844 m_aTypes
.RemoveAt(nIndex
);
2845 m_aEntries
.RemoveAt(nIndex
);
2846 m_aExtensions
.RemoveAt(nIndex
);
2847 m_aDescriptions
.RemoveAt(nIndex
);
2848 m_aIcons
.RemoveAt(nIndex
);
2851 // check data integrity
2852 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2853 m_aTypes
.Count() == m_aExtensions
.Count() &&
2854 m_aTypes
.Count() == m_aIcons
.Count() &&
2855 m_aTypes
.Count() == m_aDescriptions
.Count() );
2860 // ----------------------------------------------------------------------------
2861 // private functions
2862 // ----------------------------------------------------------------------------
2864 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2866 static const wxChar
* const knownFields
[] =
2868 wxT("x-mozilla-flags"),
2869 wxT("nametemplate"),
2870 wxT("textualnewlines"),
2873 wxString field
= fieldAll
.BeforeFirst(wxT('='));
2874 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2876 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2884 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE