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
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"
43 #if wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE
46 #include "wx/string.h"
52 #include "wx/dynarray.h"
53 #include "wx/confbase.h"
56 #include "wx/textfile.h"
59 #include "wx/tokenzr.h"
60 #include "wx/iconloc.h"
61 #include "wx/filename.h"
63 #include "wx/unix/mimetype.h"
65 // other standard headers
69 /* silence warnings for comparing unsigned int's <0 */
70 # pragma message disable unscomzer
73 // wxMimeTypeCommands stores the verbs defined for the given MIME type with
75 class wxMimeTypeCommands
78 wxMimeTypeCommands() {}
80 wxMimeTypeCommands(const wxArrayString
& verbs
,
81 const wxArrayString
& commands
)
87 // add a new verb with the command or replace the old value
88 void AddOrReplaceVerb(const wxString
& verb
, const wxString
& cmd
)
90 int n
= m_verbs
.Index(verb
, false /* ignore case */);
91 if ( n
== wxNOT_FOUND
)
102 void Add(const wxString
& s
)
104 m_verbs
.Add(s
.BeforeFirst(wxT('=')));
105 m_commands
.Add(s
.AfterFirst(wxT('=')));
108 // access the commands
109 size_t GetCount() const { return m_verbs
.GetCount(); }
110 const wxString
& GetVerb(size_t n
) const { return m_verbs
[n
]; }
111 const wxString
& GetCmd(size_t n
) const { return m_commands
[n
]; }
113 bool HasVerb(const wxString
& verb
) const
114 { return m_verbs
.Index(verb
) != wxNOT_FOUND
; }
116 wxString
GetCommandForVerb(const wxString
& verb
, size_t *idx
= NULL
) const
120 int n
= m_verbs
.Index(verb
);
121 if ( n
!= wxNOT_FOUND
)
123 s
= m_commands
[(size_t)n
];
131 // get a "verb=command" string
132 wxString
GetVerbCmd(size_t n
) const
134 return m_verbs
[n
] + wxT('=') + m_commands
[n
];
138 wxArrayString m_verbs
;
139 wxArrayString m_commands
;
142 // this class extends wxTextFile
145 class wxMimeTextFile
: public wxTextFile
149 wxMimeTextFile () : wxTextFile () {};
150 wxMimeTextFile(const wxString
& strFile
) : wxTextFile(strFile
) {};
152 int pIndexOf(const wxString
& sSearch
, bool bIncludeComments
= false, int iStart
= 0)
155 int nResult
= wxNOT_FOUND
;
156 if (i
>= GetLineCount())
159 wxString sTest
= sSearch
;
163 if (bIncludeComments
)
165 while ( i
< GetLineCount() )
169 if (sLine
.Contains(sTest
))
177 while ( (i
< GetLineCount()) )
181 if ( ! sLine
.StartsWith(wxT("#")))
183 if (sLine
.Contains(sTest
))
194 bool CommentLine(int nIndex
)
198 if (nIndex
>= (int)GetLineCount() )
201 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
205 bool CommentLine(const wxString
& sTest
)
207 int nIndex
= pIndexOf(sTest
);
210 if (nIndex
>= (int)GetLineCount() )
213 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
217 wxString
GetVerb(size_t i
)
219 if (i
> GetLineCount() )
220 return wxEmptyString
;
222 wxString sTmp
= GetLine(i
).BeforeFirst(wxT('='));
226 wxString
GetCmd(size_t i
)
228 if (i
> GetLineCount() )
229 return wxEmptyString
;
231 wxString sTmp
= GetLine(i
).AfterFirst(wxT('='));
236 // in case we're compiling in non-GUI mode
237 class WXDLLEXPORT wxIcon
;
239 // ----------------------------------------------------------------------------
241 // ----------------------------------------------------------------------------
243 // MIME code tracing mask
244 #define TRACE_MIME wxT("mime")
246 // give trace messages about the results of mailcap tests
247 #define TRACE_MIME_TEST wxT("mimetest")
249 // ----------------------------------------------------------------------------
251 // ----------------------------------------------------------------------------
253 // there are some fields which we don't understand but for which we don't give
254 // warnings as we know that they're not important - this function is used to
256 static bool IsKnownUnimportantField(const wxString
& field
);
258 // ----------------------------------------------------------------------------
260 // ----------------------------------------------------------------------------
263 // This class uses both mailcap and mime.types to gather information about file
266 // The information about mailcap file was extracted from metamail(1) sources
267 // and documentation and subsequently revised when I found the RFC 1524
270 // Format of mailcap file: spaces are ignored, each line is either a comment
271 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
272 // A backslash can be used to quote semicolons and newlines (and, in fact,
273 // anything else including itself).
275 // The first field is always the MIME type in the form of type/subtype (see RFC
276 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
277 // "type" which means the same as "type/*", although I'm not sure whether this
280 // The second field is always the command to run. It is subject to
281 // parameter/filename expansion described below.
283 // All the following fields are optional and may not be present at all. If
284 // they're present they may appear in any order, although each of them should
285 // appear only once. The optional fields are the following:
286 // * notes=xxx is an uninterpreted string which is silently ignored
287 // * test=xxx is the command to be used to determine whether this mailcap line
288 // applies to our data or not. The RHS of this field goes through the
289 // parameter/filename expansion (as the 2nd field) and the resulting string
290 // is executed. The line applies only if the command succeeds, i.e. returns 0
292 // * print=xxx is the command to be used to print (and not view) the data of
293 // this type (parameter/filename expansion is done here too)
294 // * edit=xxx is the command to open/edit the data of this type
295 // * needsterminal means that a new interactive console must be created for
297 // * copiousoutput means that the viewer doesn't interact with the user but
298 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
299 // good example), thus it might be a good idea to use some kind of paging
301 // * textualnewlines means not to perform CR/LF translation (not honored)
302 // * compose and composetyped fields are used to determine the program to be
303 // called to create a new message pert in the specified format (unused).
305 // Parameter/filename expansion:
306 // * %s is replaced with the (full) file name
307 // * %t is replaced with MIME type/subtype of the entry
308 // * for multipart type only %n is replaced with the nnumber of parts and %F is
309 // replaced by an array of (content-type, temporary file name) pairs for all
310 // message parts (TODO)
311 // * %{parameter} is replaced with the value of parameter taken from
312 // Content-type header line of the message.
315 // There are 2 possible formats for mime.types file, one entry per line (used
316 // for global mime.types and called Mosaic format) and "expanded" format where
317 // an entry takes multiple lines (used for users mime.types and called
320 // For both formats spaces are ignored and lines starting with a '#' are
321 // comments. Each record has one of two following forms:
322 // a) for "brief" format:
323 // <mime type> <space separated list of extensions>
324 // b) for "expanded" format:
325 // type=<mime type> BACKSLASH
326 // desc="<description>" BACKSLASH
327 // exts="<comma separated list of extensions>"
329 // (where BACKSLASH is a literal '\\' which we can't put here because cpp
332 // We try to autodetect the format of mime.types: if a non-comment line starts
333 // with "type=" we assume the second format, otherwise the first one.
335 // there may be more than one entry for one and the same mime type, to
336 // choose the right one we have to run the command specified in the test
337 // field on our data.
339 // ----------------------------------------------------------------------------
341 // ----------------------------------------------------------------------------
343 // GNOME stores the info we're interested in in several locations:
344 // 1. xxx.keys files under /usr/share/mime-info
345 // 2. xxx.keys files under ~/.gnome/mime-info
347 // The format of xxx.keys file is the following:
352 // with blank lines separating the entries and indented lines starting with
353 // TABs. We're interested in the field icon-filename whose value is the path
354 // containing the icon.
356 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
357 // just before the field name.
360 bool wxMimeTypesManagerImpl::CheckGnomeDirsExist()
363 wxGetHomeDir( &gnomedir
);
364 wxString sTmp
= gnomedir
;
365 sTmp
= sTmp
+ wxT("/.gnome");
366 if (! wxDir::Exists( sTmp
) )
368 if (!wxMkdir( sTmp
))
370 wxLogError(wxT("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(wxT("Failed to create directory %s/mime-info."), sTmp
.c_str());
388 bool wxMimeTypesManagerImpl::WriteGnomeKeyFile(int index
, bool delete_index
)
391 wxGetHomeDir( &gnomedir
);
393 wxMimeTextFile
outfile( gnomedir
+ wxT("/.gnome/mime-info/user.keys"));
394 // if this fails probably Gnome is not installed ??
395 // create it anyway as a private mime store
397 #if defined(__WXGTK20__) && wxUSE_UNICODE
398 if (! outfile
.Open( wxConvUTF8
) )
400 if (! outfile
.Open() )
405 if (!CheckGnomeDirsExist() )
411 wxString sTmp
, strType
= m_aTypes
[index
];
412 int nIndex
= outfile
.pIndexOf(strType
);
413 if ( nIndex
== wxNOT_FOUND
)
415 outfile
.AddLine( strType
+ wxT(':') );
416 // see file:/usr/doc/gnome-libs-devel-1.0.40/devel-docs/mime-type-handling.txt
417 // as this does not deal with internationalisation
418 // wxT( "\t[en_US]") + verb + wxT ('=') + cmd + wxT(" %f");
419 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
420 size_t count
= entries
->GetCount();
421 for ( size_t i
= 0; i
< count
; i
++ )
423 sTmp
= entries
->GetVerbCmd( i
);
424 sTmp
.Replace( wxT("%s"), wxT("%f") );
425 sTmp
= wxT( "\t") + sTmp
;
426 outfile
.AddLine( sTmp
);
429 //for international use do something like this
430 //outfile.AddLine( wxString( "\t[en_US]icon-filename=") + cmd );
431 outfile
.AddLine( wxT( "\ticon-filename=") + m_aIcons
[index
] );
436 outfile
.CommentLine(nIndex
);
438 wxMimeTypeCommands sOld
;
439 size_t nOld
= nIndex
+ 1;
440 bool oldEntryEnd
= false;
441 while ( (nOld
< outfile
.GetLineCount() ) && !oldEntryEnd
)
443 sTmp
= outfile
.GetLine(nOld
);
444 if ( (sTmp
[0u] == wxT('\t')) || (sTmp
[0u] == wxT('#')) )
446 // we have another line to deal with
447 outfile
.CommentLine(nOld
);
450 // add the line to our store
451 if ((!delete_index
) && (sTmp
[0u] == wxT('\t')))
454 // next mimetpye ?? or blank line
459 // list of entries in our data; these should all be in sOld,
460 // though sOld may also contain other entries , eg flags
463 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
465 for (i
=0; i
< entries
->GetCount(); i
++)
467 // replace any entries in sold that match verbs we know
468 sOld
.AddOrReplaceVerb( entries
->GetVerb(i
), entries
->GetCmd(i
) );
471 //sOld should also contain the icon
472 if ( !m_aIcons
[index
].empty() )
473 sOld
.AddOrReplaceVerb( wxT("icon-filename"), m_aIcons
[index
] );
475 for (i
=0; i
< sOld
.GetCount(); i
++)
477 sTmp
= sOld
.GetVerbCmd( i
);
478 sTmp
.Replace( wxT("%s"), wxT("%f") );
479 sTmp
= wxT("\t") + sTmp
;
481 outfile
.InsertLine( sTmp
, nIndex
);
486 bool bTmp
= outfile
.Write();
490 bool wxMimeTypesManagerImpl::WriteGnomeMimeFile(int index
, bool delete_index
)
493 wxGetHomeDir( &gnomedir
);
495 wxMimeTextFile
outfile( gnomedir
+ wxT("/.gnome/mime-info/user.mime") );
496 // if this fails probably Gnome is not installed ??
497 // create it anyway as a private mime store
498 if (! outfile
.Open() )
502 if (!CheckGnomeDirsExist() )
508 wxString strType
= m_aTypes
[index
];
509 int nIndex
= outfile
.pIndexOf(strType
);
510 if ( nIndex
== wxNOT_FOUND
)
512 outfile
.AddLine( strType
);
513 outfile
.AddLine( wxT("\text:") + m_aExtensions
.Item(index
) );
519 outfile
.CommentLine(nIndex
);
520 outfile
.CommentLine(nIndex
+ 1);
524 // check for next line being the right one to replace ??
525 wxString sOld
= outfile
.GetLine(nIndex
+ 1);
526 if (sOld
.Contains( wxT("\text: ") ))
528 outfile
.GetLine(nIndex
+ 1) = wxT("\text: ") + m_aExtensions
.Item(index
);
532 outfile
.InsertLine( wxT("\text: ") + m_aExtensions
.Item(index
), nIndex
+ 1 );
537 bool bTmp
= outfile
.Write();
541 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString
& filename
,
542 const wxArrayString
& dirs
)
544 wxTextFile
textfile(filename
);
545 #if defined(__WXGTK20__) && wxUSE_UNICODE
546 if ( !textfile
.Open(wxConvUTF8
) )
548 if ( !textfile
.Open() )
552 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
555 // values for the entry being parsed
556 wxString curMimeType
, curIconFile
;
557 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
559 // these are always empty in this file
560 wxArrayString strExtensions
;
564 size_t nLineCount
= textfile
.GetLineCount();
566 while ( nLine
< nLineCount
)
568 pc
= textfile
[nLine
].c_str();
569 if ( *pc
!= wxT('#') )
572 wxLogTrace(TRACE_MIME
, wxT("--- Reading from Gnome file %s '%s' ---"),
573 filename
.c_str(), pc
);
576 if (sTmp
.Contains(wxT("=")) )
578 if (sTmp
.Contains( wxT("icon-filename=") ) )
581 curIconFile
= sTmp
.AfterFirst(wxT('='));
583 else if (sTmp
.Contains( wxT("icon_filename=") ) )
586 curIconFile
= sTmp
.AfterFirst(wxT('='));
588 if (!wxFileExists(curIconFile
))
590 size_t nDirs
= dirs
.GetCount();
591 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
593 wxFileName
newFile( curIconFile
);
594 newFile
.SetPath( dirs
[nDir
] );
595 newFile
.AppendDir( wxT("pixmaps") );
596 newFile
.AppendDir( wxT("document-icons") );
597 newFile
.SetExt( wxT("png") );
598 if (newFile
.FileExists())
599 curIconFile
= newFile
.GetFullPath();
603 else //: some other field,
605 //may contain lines like this (RH7)
606 // \t[lang]open.tex."TeX this file"=tex %f
607 // \tflags.tex.flags=needsterminal
608 // \topen.latex."LaTeX this file"=latex %f
609 // \tflags.latex.flags=needsterminal
613 // \topen.convert.Convert file to Postscript=dvips %f -o `basename %f .dvi`.ps
615 // for now ignore lines with flags in...FIX
616 sTmp
= sTmp
.AfterLast(wxT(']'));
617 sTmp
= sTmp
.AfterLast(wxT('\t'));
618 sTmp
.Trim(false).Trim();
619 if (0 == sTmp
.Replace( wxT("%f"), wxT("%s") ))
620 sTmp
= sTmp
+ wxT(" %s");
624 } // emd of has an equals sign
627 // not a comment and not an equals sign
628 if (sTmp
.Contains(wxT('/')))
630 // this is the start of the new mimetype
631 // overwrite any existing data
632 if (! curMimeType
.empty())
634 AddToMimeData( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
636 // now get ready for next bit
637 entry
= new wxMimeTypeCommands
;
640 curMimeType
= sTmp
.BeforeFirst(wxT(':'));
643 } // end of not a comment
645 // ignore blank lines
647 } // end of while, save any data
649 if (! curMimeType
.empty())
650 AddToMimeData( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
653 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString
& filename
)
655 wxTextFile
textfile(filename
);
656 if ( !textfile
.Open() )
659 wxLogTrace(TRACE_MIME
,
660 wxT("--- Opened Gnome file %s ---"),
663 // values for the entry being parsed
664 wxString curMimeType
, curExtList
;
667 size_t nLineCount
= textfile
.GetLineCount();
668 for ( size_t nLine
= 0; /* nothing */; nLine
++ )
670 if ( nLine
< nLineCount
)
672 pc
= textfile
[nLine
].c_str();
673 if ( *pc
== wxT('#') )
681 // so that we will fall into the "if" below
688 if ( !curMimeType
.empty() && !curExtList
.empty() )
690 wxLogTrace(TRACE_MIME
,
691 wxT("--- At end of Gnome file finding mimetype %s ---"),
692 curMimeType
.c_str());
694 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
699 // the end: this can only happen if nLine == nLineCount
708 // what do we have here?
709 if ( *pc
== wxT('\t') )
711 // this is a field=value ling
712 pc
++; // skip leading TAB
714 static const int lenField
= 5; // strlen("ext: ")
715 if ( wxStrncmp(pc
, wxT("ext: "), lenField
) == 0 )
717 // skip it and take everything left until the end of line
718 curExtList
= pc
+ lenField
;
720 //else: some other field, we don't care
724 // this is the start of the new section
725 wxLogTrace(TRACE_MIME
,
726 wxT("--- In Gnome file finding mimetype %s ---"),
727 curMimeType
.c_str());
729 if (! curMimeType
.empty())
730 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
734 while ( *pc
!= wxT(':') && *pc
!= wxT('\0') )
736 curMimeType
+= *pc
++;
743 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
744 const wxString
& dirbase
, const wxArrayString
& dirs
)
746 wxASSERT_MSG( !dirbase
.empty() && !wxEndsWithPathSeparator(dirbase
),
747 wxT("base directory shouldn't end with a slash") );
749 wxString dirname
= dirbase
;
750 dirname
<< wxT("/mime-info");
752 if ( !wxDir::Exists(dirname
) )
756 if ( !dir
.IsOpened() )
759 // we will concatenate it with filename to get the full path below
765 cont
= dir
.GetFirst(&filename
, wxT("*.mime"), wxDIR_FILES
);
768 LoadGnomeMimeTypesFromMimeFile(dirname
+ filename
);
770 cont
= dir
.GetNext(&filename
);
773 cont
= dir
.GetFirst(&filename
, wxT("*.keys"), wxDIR_FILES
);
776 LoadGnomeDataFromKeyFile(dirname
+ filename
, dirs
);
778 cont
= dir
.GetNext(&filename
);
781 // FIXME: Hack alert: We scan all icons and deduce the
782 // mime-type from the file name.
784 dirname
<< wxT("/pixmaps/document-icons");
786 // these are always empty in this file
787 wxArrayString strExtensions
;
790 if ( !wxDir::Exists(dirname
) )
792 // Just test for default GPE dir also
793 dirname
= wxT("/usr/share/gpe/pixmaps/default/filemanager/document-icons");
795 if ( !wxDir::Exists(dirname
) )
799 wxDir
dir2( dirname
);
801 cont
= dir2
.GetFirst(&filename
, wxT("gnome-*.png"), wxDIR_FILES
);
804 wxString mimeType
= filename
;
805 mimeType
.Remove( 0, 6 ); // remove "gnome-"
806 mimeType
.Remove( mimeType
.Len() - 4, 4 ); // remove ".png"
807 int pos
= mimeType
.Find( wxT("-") );
808 if (pos
!= wxNOT_FOUND
)
810 mimeType
.SetChar( pos
, wxT('/') );
811 wxString iconFile
= dirname
;
812 iconFile
<< wxT("/");
813 iconFile
<< filename
;
814 AddToMimeData( mimeType
, iconFile
, NULL
, strExtensions
, strDesc
, true );
817 cont
= dir2
.GetNext(&filename
);
821 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString
& sExtraDir
)
825 wxString gnomedir
= wxGetenv( wxT("GNOMEDIR") );
826 if (!gnomedir
.empty())
828 gnomedir
<< wxT("/share");
829 dirs
.Add( gnomedir
);
832 dirs
.Add(wxT("/usr/share"));
833 dirs
.Add(wxT("/usr/local/share"));
835 gnomedir
= wxGetHomeDir();
836 gnomedir
<< wxT("/.gnome");
837 dirs
.Add( gnomedir
);
839 if (!sExtraDir
.empty())
840 dirs
.Add( sExtraDir
);
842 size_t nDirs
= dirs
.GetCount();
843 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
845 LoadGnomeMimeFilesFromDir(dirs
[nDir
], dirs
);
849 // ----------------------------------------------------------------------------
851 // ----------------------------------------------------------------------------
854 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
855 // may be found in either of the following locations
857 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
858 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
860 // The format of a .kdelnk file is almost the same as the one used by
861 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
862 // value for the entry "Type"
864 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
865 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
867 bool wxMimeTypesManagerImpl::CheckKDEDirsExist( const wxString
&sOK
, const wxString
&sTest
)
871 return wxDir::Exists(sOK
);
875 wxString sStart
= sOK
+ wxT("/") + sTest
.BeforeFirst(wxT('/'));
876 if (!wxDir::Exists(sStart
))
878 wxString sEnd
= sTest
.AfterFirst(wxT('/'));
879 return CheckKDEDirsExist(sStart
, sEnd
);
883 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index
, bool delete_index
)
885 wxMimeTextFile appoutfile
, mimeoutfile
;
886 wxString sHome
= wxGetHomeDir();
887 wxString sTmp
= wxT(".kde/share/mimelnk/");
888 wxString sMime
= m_aTypes
[index
];
889 CheckKDEDirsExist(sHome
, sTmp
+ sMime
.BeforeFirst(wxT('/')) );
890 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
+ wxT(".kdelnk");
893 bool bMimeExists
= mimeoutfile
.Open(sTmp
);
896 bTemp
= mimeoutfile
.Create(sTmp
);
897 // some unknown error eg out of disk space
902 sTmp
= wxT(".kde/share/applnk/");
903 CheckKDEDirsExist(sHome
, sTmp
+ sMime
.AfterFirst(wxT('/')) );
904 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
.AfterFirst(wxT('/')) + wxT(".kdelnk");
907 bAppExists
= appoutfile
.Open(sTmp
);
910 bTemp
= appoutfile
.Create(sTmp
);
911 // some unknown error eg out of disk space
916 // fixed data; write if new file
919 mimeoutfile
.AddLine(wxT("#KDE Config File"));
920 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
921 mimeoutfile
.AddLine(wxT("Version=1.0"));
922 mimeoutfile
.AddLine(wxT("Type=MimeType"));
923 mimeoutfile
.AddLine(wxT("MimeType=") + sMime
);
928 mimeoutfile
.AddLine(wxT("#KDE Config File"));
929 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
930 appoutfile
.AddLine(wxT("Version=1.0"));
931 appoutfile
.AddLine(wxT("Type=Application"));
932 appoutfile
.AddLine(wxT("MimeType=") + sMime
+ wxT(';'));
937 mimeoutfile
.CommentLine(wxT("Comment="));
939 mimeoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
940 appoutfile
.CommentLine(wxT("Name="));
942 appoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
944 sTmp
= m_aIcons
[index
];
945 // we can either give the full path, or the shortfilename if its in
946 // one of the directories we search
947 mimeoutfile
.CommentLine(wxT("Icon=") );
949 mimeoutfile
.AddLine(wxT("Icon=") + sTmp
);
950 appoutfile
.CommentLine(wxT("Icon=") );
952 appoutfile
.AddLine(wxT("Icon=") + sTmp
);
954 sTmp
= wxT(" ") + m_aExtensions
[index
];
956 wxStringTokenizer
tokenizer(sTmp
, wxT(" "));
957 sTmp
= wxT("Patterns=");
958 mimeoutfile
.CommentLine(sTmp
);
959 while ( tokenizer
.HasMoreTokens() )
961 // holds an extension; need to change it to *.ext;
962 wxString e
= wxT("*.") + tokenizer
.GetNextToken() + wxT(";");
967 mimeoutfile
.AddLine(sTmp
);
969 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
970 // if we don't find open just have an empty string ... FIX this
971 sTmp
= entries
->GetCommandForVerb(wxT("open"));
972 sTmp
.Replace( wxT("%s"), wxT("%f") );
974 mimeoutfile
.CommentLine(wxT("DefaultApp=") );
976 mimeoutfile
.AddLine(wxT("DefaultApp=") + sTmp
);
978 sTmp
.Replace( wxT("%f"), wxT("") );
979 appoutfile
.CommentLine(wxT("Exec="));
981 appoutfile
.AddLine(wxT("Exec=") + sTmp
);
983 if (entries
->GetCount() > 1)
985 //other actions as well as open
989 if (mimeoutfile
.Write())
992 if (appoutfile
.Write())
999 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString
& dirbase
,
1000 const wxString
& subdir
,
1001 const wxString
& filename
,
1002 const wxArrayString
& icondirs
)
1004 wxMimeTextFile file
;
1005 if ( !file
.Open(dirbase
+ filename
) )
1008 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
1009 (dirbase
+ filename
).c_str());
1011 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
1012 wxArrayString sExts
;
1013 wxString mimetype
, mime_desc
, strIcon
;
1015 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
1016 if (nIndex
== wxNOT_FOUND
)
1018 // construct mimetype from the directory name and the basename of the
1019 // file (it always has .kdelnk extension)
1020 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
1023 mimetype
= file
.GetCmd(nIndex
);
1025 // first find the description string: it is the value in either "Comment="
1026 // line or "Comment[<locale_name>]=" one
1027 nIndex
= wxNOT_FOUND
;
1032 wxLocale
*locale
= wxGetLocale();
1035 // try "Comment[locale name]" first
1036 comment
<< wxT("Comment[") + locale
->GetName() + wxT("]=");
1037 nIndex
= file
.pIndexOf(comment
);
1041 if ( nIndex
== wxNOT_FOUND
)
1043 comment
= wxT("Comment=");
1044 nIndex
= file
.pIndexOf(comment
);
1047 if ( nIndex
!= wxNOT_FOUND
)
1048 mime_desc
= file
.GetCmd(nIndex
);
1049 //else: no description
1051 // next find the extensions
1052 wxString mime_extension
;
1054 nIndex
= file
.pIndexOf(wxT("Patterns="));
1055 if ( nIndex
!= wxNOT_FOUND
)
1057 wxString exts
= file
.GetCmd(nIndex
);
1059 wxStringTokenizer
tokenizer(exts
, wxT(";"));
1060 while ( tokenizer
.HasMoreTokens() )
1062 wxString e
= tokenizer
.GetNextToken();
1064 // don't support too difficult patterns
1065 if ( e
.Left(2) != wxT("*.") )
1068 if ( !mime_extension
.empty() )
1070 // separate from the previous ext
1071 mime_extension
<< wxT(' ');
1074 mime_extension
<< e
.Mid(2);
1078 sExts
.Add(mime_extension
);
1080 // ok, now we can take care of icon:
1082 nIndex
= file
.pIndexOf(wxT("Icon="));
1083 if ( nIndex
!= wxNOT_FOUND
)
1085 strIcon
= file
.GetCmd(nIndex
);
1087 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
1089 // it could be the real path, but more often a short name
1090 if (!wxFileExists(strIcon
))
1092 // icon is just the short name
1093 if ( !strIcon
.empty() )
1095 // we must check if the file exists because it may be stored
1096 // in many locations, at least ~/.kde and $KDEDIR
1097 size_t nDir
, nDirs
= icondirs
.GetCount();
1098 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
1100 wxFileName
fnameIcon( strIcon
);
1101 wxFileName
fname( icondirs
[nDir
], fnameIcon
.GetName() );
1102 fname
.SetExt( wxT("png") );
1103 if (fname
.FileExists())
1105 strIcon
= fname
.GetFullPath();
1106 wxLogTrace(TRACE_MIME
, wxT(" iconfile %s"), strIcon
.c_str());
1114 // now look for lines which know about the application
1115 // exec= or DefaultApp=
1117 nIndex
= file
.pIndexOf(wxT("DefaultApp"));
1119 if ( nIndex
== wxNOT_FOUND
)
1121 // no entry try exec
1122 nIndex
= file
.pIndexOf(wxT("Exec"));
1125 if ( nIndex
!= wxNOT_FOUND
)
1127 // we expect %f; others including %F and %U and %u are possible
1128 wxString sTmp
= file
.GetCmd(nIndex
);
1129 if (0 == sTmp
.Replace( wxT("%f"), wxT("%s") ))
1130 sTmp
= sTmp
+ wxT(" %s");
1131 entry
->AddOrReplaceVerb(wxString(wxT("open")), sTmp
);
1134 AddToMimeData(mimetype
, strIcon
, entry
, sExts
, mime_desc
);
1137 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString
& dirbase
,
1138 const wxString
& subdir
,
1139 const wxArrayString
& icondirs
)
1141 wxString dirname
= dirbase
;
1144 if ( !dir
.IsOpened() )
1147 wxLogTrace(TRACE_MIME
, wxT("--- Loading from KDE directory %s ---"),
1150 dirname
+= wxT('/');
1153 bool cont
= dir
.GetFirst(&filename
, wxT("*.kdelnk"), wxDIR_FILES
);
1156 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1158 cont
= dir
.GetNext(&filename
);
1161 // new standard for Gnome and KDE
1162 cont
= dir
.GetFirst(&filename
, wxT("*.desktop"), wxDIR_FILES
);
1165 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1167 cont
= dir
.GetNext(&filename
);
1171 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString
& dirbase
,
1172 const wxArrayString
& icondirs
)
1174 wxASSERT_MSG( !dirbase
.empty() && !wxEndsWithPathSeparator(dirbase
),
1175 wxT("base directory shouldn't end with a slash") );
1177 wxString dirname
= dirbase
;
1178 dirname
<< wxT("/mimelnk");
1180 if ( !wxDir::Exists(dirname
) )
1184 if ( !dir
.IsOpened() )
1187 // we will concatenate it with dir name to get the full path below
1188 dirname
+= wxT('/');
1191 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
1194 LoadKDELinksForMimeType(dirname
, subdir
, icondirs
);
1196 cont
= dir
.GetNext(&subdir
);
1200 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString
& sExtraDir
)
1203 wxArrayString icondirs
;
1205 // FIXME: This code is heavily broken. There are three bugs in it:
1206 // 1) it uses only KDEDIR, which is deprecated, instead of using
1207 // list of paths from KDEDIRS and using KDEDIR only if KDEDIRS
1209 // 2) it doesn't look into ~/.kde/share/config/kdeglobals where
1210 // user's settings are stored and thus *ignores* user's settings
1211 // instead of respecting them
1212 // 3) it "tries to guess KDEDIR" and "tries a few likely theme
1213 // names", both of which is completely arbitrary; instead, the
1214 // code should give up if KDEDIR(S) is not set and/or the icon
1215 // theme cannot be determined, because it means that the user is
1216 // not using KDE (and thus is not interested in KDE icons anyway)
1218 // the variable $KDEDIR is set when KDE is running
1219 wxString kdedir
= wxGetenv( wxT("KDEDIR") );
1221 if (!kdedir
.empty())
1223 // $(KDEDIR)/share/config/kdeglobals holds info
1224 // the current icons theme
1225 wxFileName
configFile( kdedir
, wxEmptyString
);
1226 configFile
.AppendDir( wxT("share") );
1227 configFile
.AppendDir( wxT("config") );
1228 configFile
.SetName( wxT("kdeglobals") );
1231 if (configFile
.FileExists() && config
.Open(configFile
.GetFullPath()))
1233 // $(KDEDIR)/share/config -> $(KDEDIR)/share
1234 configFile
.RemoveDir( configFile
.GetDirCount() - 1 );
1235 // $(KDEDIR)/share/ -> $(KDEDIR)/share/icons
1236 configFile
.AppendDir( wxT("icons") );
1239 wxString
theme(wxT("default.kde"));
1240 size_t cnt
= config
.GetLineCount();
1241 for (size_t i
= 0; i
< cnt
; i
++)
1243 if (config
[i
].StartsWith(wxT("Theme="), &theme
/*rest*/))
1247 configFile
.AppendDir(theme
);
1251 // $(KDEDIR)/share/config -> $(KDEDIR)/share
1252 configFile
.RemoveDir( configFile
.GetDirCount() - 1 );
1254 // $(KDEDIR)/share/ -> $(KDEDIR)/share/icons
1255 configFile
.AppendDir( wxT("icons") );
1257 // $(KDEDIR)/share/icons -> $(KDEDIR)/share/icons/default.kde
1258 configFile
.AppendDir( wxT("default.kde") );
1261 configFile
.SetName( wxEmptyString
);
1262 configFile
.AppendDir( wxT("32x32") );
1263 configFile
.AppendDir( wxT("mimetypes") );
1265 // Just try a few likely icons theme names
1267 int pos
= configFile
.GetDirCount() - 3;
1269 if (!wxDir::Exists(configFile
.GetPath()))
1271 configFile
.RemoveDir( pos
);
1272 configFile
.InsertDir( pos
, wxT("default.kde") );
1275 if (!wxDir::Exists(configFile
.GetPath()))
1277 configFile
.RemoveDir( pos
);
1278 configFile
.InsertDir( pos
, wxT("default") );
1281 if (!wxDir::Exists(configFile
.GetPath()))
1283 configFile
.RemoveDir( pos
);
1284 configFile
.InsertDir( pos
, wxT("crystalsvg") );
1287 if (!wxDir::Exists(configFile
.GetPath()))
1289 configFile
.RemoveDir( pos
);
1290 configFile
.InsertDir( pos
, wxT("crystal") );
1293 if (wxDir::Exists(configFile
.GetPath()))
1294 icondirs
.Add( configFile
.GetFullPath() );
1297 // settings in ~/.kde have maximal priority
1298 dirs
.Add(wxGetHomeDir() + wxT("/.kde/share"));
1299 icondirs
.Add(wxGetHomeDir() + wxT("/.kde/share/icons/"));
1303 dirs
.Add( wxString(kdedir
) + wxT("/share") );
1304 icondirs
.Add( wxString(kdedir
) + wxT("/share/icons/") );
1308 // try to guess KDEDIR
1309 dirs
.Add(wxT("/usr/share"));
1310 dirs
.Add(wxT("/opt/kde/share"));
1311 icondirs
.Add(wxT("/usr/share/icons/"));
1312 icondirs
.Add(wxT("/usr/X11R6/share/icons/")); // Debian/Corel linux
1313 icondirs
.Add(wxT("/opt/kde/share/icons/"));
1316 if (!sExtraDir
.empty())
1317 dirs
.Add(sExtraDir
);
1318 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1320 size_t nDirs
= dirs
.GetCount();
1321 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1323 LoadKDELinkFilesFromDir(dirs
[nDir
], icondirs
);
1327 // ----------------------------------------------------------------------------
1328 // wxFileTypeImpl (Unix)
1329 // ----------------------------------------------------------------------------
1331 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1335 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1337 sTmp
= m_manager
->GetCommand( verb
, m_index
[i
] );
1341 return wxFileType::ExpandCommand(sTmp
, params
);
1344 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
1348 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1350 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1359 iconLoc
->SetFileName(sTmp
);
1365 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1368 for (size_t i
= 0; i
< m_index
.GetCount(); i
++)
1369 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1374 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1375 wxArrayString
*commands
,
1376 const wxFileType::MessageParameters
& params
) const
1378 wxString vrb
, cmd
, sTmp
;
1380 wxMimeTypeCommands
* sPairs
;
1382 // verbs and commands have been cleared already in mimecmn.cpp...
1383 // if we find no entries in the exact match, try the inexact match
1384 for (size_t n
= 0; ((count
== 0) && (n
< m_index
.GetCount())); n
++)
1386 // list of verb = command pairs for this mimetype
1387 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1389 for ( i
= 0; i
< sPairs
->GetCount(); i
++ )
1391 vrb
= sPairs
->GetVerb(i
);
1392 // some gnome entries have "." inside
1393 vrb
= vrb
.AfterLast(wxT('.'));
1394 cmd
= sPairs
->GetCmd(i
);
1397 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1399 if ( vrb
.IsSameAs(wxT("open")))
1401 verbs
->Insert(vrb
, 0u);
1402 commands
->Insert(cmd
, 0u);
1416 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1418 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1421 // one extension in the space or comma-delimited list
1423 for ( const wxChar
*p
= strExtensions
; /* nothing */; p
++ )
1425 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') )
1427 if ( !strExt
.empty() )
1429 extensions
.Add(strExt
);
1432 //else: repeated spaces
1433 // (shouldn't happen, but it's not that important if it does happen)
1435 if ( *p
== wxT('\0') )
1438 else if ( *p
== wxT('.') )
1440 // remove the dot from extension (but only if it's the first char)
1441 if ( !strExt
.empty() )
1445 //else: no, don't append it
1456 // set an arbitrary command:
1457 // could adjust the code to ask confirmation if it already exists and
1458 // overwriteprompt is true, but this is currently ignored as *Associate* has
1459 // no overwrite prompt
1461 wxFileTypeImpl::SetCommand(const wxString
& cmd
,
1462 const wxString
& verb
,
1463 bool WXUNUSED(overwriteprompt
))
1465 wxArrayString strExtensions
;
1466 wxString strDesc
, strIcon
;
1468 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1469 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1471 wxArrayString strTypes
;
1472 GetMimeTypes(strTypes
);
1473 if (strTypes
.GetCount() < 1)
1478 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1480 if (!m_manager
->DoAssociation(strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1487 // ignore index on the grouds that we only have one icon in a Unix file
1488 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
, int WXUNUSED(index
))
1490 if (strIcon
.empty())
1493 wxArrayString strExtensions
;
1496 wxArrayString strTypes
;
1497 GetMimeTypes(strTypes
);
1498 if ( strTypes
.IsEmpty() )
1501 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1503 for ( size_t i
= 0; i
< strTypes
.GetCount(); i
++ )
1505 if ( !m_manager
->DoAssociation
1521 // ----------------------------------------------------------------------------
1522 // wxMimeTypesManagerImpl (Unix)
1523 // ----------------------------------------------------------------------------
1525 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1527 m_initialized
= false;
1528 m_mailcapStylesInited
= 0;
1531 void wxMimeTypesManagerImpl::InitIfNeeded()
1533 if ( !m_initialized
)
1535 // set the flag first to prevent recursion
1536 m_initialized
= true;
1541 wxString wm
= wxGetenv( wxT("WINDOWMANAGER") );
1543 if (wm
.Find( wxT("kde") ) != wxNOT_FOUND
)
1544 Initialize( wxMAILCAP_KDE
| wxMAILCAP_STANDARD
);
1545 else if (wm
.Find( wxT("gnome") ) != wxNOT_FOUND
)
1546 Initialize( wxMAILCAP_GNOME
| wxMAILCAP_STANDARD
);
1553 // read system and user mailcaps and other files
1554 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1555 const wxString
& sExtraDir
)
1557 // read mimecap amd mime.types
1558 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1559 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1560 GetMimeInfo(sExtraDir
);
1562 // read GNOME tables
1563 if (mailcapStyles
& wxMAILCAP_GNOME
)
1564 GetGnomeMimeInfo(sExtraDir
);
1567 if (mailcapStyles
& wxMAILCAP_KDE
)
1568 GetKDEMimeInfo(sExtraDir
);
1570 m_mailcapStylesInited
|= mailcapStyles
;
1573 // clear data so you can read another group of WM files
1574 void wxMimeTypesManagerImpl::ClearData()
1578 m_aExtensions
.Clear();
1579 m_aDescriptions
.Clear();
1581 WX_CLEAR_ARRAY(m_aEntries
);
1584 m_mailcapStylesInited
= 0;
1587 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1592 void wxMimeTypesManagerImpl::GetMimeInfo(const wxString
& sExtraDir
)
1594 // read this for netscape or Metamail formats
1596 // directories where we look for mailcap and mime.types by default
1597 // used by netscape and pine and other mailers, using 2 different formats!
1599 // (taken from metamail(1) sources)
1601 // although RFC 1524 specifies the search path of
1602 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1603 // places - OTOH, the RFC also says that this path can be changed with
1604 // MAILCAPS environment variable (containing the colon separated full
1605 // filenames to try) which is not done yet (TODO?)
1607 wxString strHome
= wxGetenv(wxT("HOME"));
1610 dirs
.Add( strHome
+ wxT("/.") );
1611 dirs
.Add( wxT("/etc/") );
1612 dirs
.Add( wxT("/usr/etc/") );
1613 dirs
.Add( wxT("/usr/local/etc/") );
1614 dirs
.Add( wxT("/etc/mail/") );
1615 dirs
.Add( wxT("/usr/public/lib/") );
1616 if (!sExtraDir
.empty())
1617 dirs
.Add( sExtraDir
+ wxT("/") );
1619 size_t nDirs
= dirs
.GetCount();
1620 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1622 wxString file
= dirs
[nDir
] + wxT("mailcap");
1623 if ( wxFile::Exists(file
) )
1628 file
= dirs
[nDir
] + wxT("mime.types");
1629 if ( wxFile::Exists(file
) )
1631 ReadMimeTypes(file
);
1636 bool wxMimeTypesManagerImpl::WriteToMimeTypes(int index
, bool delete_index
)
1638 // check we have the right manager
1639 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
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
);
1664 // test for netscape's header and return false if its found
1665 nIndex
= file
.pIndexOf(wxT("#--Netscape"));
1666 if (nIndex
!= wxNOT_FOUND
)
1668 wxASSERT_MSG(false,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1672 // write it in alternative format
1673 // get rid of unwanted entries
1674 wxString strType
= m_aTypes
[index
];
1675 nIndex
= file
.pIndexOf(strType
);
1677 // get rid of all the unwanted entries...
1678 if (nIndex
!= wxNOT_FOUND
)
1679 file
.CommentLine(nIndex
);
1683 // add the new entries in
1684 wxString sTmp
= strType
.Append( wxT(' '), 40 - strType
.Len() );
1685 sTmp
= sTmp
+ m_aExtensions
[index
];
1689 bTemp
= file
.Write();
1696 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes(int index
, bool delete_index
)
1698 //check we have the right managers
1699 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1703 wxString strHome
= wxGetenv(wxT("HOME"));
1705 // and now the users mailcap
1706 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1708 wxMimeTextFile file
;
1709 if ( wxFile::Exists(strUserMailcap
) )
1711 bTemp
= file
.Open(strUserMailcap
);
1718 bTemp
= file
.Create(strUserMailcap
);
1723 // write it in the format that Netscape uses
1725 // test for netscape's header and insert if required...
1726 // this is a comment so use true
1727 nIndex
= file
.pIndexOf(wxT("#--Netscape"), true);
1728 if (nIndex
== wxNOT_FOUND
)
1730 // either empty file or metamail format
1731 // at present we can't cope with mixed formats, so exit to preseve
1732 // metamail entreies
1733 if (file
.GetLineCount() > 0)
1735 wxASSERT_MSG(false, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1739 file
.InsertLine(wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1743 wxString strType
= wxT("type=") + m_aTypes
[index
];
1744 nIndex
= file
.pIndexOf(strType
);
1746 // get rid of all the unwanted entries...
1747 if (nIndex
!= wxNOT_FOUND
)
1749 wxString sOld
= file
[nIndex
];
1750 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1752 file
.CommentLine(nIndex
);
1753 sOld
= file
[nIndex
];
1755 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1760 if (nIndex
< (int) file
.GetLineCount())
1761 file
.CommentLine(nIndex
);
1764 nIndex
= (int) file
.GetLineCount();
1766 wxString sTmp
= strType
+ wxT(" \\");
1768 file
.InsertLine(sTmp
, nIndex
);
1770 if ( ! m_aDescriptions
.Item(index
).empty() )
1772 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1776 file
.InsertLine(sTmp
, nIndex
);
1780 wxString sExts
= m_aExtensions
.Item(index
);
1781 sTmp
= wxT("exts=\"") + sExts
.Trim(false).Trim() + wxT("\"");
1785 file
.InsertLine(sTmp
, nIndex
);
1788 bTemp
= file
.Write();
1795 bool wxMimeTypesManagerImpl::WriteToMailCap(int index
, bool delete_index
)
1797 //check we have the right managers
1798 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1799 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1803 wxString strHome
= wxGetenv(wxT("HOME"));
1805 // and now the users mailcap
1806 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1808 wxMimeTextFile file
;
1809 if ( wxFile::Exists(strUserMailcap
) )
1811 bTemp
= file
.Open(strUserMailcap
);
1818 bTemp
= file
.Create(strUserMailcap
);
1823 // now got a file we can write to ....
1824 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1826 wxString sCmd
= entries
->GetCommandForVerb(wxT("open"), &iOpen
);
1829 sTmp
= m_aTypes
[index
];
1831 int nIndex
= file
.pIndexOf(sTmp
);
1833 // get rid of all the unwanted entries...
1834 if (nIndex
== wxNOT_FOUND
)
1836 nIndex
= (int) file
.GetLineCount();
1840 sOld
= file
[nIndex
];
1841 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1843 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1845 file
.CommentLine(nIndex
);
1846 if (nIndex
< (int) file
.GetLineCount())
1847 sOld
= sOld
+ file
[nIndex
];
1851 file
.GetLineCount()) file
.CommentLine(nIndex
);
1854 sTmp
= sTmp
+ wxT(";") + sCmd
; //includes wxT(" %s ");
1856 // write it in the format that Netscape uses (default)
1857 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1860 file
.InsertLine(sTmp
, nIndex
);
1865 // write extended format
1867 // TODO - FIX this code:
1869 // sOld holds all the entries, but our data store only has some
1870 // eg test= is not stored
1872 // so far we have written the mimetype and command out
1873 wxStringTokenizer
sT(sOld
, wxT(";\\"));
1874 if (sT
.CountTokens() > 2)
1876 // first one mimetype; second one command, rest unknown...
1878 s
= sT
.GetNextToken();
1879 s
= sT
.GetNextToken();
1882 s
= sT
.GetNextToken();
1883 while ( ! s
.empty() )
1885 bool bKnownToken
= false;
1886 if (s
.Contains(wxT("description=")))
1888 if (s
.Contains(wxT("x11-bitmap=")))
1892 for (i
=0; i
< entries
->GetCount(); i
++)
1894 if (s
.Contains(entries
->GetVerb(i
)))
1900 sTmp
= sTmp
+ wxT("; \\");
1901 file
.InsertLine(sTmp
, nIndex
);
1905 s
= sT
.GetNextToken();
1909 if (! m_aDescriptions
[index
].empty() )
1911 sTmp
= sTmp
+ wxT("; \\");
1912 file
.InsertLine(sTmp
, nIndex
);
1914 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1917 if (! m_aIcons
[index
].empty() )
1919 sTmp
= sTmp
+ wxT("; \\");
1920 file
.InsertLine(sTmp
, nIndex
);
1922 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1925 if ( entries
->GetCount() > 1 )
1928 for (i
=0; i
< entries
->GetCount(); i
++)
1931 sTmp
= sTmp
+ wxT("; \\");
1932 file
.InsertLine(sTmp
, nIndex
);
1934 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1938 file
.InsertLine(sTmp
, nIndex
);
1942 bTemp
= file
.Write();
1949 wxFileType
* wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1953 wxString strType
= ftInfo
.GetMimeType();
1954 wxString strDesc
= ftInfo
.GetDescription();
1955 wxString strIcon
= ftInfo
.GetIconFile();
1957 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
1959 if ( ! ftInfo
.GetOpenCommand().empty())
1960 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand() + wxT(" %s "));
1961 if ( ! ftInfo
.GetPrintCommand().empty())
1962 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand() + wxT(" %s "));
1964 // now find where these extensions are in the data store and remove them
1965 wxArrayString sA_Exts
= ftInfo
.GetExtensions();
1966 wxString sExt
, sExtStore
;
1968 for (i
=0; i
< sA_Exts
.GetCount(); i
++)
1970 sExt
= sA_Exts
.Item(i
);
1972 // clean up to just a space before and after
1973 sExt
.Trim().Trim(false);
1974 sExt
= wxT(' ') + sExt
+ wxT(' ');
1975 for (nIndex
= 0; nIndex
< m_aExtensions
.GetCount(); nIndex
++)
1977 sExtStore
= m_aExtensions
.Item(nIndex
);
1978 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0)
1979 m_aExtensions
.Item(nIndex
) = sExtStore
;
1983 if ( !DoAssociation(strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1986 return GetFileTypeFromMimeType(strType
);
1989 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1990 const wxString
& strIcon
,
1991 wxMimeTypeCommands
*entry
,
1992 const wxArrayString
& strExtensions
,
1993 const wxString
& strDesc
)
1995 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
1997 if ( nIndex
== wxNOT_FOUND
)
2000 return WriteMimeInfo(nIndex
, false);
2003 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
2007 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
2009 // write in metamail format;
2010 if (WriteToMimeTypes(nIndex
, delete_mime
) )
2011 if ( WriteToMailCap(nIndex
, delete_mime
) )
2015 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
2017 // write in netsacpe format;
2018 if (WriteToNSMimeTypes(nIndex
, delete_mime
) )
2019 if ( WriteToMailCap(nIndex
, delete_mime
) )
2023 if (m_mailcapStylesInited
& wxMAILCAP_GNOME
)
2025 // write in Gnome format;
2026 if (WriteGnomeMimeFile(nIndex
, delete_mime
) )
2027 if (WriteGnomeKeyFile(nIndex
, delete_mime
) )
2031 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
2033 // write in KDE format;
2034 if (WriteKDEMimeFile(nIndex
, delete_mime
) )
2041 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
2042 const wxString
& strIcon
,
2043 wxMimeTypeCommands
*entry
,
2044 const wxArrayString
& strExtensions
,
2045 const wxString
& strDesc
,
2046 bool replaceExisting
)
2050 // ensure mimetype is always lower case
2051 wxString mimeType
= strType
.Lower();
2053 // is this a known MIME type?
2054 int nIndex
= m_aTypes
.Index(mimeType
);
2055 if ( nIndex
== wxNOT_FOUND
)
2058 m_aTypes
.Add(mimeType
);
2059 m_aIcons
.Add(strIcon
);
2060 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
2062 // change nIndex so we can use it below to add the extensions
2063 m_aExtensions
.Add(wxEmptyString
);
2064 nIndex
= m_aExtensions
.size() - 1;
2066 m_aDescriptions
.Add(strDesc
);
2068 else // yes, we already have it
2070 if ( replaceExisting
)
2072 // if new description change it
2073 if ( !strDesc
.empty())
2074 m_aDescriptions
[nIndex
] = strDesc
;
2076 // if new icon change it
2077 if ( !strIcon
.empty())
2078 m_aIcons
[nIndex
] = strIcon
;
2082 delete m_aEntries
[nIndex
];
2083 m_aEntries
[nIndex
] = entry
;
2086 else // add data we don't already have ...
2088 // if new description add only if none
2089 if ( m_aDescriptions
[nIndex
].empty() )
2090 m_aDescriptions
[nIndex
] = strDesc
;
2092 // if new icon and no existing icon
2093 if ( m_aIcons
[nIndex
].empty() )
2094 m_aIcons
[nIndex
] = strIcon
;
2096 // add any new entries...
2099 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
2101 size_t count
= entry
->GetCount();
2102 for ( size_t i
= 0; i
< count
; i
++ )
2104 const wxString
& verb
= entry
->GetVerb(i
);
2105 if ( !entryOld
->HasVerb(verb
) )
2107 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
2111 // as we don't store it anywhere, it won't be deleted later as
2112 // usual -- do it immediately instead
2118 // always add the extensions to this mimetype
2119 wxString
& exts
= m_aExtensions
[nIndex
];
2121 // add all extensions we don't have yet
2122 size_t count
= strExtensions
.GetCount();
2123 for ( size_t i
= 0; i
< count
; i
++ )
2125 wxString ext
= strExtensions
[i
] + wxT(' ');
2127 if ( exts
.Find(ext
) == wxNOT_FOUND
)
2133 // check data integrity
2134 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2135 m_aTypes
.Count() == m_aExtensions
.Count() &&
2136 m_aTypes
.Count() == m_aIcons
.Count() &&
2137 m_aTypes
.Count() == m_aDescriptions
.Count() );
2142 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
2149 size_t count
= m_aExtensions
.GetCount();
2150 for ( size_t n
= 0; n
< count
; n
++ )
2152 wxStringTokenizer
tk(m_aExtensions
[n
], wxT(' '));
2154 while ( tk
.HasMoreTokens() )
2156 // consider extensions as not being case-sensitive
2157 if ( tk
.GetNextToken().IsSameAs(ext
, false /* no case */) )
2160 wxFileType
*fileType
= new wxFileType
;
2161 fileType
->m_impl
->Init(this, n
);
2171 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
2175 wxFileType
* fileType
= NULL
;
2176 // mime types are not case-sensitive
2177 wxString
mimetype(mimeType
);
2178 mimetype
.MakeLower();
2180 // first look for an exact match
2181 int index
= m_aTypes
.Index(mimetype
);
2182 if ( index
!= wxNOT_FOUND
)
2184 fileType
= new wxFileType
;
2185 fileType
->m_impl
->Init(this, index
);
2188 // then try to find "text/*" as match for "text/plain" (for example)
2189 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
2190 // the whole string - ok.
2192 index
= wxNOT_FOUND
;
2193 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
2195 size_t nCount
= m_aTypes
.Count();
2196 for ( size_t n
= 0; n
< nCount
; n
++ )
2198 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
2199 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") )
2206 if ( index
!= wxNOT_FOUND
)
2208 // don't throw away fileType that was already found
2210 fileType
= new wxFileType
;
2211 fileType
->m_impl
->Init(this, index
);
2217 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
2219 wxString command
, testcmd
, sV
, sTmp
;
2220 sV
= verb
+ wxT("=");
2222 // list of verb = command pairs for this mimetype
2223 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
2226 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
2228 sTmp
= sPairs
->GetVerbCmd (i
);
2229 if ( sTmp
.Contains(sV
) )
2230 command
= sTmp
.AfterFirst(wxT('='));
2236 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
2240 wxString extensions
;
2241 const wxArrayString
& exts
= filetype
.GetExtensions();
2242 size_t nExts
= exts
.GetCount();
2243 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ )
2246 extensions
+= wxT(' ');
2248 extensions
+= exts
[nExt
];
2251 AddMimeTypeInfo(filetype
.GetMimeType(),
2253 filetype
.GetDescription());
2255 AddMailcapInfo(filetype
.GetMimeType(),
2256 filetype
.GetOpenCommand(),
2257 filetype
.GetPrintCommand(),
2259 filetype
.GetDescription());
2262 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2263 const wxString
& strExtensions
,
2264 const wxString
& strDesc
)
2266 // reading mailcap may find image/* , while
2267 // reading mime.types finds image/gif and no match is made
2268 // this means all the get functions don't work fix this
2270 wxString sTmp
= strExtensions
;
2272 wxArrayString sExts
;
2273 sTmp
.Trim().Trim(false);
2275 while (!sTmp
.empty())
2277 sExts
.Add(sTmp
.AfterLast(wxT(' ')));
2278 sTmp
= sTmp
.BeforeLast(wxT(' '));
2281 AddToMimeData(strMimeType
, strIcon
, NULL
, sExts
, strDesc
, true);
2284 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2285 const wxString
& strOpenCmd
,
2286 const wxString
& strPrintCmd
,
2287 const wxString
& strTest
,
2288 const wxString
& strDesc
)
2292 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2293 entry
->Add(wxT("open=") + strOpenCmd
);
2294 entry
->Add(wxT("print=") + strPrintCmd
);
2295 entry
->Add(wxT("test=") + strTest
);
2298 wxArrayString strExtensions
;
2300 AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
2303 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2305 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2306 strFileName
.c_str());
2308 wxTextFile
file(strFileName
);
2309 #if defined(__WXGTK20__) && wxUSE_UNICODE
2310 if ( !file
.Open(wxConvUTF8
) )
2316 // the information we extract
2317 wxString strMimeType
, strDesc
, strExtensions
;
2319 size_t nLineCount
= file
.GetLineCount();
2320 const wxChar
*pc
= NULL
;
2321 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2325 // now we're at the start of the line
2326 pc
= file
[nLine
].c_str();
2330 // we didn't finish with the previous line yet
2335 while ( wxIsspace(*pc
) )
2338 // comment or blank line?
2339 if ( *pc
== wxT('#') || !*pc
)
2341 // skip the whole line
2346 // detect file format
2347 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2348 if ( pEqualSign
== NULL
)
2353 // first field is mime type
2354 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ )
2360 while ( wxIsspace(*pc
) )
2363 // take all the rest of the string
2366 // no description...
2374 // the string on the left of '=' is the field name
2375 wxString
strLHS(pc
, pEqualSign
- pc
);
2378 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2382 if ( *pc
== wxT('"') )
2384 // the string is quoted and ends at the matching quote
2385 pEnd
= wxStrchr(++pc
, wxT('"'));
2388 wxLogWarning(wxT("Mime.types file %s, line %d: unterminated quoted string."),
2389 strFileName
.c_str(), nLine
+ 1);
2394 // unquoted string ends at the first space or at the end of
2396 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2400 // now we have the RHS (field value)
2401 wxString
strRHS(pc
, pEnd
- pc
);
2403 // check what follows this entry
2404 if ( *pEnd
== wxT('"') )
2410 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2413 // if there is something left, it may be either a '\\' to continue
2414 // the line or the next field of the same entry
2415 bool entryEnded
= *pc
== wxT('\0');
2416 bool nextFieldOnSameLine
= false;
2419 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2422 // now see what we got
2423 if ( strLHS
== wxT("type") )
2425 strMimeType
= strRHS
;
2427 else if ( strLHS
.StartsWith(wxT("desc")) )
2431 else if ( strLHS
== wxT("exts") )
2433 strExtensions
= strRHS
;
2435 else if ( strLHS
== wxT("icon") )
2437 // this one is simply ignored: it usually refers to Netscape
2438 // built in icons which are useless for us anyhow
2440 else if ( !strLHS
.StartsWith(wxT("x-")) )
2442 // we suppose that all fields starting with "X-" are
2443 // unregistered extensions according to the standard practice,
2444 // but it may be worth telling the user about other junk in
2445 // his mime.types file
2446 wxLogWarning(wxT("Unknown field in file %s, line %d: '%s'."),
2447 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
2452 if ( !nextFieldOnSameLine
)
2454 //else: don't reset it
2456 // as we don't reset strMimeType, the next field in this entry
2457 // will be interpreted correctly.
2463 // depending on the format (Mosaic or Netscape) either space or comma
2464 // is used to separate the extensions
2465 strExtensions
.Replace(wxT(","), wxT(" "));
2467 // also deal with the leading dot
2468 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2470 strExtensions
.erase(0, 1);
2473 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2474 strExtensions
.c_str(),
2475 strMimeType
.c_str(),
2478 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2480 // finished with this line
2487 // ----------------------------------------------------------------------------
2488 // UNIX mailcap files parsing
2489 // ----------------------------------------------------------------------------
2491 // the data for a single MIME type
2492 struct MailcapLineData
2501 wxArrayString verbs
,
2509 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= false; }
2512 // process a non-standard (i.e. not the first or second one) mailcap field
2514 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2515 const wxString
& curField
)
2517 if ( curField
.empty() )
2523 // is this something of the form foo=bar?
2524 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2527 // split "LHS = RHS" in 2
2528 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2529 rhs
= curField
.AfterFirst(wxT('='));
2531 lhs
.Trim(true); // from right
2532 rhs
.Trim(false); // from left
2534 // it might be quoted
2535 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2537 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2540 // is it a command verb or something else?
2541 if ( lhs
== wxT("test") )
2543 if ( wxSystem(rhs
) == 0 )
2546 wxLogTrace(TRACE_MIME_TEST
,
2547 wxT("Test '%s' for mime type '%s' succeeded."),
2548 rhs
.c_str(), data
.type
.c_str());
2552 wxLogTrace(TRACE_MIME_TEST
,
2553 wxT("Test '%s' for mime type '%s' failed, skipping."),
2554 rhs
.c_str(), data
.type
.c_str());
2556 data
.testfailed
= true;
2559 else if ( lhs
== wxT("desc") )
2563 else if ( lhs
== wxT("x11-bitmap") )
2567 else if ( lhs
== wxT("notes") )
2571 else // not a (recognized) special case, must be a verb (e.g. "print")
2573 data
.verbs
.Add(lhs
);
2574 data
.commands
.Add(rhs
);
2577 else // '=' not found
2579 // so it must be a simple flag
2580 if ( curField
== wxT("needsterminal") )
2582 data
.needsterminal
= true;
2584 else if ( curField
== wxT("copiousoutput"))
2586 // copiousoutput impies that the viewer is a console program
2587 data
.needsterminal
=
2588 data
.copiousoutput
= true;
2590 else if ( !IsKnownUnimportantField(curField
) )
2599 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2602 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2603 strFileName
.c_str());
2605 wxTextFile
file(strFileName
);
2606 #if defined(__WXGTK20__) && wxUSE_UNICODE
2607 if ( !file
.Open(wxConvUTF8
) )
2613 // indices of MIME types (in m_aTypes) we already found in this file
2615 // (see the comments near the end of function for the reason we need this)
2616 wxArrayInt aIndicesSeenHere
;
2618 // accumulator for the current field
2620 curField
.reserve(1024);
2622 size_t nLineCount
= file
.GetLineCount();
2623 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2625 // now we're at the start of the line
2626 const wxChar
*pc
= file
[nLine
].c_str();
2629 while ( wxIsspace(*pc
) )
2632 // comment or empty string?
2633 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2639 // what field are we currently in? The first 2 are fixed and there may
2640 // be an arbitrary number of other fields parsed by
2641 // ProcessOtherMailcapField()
2643 // the first field is the MIME type
2650 currentToken
= Field_Type
;
2652 // the flags and field values on the current line
2653 MailcapLineData data
;
2661 // interpret the next character literally (notice that
2662 // backslash can be used for line continuation)
2663 if ( *++pc
== wxT('\0') )
2665 // fetch the next line if there is one
2666 if ( nLine
== nLineCount
- 1 )
2668 // something is wrong, bail out
2671 wxLogDebug(wxT("Mailcap file %s, line %lu: '\\' on the end of the last line ignored."),
2672 strFileName
.c_str(),
2673 (unsigned long)nLine
+ 1);
2677 // pass to the beginning of the next line
2678 pc
= file
[++nLine
].c_str();
2680 // skip pc++ at the end of the loop
2686 // just a normal character
2692 cont
= false; // end of line reached, exit the loop
2694 // fall through to still process this field
2697 // trim whitespaces from both sides
2698 curField
.Trim(true).Trim(false);
2700 switch ( currentToken
)
2703 data
.type
= curField
.Lower();
2704 if ( data
.type
.empty() )
2706 // I don't think that this is a valid mailcap
2707 // entry, but try to interpret it somehow
2708 data
.type
= wxT('*');
2711 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2713 // we interpret "type" as "type/*"
2714 data
.type
+= wxT("/*");
2717 currentToken
= Field_OpenCmd
;
2721 data
.cmdOpen
= curField
;
2723 currentToken
= Field_Other
;
2727 if ( !ProcessOtherMailcapField(data
, curField
) )
2729 // don't flood the user with error messages if
2730 // we don't understand something in his
2731 // mailcap, but give them in debug mode because
2732 // this might be useful for the programmer
2735 wxT("Mailcap file %s, line %lu: unknown field '%s' for the MIME type '%s' ignored."),
2736 strFileName
.c_str(),
2737 (unsigned long)nLine
+ 1,
2742 else if ( data
.testfailed
)
2744 // skip this entry entirely
2748 // it already has this value
2749 //currentToken = Field_Other;
2753 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2756 // next token starts immediately after ';'
2764 // continue in the same line
2768 // we read the entire entry, check what have we got
2769 // ------------------------------------------------
2771 // check that we really read something reasonable
2772 if ( currentToken
< Field_Other
)
2774 wxLogWarning(wxT("Mailcap file %s, line %d: incomplete entry ignored."),
2775 strFileName
.c_str(), nLine
+ 1);
2780 // if the test command failed, it's as if the entry were not there at all
2781 if ( data
.testfailed
)
2786 // support for flags:
2787 // 1. create an xterm for 'needsterminal'
2788 // 2. append "| $PAGER" for 'copiousoutput'
2790 // Note that the RFC says that having both needsterminal and
2791 // copiousoutput is probably a mistake, so it seems that running
2792 // programs with copiousoutput inside an xterm as it is done now
2793 // is a bad idea (FIXME)
2794 if ( data
.copiousoutput
)
2796 const wxChar
*p
= wxGetenv(wxT("PAGER"));
2797 data
.cmdOpen
<< wxT(" | ") << (p
? p
: wxT("more"));
2800 if ( data
.needsterminal
)
2802 data
.cmdOpen
= wxString::Format(wxT("xterm -e sh -c '%s'"),
2803 data
.cmdOpen
.c_str());
2806 if ( !data
.cmdOpen
.empty() )
2808 data
.verbs
.Insert(wxT("open"), 0);
2809 data
.commands
.Insert(data
.cmdOpen
, 0);
2812 // we have to decide whether the new entry should replace any entries
2813 // for the same MIME type we had previously found or not
2816 // the fall back entries have the lowest priority, by definition
2823 // have we seen this one before?
2824 int nIndex
= m_aTypes
.Index(data
.type
);
2826 // and if we have, was it in this file? if not, we should
2827 // overwrite the previously seen one
2828 overwrite
= nIndex
== wxNOT_FOUND
||
2829 aIndicesSeenHere
.Index(nIndex
) == wxNOT_FOUND
;
2832 wxLogTrace(TRACE_MIME
, wxT("mailcap %s: %s [%s]"),
2833 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2834 overwrite
? wxT("replace") : wxT("add"));
2836 int n
= AddToMimeData
2840 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2841 wxArrayString() /* extensions */,
2848 aIndicesSeenHere
.Add(n
);
2855 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2862 size_t count
= m_aTypes
.GetCount();
2863 for ( size_t n
= 0; n
< count
; n
++ )
2865 // don't return template types from here (i.e. anything containg '*')
2867 if ( type
.Find(wxT('*')) == wxNOT_FOUND
)
2869 mimetypes
.Add(type
);
2873 return mimetypes
.GetCount();
2876 // ----------------------------------------------------------------------------
2877 // writing to MIME type files
2878 // ----------------------------------------------------------------------------
2880 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2882 wxArrayString sMimeTypes
;
2883 ft
->GetMimeTypes(sMimeTypes
);
2887 for (i
= 0; i
< sMimeTypes
.GetCount(); i
++)
2889 sMime
= sMimeTypes
.Item(i
);
2890 int nIndex
= m_aTypes
.Index(sMime
);
2891 if ( nIndex
== wxNOT_FOUND
)
2893 // error if we get here ??
2898 WriteMimeInfo(nIndex
, true);
2899 m_aTypes
.RemoveAt(nIndex
);
2900 m_aEntries
.RemoveAt(nIndex
);
2901 m_aExtensions
.RemoveAt(nIndex
);
2902 m_aDescriptions
.RemoveAt(nIndex
);
2903 m_aIcons
.RemoveAt(nIndex
);
2906 // check data integrity
2907 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2908 m_aTypes
.Count() == m_aExtensions
.Count() &&
2909 m_aTypes
.Count() == m_aIcons
.Count() &&
2910 m_aTypes
.Count() == m_aDescriptions
.Count() );
2915 // ----------------------------------------------------------------------------
2916 // private functions
2917 // ----------------------------------------------------------------------------
2919 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2921 static const wxChar
*knownFields
[] =
2923 wxT("x-mozilla-flags"),
2924 wxT("nametemplate"),
2925 wxT("textualnewlines"),
2928 wxString field
= fieldAll
.BeforeFirst(wxT('='));
2929 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2931 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2939 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE