1 /////////////////////////////////////////////////////////////////////////////
2 // Name: unix/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows 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
31 TODO: this file is a mess, we need to split it and reformet/review
35 // ============================================================================
37 // ============================================================================
39 // ----------------------------------------------------------------------------
41 // ----------------------------------------------------------------------------
43 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
44 #pragma implementation "mimetype.h"
47 // for compilers that support precompilation, includes "wx.h".
48 #include "wx/wxprec.h"
58 #if wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE
61 #include "wx/string.h"
68 #include "wx/dynarray.h"
69 #include "wx/confbase.h"
72 #include "wx/textfile.h"
75 #include "wx/tokenzr.h"
76 #include "wx/iconloc.h"
77 #include "wx/filename.h"
78 #include "wx/fileconf.h"
80 #include "wx/unix/mimetype.h"
82 // other standard headers
86 /* silence warnings for comparing unsigned int's <0 */
87 # pragma message disable unscomzer
90 // wxMimeTypeCommands stores the verbs defined for the given MIME type with
92 class wxMimeTypeCommands
95 wxMimeTypeCommands() { }
97 wxMimeTypeCommands(const wxArrayString
& verbs
,
98 const wxArrayString
& commands
)
104 // add a new verb with the command or replace the old value
105 void AddOrReplaceVerb(const wxString
& verb
, const wxString
& cmd
)
107 int n
= m_verbs
.Index(verb
, FALSE
/* ignore case */);
108 if ( n
== wxNOT_FOUND
)
119 void Add(const wxString
& s
)
121 m_verbs
.Add(s
.BeforeFirst(_T('=')));
122 m_commands
.Add(s
.AfterFirst(_T('=')));
125 // access the commands
126 size_t GetCount() const { return m_verbs
.GetCount(); }
127 const wxString
& GetVerb(size_t n
) const { return m_verbs
[n
]; }
128 const wxString
& GetCmd(size_t n
) const { return m_commands
[n
]; }
130 bool HasVerb(const wxString
& verb
) const
131 { return m_verbs
.Index(verb
) != wxNOT_FOUND
; }
133 wxString
GetCommandForVerb(const wxString
& verb
, size_t *idx
= NULL
) const
137 int n
= m_verbs
.Index(verb
);
138 if ( n
!= wxNOT_FOUND
)
140 s
= m_commands
[(size_t)n
];
148 // get a "verb=command" string
149 wxString
GetVerbCmd(size_t n
) const
151 return m_verbs
[n
] + _T('=') + m_commands
[n
];
155 wxArrayString m_verbs
,
159 // this class extends wxTextFile
162 class wxMimeTextFile
: public wxTextFile
166 wxMimeTextFile () : wxTextFile () {};
167 wxMimeTextFile (const wxString
& strFile
) : wxTextFile (strFile
) { };
169 int pIndexOf(const wxString
& sSearch
, bool bIncludeComments
= FALSE
, int iStart
= 0)
172 int nResult
= wxNOT_FOUND
;
173 if (i
>=GetLineCount()) return wxNOT_FOUND
;
175 wxString sTest
= sSearch
;
179 if (bIncludeComments
)
181 while ( (i
< GetLineCount()) )
185 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
191 while ( (i
< GetLineCount()) )
195 if ( ! sLine
.StartsWith(wxT("#")))
197 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
205 bool CommentLine(int nIndex
)
207 if (nIndex
<0) return FALSE
;
208 if (nIndex
>= (int)GetLineCount() ) return FALSE
;
209 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
213 bool CommentLine(const wxString
& sTest
)
215 int nIndex
= pIndexOf(sTest
);
216 if (nIndex
<0) return FALSE
;
217 if (nIndex
>= (int)GetLineCount() ) return FALSE
;
218 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
222 wxString
GetVerb (size_t i
)
224 if (i
> GetLineCount() ) return wxEmptyString
;
225 wxString sTmp
= GetLine(i
).BeforeFirst(wxT('='));
229 wxString
GetCmd (size_t i
)
231 if (i
> GetLineCount() ) return wxEmptyString
;
232 wxString sTmp
= GetLine(i
).AfterFirst(wxT('='));
237 // in case we're compiling in non-GUI mode
238 class WXDLLEXPORT wxIcon
;
240 // ----------------------------------------------------------------------------
242 // ----------------------------------------------------------------------------
244 // MIME code tracing mask
245 #define TRACE_MIME _T("mime")
247 // give trace messages about the results of mailcap tests
248 #define TRACE_MIME_TEST _T("mimetest")
250 // ----------------------------------------------------------------------------
252 // ----------------------------------------------------------------------------
254 // there are some fields which we don't understand but for which we don't give
255 // warnings as we know that they're not important - this function is used to
257 static bool IsKnownUnimportantField(const wxString
& field
);
259 // ----------------------------------------------------------------------------
261 // ----------------------------------------------------------------------------
264 // This class uses both mailcap and mime.types to gather information about file
267 // The information about mailcap file was extracted from metamail(1) sources
268 // and documentation and subsequently revised when I found the RFC 1524
271 // Format of mailcap file: spaces are ignored, each line is either a comment
272 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
273 // A backslash can be used to quote semicolons and newlines (and, in fact,
274 // anything else including itself).
276 // The first field is always the MIME type in the form of type/subtype (see RFC
277 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
278 // "type" which means the same as "type/*", although I'm not sure whether this
281 // The second field is always the command to run. It is subject to
282 // parameter/filename expansion described below.
284 // All the following fields are optional and may not be present at all. If
285 // they're present they may appear in any order, although each of them should
286 // appear only once. The optional fields are the following:
287 // * notes=xxx is an uninterpreted string which is silently ignored
288 // * test=xxx is the command to be used to determine whether this mailcap line
289 // applies to our data or not. The RHS of this field goes through the
290 // parameter/filename expansion (as the 2nd field) and the resulting string
291 // is executed. The line applies only if the command succeeds, i.e. returns 0
293 // * print=xxx is the command to be used to print (and not view) the data of
294 // this type (parameter/filename expansion is done here too)
295 // * edit=xxx is the command to open/edit the data of this type
296 // * needsterminal means that a new interactive console must be created for
298 // * copiousoutput means that the viewer doesn't interact with the user but
299 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
300 // good example), thus it might be a good idea to use some kind of paging
302 // * textualnewlines means not to perform CR/LF translation (not honored)
303 // * compose and composetyped fields are used to determine the program to be
304 // called to create a new message pert in the specified format (unused).
306 // Parameter/filename expansion:
307 // * %s is replaced with the (full) file name
308 // * %t is replaced with MIME type/subtype of the entry
309 // * for multipart type only %n is replaced with the nnumber of parts and %F is
310 // replaced by an array of (content-type, temporary file name) pairs for all
311 // message parts (TODO)
312 // * %{parameter} is replaced with the value of parameter taken from
313 // Content-type header line of the message.
316 // There are 2 possible formats for mime.types file, one entry per line (used
317 // for global mime.types and called Mosaic format) and "expanded" format where
318 // an entry takes multiple lines (used for users mime.types and called
321 // For both formats spaces are ignored and lines starting with a '#' are
322 // comments. Each record has one of two following forms:
323 // a) for "brief" format:
324 // <mime type> <space separated list of extensions>
325 // b) for "expanded" format:
326 // type=<mime type> BACKSLASH
327 // desc="<description>" BACKSLASH
328 // exts="<comma separated list of extensions>"
330 // (where BACKSLASH is a literal '\\' which we can't put here because cpp
333 // We try to autodetect the format of mime.types: if a non-comment line starts
334 // with "type=" we assume the second format, otherwise the first one.
336 // there may be more than one entry for one and the same mime type, to
337 // choose the right one we have to run the command specified in the test
338 // field on our data.
340 // ----------------------------------------------------------------------------
342 // ----------------------------------------------------------------------------
344 // GNOME stores the info we're interested in in several locations:
345 // 1. xxx.keys files under /usr/share/mime-info
346 // 2. xxx.keys files under ~/.gnome/mime-info
348 // The format of xxx.keys file is the following:
353 // with blank lines separating the entries and indented lines starting with
354 // TABs. We're interested in the field icon-filename whose value is the path
355 // containing the icon.
357 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
358 // just before the field name.
361 bool wxMimeTypesManagerImpl::CheckGnomeDirsExist ()
364 wxGetHomeDir( &gnomedir
);
365 wxString sTmp
= gnomedir
;
366 sTmp
= sTmp
+ wxT("/.gnome");
367 if (! wxDir::Exists ( sTmp
) )
369 if (!wxMkdir ( sTmp
))
371 wxLogError(_("Failed to create directory %s/.gnome."), sTmp
.c_str());
375 sTmp
= sTmp
+ wxT("/mime-info");
376 if (! wxDir::Exists ( sTmp
) )
378 if (!wxMkdir ( sTmp
))
380 wxLogError(_("Failed to create directory %s/mime-info."), sTmp
.c_str());
390 bool wxMimeTypesManagerImpl::WriteGnomeKeyFile(int index
, bool delete_index
)
393 wxGetHomeDir( &gnomedir
);
395 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.keys"));
396 // if this fails probably Gnome is not installed ??
397 // create it anyway as a private mime store
399 #if defined(__WXGTK20__) && wxUSE_UNICODE
400 if (! outfile
.Open ( wxConvUTF8
) )
402 if (! outfile
.Open () )
405 if (delete_index
) return FALSE
;
406 if (!CheckGnomeDirsExist() ) return FALSE
;
410 wxString sTmp
, strType
= m_aTypes
[index
];
411 int nIndex
= outfile
.pIndexOf(strType
);
412 if ( nIndex
== wxNOT_FOUND
)
414 outfile
.AddLine ( strType
+ wxT(':') );
415 // see file:/usr/doc/gnome-libs-devel-1.0.40/devel-docs/mime-type-handling.txt
416 // as this does not deal with internationalisation
417 // wxT( "\t[en_US]") + verb + wxT ('=') + cmd + wxT(" %f");
418 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
419 size_t count
= entries
->GetCount();
420 for ( size_t i
= 0; i
< count
; i
++ )
422 sTmp
= entries
->GetVerbCmd(i
);
423 sTmp
.Replace( wxT("%s"), wxT("%f") );
424 sTmp
= wxT ( "\t") + sTmp
;
425 outfile
.AddLine ( sTmp
);
427 //for international use do something like this
428 //outfile.AddLine ( wxString( "\t[en_US]icon-filename=") + cmd );
429 outfile
.AddLine ( wxT( "\ticon-filename=") + m_aIcons
[index
] );
434 outfile
.CommentLine(nIndex
);
436 wxMimeTypeCommands sOld
;
437 size_t nOld
= nIndex
+ 1;
438 bool oldEntryEnd
= FALSE
;
439 while ( (nOld
< outfile
.GetLineCount() )&& (oldEntryEnd
== FALSE
))
441 sTmp
= outfile
.GetLine(nOld
);
442 if ( (sTmp
[0u] == wxT('\t')) || (sTmp
[0u] == wxT('#')) )
444 // we have another line to deal with
445 outfile
.CommentLine(nOld
);
447 // add the line to our store
448 if ((!delete_index
) && (sTmp
[0u] == wxT('\t')))
451 // next mimetpye ??or blank line
455 // list of entries in our data; these should all be in sOld,
456 // though sOld may also contain other entries , eg flags
459 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
461 for (i
=0; i
< entries
->GetCount(); i
++)
463 // replace any entries in sold that match verbs we know
464 sOld
.AddOrReplaceVerb ( entries
->GetVerb(i
), entries
->GetCmd (i
) );
466 //sOld should also contain the icon
467 if ( !m_aIcons
[index
].empty() )
468 sOld
.AddOrReplaceVerb ( wxT("icon-filename"), m_aIcons
[index
] );
470 for (i
=0; i
< sOld
.GetCount(); i
++)
472 sTmp
= sOld
.GetVerbCmd(i
);
473 sTmp
.Replace( wxT("%s"), wxT("%f") );
474 sTmp
= wxT("\t") + sTmp
;
476 outfile
.InsertLine ( sTmp
, nIndex
);
480 bool bTmp
= outfile
.Write ();
485 bool wxMimeTypesManagerImpl::WriteGnomeMimeFile(int index
, bool delete_index
)
488 wxGetHomeDir( &gnomedir
);
490 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.mime"));
491 // if this fails probably Gnome is not installed ??
492 // create it anyway as a private mime store
493 if (! outfile
.Open () )
495 if (delete_index
) return FALSE
;
496 if (!CheckGnomeDirsExist() ) return FALSE
;
499 wxString strType
= m_aTypes
[index
];
500 int nIndex
= outfile
.pIndexOf(strType
);
501 if ( nIndex
== wxNOT_FOUND
)
503 outfile
.AddLine ( strType
);
504 outfile
.AddLine ( wxT("\text:") + m_aExtensions
.Item(index
) );
510 outfile
.CommentLine(nIndex
);
511 outfile
.CommentLine(nIndex
+1);
514 {// check for next line being the right one to replace ??
515 wxString sOld
= outfile
.GetLine(nIndex
+1);
516 if (sOld
.Contains( wxT("\text: ")))
518 outfile
.GetLine(nIndex
+1) = wxT("\text: ") + m_aExtensions
.Item(index
);
522 outfile
.InsertLine( wxT("\text: ") + m_aExtensions
.Item(index
), nIndex
+ 1 );
526 bool bTmp
= outfile
.Write ();
531 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString
& filename
,
532 const wxArrayString
& dirs
)
534 wxTextFile
textfile(filename
);
535 #if defined(__WXGTK20__) && wxUSE_UNICODE
536 if ( !textfile
.Open( wxConvUTF8
) )
538 if ( !textfile
.Open() )
541 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
544 // values for the entry being parsed
545 wxString curMimeType
, curIconFile
;
546 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
548 // these are always empty in this file
549 wxArrayString strExtensions
;
553 size_t nLineCount
= textfile
.GetLineCount();
555 while ( nLine
< nLineCount
)
557 pc
= textfile
[nLine
].c_str();
558 if ( *pc
!= _T('#') )
561 wxLogTrace(TRACE_MIME
, wxT("--- Reading from Gnome file %s '%s' ---"),
562 filename
.c_str(),pc
);
565 if (sTmp
.Contains(wxT("=")) )
568 if (sTmp
.Contains( wxT("icon-filename=") ) )
570 curIconFile
= sTmp
.AfterFirst(wxT('='));
573 else if (sTmp
.Contains( wxT("icon_filename=") ) )
575 curIconFile
= sTmp
.AfterFirst(wxT('='));
577 if (!wxFileExists(curIconFile
))
579 size_t nDirs
= dirs
.GetCount();
580 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
582 wxFileName
newFile( curIconFile
);
583 newFile
.SetPath( dirs
[nDir
] );
584 newFile
.AppendDir( wxT("pixmaps") );
585 newFile
.AppendDir( wxT("document-icons") );
586 newFile
.SetExt( wxT("png") );
587 if (newFile
.FileExists())
588 curIconFile
= newFile
.GetFullPath();
592 else //: some other field,
594 //may contain lines like this (RH7)
595 // \t[lang]open.tex."TeX this file"=tex %f
596 // \tflags.tex.flags=needsterminal
597 // \topen.latex."LaTeX this file"=latex %f
598 // \tflags.latex.flags=needsterminal
602 // \topen.convert.Convert file to Postscript=dvips %f -o `basename %f .dvi`.ps
604 // for now ignore lines with flags in...FIX
605 sTmp
= sTmp
.AfterLast(wxT(']'));
606 sTmp
= sTmp
.AfterLast(wxT('\t'));
607 sTmp
.Trim(FALSE
).Trim();
608 if (0 == sTmp
.Replace ( wxT("%f"), wxT("%s") )) sTmp
= sTmp
+ wxT(" %s");
613 } // emd of has an equals sign
616 // not a comment and not an equals sign
617 if (sTmp
.Contains(wxT('/')))
619 // this is the start of the new mimetype
620 // overwrite any existing data
621 if (! curMimeType
.empty())
623 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
625 // now get ready for next bit
626 entry
= new wxMimeTypeCommands
;
628 curMimeType
= sTmp
.BeforeFirst(wxT(':'));
631 } // end of not a comment
632 // ignore blank lines
634 } // end of while, save any data
636 if (! curMimeType
.empty())
637 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
642 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString
& filename
)
644 wxTextFile
textfile(filename
);
645 if ( !textfile
.Open() )
648 wxLogTrace(TRACE_MIME
,
649 wxT("--- Opened Gnome file %s ---"),
652 // values for the entry being parsed
653 wxString curMimeType
, curExtList
;
656 size_t nLineCount
= textfile
.GetLineCount();
657 for ( size_t nLine
= 0;; nLine
++ )
659 if ( nLine
< nLineCount
)
661 pc
= textfile
[nLine
].c_str();
662 if ( *pc
== wxT('#') )
670 // so that we will fall into the "if" below
677 if ( !!curMimeType
&& !!curExtList
)
679 wxLogTrace(TRACE_MIME
,
680 wxT("--- At end of Gnome file finding mimetype %s ---"),
681 curMimeType
.c_str());
683 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
688 // the end - this can only happen if nLine == nLineCount
697 // what do we have here?
698 if ( *pc
== wxT('\t') )
700 // this is a field=value ling
701 pc
++; // skip leading TAB
703 static const int lenField
= 5; // strlen("ext: ")
704 if ( wxStrncmp(pc
, wxT("ext: "), lenField
) == 0 )
706 // skip it and take everything left until the end of line
707 curExtList
= pc
+ lenField
;
709 //else: some other field, we don't care
713 // this is the start of the new section
714 wxLogTrace(TRACE_MIME
,
715 wxT("--- In Gnome file finding mimetype %s ---"),
716 curMimeType
.c_str());
718 if (! curMimeType
.empty())
719 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
723 while ( *pc
!= wxT(':') && *pc
!= wxT('\0') )
725 curMimeType
+= *pc
++;
732 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
733 const wxString
& dirbase
, const wxArrayString
& dirs
)
735 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
736 _T("base directory shouldn't end with a slash") );
738 wxString dirname
= dirbase
;
739 dirname
<< wxT("/mime-info");
741 if ( !wxDir::Exists(dirname
) )
745 if ( !dir
.IsOpened() )
748 // we will concatenate it with filename to get the full path below
753 cont
= dir
.GetFirst(&filename
, _T("*.mime"), wxDIR_FILES
);
756 LoadGnomeMimeTypesFromMimeFile(dirname
+ filename
);
758 cont
= dir
.GetNext(&filename
);
761 cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
764 LoadGnomeDataFromKeyFile(dirname
+ filename
, dirs
);
766 cont
= dir
.GetNext(&filename
);
769 // Hack alert: We scan all icons and deduce the
770 // mime-type from the file name.
772 dirname
<< wxT("/pixmaps/document-icons");
774 // these are always empty in this file
775 wxArrayString strExtensions
;
778 if ( !wxDir::Exists(dirname
) )
780 // Jst test for default GPE dir also
781 dirname
= wxT("/usr/share/gpe/pixmaps/default/filemanager/document-icons");
783 if ( !wxDir::Exists(dirname
) )
787 wxDir
dir2( dirname
);
789 cont
= dir2
.GetFirst(&filename
, wxT("gnome-*.png"), wxDIR_FILES
);
792 wxString mimeType
= filename
;
793 mimeType
.Remove( 0, 6 ); // remove "gnome-"
794 mimeType
.Remove( mimeType
.Len()-4, 4 ); // remove ".png"
795 int pos
= mimeType
.Find( wxT("-") );
796 if (pos
!= wxNOT_FOUND
)
798 mimeType
.SetChar( pos
, wxT('/') );
799 wxString iconFile
= dirname
;
800 iconFile
<< wxT("/");
801 iconFile
<< filename
;
802 AddToMimeData ( mimeType
, iconFile
, NULL
, strExtensions
, strDesc
, TRUE
);
805 cont
= dir2
.GetNext(&filename
);
809 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString
& sExtraDir
)
813 wxString gnomedir
= wxGetenv( wxT("GNOMEDIR") );;
814 if (!gnomedir
.empty())
816 gnomedir
<< wxT("/share");
817 dirs
.Add( gnomedir
);
820 dirs
.Add(wxT("/usr/share"));
821 dirs
.Add(wxT("/usr/local/share"));
823 gnomedir
= wxGetHomeDir();
824 gnomedir
<< wxT("/.gnome");
825 dirs
.Add( gnomedir
);
827 if (!sExtraDir
.empty()) dirs
.Add( sExtraDir
);
829 size_t nDirs
= dirs
.GetCount();
830 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
832 LoadGnomeMimeFilesFromDir(dirs
[nDir
], dirs
);
836 // ----------------------------------------------------------------------------
838 // ----------------------------------------------------------------------------
841 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
842 // may be found in either of the following locations
844 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
845 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
847 // The format of a .kdelnk file is almost the same as the one used by
848 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
849 // value for the entry "Type"
851 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
852 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
854 bool wxMimeTypesManagerImpl::CheckKDEDirsExist ( const wxString
&sOK
, const wxString
&sTest
)
858 if (wxDir::Exists(sOK
))
865 wxString sStart
= sOK
+ wxT("/") + sTest
.BeforeFirst(wxT('/'));
866 if (!wxDir::Exists(sStart
)) wxMkdir(sStart
);
867 wxString sEnd
= sTest
.AfterFirst(wxT('/'));
868 return CheckKDEDirsExist(sStart
, sEnd
);
872 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index
, bool delete_index
)
874 wxMimeTextFile appoutfile
, mimeoutfile
;
875 wxString sHome
= wxGetHomeDir();
876 wxString sTmp
= wxT(".kde/share/mimelnk/");
877 wxString sMime
= m_aTypes
[index
];
878 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.BeforeFirst(wxT('/')) );
879 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
+ wxT(".kdelnk");
882 bool bMimeExists
= mimeoutfile
.Open (sTmp
);
885 bTemp
= mimeoutfile
.Create (sTmp
);
886 // some unknown error eg out of disk space
887 if (!bTemp
) return FALSE
;
890 sTmp
= wxT(".kde/share/applnk/");
891 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.AfterFirst(wxT('/')) );
892 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
.AfterFirst(wxT('/')) + wxT(".kdelnk");
895 bAppExists
= appoutfile
.Open (sTmp
);
898 bTemp
= appoutfile
.Create (sTmp
);
899 // some unknown error eg out of disk space
900 if (!bTemp
) return FALSE
;
903 // fixed data; write if new file
906 mimeoutfile
.AddLine(wxT("#KDE Config File"));
907 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
908 mimeoutfile
.AddLine(wxT("Version=1.0"));
909 mimeoutfile
.AddLine(wxT("Type=MimeType"));
910 mimeoutfile
.AddLine(wxT("MimeType=") + sMime
);
915 mimeoutfile
.AddLine(wxT("#KDE Config File"));
916 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
917 appoutfile
.AddLine(wxT("Version=1.0"));
918 appoutfile
.AddLine(wxT("Type=Application"));
919 appoutfile
.AddLine(wxT("MimeType=") + sMime
+ wxT(';'));
924 mimeoutfile
.CommentLine(wxT("Comment="));
926 mimeoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
927 appoutfile
.CommentLine(wxT("Name="));
929 appoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
931 sTmp
= m_aIcons
[index
];
932 // we can either give the full path, or the shortfilename if its in
933 // one of the directories we search
934 mimeoutfile
.CommentLine(wxT("Icon=") );
935 if (!delete_index
) mimeoutfile
.AddLine(wxT("Icon=") + sTmp
);
936 appoutfile
.CommentLine(wxT("Icon=") );
937 if (!delete_index
) appoutfile
.AddLine(wxT("Icon=") + sTmp
);
939 sTmp
= wxT(" ") + m_aExtensions
[index
];
941 wxStringTokenizer
tokenizer(sTmp
, _T(" "));
942 sTmp
= wxT("Patterns=");
943 mimeoutfile
.CommentLine(sTmp
);
944 while ( tokenizer
.HasMoreTokens() )
946 // holds an extension; need to change it to *.ext;
947 wxString e
= wxT("*.") + tokenizer
.GetNextToken() + wxT(";");
950 if (!delete_index
) mimeoutfile
.AddLine(sTmp
);
952 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
953 // if we don't find open just have an empty string ... FIX this
954 sTmp
= entries
->GetCommandForVerb(_T("open"));
955 sTmp
.Replace( wxT("%s"), wxT("%f") );
957 mimeoutfile
.CommentLine(wxT("DefaultApp=") );
958 if (!delete_index
) mimeoutfile
.AddLine(wxT("DefaultApp=") + sTmp
);
960 sTmp
.Replace( wxT("%f"), wxT("") );
961 appoutfile
.CommentLine(wxT("Exec="));
962 if (!delete_index
) appoutfile
.AddLine(wxT("Exec=") + sTmp
);
964 if (entries
->GetCount() > 1)
966 //other actions as well as open
970 if (mimeoutfile
.Write ()) bTemp
= TRUE
;
971 mimeoutfile
.Close ();
972 if (appoutfile
.Write ()) bTemp
= TRUE
;
978 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString
& dirbase
,
979 const wxString
& subdir
,
980 const wxString
& filename
,
981 const wxArrayString
& icondirs
)
984 if ( !file
.Open(dirbase
+ filename
) ) return;
986 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
987 (dirbase
+filename
).c_str());
989 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
991 wxString mimetype
, mime_desc
, strIcon
;
993 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
994 if (nIndex
== wxNOT_FOUND
)
996 // construct mimetype from the directory name and the basename of the
997 // file (it always has .kdelnk extension)
998 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
1000 else mimetype
= file
.GetCmd (nIndex
);
1002 // first find the description string: it is the value in either "Comment="
1003 // line or "Comment[<locale_name>]=" one
1004 nIndex
= wxNOT_FOUND
;
1008 wxLocale
*locale
= wxGetLocale();
1011 // try "Comment[locale name]" first
1012 comment
<< _T("Comment[") + locale
->GetName() + _T("]=");
1013 nIndex
= file
.pIndexOf(comment
);
1015 #endif // wxUSE_INTL
1017 if ( nIndex
== wxNOT_FOUND
)
1019 comment
= _T("Comment=");
1020 nIndex
= file
.pIndexOf(comment
);
1023 if ( nIndex
!= wxNOT_FOUND
) mime_desc
= file
.GetCmd(nIndex
);
1024 //else: no description
1026 // next find the extensions
1027 wxString mime_extension
;
1029 nIndex
= file
.pIndexOf(_T("Patterns="));
1030 if ( nIndex
!= wxNOT_FOUND
)
1032 wxString exts
= file
.GetCmd (nIndex
);;
1034 wxStringTokenizer
tokenizer(exts
, _T(";"));
1035 while ( tokenizer
.HasMoreTokens() )
1037 wxString e
= tokenizer
.GetNextToken();
1038 if ( e
.Left(2) != _T("*.") )
1039 continue; // don't support too difficult patterns
1041 if ( !mime_extension
.empty() )
1043 // separate from the previous ext
1044 mime_extension
<< _T(' ');
1047 mime_extension
<< e
.Mid(2);
1050 sExts
.Add(mime_extension
);
1052 // ok, now we can take care of icon:
1054 nIndex
= file
.pIndexOf(_T("Icon="));
1055 if ( nIndex
!= wxNOT_FOUND
)
1057 strIcon
= file
.GetCmd(nIndex
);
1058 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
1059 //it could be the real path, but more often a short name
1062 if (!wxFileExists(strIcon
))
1064 // icon is just the short name
1065 if ( !strIcon
.empty() )
1067 // we must check if the file exists because it may be stored
1068 // in many locations, at least ~/.kde and $KDEDIR
1069 size_t nDir
, nDirs
= icondirs
.GetCount();
1070 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
1072 wxFileName
fname( icondirs
[nDir
], strIcon
);
1073 fname
.SetExt( wxT("png") );
1074 if (fname
.FileExists())
1076 strIcon
= fname
.GetFullPath();
1077 wxLogTrace(TRACE_MIME
, wxT(" iconfile %s"), strIcon
.c_str());
1084 // now look for lines which know about the application
1085 // exec= or DefaultApp=
1087 nIndex
= file
.pIndexOf(wxT("DefaultApp"));
1089 if ( nIndex
== wxNOT_FOUND
)
1091 // no entry try exec
1092 nIndex
= file
.pIndexOf(wxT("Exec"));
1095 if ( nIndex
!= wxNOT_FOUND
)
1097 wxString sTmp
= file
.GetCmd(nIndex
);
1098 // we expect %f; others including %F and %U and %u are possible
1099 if (0 == sTmp
.Replace ( wxT("%f"), wxT("%s") ))
1100 sTmp
= sTmp
+ wxT(" %s");
1101 entry
->AddOrReplaceVerb (wxString(wxT("open")), sTmp
);
1104 AddToMimeData (mimetype
, strIcon
, entry
, sExts
, mime_desc
);
1107 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString
& dirbase
,
1108 const wxString
& subdir
,
1109 const wxArrayString
& icondirs
)
1111 wxString dirname
= dirbase
;
1114 if ( !dir
.IsOpened() )
1117 wxLogTrace(TRACE_MIME
, wxT("--- Loading from KDE directory %s ---"),
1123 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
1126 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1128 cont
= dir
.GetNext(&filename
);
1130 // new standard for Gnome and KDE
1131 cont
= dir
.GetFirst(&filename
, _T("*.desktop"), wxDIR_FILES
);
1134 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1136 cont
= dir
.GetNext(&filename
);
1140 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString
& dirbase
,
1141 const wxArrayString
& icondirs
)
1143 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1144 _T("base directory shouldn't end with a slash") );
1146 wxString dirname
= dirbase
;
1147 dirname
<< _T("/mimelnk");
1149 if ( !wxDir::Exists(dirname
) )
1153 if ( !dir
.IsOpened() )
1156 // we will concatenate it with dir name to get the full path below
1160 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
1163 LoadKDELinksForMimeType(dirname
, subdir
, icondirs
);
1165 cont
= dir
.GetNext(&subdir
);
1169 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString
& sExtraDir
)
1172 wxArrayString icondirs
;
1174 // the variable $KDEDIR is set when KDE is running
1175 wxString kdedir
= wxGetenv( wxT("KDEDIR") );
1177 if (!kdedir
.empty())
1179 // $(KDEDIR)/share/config/kdeglobals holds info
1180 // the current icons theme
1181 wxFileName
configFile( kdedir
, wxEmptyString
);
1182 configFile
.AppendDir( wxT("share") );
1183 configFile
.AppendDir( wxT("config") );
1184 configFile
.SetName( wxT("kdeglobals") );
1186 if (configFile
.FileExists())
1188 wxFileConfig
config( wxEmptyString
, wxEmptyString
, configFile
.GetFullPath() );
1189 // $(KDEDIR)/share/config -> $(KDEDIR)/share
1190 configFile
.RemoveDir( configFile
.GetDirCount()-1 );
1191 // $(KDEDIR)/share/ -> $(KDEDIR)/share/icons
1192 configFile
.AppendDir( wxT("icons") );
1195 config
.SetPath( wxT("Icons") );
1197 if (config
.Read( wxT("Theme"), &theme
))
1198 configFile
.AppendDir( theme
);
1200 configFile
.AppendDir( wxT("default.kde") );
1204 // $(KDEDIR)/share/config -> $(KDEDIR)/share
1205 configFile
.RemoveDir( configFile
.GetDirCount()-1 );
1206 // $(KDEDIR)/share/ -> $(KDEDIR)/share/icons
1207 configFile
.AppendDir( wxT("icons") );
1208 // $(KDEDIR)/share/icons -> $(KDEDIR)/share/icons/default.kde
1209 configFile
.AppendDir( wxT("default.kde") );
1212 configFile
.SetName( wxEmptyString
);
1213 configFile
.AppendDir( wxT("32x32") );
1214 configFile
.AppendDir( wxT("mimetypes") );
1216 // Just try a few likely icons theme names
1218 int pos
= configFile
.GetDirCount()-3;
1220 if (!wxDir::Exists(configFile
.GetPath()))
1222 configFile
.RemoveDir( pos
);
1223 configFile
.InsertDir( pos
, wxT("default.kde") );
1226 if (!wxDir::Exists(configFile
.GetPath()))
1228 configFile
.RemoveDir( pos
);
1229 configFile
.InsertDir( pos
, wxT("default") );
1232 if (!wxDir::Exists(configFile
.GetPath()))
1234 configFile
.RemoveDir( pos
);
1235 configFile
.InsertDir( pos
, wxT("crystalsvg") );
1238 if (!wxDir::Exists(configFile
.GetPath()))
1240 configFile
.RemoveDir( pos
);
1241 configFile
.InsertDir( pos
, wxT("crystal") );
1244 if (wxDir::Exists(configFile
.GetPath()))
1245 icondirs
.Add( configFile
.GetFullPath() );
1248 // settings in ~/.kde have maximal priority
1249 dirs
.Add(wxGetHomeDir() + wxT("/.kde/share"));
1250 icondirs
.Add(wxGetHomeDir() + wxT("/.kde/share/icons/"));
1254 dirs
.Add( wxString(kdedir
) + wxT("/share") );
1255 icondirs
.Add( wxString(kdedir
) + wxT("/share/icons/") );
1259 // try to guess KDEDIR
1260 dirs
.Add(_T("/usr/share"));
1261 dirs
.Add(_T("/opt/kde/share"));
1262 icondirs
.Add(_T("/usr/share/icons/"));
1263 icondirs
.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
1264 icondirs
.Add(_T("/opt/kde/share/icons/"));
1267 if (!sExtraDir
.empty()) dirs
.Add (sExtraDir
);
1268 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1270 size_t nDirs
= dirs
.GetCount();
1271 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1273 LoadKDELinkFilesFromDir(dirs
[nDir
], icondirs
);
1277 // ----------------------------------------------------------------------------
1278 // wxFileTypeImpl (Unix)
1279 // ----------------------------------------------------------------------------
1281 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1285 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1287 sTmp
= m_manager
->GetCommand ( verb
, m_index
[i
] );
1291 return wxFileType::ExpandCommand(sTmp
, params
);
1294 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
1299 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1301 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1304 if ( sTmp
.empty () )
1309 iconLoc
->SetFileName(sTmp
);
1317 wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1320 for (size_t i
= 0; i
< m_index
.GetCount(); i
++)
1321 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1326 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1327 wxArrayString
*commands
,
1328 const wxFileType::MessageParameters
& params
) const
1331 wxString vrb
, cmd
, sTmp
;
1333 wxMimeTypeCommands
* sPairs
;
1335 // verbs and commands have been cleared already in mimecmn.cpp...
1336 // if we find no entries in the exact match, try the inexact match
1337 for (size_t n
= 0; ((count
==0) && (n
< m_index
.GetCount())); n
++)
1339 // list of verb = command pairs for this mimetype
1340 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1342 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
1344 vrb
= sPairs
->GetVerb(i
);
1345 // some gnome entries have . inside
1346 vrb
= vrb
.AfterLast(wxT('.'));
1347 cmd
= sPairs
->GetCmd (i
);
1350 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1352 if ( vrb
.IsSameAs (wxT("open")))
1354 verbs
->Insert(vrb
,0u);
1355 commands
->Insert(cmd
,0u);
1360 commands
->Add (cmd
);
1371 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1373 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1376 // one extension in the space or comma delimitid list
1378 for ( const wxChar
*p
= strExtensions
;; p
++ ) {
1379 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1380 if ( !strExt
.empty() ) {
1381 extensions
.Add(strExt
);
1384 //else: repeated spaces (shouldn't happen, but it's not that
1385 // important if it does happen)
1387 if ( *p
== wxT('\0') )
1390 else if ( *p
== wxT('.') ) {
1391 // remove the dot from extension (but only if it's the first char)
1392 if ( !strExt
.empty() ) {
1395 //else: no, don't append it
1405 // set an arbitrary command,
1406 // could adjust the code to ask confirmation if it already exists and
1407 // overwriteprompt is TRUE, but this is currently ignored as *Associate* has
1408 // no overwrite prompt
1409 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
, const wxString
& verb
, bool overwriteprompt
/*= TRUE*/)
1411 wxArrayString strExtensions
;
1412 wxString strDesc
, strIcon
;
1414 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1415 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1417 wxArrayString strTypes
;
1418 GetMimeTypes (strTypes
);
1419 if (strTypes
.GetCount() < 1) return FALSE
;
1423 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1425 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1432 // ignore index on the grouds that we only have one icon in a Unix file
1433 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
/*= wxEmptyString*/, int /*index = 0*/)
1435 if (strIcon
.empty()) return FALSE
;
1436 wxArrayString strExtensions
;
1439 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1441 wxArrayString strTypes
;
1442 GetMimeTypes (strTypes
);
1443 if (strTypes
.GetCount() < 1) return FALSE
;
1447 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1449 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1456 // ----------------------------------------------------------------------------
1457 // wxMimeTypesManagerImpl (Unix)
1458 // ----------------------------------------------------------------------------
1461 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1463 m_initialized
= FALSE
;
1464 m_mailcapStylesInited
= 0;
1467 void wxMimeTypesManagerImpl::InitIfNeeded()
1469 if ( !m_initialized
)
1471 // set the flag first to prevent recursion
1472 m_initialized
= TRUE
;
1475 wxString wm
= wxGetenv( wxT("WINDOWMANAGER") );
1477 if (wm
.Find( wxT("kde") ) != wxNOT_FOUND
)
1478 Initialize( wxMAILCAP_KDE
|wxMAILCAP_STANDARD
);
1479 else if (wm
.Find( wxT("gnome") ) != wxNOT_FOUND
)
1480 Initialize( wxMAILCAP_GNOME
|wxMAILCAP_STANDARD
);
1487 // read system and user mailcaps and other files
1488 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1489 const wxString
& sExtraDir
)
1491 // read mimecap amd mime.types
1492 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1493 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1494 GetMimeInfo(sExtraDir
);
1496 // read GNOME tables
1497 if (mailcapStyles
& wxMAILCAP_GNOME
)
1498 GetGnomeMimeInfo(sExtraDir
);
1501 if (mailcapStyles
& wxMAILCAP_KDE
)
1502 GetKDEMimeInfo(sExtraDir
);
1504 m_mailcapStylesInited
|= mailcapStyles
;
1507 // clear data so you can read another group of WM files
1508 void wxMimeTypesManagerImpl::ClearData()
1512 m_aExtensions
.Clear ();
1513 m_aDescriptions
.Clear ();
1515 WX_CLEAR_ARRAY(m_aEntries
);
1518 m_mailcapStylesInited
= 0;
1521 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1527 void wxMimeTypesManagerImpl::GetMimeInfo (const wxString
& sExtraDir
)
1529 // read this for netscape or Metamail formats
1531 // directories where we look for mailcap and mime.types by default
1532 // used by netscape and pine and other mailers, using 2 different formats!
1534 // (taken from metamail(1) sources)
1536 // although RFC 1524 specifies the search path of
1537 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1538 // places - OTOH, the RFC also says that this path can be changed with
1539 // MAILCAPS environment variable (containing the colon separated full
1540 // filenames to try) which is not done yet (TODO?)
1542 wxString strHome
= wxGetenv(wxT("HOME"));
1545 dirs
.Add ( strHome
+ wxT("/.") );
1546 dirs
.Add ( wxT("/etc/") );
1547 dirs
.Add ( wxT("/usr/etc/") );
1548 dirs
.Add ( wxT("/usr/local/etc/") );
1549 dirs
.Add ( wxT("/etc/mail/") );
1550 dirs
.Add ( wxT("/usr/public/lib/") );
1551 if (!sExtraDir
.empty()) dirs
.Add ( sExtraDir
+ wxT("/") );
1553 size_t nDirs
= dirs
.GetCount();
1554 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1556 wxString file
= dirs
[nDir
] + wxT("mailcap");
1557 if ( wxFile::Exists(file
) ) {
1561 file
= dirs
[nDir
] + wxT("mime.types");
1562 if ( wxFile::Exists(file
) ) {
1563 ReadMimeTypes(file
);
1569 bool wxMimeTypesManagerImpl::WriteToMimeTypes (int index
, bool delete_index
)
1571 // check we have the right manager
1572 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1576 wxString strHome
= wxGetenv(wxT("HOME"));
1578 // and now the users mailcap
1579 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1581 wxMimeTextFile file
;
1582 if ( wxFile::Exists(strUserMailcap
) )
1584 bTemp
= file
.Open(strUserMailcap
);
1588 if (delete_index
) return FALSE
;
1589 bTemp
= file
.Create(strUserMailcap
);
1594 // test for netscape's header and return FALSE if its found
1595 nIndex
= file
.pIndexOf (wxT("#--Netscape"));
1596 if (nIndex
!= wxNOT_FOUND
)
1598 wxASSERT_MSG(FALSE
,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1601 // write it in alternative format
1602 // get rid of unwanted entries
1603 wxString strType
= m_aTypes
[index
];
1604 nIndex
= file
.pIndexOf (strType
);
1605 // get rid of all the unwanted entries...
1606 if (nIndex
!= wxNOT_FOUND
) file
.CommentLine (nIndex
);
1610 // add the new entries in
1611 wxString sTmp
= strType
.Append (wxT(' '), 40-strType
.Len() );
1612 sTmp
= sTmp
+ m_aExtensions
[index
];
1613 file
.AddLine (sTmp
);
1617 bTemp
= file
.Write ();
1623 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes (int index
, bool delete_index
)
1625 //check we have the right managers
1626 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1630 wxString strHome
= wxGetenv(wxT("HOME"));
1632 // and now the users mailcap
1633 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1635 wxMimeTextFile file
;
1636 if ( wxFile::Exists(strUserMailcap
) )
1638 bTemp
= file
.Open(strUserMailcap
);
1642 if (delete_index
) return FALSE
;
1643 bTemp
= file
.Create(strUserMailcap
);
1648 // write it in the format that Netscape uses
1650 // test for netscape's header and insert if required...
1651 // this is a comment so use TRUE
1652 nIndex
= file
.pIndexOf (wxT("#--Netscape"), TRUE
);
1653 if (nIndex
== wxNOT_FOUND
)
1655 // either empty file or metamail format
1656 // at present we can't cope with mixed formats, so exit to preseve
1657 // metamail entreies
1658 if (file
.GetLineCount () > 0)
1660 wxASSERT_MSG(FALSE
, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1663 file
.InsertLine (wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1667 wxString strType
= wxT("type=") + m_aTypes
[index
];
1668 nIndex
= file
.pIndexOf (strType
);
1669 // get rid of all the unwanted entries...
1670 if (nIndex
!= wxNOT_FOUND
)
1672 wxString sOld
= file
[nIndex
];
1673 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1675 file
.CommentLine(nIndex
);
1676 sOld
= file
[nIndex
];
1677 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1680 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1682 else nIndex
= (int) file
.GetLineCount();
1684 wxString sTmp
= strType
+ wxT(" \\");
1685 if (!delete_index
) file
.InsertLine (sTmp
, nIndex
);
1686 if ( ! m_aDescriptions
.Item(index
).empty() )
1688 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1692 file
.InsertLine (sTmp
, nIndex
);
1695 wxString sExts
= m_aExtensions
.Item(index
);
1696 sTmp
= wxT("exts=\"") + sExts
.Trim(FALSE
).Trim() + wxT("\"");
1700 file
.InsertLine (sTmp
, nIndex
);
1703 bTemp
= file
.Write ();
1710 bool wxMimeTypesManagerImpl::WriteToMailCap (int index
, bool delete_index
)
1712 //check we have the right managers
1713 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1714 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1718 wxString strHome
= wxGetenv(wxT("HOME"));
1720 // and now the users mailcap
1721 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1723 wxMimeTextFile file
;
1724 if ( wxFile::Exists(strUserMailcap
) )
1726 bTemp
= file
.Open(strUserMailcap
);
1730 if (delete_index
) return FALSE
;
1731 bTemp
= file
.Create(strUserMailcap
);
1735 // now got a file we can write to ....
1736 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1738 wxString sCmd
= entries
->GetCommandForVerb(_T("open"), &iOpen
);
1741 sTmp
= m_aTypes
[index
];
1743 int nIndex
= file
.pIndexOf(sTmp
);
1744 // get rid of all the unwanted entries...
1745 if (nIndex
== wxNOT_FOUND
)
1747 nIndex
= (int) file
.GetLineCount();
1751 sOld
= file
[nIndex
];
1752 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1754 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1756 file
.CommentLine(nIndex
);
1757 if (nIndex
< (int) file
.GetLineCount()) sOld
= sOld
+ file
[nIndex
];
1759 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1762 sTmp
= sTmp
+ wxT(";") + sCmd
; //includes wxT(" %s ");
1764 // write it in the format that Netscape uses (default)
1765 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1767 if (! delete_index
) file
.InsertLine (sTmp
, nIndex
);
1771 // write extended format
1774 // todo FIX this code;
1776 // sOld holds all the entries, but our data store only has some
1777 // eg test= is not stored
1779 // so far we have written the mimetype and command out
1780 wxStringTokenizer
sT (sOld
, wxT(";\\"));
1781 if (sT
.CountTokens () > 2)
1783 // first one mimetype; second one command, rest unknown...
1785 s
= sT
.GetNextToken();
1786 s
= sT
.GetNextToken();
1789 s
= sT
.GetNextToken();
1790 while ( ! s
.empty() )
1792 bool bKnownToken
= FALSE
;
1793 if (s
.Contains(wxT("description="))) bKnownToken
= TRUE
;
1794 if (s
.Contains(wxT("x11-bitmap="))) bKnownToken
= TRUE
;
1796 for (i
=0; i
< entries
->GetCount(); i
++)
1798 if (s
.Contains(entries
->GetVerb(i
))) bKnownToken
= TRUE
;
1802 sTmp
= sTmp
+ wxT("; \\");
1803 file
.InsertLine (sTmp
, nIndex
);
1806 s
= sT
.GetNextToken ();
1811 if (! m_aDescriptions
[index
].empty() )
1813 sTmp
= sTmp
+ wxT("; \\");
1814 file
.InsertLine (sTmp
, nIndex
);
1816 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1819 if (! m_aIcons
[index
].empty() )
1821 sTmp
= sTmp
+ wxT("; \\");
1822 file
.InsertLine (sTmp
, nIndex
);
1824 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1826 if ( entries
->GetCount() > 1 )
1830 for (i
=0; i
< entries
->GetCount(); i
++)
1833 sTmp
= sTmp
+ wxT("; \\");
1834 file
.InsertLine (sTmp
, nIndex
);
1836 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1840 file
.InsertLine (sTmp
, nIndex
);
1844 bTemp
= file
.Write ();
1851 wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1855 wxString strType
= ftInfo
.GetMimeType ();
1856 wxString strDesc
= ftInfo
.GetDescription ();
1857 wxString strIcon
= ftInfo
.GetIconFile ();
1859 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1861 if ( ! ftInfo
.GetOpenCommand().empty())
1862 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand () + wxT(" %s "));
1863 if ( ! ftInfo
.GetPrintCommand ().empty())
1864 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand () + wxT(" %s "));
1866 // now find where these extensions are in the data store and remove them
1867 wxArrayString sA_Exts
= ftInfo
.GetExtensions ();
1868 wxString sExt
, sExtStore
;
1870 for (i
=0; i
< sA_Exts
.GetCount(); i
++)
1872 sExt
= sA_Exts
.Item(i
);
1873 //clean up to just a space before and after
1874 sExt
.Trim().Trim(FALSE
);
1875 sExt
= wxT(' ') + sExt
+ wxT(' ');
1876 for (nIndex
= 0; nIndex
< m_aExtensions
.GetCount(); nIndex
++)
1878 sExtStore
= m_aExtensions
.Item(nIndex
);
1879 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0) m_aExtensions
.Item(nIndex
) = sExtStore
;
1884 if ( !DoAssociation (strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1887 return GetFileTypeFromMimeType(strType
);
1891 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1892 const wxString
& strIcon
,
1893 wxMimeTypeCommands
*entry
,
1894 const wxArrayString
& strExtensions
,
1895 const wxString
& strDesc
)
1897 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, TRUE
);
1899 if ( nIndex
== wxNOT_FOUND
)
1902 return WriteMimeInfo (nIndex
, FALSE
);
1905 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
1909 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
1911 // write in metamail format;
1912 if (WriteToMimeTypes (nIndex
, delete_mime
) )
1913 if ( WriteToMailCap (nIndex
, delete_mime
) )
1916 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
1918 // write in netsacpe format;
1919 if (WriteToNSMimeTypes (nIndex
, delete_mime
) )
1920 if ( WriteToMailCap (nIndex
, delete_mime
) )
1923 if (m_mailcapStylesInited
& wxMAILCAP_GNOME
)
1925 // write in Gnome format;
1926 if (WriteGnomeMimeFile (nIndex
, delete_mime
) )
1927 if (WriteGnomeKeyFile (nIndex
, delete_mime
) )
1930 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
1932 // write in KDE format;
1933 if (WriteKDEMimeFile (nIndex
, delete_mime
) )
1940 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
1941 const wxString
& strIcon
,
1942 wxMimeTypeCommands
*entry
,
1943 const wxArrayString
& strExtensions
,
1944 const wxString
& strDesc
,
1945 bool replaceExisting
)
1949 // ensure mimetype is always lower case
1950 wxString mimeType
= strType
.Lower();
1952 // is this a known MIME type?
1953 int nIndex
= m_aTypes
.Index(mimeType
);
1954 if ( nIndex
== wxNOT_FOUND
)
1957 m_aTypes
.Add(mimeType
);
1958 m_aIcons
.Add(strIcon
);
1959 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
1961 // change nIndex so we can use it below to add the extensions
1962 m_aExtensions
.Add(wxEmptyString
);
1963 nIndex
= m_aExtensions
.size() - 1;
1965 m_aDescriptions
.Add(strDesc
);
1967 else // yes, we already have it
1969 if ( replaceExisting
)
1971 // if new description change it
1972 if ( !strDesc
.empty())
1973 m_aDescriptions
[nIndex
] = strDesc
;
1975 // if new icon change it
1976 if ( !strIcon
.empty())
1977 m_aIcons
[nIndex
] = strIcon
;
1981 delete m_aEntries
[nIndex
];
1982 m_aEntries
[nIndex
] = entry
;
1985 else // add data we don't already have ...
1987 // if new description add only if none
1988 if ( m_aDescriptions
[nIndex
].empty() )
1989 m_aDescriptions
[nIndex
] = strDesc
;
1991 // if new icon and no existing icon
1992 if ( m_aIcons
[nIndex
].empty () )
1993 m_aIcons
[nIndex
] = strIcon
;
1995 // add any new entries...
1998 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
2000 size_t count
= entry
->GetCount();
2001 for ( size_t i
= 0; i
< count
; i
++ )
2003 const wxString
& verb
= entry
->GetVerb(i
);
2004 if ( !entryOld
->HasVerb(verb
) )
2006 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
2010 // as we don't store it anywhere, it won't be deleted later as
2011 // usual -- do it immediately instead
2017 // always add the extensions to this mimetype
2018 wxString
& exts
= m_aExtensions
[nIndex
];
2020 // add all extensions we don't have yet
2021 size_t count
= strExtensions
.GetCount();
2022 for ( size_t i
= 0; i
< count
; i
++ )
2024 wxString ext
= strExtensions
[i
] + _T(' ');
2026 if ( exts
.Find(ext
) == wxNOT_FOUND
)
2032 // check data integrity
2033 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2034 m_aTypes
.Count() == m_aExtensions
.Count() &&
2035 m_aTypes
.Count() == m_aIcons
.Count() &&
2036 m_aTypes
.Count() == m_aDescriptions
.Count() );
2043 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
2050 size_t count
= m_aExtensions
.GetCount();
2051 for ( size_t n
= 0; n
< count
; n
++ )
2053 wxStringTokenizer
tk(m_aExtensions
[n
], _T(' '));
2055 while ( tk
.HasMoreTokens() )
2057 // consider extensions as not being case-sensitive
2058 if ( tk
.GetNextToken().IsSameAs(ext
, FALSE
/* no case */) )
2061 wxFileType
*fileType
= new wxFileType
;
2062 fileType
->m_impl
->Init(this, n
);
2073 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
2077 wxFileType
* fileType
= NULL
;
2078 // mime types are not case-sensitive
2079 wxString
mimetype(mimeType
);
2080 mimetype
.MakeLower();
2082 // first look for an exact match
2083 int index
= m_aTypes
.Index(mimetype
);
2084 if ( index
!= wxNOT_FOUND
)
2086 fileType
= new wxFileType
;
2087 fileType
->m_impl
->Init(this, index
);
2090 // then try to find "text/*" as match for "text/plain" (for example)
2091 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
2092 // the whole string - ok.
2094 index
= wxNOT_FOUND
;
2095 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
2097 size_t nCount
= m_aTypes
.Count();
2098 for ( size_t n
= 0; n
< nCount
; n
++ ) {
2099 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
2100 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
2107 if ( index
!= wxNOT_FOUND
)
2109 fileType
= new wxFileType
;
2110 fileType
->m_impl
->Init(this, index
);
2116 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
2118 wxString command
, testcmd
, sV
, sTmp
;
2119 sV
= verb
+ wxT("=");
2120 // list of verb = command pairs for this mimetype
2121 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
2124 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
2126 sTmp
= sPairs
->GetVerbCmd (i
);
2127 if ( sTmp
.Contains(sV
) )
2128 command
= sTmp
.AfterFirst(wxT('='));
2133 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
2137 wxString extensions
;
2138 const wxArrayString
& exts
= filetype
.GetExtensions();
2139 size_t nExts
= exts
.GetCount();
2140 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
2142 extensions
+= wxT(' ');
2144 extensions
+= exts
[nExt
];
2147 AddMimeTypeInfo(filetype
.GetMimeType(),
2149 filetype
.GetDescription());
2151 AddMailcapInfo(filetype
.GetMimeType(),
2152 filetype
.GetOpenCommand(),
2153 filetype
.GetPrintCommand(),
2155 filetype
.GetDescription());
2158 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2159 const wxString
& strExtensions
,
2160 const wxString
& strDesc
)
2162 // reading mailcap may find image/* , while
2163 // reading mime.types finds image/gif and no match is made
2164 // this means all the get functions don't work fix this
2166 wxString sTmp
= strExtensions
;
2168 wxArrayString sExts
;
2169 sTmp
.Trim().Trim(FALSE
);
2171 while (!sTmp
.empty())
2173 sExts
.Add (sTmp
.AfterLast(wxT(' ')));
2174 sTmp
= sTmp
.BeforeLast(wxT(' '));
2177 AddToMimeData (strMimeType
, strIcon
, NULL
, sExts
, strDesc
, TRUE
);
2180 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2181 const wxString
& strOpenCmd
,
2182 const wxString
& strPrintCmd
,
2183 const wxString
& strTest
,
2184 const wxString
& strDesc
)
2188 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2189 entry
->Add(wxT("open=") + strOpenCmd
);
2190 entry
->Add(wxT("print=") + strPrintCmd
);
2191 entry
->Add(wxT("test=") + strTest
);
2194 wxArrayString strExtensions
;
2196 AddToMimeData (strType
, strIcon
, entry
, strExtensions
, strDesc
, TRUE
);
2200 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2202 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2203 strFileName
.c_str());
2205 wxTextFile
file(strFileName
);
2206 #if defined(__WXGTK20__) && wxUSE_UNICODE
2207 if ( !file
.Open( wxConvUTF8
) )
2213 // the information we extract
2214 wxString strMimeType
, strDesc
, strExtensions
;
2216 size_t nLineCount
= file
.GetLineCount();
2217 const wxChar
*pc
= NULL
;
2218 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2221 // now we're at the start of the line
2222 pc
= file
[nLine
].c_str();
2225 // we didn't finish with the previous line yet
2230 while ( wxIsspace(*pc
) )
2233 // comment or blank line?
2234 if ( *pc
== wxT('#') || !*pc
) {
2235 // skip the whole line
2240 // detect file format
2241 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2242 if ( pEqualSign
== NULL
) {
2246 // first field is mime type
2247 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
2252 while ( wxIsspace(*pc
) )
2255 // take all the rest of the string
2258 // no description...
2265 // the string on the left of '=' is the field name
2266 wxString
strLHS(pc
, pEqualSign
- pc
);
2269 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2273 if ( *pc
== wxT('"') ) {
2274 // the string is quoted and ends at the matching quote
2275 pEnd
= wxStrchr(++pc
, wxT('"'));
2276 if ( pEnd
== NULL
) {
2277 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2279 strFileName
.c_str(), nLine
+ 1);
2283 // unquoted string ends at the first space or at the end of
2285 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2289 // now we have the RHS (field value)
2290 wxString
strRHS(pc
, pEnd
- pc
);
2292 // check what follows this entry
2293 if ( *pEnd
== wxT('"') ) {
2298 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2301 // if there is something left, it may be either a '\\' to continue
2302 // the line or the next field of the same entry
2303 bool entryEnded
= *pc
== wxT('\0'),
2304 nextFieldOnSameLine
= FALSE
;
2305 if ( !entryEnded
) {
2306 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2309 // now see what we got
2310 if ( strLHS
== wxT("type") ) {
2311 strMimeType
= strRHS
;
2313 else if ( strLHS
.StartsWith(wxT("desc")) ) {
2316 else if ( strLHS
== wxT("exts") ) {
2317 strExtensions
= strRHS
;
2319 else if ( strLHS
== _T("icon") )
2321 // this one is simply ignored: it usually refers to Netscape
2322 // built in icons which are useless for us anyhow
2324 else if ( !strLHS
.StartsWith(_T("x-")) )
2326 // we suppose that all fields starting with "X-" are
2327 // unregistered extensions according to the standard practice,
2328 // but it may be worth telling the user about other junk in
2329 // his mime.types file
2330 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2331 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
2334 if ( !entryEnded
) {
2335 if ( !nextFieldOnSameLine
)
2337 //else: don't reset it
2339 // as we don't reset strMimeType, the next field in this entry
2340 // will be interpreted correctly.
2346 // depending on the format (Mosaic or Netscape) either space or comma
2347 // is used to separate the extensions
2348 strExtensions
.Replace(wxT(","), wxT(" "));
2350 // also deal with the leading dot
2351 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2353 strExtensions
.erase(0, 1);
2356 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2357 strExtensions
.c_str(),
2358 strMimeType
.c_str(),
2361 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2363 // finished with this line
2370 // ----------------------------------------------------------------------------
2371 // UNIX mailcap files parsing
2372 // ----------------------------------------------------------------------------
2374 // the data for a single MIME type
2375 struct MailcapLineData
2384 wxArrayString verbs
,
2392 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= FALSE
; }
2395 // process a non-standard (i.e. not the first or second one) mailcap field
2397 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2398 const wxString
& curField
)
2400 if ( curField
.empty() )
2406 // is this something of the form foo=bar?
2407 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2410 // split "LHS = RHS" in 2
2411 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2412 rhs
= curField
.AfterFirst(wxT('='));
2414 lhs
.Trim(TRUE
); // from right
2415 rhs
.Trim(FALSE
); // from left
2417 // it might be quoted
2418 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2420 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2423 // is it a command verb or something else?
2424 if ( lhs
== wxT("test") )
2426 if ( wxSystem(rhs
) == 0 )
2429 wxLogTrace(TRACE_MIME_TEST
,
2430 wxT("Test '%s' for mime type '%s' succeeded."),
2431 rhs
.c_str(), data
.type
.c_str());
2436 wxLogTrace(TRACE_MIME_TEST
,
2437 wxT("Test '%s' for mime type '%s' failed, skipping."),
2438 rhs
.c_str(), data
.type
.c_str());
2440 data
.testfailed
= TRUE
;
2443 else if ( lhs
== wxT("desc") )
2447 else if ( lhs
== wxT("x11-bitmap") )
2451 else if ( lhs
== wxT("notes") )
2455 else // not a (recognized) special case, must be a verb (e.g. "print")
2457 data
.verbs
.Add(lhs
);
2458 data
.commands
.Add(rhs
);
2461 else // '=' not found
2463 // so it must be a simple flag
2464 if ( curField
== wxT("needsterminal") )
2466 data
.needsterminal
= TRUE
;
2468 else if ( curField
== wxT("copiousoutput"))
2470 // copiousoutput impies that the viewer is a console program
2471 data
.needsterminal
=
2472 data
.copiousoutput
= TRUE
;
2474 else if ( !IsKnownUnimportantField(curField
) )
2483 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2486 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2487 strFileName
.c_str());
2489 wxTextFile
file(strFileName
);
2490 #if defined(__WXGTK20__) && wxUSE_UNICODE
2491 if ( !file
.Open( wxConvUTF8
) )
2497 // indices of MIME types (in m_aTypes) we already found in this file
2499 // (see the comments near the end of function for the reason we need this)
2500 wxArrayInt aIndicesSeenHere
;
2502 // accumulator for the current field
2504 curField
.reserve(1024);
2506 size_t nLineCount
= file
.GetLineCount();
2507 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2509 // now we're at the start of the line
2510 const wxChar
*pc
= file
[nLine
].c_str();
2513 while ( wxIsspace(*pc
) )
2516 // comment or empty string?
2517 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2523 // what field are we currently in? The first 2 are fixed and there may
2524 // be an arbitrary number of other fields parsed by
2525 // ProcessOtherMailcapField()
2527 // the first field is the MIME type
2533 } currentToken
= Field_Type
;
2535 // the flags and field values on the current line
2536 MailcapLineData data
;
2544 // interpret the next character literally (notice that
2545 // backslash can be used for line continuation)
2546 if ( *++pc
== wxT('\0') )
2548 // fetch the next line if there is one
2549 if ( nLine
== nLineCount
- 1 )
2551 // something is wrong, bail out
2554 wxLogDebug(wxT("Mailcap file %s, line %lu: "
2555 "'\\' on the end of the last line "
2557 strFileName
.c_str(),
2558 (unsigned long)nLine
+ 1);
2562 // pass to the beginning of the next line
2563 pc
= file
[++nLine
].c_str();
2565 // skip pc++ at the end of the loop
2571 // just a normal character
2577 cont
= FALSE
; // end of line reached, exit the loop
2579 // fall through to still process this field
2582 // trim whitespaces from both sides
2583 curField
.Trim(TRUE
).Trim(FALSE
);
2585 switch ( currentToken
)
2588 data
.type
= curField
.Lower();
2589 if ( data
.type
.empty() )
2591 // I don't think that this is a valid mailcap
2592 // entry, but try to interpret it somehow
2593 data
.type
= _T('*');
2596 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2598 // we interpret "type" as "type/*"
2599 data
.type
+= wxT("/*");
2602 currentToken
= Field_OpenCmd
;
2606 data
.cmdOpen
= curField
;
2608 currentToken
= Field_Other
;
2612 if ( !ProcessOtherMailcapField(data
, curField
) )
2614 // don't flood the user with error messages if
2615 // we don't understand something in his
2616 // mailcap, but give them in debug mode because
2617 // this might be useful for the programmer
2620 wxT("Mailcap file %s, line %lu: "
2621 "unknown field '%s' for the "
2622 "MIME type '%s' ignored."),
2623 strFileName
.c_str(),
2624 (unsigned long)nLine
+ 1,
2629 else if ( data
.testfailed
)
2631 // skip this entry entirely
2635 // it already has this value
2636 //currentToken = Field_Other;
2640 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2643 // next token starts immediately after ';'
2651 // continue in the same line
2655 // we read the entire entry, check what have we got
2656 // ------------------------------------------------
2658 // check that we really read something reasonable
2659 if ( currentToken
< Field_Other
)
2661 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2663 strFileName
.c_str(), nLine
+ 1);
2668 // if the test command failed, it's as if the entry were not there at
2670 if ( data
.testfailed
)
2675 // support for flags:
2676 // 1. create an xterm for 'needsterminal'
2677 // 2. append "| $PAGER" for 'copiousoutput'
2679 // Note that the RFC says that having both needsterminal and
2680 // copiousoutput is probably a mistake, so it seems that running
2681 // programs with copiousoutput inside an xterm as it is done now
2682 // is a bad idea (FIXME)
2683 if ( data
.copiousoutput
)
2685 const wxChar
*p
= wxGetenv(_T("PAGER"));
2686 data
.cmdOpen
<< _T(" | ") << (p
? p
: _T("more"));
2689 if ( data
.needsterminal
)
2691 data
.cmdOpen
= wxString::Format(_T("xterm -e sh -c '%s'"),
2692 data
.cmdOpen
.c_str());
2695 if ( !data
.cmdOpen
.empty() )
2697 data
.verbs
.Insert(_T("open"), 0);
2698 data
.commands
.Insert(data
.cmdOpen
, 0);
2701 // we have to decide whether the new entry should replace any entries
2702 // for the same MIME type we had previously found or not
2705 // the fall back entries have the lowest priority, by definition
2712 // have we seen this one before?
2713 int nIndex
= m_aTypes
.Index(data
.type
);
2715 // and if we have, was it in this file?
2716 overwrite
= nIndex
== wxNOT_FOUND
||
2717 aIndicesSeenHere
.Index(nIndex
) != wxNOT_FOUND
;
2720 wxLogTrace(TRACE_MIME
, _T("mailcap %s: %s [%s]"),
2721 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2722 overwrite
? _T("replace") : _T("add"));
2724 int n
= AddToMimeData
2728 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2729 wxArrayString() /* extensions */,
2736 aIndicesSeenHere
.Add(n
);
2743 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2750 size_t count
= m_aTypes
.GetCount();
2751 for ( size_t n
= 0; n
< count
; n
++ )
2753 // don't return template types from here (i.e. anything containg '*')
2755 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
2757 mimetypes
.Add(type
);
2761 return mimetypes
.GetCount();
2764 // ----------------------------------------------------------------------------
2765 // writing to MIME type files
2766 // ----------------------------------------------------------------------------
2768 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2770 wxArrayString sMimeTypes
;
2771 ft
->GetMimeTypes (sMimeTypes
);
2775 for (i
= 0; i
< sMimeTypes
.GetCount(); i
++)
2777 sMime
= sMimeTypes
.Item(i
);
2778 int nIndex
= m_aTypes
.Index (sMime
);
2779 if ( nIndex
== wxNOT_FOUND
)
2781 // error if we get here ??
2786 WriteMimeInfo(nIndex
, TRUE
);
2787 m_aTypes
.RemoveAt(nIndex
);
2788 m_aEntries
.RemoveAt(nIndex
);
2789 m_aExtensions
.RemoveAt(nIndex
);
2790 m_aDescriptions
.RemoveAt(nIndex
);
2791 m_aIcons
.RemoveAt(nIndex
);
2794 // check data integrity
2795 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2796 m_aTypes
.Count() == m_aExtensions
.Count() &&
2797 m_aTypes
.Count() == m_aIcons
.Count() &&
2798 m_aTypes
.Count() == m_aDescriptions
.Count() );
2803 // ----------------------------------------------------------------------------
2804 // private functions
2805 // ----------------------------------------------------------------------------
2807 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2809 static const wxChar
*knownFields
[] =
2811 _T("x-mozilla-flags"),
2813 _T("textualnewlines"),
2816 wxString field
= fieldAll
.BeforeFirst(_T('='));
2817 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2819 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2827 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE