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"
78 #include "wx/unix/mimetype.h"
80 // other standard headers
84 /* silence warnings for comparing unsigned int's <0 */
85 # pragma message disable unscomzer
88 // wxMimeTypeCommands stores the verbs defined for the given MIME type with
90 class wxMimeTypeCommands
93 wxMimeTypeCommands() { }
95 wxMimeTypeCommands(const wxArrayString
& verbs
,
96 const wxArrayString
& commands
)
102 // add a new verb with the command or replace the old value
103 void AddOrReplaceVerb(const wxString
& verb
, const wxString
& cmd
)
105 int n
= m_verbs
.Index(verb
, FALSE
/* ignore case */);
106 if ( n
== wxNOT_FOUND
)
117 void Add(const wxString
& s
)
119 m_verbs
.Add(s
.BeforeFirst(_T('=')));
120 m_commands
.Add(s
.AfterFirst(_T('=')));
123 // access the commands
124 size_t GetCount() const { return m_verbs
.GetCount(); }
125 const wxString
& GetVerb(size_t n
) const { return m_verbs
[n
]; }
126 const wxString
& GetCmd(size_t n
) const { return m_commands
[n
]; }
128 bool HasVerb(const wxString
& verb
) const
129 { return m_verbs
.Index(verb
) != wxNOT_FOUND
; }
131 wxString
GetCommandForVerb(const wxString
& verb
, size_t *idx
= NULL
) const
135 int n
= m_verbs
.Index(verb
);
136 if ( n
!= wxNOT_FOUND
)
138 s
= m_commands
[(size_t)n
];
146 // get a "verb=command" string
147 wxString
GetVerbCmd(size_t n
) const
149 return m_verbs
[n
] + _T('=') + m_commands
[n
];
153 wxArrayString m_verbs
,
157 // this class extends wxTextFile
160 class wxMimeTextFile
: public wxTextFile
164 wxMimeTextFile () : wxTextFile () {};
165 wxMimeTextFile (const wxString
& strFile
) : wxTextFile (strFile
) { };
167 int pIndexOf(const wxString
& sSearch
, bool bIncludeComments
= FALSE
, int iStart
= 0)
170 int nResult
= wxNOT_FOUND
;
171 if (i
>=GetLineCount()) return wxNOT_FOUND
;
173 wxString sTest
= sSearch
;
177 if (bIncludeComments
)
179 while ( (i
< GetLineCount()) )
183 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
189 while ( (i
< GetLineCount()) )
193 if ( ! sLine
.StartsWith(wxT("#")))
195 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
203 bool CommentLine(int nIndex
)
205 if (nIndex
<0) return FALSE
;
206 if (nIndex
>= (int)GetLineCount() ) return FALSE
;
207 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
211 bool CommentLine(const wxString
& sTest
)
213 int nIndex
= pIndexOf(sTest
);
214 if (nIndex
<0) return FALSE
;
215 if (nIndex
>= (int)GetLineCount() ) return FALSE
;
216 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
220 wxString
GetVerb (size_t i
)
222 if (i
> GetLineCount() ) return wxEmptyString
;
223 wxString sTmp
= GetLine(i
).BeforeFirst(wxT('='));
227 wxString
GetCmd (size_t i
)
229 if (i
> GetLineCount() ) return wxEmptyString
;
230 wxString sTmp
= GetLine(i
).AfterFirst(wxT('='));
235 // in case we're compiling in non-GUI mode
236 class WXDLLEXPORT wxIcon
;
238 // ----------------------------------------------------------------------------
240 // ----------------------------------------------------------------------------
242 // MIME code tracing mask
243 #define TRACE_MIME _T("mime")
245 // give trace messages about the results of mailcap tests
246 #define TRACE_MIME_TEST _T("mimetest")
248 // ----------------------------------------------------------------------------
250 // ----------------------------------------------------------------------------
252 // there are some fields which we don't understand but for which we don't give
253 // warnings as we know that they're not important - this function is used to
255 static bool IsKnownUnimportantField(const wxString
& field
);
257 // ----------------------------------------------------------------------------
259 // ----------------------------------------------------------------------------
262 // This class uses both mailcap and mime.types to gather information about file
265 // The information about mailcap file was extracted from metamail(1) sources
266 // and documentation and subsequently revised when I found the RFC 1524
269 // Format of mailcap file: spaces are ignored, each line is either a comment
270 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
271 // A backslash can be used to quote semicolons and newlines (and, in fact,
272 // anything else including itself).
274 // The first field is always the MIME type in the form of type/subtype (see RFC
275 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
276 // "type" which means the same as "type/*", although I'm not sure whether this
279 // The second field is always the command to run. It is subject to
280 // parameter/filename expansion described below.
282 // All the following fields are optional and may not be present at all. If
283 // they're present they may appear in any order, although each of them should
284 // appear only once. The optional fields are the following:
285 // * notes=xxx is an uninterpreted string which is silently ignored
286 // * test=xxx is the command to be used to determine whether this mailcap line
287 // applies to our data or not. The RHS of this field goes through the
288 // parameter/filename expansion (as the 2nd field) and the resulting string
289 // is executed. The line applies only if the command succeeds, i.e. returns 0
291 // * print=xxx is the command to be used to print (and not view) the data of
292 // this type (parameter/filename expansion is done here too)
293 // * edit=xxx is the command to open/edit the data of this type
294 // * needsterminal means that a new interactive console must be created for
296 // * copiousoutput means that the viewer doesn't interact with the user but
297 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
298 // good example), thus it might be a good idea to use some kind of paging
300 // * textualnewlines means not to perform CR/LF translation (not honored)
301 // * compose and composetyped fields are used to determine the program to be
302 // called to create a new message pert in the specified format (unused).
304 // Parameter/filename expansion:
305 // * %s is replaced with the (full) file name
306 // * %t is replaced with MIME type/subtype of the entry
307 // * for multipart type only %n is replaced with the nnumber of parts and %F is
308 // replaced by an array of (content-type, temporary file name) pairs for all
309 // message parts (TODO)
310 // * %{parameter} is replaced with the value of parameter taken from
311 // Content-type header line of the message.
314 // There are 2 possible formats for mime.types file, one entry per line (used
315 // for global mime.types and called Mosaic format) and "expanded" format where
316 // an entry takes multiple lines (used for users mime.types and called
319 // For both formats spaces are ignored and lines starting with a '#' are
320 // comments. Each record has one of two following forms:
321 // a) for "brief" format:
322 // <mime type> <space separated list of extensions>
323 // b) for "expanded" format:
324 // type=<mime type> BACKSLASH
325 // desc="<description>" BACKSLASH
326 // exts="<comma separated list of extensions>"
328 // (where BACKSLASH is a literal '\\' which we can't put here because cpp
331 // We try to autodetect the format of mime.types: if a non-comment line starts
332 // with "type=" we assume the second format, otherwise the first one.
334 // there may be more than one entry for one and the same mime type, to
335 // choose the right one we have to run the command specified in the test
336 // field on our data.
338 // ----------------------------------------------------------------------------
340 // ----------------------------------------------------------------------------
342 // GNOME stores the info we're interested in in several locations:
343 // 1. xxx.keys files under /usr/share/mime-info
344 // 2. xxx.keys files under ~/.gnome/mime-info
346 // The format of xxx.keys file is the following:
351 // with blank lines separating the entries and indented lines starting with
352 // TABs. We're interested in the field icon-filename whose value is the path
353 // containing the icon.
355 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
356 // just before the field name.
359 bool wxMimeTypesManagerImpl::CheckGnomeDirsExist ()
362 wxGetHomeDir( &gnomedir
);
363 wxString sTmp
= gnomedir
;
364 sTmp
= sTmp
+ wxT("/.gnome");
365 if (! wxDir::Exists ( sTmp
) )
367 if (!wxMkdir ( sTmp
))
369 wxLogError(_("Failed to create directory %s/.gnome."), sTmp
.c_str());
373 sTmp
= sTmp
+ wxT("/mime-info");
374 if (! wxDir::Exists ( sTmp
) )
376 if (!wxMkdir ( sTmp
))
378 wxLogError(_("Failed to create directory %s/mime-info."), sTmp
.c_str());
388 bool wxMimeTypesManagerImpl::WriteGnomeKeyFile(int index
, bool delete_index
)
391 wxGetHomeDir( &gnomedir
);
393 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.keys"));
394 // if this fails probably Gnome is not installed ??
395 // create it anyway as a private mime store
397 #if defined(__WXGTK20__) && wxUSE_UNICODE
398 if (! outfile
.Open ( wxConvUTF8
) )
400 if (! outfile
.Open () )
403 if (delete_index
) return FALSE
;
404 if (!CheckGnomeDirsExist() ) return FALSE
;
408 wxString sTmp
, strType
= m_aTypes
[index
];
409 int nIndex
= outfile
.pIndexOf(strType
);
410 if ( nIndex
== wxNOT_FOUND
)
412 outfile
.AddLine ( strType
+ wxT(':') );
413 // see file:/usr/doc/gnome-libs-devel-1.0.40/devel-docs/mime-type-handling.txt
414 // as this does not deal with internationalisation
415 // wxT( "\t[en_US]") + verb + wxT ('=') + cmd + wxT(" %f");
416 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
417 size_t count
= entries
->GetCount();
418 for ( size_t i
= 0; i
< count
; i
++ )
420 sTmp
= entries
->GetVerbCmd(i
);
421 sTmp
.Replace( wxT("%s"), wxT("%f") );
422 sTmp
= wxT ( "\t") + sTmp
;
423 outfile
.AddLine ( sTmp
);
425 //for international use do something like this
426 //outfile.AddLine ( wxString( "\t[en_US]icon-filename=") + cmd );
427 outfile
.AddLine ( wxT( "\ticon-filename=") + m_aIcons
[index
] );
432 outfile
.CommentLine(nIndex
);
434 wxMimeTypeCommands sOld
;
435 size_t nOld
= nIndex
+ 1;
436 bool oldEntryEnd
= FALSE
;
437 while ( (nOld
< outfile
.GetLineCount() )&& (oldEntryEnd
== FALSE
))
439 sTmp
= outfile
.GetLine(nOld
);
440 if ( (sTmp
[0u] == wxT('\t')) || (sTmp
[0u] == wxT('#')) )
442 // we have another line to deal with
443 outfile
.CommentLine(nOld
);
445 // add the line to our store
446 if ((!delete_index
) && (sTmp
[0u] == wxT('\t')))
449 // next mimetpye ??or blank line
453 // list of entries in our data; these should all be in sOld,
454 // though sOld may also contain other entries , eg flags
457 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
459 for (i
=0; i
< entries
->GetCount(); i
++)
461 // replace any entries in sold that match verbs we know
462 sOld
.AddOrReplaceVerb ( entries
->GetVerb(i
), entries
->GetCmd (i
) );
464 //sOld should also contain the icon
465 if ( !m_aIcons
[index
].empty() )
466 sOld
.AddOrReplaceVerb ( wxT("icon-filename"), m_aIcons
[index
] );
468 for (i
=0; i
< sOld
.GetCount(); i
++)
470 sTmp
= sOld
.GetVerbCmd(i
);
471 sTmp
.Replace( wxT("%s"), wxT("%f") );
472 sTmp
= wxT("\t") + sTmp
;
474 outfile
.InsertLine ( sTmp
, nIndex
);
478 bool bTmp
= outfile
.Write ();
483 bool wxMimeTypesManagerImpl::WriteGnomeMimeFile(int index
, bool delete_index
)
486 wxGetHomeDir( &gnomedir
);
488 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.mime"));
489 // if this fails probably Gnome is not installed ??
490 // create it anyway as a private mime store
491 if (! outfile
.Open () )
493 if (delete_index
) return FALSE
;
494 if (!CheckGnomeDirsExist() ) return FALSE
;
497 wxString strType
= m_aTypes
[index
];
498 int nIndex
= outfile
.pIndexOf(strType
);
499 if ( nIndex
== wxNOT_FOUND
)
501 outfile
.AddLine ( strType
);
502 outfile
.AddLine ( wxT("\text:") + m_aExtensions
.Item(index
) );
508 outfile
.CommentLine(nIndex
);
509 outfile
.CommentLine(nIndex
+1);
512 {// check for next line being the right one to replace ??
513 wxString sOld
= outfile
.GetLine(nIndex
+1);
514 if (sOld
.Contains( wxT("\text: ")))
516 outfile
.GetLine(nIndex
+1) = wxT("\text: ") + m_aExtensions
.Item(index
);
520 outfile
.InsertLine( wxT("\text: ") + m_aExtensions
.Item(index
), nIndex
+ 1 );
524 bool bTmp
= outfile
.Write ();
529 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString
& filename
,
530 const wxArrayString
& dirs
)
532 wxTextFile
textfile(filename
);
533 #if defined(__WXGTK20__) && wxUSE_UNICODE
534 if ( !textfile
.Open( wxConvUTF8
) )
536 if ( !textfile
.Open() )
539 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
542 // values for the entry being parsed
543 wxString curMimeType
, curIconFile
;
544 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
546 // these are always empty in this file
547 wxArrayString strExtensions
;
551 size_t nLineCount
= textfile
.GetLineCount();
553 while ( nLine
< nLineCount
)
555 pc
= textfile
[nLine
].c_str();
556 if ( *pc
!= _T('#') )
559 wxLogTrace(TRACE_MIME
, wxT("--- Reading from Gnome file %s '%s' ---"),
560 filename
.c_str(),pc
);
563 if (sTmp
.Contains(wxT("=")) )
566 if (sTmp
.Contains( wxT("icon-filename=") ) )
568 curIconFile
= sTmp
.AfterFirst(wxT('='));
571 else if (sTmp
.Contains( wxT("icon_filename=") ) )
573 curIconFile
= sTmp
.AfterFirst(wxT('='));
574 if (!wxFileExists(curIconFile
))
576 size_t nDirs
= dirs
.GetCount();
577 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
580 newFile
.Printf(wxT("%s/pixmaps/document-icons/%s.png"),
582 curIconFile
.c_str());
583 if (wxFileExists(newFile
))
584 curIconFile
= newFile
;
588 else //: some other field,
590 //may contain lines like this (RH7)
591 // \t[lang]open.tex."TeX this file"=tex %f
592 // \tflags.tex.flags=needsterminal
593 // \topen.latex."LaTeX this file"=latex %f
594 // \tflags.latex.flags=needsterminal
598 // \topen.convert.Convert file to Postscript=dvips %f -o `basename %f .dvi`.ps
600 // for now ignore lines with flags in...FIX
601 sTmp
= sTmp
.AfterLast(wxT(']'));
602 sTmp
= sTmp
.AfterLast(wxT('\t'));
603 sTmp
.Trim(FALSE
).Trim();
604 if (0 == sTmp
.Replace ( wxT("%f"), wxT("%s") )) sTmp
= sTmp
+ wxT(" %s");
609 } // emd of has an equals sign
612 // not a comment and not an equals sign
613 if (sTmp
.Contains(wxT('/')))
615 // this is the start of the new mimetype
616 // overwrite any existing data
617 if (! curMimeType
.empty())
619 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
621 // now get ready for next bit
622 entry
= new wxMimeTypeCommands
;
624 curMimeType
= sTmp
.BeforeFirst(wxT(':'));
627 } // end of not a comment
628 // ignore blank lines
630 } // end of while, save any data
631 if (! curMimeType
.empty())
633 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
640 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString
& filename
)
642 wxTextFile
textfile(filename
);
643 if ( !textfile
.Open() )
646 wxLogTrace(TRACE_MIME
,
647 wxT("--- Opened Gnome file %s ---"),
650 // values for the entry being parsed
651 wxString curMimeType
, curExtList
;
654 size_t nLineCount
= textfile
.GetLineCount();
655 for ( size_t nLine
= 0;; nLine
++ )
657 if ( nLine
< nLineCount
)
659 pc
= textfile
[nLine
].c_str();
660 if ( *pc
== wxT('#') )
668 // so that we will fall into the "if" below
675 if ( !!curMimeType
&& !!curExtList
)
677 wxLogTrace(TRACE_MIME
,
678 wxT("--- At end of Gnome file finding mimetype %s ---"),
679 curMimeType
.c_str());
681 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
686 // the end - this can only happen if nLine == nLineCount
695 // what do we have here?
696 if ( *pc
== wxT('\t') )
698 // this is a field=value ling
699 pc
++; // skip leading TAB
701 static const int lenField
= 5; // strlen("ext: ")
702 if ( wxStrncmp(pc
, wxT("ext: "), lenField
) == 0 )
704 // skip it and take everything left until the end of line
705 curExtList
= pc
+ lenField
;
707 //else: some other field, we don't care
711 // this is the start of the new section
712 wxLogTrace(TRACE_MIME
,
713 wxT("--- In Gnome file finding mimetype %s ---"),
714 curMimeType
.c_str());
716 if (! curMimeType
.empty())
717 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
721 while ( *pc
!= wxT(':') && *pc
!= wxT('\0') )
723 curMimeType
+= *pc
++;
730 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
731 const wxString
& dirbase
, const wxArrayString
& dirs
)
733 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
734 _T("base directory shouldn't end with a slash") );
736 wxString dirname
= dirbase
;
737 dirname
<< wxT("/mime-info");
739 if ( !wxDir::Exists(dirname
) )
743 if ( !dir
.IsOpened() )
746 // we will concatenate it with filename to get the full path below
750 bool cont
= dir
.GetFirst(&filename
, _T("*.mime"), wxDIR_FILES
);
753 LoadGnomeMimeTypesFromMimeFile(dirname
+ filename
);
755 cont
= dir
.GetNext(&filename
);
758 cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
761 LoadGnomeDataFromKeyFile(dirname
+ filename
, dirs
);
763 cont
= dir
.GetNext(&filename
);
770 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString
& sExtraDir
)
773 dirs
.Add(wxT("/usr/share"));
774 dirs
.Add(wxT("/usr/local/share"));
777 wxGetHomeDir( &gnomedir
);
778 gnomedir
+= wxT("/.gnome");
779 dirs
.Add( gnomedir
);
780 if (!sExtraDir
.empty()) dirs
.Add( sExtraDir
);
782 size_t nDirs
= dirs
.GetCount();
783 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
785 LoadGnomeMimeFilesFromDir(dirs
[nDir
], dirs
);
789 // ----------------------------------------------------------------------------
791 // ----------------------------------------------------------------------------
794 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
795 // may be found in either of the following locations
797 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
798 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
800 // The format of a .kdelnk file is almost the same as the one used by
801 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
802 // value for the entry "Type"
804 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
805 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
807 bool wxMimeTypesManagerImpl::CheckKDEDirsExist ( const wxString
& sOK
, const wxString
& sTest
)
812 if (wxDir::Exists(sOK
)) return TRUE
;
817 wxString sStart
= sOK
+ wxT("/") + sTest
.BeforeFirst(wxT('/'));
818 if (!wxDir::Exists(sStart
)) wxMkdir(sStart
);
819 wxString sEnd
= sTest
.AfterFirst(wxT('/'));
820 return CheckKDEDirsExist(sStart
, sEnd
);
824 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index
, bool delete_index
)
826 wxMimeTextFile appoutfile
, mimeoutfile
;
827 wxString sHome
= wxGetHomeDir();
828 wxString sTmp
= wxT(".kde/share/mimelnk/");
829 wxString sMime
= m_aTypes
[index
];
830 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.BeforeFirst(wxT('/')) );
831 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
+ wxT(".kdelnk");
834 bool bMimeExists
= mimeoutfile
.Open (sTmp
);
837 bTemp
= mimeoutfile
.Create (sTmp
);
838 // some unknown error eg out of disk space
839 if (!bTemp
) return FALSE
;
842 sTmp
= wxT(".kde/share/applnk/");
843 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.AfterFirst(wxT('/')) );
844 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
.AfterFirst(wxT('/')) + wxT(".kdelnk");
847 bAppExists
= appoutfile
.Open (sTmp
);
850 bTemp
= appoutfile
.Create (sTmp
);
851 // some unknown error eg out of disk space
852 if (!bTemp
) return FALSE
;
855 // fixed data; write if new file
858 mimeoutfile
.AddLine(wxT("#KDE Config File"));
859 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
860 mimeoutfile
.AddLine(wxT("Version=1.0"));
861 mimeoutfile
.AddLine(wxT("Type=MimeType"));
862 mimeoutfile
.AddLine(wxT("MimeType=") + sMime
);
867 mimeoutfile
.AddLine(wxT("#KDE Config File"));
868 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
869 appoutfile
.AddLine(wxT("Version=1.0"));
870 appoutfile
.AddLine(wxT("Type=Application"));
871 appoutfile
.AddLine(wxT("MimeType=") + sMime
+ wxT(';'));
876 mimeoutfile
.CommentLine(wxT("Comment="));
878 mimeoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
879 appoutfile
.CommentLine(wxT("Name="));
881 appoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
883 sTmp
= m_aIcons
[index
];
884 // we can either give the full path, or the shortfilename if its in
885 // one of the directories we search
886 mimeoutfile
.CommentLine(wxT("Icon=") );
887 if (!delete_index
) mimeoutfile
.AddLine(wxT("Icon=") + sTmp
);
888 appoutfile
.CommentLine(wxT("Icon=") );
889 if (!delete_index
) appoutfile
.AddLine(wxT("Icon=") + sTmp
);
891 sTmp
= wxT(" ") + m_aExtensions
[index
];
893 wxStringTokenizer
tokenizer(sTmp
, _T(" "));
894 sTmp
= wxT("Patterns=");
895 mimeoutfile
.CommentLine(sTmp
);
896 while ( tokenizer
.HasMoreTokens() )
898 // holds an extension; need to change it to *.ext;
899 wxString e
= wxT("*.") + tokenizer
.GetNextToken() + wxT(";");
902 if (!delete_index
) mimeoutfile
.AddLine(sTmp
);
904 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
905 // if we don't find open just have an empty string ... FIX this
906 sTmp
= entries
->GetCommandForVerb(_T("open"));
907 sTmp
.Replace( wxT("%s"), wxT("%f") );
909 mimeoutfile
.CommentLine(wxT("DefaultApp=") );
910 if (!delete_index
) mimeoutfile
.AddLine(wxT("DefaultApp=") + sTmp
);
912 sTmp
.Replace( wxT("%f"), wxT("") );
913 appoutfile
.CommentLine(wxT("Exec="));
914 if (!delete_index
) appoutfile
.AddLine(wxT("Exec=") + sTmp
);
916 if (entries
->GetCount() > 1)
918 //other actions as well as open
922 if (mimeoutfile
.Write ()) bTemp
= TRUE
;
923 mimeoutfile
.Close ();
924 if (appoutfile
.Write ()) bTemp
= TRUE
;
932 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString
& dirbase
,
933 const wxString
& subdir
,
934 const wxString
& filename
,
935 const wxArrayString
& icondirs
)
938 if ( !file
.Open(dirbase
+ filename
) ) return;
940 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
941 (dirbase
+filename
).c_str());
943 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
945 wxString mimetype
, mime_desc
, strIcon
;
947 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
948 if (nIndex
== wxNOT_FOUND
)
950 // construct mimetype from the directory name and the basename of the
951 // file (it always has .kdelnk extension)
952 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
954 else mimetype
= file
.GetCmd (nIndex
);
956 // first find the description string: it is the value in either "Comment="
957 // line or "Comment[<locale_name>]=" one
958 nIndex
= wxNOT_FOUND
;
962 wxLocale
*locale
= wxGetLocale();
965 // try "Comment[locale name]" first
966 comment
<< _T("Comment[") + locale
->GetName() + _T("]=");
967 nIndex
= file
.pIndexOf(comment
);
971 if ( nIndex
== wxNOT_FOUND
)
973 comment
= _T("Comment=");
974 nIndex
= file
.pIndexOf(comment
);
977 if ( nIndex
!= wxNOT_FOUND
) mime_desc
= file
.GetCmd(nIndex
);
978 //else: no description
980 // next find the extensions
981 wxString mime_extension
;
983 nIndex
= file
.pIndexOf(_T("Patterns="));
984 if ( nIndex
!= wxNOT_FOUND
)
986 wxString exts
= file
.GetCmd (nIndex
);;
988 wxStringTokenizer
tokenizer(exts
, _T(";"));
989 while ( tokenizer
.HasMoreTokens() )
991 wxString e
= tokenizer
.GetNextToken();
992 if ( e
.Left(2) != _T("*.") )
993 continue; // don't support too difficult patterns
995 if ( !mime_extension
.empty() )
997 // separate from the previous ext
998 mime_extension
<< _T(' ');
1001 mime_extension
<< e
.Mid(2);
1004 sExts
.Add(mime_extension
);
1007 // ok, now we can take care of icon:
1009 nIndex
= file
.pIndexOf(_T("Icon="));
1010 if ( nIndex
!= wxNOT_FOUND
)
1012 strIcon
= file
.GetCmd(nIndex
);
1013 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
1014 //it could be the real path, but more often a short name
1015 if (!wxFileExists(strIcon
))
1017 // icon is just the short name
1018 if ( !strIcon
.empty() )
1020 // we must check if the file exists because it may be stored
1021 // in many locations, at least ~/.kde and $KDEDIR
1022 size_t nDir
, nDirs
= icondirs
.GetCount();
1023 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
1024 if (wxFileExists(icondirs
[nDir
] + strIcon
))
1026 strIcon
.Prepend(icondirs
[nDir
]);
1027 wxLogTrace(TRACE_MIME
, wxT(" iconfile %s"), strIcon
.c_str());
1033 // now look for lines which know about the application
1034 // exec= or DefaultApp=
1036 nIndex
= file
.pIndexOf(wxT("DefaultApp"));
1038 if ( nIndex
== wxNOT_FOUND
)
1040 // no entry try exec
1041 nIndex
= file
.pIndexOf(wxT("Exec"));
1044 if ( nIndex
!= wxNOT_FOUND
)
1046 wxString sTmp
= file
.GetCmd(nIndex
);
1047 // we expect %f; others including %F and %U and %u are possible
1048 if (0 == sTmp
.Replace ( wxT("%f"), wxT("%s") ))
1049 sTmp
= sTmp
+ wxT(" %s");
1050 entry
->AddOrReplaceVerb (wxString(wxT("open")), sTmp
);
1053 AddToMimeData (mimetype
, strIcon
, entry
, sExts
, mime_desc
);
1056 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString
& dirbase
,
1057 const wxString
& subdir
,
1058 const wxArrayString
& icondirs
)
1060 wxString dirname
= dirbase
;
1063 if ( !dir
.IsOpened() )
1066 wxLogTrace(TRACE_MIME
, wxT("--- Loading from KDE directory %s ---"),
1072 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
1075 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1077 cont
= dir
.GetNext(&filename
);
1079 // new standard for Gnome and KDE
1080 cont
= dir
.GetFirst(&filename
, _T("*.desktop"), wxDIR_FILES
);
1083 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1085 cont
= dir
.GetNext(&filename
);
1089 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString
& dirbase
,
1090 const wxArrayString
& icondirs
)
1092 wxASSERT_MSG( !!dirbase
&& !wxEndsWithPathSeparator(dirbase
),
1093 _T("base directory shouldn't end with a slash") );
1095 wxString dirname
= dirbase
;
1096 dirname
<< _T("/mimelnk");
1098 if ( !wxDir::Exists(dirname
) )
1102 if ( !dir
.IsOpened() )
1105 // we will concatenate it with dir name to get the full path below
1109 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
1112 LoadKDELinksForMimeType(dirname
, subdir
, icondirs
);
1114 cont
= dir
.GetNext(&subdir
);
1118 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString
& sExtraDir
)
1121 wxArrayString icondirs
;
1123 // settings in ~/.kde have maximal priority
1124 dirs
.Add(wxGetHomeDir() + wxT("/.kde/share"));
1125 icondirs
.Add(wxGetHomeDir() + wxT("/.kde/share/icons/"));
1127 // the variable KDEDIR is set when KDE is running
1128 const wxChar
*kdedir
= wxGetenv( wxT("KDEDIR") );
1131 dirs
.Add( wxString(kdedir
) + wxT("/share") );
1132 icondirs
.Add( wxString(kdedir
) + wxT("/share/icons/") );
1136 // try to guess KDEDIR
1137 dirs
.Add(_T("/usr/share"));
1138 dirs
.Add(_T("/opt/kde/share"));
1139 icondirs
.Add(_T("/usr/share/icons/"));
1140 icondirs
.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
1141 icondirs
.Add(_T("/opt/kde/share/icons/"));
1144 if (!sExtraDir
.empty()) dirs
.Add (sExtraDir
);
1145 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1147 size_t nDirs
= dirs
.GetCount();
1148 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1150 LoadKDELinkFilesFromDir(dirs
[nDir
], icondirs
);
1154 // ----------------------------------------------------------------------------
1155 // wxFileTypeImpl (Unix)
1156 // ----------------------------------------------------------------------------
1158 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1162 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1164 sTmp
= m_manager
->GetCommand ( verb
, m_index
[i
] );
1168 return wxFileType::ExpandCommand(sTmp
, params
);
1171 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
1176 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1178 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1181 if ( sTmp
.empty () )
1186 iconLoc
->SetFileName(sTmp
);
1194 wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1197 for (size_t i
= 0; i
< m_index
.GetCount(); i
++)
1198 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1203 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1204 wxArrayString
*commands
,
1205 const wxFileType::MessageParameters
& params
) const
1208 wxString vrb
, cmd
, sTmp
;
1210 wxMimeTypeCommands
* sPairs
;
1212 // verbs and commands have been cleared already in mimecmn.cpp...
1213 // if we find no entries in the exact match, try the inexact match
1214 for (size_t n
= 0; ((count
==0) && (n
< m_index
.GetCount())); n
++)
1216 // list of verb = command pairs for this mimetype
1217 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1219 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
1221 vrb
= sPairs
->GetVerb(i
);
1222 // some gnome entries have . inside
1223 vrb
= vrb
.AfterLast(wxT('.'));
1224 cmd
= sPairs
->GetCmd (i
);
1227 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1229 if ( vrb
.IsSameAs (wxT("open")))
1231 verbs
->Insert(vrb
,0u);
1232 commands
->Insert(cmd
,0u);
1237 commands
->Add (cmd
);
1248 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1250 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1253 // one extension in the space or comma delimitid list
1255 for ( const wxChar
*p
= strExtensions
;; p
++ ) {
1256 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1257 if ( !strExt
.empty() ) {
1258 extensions
.Add(strExt
);
1261 //else: repeated spaces (shouldn't happen, but it's not that
1262 // important if it does happen)
1264 if ( *p
== wxT('\0') )
1267 else if ( *p
== wxT('.') ) {
1268 // remove the dot from extension (but only if it's the first char)
1269 if ( !strExt
.empty() ) {
1272 //else: no, don't append it
1282 // set an arbitrary command,
1283 // could adjust the code to ask confirmation if it already exists and
1284 // overwriteprompt is TRUE, but this is currently ignored as *Associate* has
1285 // no overwrite prompt
1286 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
, const wxString
& verb
, bool overwriteprompt
/*= TRUE*/)
1288 wxArrayString strExtensions
;
1289 wxString strDesc
, strIcon
;
1291 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1292 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1294 wxArrayString strTypes
;
1295 GetMimeTypes (strTypes
);
1296 if (strTypes
.GetCount() < 1) return FALSE
;
1300 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1302 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1309 // ignore index on the grouds that we only have one icon in a Unix file
1310 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
/*= wxEmptyString*/, int /*index = 0*/)
1312 if (strIcon
.empty()) return FALSE
;
1313 wxArrayString strExtensions
;
1316 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1318 wxArrayString strTypes
;
1319 GetMimeTypes (strTypes
);
1320 if (strTypes
.GetCount() < 1) return FALSE
;
1324 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1326 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1333 // ----------------------------------------------------------------------------
1334 // wxMimeTypesManagerImpl (Unix)
1335 // ----------------------------------------------------------------------------
1338 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1340 m_initialized
= FALSE
;
1341 m_mailcapStylesInited
= 0;
1344 // read system and user mailcaps and other files
1345 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1346 const wxString
& sExtraDir
)
1348 // read mimecap amd mime.types
1349 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1350 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1351 GetMimeInfo(sExtraDir
);
1353 // read GNOME tables
1354 if ( mailcapStyles
& wxMAILCAP_GNOME
)
1355 GetGnomeMimeInfo(sExtraDir
);
1358 if ( mailcapStyles
& wxMAILCAP_KDE
)
1359 GetKDEMimeInfo(sExtraDir
);
1361 m_mailcapStylesInited
|= mailcapStyles
;
1364 // clear data so you can read another group of WM files
1365 void wxMimeTypesManagerImpl::ClearData()
1369 m_aExtensions
.Clear ();
1370 m_aDescriptions
.Clear ();
1372 WX_CLEAR_ARRAY(m_aEntries
);
1375 m_mailcapStylesInited
= 0;
1378 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1384 void wxMimeTypesManagerImpl::GetMimeInfo (const wxString
& sExtraDir
)
1386 // read this for netscape or Metamail formats
1388 // directories where we look for mailcap and mime.types by default
1389 // used by netscape and pine and other mailers, using 2 different formats!
1391 // (taken from metamail(1) sources)
1393 // although RFC 1524 specifies the search path of
1394 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1395 // places - OTOH, the RFC also says that this path can be changed with
1396 // MAILCAPS environment variable (containing the colon separated full
1397 // filenames to try) which is not done yet (TODO?)
1399 wxString strHome
= wxGetenv(wxT("HOME"));
1402 dirs
.Add ( strHome
+ wxT("/.") );
1403 dirs
.Add ( wxT("/etc/") );
1404 dirs
.Add ( wxT("/usr/etc/") );
1405 dirs
.Add ( wxT("/usr/local/etc/") );
1406 dirs
.Add ( wxT("/etc/mail/") );
1407 dirs
.Add ( wxT("/usr/public/lib/") );
1408 if (!sExtraDir
.empty()) dirs
.Add ( sExtraDir
+ wxT("/") );
1410 size_t nDirs
= dirs
.GetCount();
1411 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1413 wxString file
= dirs
[nDir
] + wxT("mailcap");
1414 if ( wxFile::Exists(file
) ) {
1418 file
= dirs
[nDir
] + wxT("mime.types");
1419 if ( wxFile::Exists(file
) ) {
1420 ReadMimeTypes(file
);
1426 bool wxMimeTypesManagerImpl::WriteToMimeTypes (int index
, bool delete_index
)
1428 // check we have the right manager
1429 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1433 wxString strHome
= wxGetenv(wxT("HOME"));
1435 // and now the users mailcap
1436 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1438 wxMimeTextFile file
;
1439 if ( wxFile::Exists(strUserMailcap
) )
1441 bTemp
= file
.Open(strUserMailcap
);
1445 if (delete_index
) return FALSE
;
1446 bTemp
= file
.Create(strUserMailcap
);
1451 // test for netscape's header and return FALSE if its found
1452 nIndex
= file
.pIndexOf (wxT("#--Netscape"));
1453 if (nIndex
!= wxNOT_FOUND
)
1455 wxASSERT_MSG(FALSE
,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1458 // write it in alternative format
1459 // get rid of unwanted entries
1460 wxString strType
= m_aTypes
[index
];
1461 nIndex
= file
.pIndexOf (strType
);
1462 // get rid of all the unwanted entries...
1463 if (nIndex
!= wxNOT_FOUND
) file
.CommentLine (nIndex
);
1467 // add the new entries in
1468 wxString sTmp
= strType
.Append (wxT(' '), 40-strType
.Len() );
1469 sTmp
= sTmp
+ m_aExtensions
[index
];
1470 file
.AddLine (sTmp
);
1474 bTemp
= file
.Write ();
1480 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes (int index
, bool delete_index
)
1482 //check we have the right managers
1483 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1487 wxString strHome
= wxGetenv(wxT("HOME"));
1489 // and now the users mailcap
1490 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1492 wxMimeTextFile file
;
1493 if ( wxFile::Exists(strUserMailcap
) )
1495 bTemp
= file
.Open(strUserMailcap
);
1499 if (delete_index
) return FALSE
;
1500 bTemp
= file
.Create(strUserMailcap
);
1505 // write it in the format that Netscape uses
1507 // test for netscape's header and insert if required...
1508 // this is a comment so use TRUE
1509 nIndex
= file
.pIndexOf (wxT("#--Netscape"), TRUE
);
1510 if (nIndex
== wxNOT_FOUND
)
1512 // either empty file or metamail format
1513 // at present we can't cope with mixed formats, so exit to preseve
1514 // metamail entreies
1515 if (file
.GetLineCount () > 0)
1517 wxASSERT_MSG(FALSE
, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1520 file
.InsertLine (wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1524 wxString strType
= wxT("type=") + m_aTypes
[index
];
1525 nIndex
= file
.pIndexOf (strType
);
1526 // get rid of all the unwanted entries...
1527 if (nIndex
!= wxNOT_FOUND
)
1529 wxString sOld
= file
[nIndex
];
1530 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1532 file
.CommentLine(nIndex
);
1533 sOld
= file
[nIndex
];
1534 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1537 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1539 else nIndex
= (int) file
.GetLineCount();
1541 wxString sTmp
= strType
+ wxT(" \\");
1542 if (!delete_index
) file
.InsertLine (sTmp
, nIndex
);
1543 if ( ! m_aDescriptions
.Item(index
).empty() )
1545 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1549 file
.InsertLine (sTmp
, nIndex
);
1552 wxString sExts
= m_aExtensions
.Item(index
);
1553 sTmp
= wxT("exts=\"") + sExts
.Trim(FALSE
).Trim() + wxT("\"");
1557 file
.InsertLine (sTmp
, nIndex
);
1560 bTemp
= file
.Write ();
1567 bool wxMimeTypesManagerImpl::WriteToMailCap (int index
, bool delete_index
)
1569 //check we have the right managers
1570 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1571 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1575 wxString strHome
= wxGetenv(wxT("HOME"));
1577 // and now the users mailcap
1578 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1580 wxMimeTextFile file
;
1581 if ( wxFile::Exists(strUserMailcap
) )
1583 bTemp
= file
.Open(strUserMailcap
);
1587 if (delete_index
) return FALSE
;
1588 bTemp
= file
.Create(strUserMailcap
);
1592 // now got a file we can write to ....
1593 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1595 wxString sCmd
= entries
->GetCommandForVerb(_T("open"), &iOpen
);
1598 sTmp
= m_aTypes
[index
];
1600 int nIndex
= file
.pIndexOf(sTmp
);
1601 // get rid of all the unwanted entries...
1602 if (nIndex
== wxNOT_FOUND
)
1604 nIndex
= (int) file
.GetLineCount();
1608 sOld
= file
[nIndex
];
1609 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1611 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1613 file
.CommentLine(nIndex
);
1614 if (nIndex
< (int) file
.GetLineCount()) sOld
= sOld
+ file
[nIndex
];
1616 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1619 sTmp
= sTmp
+ wxT(";") + sCmd
; //includes wxT(" %s ");
1621 // write it in the format that Netscape uses (default)
1622 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1624 if (! delete_index
) file
.InsertLine (sTmp
, nIndex
);
1628 // write extended format
1631 // todo FIX this code;
1633 // sOld holds all the entries, but our data store only has some
1634 // eg test= is not stored
1636 // so far we have written the mimetype and command out
1637 wxStringTokenizer
sT (sOld
, wxT(";\\"));
1638 if (sT
.CountTokens () > 2)
1640 // first one mimetype; second one command, rest unknown...
1642 s
= sT
.GetNextToken();
1643 s
= sT
.GetNextToken();
1646 s
= sT
.GetNextToken();
1647 while ( ! s
.empty() )
1649 bool bKnownToken
= FALSE
;
1650 if (s
.Contains(wxT("description="))) bKnownToken
= TRUE
;
1651 if (s
.Contains(wxT("x11-bitmap="))) bKnownToken
= TRUE
;
1653 for (i
=0; i
< entries
->GetCount(); i
++)
1655 if (s
.Contains(entries
->GetVerb(i
))) bKnownToken
= TRUE
;
1659 sTmp
= sTmp
+ wxT("; \\");
1660 file
.InsertLine (sTmp
, nIndex
);
1663 s
= sT
.GetNextToken ();
1668 if (! m_aDescriptions
[index
].empty() )
1670 sTmp
= sTmp
+ wxT("; \\");
1671 file
.InsertLine (sTmp
, nIndex
);
1673 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1676 if (! m_aIcons
[index
].empty() )
1678 sTmp
= sTmp
+ wxT("; \\");
1679 file
.InsertLine (sTmp
, nIndex
);
1681 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1683 if ( entries
->GetCount() > 1 )
1687 for (i
=0; i
< entries
->GetCount(); i
++)
1690 sTmp
= sTmp
+ wxT("; \\");
1691 file
.InsertLine (sTmp
, nIndex
);
1693 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1697 file
.InsertLine (sTmp
, nIndex
);
1701 bTemp
= file
.Write ();
1708 wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1712 wxString strType
= ftInfo
.GetMimeType ();
1713 wxString strDesc
= ftInfo
.GetDescription ();
1714 wxString strIcon
= ftInfo
.GetIconFile ();
1716 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1718 if ( ! ftInfo
.GetOpenCommand().empty())
1719 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand () + wxT(" %s "));
1720 if ( ! ftInfo
.GetPrintCommand ().empty())
1721 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand () + wxT(" %s "));
1723 // now find where these extensions are in the data store and remove them
1724 wxArrayString sA_Exts
= ftInfo
.GetExtensions ();
1725 wxString sExt
, sExtStore
;
1727 for (i
=0; i
< sA_Exts
.GetCount(); i
++)
1729 sExt
= sA_Exts
.Item(i
);
1730 //clean up to just a space before and after
1731 sExt
.Trim().Trim(FALSE
);
1732 sExt
= wxT(' ') + sExt
+ wxT(' ');
1733 for (nIndex
= 0; nIndex
< m_aExtensions
.GetCount(); nIndex
++)
1735 sExtStore
= m_aExtensions
.Item(nIndex
);
1736 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0) m_aExtensions
.Item(nIndex
) = sExtStore
;
1741 if ( !DoAssociation (strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1744 return GetFileTypeFromMimeType(strType
);
1748 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1749 const wxString
& strIcon
,
1750 wxMimeTypeCommands
*entry
,
1751 const wxArrayString
& strExtensions
,
1752 const wxString
& strDesc
)
1754 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, TRUE
);
1756 if ( nIndex
== wxNOT_FOUND
)
1759 return WriteMimeInfo (nIndex
, FALSE
);
1762 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
1766 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
1768 // write in metamail format;
1769 if (WriteToMimeTypes (nIndex
, delete_mime
) )
1770 if ( WriteToMailCap (nIndex
, delete_mime
) )
1773 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
1775 // write in netsacpe format;
1776 if (WriteToNSMimeTypes (nIndex
, delete_mime
) )
1777 if ( WriteToMailCap (nIndex
, delete_mime
) )
1780 if (m_mailcapStylesInited
& wxMAILCAP_GNOME
)
1782 // write in Gnome format;
1783 if (WriteGnomeMimeFile (nIndex
, delete_mime
) )
1784 if (WriteGnomeKeyFile (nIndex
, delete_mime
) )
1787 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
1789 // write in KDE format;
1790 if (WriteKDEMimeFile (nIndex
, delete_mime
) )
1797 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
1798 const wxString
& strIcon
,
1799 wxMimeTypeCommands
*entry
,
1800 const wxArrayString
& strExtensions
,
1801 const wxString
& strDesc
,
1802 bool replaceExisting
)
1806 // ensure mimetype is always lower case
1807 wxString mimeType
= strType
.Lower();
1809 // is this a known MIME type?
1810 int nIndex
= m_aTypes
.Index(mimeType
);
1811 if ( nIndex
== wxNOT_FOUND
)
1814 m_aTypes
.Add(mimeType
);
1815 m_aIcons
.Add(strIcon
);
1816 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
1818 // change nIndex so we can use it below to add the extensions
1819 m_aExtensions
.Add(wxEmptyString
);
1820 nIndex
= m_aExtensions
.size() - 1;
1822 m_aDescriptions
.Add(strDesc
);
1824 else // yes, we already have it
1826 if ( replaceExisting
)
1828 // if new description change it
1829 if ( !strDesc
.empty())
1830 m_aDescriptions
[nIndex
] = strDesc
;
1832 // if new icon change it
1833 if ( !strIcon
.empty())
1834 m_aIcons
[nIndex
] = strIcon
;
1838 delete m_aEntries
[nIndex
];
1839 m_aEntries
[nIndex
] = entry
;
1842 else // add data we don't already have ...
1844 // if new description add only if none
1845 if ( m_aDescriptions
[nIndex
].empty() )
1846 m_aDescriptions
[nIndex
] = strDesc
;
1848 // if new icon and no existing icon
1849 if ( m_aIcons
[nIndex
].empty () )
1850 m_aIcons
[nIndex
] = strIcon
;
1852 // add any new entries...
1855 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
1857 size_t count
= entry
->GetCount();
1858 for ( size_t i
= 0; i
< count
; i
++ )
1860 const wxString
& verb
= entry
->GetVerb(i
);
1861 if ( !entryOld
->HasVerb(verb
) )
1863 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
1867 // as we don't store it anywhere, it won't be deleted later as
1868 // usual -- do it immediately instead
1874 // always add the extensions to this mimetype
1875 wxString
& exts
= m_aExtensions
[nIndex
];
1877 // add all extensions we don't have yet
1878 size_t count
= strExtensions
.GetCount();
1879 for ( size_t i
= 0; i
< count
; i
++ )
1881 wxString ext
= strExtensions
[i
] + _T(' ');
1883 if ( exts
.Find(ext
) == wxNOT_FOUND
)
1889 // check data integrity
1890 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
1891 m_aTypes
.Count() == m_aExtensions
.Count() &&
1892 m_aTypes
.Count() == m_aIcons
.Count() &&
1893 m_aTypes
.Count() == m_aDescriptions
.Count() );
1900 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
1907 size_t count
= m_aExtensions
.GetCount();
1908 for ( size_t n
= 0; n
< count
; n
++ )
1910 wxStringTokenizer
tk(m_aExtensions
[n
], _T(' '));
1912 while ( tk
.HasMoreTokens() )
1914 // consider extensions as not being case-sensitive
1915 if ( tk
.GetNextToken().IsSameAs(ext
, FALSE
/* no case */) )
1918 wxFileType
*fileType
= new wxFileType
;
1919 fileType
->m_impl
->Init(this, n
);
1930 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
1934 wxFileType
* fileType
= NULL
;
1935 // mime types are not case-sensitive
1936 wxString
mimetype(mimeType
);
1937 mimetype
.MakeLower();
1939 // first look for an exact match
1940 int index
= m_aTypes
.Index(mimetype
);
1941 if ( index
!= wxNOT_FOUND
)
1943 fileType
= new wxFileType
;
1944 fileType
->m_impl
->Init(this, index
);
1947 // then try to find "text/*" as match for "text/plain" (for example)
1948 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1949 // the whole string - ok.
1951 index
= wxNOT_FOUND
;
1952 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
1954 size_t nCount
= m_aTypes
.Count();
1955 for ( size_t n
= 0; n
< nCount
; n
++ ) {
1956 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
1957 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
1964 if ( index
!= wxNOT_FOUND
)
1966 fileType
= new wxFileType
;
1967 fileType
->m_impl
->Init(this, index
);
1973 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
1975 wxString command
, testcmd
, sV
, sTmp
;
1976 sV
= verb
+ wxT("=");
1977 // list of verb = command pairs for this mimetype
1978 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
1981 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
1983 sTmp
= sPairs
->GetVerbCmd (i
);
1984 if ( sTmp
.Contains(sV
) )
1985 command
= sTmp
.AfterFirst(wxT('='));
1990 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
1994 wxString extensions
;
1995 const wxArrayString
& exts
= filetype
.GetExtensions();
1996 size_t nExts
= exts
.GetCount();
1997 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
1999 extensions
+= wxT(' ');
2001 extensions
+= exts
[nExt
];
2004 AddMimeTypeInfo(filetype
.GetMimeType(),
2006 filetype
.GetDescription());
2008 AddMailcapInfo(filetype
.GetMimeType(),
2009 filetype
.GetOpenCommand(),
2010 filetype
.GetPrintCommand(),
2012 filetype
.GetDescription());
2015 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2016 const wxString
& strExtensions
,
2017 const wxString
& strDesc
)
2019 // reading mailcap may find image/* , while
2020 // reading mime.types finds image/gif and no match is made
2021 // this means all the get functions don't work fix this
2023 wxString sTmp
= strExtensions
;
2025 wxArrayString sExts
;
2026 sTmp
.Trim().Trim(FALSE
);
2028 while (!sTmp
.empty())
2030 sExts
.Add (sTmp
.AfterLast(wxT(' ')));
2031 sTmp
= sTmp
.BeforeLast(wxT(' '));
2034 AddToMimeData (strMimeType
, strIcon
, NULL
, sExts
, strDesc
, TRUE
);
2037 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2038 const wxString
& strOpenCmd
,
2039 const wxString
& strPrintCmd
,
2040 const wxString
& strTest
,
2041 const wxString
& strDesc
)
2045 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2046 entry
->Add(wxT("open=") + strOpenCmd
);
2047 entry
->Add(wxT("print=") + strPrintCmd
);
2048 entry
->Add(wxT("test=") + strTest
);
2051 wxArrayString strExtensions
;
2053 AddToMimeData (strType
, strIcon
, entry
, strExtensions
, strDesc
, TRUE
);
2057 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2059 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2060 strFileName
.c_str());
2062 wxTextFile
file(strFileName
);
2063 #if defined(__WXGTK20__) && wxUSE_UNICODE
2064 if ( !file
.Open( wxConvUTF8
) )
2070 // the information we extract
2071 wxString strMimeType
, strDesc
, strExtensions
;
2073 size_t nLineCount
= file
.GetLineCount();
2074 const wxChar
*pc
= NULL
;
2075 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2078 // now we're at the start of the line
2079 pc
= file
[nLine
].c_str();
2082 // we didn't finish with the previous line yet
2087 while ( wxIsspace(*pc
) )
2090 // comment or blank line?
2091 if ( *pc
== wxT('#') || !*pc
) {
2092 // skip the whole line
2097 // detect file format
2098 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2099 if ( pEqualSign
== NULL
) {
2103 // first field is mime type
2104 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
2109 while ( wxIsspace(*pc
) )
2112 // take all the rest of the string
2115 // no description...
2122 // the string on the left of '=' is the field name
2123 wxString
strLHS(pc
, pEqualSign
- pc
);
2126 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2130 if ( *pc
== wxT('"') ) {
2131 // the string is quoted and ends at the matching quote
2132 pEnd
= wxStrchr(++pc
, wxT('"'));
2133 if ( pEnd
== NULL
) {
2134 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2136 strFileName
.c_str(), nLine
+ 1);
2140 // unquoted string ends at the first space or at the end of
2142 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2146 // now we have the RHS (field value)
2147 wxString
strRHS(pc
, pEnd
- pc
);
2149 // check what follows this entry
2150 if ( *pEnd
== wxT('"') ) {
2155 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2158 // if there is something left, it may be either a '\\' to continue
2159 // the line or the next field of the same entry
2160 bool entryEnded
= *pc
== wxT('\0'),
2161 nextFieldOnSameLine
= FALSE
;
2162 if ( !entryEnded
) {
2163 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2166 // now see what we got
2167 if ( strLHS
== wxT("type") ) {
2168 strMimeType
= strRHS
;
2170 else if ( strLHS
.StartsWith(wxT("desc")) ) {
2173 else if ( strLHS
== wxT("exts") ) {
2174 strExtensions
= strRHS
;
2176 else if ( strLHS
== _T("icon") )
2178 // this one is simply ignored: it usually refers to Netscape
2179 // built in icons which are useless for us anyhow
2181 else if ( !strLHS
.StartsWith(_T("x-")) )
2183 // we suppose that all fields starting with "X-" are
2184 // unregistered extensions according to the standard practice,
2185 // but it may be worth telling the user about other junk in
2186 // his mime.types file
2187 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2188 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
2191 if ( !entryEnded
) {
2192 if ( !nextFieldOnSameLine
)
2194 //else: don't reset it
2196 // as we don't reset strMimeType, the next field in this entry
2197 // will be interpreted correctly.
2203 // depending on the format (Mosaic or Netscape) either space or comma
2204 // is used to separate the extensions
2205 strExtensions
.Replace(wxT(","), wxT(" "));
2207 // also deal with the leading dot
2208 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2210 strExtensions
.erase(0, 1);
2213 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2214 strExtensions
.c_str(),
2215 strMimeType
.c_str(),
2218 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2220 // finished with this line
2227 // ----------------------------------------------------------------------------
2228 // UNIX mailcap files parsing
2229 // ----------------------------------------------------------------------------
2231 // the data for a single MIME type
2232 struct MailcapLineData
2241 wxArrayString verbs
,
2249 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= FALSE
; }
2252 // process a non-standard (i.e. not the first or second one) mailcap field
2254 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2255 const wxString
& curField
)
2257 if ( curField
.empty() )
2263 // is this something of the form foo=bar?
2264 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2267 // split "LHS = RHS" in 2
2268 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2269 rhs
= curField
.AfterFirst(wxT('='));
2271 lhs
.Trim(TRUE
); // from right
2272 rhs
.Trim(FALSE
); // from left
2274 // it might be quoted
2275 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2277 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2280 // is it a command verb or something else?
2281 if ( lhs
== wxT("test") )
2283 if ( wxSystem(rhs
) == 0 )
2286 wxLogTrace(TRACE_MIME_TEST
,
2287 wxT("Test '%s' for mime type '%s' succeeded."),
2288 rhs
.c_str(), data
.type
.c_str());
2293 wxLogTrace(TRACE_MIME_TEST
,
2294 wxT("Test '%s' for mime type '%s' failed, skipping."),
2295 rhs
.c_str(), data
.type
.c_str());
2297 data
.testfailed
= TRUE
;
2300 else if ( lhs
== wxT("desc") )
2304 else if ( lhs
== wxT("x11-bitmap") )
2308 else if ( lhs
== wxT("notes") )
2312 else // not a (recognized) special case, must be a verb (e.g. "print")
2314 data
.verbs
.Add(lhs
);
2315 data
.commands
.Add(rhs
);
2318 else // '=' not found
2320 // so it must be a simple flag
2321 if ( curField
== wxT("needsterminal") )
2323 data
.needsterminal
= TRUE
;
2325 else if ( curField
== wxT("copiousoutput"))
2327 // copiousoutput impies that the viewer is a console program
2328 data
.needsterminal
=
2329 data
.copiousoutput
= TRUE
;
2331 else if ( !IsKnownUnimportantField(curField
) )
2340 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2343 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2344 strFileName
.c_str());
2346 wxTextFile
file(strFileName
);
2347 #if defined(__WXGTK20__) && wxUSE_UNICODE
2348 if ( !file
.Open( wxConvUTF8
) )
2354 // indices of MIME types (in m_aTypes) we already found in this file
2356 // (see the comments near the end of function for the reason we need this)
2357 wxArrayInt aIndicesSeenHere
;
2359 // accumulator for the current field
2361 curField
.reserve(1024);
2363 size_t nLineCount
= file
.GetLineCount();
2364 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2366 // now we're at the start of the line
2367 const wxChar
*pc
= file
[nLine
].c_str();
2370 while ( wxIsspace(*pc
) )
2373 // comment or empty string?
2374 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2380 // what field are we currently in? The first 2 are fixed and there may
2381 // be an arbitrary number of other fields parsed by
2382 // ProcessOtherMailcapField()
2384 // the first field is the MIME type
2390 } currentToken
= Field_Type
;
2392 // the flags and field values on the current line
2393 MailcapLineData data
;
2401 // interpret the next character literally (notice that
2402 // backslash can be used for line continuation)
2403 if ( *++pc
== wxT('\0') )
2405 // fetch the next line if there is one
2406 if ( nLine
== nLineCount
- 1 )
2408 // something is wrong, bail out
2411 wxLogDebug(wxT("Mailcap file %s, line %lu: "
2412 "'\\' on the end of the last line "
2414 strFileName
.c_str(),
2415 (unsigned long)nLine
+ 1);
2419 // pass to the beginning of the next line
2420 pc
= file
[++nLine
].c_str();
2422 // skip pc++ at the end of the loop
2428 // just a normal character
2434 cont
= FALSE
; // end of line reached, exit the loop
2436 // fall through to still process this field
2439 // trim whitespaces from both sides
2440 curField
.Trim(TRUE
).Trim(FALSE
);
2442 switch ( currentToken
)
2445 data
.type
= curField
.Lower();
2446 if ( data
.type
.empty() )
2448 // I don't think that this is a valid mailcap
2449 // entry, but try to interpret it somehow
2450 data
.type
= _T('*');
2453 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2455 // we interpret "type" as "type/*"
2456 data
.type
+= wxT("/*");
2459 currentToken
= Field_OpenCmd
;
2463 data
.cmdOpen
= curField
;
2465 currentToken
= Field_Other
;
2469 if ( !ProcessOtherMailcapField(data
, curField
) )
2471 // don't flood the user with error messages if
2472 // we don't understand something in his
2473 // mailcap, but give them in debug mode because
2474 // this might be useful for the programmer
2477 wxT("Mailcap file %s, line %lu: "
2478 "unknown field '%s' for the "
2479 "MIME type '%s' ignored."),
2480 strFileName
.c_str(),
2481 (unsigned long)nLine
+ 1,
2486 else if ( data
.testfailed
)
2488 // skip this entry entirely
2492 // it already has this value
2493 //currentToken = Field_Other;
2497 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2500 // next token starts immediately after ';'
2508 // continue in the same line
2512 // we read the entire entry, check what have we got
2513 // ------------------------------------------------
2515 // check that we really read something reasonable
2516 if ( currentToken
< Field_Other
)
2518 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2520 strFileName
.c_str(), nLine
+ 1);
2525 // if the test command failed, it's as if the entry were not there at
2527 if ( data
.testfailed
)
2532 // support for flags:
2533 // 1. create an xterm for 'needsterminal'
2534 // 2. append "| $PAGER" for 'copiousoutput'
2536 // Note that the RFC says that having both needsterminal and
2537 // copiousoutput is probably a mistake, so it seems that running
2538 // programs with copiousoutput inside an xterm as it is done now
2539 // is a bad idea (FIXME)
2540 if ( data
.copiousoutput
)
2542 const wxChar
*p
= wxGetenv(_T("PAGER"));
2543 data
.cmdOpen
<< _T(" | ") << (p
? p
: _T("more"));
2546 if ( data
.needsterminal
)
2548 data
.cmdOpen
= wxString::Format(_T("xterm -e sh -c '%s'"),
2549 data
.cmdOpen
.c_str());
2552 if ( !data
.cmdOpen
.empty() )
2554 data
.verbs
.Insert(_T("open"), 0);
2555 data
.commands
.Insert(data
.cmdOpen
, 0);
2558 // we have to decide whether the new entry should replace any entries
2559 // for the same MIME type we had previously found or not
2562 // the fall back entries have the lowest priority, by definition
2569 // have we seen this one before?
2570 int nIndex
= m_aTypes
.Index(data
.type
);
2572 // and if we have, was it in this file?
2573 overwrite
= nIndex
== wxNOT_FOUND
||
2574 aIndicesSeenHere
.Index(nIndex
) != wxNOT_FOUND
;
2577 wxLogTrace(TRACE_MIME
, _T("mailcap %s: %s [%s]"),
2578 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2579 overwrite
? _T("replace") : _T("add"));
2581 int n
= AddToMimeData
2585 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2586 wxArrayString() /* extensions */,
2593 aIndicesSeenHere
.Add(n
);
2600 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2607 size_t count
= m_aTypes
.GetCount();
2608 for ( size_t n
= 0; n
< count
; n
++ )
2610 // don't return template types from here (i.e. anything containg '*')
2612 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
2614 mimetypes
.Add(type
);
2618 return mimetypes
.GetCount();
2621 // ----------------------------------------------------------------------------
2622 // writing to MIME type files
2623 // ----------------------------------------------------------------------------
2625 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2627 wxArrayString sMimeTypes
;
2628 ft
->GetMimeTypes (sMimeTypes
);
2632 for (i
= 0; i
< sMimeTypes
.GetCount(); i
++)
2634 sMime
= sMimeTypes
.Item(i
);
2635 int nIndex
= m_aTypes
.Index (sMime
);
2636 if ( nIndex
== wxNOT_FOUND
)
2638 // error if we get here ??
2643 WriteMimeInfo(nIndex
, TRUE
);
2644 m_aTypes
.RemoveAt(nIndex
);
2645 m_aEntries
.RemoveAt(nIndex
);
2646 m_aExtensions
.RemoveAt(nIndex
);
2647 m_aDescriptions
.RemoveAt(nIndex
);
2648 m_aIcons
.RemoveAt(nIndex
);
2651 // check data integrity
2652 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2653 m_aTypes
.Count() == m_aExtensions
.Count() &&
2654 m_aTypes
.Count() == m_aIcons
.Count() &&
2655 m_aTypes
.Count() == m_aDescriptions
.Count() );
2660 // ----------------------------------------------------------------------------
2661 // private functions
2662 // ----------------------------------------------------------------------------
2664 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2666 static const wxChar
*knownFields
[] =
2668 _T("x-mozilla-flags"),
2670 _T("textualnewlines"),
2673 wxString field
= fieldAll
.BeforeFirst(_T('='));
2674 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2676 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2684 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE