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 license (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 // ----------------------------------------------------------------------------
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"
72 #include "wx/dynarray.h"
73 #include "wx/confbase.h"
76 #include "wx/textfile.h"
79 #include "wx/tokenzr.h"
81 #include "wx/unix/mimetype.h"
83 // other standard headers
87 /* silence warnings for comparing unsigned int's <0 */
88 # pragma message disable unscomzer
91 // wxMimeTypeCommands stores the verbs defined for the given MIME type with
93 class wxMimeTypeCommands
96 wxMimeTypeCommands() { }
98 wxMimeTypeCommands(const wxArrayString
& verbs
,
99 const wxArrayString
& commands
)
105 // add a new verb with the command or replace the old value
106 void AddOrReplaceVerb(const wxString
& verb
, const wxString
& cmd
)
108 int n
= m_verbs
.Index(verb
, FALSE
/* ignore case */);
109 if ( n
== wxNOT_FOUND
)
120 void Add(const wxString
& s
)
122 m_verbs
.Add(s
.BeforeFirst(_T('=')));
123 m_commands
.Add(s
.AfterFirst(_T('=')));
126 // access the commands
127 size_t GetCount() const { return m_verbs
.GetCount(); }
128 const wxString
& GetVerb(size_t n
) const { return m_verbs
[n
]; }
129 const wxString
& GetCmd(size_t n
) const { return m_commands
[n
]; }
131 bool HasVerb(const wxString
& verb
) const
132 { return m_verbs
.Index(verb
) != wxNOT_FOUND
; }
134 wxString
GetCommandForVerb(const wxString
& verb
, size_t *idx
= NULL
) const
138 int n
= m_verbs
.Index(verb
);
139 if ( n
!= wxNOT_FOUND
)
141 s
= m_commands
[(size_t)n
];
149 // get a "verb=command" string
150 wxString
GetVerbCmd(size_t n
) const
152 return m_verbs
[n
] + _T('=') + m_commands
[n
];
156 wxArrayString m_verbs
,
160 // this class extends wxTextFile
163 class wxMimeTextFile
: public wxTextFile
167 wxMimeTextFile () : wxTextFile () {};
168 wxMimeTextFile (const wxString
& strFile
) : wxTextFile (strFile
) { };
170 int pIndexOf(const wxString
& sSearch
, bool bIncludeComments
= FALSE
, int iStart
= 0)
173 int nResult
= wxNOT_FOUND
;
174 if (i
>=GetLineCount()) return wxNOT_FOUND
;
176 wxString sTest
= sSearch
;
180 if (bIncludeComments
)
182 while ( (i
< GetLineCount()) )
186 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
192 while ( (i
< GetLineCount()) )
196 if ( ! sLine
.StartsWith(wxT("#")))
198 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
206 bool CommentLine(int nIndex
)
208 if (nIndex
<0) return FALSE
;
209 if (nIndex
>= (int)GetLineCount() ) return FALSE
;
210 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
214 bool CommentLine(const wxString
& sTest
)
216 int nIndex
= pIndexOf(sTest
);
217 if (nIndex
<0) return FALSE
;
218 if (nIndex
>= (int)GetLineCount() ) return FALSE
;
219 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
223 wxString
GetVerb (size_t i
)
225 if (i
> GetLineCount() ) return wxEmptyString
;
226 wxString sTmp
= GetLine(i
).BeforeFirst(wxT('='));
230 wxString
GetCmd (size_t i
)
232 if (i
> GetLineCount() ) return wxEmptyString
;
233 wxString sTmp
= GetLine(i
).AfterFirst(wxT('='));
238 // in case we're compiling in non-GUI mode
239 class WXDLLEXPORT wxIcon
;
241 // ----------------------------------------------------------------------------
243 // ----------------------------------------------------------------------------
245 // MIME code tracing mask
246 #define TRACE_MIME _T("mime")
248 // give trace messages about the results of mailcap tests
249 #define TRACE_MIME_TEST _T("mimetest")
251 // ----------------------------------------------------------------------------
253 // ----------------------------------------------------------------------------
255 // there are some fields which we don't understand but for which we don't give
256 // warnings as we know that they're not important - this function is used to
258 static bool IsKnownUnimportantField(const wxString
& field
);
260 // ----------------------------------------------------------------------------
262 // ----------------------------------------------------------------------------
265 // This class uses both mailcap and mime.types to gather information about file
268 // The information about mailcap file was extracted from metamail(1) sources
269 // and documentation and subsequently revised when I found the RFC 1524
272 // Format of mailcap file: spaces are ignored, each line is either a comment
273 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
274 // A backslash can be used to quote semicolons and newlines (and, in fact,
275 // anything else including itself).
277 // The first field is always the MIME type in the form of type/subtype (see RFC
278 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
279 // "type" which means the same as "type/*", although I'm not sure whether this
282 // The second field is always the command to run. It is subject to
283 // parameter/filename expansion described below.
285 // All the following fields are optional and may not be present at all. If
286 // they're present they may appear in any order, although each of them should
287 // appear only once. The optional fields are the following:
288 // * notes=xxx is an uninterpreted string which is silently ignored
289 // * test=xxx is the command to be used to determine whether this mailcap line
290 // applies to our data or not. The RHS of this field goes through the
291 // parameter/filename expansion (as the 2nd field) and the resulting string
292 // is executed. The line applies only if the command succeeds, i.e. returns 0
294 // * print=xxx is the command to be used to print (and not view) the data of
295 // this type (parameter/filename expansion is done here too)
296 // * edit=xxx is the command to open/edit the data of this type
297 // * needsterminal means that a new interactive console must be created for
299 // * copiousoutput means that the viewer doesn't interact with the user but
300 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
301 // good example), thus it might be a good idea to use some kind of paging
303 // * textualnewlines means not to perform CR/LF translation (not honored)
304 // * compose and composetyped fields are used to determine the program to be
305 // called to create a new message pert in the specified format (unused).
307 // Parameter/filename expansion:
308 // * %s is replaced with the (full) file name
309 // * %t is replaced with MIME type/subtype of the entry
310 // * for multipart type only %n is replaced with the nnumber of parts and %F is
311 // replaced by an array of (content-type, temporary file name) pairs for all
312 // message parts (TODO)
313 // * %{parameter} is replaced with the value of parameter taken from
314 // Content-type header line of the message.
317 // There are 2 possible formats for mime.types file, one entry per line (used
318 // for global mime.types and called Mosaic format) and "expanded" format where
319 // an entry takes multiple lines (used for users mime.types and called
322 // For both formats spaces are ignored and lines starting with a '#' are
323 // comments. Each record has one of two following forms:
324 // a) for "brief" format:
325 // <mime type> <space separated list of extensions>
326 // b) for "expanded" format:
327 // type=<mime type> BACKSLASH
328 // desc="<description>" BACKSLASH
329 // exts="<comma separated list of extensions>"
331 // (where BACKSLASH is a literal '\\' which we can't put here because cpp
334 // We try to autodetect the format of mime.types: if a non-comment line starts
335 // with "type=" we assume the second format, otherwise the first one.
337 // there may be more than one entry for one and the same mime type, to
338 // choose the right one we have to run the command specified in the test
339 // field on our data.
341 // ----------------------------------------------------------------------------
343 // ----------------------------------------------------------------------------
345 // GNOME stores the info we're interested in in several locations:
346 // 1. xxx.keys files under /usr/share/mime-info
347 // 2. xxx.keys files under ~/.gnome/mime-info
349 // The format of xxx.keys file is the following:
354 // with blank lines separating the entries and indented lines starting with
355 // TABs. We're interested in the field icon-filename whose value is the path
356 // containing the icon.
358 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
359 // just before the field name.
362 bool wxMimeTypesManagerImpl::CheckGnomeDirsExist ()
365 wxGetHomeDir( &gnomedir
);
366 wxString sTmp
= gnomedir
;
367 sTmp
= sTmp
+ wxT("/.gnome");
368 if (! wxDir::Exists ( sTmp
) )
370 if (!wxMkdir ( sTmp
))
372 wxLogError(_("Failed to create directory %s/.gnome."), sTmp
.c_str());
376 sTmp
= sTmp
+ wxT("/mime-info");
377 if (! wxDir::Exists ( sTmp
) )
379 if (!wxMkdir ( sTmp
))
381 wxLogError(_("Failed to create directory %s/mime-info."), sTmp
.c_str());
391 bool wxMimeTypesManagerImpl::WriteGnomeKeyFile(int index
, bool delete_index
)
394 wxGetHomeDir( &gnomedir
);
396 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.keys"));
397 // if this fails probably Gnome is not installed ??
398 // create it anyway as a private mime store
400 #if defined(__WXGTK20__) && wxUSE_UNICODE
401 if (! outfile
.Open ( wxConvUTF8
) )
403 if (! outfile
.Open () )
406 if (delete_index
) return FALSE
;
407 if (!CheckGnomeDirsExist() ) return FALSE
;
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
);
428 //for international use do something like this
429 //outfile.AddLine ( wxString( "\t[en_US]icon-filename=") + cmd );
430 outfile
.AddLine ( wxT( "\ticon-filename=") + m_aIcons
[index
] );
435 outfile
.CommentLine(nIndex
);
437 wxMimeTypeCommands sOld
;
438 size_t nOld
= nIndex
+ 1;
439 bool oldEntryEnd
= FALSE
;
440 while ( (nOld
< outfile
.GetLineCount() )&& (oldEntryEnd
== FALSE
))
442 sTmp
= outfile
.GetLine(nOld
);
443 if ( (sTmp
[0u] == wxT('\t')) || (sTmp
[0u] == wxT('#')) )
445 // we have another line to deal with
446 outfile
.CommentLine(nOld
);
448 // add the line to our store
449 if ((!delete_index
) && (sTmp
[0u] == wxT('\t')))
452 // next mimetpye ??or blank line
456 // list of entries in our data; these should all be in sOld,
457 // though sOld may also contain other entries , eg flags
460 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
462 for (i
=0; i
< entries
->GetCount(); i
++)
464 // replace any entries in sold that match verbs we know
465 sOld
.AddOrReplaceVerb ( entries
->GetVerb(i
), entries
->GetCmd (i
) );
467 //sOld should also contain the icon
468 if ( !m_aIcons
[index
].empty() )
469 sOld
.AddOrReplaceVerb ( wxT("icon-filename"), m_aIcons
[index
] );
471 for (i
=0; i
< sOld
.GetCount(); i
++)
473 sTmp
= sOld
.GetVerbCmd(i
);
474 sTmp
.Replace( wxT("%s"), wxT("%f") );
475 sTmp
= wxT("\t") + sTmp
;
477 outfile
.InsertLine ( sTmp
, nIndex
);
481 bool bTmp
= outfile
.Write ();
486 bool wxMimeTypesManagerImpl::WriteGnomeMimeFile(int index
, bool delete_index
)
489 wxGetHomeDir( &gnomedir
);
491 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.mime"));
492 // if this fails probably Gnome is not installed ??
493 // create it anyway as a private mime store
494 if (! outfile
.Open () )
496 if (delete_index
) return FALSE
;
497 if (!CheckGnomeDirsExist() ) return FALSE
;
500 wxString strType
= m_aTypes
[index
];
501 int nIndex
= outfile
.pIndexOf(strType
);
502 if ( nIndex
== wxNOT_FOUND
)
504 outfile
.AddLine ( strType
);
505 outfile
.AddLine ( wxT("\text:") + m_aExtensions
.Item(index
) );
511 outfile
.CommentLine(nIndex
);
512 outfile
.CommentLine(nIndex
+1);
515 {// check for next line being the right one to replace ??
516 wxString sOld
= outfile
.GetLine(nIndex
+1);
517 if (sOld
.Contains( wxT("\text: ")))
519 outfile
.GetLine(nIndex
+1) = wxT("\text: ") + m_aExtensions
.Item(index
);
523 outfile
.InsertLine( wxT("\text: ") + m_aExtensions
.Item(index
), nIndex
+ 1 );
527 bool bTmp
= outfile
.Write ();
532 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString
& filename
,
533 const wxArrayString
& dirs
)
535 wxTextFile
textfile(filename
);
536 #if defined(__WXGTK20__) && wxUSE_UNICODE
537 if ( !textfile
.Open( wxConvUTF8
) )
539 if ( !textfile
.Open() )
542 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
545 // values for the entry being parsed
546 wxString curMimeType
, curIconFile
;
547 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
549 // these are always empty in this file
550 wxArrayString strExtensions
;
554 size_t nLineCount
= textfile
.GetLineCount();
556 while ( nLine
< nLineCount
)
558 pc
= textfile
[nLine
].c_str();
559 if ( *pc
!= _T('#') )
562 wxLogTrace(TRACE_MIME
, wxT("--- Reading from Gnome file %s '%s' ---"),
563 filename
.c_str(),pc
);
566 if (sTmp
.Contains(wxT("=")) )
569 if (sTmp
.Contains( wxT("icon-filename=") ) )
571 curIconFile
= sTmp
.AfterFirst(wxT('='));
574 else if (sTmp
.Contains( wxT("icon_filename=") ) )
576 curIconFile
= sTmp
.AfterFirst(wxT('='));
577 if (!wxFileExists(curIconFile
))
579 size_t nDirs
= dirs
.GetCount();
580 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
583 newFile
.Printf(wxT("%s/pixmaps/document-icons/%s.png"),
585 curIconFile
.c_str());
586 if (wxFileExists(newFile
))
587 curIconFile
= newFile
;
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
634 if (! curMimeType
.empty())
636 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
643 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString
& filename
)
645 wxTextFile
textfile(filename
);
646 #if defined(__WXGTK20__) && wxUSE_UNICODE
647 if ( !textfile
.Open( wxConvUTF8
) )
649 if ( !textfile
.Open() )
652 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
655 // values for the entry being parsed
656 wxString curMimeType
, curExtList
;
659 size_t nLineCount
= textfile
.GetLineCount();
660 for ( size_t nLine
= 0;; nLine
++ )
662 if ( nLine
< nLineCount
)
664 pc
= textfile
[nLine
].c_str();
665 if ( *pc
== wxT('#') )
673 // so that we will fall into the "if" below
680 if ( !!curMimeType
&& !!curExtList
)
682 wxLogTrace(TRACE_MIME
, wxT("--- At end of Gnome file finding mimetype %s ---"),
683 curMimeType
.c_str());
685 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
690 // the end - this can only happen if nLine == nLineCount
699 // what do we have here?
700 if ( *pc
== wxT('\t') )
702 // this is a field=value ling
703 pc
++; // skip leading TAB
705 static const int lenField
= 4; // strlen("ext:")
706 if ( wxStrncmp(pc
, wxT("ext:"), lenField
) == 0 )
708 // skip ' ' which follows and take everything left until the end
710 curExtList
= pc
+ lenField
+ 1;
712 //else: some other field, we don't care
716 // this is the start of the new section
717 wxLogTrace(TRACE_MIME
, wxT("--- In Gnome file finding mimetype %s ---"),
718 curMimeType
.c_str());
720 if (! curMimeType
.empty())
721 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
725 while ( *pc
!= wxT(':') && *pc
!= wxT('\0') )
727 curMimeType
+= *pc
++;
734 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
735 const wxString
& dirbase
, const wxArrayString
& dirs
)
737 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
738 _T("base directory shouldn't end with a slash") );
740 wxString dirname
= dirbase
;
741 dirname
<< wxT("/mime-info");
743 if ( !wxDir::Exists(dirname
) )
747 if ( !dir
.IsOpened() )
750 // we will concatenate it with filename to get the full path below
754 bool cont
= dir
.GetFirst(&filename
, _T("*.mime"), wxDIR_FILES
);
757 LoadGnomeMimeTypesFromMimeFile(dirname
+ filename
);
759 cont
= dir
.GetNext(&filename
);
762 cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
765 LoadGnomeDataFromKeyFile(dirname
+ filename
, dirs
);
767 cont
= dir
.GetNext(&filename
);
774 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString
& sExtraDir
)
777 dirs
.Add(wxT("/usr/share"));
778 dirs
.Add(wxT("/usr/local/share"));
781 wxGetHomeDir( &gnomedir
);
782 gnomedir
+= wxT("/.gnome");
783 dirs
.Add( gnomedir
);
784 if (!sExtraDir
.empty()) dirs
.Add( sExtraDir
);
786 size_t nDirs
= dirs
.GetCount();
787 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
789 LoadGnomeMimeFilesFromDir(dirs
[nDir
], dirs
);
793 // ----------------------------------------------------------------------------
795 // ----------------------------------------------------------------------------
798 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
799 // may be found in either of the following locations
801 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
802 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
804 // The format of a .kdelnk file is almost the same as the one used by
805 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
806 // value for the entry "Type"
808 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
809 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
811 bool wxMimeTypesManagerImpl::CheckKDEDirsExist ( const wxString
& sOK
, const wxString
& sTest
)
816 if (wxDir::Exists(sOK
)) return TRUE
;
821 wxString sStart
= sOK
+ wxT("/") + sTest
.BeforeFirst(wxT('/'));
822 if (!wxDir::Exists(sStart
)) wxMkdir(sStart
);
823 wxString sEnd
= sTest
.AfterFirst(wxT('/'));
824 return CheckKDEDirsExist(sStart
, sEnd
);
828 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index
, bool delete_index
)
830 wxMimeTextFile appoutfile
, mimeoutfile
;
831 wxString sHome
= wxGetHomeDir();
832 wxString sTmp
= wxT(".kde/share/mimelnk/");
833 wxString sMime
= m_aTypes
[index
];
834 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.BeforeFirst(wxT('/')) );
835 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
+ wxT(".kdelnk");
838 bool bMimeExists
= mimeoutfile
.Open (sTmp
);
841 bTemp
= mimeoutfile
.Create (sTmp
);
842 // some unknown error eg out of disk space
843 if (!bTemp
) return FALSE
;
846 sTmp
= wxT(".kde/share/applnk/");
847 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.AfterFirst(wxT('/')) );
848 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
.AfterFirst(wxT('/')) + wxT(".kdelnk");
851 bAppExists
= appoutfile
.Open (sTmp
);
854 bTemp
= appoutfile
.Create (sTmp
);
855 // some unknown error eg out of disk space
856 if (!bTemp
) return FALSE
;
859 // fixed data; write if new file
862 mimeoutfile
.AddLine(wxT("#KDE Config File"));
863 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
864 mimeoutfile
.AddLine(wxT("Version=1.0"));
865 mimeoutfile
.AddLine(wxT("Type=MimeType"));
866 mimeoutfile
.AddLine(wxT("MimeType=") + sMime
);
871 mimeoutfile
.AddLine(wxT("#KDE Config File"));
872 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
873 appoutfile
.AddLine(wxT("Version=1.0"));
874 appoutfile
.AddLine(wxT("Type=Application"));
875 appoutfile
.AddLine(wxT("MimeType=") + sMime
+ wxT(';'));
880 mimeoutfile
.CommentLine(wxT("Comment="));
882 mimeoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
883 appoutfile
.CommentLine(wxT("Name="));
885 appoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
887 sTmp
= m_aIcons
[index
];
888 // we can either give the full path, or the shortfilename if its in
889 // one of the directories we search
890 mimeoutfile
.CommentLine(wxT("Icon=") );
891 if (!delete_index
) mimeoutfile
.AddLine(wxT("Icon=") + sTmp
);
892 appoutfile
.CommentLine(wxT("Icon=") );
893 if (!delete_index
) appoutfile
.AddLine(wxT("Icon=") + sTmp
);
895 sTmp
= wxT(" ") + m_aExtensions
[index
];
897 wxStringTokenizer
tokenizer(sTmp
, _T(" "));
898 sTmp
= wxT("Patterns=");
899 mimeoutfile
.CommentLine(sTmp
);
900 while ( tokenizer
.HasMoreTokens() )
902 // holds an extension; need to change it to *.ext;
903 wxString e
= wxT("*.") + tokenizer
.GetNextToken() + wxT(";");
906 if (!delete_index
) mimeoutfile
.AddLine(sTmp
);
908 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
909 // if we don't find open just have an empty string ... FIX this
910 sTmp
= entries
->GetCommandForVerb(_T("open"));
911 sTmp
.Replace( wxT("%s"), wxT("%f") );
913 mimeoutfile
.CommentLine(wxT("DefaultApp=") );
914 if (!delete_index
) mimeoutfile
.AddLine(wxT("DefaultApp=") + sTmp
);
916 sTmp
.Replace( wxT("%f"), wxT("") );
917 appoutfile
.CommentLine(wxT("Exec="));
918 if (!delete_index
) appoutfile
.AddLine(wxT("Exec=") + sTmp
);
920 if (entries
->GetCount() > 1)
922 //other actions as well as open
926 if (mimeoutfile
.Write ()) bTemp
= TRUE
;
927 mimeoutfile
.Close ();
928 if (appoutfile
.Write ()) bTemp
= TRUE
;
936 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString
& dirbase
,
937 const wxString
& subdir
,
938 const wxString
& filename
,
939 const wxArrayString
& icondirs
)
942 if ( !file
.Open(dirbase
+ filename
) ) return;
944 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
945 (dirbase
+filename
).c_str());
947 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
949 wxString mimetype
, mime_desc
, strIcon
;
951 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
952 if (nIndex
== wxNOT_FOUND
)
954 // construct mimetype from the directory name and the basename of the
955 // file (it always has .kdelnk extension)
956 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
958 else mimetype
= file
.GetCmd (nIndex
);
960 // first find the description string: it is the value in either "Comment="
961 // line or "Comment[<locale_name>]=" one
962 nIndex
= wxNOT_FOUND
;
966 wxLocale
*locale
= wxGetLocale();
969 // try "Comment[locale name]" first
970 comment
<< _T("Comment[") + locale
->GetName() + _T("]=");
971 nIndex
= file
.pIndexOf(comment
);
975 if ( nIndex
== wxNOT_FOUND
)
977 comment
= _T("Comment=");
978 nIndex
= file
.pIndexOf(comment
);
981 if ( nIndex
!= wxNOT_FOUND
) mime_desc
= file
.GetCmd(nIndex
);
982 //else: no description
984 // next find the extensions
985 wxString mime_extension
;
987 nIndex
= file
.pIndexOf(_T("Patterns="));
988 if ( nIndex
!= wxNOT_FOUND
)
990 wxString exts
= file
.GetCmd (nIndex
);;
992 wxStringTokenizer
tokenizer(exts
, _T(";"));
993 while ( tokenizer
.HasMoreTokens() )
995 wxString e
= tokenizer
.GetNextToken();
996 if ( e
.Left(2) != _T("*.") )
997 continue; // don't support too difficult patterns
999 if ( !mime_extension
.empty() )
1001 // separate from the previous ext
1002 mime_extension
<< _T(' ');
1005 mime_extension
<< e
.Mid(2);
1008 sExts
.Add(mime_extension
);
1011 // ok, now we can take care of icon:
1013 nIndex
= file
.pIndexOf(_T("Icon="));
1014 if ( nIndex
!= wxNOT_FOUND
)
1016 strIcon
= file
.GetCmd(nIndex
);
1017 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
1018 //it could be the real path, but more often a short name
1019 if (!wxFileExists(strIcon
))
1021 // icon is just the short name
1022 if ( !strIcon
.empty() )
1024 // we must check if the file exists because it may be stored
1025 // in many locations, at least ~/.kde and $KDEDIR
1026 size_t nDir
, nDirs
= icondirs
.GetCount();
1027 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
1028 if (wxFileExists(icondirs
[nDir
] + strIcon
))
1030 strIcon
.Prepend(icondirs
[nDir
]);
1031 wxLogTrace(TRACE_MIME
, wxT(" iconfile %s"), strIcon
.c_str());
1037 // now look for lines which know about the application
1038 // exec= or DefaultApp=
1040 nIndex
= file
.pIndexOf(wxT("DefaultApp"));
1042 if ( nIndex
== wxNOT_FOUND
)
1044 // no entry try exec
1045 nIndex
= file
.pIndexOf(wxT("Exec"));
1048 if ( nIndex
!= wxNOT_FOUND
)
1050 wxString sTmp
= file
.GetCmd(nIndex
);
1051 // we expect %f; others including %F and %U and %u are possible
1052 if (0 == sTmp
.Replace ( wxT("%f"), wxT("%s") ))
1053 sTmp
= sTmp
+ wxT(" %s");
1054 entry
->AddOrReplaceVerb (wxString(wxT("open")), sTmp
);
1057 AddToMimeData (mimetype
, strIcon
, entry
, sExts
, mime_desc
);
1060 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString
& dirbase
,
1061 const wxString
& subdir
,
1062 const wxArrayString
& icondirs
)
1064 wxString dirname
= dirbase
;
1067 if ( !dir
.IsOpened() )
1070 wxLogTrace(TRACE_MIME
, wxT("--- Loading from KDE directory %s ---"),
1076 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
1079 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1081 cont
= dir
.GetNext(&filename
);
1083 // new standard for Gnome and KDE
1084 cont
= dir
.GetFirst(&filename
, _T("*.desktop"), wxDIR_FILES
);
1087 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1089 cont
= dir
.GetNext(&filename
);
1093 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString
& dirbase
,
1094 const wxArrayString
& icondirs
)
1096 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1097 _T("base directory shouldn't end with a slash") );
1099 wxString dirname
= dirbase
;
1100 dirname
<< _T("/mimelnk");
1102 if ( !wxDir::Exists(dirname
) )
1106 if ( !dir
.IsOpened() )
1109 // we will concatenate it with dir name to get the full path below
1113 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
1116 LoadKDELinksForMimeType(dirname
, subdir
, icondirs
);
1118 cont
= dir
.GetNext(&subdir
);
1122 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString
& sExtraDir
)
1125 wxArrayString icondirs
;
1127 // settings in ~/.kde have maximal priority
1128 dirs
.Add(wxGetHomeDir() + wxT("/.kde/share"));
1129 icondirs
.Add(wxGetHomeDir() + wxT("/.kde/share/icons/"));
1131 // the variable KDEDIR is set when KDE is running
1132 const wxChar
*kdedir
= wxGetenv( wxT("KDEDIR") );
1135 dirs
.Add( wxString(kdedir
) + wxT("/share") );
1136 icondirs
.Add( wxString(kdedir
) + wxT("/share/icons/") );
1140 // try to guess KDEDIR
1141 dirs
.Add(_T("/usr/share"));
1142 dirs
.Add(_T("/opt/kde/share"));
1143 icondirs
.Add(_T("/usr/share/icons/"));
1144 icondirs
.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
1145 icondirs
.Add(_T("/opt/kde/share/icons/"));
1148 if (!sExtraDir
.empty()) dirs
.Add (sExtraDir
);
1149 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1151 size_t nDirs
= dirs
.GetCount();
1152 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1154 LoadKDELinkFilesFromDir(dirs
[nDir
], icondirs
);
1158 // ----------------------------------------------------------------------------
1159 // wxFileTypeImpl (Unix)
1160 // ----------------------------------------------------------------------------
1162 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1166 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1168 sTmp
= m_manager
->GetCommand ( verb
, m_index
[i
] );
1172 return wxFileType::ExpandCommand(sTmp
, params
);
1175 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
,
1176 wxString
*iconFile
/*= NULL */,
1177 int *iconIndex
/*= NULL*/) const
1183 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1185 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1188 if ( sTmp
.empty () ) return FALSE
;
1192 if (sTmp
.Right(4).MakeUpper() == _T(".XPM"))
1195 icn
= wxIcon(sTmp
, wxBITMAP_TYPE_ANY
);
1200 if (iconFile
) *iconFile
= sTmp
;
1201 if (iconIndex
) *iconIndex
= 0;
1211 wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1214 for (size_t i
= 0; i
< m_index
.GetCount(); i
++)
1215 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1220 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1221 wxArrayString
*commands
,
1222 const wxFileType::MessageParameters
& params
) const
1225 wxString vrb
, cmd
, sTmp
;
1227 wxMimeTypeCommands
* sPairs
;
1229 // verbs and commands have been cleared already in mimecmn.cpp...
1230 // if we find no entries in the exact match, try the inexact match
1231 for (size_t n
= 0; ((count
==0) && (n
< m_index
.GetCount())); n
++)
1233 // list of verb = command pairs for this mimetype
1234 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1236 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
1238 vrb
= sPairs
->GetVerb(i
);
1239 // some gnome entries have . inside
1240 vrb
= vrb
.AfterLast(wxT('.'));
1241 cmd
= sPairs
->GetCmd (i
);
1244 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1246 if ( vrb
.IsSameAs (wxT("open")))
1248 verbs
->Insert(vrb
,0u);
1249 commands
->Insert(cmd
,0u);
1254 commands
->Add (cmd
);
1265 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1267 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1270 // one extension in the space or comma delimitid list
1272 for ( const wxChar
*p
= strExtensions
;; p
++ ) {
1273 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1274 if ( !strExt
.empty() ) {
1275 extensions
.Add(strExt
);
1278 //else: repeated spaces (shouldn't happen, but it's not that
1279 // important if it does happen)
1281 if ( *p
== wxT('\0') )
1284 else if ( *p
== wxT('.') ) {
1285 // remove the dot from extension (but only if it's the first char)
1286 if ( !strExt
.empty() ) {
1289 //else: no, don't append it
1299 // set an arbitrary command,
1300 // could adjust the code to ask confirmation if it already exists and
1301 // overwriteprompt is TRUE, but this is currently ignored as *Associate* has
1302 // no overwrite prompt
1303 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
, const wxString
& verb
, bool overwriteprompt
/*= TRUE*/)
1305 wxArrayString strExtensions
;
1306 wxString strDesc
, strIcon
;
1308 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1309 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1311 wxArrayString strTypes
;
1312 GetMimeTypes (strTypes
);
1313 if (strTypes
.GetCount() < 1) return FALSE
;
1317 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1319 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1326 // ignore index on the grouds that we only have one icon in a Unix file
1327 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
/*= wxEmptyString*/, int /*index = 0*/)
1329 if (strIcon
.empty()) return FALSE
;
1330 wxArrayString strExtensions
;
1333 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1335 wxArrayString strTypes
;
1336 GetMimeTypes (strTypes
);
1337 if (strTypes
.GetCount() < 1) return FALSE
;
1341 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1343 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1350 // ----------------------------------------------------------------------------
1351 // wxMimeTypesManagerImpl (Unix)
1352 // ----------------------------------------------------------------------------
1355 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1357 m_initialized
= FALSE
;
1358 m_mailcapStylesInited
= 0;
1361 // read system and user mailcaps and other files
1362 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1363 const wxString
& sExtraDir
)
1365 // read mimecap amd mime.types
1366 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1367 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1368 GetMimeInfo(sExtraDir
);
1370 // read GNOME tables
1371 if ( mailcapStyles
& wxMAILCAP_GNOME
)
1372 GetGnomeMimeInfo(sExtraDir
);
1375 if ( mailcapStyles
& wxMAILCAP_KDE
)
1376 GetKDEMimeInfo(sExtraDir
);
1378 m_mailcapStylesInited
|= mailcapStyles
;
1381 // clear data so you can read another group of WM files
1382 void wxMimeTypesManagerImpl::ClearData()
1386 m_aExtensions
.Clear ();
1387 m_aDescriptions
.Clear ();
1389 WX_CLEAR_ARRAY(m_aEntries
);
1392 m_mailcapStylesInited
= 0;
1395 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1401 void wxMimeTypesManagerImpl::GetMimeInfo (const wxString
& sExtraDir
)
1403 // read this for netscape or Metamail formats
1405 // directories where we look for mailcap and mime.types by default
1406 // used by netscape and pine and other mailers, using 2 different formats!
1408 // (taken from metamail(1) sources)
1410 // although RFC 1524 specifies the search path of
1411 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1412 // places - OTOH, the RFC also says that this path can be changed with
1413 // MAILCAPS environment variable (containing the colon separated full
1414 // filenames to try) which is not done yet (TODO?)
1416 wxString strHome
= wxGetenv(wxT("HOME"));
1419 dirs
.Add ( strHome
+ wxT("/.") );
1420 dirs
.Add ( wxT("/etc/") );
1421 dirs
.Add ( wxT("/usr/etc/") );
1422 dirs
.Add ( wxT("/usr/local/etc/") );
1423 dirs
.Add ( wxT("/etc/mail/") );
1424 dirs
.Add ( wxT("/usr/public/lib/") );
1425 if (!sExtraDir
.empty()) dirs
.Add ( sExtraDir
+ wxT("/") );
1427 size_t nDirs
= dirs
.GetCount();
1428 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1430 wxString file
= dirs
[nDir
] + wxT("mailcap");
1431 if ( wxFile::Exists(file
) ) {
1435 file
= dirs
[nDir
] + wxT("mime.types");
1436 if ( wxFile::Exists(file
) ) {
1437 ReadMimeTypes(file
);
1443 bool wxMimeTypesManagerImpl::WriteToMimeTypes (int index
, bool delete_index
)
1445 // check we have the right manager
1446 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1450 wxString strHome
= wxGetenv(wxT("HOME"));
1452 // and now the users mailcap
1453 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1455 wxMimeTextFile file
;
1456 if ( wxFile::Exists(strUserMailcap
) )
1458 bTemp
= file
.Open(strUserMailcap
);
1462 if (delete_index
) return FALSE
;
1463 bTemp
= file
.Create(strUserMailcap
);
1468 // test for netscape's header and return FALSE if its found
1469 nIndex
= file
.pIndexOf (wxT("#--Netscape"));
1470 if (nIndex
!= wxNOT_FOUND
)
1472 wxASSERT_MSG(FALSE
,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1475 // write it in alternative format
1476 // get rid of unwanted entries
1477 wxString strType
= m_aTypes
[index
];
1478 nIndex
= file
.pIndexOf (strType
);
1479 // get rid of all the unwanted entries...
1480 if (nIndex
!= wxNOT_FOUND
) file
.CommentLine (nIndex
);
1484 // add the new entries in
1485 wxString sTmp
= strType
.Append (wxT(' '), 40-strType
.Len() );
1486 sTmp
= sTmp
+ m_aExtensions
[index
];
1487 file
.AddLine (sTmp
);
1491 bTemp
= file
.Write ();
1497 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes (int index
, bool delete_index
)
1499 //check we have the right managers
1500 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1504 wxString strHome
= wxGetenv(wxT("HOME"));
1506 // and now the users mailcap
1507 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1509 wxMimeTextFile file
;
1510 if ( wxFile::Exists(strUserMailcap
) )
1512 bTemp
= file
.Open(strUserMailcap
);
1516 if (delete_index
) return FALSE
;
1517 bTemp
= file
.Create(strUserMailcap
);
1522 // write it in the format that Netscape uses
1524 // test for netscape's header and insert if required...
1525 // this is a comment so use TRUE
1526 nIndex
= file
.pIndexOf (wxT("#--Netscape"), TRUE
);
1527 if (nIndex
== wxNOT_FOUND
)
1529 // either empty file or metamail format
1530 // at present we can't cope with mixed formats, so exit to preseve
1531 // metamail entreies
1532 if (file
.GetLineCount () > 0)
1534 wxASSERT_MSG(FALSE
, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1537 file
.InsertLine (wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1541 wxString strType
= wxT("type=") + m_aTypes
[index
];
1542 nIndex
= file
.pIndexOf (strType
);
1543 // get rid of all the unwanted entries...
1544 if (nIndex
!= wxNOT_FOUND
)
1546 wxString sOld
= file
[nIndex
];
1547 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1549 file
.CommentLine(nIndex
);
1550 sOld
= file
[nIndex
];
1551 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1554 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1556 else nIndex
= (int) file
.GetLineCount();
1558 wxString sTmp
= strType
+ wxT(" \\");
1559 if (!delete_index
) file
.InsertLine (sTmp
, nIndex
);
1560 if ( ! m_aDescriptions
.Item(index
).empty() )
1562 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1566 file
.InsertLine (sTmp
, nIndex
);
1569 wxString sExts
= m_aExtensions
.Item(index
);
1570 sTmp
= wxT("exts=\"") + sExts
.Trim(FALSE
).Trim() + wxT("\"");
1574 file
.InsertLine (sTmp
, nIndex
);
1577 bTemp
= file
.Write ();
1584 bool wxMimeTypesManagerImpl::WriteToMailCap (int index
, bool delete_index
)
1586 //check we have the right managers
1587 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1588 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1592 wxString strHome
= wxGetenv(wxT("HOME"));
1594 // and now the users mailcap
1595 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1597 wxMimeTextFile file
;
1598 if ( wxFile::Exists(strUserMailcap
) )
1600 bTemp
= file
.Open(strUserMailcap
);
1604 if (delete_index
) return FALSE
;
1605 bTemp
= file
.Create(strUserMailcap
);
1609 // now got a file we can write to ....
1610 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1612 wxString sCmd
= entries
->GetCommandForVerb(_T("open"), &iOpen
);
1615 sTmp
= m_aTypes
[index
];
1617 int nIndex
= file
.pIndexOf(sTmp
);
1618 // get rid of all the unwanted entries...
1619 if (nIndex
== wxNOT_FOUND
)
1621 nIndex
= (int) file
.GetLineCount();
1625 sOld
= file
[nIndex
];
1626 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1628 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1630 file
.CommentLine(nIndex
);
1631 if (nIndex
< (int) file
.GetLineCount()) sOld
= sOld
+ file
[nIndex
];
1633 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1636 sTmp
= sTmp
+ wxT(";") + sCmd
; //includes wxT(" %s ");
1638 // write it in the format that Netscape uses (default)
1639 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1641 if (! delete_index
) file
.InsertLine (sTmp
, nIndex
);
1645 // write extended format
1648 // todo FIX this code;
1650 // sOld holds all the entries, but our data store only has some
1651 // eg test= is not stored
1653 // so far we have written the mimetype and command out
1654 wxStringTokenizer
sT (sOld
, wxT(";\\"));
1655 if (sT
.CountTokens () > 2)
1657 // first one mimetype; second one command, rest unknown...
1659 s
= sT
.GetNextToken();
1660 s
= sT
.GetNextToken();
1663 s
= sT
.GetNextToken();
1664 while ( ! s
.empty() )
1666 bool bKnownToken
= FALSE
;
1667 if (s
.Contains(wxT("description="))) bKnownToken
= TRUE
;
1668 if (s
.Contains(wxT("x11-bitmap="))) bKnownToken
= TRUE
;
1670 for (i
=0; i
< entries
->GetCount(); i
++)
1672 if (s
.Contains(entries
->GetVerb(i
))) bKnownToken
= TRUE
;
1676 sTmp
= sTmp
+ wxT("; \\");
1677 file
.InsertLine (sTmp
, nIndex
);
1680 s
= sT
.GetNextToken ();
1685 if (! m_aDescriptions
[index
].empty() )
1687 sTmp
= sTmp
+ wxT("; \\");
1688 file
.InsertLine (sTmp
, nIndex
);
1690 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1693 if (! m_aIcons
[index
].empty() )
1695 sTmp
= sTmp
+ wxT("; \\");
1696 file
.InsertLine (sTmp
, nIndex
);
1698 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1700 if ( entries
->GetCount() > 1 )
1704 for (i
=0; i
< entries
->GetCount(); i
++)
1707 sTmp
= sTmp
+ wxT("; \\");
1708 file
.InsertLine (sTmp
, nIndex
);
1710 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1714 file
.InsertLine (sTmp
, nIndex
);
1718 bTemp
= file
.Write ();
1725 wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1729 wxString strType
= ftInfo
.GetMimeType ();
1730 wxString strDesc
= ftInfo
.GetDescription ();
1731 wxString strIcon
= ftInfo
.GetIconFile ();
1733 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1735 if ( ! ftInfo
.GetOpenCommand().empty())
1736 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand () + wxT(" %s "));
1737 if ( ! ftInfo
.GetPrintCommand ().empty())
1738 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand () + wxT(" %s "));
1740 // now find where these extensions are in the data store and remove them
1741 wxArrayString sA_Exts
= ftInfo
.GetExtensions ();
1742 wxString sExt
, sExtStore
;
1744 for (i
=0; i
< sA_Exts
.GetCount(); i
++)
1746 sExt
= sA_Exts
.Item(i
);
1747 //clean up to just a space before and after
1748 sExt
.Trim().Trim(FALSE
);
1749 sExt
= wxT(' ') + sExt
+ wxT(' ');
1750 for (nIndex
= 0; nIndex
< m_aExtensions
.GetCount(); nIndex
++)
1752 sExtStore
= m_aExtensions
.Item(nIndex
);
1753 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0) m_aExtensions
.Item(nIndex
) = sExtStore
;
1758 if ( !DoAssociation (strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1761 return GetFileTypeFromMimeType(strType
);
1765 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1766 const wxString
& strIcon
,
1767 wxMimeTypeCommands
*entry
,
1768 const wxArrayString
& strExtensions
,
1769 const wxString
& strDesc
)
1771 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, TRUE
);
1773 if ( nIndex
== wxNOT_FOUND
)
1776 return WriteMimeInfo (nIndex
, FALSE
);
1779 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
1783 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
1785 // write in metamail format;
1786 if (WriteToMimeTypes (nIndex
, delete_mime
) )
1787 if ( WriteToMailCap (nIndex
, delete_mime
) )
1790 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
1792 // write in netsacpe format;
1793 if (WriteToNSMimeTypes (nIndex
, delete_mime
) )
1794 if ( WriteToMailCap (nIndex
, delete_mime
) )
1797 if (m_mailcapStylesInited
& wxMAILCAP_GNOME
)
1799 // write in Gnome format;
1800 if (WriteGnomeMimeFile (nIndex
, delete_mime
) )
1801 if (WriteGnomeKeyFile (nIndex
, delete_mime
) )
1804 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
1806 // write in KDE format;
1807 if (WriteKDEMimeFile (nIndex
, delete_mime
) )
1814 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
1815 const wxString
& strIcon
,
1816 wxMimeTypeCommands
*entry
,
1817 const wxArrayString
& strExtensions
,
1818 const wxString
& strDesc
,
1819 bool replaceExisting
)
1823 // ensure mimetype is always lower case
1824 wxString mimeType
= strType
.Lower();
1826 // is this a known MIME type?
1827 int nIndex
= m_aTypes
.Index(mimeType
);
1828 if ( nIndex
== wxNOT_FOUND
)
1831 m_aTypes
.Add(mimeType
);
1832 m_aIcons
.Add(strIcon
);
1833 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
1835 // change nIndex so we can use it below to add the extensions
1836 nIndex
= m_aExtensions
.Add(wxEmptyString
);
1838 m_aDescriptions
.Add(strDesc
);
1840 else // yes, we already have it
1842 if ( replaceExisting
)
1844 // if new description change it
1845 if ( !strDesc
.empty())
1846 m_aDescriptions
[nIndex
] = strDesc
;
1848 // if new icon change it
1849 if ( !strIcon
.empty())
1850 m_aIcons
[nIndex
] = strIcon
;
1854 delete m_aEntries
[nIndex
];
1855 m_aEntries
[nIndex
] = entry
;
1858 else // add data we don't already have ...
1860 // if new description add only if none
1861 if ( m_aDescriptions
[nIndex
].empty() )
1862 m_aDescriptions
[nIndex
] = strDesc
;
1864 // if new icon and no existing icon
1865 if ( m_aIcons
[nIndex
].empty () )
1866 m_aIcons
[nIndex
] = strIcon
;
1868 // add any new entries...
1871 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
1873 size_t count
= entry
->GetCount();
1874 for ( size_t i
= 0; i
< count
; i
++ )
1876 const wxString
& verb
= entry
->GetVerb(i
);
1877 if ( !entryOld
->HasVerb(verb
) )
1879 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
1886 // always add the extensions to this mimetype
1887 wxString
& exts
= m_aExtensions
[nIndex
];
1889 // add all extensions we don't have yet
1890 size_t count
= strExtensions
.GetCount();
1891 for ( size_t i
= 0; i
< count
; i
++ )
1893 wxString ext
= strExtensions
[i
] + _T(' ');
1895 if ( exts
.Find(ext
) == wxNOT_FOUND
)
1901 // check data integrity
1902 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1903 m_aTypes
.Count() == m_aExtensions
.Count() &&
1904 m_aTypes
.Count() == m_aIcons
.Count() &&
1905 m_aTypes
.Count() == m_aDescriptions
.Count() );
1912 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1919 size_t count
= m_aExtensions
.GetCount();
1920 for ( size_t n
= 0; n
< count
; n
++ )
1922 wxStringTokenizer
tk(m_aExtensions
[n
], _T(' '));
1924 while ( tk
.HasMoreTokens() )
1926 // consider extensions as not being case-sensitive
1927 if ( tk
.GetNextToken().IsSameAs(ext
, FALSE
/* no case */) )
1930 wxFileType
*fileType
= new wxFileType
;
1931 fileType
->m_impl
->Init(this, n
);
1942 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1946 wxFileType
* fileType
= NULL
;
1947 // mime types are not case-sensitive
1948 wxString
mimetype(mimeType
);
1949 mimetype
.MakeLower();
1951 // first look for an exact match
1952 int index
= m_aTypes
.Index(mimetype
);
1953 if ( index
!= wxNOT_FOUND
)
1955 fileType
= new wxFileType
;
1956 fileType
->m_impl
->Init(this, index
);
1959 // then try to find "text/*" as match for "text/plain" (for example)
1960 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1961 // the whole string - ok.
1963 index
= wxNOT_FOUND
;
1964 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1966 size_t nCount
= m_aTypes
.Count();
1967 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1968 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1969 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1976 if ( index
!= wxNOT_FOUND
)
1978 fileType
= new wxFileType
;
1979 fileType
->m_impl
->Init(this, index
);
1985 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
1987 wxString command
, testcmd
, sV
, sTmp
;
1988 sV
= verb
+ wxT("=");
1989 // list of verb = command pairs for this mimetype
1990 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
1993 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
1995 sTmp
= sPairs
->GetVerbCmd (i
);
1996 if ( sTmp
.Contains(sV
) )
1997 command
= sTmp
.AfterFirst(wxT('='));
2002 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
2006 wxString extensions
;
2007 const wxArrayString
& exts
= filetype
.GetExtensions();
2008 size_t nExts
= exts
.GetCount();
2009 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
2011 extensions
+= wxT(' ');
2013 extensions
+= exts
[nExt
];
2016 AddMimeTypeInfo(filetype
.GetMimeType(),
2018 filetype
.GetDescription());
2020 AddMailcapInfo(filetype
.GetMimeType(),
2021 filetype
.GetOpenCommand(),
2022 filetype
.GetPrintCommand(),
2024 filetype
.GetDescription());
2027 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2028 const wxString
& strExtensions
,
2029 const wxString
& strDesc
)
2031 // reading mailcap may find image/* , while
2032 // reading mime.types finds image/gif and no match is made
2033 // this means all the get functions don't work fix this
2035 wxString sTmp
= strExtensions
;
2037 wxArrayString sExts
;
2038 sTmp
.Trim().Trim(FALSE
);
2040 while (!sTmp
.empty())
2042 sExts
.Add (sTmp
.AfterLast(wxT(' ')));
2043 sTmp
= sTmp
.BeforeLast(wxT(' '));
2046 AddToMimeData (strMimeType
, strIcon
, NULL
, sExts
, strDesc
, TRUE
);
2049 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2050 const wxString
& strOpenCmd
,
2051 const wxString
& strPrintCmd
,
2052 const wxString
& strTest
,
2053 const wxString
& strDesc
)
2057 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2058 entry
->Add(wxT("open=") + strOpenCmd
);
2059 entry
->Add(wxT("print=") + strPrintCmd
);
2060 entry
->Add(wxT("test=") + strTest
);
2063 wxArrayString strExtensions
;
2065 AddToMimeData (strType
, strIcon
, entry
, strExtensions
, strDesc
, TRUE
);
2069 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2071 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2072 strFileName
.c_str());
2074 wxTextFile
file(strFileName
);
2075 #if defined(__WXGTK20__) && wxUSE_UNICODE
2076 if ( !file
.Open( wxConvUTF8
) )
2082 // the information we extract
2083 wxString strMimeType
, strDesc
, strExtensions
;
2085 size_t nLineCount
= file
.GetLineCount();
2086 const wxChar
*pc
= NULL
;
2087 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2090 // now we're at the start of the line
2091 pc
= file
[nLine
].c_str();
2094 // we didn't finish with the previous line yet
2099 while ( wxIsspace(*pc
) )
2102 // comment or blank line?
2103 if ( *pc
== wxT('#') || !*pc
) {
2104 // skip the whole line
2109 // detect file format
2110 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2111 if ( pEqualSign
== NULL
) {
2115 // first field is mime type
2116 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
2121 while ( wxIsspace(*pc
) )
2124 // take all the rest of the string
2127 // no description...
2134 // the string on the left of '=' is the field name
2135 wxString
strLHS(pc
, pEqualSign
- pc
);
2138 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2142 if ( *pc
== wxT('"') ) {
2143 // the string is quoted and ends at the matching quote
2144 pEnd
= wxStrchr(++pc
, wxT('"'));
2145 if ( pEnd
== NULL
) {
2146 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2148 strFileName
.c_str(), nLine
+ 1);
2152 // unquoted string ends at the first space or at the end of
2154 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2158 // now we have the RHS (field value)
2159 wxString
strRHS(pc
, pEnd
- pc
);
2161 // check what follows this entry
2162 if ( *pEnd
== wxT('"') ) {
2167 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2170 // if there is something left, it may be either a '\\' to continue
2171 // the line or the next field of the same entry
2172 bool entryEnded
= *pc
== wxT('\0'),
2173 nextFieldOnSameLine
= FALSE
;
2174 if ( !entryEnded
) {
2175 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2178 // now see what we got
2179 if ( strLHS
== wxT("type") ) {
2180 strMimeType
= strRHS
;
2182 else if ( strLHS
.StartsWith(wxT("desc")) ) {
2185 else if ( strLHS
== wxT("exts") ) {
2186 strExtensions
= strRHS
;
2188 else if ( strLHS
!= _T("icon") )
2190 // this one is simply ignored: it usually refers to Netscape
2191 // built in icons which are useless for us anyhow
2193 else if ( !strLHS
.StartsWith(_T("x-")) )
2195 // we suppose that all fields starting with "X-" are
2196 // unregistered extensions according to the standard practice,
2197 // but it may be worth telling the user about other junk in
2198 // his mime.types file
2199 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2200 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
2203 if ( !entryEnded
) {
2204 if ( !nextFieldOnSameLine
)
2206 //else: don't reset it
2208 // as we don't reset strMimeType, the next field in this entry
2209 // will be interpreted correctly.
2215 // depending on the format (Mosaic or Netscape) either space or comma
2216 // is used to separate the extensions
2217 strExtensions
.Replace(wxT(","), wxT(" "));
2219 // also deal with the leading dot
2220 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2222 strExtensions
.erase(0, 1);
2225 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2226 strExtensions
.c_str(),
2227 strMimeType
.c_str(),
2230 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2232 // finished with this line
2239 // ----------------------------------------------------------------------------
2240 // UNIX mailcap files parsing
2241 // ----------------------------------------------------------------------------
2243 // the data for a single MIME type
2244 struct MailcapLineData
2253 wxArrayString verbs
,
2261 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= FALSE
; }
2264 // process a non-standard (i.e. not the first or second one) mailcap field
2266 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2267 const wxString
& curField
)
2269 if ( curField
.empty() )
2275 // is this something of the form foo=bar?
2276 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2279 // split "LHS = RHS" in 2
2280 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2281 rhs
= curField
.AfterFirst(wxT('='));
2283 lhs
.Trim(TRUE
); // from right
2284 rhs
.Trim(FALSE
); // from left
2286 // it might be quoted
2287 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2289 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2292 // is it a command verb or something else?
2293 if ( lhs
== wxT("test") )
2295 if ( wxSystem(rhs
) == 0 )
2298 wxLogTrace(TRACE_MIME_TEST
,
2299 wxT("Test '%s' for mime type '%s' succeeded."),
2300 rhs
.c_str(), data
.type
.c_str());
2305 wxLogTrace(TRACE_MIME_TEST
,
2306 wxT("Test '%s' for mime type '%s' failed, skipping."),
2307 rhs
.c_str(), data
.type
.c_str());
2309 data
.testfailed
= TRUE
;
2312 else if ( lhs
== wxT("desc") )
2316 else if ( lhs
== wxT("x11-bitmap") )
2320 else if ( lhs
== wxT("notes") )
2324 else // not a (recognized) special case, must be a verb (e.g. "print")
2326 data
.verbs
.Add(lhs
);
2327 data
.commands
.Add(rhs
);
2330 else // '=' not found
2332 // so it must be a simple flag
2333 if ( curField
== wxT("needsterminal") )
2335 data
.needsterminal
= TRUE
;
2337 else if ( curField
== wxT("copiousoutput"))
2339 // copiousoutput impies that the viewer is a console program
2340 data
.needsterminal
=
2341 data
.copiousoutput
= TRUE
;
2343 else if ( !IsKnownUnimportantField(curField
) )
2352 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2355 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2356 strFileName
.c_str());
2358 wxTextFile
file(strFileName
);
2359 #if defined(__WXGTK20__) && wxUSE_UNICODE
2360 if ( !file
.Open( wxConvUTF8
) )
2366 // indices of MIME types (in m_aTypes) we already found in this file
2368 // (see the comments near the end of function for the reason we need this)
2369 wxArrayInt aIndicesSeenHere
;
2371 // accumulator for the current field
2373 curField
.reserve(1024);
2375 size_t nLineCount
= file
.GetLineCount();
2376 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2378 // now we're at the start of the line
2379 const wxChar
*pc
= file
[nLine
].c_str();
2382 while ( wxIsspace(*pc
) )
2385 // comment or empty string?
2386 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2392 // what field are we currently in? The first 2 are fixed and there may
2393 // be an arbitrary number of other fields parsed by
2394 // ProcessOtherMailcapField()
2396 // the first field is the MIME type
2402 } currentToken
= Field_Type
;
2404 // the flags and field values on the current line
2405 MailcapLineData data
;
2413 // interpret the next character literally (notice that
2414 // backslash can be used for line continuation)
2415 if ( *++pc
== wxT('\0') )
2417 // fetch the next line if there is one
2418 if ( nLine
== nLineCount
- 1 )
2420 // something is wrong, bail out
2423 wxLogDebug(wxT("Mailcap file %s, line %lu: "
2424 "'\\' on the end of the last line "
2426 strFileName
.c_str(),
2427 (unsigned long)nLine
+ 1);
2431 // pass to the beginning of the next line
2432 pc
= file
[++nLine
].c_str();
2434 // skip pc++ at the end of the loop
2440 // just a normal character
2446 cont
= FALSE
; // end of line reached, exit the loop
2448 // fall through to still process this field
2451 // trim whitespaces from both sides
2452 curField
.Trim(TRUE
).Trim(FALSE
);
2454 switch ( currentToken
)
2457 data
.type
= curField
.Lower();
2458 if ( data
.type
.empty() )
2460 // I don't think that this is a valid mailcap
2461 // entry, but try to interpret it somehow
2462 data
.type
= _T('*');
2465 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2467 // we interpret "type" as "type/*"
2468 data
.type
+= wxT("/*");
2471 currentToken
= Field_OpenCmd
;
2475 data
.cmdOpen
= curField
;
2477 currentToken
= Field_Other
;
2481 if ( !ProcessOtherMailcapField(data
, curField
) )
2483 // don't flood the user with error messages if
2484 // we don't understand something in his
2485 // mailcap, but give them in debug mode because
2486 // this might be useful for the programmer
2489 wxT("Mailcap file %s, line %lu: "
2490 "unknown field '%s' for the "
2491 "MIME type '%s' ignored."),
2492 strFileName
.c_str(),
2493 (unsigned long)nLine
+ 1,
2498 else if ( data
.testfailed
)
2500 // skip this entry entirely
2504 // it already has this value
2505 //currentToken = Field_Other;
2509 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2512 // next token starts immediately after ';'
2520 // continue in the same line
2524 // we read the entire entry, check what have we got
2525 // ------------------------------------------------
2527 // check that we really read something reasonable
2528 if ( currentToken
< Field_Other
)
2530 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2532 strFileName
.c_str(), nLine
+ 1);
2537 // if the test command failed, it's as if the entry were not there at
2539 if ( data
.testfailed
)
2544 // support for flags:
2545 // 1. create an xterm for 'needsterminal'
2546 // 2. append "| $PAGER" for 'copiousoutput'
2548 // Note that the RFC says that having both needsterminal and
2549 // copiousoutput is probably a mistake, so it seems that running
2550 // programs with copiousoutput inside an xterm as it is done now
2551 // is a bad idea (FIXME)
2552 if ( data
.copiousoutput
)
2554 const wxChar
*p
= wxGetenv(_T("PAGER"));
2555 data
.cmdOpen
<< _T(" | ") << (p
? p
: _T("more"));
2558 if ( data
.needsterminal
)
2560 data
.cmdOpen
= wxString::Format(_T("xterm -e sh -c '%s'"),
2561 data
.cmdOpen
.c_str());
2564 if ( !data
.cmdOpen
.empty() )
2566 data
.verbs
.Insert(_T("open"), 0);
2567 data
.commands
.Insert(data
.cmdOpen
, 0);
2570 // we have to decide whether the new entry should replace any entries
2571 // for the same MIME type we had previously found or not
2574 // the fall back entries have the lowest priority, by definition
2581 // have we seen this one before?
2582 int nIndex
= m_aTypes
.Index(data
.type
);
2584 // and if we have, was it in this file?
2585 overwrite
= nIndex
== wxNOT_FOUND
||
2586 aIndicesSeenHere
.Index(nIndex
) != wxNOT_FOUND
;
2589 wxLogTrace(TRACE_MIME
, _T("mailcap %s: %s [%s]"),
2590 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2591 overwrite
? _T("replace") : _T("add"));
2593 int n
= AddToMimeData
2597 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2598 wxArrayString() /* extensions */,
2605 aIndicesSeenHere
.Add(n
);
2612 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2619 size_t count
= m_aTypes
.GetCount();
2620 for ( size_t n
= 0; n
< count
; n
++ )
2622 // don't return template types from here (i.e. anything containg '*')
2624 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
2626 mimetypes
.Add(type
);
2630 return mimetypes
.GetCount();
2633 // ----------------------------------------------------------------------------
2634 // writing to MIME type files
2635 // ----------------------------------------------------------------------------
2637 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2639 wxArrayString sMimeTypes
;
2640 ft
->GetMimeTypes (sMimeTypes
);
2644 for (i
= 0; i
< sMimeTypes
.GetCount(); i
++)
2646 sMime
= sMimeTypes
.Item(i
);
2647 int nIndex
= m_aTypes
.Index (sMime
);
2648 if ( nIndex
== wxNOT_FOUND
)
2650 // error if we get here ??
2655 WriteMimeInfo(nIndex
, TRUE
);
2656 m_aTypes
.RemoveAt(nIndex
);
2657 m_aEntries
.RemoveAt(nIndex
);
2658 m_aExtensions
.RemoveAt(nIndex
);
2659 m_aDescriptions
.RemoveAt(nIndex
);
2660 m_aIcons
.RemoveAt(nIndex
);
2663 // check data integrity
2664 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2665 m_aTypes
.Count() == m_aExtensions
.Count() &&
2666 m_aTypes
.Count() == m_aIcons
.Count() &&
2667 m_aTypes
.Count() == m_aDescriptions
.Count() );
2672 // ----------------------------------------------------------------------------
2673 // private functions
2674 // ----------------------------------------------------------------------------
2676 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2678 static const wxChar
*knownFields
[] =
2680 _T("x-mozilla-flags"),
2682 _T("textualnewlines"),
2685 wxString field
= fieldAll
.BeforeFirst(_T('='));
2686 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2688 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2696 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE