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"
79 #include "wx/unix/mimetype.h"
81 // other standard headers
85 /* silence warnings for comparing unsigned int's <0 */
86 # pragma message disable unscomzer
89 // wxMimeTypeCommands stores the verbs defined for the given MIME type with
91 class wxMimeTypeCommands
94 wxMimeTypeCommands() { }
96 wxMimeTypeCommands(const wxArrayString
& verbs
,
97 const wxArrayString
& commands
)
103 // add a new verb with the command or replace the old value
104 void AddOrReplaceVerb(const wxString
& verb
, const wxString
& cmd
)
106 int n
= m_verbs
.Index(verb
, FALSE
/* ignore case */);
107 if ( n
== wxNOT_FOUND
)
118 void Add(const wxString
& s
)
120 m_verbs
.Add(s
.BeforeFirst(_T('=')));
121 m_commands
.Add(s
.AfterFirst(_T('=')));
124 // access the commands
125 size_t GetCount() const { return m_verbs
.GetCount(); }
126 const wxString
& GetVerb(size_t n
) const { return m_verbs
[n
]; }
127 const wxString
& GetCmd(size_t n
) const { return m_commands
[n
]; }
129 bool HasVerb(const wxString
& verb
) const
130 { return m_verbs
.Index(verb
) != wxNOT_FOUND
; }
132 wxString
GetCommandForVerb(const wxString
& verb
, size_t *idx
= NULL
) const
136 int n
= m_verbs
.Index(verb
);
137 if ( n
!= wxNOT_FOUND
)
139 s
= m_commands
[(size_t)n
];
147 // get a "verb=command" string
148 wxString
GetVerbCmd(size_t n
) const
150 return m_verbs
[n
] + _T('=') + m_commands
[n
];
154 wxArrayString m_verbs
,
158 // this class extends wxTextFile
161 class wxMimeTextFile
: public wxTextFile
165 wxMimeTextFile () : wxTextFile () {};
166 wxMimeTextFile (const wxString
& strFile
) : wxTextFile (strFile
) { };
168 int pIndexOf(const wxString
& sSearch
, bool bIncludeComments
= FALSE
, int iStart
= 0)
171 int nResult
= wxNOT_FOUND
;
172 if (i
>=GetLineCount()) return wxNOT_FOUND
;
174 wxString sTest
= sSearch
;
178 if (bIncludeComments
)
180 while ( (i
< GetLineCount()) )
184 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
190 while ( (i
< GetLineCount()) )
194 if ( ! sLine
.StartsWith(wxT("#")))
196 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
204 bool CommentLine(int nIndex
)
206 if (nIndex
<0) return FALSE
;
207 if (nIndex
>= (int)GetLineCount() ) return FALSE
;
208 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
212 bool CommentLine(const wxString
& sTest
)
214 int nIndex
= pIndexOf(sTest
);
215 if (nIndex
<0) return FALSE
;
216 if (nIndex
>= (int)GetLineCount() ) return FALSE
;
217 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
221 wxString
GetVerb (size_t i
)
223 if (i
> GetLineCount() ) return wxEmptyString
;
224 wxString sTmp
= GetLine(i
).BeforeFirst(wxT('='));
228 wxString
GetCmd (size_t i
)
230 if (i
> GetLineCount() ) 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 _T("mime")
246 // give trace messages about the results of mailcap tests
247 #define TRACE_MIME_TEST _T("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(_("Failed to create directory %s/.gnome."), sTmp
.c_str());
374 sTmp
= sTmp
+ wxT("/mime-info");
375 if (! wxDir::Exists ( sTmp
) )
377 if (!wxMkdir ( sTmp
))
379 wxLogError(_("Failed to create directory %s/mime-info."), sTmp
.c_str());
389 bool wxMimeTypesManagerImpl::WriteGnomeKeyFile(int index
, bool delete_index
)
392 wxGetHomeDir( &gnomedir
);
394 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.keys"));
395 // if this fails probably Gnome is not installed ??
396 // create it anyway as a private mime store
398 #if defined(__WXGTK20__) && wxUSE_UNICODE
399 if (! outfile
.Open ( wxConvUTF8
) )
401 if (! outfile
.Open () )
404 if (delete_index
) return FALSE
;
405 if (!CheckGnomeDirsExist() ) return FALSE
;
409 wxString sTmp
, strType
= m_aTypes
[index
];
410 int nIndex
= outfile
.pIndexOf(strType
);
411 if ( nIndex
== wxNOT_FOUND
)
413 outfile
.AddLine ( strType
+ wxT(':') );
414 // see file:/usr/doc/gnome-libs-devel-1.0.40/devel-docs/mime-type-handling.txt
415 // as this does not deal with internationalisation
416 // wxT( "\t[en_US]") + verb + wxT ('=') + cmd + wxT(" %f");
417 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
418 size_t count
= entries
->GetCount();
419 for ( size_t i
= 0; i
< count
; i
++ )
421 sTmp
= entries
->GetVerbCmd(i
);
422 sTmp
.Replace( wxT("%s"), wxT("%f") );
423 sTmp
= wxT ( "\t") + sTmp
;
424 outfile
.AddLine ( sTmp
);
426 //for international use do something like this
427 //outfile.AddLine ( wxString( "\t[en_US]icon-filename=") + cmd );
428 outfile
.AddLine ( wxT( "\ticon-filename=") + m_aIcons
[index
] );
433 outfile
.CommentLine(nIndex
);
435 wxMimeTypeCommands sOld
;
436 size_t nOld
= nIndex
+ 1;
437 bool oldEntryEnd
= FALSE
;
438 while ( (nOld
< outfile
.GetLineCount() )&& (oldEntryEnd
== FALSE
))
440 sTmp
= outfile
.GetLine(nOld
);
441 if ( (sTmp
[0u] == wxT('\t')) || (sTmp
[0u] == wxT('#')) )
443 // we have another line to deal with
444 outfile
.CommentLine(nOld
);
446 // add the line to our store
447 if ((!delete_index
) && (sTmp
[0u] == wxT('\t')))
450 // next mimetpye ??or blank line
454 // list of entries in our data; these should all be in sOld,
455 // though sOld may also contain other entries , eg flags
458 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
460 for (i
=0; i
< entries
->GetCount(); i
++)
462 // replace any entries in sold that match verbs we know
463 sOld
.AddOrReplaceVerb ( entries
->GetVerb(i
), entries
->GetCmd (i
) );
465 //sOld should also contain the icon
466 if ( !m_aIcons
[index
].empty() )
467 sOld
.AddOrReplaceVerb ( wxT("icon-filename"), m_aIcons
[index
] );
469 for (i
=0; i
< sOld
.GetCount(); i
++)
471 sTmp
= sOld
.GetVerbCmd(i
);
472 sTmp
.Replace( wxT("%s"), wxT("%f") );
473 sTmp
= wxT("\t") + sTmp
;
475 outfile
.InsertLine ( sTmp
, nIndex
);
479 bool bTmp
= outfile
.Write ();
484 bool wxMimeTypesManagerImpl::WriteGnomeMimeFile(int index
, bool delete_index
)
487 wxGetHomeDir( &gnomedir
);
489 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.mime"));
490 // if this fails probably Gnome is not installed ??
491 // create it anyway as a private mime store
492 if (! outfile
.Open () )
494 if (delete_index
) return FALSE
;
495 if (!CheckGnomeDirsExist() ) return FALSE
;
498 wxString strType
= m_aTypes
[index
];
499 int nIndex
= outfile
.pIndexOf(strType
);
500 if ( nIndex
== wxNOT_FOUND
)
502 outfile
.AddLine ( strType
);
503 outfile
.AddLine ( wxT("\text:") + m_aExtensions
.Item(index
) );
509 outfile
.CommentLine(nIndex
);
510 outfile
.CommentLine(nIndex
+1);
513 {// check for next line being the right one to replace ??
514 wxString sOld
= outfile
.GetLine(nIndex
+1);
515 if (sOld
.Contains( wxT("\text: ")))
517 outfile
.GetLine(nIndex
+1) = wxT("\text: ") + m_aExtensions
.Item(index
);
521 outfile
.InsertLine( wxT("\text: ") + m_aExtensions
.Item(index
), nIndex
+ 1 );
525 bool bTmp
= outfile
.Write ();
530 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString
& filename
,
531 const wxArrayString
& dirs
)
533 wxTextFile
textfile(filename
);
534 #if defined(__WXGTK20__) && wxUSE_UNICODE
535 if ( !textfile
.Open( wxConvUTF8
) )
537 if ( !textfile
.Open() )
540 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
543 // values for the entry being parsed
544 wxString curMimeType
, curIconFile
;
545 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
547 // these are always empty in this file
548 wxArrayString strExtensions
;
552 size_t nLineCount
= textfile
.GetLineCount();
554 while ( nLine
< nLineCount
)
556 pc
= textfile
[nLine
].c_str();
557 if ( *pc
!= _T('#') )
560 wxLogTrace(TRACE_MIME
, wxT("--- Reading from Gnome file %s '%s' ---"),
561 filename
.c_str(),pc
);
564 if (sTmp
.Contains(wxT("=")) )
567 if (sTmp
.Contains( wxT("icon-filename=") ) )
569 curIconFile
= sTmp
.AfterFirst(wxT('='));
572 else if (sTmp
.Contains( wxT("icon_filename=") ) )
574 curIconFile
= sTmp
.AfterFirst(wxT('='));
576 if (!wxFileExists(curIconFile
))
578 size_t nDirs
= dirs
.GetCount();
579 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
581 wxFileName
newFile( curIconFile
);
582 newFile
.SetPath( dirs
[nDir
] );
583 newFile
.AppendDir( wxT("pixmaps") );
584 newFile
.AppendDir( wxT("document-icons") );
585 newFile
.SetExt( wxT("png") );
586 if (newFile
.FileExists())
587 curIconFile
= newFile
.GetFullPath();
591 else //: some other field,
593 //may contain lines like this (RH7)
594 // \t[lang]open.tex."TeX this file"=tex %f
595 // \tflags.tex.flags=needsterminal
596 // \topen.latex."LaTeX this file"=latex %f
597 // \tflags.latex.flags=needsterminal
601 // \topen.convert.Convert file to Postscript=dvips %f -o `basename %f .dvi`.ps
603 // for now ignore lines with flags in...FIX
604 sTmp
= sTmp
.AfterLast(wxT(']'));
605 sTmp
= sTmp
.AfterLast(wxT('\t'));
606 sTmp
.Trim(FALSE
).Trim();
607 if (0 == sTmp
.Replace ( wxT("%f"), wxT("%s") )) sTmp
= sTmp
+ wxT(" %s");
612 } // emd of has an equals sign
615 // not a comment and not an equals sign
616 if (sTmp
.Contains(wxT('/')))
618 // this is the start of the new mimetype
619 // overwrite any existing data
620 if (! curMimeType
.empty())
622 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
624 // now get ready for next bit
625 entry
= new wxMimeTypeCommands
;
627 curMimeType
= sTmp
.BeforeFirst(wxT(':'));
630 } // end of not a comment
631 // ignore blank lines
633 } // end of while, save any data
635 if (! curMimeType
.empty())
636 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
641 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString
& filename
)
643 wxTextFile
textfile(filename
);
644 if ( !textfile
.Open() )
647 wxLogTrace(TRACE_MIME
,
648 wxT("--- Opened Gnome file %s ---"),
651 // values for the entry being parsed
652 wxString curMimeType
, curExtList
;
655 size_t nLineCount
= textfile
.GetLineCount();
656 for ( size_t nLine
= 0;; nLine
++ )
658 if ( nLine
< nLineCount
)
660 pc
= textfile
[nLine
].c_str();
661 if ( *pc
== wxT('#') )
669 // so that we will fall into the "if" below
676 if ( !!curMimeType
&& !!curExtList
)
678 wxLogTrace(TRACE_MIME
,
679 wxT("--- At end of Gnome file finding mimetype %s ---"),
680 curMimeType
.c_str());
682 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
687 // the end - this can only happen if nLine == nLineCount
696 // what do we have here?
697 if ( *pc
== wxT('\t') )
699 // this is a field=value ling
700 pc
++; // skip leading TAB
702 static const int lenField
= 5; // strlen("ext: ")
703 if ( wxStrncmp(pc
, wxT("ext: "), lenField
) == 0 )
705 // skip it and take everything left until the end of line
706 curExtList
= pc
+ lenField
;
708 //else: some other field, we don't care
712 // this is the start of the new section
713 wxLogTrace(TRACE_MIME
,
714 wxT("--- In Gnome file finding mimetype %s ---"),
715 curMimeType
.c_str());
717 if (! curMimeType
.empty())
718 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
722 while ( *pc
!= wxT(':') && *pc
!= wxT('\0') )
724 curMimeType
+= *pc
++;
731 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
732 const wxString
& dirbase
, const wxArrayString
& dirs
)
734 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
735 _T("base directory shouldn't end with a slash") );
737 wxString dirname
= dirbase
;
738 dirname
<< wxT("/mime-info");
740 if ( !wxDir::Exists(dirname
) )
744 if ( !dir
.IsOpened() )
747 // we will concatenate it with filename to get the full path below
752 cont
= dir
.GetFirst(&filename
, _T("*.mime"), wxDIR_FILES
);
755 LoadGnomeMimeTypesFromMimeFile(dirname
+ filename
);
757 cont
= dir
.GetNext(&filename
);
760 cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
763 LoadGnomeDataFromKeyFile(dirname
+ filename
, dirs
);
765 cont
= dir
.GetNext(&filename
);
768 // Hack alert: We scan all icons and deduce the
769 // mime-type from the file name.
771 dirname
<< wxT("/pixmaps/document-icons");
773 // these are always empty in this file
774 wxArrayString strExtensions
;
777 if ( !wxDir::Exists(dirname
) )
779 // Jst test for default GPE dir also
780 dirname
= wxT("/usr/share/gpe/pixmaps/default/filemanager/document-icons");
782 if ( !wxDir::Exists(dirname
) )
786 wxDir
dir2( dirname
);
788 cont
= dir2
.GetFirst(&filename
, wxT("gnome-*.png"), wxDIR_FILES
);
791 wxString mimeType
= filename
;
792 mimeType
.Remove( 0, 6 ); // remove "gnome-"
793 mimeType
.Remove( mimeType
.Len()-4, 4 ); // remove ".png"
794 int pos
= mimeType
.Find( wxT("-") );
795 if (pos
!= wxNOT_FOUND
)
797 mimeType
.SetChar( pos
, wxT('/') );
798 wxString iconFile
= dirname
;
799 iconFile
<< wxT("/");
800 iconFile
<< filename
;
801 AddToMimeData ( mimeType
, iconFile
, NULL
, strExtensions
, strDesc
, TRUE
);
804 cont
= dir2
.GetNext(&filename
);
808 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString
& sExtraDir
)
812 wxString gnomedir
= wxGetenv( wxT("GNOMEDIR") );;
813 if (!gnomedir
.empty())
815 gnomedir
<< wxT("/share");
816 dirs
.Add( gnomedir
);
819 dirs
.Add(wxT("/usr/share"));
820 dirs
.Add(wxT("/usr/local/share"));
822 gnomedir
= wxGetHomeDir();
823 gnomedir
<< wxT("/.gnome");
824 dirs
.Add( gnomedir
);
826 if (!sExtraDir
.empty()) dirs
.Add( sExtraDir
);
828 size_t nDirs
= dirs
.GetCount();
829 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
831 LoadGnomeMimeFilesFromDir(dirs
[nDir
], dirs
);
835 // ----------------------------------------------------------------------------
837 // ----------------------------------------------------------------------------
840 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
841 // may be found in either of the following locations
843 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
844 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
846 // The format of a .kdelnk file is almost the same as the one used by
847 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
848 // value for the entry "Type"
850 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
851 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
853 bool wxMimeTypesManagerImpl::CheckKDEDirsExist ( const wxString
&sOK
, const wxString
&sTest
)
857 if (wxDir::Exists(sOK
))
864 wxString sStart
= sOK
+ wxT("/") + sTest
.BeforeFirst(wxT('/'));
865 if (!wxDir::Exists(sStart
)) wxMkdir(sStart
);
866 wxString sEnd
= sTest
.AfterFirst(wxT('/'));
867 return CheckKDEDirsExist(sStart
, sEnd
);
871 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index
, bool delete_index
)
873 wxMimeTextFile appoutfile
, mimeoutfile
;
874 wxString sHome
= wxGetHomeDir();
875 wxString sTmp
= wxT(".kde/share/mimelnk/");
876 wxString sMime
= m_aTypes
[index
];
877 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.BeforeFirst(wxT('/')) );
878 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
+ wxT(".kdelnk");
881 bool bMimeExists
= mimeoutfile
.Open (sTmp
);
884 bTemp
= mimeoutfile
.Create (sTmp
);
885 // some unknown error eg out of disk space
886 if (!bTemp
) return FALSE
;
889 sTmp
= wxT(".kde/share/applnk/");
890 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.AfterFirst(wxT('/')) );
891 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
.AfterFirst(wxT('/')) + wxT(".kdelnk");
894 bAppExists
= appoutfile
.Open (sTmp
);
897 bTemp
= appoutfile
.Create (sTmp
);
898 // some unknown error eg out of disk space
899 if (!bTemp
) return FALSE
;
902 // fixed data; write if new file
905 mimeoutfile
.AddLine(wxT("#KDE Config File"));
906 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
907 mimeoutfile
.AddLine(wxT("Version=1.0"));
908 mimeoutfile
.AddLine(wxT("Type=MimeType"));
909 mimeoutfile
.AddLine(wxT("MimeType=") + sMime
);
914 mimeoutfile
.AddLine(wxT("#KDE Config File"));
915 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
916 appoutfile
.AddLine(wxT("Version=1.0"));
917 appoutfile
.AddLine(wxT("Type=Application"));
918 appoutfile
.AddLine(wxT("MimeType=") + sMime
+ wxT(';'));
923 mimeoutfile
.CommentLine(wxT("Comment="));
925 mimeoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
926 appoutfile
.CommentLine(wxT("Name="));
928 appoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
930 sTmp
= m_aIcons
[index
];
931 // we can either give the full path, or the shortfilename if its in
932 // one of the directories we search
933 mimeoutfile
.CommentLine(wxT("Icon=") );
934 if (!delete_index
) mimeoutfile
.AddLine(wxT("Icon=") + sTmp
);
935 appoutfile
.CommentLine(wxT("Icon=") );
936 if (!delete_index
) appoutfile
.AddLine(wxT("Icon=") + sTmp
);
938 sTmp
= wxT(" ") + m_aExtensions
[index
];
940 wxStringTokenizer
tokenizer(sTmp
, _T(" "));
941 sTmp
= wxT("Patterns=");
942 mimeoutfile
.CommentLine(sTmp
);
943 while ( tokenizer
.HasMoreTokens() )
945 // holds an extension; need to change it to *.ext;
946 wxString e
= wxT("*.") + tokenizer
.GetNextToken() + wxT(";");
949 if (!delete_index
) mimeoutfile
.AddLine(sTmp
);
951 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
952 // if we don't find open just have an empty string ... FIX this
953 sTmp
= entries
->GetCommandForVerb(_T("open"));
954 sTmp
.Replace( wxT("%s"), wxT("%f") );
956 mimeoutfile
.CommentLine(wxT("DefaultApp=") );
957 if (!delete_index
) mimeoutfile
.AddLine(wxT("DefaultApp=") + sTmp
);
959 sTmp
.Replace( wxT("%f"), wxT("") );
960 appoutfile
.CommentLine(wxT("Exec="));
961 if (!delete_index
) appoutfile
.AddLine(wxT("Exec=") + sTmp
);
963 if (entries
->GetCount() > 1)
965 //other actions as well as open
969 if (mimeoutfile
.Write ()) bTemp
= TRUE
;
970 mimeoutfile
.Close ();
971 if (appoutfile
.Write ()) bTemp
= TRUE
;
977 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString
& dirbase
,
978 const wxString
& subdir
,
979 const wxString
& filename
,
980 const wxArrayString
& icondirs
)
983 if ( !file
.Open(dirbase
+ filename
) ) return;
985 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
986 (dirbase
+filename
).c_str());
988 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
990 wxString mimetype
, mime_desc
, strIcon
;
992 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
993 if (nIndex
== wxNOT_FOUND
)
995 // construct mimetype from the directory name and the basename of the
996 // file (it always has .kdelnk extension)
997 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
999 else mimetype
= file
.GetCmd (nIndex
);
1001 // first find the description string: it is the value in either "Comment="
1002 // line or "Comment[<locale_name>]=" one
1003 nIndex
= wxNOT_FOUND
;
1007 wxLocale
*locale
= wxGetLocale();
1010 // try "Comment[locale name]" first
1011 comment
<< _T("Comment[") + locale
->GetName() + _T("]=");
1012 nIndex
= file
.pIndexOf(comment
);
1014 #endif // wxUSE_INTL
1016 if ( nIndex
== wxNOT_FOUND
)
1018 comment
= _T("Comment=");
1019 nIndex
= file
.pIndexOf(comment
);
1022 if ( nIndex
!= wxNOT_FOUND
) mime_desc
= file
.GetCmd(nIndex
);
1023 //else: no description
1025 // next find the extensions
1026 wxString mime_extension
;
1028 nIndex
= file
.pIndexOf(_T("Patterns="));
1029 if ( nIndex
!= wxNOT_FOUND
)
1031 wxString exts
= file
.GetCmd (nIndex
);;
1033 wxStringTokenizer
tokenizer(exts
, _T(";"));
1034 while ( tokenizer
.HasMoreTokens() )
1036 wxString e
= tokenizer
.GetNextToken();
1037 if ( e
.Left(2) != _T("*.") )
1038 continue; // don't support too difficult patterns
1040 if ( !mime_extension
.empty() )
1042 // separate from the previous ext
1043 mime_extension
<< _T(' ');
1046 mime_extension
<< e
.Mid(2);
1049 sExts
.Add(mime_extension
);
1051 // ok, now we can take care of icon:
1053 nIndex
= file
.pIndexOf(_T("Icon="));
1054 if ( nIndex
!= wxNOT_FOUND
)
1056 strIcon
= file
.GetCmd(nIndex
);
1057 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
1058 //it could be the real path, but more often a short name
1061 if (!wxFileExists(strIcon
))
1063 // icon is just the short name
1064 if ( !strIcon
.empty() )
1066 // we must check if the file exists because it may be stored
1067 // in many locations, at least ~/.kde and $KDEDIR
1068 size_t nDir
, nDirs
= icondirs
.GetCount();
1069 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
1071 wxFileName
fnameIcon( strIcon
);
1072 wxFileName
fname( icondirs
[nDir
], fnameIcon
.GetName() );
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 // FIXME: This code is heavily broken. There are three bugs in it:
1175 // 1) it uses only KDEDIR, which is deprecated, instead of using
1176 // list of paths from KDEDIRS and using KDEDIR only if KDEDIRS
1178 // 2) it doesn't look into ~/.kde/share/config/kdeglobals where
1179 // user's settings are stored and thus *ignores* user's settings
1180 // instead of respecting them
1181 // 3) it "tries to guess KDEDIR" and "tries a few likely theme
1182 // names", both of which is completely arbitrary; instead, the
1183 // code should give up if KDEDIR(S) is not set and/or the icon
1184 // theme cannot be determined, because it means that the user is
1185 // not using KDE (and thus is not interested in KDE icons anyway)
1187 // the variable $KDEDIR is set when KDE is running
1188 wxString kdedir
= wxGetenv( wxT("KDEDIR") );
1190 if (!kdedir
.empty())
1192 // $(KDEDIR)/share/config/kdeglobals holds info
1193 // the current icons theme
1194 wxFileName
configFile( kdedir
, wxEmptyString
);
1195 configFile
.AppendDir( wxT("share") );
1196 configFile
.AppendDir( wxT("config") );
1197 configFile
.SetName( wxT("kdeglobals") );
1200 if (configFile
.FileExists() && config
.Open(configFile
.GetFullPath()))
1202 // $(KDEDIR)/share/config -> $(KDEDIR)/share
1203 configFile
.RemoveDir( configFile
.GetDirCount()-1 );
1204 // $(KDEDIR)/share/ -> $(KDEDIR)/share/icons
1205 configFile
.AppendDir( wxT("icons") );
1208 wxString
theme(wxT("default.kde"));
1209 size_t cnt
= config
.GetLineCount();
1210 for (size_t i
= 0; i
< cnt
; i
++)
1212 if (config
[i
].StartsWith(wxT("Theme="), &theme
/*rest*/))
1215 configFile
.AppendDir(theme
);
1219 // $(KDEDIR)/share/config -> $(KDEDIR)/share
1220 configFile
.RemoveDir( configFile
.GetDirCount()-1 );
1221 // $(KDEDIR)/share/ -> $(KDEDIR)/share/icons
1222 configFile
.AppendDir( wxT("icons") );
1223 // $(KDEDIR)/share/icons -> $(KDEDIR)/share/icons/default.kde
1224 configFile
.AppendDir( wxT("default.kde") );
1227 configFile
.SetName( wxEmptyString
);
1228 configFile
.AppendDir( wxT("32x32") );
1229 configFile
.AppendDir( wxT("mimetypes") );
1231 // Just try a few likely icons theme names
1233 int pos
= configFile
.GetDirCount()-3;
1235 if (!wxDir::Exists(configFile
.GetPath()))
1237 configFile
.RemoveDir( pos
);
1238 configFile
.InsertDir( pos
, wxT("default.kde") );
1241 if (!wxDir::Exists(configFile
.GetPath()))
1243 configFile
.RemoveDir( pos
);
1244 configFile
.InsertDir( pos
, wxT("default") );
1247 if (!wxDir::Exists(configFile
.GetPath()))
1249 configFile
.RemoveDir( pos
);
1250 configFile
.InsertDir( pos
, wxT("crystalsvg") );
1253 if (!wxDir::Exists(configFile
.GetPath()))
1255 configFile
.RemoveDir( pos
);
1256 configFile
.InsertDir( pos
, wxT("crystal") );
1259 if (wxDir::Exists(configFile
.GetPath()))
1260 icondirs
.Add( configFile
.GetFullPath() );
1263 // settings in ~/.kde have maximal priority
1264 dirs
.Add(wxGetHomeDir() + wxT("/.kde/share"));
1265 icondirs
.Add(wxGetHomeDir() + wxT("/.kde/share/icons/"));
1269 dirs
.Add( wxString(kdedir
) + wxT("/share") );
1270 icondirs
.Add( wxString(kdedir
) + wxT("/share/icons/") );
1274 // try to guess KDEDIR
1275 dirs
.Add(_T("/usr/share"));
1276 dirs
.Add(_T("/opt/kde/share"));
1277 icondirs
.Add(_T("/usr/share/icons/"));
1278 icondirs
.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
1279 icondirs
.Add(_T("/opt/kde/share/icons/"));
1282 if (!sExtraDir
.empty()) dirs
.Add (sExtraDir
);
1283 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1285 size_t nDirs
= dirs
.GetCount();
1286 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1288 LoadKDELinkFilesFromDir(dirs
[nDir
], icondirs
);
1292 // ----------------------------------------------------------------------------
1293 // wxFileTypeImpl (Unix)
1294 // ----------------------------------------------------------------------------
1296 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1300 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1302 sTmp
= m_manager
->GetCommand ( verb
, m_index
[i
] );
1306 return wxFileType::ExpandCommand(sTmp
, params
);
1309 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
1314 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1316 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1319 if ( sTmp
.empty () )
1324 iconLoc
->SetFileName(sTmp
);
1332 wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1335 for (size_t i
= 0; i
< m_index
.GetCount(); i
++)
1336 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1341 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1342 wxArrayString
*commands
,
1343 const wxFileType::MessageParameters
& params
) const
1346 wxString vrb
, cmd
, sTmp
;
1348 wxMimeTypeCommands
* sPairs
;
1350 // verbs and commands have been cleared already in mimecmn.cpp...
1351 // if we find no entries in the exact match, try the inexact match
1352 for (size_t n
= 0; ((count
==0) && (n
< m_index
.GetCount())); n
++)
1354 // list of verb = command pairs for this mimetype
1355 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1357 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
1359 vrb
= sPairs
->GetVerb(i
);
1360 // some gnome entries have . inside
1361 vrb
= vrb
.AfterLast(wxT('.'));
1362 cmd
= sPairs
->GetCmd (i
);
1365 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1367 if ( vrb
.IsSameAs (wxT("open")))
1369 verbs
->Insert(vrb
,0u);
1370 commands
->Insert(cmd
,0u);
1375 commands
->Add (cmd
);
1386 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1388 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1391 // one extension in the space or comma delimitid list
1393 for ( const wxChar
*p
= strExtensions
;; p
++ ) {
1394 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1395 if ( !strExt
.empty() ) {
1396 extensions
.Add(strExt
);
1399 //else: repeated spaces (shouldn't happen, but it's not that
1400 // important if it does happen)
1402 if ( *p
== wxT('\0') )
1405 else if ( *p
== wxT('.') ) {
1406 // remove the dot from extension (but only if it's the first char)
1407 if ( !strExt
.empty() ) {
1410 //else: no, don't append it
1420 // set an arbitrary command,
1421 // could adjust the code to ask confirmation if it already exists and
1422 // overwriteprompt is TRUE, but this is currently ignored as *Associate* has
1423 // no overwrite prompt
1424 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
, const wxString
& verb
, bool overwriteprompt
/*= TRUE*/)
1426 wxArrayString strExtensions
;
1427 wxString strDesc
, strIcon
;
1429 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1430 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1432 wxArrayString strTypes
;
1433 GetMimeTypes (strTypes
);
1434 if (strTypes
.GetCount() < 1) return FALSE
;
1438 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1440 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1447 // ignore index on the grouds that we only have one icon in a Unix file
1448 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
/*= wxEmptyString*/, int /*index = 0*/)
1450 if (strIcon
.empty()) return FALSE
;
1451 wxArrayString strExtensions
;
1454 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1456 wxArrayString strTypes
;
1457 GetMimeTypes (strTypes
);
1458 if (strTypes
.GetCount() < 1) return FALSE
;
1462 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1464 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1471 // ----------------------------------------------------------------------------
1472 // wxMimeTypesManagerImpl (Unix)
1473 // ----------------------------------------------------------------------------
1476 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1478 m_initialized
= FALSE
;
1479 m_mailcapStylesInited
= 0;
1482 void wxMimeTypesManagerImpl::InitIfNeeded()
1484 if ( !m_initialized
)
1486 // set the flag first to prevent recursion
1487 m_initialized
= TRUE
;
1490 wxString wm
= wxGetenv( wxT("WINDOWMANAGER") );
1492 if (wm
.Find( wxT("kde") ) != wxNOT_FOUND
)
1493 Initialize( wxMAILCAP_KDE
|wxMAILCAP_STANDARD
);
1494 else if (wm
.Find( wxT("gnome") ) != wxNOT_FOUND
)
1495 Initialize( wxMAILCAP_GNOME
|wxMAILCAP_STANDARD
);
1502 // read system and user mailcaps and other files
1503 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1504 const wxString
& sExtraDir
)
1506 // read mimecap amd mime.types
1507 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1508 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1509 GetMimeInfo(sExtraDir
);
1511 // read GNOME tables
1512 if (mailcapStyles
& wxMAILCAP_GNOME
)
1513 GetGnomeMimeInfo(sExtraDir
);
1516 if (mailcapStyles
& wxMAILCAP_KDE
)
1517 GetKDEMimeInfo(sExtraDir
);
1519 m_mailcapStylesInited
|= mailcapStyles
;
1522 // clear data so you can read another group of WM files
1523 void wxMimeTypesManagerImpl::ClearData()
1527 m_aExtensions
.Clear ();
1528 m_aDescriptions
.Clear ();
1530 WX_CLEAR_ARRAY(m_aEntries
);
1533 m_mailcapStylesInited
= 0;
1536 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1542 void wxMimeTypesManagerImpl::GetMimeInfo (const wxString
& sExtraDir
)
1544 // read this for netscape or Metamail formats
1546 // directories where we look for mailcap and mime.types by default
1547 // used by netscape and pine and other mailers, using 2 different formats!
1549 // (taken from metamail(1) sources)
1551 // although RFC 1524 specifies the search path of
1552 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1553 // places - OTOH, the RFC also says that this path can be changed with
1554 // MAILCAPS environment variable (containing the colon separated full
1555 // filenames to try) which is not done yet (TODO?)
1557 wxString strHome
= wxGetenv(wxT("HOME"));
1560 dirs
.Add ( strHome
+ wxT("/.") );
1561 dirs
.Add ( wxT("/etc/") );
1562 dirs
.Add ( wxT("/usr/etc/") );
1563 dirs
.Add ( wxT("/usr/local/etc/") );
1564 dirs
.Add ( wxT("/etc/mail/") );
1565 dirs
.Add ( wxT("/usr/public/lib/") );
1566 if (!sExtraDir
.empty()) dirs
.Add ( sExtraDir
+ wxT("/") );
1568 size_t nDirs
= dirs
.GetCount();
1569 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1571 wxString file
= dirs
[nDir
] + wxT("mailcap");
1572 if ( wxFile::Exists(file
) ) {
1576 file
= dirs
[nDir
] + wxT("mime.types");
1577 if ( wxFile::Exists(file
) ) {
1578 ReadMimeTypes(file
);
1584 bool wxMimeTypesManagerImpl::WriteToMimeTypes (int index
, bool delete_index
)
1586 // check we have the right manager
1587 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1591 wxString strHome
= wxGetenv(wxT("HOME"));
1593 // and now the users mailcap
1594 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1596 wxMimeTextFile file
;
1597 if ( wxFile::Exists(strUserMailcap
) )
1599 bTemp
= file
.Open(strUserMailcap
);
1603 if (delete_index
) return FALSE
;
1604 bTemp
= file
.Create(strUserMailcap
);
1609 // test for netscape's header and return FALSE if its found
1610 nIndex
= file
.pIndexOf (wxT("#--Netscape"));
1611 if (nIndex
!= wxNOT_FOUND
)
1613 wxASSERT_MSG(FALSE
,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1616 // write it in alternative format
1617 // get rid of unwanted entries
1618 wxString strType
= m_aTypes
[index
];
1619 nIndex
= file
.pIndexOf (strType
);
1620 // get rid of all the unwanted entries...
1621 if (nIndex
!= wxNOT_FOUND
) file
.CommentLine (nIndex
);
1625 // add the new entries in
1626 wxString sTmp
= strType
.Append (wxT(' '), 40-strType
.Len() );
1627 sTmp
= sTmp
+ m_aExtensions
[index
];
1628 file
.AddLine (sTmp
);
1632 bTemp
= file
.Write ();
1638 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes (int index
, bool delete_index
)
1640 //check we have the right managers
1641 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1645 wxString strHome
= wxGetenv(wxT("HOME"));
1647 // and now the users mailcap
1648 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1650 wxMimeTextFile file
;
1651 if ( wxFile::Exists(strUserMailcap
) )
1653 bTemp
= file
.Open(strUserMailcap
);
1657 if (delete_index
) return FALSE
;
1658 bTemp
= file
.Create(strUserMailcap
);
1663 // write it in the format that Netscape uses
1665 // test for netscape's header and insert if required...
1666 // this is a comment so use TRUE
1667 nIndex
= file
.pIndexOf (wxT("#--Netscape"), TRUE
);
1668 if (nIndex
== wxNOT_FOUND
)
1670 // either empty file or metamail format
1671 // at present we can't cope with mixed formats, so exit to preseve
1672 // metamail entreies
1673 if (file
.GetLineCount () > 0)
1675 wxASSERT_MSG(FALSE
, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1678 file
.InsertLine (wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1682 wxString strType
= wxT("type=") + m_aTypes
[index
];
1683 nIndex
= file
.pIndexOf (strType
);
1684 // get rid of all the unwanted entries...
1685 if (nIndex
!= wxNOT_FOUND
)
1687 wxString sOld
= file
[nIndex
];
1688 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1690 file
.CommentLine(nIndex
);
1691 sOld
= file
[nIndex
];
1692 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1695 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1697 else nIndex
= (int) file
.GetLineCount();
1699 wxString sTmp
= strType
+ wxT(" \\");
1700 if (!delete_index
) file
.InsertLine (sTmp
, nIndex
);
1701 if ( ! m_aDescriptions
.Item(index
).empty() )
1703 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1707 file
.InsertLine (sTmp
, nIndex
);
1710 wxString sExts
= m_aExtensions
.Item(index
);
1711 sTmp
= wxT("exts=\"") + sExts
.Trim(FALSE
).Trim() + wxT("\"");
1715 file
.InsertLine (sTmp
, nIndex
);
1718 bTemp
= file
.Write ();
1725 bool wxMimeTypesManagerImpl::WriteToMailCap (int index
, bool delete_index
)
1727 //check we have the right managers
1728 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1729 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1733 wxString strHome
= wxGetenv(wxT("HOME"));
1735 // and now the users mailcap
1736 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1738 wxMimeTextFile file
;
1739 if ( wxFile::Exists(strUserMailcap
) )
1741 bTemp
= file
.Open(strUserMailcap
);
1745 if (delete_index
) return FALSE
;
1746 bTemp
= file
.Create(strUserMailcap
);
1750 // now got a file we can write to ....
1751 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1753 wxString sCmd
= entries
->GetCommandForVerb(_T("open"), &iOpen
);
1756 sTmp
= m_aTypes
[index
];
1758 int nIndex
= file
.pIndexOf(sTmp
);
1759 // get rid of all the unwanted entries...
1760 if (nIndex
== wxNOT_FOUND
)
1762 nIndex
= (int) file
.GetLineCount();
1766 sOld
= file
[nIndex
];
1767 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1769 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1771 file
.CommentLine(nIndex
);
1772 if (nIndex
< (int) file
.GetLineCount()) sOld
= sOld
+ file
[nIndex
];
1774 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1777 sTmp
= sTmp
+ wxT(";") + sCmd
; //includes wxT(" %s ");
1779 // write it in the format that Netscape uses (default)
1780 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1782 if (! delete_index
) file
.InsertLine (sTmp
, nIndex
);
1786 // write extended format
1789 // todo FIX this code;
1791 // sOld holds all the entries, but our data store only has some
1792 // eg test= is not stored
1794 // so far we have written the mimetype and command out
1795 wxStringTokenizer
sT (sOld
, wxT(";\\"));
1796 if (sT
.CountTokens () > 2)
1798 // first one mimetype; second one command, rest unknown...
1800 s
= sT
.GetNextToken();
1801 s
= sT
.GetNextToken();
1804 s
= sT
.GetNextToken();
1805 while ( ! s
.empty() )
1807 bool bKnownToken
= FALSE
;
1808 if (s
.Contains(wxT("description="))) bKnownToken
= TRUE
;
1809 if (s
.Contains(wxT("x11-bitmap="))) bKnownToken
= TRUE
;
1811 for (i
=0; i
< entries
->GetCount(); i
++)
1813 if (s
.Contains(entries
->GetVerb(i
))) bKnownToken
= TRUE
;
1817 sTmp
= sTmp
+ wxT("; \\");
1818 file
.InsertLine (sTmp
, nIndex
);
1821 s
= sT
.GetNextToken ();
1826 if (! m_aDescriptions
[index
].empty() )
1828 sTmp
= sTmp
+ wxT("; \\");
1829 file
.InsertLine (sTmp
, nIndex
);
1831 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1834 if (! m_aIcons
[index
].empty() )
1836 sTmp
= sTmp
+ wxT("; \\");
1837 file
.InsertLine (sTmp
, nIndex
);
1839 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1841 if ( entries
->GetCount() > 1 )
1845 for (i
=0; i
< entries
->GetCount(); i
++)
1848 sTmp
= sTmp
+ wxT("; \\");
1849 file
.InsertLine (sTmp
, nIndex
);
1851 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1855 file
.InsertLine (sTmp
, nIndex
);
1859 bTemp
= file
.Write ();
1866 wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1870 wxString strType
= ftInfo
.GetMimeType ();
1871 wxString strDesc
= ftInfo
.GetDescription ();
1872 wxString strIcon
= ftInfo
.GetIconFile ();
1874 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1876 if ( ! ftInfo
.GetOpenCommand().empty())
1877 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand () + wxT(" %s "));
1878 if ( ! ftInfo
.GetPrintCommand ().empty())
1879 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand () + wxT(" %s "));
1881 // now find where these extensions are in the data store and remove them
1882 wxArrayString sA_Exts
= ftInfo
.GetExtensions ();
1883 wxString sExt
, sExtStore
;
1885 for (i
=0; i
< sA_Exts
.GetCount(); i
++)
1887 sExt
= sA_Exts
.Item(i
);
1888 //clean up to just a space before and after
1889 sExt
.Trim().Trim(FALSE
);
1890 sExt
= wxT(' ') + sExt
+ wxT(' ');
1891 for (nIndex
= 0; nIndex
< m_aExtensions
.GetCount(); nIndex
++)
1893 sExtStore
= m_aExtensions
.Item(nIndex
);
1894 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0) m_aExtensions
.Item(nIndex
) = sExtStore
;
1899 if ( !DoAssociation (strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1902 return GetFileTypeFromMimeType(strType
);
1906 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1907 const wxString
& strIcon
,
1908 wxMimeTypeCommands
*entry
,
1909 const wxArrayString
& strExtensions
,
1910 const wxString
& strDesc
)
1912 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, TRUE
);
1914 if ( nIndex
== wxNOT_FOUND
)
1917 return WriteMimeInfo (nIndex
, FALSE
);
1920 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
1924 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
1926 // write in metamail format;
1927 if (WriteToMimeTypes (nIndex
, delete_mime
) )
1928 if ( WriteToMailCap (nIndex
, delete_mime
) )
1931 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
1933 // write in netsacpe format;
1934 if (WriteToNSMimeTypes (nIndex
, delete_mime
) )
1935 if ( WriteToMailCap (nIndex
, delete_mime
) )
1938 if (m_mailcapStylesInited
& wxMAILCAP_GNOME
)
1940 // write in Gnome format;
1941 if (WriteGnomeMimeFile (nIndex
, delete_mime
) )
1942 if (WriteGnomeKeyFile (nIndex
, delete_mime
) )
1945 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
1947 // write in KDE format;
1948 if (WriteKDEMimeFile (nIndex
, delete_mime
) )
1955 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
1956 const wxString
& strIcon
,
1957 wxMimeTypeCommands
*entry
,
1958 const wxArrayString
& strExtensions
,
1959 const wxString
& strDesc
,
1960 bool replaceExisting
)
1964 // ensure mimetype is always lower case
1965 wxString mimeType
= strType
.Lower();
1967 // is this a known MIME type?
1968 int nIndex
= m_aTypes
.Index(mimeType
);
1969 if ( nIndex
== wxNOT_FOUND
)
1972 m_aTypes
.Add(mimeType
);
1973 m_aIcons
.Add(strIcon
);
1974 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
1976 // change nIndex so we can use it below to add the extensions
1977 m_aExtensions
.Add(wxEmptyString
);
1978 nIndex
= m_aExtensions
.size() - 1;
1980 m_aDescriptions
.Add(strDesc
);
1982 else // yes, we already have it
1984 if ( replaceExisting
)
1986 // if new description change it
1987 if ( !strDesc
.empty())
1988 m_aDescriptions
[nIndex
] = strDesc
;
1990 // if new icon change it
1991 if ( !strIcon
.empty())
1992 m_aIcons
[nIndex
] = strIcon
;
1996 delete m_aEntries
[nIndex
];
1997 m_aEntries
[nIndex
] = entry
;
2000 else // add data we don't already have ...
2002 // if new description add only if none
2003 if ( m_aDescriptions
[nIndex
].empty() )
2004 m_aDescriptions
[nIndex
] = strDesc
;
2006 // if new icon and no existing icon
2007 if ( m_aIcons
[nIndex
].empty () )
2008 m_aIcons
[nIndex
] = strIcon
;
2010 // add any new entries...
2013 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
2015 size_t count
= entry
->GetCount();
2016 for ( size_t i
= 0; i
< count
; i
++ )
2018 const wxString
& verb
= entry
->GetVerb(i
);
2019 if ( !entryOld
->HasVerb(verb
) )
2021 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
2025 // as we don't store it anywhere, it won't be deleted later as
2026 // usual -- do it immediately instead
2032 // always add the extensions to this mimetype
2033 wxString
& exts
= m_aExtensions
[nIndex
];
2035 // add all extensions we don't have yet
2036 size_t count
= strExtensions
.GetCount();
2037 for ( size_t i
= 0; i
< count
; i
++ )
2039 wxString ext
= strExtensions
[i
] + _T(' ');
2041 if ( exts
.Find(ext
) == wxNOT_FOUND
)
2047 // check data integrity
2048 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2049 m_aTypes
.Count() == m_aExtensions
.Count() &&
2050 m_aTypes
.Count() == m_aIcons
.Count() &&
2051 m_aTypes
.Count() == m_aDescriptions
.Count() );
2058 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
2065 size_t count
= m_aExtensions
.GetCount();
2066 for ( size_t n
= 0; n
< count
; n
++ )
2068 wxStringTokenizer
tk(m_aExtensions
[n
], _T(' '));
2070 while ( tk
.HasMoreTokens() )
2072 // consider extensions as not being case-sensitive
2073 if ( tk
.GetNextToken().IsSameAs(ext
, FALSE
/* no case */) )
2076 wxFileType
*fileType
= new wxFileType
;
2077 fileType
->m_impl
->Init(this, n
);
2088 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
2092 wxFileType
* fileType
= NULL
;
2093 // mime types are not case-sensitive
2094 wxString
mimetype(mimeType
);
2095 mimetype
.MakeLower();
2097 // first look for an exact match
2098 int index
= m_aTypes
.Index(mimetype
);
2099 if ( index
!= wxNOT_FOUND
)
2101 fileType
= new wxFileType
;
2102 fileType
->m_impl
->Init(this, index
);
2105 // then try to find "text/*" as match for "text/plain" (for example)
2106 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
2107 // the whole string - ok.
2109 index
= wxNOT_FOUND
;
2110 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
2112 size_t nCount
= m_aTypes
.Count();
2113 for ( size_t n
= 0; n
< nCount
; n
++ ) {
2114 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
2115 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
2122 if ( index
!= wxNOT_FOUND
)
2124 fileType
= new wxFileType
;
2125 fileType
->m_impl
->Init(this, index
);
2131 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
2133 wxString command
, testcmd
, sV
, sTmp
;
2134 sV
= verb
+ wxT("=");
2135 // list of verb = command pairs for this mimetype
2136 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
2139 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
2141 sTmp
= sPairs
->GetVerbCmd (i
);
2142 if ( sTmp
.Contains(sV
) )
2143 command
= sTmp
.AfterFirst(wxT('='));
2148 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
2152 wxString extensions
;
2153 const wxArrayString
& exts
= filetype
.GetExtensions();
2154 size_t nExts
= exts
.GetCount();
2155 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
2157 extensions
+= wxT(' ');
2159 extensions
+= exts
[nExt
];
2162 AddMimeTypeInfo(filetype
.GetMimeType(),
2164 filetype
.GetDescription());
2166 AddMailcapInfo(filetype
.GetMimeType(),
2167 filetype
.GetOpenCommand(),
2168 filetype
.GetPrintCommand(),
2170 filetype
.GetDescription());
2173 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2174 const wxString
& strExtensions
,
2175 const wxString
& strDesc
)
2177 // reading mailcap may find image/* , while
2178 // reading mime.types finds image/gif and no match is made
2179 // this means all the get functions don't work fix this
2181 wxString sTmp
= strExtensions
;
2183 wxArrayString sExts
;
2184 sTmp
.Trim().Trim(FALSE
);
2186 while (!sTmp
.empty())
2188 sExts
.Add (sTmp
.AfterLast(wxT(' ')));
2189 sTmp
= sTmp
.BeforeLast(wxT(' '));
2192 AddToMimeData (strMimeType
, strIcon
, NULL
, sExts
, strDesc
, TRUE
);
2195 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2196 const wxString
& strOpenCmd
,
2197 const wxString
& strPrintCmd
,
2198 const wxString
& strTest
,
2199 const wxString
& strDesc
)
2203 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2204 entry
->Add(wxT("open=") + strOpenCmd
);
2205 entry
->Add(wxT("print=") + strPrintCmd
);
2206 entry
->Add(wxT("test=") + strTest
);
2209 wxArrayString strExtensions
;
2211 AddToMimeData (strType
, strIcon
, entry
, strExtensions
, strDesc
, TRUE
);
2215 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2217 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2218 strFileName
.c_str());
2220 wxTextFile
file(strFileName
);
2221 #if defined(__WXGTK20__) && wxUSE_UNICODE
2222 if ( !file
.Open( wxConvUTF8
) )
2228 // the information we extract
2229 wxString strMimeType
, strDesc
, strExtensions
;
2231 size_t nLineCount
= file
.GetLineCount();
2232 const wxChar
*pc
= NULL
;
2233 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2236 // now we're at the start of the line
2237 pc
= file
[nLine
].c_str();
2240 // we didn't finish with the previous line yet
2245 while ( wxIsspace(*pc
) )
2248 // comment or blank line?
2249 if ( *pc
== wxT('#') || !*pc
) {
2250 // skip the whole line
2255 // detect file format
2256 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2257 if ( pEqualSign
== NULL
) {
2261 // first field is mime type
2262 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
2267 while ( wxIsspace(*pc
) )
2270 // take all the rest of the string
2273 // no description...
2280 // the string on the left of '=' is the field name
2281 wxString
strLHS(pc
, pEqualSign
- pc
);
2284 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2288 if ( *pc
== wxT('"') ) {
2289 // the string is quoted and ends at the matching quote
2290 pEnd
= wxStrchr(++pc
, wxT('"'));
2291 if ( pEnd
== NULL
) {
2292 wxLogWarning(_("Mime.types file %s, line %d: unterminated quoted string."),
2293 strFileName
.c_str(), nLine
+ 1);
2297 // unquoted string ends at the first space or at the end of
2299 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2303 // now we have the RHS (field value)
2304 wxString
strRHS(pc
, pEnd
- pc
);
2306 // check what follows this entry
2307 if ( *pEnd
== wxT('"') ) {
2312 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2315 // if there is something left, it may be either a '\\' to continue
2316 // the line or the next field of the same entry
2317 bool entryEnded
= *pc
== wxT('\0'),
2318 nextFieldOnSameLine
= FALSE
;
2319 if ( !entryEnded
) {
2320 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2323 // now see what we got
2324 if ( strLHS
== wxT("type") ) {
2325 strMimeType
= strRHS
;
2327 else if ( strLHS
.StartsWith(wxT("desc")) ) {
2330 else if ( strLHS
== wxT("exts") ) {
2331 strExtensions
= strRHS
;
2333 else if ( strLHS
== _T("icon") )
2335 // this one is simply ignored: it usually refers to Netscape
2336 // built in icons which are useless for us anyhow
2338 else if ( !strLHS
.StartsWith(_T("x-")) )
2340 // we suppose that all fields starting with "X-" are
2341 // unregistered extensions according to the standard practice,
2342 // but it may be worth telling the user about other junk in
2343 // his mime.types file
2344 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2345 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
2348 if ( !entryEnded
) {
2349 if ( !nextFieldOnSameLine
)
2351 //else: don't reset it
2353 // as we don't reset strMimeType, the next field in this entry
2354 // will be interpreted correctly.
2360 // depending on the format (Mosaic or Netscape) either space or comma
2361 // is used to separate the extensions
2362 strExtensions
.Replace(wxT(","), wxT(" "));
2364 // also deal with the leading dot
2365 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2367 strExtensions
.erase(0, 1);
2370 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2371 strExtensions
.c_str(),
2372 strMimeType
.c_str(),
2375 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2377 // finished with this line
2384 // ----------------------------------------------------------------------------
2385 // UNIX mailcap files parsing
2386 // ----------------------------------------------------------------------------
2388 // the data for a single MIME type
2389 struct MailcapLineData
2398 wxArrayString verbs
,
2406 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= FALSE
; }
2409 // process a non-standard (i.e. not the first or second one) mailcap field
2411 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2412 const wxString
& curField
)
2414 if ( curField
.empty() )
2420 // is this something of the form foo=bar?
2421 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2424 // split "LHS = RHS" in 2
2425 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2426 rhs
= curField
.AfterFirst(wxT('='));
2428 lhs
.Trim(TRUE
); // from right
2429 rhs
.Trim(FALSE
); // from left
2431 // it might be quoted
2432 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2434 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2437 // is it a command verb or something else?
2438 if ( lhs
== wxT("test") )
2440 if ( wxSystem(rhs
) == 0 )
2443 wxLogTrace(TRACE_MIME_TEST
,
2444 wxT("Test '%s' for mime type '%s' succeeded."),
2445 rhs
.c_str(), data
.type
.c_str());
2450 wxLogTrace(TRACE_MIME_TEST
,
2451 wxT("Test '%s' for mime type '%s' failed, skipping."),
2452 rhs
.c_str(), data
.type
.c_str());
2454 data
.testfailed
= TRUE
;
2457 else if ( lhs
== wxT("desc") )
2461 else if ( lhs
== wxT("x11-bitmap") )
2465 else if ( lhs
== wxT("notes") )
2469 else // not a (recognized) special case, must be a verb (e.g. "print")
2471 data
.verbs
.Add(lhs
);
2472 data
.commands
.Add(rhs
);
2475 else // '=' not found
2477 // so it must be a simple flag
2478 if ( curField
== wxT("needsterminal") )
2480 data
.needsterminal
= TRUE
;
2482 else if ( curField
== wxT("copiousoutput"))
2484 // copiousoutput impies that the viewer is a console program
2485 data
.needsterminal
=
2486 data
.copiousoutput
= TRUE
;
2488 else if ( !IsKnownUnimportantField(curField
) )
2497 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2500 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2501 strFileName
.c_str());
2503 wxTextFile
file(strFileName
);
2504 #if defined(__WXGTK20__) && wxUSE_UNICODE
2505 if ( !file
.Open( wxConvUTF8
) )
2511 // indices of MIME types (in m_aTypes) we already found in this file
2513 // (see the comments near the end of function for the reason we need this)
2514 wxArrayInt aIndicesSeenHere
;
2516 // accumulator for the current field
2518 curField
.reserve(1024);
2520 size_t nLineCount
= file
.GetLineCount();
2521 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2523 // now we're at the start of the line
2524 const wxChar
*pc
= file
[nLine
].c_str();
2527 while ( wxIsspace(*pc
) )
2530 // comment or empty string?
2531 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2537 // what field are we currently in? The first 2 are fixed and there may
2538 // be an arbitrary number of other fields parsed by
2539 // ProcessOtherMailcapField()
2541 // the first field is the MIME type
2547 } currentToken
= Field_Type
;
2549 // the flags and field values on the current line
2550 MailcapLineData data
;
2558 // interpret the next character literally (notice that
2559 // backslash can be used for line continuation)
2560 if ( *++pc
== wxT('\0') )
2562 // fetch the next line if there is one
2563 if ( nLine
== nLineCount
- 1 )
2565 // something is wrong, bail out
2568 wxLogDebug(wxT("Mailcap file %s, line %lu: '\\' on the end of the last line ignored."),
2569 strFileName
.c_str(),
2570 (unsigned long)nLine
+ 1);
2574 // pass to the beginning of the next line
2575 pc
= file
[++nLine
].c_str();
2577 // skip pc++ at the end of the loop
2583 // just a normal character
2589 cont
= FALSE
; // end of line reached, exit the loop
2591 // fall through to still process this field
2594 // trim whitespaces from both sides
2595 curField
.Trim(TRUE
).Trim(FALSE
);
2597 switch ( currentToken
)
2600 data
.type
= curField
.Lower();
2601 if ( data
.type
.empty() )
2603 // I don't think that this is a valid mailcap
2604 // entry, but try to interpret it somehow
2605 data
.type
= _T('*');
2608 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2610 // we interpret "type" as "type/*"
2611 data
.type
+= wxT("/*");
2614 currentToken
= Field_OpenCmd
;
2618 data
.cmdOpen
= curField
;
2620 currentToken
= Field_Other
;
2624 if ( !ProcessOtherMailcapField(data
, curField
) )
2626 // don't flood the user with error messages if
2627 // we don't understand something in his
2628 // mailcap, but give them in debug mode because
2629 // this might be useful for the programmer
2632 wxT("Mailcap file %s, line %lu: unknown field '%s' for the MIME type '%s' ignored."),
2633 strFileName
.c_str(),
2634 (unsigned long)nLine
+ 1,
2639 else if ( data
.testfailed
)
2641 // skip this entry entirely
2645 // it already has this value
2646 //currentToken = Field_Other;
2650 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2653 // next token starts immediately after ';'
2661 // continue in the same line
2665 // we read the entire entry, check what have we got
2666 // ------------------------------------------------
2668 // check that we really read something reasonable
2669 if ( currentToken
< Field_Other
)
2671 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry ignored."),
2672 strFileName
.c_str(), nLine
+ 1);
2677 // if the test command failed, it's as if the entry were not there at
2679 if ( data
.testfailed
)
2684 // support for flags:
2685 // 1. create an xterm for 'needsterminal'
2686 // 2. append "| $PAGER" for 'copiousoutput'
2688 // Note that the RFC says that having both needsterminal and
2689 // copiousoutput is probably a mistake, so it seems that running
2690 // programs with copiousoutput inside an xterm as it is done now
2691 // is a bad idea (FIXME)
2692 if ( data
.copiousoutput
)
2694 const wxChar
*p
= wxGetenv(_T("PAGER"));
2695 data
.cmdOpen
<< _T(" | ") << (p
? p
: _T("more"));
2698 if ( data
.needsterminal
)
2700 data
.cmdOpen
= wxString::Format(_T("xterm -e sh -c '%s'"),
2701 data
.cmdOpen
.c_str());
2704 if ( !data
.cmdOpen
.empty() )
2706 data
.verbs
.Insert(_T("open"), 0);
2707 data
.commands
.Insert(data
.cmdOpen
, 0);
2710 // we have to decide whether the new entry should replace any entries
2711 // for the same MIME type we had previously found or not
2714 // the fall back entries have the lowest priority, by definition
2721 // have we seen this one before?
2722 int nIndex
= m_aTypes
.Index(data
.type
);
2724 // and if we have, was it in this file? if not, we should
2725 // overwrite the previously seen one
2726 overwrite
= nIndex
== wxNOT_FOUND
||
2727 aIndicesSeenHere
.Index(nIndex
) == wxNOT_FOUND
;
2730 wxLogTrace(TRACE_MIME
, _T("mailcap %s: %s [%s]"),
2731 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2732 overwrite
? _T("replace") : _T("add"));
2734 int n
= AddToMimeData
2738 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2739 wxArrayString() /* extensions */,
2746 aIndicesSeenHere
.Add(n
);
2753 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2760 size_t count
= m_aTypes
.GetCount();
2761 for ( size_t n
= 0; n
< count
; n
++ )
2763 // don't return template types from here (i.e. anything containg '*')
2765 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
2767 mimetypes
.Add(type
);
2771 return mimetypes
.GetCount();
2774 // ----------------------------------------------------------------------------
2775 // writing to MIME type files
2776 // ----------------------------------------------------------------------------
2778 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2780 wxArrayString sMimeTypes
;
2781 ft
->GetMimeTypes (sMimeTypes
);
2785 for (i
= 0; i
< sMimeTypes
.GetCount(); i
++)
2787 sMime
= sMimeTypes
.Item(i
);
2788 int nIndex
= m_aTypes
.Index (sMime
);
2789 if ( nIndex
== wxNOT_FOUND
)
2791 // error if we get here ??
2796 WriteMimeInfo(nIndex
, TRUE
);
2797 m_aTypes
.RemoveAt(nIndex
);
2798 m_aEntries
.RemoveAt(nIndex
);
2799 m_aExtensions
.RemoveAt(nIndex
);
2800 m_aDescriptions
.RemoveAt(nIndex
);
2801 m_aIcons
.RemoveAt(nIndex
);
2804 // check data integrity
2805 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2806 m_aTypes
.Count() == m_aExtensions
.Count() &&
2807 m_aTypes
.Count() == m_aIcons
.Count() &&
2808 m_aTypes
.Count() == m_aDescriptions
.Count() );
2813 // ----------------------------------------------------------------------------
2814 // private functions
2815 // ----------------------------------------------------------------------------
2817 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2819 static const wxChar
*knownFields
[] =
2821 _T("x-mozilla-flags"),
2823 _T("textualnewlines"),
2826 wxString field
= fieldAll
.BeforeFirst(_T('='));
2827 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2829 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2837 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE