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 // for compilers that support precompilation, includes "wx.h".
44 #include "wx/wxprec.h"
54 #if wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE
57 #include "wx/string.h"
64 #include "wx/dynarray.h"
65 #include "wx/confbase.h"
68 #include "wx/textfile.h"
71 #include "wx/tokenzr.h"
72 #include "wx/iconloc.h"
73 #include "wx/filename.h"
75 #include "wx/unix/mimetype.h"
77 // other standard headers
81 /* silence warnings for comparing unsigned int's <0 */
82 # pragma message disable unscomzer
85 // wxMimeTypeCommands stores the verbs defined for the given MIME type with
87 class wxMimeTypeCommands
90 wxMimeTypeCommands() { }
92 wxMimeTypeCommands(const wxArrayString
& verbs
,
93 const wxArrayString
& commands
)
99 // add a new verb with the command or replace the old value
100 void AddOrReplaceVerb(const wxString
& verb
, const wxString
& cmd
)
102 int n
= m_verbs
.Index(verb
, false /* ignore case */);
103 if ( n
== wxNOT_FOUND
)
114 void Add(const wxString
& s
)
116 m_verbs
.Add(s
.BeforeFirst(_T('=')));
117 m_commands
.Add(s
.AfterFirst(_T('=')));
120 // access the commands
121 size_t GetCount() const { return m_verbs
.GetCount(); }
122 const wxString
& GetVerb(size_t n
) const { return m_verbs
[n
]; }
123 const wxString
& GetCmd(size_t n
) const { return m_commands
[n
]; }
125 bool HasVerb(const wxString
& verb
) const
126 { return m_verbs
.Index(verb
) != wxNOT_FOUND
; }
128 wxString
GetCommandForVerb(const wxString
& verb
, size_t *idx
= NULL
) const
132 int n
= m_verbs
.Index(verb
);
133 if ( n
!= wxNOT_FOUND
)
135 s
= m_commands
[(size_t)n
];
143 // get a "verb=command" string
144 wxString
GetVerbCmd(size_t n
) const
146 return m_verbs
[n
] + _T('=') + m_commands
[n
];
150 wxArrayString m_verbs
,
154 // this class extends wxTextFile
157 class wxMimeTextFile
: public wxTextFile
161 wxMimeTextFile () : wxTextFile () {};
162 wxMimeTextFile (const wxString
& strFile
) : wxTextFile (strFile
) { };
164 int pIndexOf(const wxString
& sSearch
, bool bIncludeComments
= false, int iStart
= 0)
167 int nResult
= wxNOT_FOUND
;
168 if (i
>=GetLineCount()) return wxNOT_FOUND
;
170 wxString sTest
= sSearch
;
174 if (bIncludeComments
)
176 while ( (i
< GetLineCount()) )
180 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
186 while ( (i
< GetLineCount()) )
190 if ( ! sLine
.StartsWith(wxT("#")))
192 if (sLine
.Contains(sTest
)) nResult
= (int) i
;
200 bool CommentLine(int nIndex
)
202 if (nIndex
<0) return false;
203 if (nIndex
>= (int)GetLineCount() ) return false;
204 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
208 bool CommentLine(const wxString
& sTest
)
210 int nIndex
= pIndexOf(sTest
);
211 if (nIndex
<0) return false;
212 if (nIndex
>= (int)GetLineCount() ) return false;
213 GetLine(nIndex
) = GetLine(nIndex
).Prepend(wxT("#"));
217 wxString
GetVerb (size_t i
)
219 if (i
> GetLineCount() ) return wxEmptyString
;
220 wxString sTmp
= GetLine(i
).BeforeFirst(wxT('='));
224 wxString
GetCmd (size_t i
)
226 if (i
> GetLineCount() ) return wxEmptyString
;
227 wxString sTmp
= GetLine(i
).AfterFirst(wxT('='));
232 // in case we're compiling in non-GUI mode
233 class WXDLLEXPORT wxIcon
;
235 // ----------------------------------------------------------------------------
237 // ----------------------------------------------------------------------------
239 // MIME code tracing mask
240 #define TRACE_MIME _T("mime")
242 // give trace messages about the results of mailcap tests
243 #define TRACE_MIME_TEST _T("mimetest")
245 // ----------------------------------------------------------------------------
247 // ----------------------------------------------------------------------------
249 // there are some fields which we don't understand but for which we don't give
250 // warnings as we know that they're not important - this function is used to
252 static bool IsKnownUnimportantField(const wxString
& field
);
254 // ----------------------------------------------------------------------------
256 // ----------------------------------------------------------------------------
259 // This class uses both mailcap and mime.types to gather information about file
262 // The information about mailcap file was extracted from metamail(1) sources
263 // and documentation and subsequently revised when I found the RFC 1524
266 // Format of mailcap file: spaces are ignored, each line is either a comment
267 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
268 // A backslash can be used to quote semicolons and newlines (and, in fact,
269 // anything else including itself).
271 // The first field is always the MIME type in the form of type/subtype (see RFC
272 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
273 // "type" which means the same as "type/*", although I'm not sure whether this
276 // The second field is always the command to run. It is subject to
277 // parameter/filename expansion described below.
279 // All the following fields are optional and may not be present at all. If
280 // they're present they may appear in any order, although each of them should
281 // appear only once. The optional fields are the following:
282 // * notes=xxx is an uninterpreted string which is silently ignored
283 // * test=xxx is the command to be used to determine whether this mailcap line
284 // applies to our data or not. The RHS of this field goes through the
285 // parameter/filename expansion (as the 2nd field) and the resulting string
286 // is executed. The line applies only if the command succeeds, i.e. returns 0
288 // * print=xxx is the command to be used to print (and not view) the data of
289 // this type (parameter/filename expansion is done here too)
290 // * edit=xxx is the command to open/edit the data of this type
291 // * needsterminal means that a new interactive console must be created for
293 // * copiousoutput means that the viewer doesn't interact with the user but
294 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
295 // good example), thus it might be a good idea to use some kind of paging
297 // * textualnewlines means not to perform CR/LF translation (not honored)
298 // * compose and composetyped fields are used to determine the program to be
299 // called to create a new message pert in the specified format (unused).
301 // Parameter/filename expansion:
302 // * %s is replaced with the (full) file name
303 // * %t is replaced with MIME type/subtype of the entry
304 // * for multipart type only %n is replaced with the nnumber of parts and %F is
305 // replaced by an array of (content-type, temporary file name) pairs for all
306 // message parts (TODO)
307 // * %{parameter} is replaced with the value of parameter taken from
308 // Content-type header line of the message.
311 // There are 2 possible formats for mime.types file, one entry per line (used
312 // for global mime.types and called Mosaic format) and "expanded" format where
313 // an entry takes multiple lines (used for users mime.types and called
316 // For both formats spaces are ignored and lines starting with a '#' are
317 // comments. Each record has one of two following forms:
318 // a) for "brief" format:
319 // <mime type> <space separated list of extensions>
320 // b) for "expanded" format:
321 // type=<mime type> BACKSLASH
322 // desc="<description>" BACKSLASH
323 // exts="<comma separated list of extensions>"
325 // (where BACKSLASH is a literal '\\' which we can't put here because cpp
328 // We try to autodetect the format of mime.types: if a non-comment line starts
329 // with "type=" we assume the second format, otherwise the first one.
331 // there may be more than one entry for one and the same mime type, to
332 // choose the right one we have to run the command specified in the test
333 // field on our data.
335 // ----------------------------------------------------------------------------
337 // ----------------------------------------------------------------------------
339 // GNOME stores the info we're interested in in several locations:
340 // 1. xxx.keys files under /usr/share/mime-info
341 // 2. xxx.keys files under ~/.gnome/mime-info
343 // The format of xxx.keys file is the following:
348 // with blank lines separating the entries and indented lines starting with
349 // TABs. We're interested in the field icon-filename whose value is the path
350 // containing the icon.
352 // Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
353 // just before the field name.
356 bool wxMimeTypesManagerImpl::CheckGnomeDirsExist ()
359 wxGetHomeDir( &gnomedir
);
360 wxString sTmp
= gnomedir
;
361 sTmp
= sTmp
+ wxT("/.gnome");
362 if (! wxDir::Exists ( sTmp
) )
364 if (!wxMkdir ( sTmp
))
366 wxLogError(_("Failed to create directory %s/.gnome."), sTmp
.c_str());
370 sTmp
= sTmp
+ wxT("/mime-info");
371 if (! wxDir::Exists ( sTmp
) )
373 if (!wxMkdir ( sTmp
))
375 wxLogError(_("Failed to create directory %s/mime-info."), sTmp
.c_str());
385 bool wxMimeTypesManagerImpl::WriteGnomeKeyFile(int index
, bool delete_index
)
388 wxGetHomeDir( &gnomedir
);
390 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.keys"));
391 // if this fails probably Gnome is not installed ??
392 // create it anyway as a private mime store
394 #if defined(__WXGTK20__) && wxUSE_UNICODE
395 if (! outfile
.Open ( wxConvUTF8
) )
397 if (! outfile
.Open () )
400 if (delete_index
) return false;
401 if (!CheckGnomeDirsExist() ) return false;
405 wxString sTmp
, strType
= m_aTypes
[index
];
406 int nIndex
= outfile
.pIndexOf(strType
);
407 if ( nIndex
== wxNOT_FOUND
)
409 outfile
.AddLine ( strType
+ wxT(':') );
410 // see file:/usr/doc/gnome-libs-devel-1.0.40/devel-docs/mime-type-handling.txt
411 // as this does not deal with internationalisation
412 // wxT( "\t[en_US]") + verb + wxT ('=') + cmd + wxT(" %f");
413 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
414 size_t count
= entries
->GetCount();
415 for ( size_t i
= 0; i
< count
; i
++ )
417 sTmp
= entries
->GetVerbCmd(i
);
418 sTmp
.Replace( wxT("%s"), wxT("%f") );
419 sTmp
= wxT ( "\t") + sTmp
;
420 outfile
.AddLine ( sTmp
);
422 //for international use do something like this
423 //outfile.AddLine ( wxString( "\t[en_US]icon-filename=") + cmd );
424 outfile
.AddLine ( wxT( "\ticon-filename=") + m_aIcons
[index
] );
429 outfile
.CommentLine(nIndex
);
431 wxMimeTypeCommands sOld
;
432 size_t nOld
= nIndex
+ 1;
433 bool oldEntryEnd
= false;
434 while ( (nOld
< outfile
.GetLineCount() )&& (!oldEntryEnd
))
436 sTmp
= outfile
.GetLine(nOld
);
437 if ( (sTmp
[0u] == wxT('\t')) || (sTmp
[0u] == wxT('#')) )
439 // we have another line to deal with
440 outfile
.CommentLine(nOld
);
442 // add the line to our store
443 if ((!delete_index
) && (sTmp
[0u] == wxT('\t')))
446 // next mimetpye ??or blank line
450 // list of entries in our data; these should all be in sOld,
451 // though sOld may also contain other entries , eg flags
454 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
456 for (i
=0; i
< entries
->GetCount(); i
++)
458 // replace any entries in sold that match verbs we know
459 sOld
.AddOrReplaceVerb ( entries
->GetVerb(i
), entries
->GetCmd (i
) );
461 //sOld should also contain the icon
462 if ( !m_aIcons
[index
].empty() )
463 sOld
.AddOrReplaceVerb ( wxT("icon-filename"), m_aIcons
[index
] );
465 for (i
=0; i
< sOld
.GetCount(); i
++)
467 sTmp
= sOld
.GetVerbCmd(i
);
468 sTmp
.Replace( wxT("%s"), wxT("%f") );
469 sTmp
= wxT("\t") + sTmp
;
471 outfile
.InsertLine ( sTmp
, nIndex
);
475 bool bTmp
= outfile
.Write ();
480 bool wxMimeTypesManagerImpl::WriteGnomeMimeFile(int index
, bool delete_index
)
483 wxGetHomeDir( &gnomedir
);
485 wxMimeTextFile
outfile ( gnomedir
+ wxT("/.gnome/mime-info/user.mime"));
486 // if this fails probably Gnome is not installed ??
487 // create it anyway as a private mime store
488 if (! outfile
.Open () )
490 if (delete_index
) return false;
491 if (!CheckGnomeDirsExist() ) return false;
494 wxString strType
= m_aTypes
[index
];
495 int nIndex
= outfile
.pIndexOf(strType
);
496 if ( nIndex
== wxNOT_FOUND
)
498 outfile
.AddLine ( strType
);
499 outfile
.AddLine ( wxT("\text:") + m_aExtensions
.Item(index
) );
505 outfile
.CommentLine(nIndex
);
506 outfile
.CommentLine(nIndex
+1);
509 {// check for next line being the right one to replace ??
510 wxString sOld
= outfile
.GetLine(nIndex
+1);
511 if (sOld
.Contains( wxT("\text: ")))
513 outfile
.GetLine(nIndex
+1) = wxT("\text: ") + m_aExtensions
.Item(index
);
517 outfile
.InsertLine( wxT("\text: ") + m_aExtensions
.Item(index
), nIndex
+ 1 );
521 bool bTmp
= outfile
.Write ();
526 void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString
& filename
,
527 const wxArrayString
& dirs
)
529 wxTextFile
textfile(filename
);
530 #if defined(__WXGTK20__) && wxUSE_UNICODE
531 if ( !textfile
.Open( wxConvUTF8
) )
533 if ( !textfile
.Open() )
536 wxLogTrace(TRACE_MIME
, wxT("--- Opened Gnome file %s ---"),
539 // values for the entry being parsed
540 wxString curMimeType
, curIconFile
;
541 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
543 // these are always empty in this file
544 wxArrayString strExtensions
;
548 size_t nLineCount
= textfile
.GetLineCount();
550 while ( nLine
< nLineCount
)
552 pc
= textfile
[nLine
].c_str();
553 if ( *pc
!= _T('#') )
556 wxLogTrace(TRACE_MIME
, wxT("--- Reading from Gnome file %s '%s' ---"),
557 filename
.c_str(),pc
);
560 if (sTmp
.Contains(wxT("=")) )
563 if (sTmp
.Contains( wxT("icon-filename=") ) )
565 curIconFile
= sTmp
.AfterFirst(wxT('='));
568 else if (sTmp
.Contains( wxT("icon_filename=") ) )
570 curIconFile
= sTmp
.AfterFirst(wxT('='));
572 if (!wxFileExists(curIconFile
))
574 size_t nDirs
= dirs
.GetCount();
575 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
577 wxFileName
newFile( curIconFile
);
578 newFile
.SetPath( dirs
[nDir
] );
579 newFile
.AppendDir( wxT("pixmaps") );
580 newFile
.AppendDir( wxT("document-icons") );
581 newFile
.SetExt( wxT("png") );
582 if (newFile
.FileExists())
583 curIconFile
= newFile
.GetFullPath();
587 else //: some other field,
589 //may contain lines like this (RH7)
590 // \t[lang]open.tex."TeX this file"=tex %f
591 // \tflags.tex.flags=needsterminal
592 // \topen.latex."LaTeX this file"=latex %f
593 // \tflags.latex.flags=needsterminal
597 // \topen.convert.Convert file to Postscript=dvips %f -o `basename %f .dvi`.ps
599 // for now ignore lines with flags in...FIX
600 sTmp
= sTmp
.AfterLast(wxT(']'));
601 sTmp
= sTmp
.AfterLast(wxT('\t'));
602 sTmp
.Trim(false).Trim();
603 if (0 == sTmp
.Replace ( wxT("%f"), wxT("%s") )) sTmp
= sTmp
+ wxT(" %s");
608 } // emd of has an equals sign
611 // not a comment and not an equals sign
612 if (sTmp
.Contains(wxT('/')))
614 // this is the start of the new mimetype
615 // overwrite any existing data
616 if (! curMimeType
.empty())
618 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
620 // now get ready for next bit
621 entry
= new wxMimeTypeCommands
;
623 curMimeType
= sTmp
.BeforeFirst(wxT(':'));
626 } // end of not a comment
627 // ignore blank lines
629 } // end of while, save any data
631 if (! curMimeType
.empty())
632 AddToMimeData ( curMimeType
, curIconFile
, entry
, strExtensions
, strDesc
);
637 void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString
& filename
)
639 wxTextFile
textfile(filename
);
640 if ( !textfile
.Open() )
643 wxLogTrace(TRACE_MIME
,
644 wxT("--- Opened Gnome file %s ---"),
647 // values for the entry being parsed
648 wxString curMimeType
, curExtList
;
651 size_t nLineCount
= textfile
.GetLineCount();
652 for ( size_t nLine
= 0;; nLine
++ )
654 if ( nLine
< nLineCount
)
656 pc
= textfile
[nLine
].c_str();
657 if ( *pc
== wxT('#') )
665 // so that we will fall into the "if" below
672 if ( !curMimeType
.empty() && !curExtList
.empty() )
674 wxLogTrace(TRACE_MIME
,
675 wxT("--- At end of Gnome file finding mimetype %s ---"),
676 curMimeType
.c_str());
678 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
683 // the end - this can only happen if nLine == nLineCount
692 // what do we have here?
693 if ( *pc
== wxT('\t') )
695 // this is a field=value ling
696 pc
++; // skip leading TAB
698 static const int lenField
= 5; // strlen("ext: ")
699 if ( wxStrncmp(pc
, wxT("ext: "), lenField
) == 0 )
701 // skip it and take everything left until the end of line
702 curExtList
= pc
+ lenField
;
704 //else: some other field, we don't care
708 // this is the start of the new section
709 wxLogTrace(TRACE_MIME
,
710 wxT("--- In Gnome file finding mimetype %s ---"),
711 curMimeType
.c_str());
713 if (! curMimeType
.empty())
714 AddMimeTypeInfo(curMimeType
, curExtList
, wxEmptyString
);
718 while ( *pc
!= wxT(':') && *pc
!= wxT('\0') )
720 curMimeType
+= *pc
++;
727 void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
728 const wxString
& dirbase
, const wxArrayString
& dirs
)
730 wxASSERT_MSG( !dirbase
.empty() && !wxEndsWithPathSeparator(dirbase
),
731 _T("base directory shouldn't end with a slash") );
733 wxString dirname
= dirbase
;
734 dirname
<< wxT("/mime-info");
736 if ( !wxDir::Exists(dirname
) )
740 if ( !dir
.IsOpened() )
743 // we will concatenate it with filename to get the full path below
748 cont
= dir
.GetFirst(&filename
, _T("*.mime"), wxDIR_FILES
);
751 LoadGnomeMimeTypesFromMimeFile(dirname
+ filename
);
753 cont
= dir
.GetNext(&filename
);
756 cont
= dir
.GetFirst(&filename
, _T("*.keys"), wxDIR_FILES
);
759 LoadGnomeDataFromKeyFile(dirname
+ filename
, dirs
);
761 cont
= dir
.GetNext(&filename
);
764 // Hack alert: We scan all icons and deduce the
765 // mime-type from the file name.
767 dirname
<< wxT("/pixmaps/document-icons");
769 // these are always empty in this file
770 wxArrayString strExtensions
;
773 if ( !wxDir::Exists(dirname
) )
775 // Jst test for default GPE dir also
776 dirname
= wxT("/usr/share/gpe/pixmaps/default/filemanager/document-icons");
778 if ( !wxDir::Exists(dirname
) )
782 wxDir
dir2( dirname
);
784 cont
= dir2
.GetFirst(&filename
, wxT("gnome-*.png"), wxDIR_FILES
);
787 wxString mimeType
= filename
;
788 mimeType
.Remove( 0, 6 ); // remove "gnome-"
789 mimeType
.Remove( mimeType
.Len()-4, 4 ); // remove ".png"
790 int pos
= mimeType
.Find( wxT("-") );
791 if (pos
!= wxNOT_FOUND
)
793 mimeType
.SetChar( pos
, wxT('/') );
794 wxString iconFile
= dirname
;
795 iconFile
<< wxT("/");
796 iconFile
<< filename
;
797 AddToMimeData ( mimeType
, iconFile
, NULL
, strExtensions
, strDesc
, true );
800 cont
= dir2
.GetNext(&filename
);
804 void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString
& sExtraDir
)
808 wxString gnomedir
= wxGetenv( wxT("GNOMEDIR") );;
809 if (!gnomedir
.empty())
811 gnomedir
<< wxT("/share");
812 dirs
.Add( gnomedir
);
815 dirs
.Add(wxT("/usr/share"));
816 dirs
.Add(wxT("/usr/local/share"));
818 gnomedir
= wxGetHomeDir();
819 gnomedir
<< wxT("/.gnome");
820 dirs
.Add( gnomedir
);
822 if (!sExtraDir
.empty()) dirs
.Add( sExtraDir
);
824 size_t nDirs
= dirs
.GetCount();
825 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
827 LoadGnomeMimeFilesFromDir(dirs
[nDir
], dirs
);
831 // ----------------------------------------------------------------------------
833 // ----------------------------------------------------------------------------
836 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
837 // may be found in either of the following locations
839 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
840 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
842 // The format of a .kdelnk file is almost the same as the one used by
843 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
844 // value for the entry "Type"
846 // kde writing; see http://webcvs.kde.org/cgi-bin/cvsweb.cgi/~checkout~/kdelibs/kio/DESKTOP_ENTRY_STANDARD
847 // for now write to .kdelnk but should eventually do .desktop instead (in preference??)
849 bool wxMimeTypesManagerImpl::CheckKDEDirsExist ( const wxString
&sOK
, const wxString
&sTest
)
853 if (wxDir::Exists(sOK
))
860 wxString sStart
= sOK
+ wxT("/") + sTest
.BeforeFirst(wxT('/'));
861 if (!wxDir::Exists(sStart
)) wxMkdir(sStart
);
862 wxString sEnd
= sTest
.AfterFirst(wxT('/'));
863 return CheckKDEDirsExist(sStart
, sEnd
);
867 bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index
, bool delete_index
)
869 wxMimeTextFile appoutfile
, mimeoutfile
;
870 wxString sHome
= wxGetHomeDir();
871 wxString sTmp
= wxT(".kde/share/mimelnk/");
872 wxString sMime
= m_aTypes
[index
];
873 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.BeforeFirst(wxT('/')) );
874 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
+ wxT(".kdelnk");
877 bool bMimeExists
= mimeoutfile
.Open (sTmp
);
880 bTemp
= mimeoutfile
.Create (sTmp
);
881 // some unknown error eg out of disk space
882 if (!bTemp
) return false;
885 sTmp
= wxT(".kde/share/applnk/");
886 CheckKDEDirsExist (sHome
, sTmp
+ sMime
.AfterFirst(wxT('/')) );
887 sTmp
= sHome
+ wxT('/') + sTmp
+ sMime
.AfterFirst(wxT('/')) + wxT(".kdelnk");
890 bAppExists
= appoutfile
.Open (sTmp
);
893 bTemp
= appoutfile
.Create (sTmp
);
894 // some unknown error eg out of disk space
895 if (!bTemp
) return false;
898 // fixed data; write if new file
901 mimeoutfile
.AddLine(wxT("#KDE Config File"));
902 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
903 mimeoutfile
.AddLine(wxT("Version=1.0"));
904 mimeoutfile
.AddLine(wxT("Type=MimeType"));
905 mimeoutfile
.AddLine(wxT("MimeType=") + sMime
);
910 mimeoutfile
.AddLine(wxT("#KDE Config File"));
911 mimeoutfile
.AddLine(wxT("[KDE Desktop Entry]"));
912 appoutfile
.AddLine(wxT("Version=1.0"));
913 appoutfile
.AddLine(wxT("Type=Application"));
914 appoutfile
.AddLine(wxT("MimeType=") + sMime
+ wxT(';'));
919 mimeoutfile
.CommentLine(wxT("Comment="));
921 mimeoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
922 appoutfile
.CommentLine(wxT("Name="));
924 appoutfile
.AddLine(wxT("Comment=") + m_aDescriptions
[index
]);
926 sTmp
= m_aIcons
[index
];
927 // we can either give the full path, or the shortfilename if its in
928 // one of the directories we search
929 mimeoutfile
.CommentLine(wxT("Icon=") );
930 if (!delete_index
) mimeoutfile
.AddLine(wxT("Icon=") + sTmp
);
931 appoutfile
.CommentLine(wxT("Icon=") );
932 if (!delete_index
) appoutfile
.AddLine(wxT("Icon=") + sTmp
);
934 sTmp
= wxT(" ") + m_aExtensions
[index
];
936 wxStringTokenizer
tokenizer(sTmp
, _T(" "));
937 sTmp
= wxT("Patterns=");
938 mimeoutfile
.CommentLine(sTmp
);
939 while ( tokenizer
.HasMoreTokens() )
941 // holds an extension; need to change it to *.ext;
942 wxString e
= wxT("*.") + tokenizer
.GetNextToken() + wxT(";");
945 if (!delete_index
) mimeoutfile
.AddLine(sTmp
);
947 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
948 // if we don't find open just have an empty string ... FIX this
949 sTmp
= entries
->GetCommandForVerb(_T("open"));
950 sTmp
.Replace( wxT("%s"), wxT("%f") );
952 mimeoutfile
.CommentLine(wxT("DefaultApp=") );
953 if (!delete_index
) mimeoutfile
.AddLine(wxT("DefaultApp=") + sTmp
);
955 sTmp
.Replace( wxT("%f"), wxT("") );
956 appoutfile
.CommentLine(wxT("Exec="));
957 if (!delete_index
) appoutfile
.AddLine(wxT("Exec=") + sTmp
);
959 if (entries
->GetCount() > 1)
961 //other actions as well as open
965 if (mimeoutfile
.Write ()) bTemp
= true;
966 mimeoutfile
.Close ();
967 if (appoutfile
.Write ()) bTemp
= true;
973 void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString
& dirbase
,
974 const wxString
& subdir
,
975 const wxString
& filename
,
976 const wxArrayString
& icondirs
)
979 if ( !file
.Open(dirbase
+ filename
) ) return;
981 wxLogTrace(TRACE_MIME
, wxT("loading KDE file %s"),
982 (dirbase
+filename
).c_str());
984 wxMimeTypeCommands
* entry
= new wxMimeTypeCommands
;
986 wxString mimetype
, mime_desc
, strIcon
;
988 int nIndex
= file
.pIndexOf( wxT("MimeType=") );
989 if (nIndex
== wxNOT_FOUND
)
991 // construct mimetype from the directory name and the basename of the
992 // file (it always has .kdelnk extension)
993 mimetype
<< subdir
<< wxT('/') << filename
.BeforeLast( wxT('.') );
995 else mimetype
= file
.GetCmd (nIndex
);
997 // first find the description string: it is the value in either "Comment="
998 // line or "Comment[<locale_name>]=" one
999 nIndex
= wxNOT_FOUND
;
1003 wxLocale
*locale
= wxGetLocale();
1006 // try "Comment[locale name]" first
1007 comment
<< _T("Comment[") + locale
->GetName() + _T("]=");
1008 nIndex
= file
.pIndexOf(comment
);
1010 #endif // wxUSE_INTL
1012 if ( nIndex
== wxNOT_FOUND
)
1014 comment
= _T("Comment=");
1015 nIndex
= file
.pIndexOf(comment
);
1018 if ( nIndex
!= wxNOT_FOUND
) mime_desc
= file
.GetCmd(nIndex
);
1019 //else: no description
1021 // next find the extensions
1022 wxString mime_extension
;
1024 nIndex
= file
.pIndexOf(_T("Patterns="));
1025 if ( nIndex
!= wxNOT_FOUND
)
1027 wxString exts
= file
.GetCmd (nIndex
);
1029 wxStringTokenizer
tokenizer(exts
, _T(";"));
1030 while ( tokenizer
.HasMoreTokens() )
1032 wxString e
= tokenizer
.GetNextToken();
1033 if ( e
.Left(2) != _T("*.") )
1034 continue; // don't support too difficult patterns
1036 if ( !mime_extension
.empty() )
1038 // separate from the previous ext
1039 mime_extension
<< _T(' ');
1042 mime_extension
<< e
.Mid(2);
1045 sExts
.Add(mime_extension
);
1047 // ok, now we can take care of icon:
1049 nIndex
= file
.pIndexOf(_T("Icon="));
1050 if ( nIndex
!= wxNOT_FOUND
)
1052 strIcon
= file
.GetCmd(nIndex
);
1053 wxLogTrace(TRACE_MIME
, wxT(" icon %s"), strIcon
.c_str());
1054 //it could be the real path, but more often a short name
1057 if (!wxFileExists(strIcon
))
1059 // icon is just the short name
1060 if ( !strIcon
.empty() )
1062 // we must check if the file exists because it may be stored
1063 // in many locations, at least ~/.kde and $KDEDIR
1064 size_t nDir
, nDirs
= icondirs
.GetCount();
1065 for ( nDir
= 0; nDir
< nDirs
; nDir
++ )
1067 wxFileName
fnameIcon( strIcon
);
1068 wxFileName
fname( icondirs
[nDir
], fnameIcon
.GetName() );
1069 fname
.SetExt( wxT("png") );
1070 if (fname
.FileExists())
1072 strIcon
= fname
.GetFullPath();
1073 wxLogTrace(TRACE_MIME
, wxT(" iconfile %s"), strIcon
.c_str());
1080 // now look for lines which know about the application
1081 // exec= or DefaultApp=
1083 nIndex
= file
.pIndexOf(wxT("DefaultApp"));
1085 if ( nIndex
== wxNOT_FOUND
)
1087 // no entry try exec
1088 nIndex
= file
.pIndexOf(wxT("Exec"));
1091 if ( nIndex
!= wxNOT_FOUND
)
1093 wxString sTmp
= file
.GetCmd(nIndex
);
1094 // we expect %f; others including %F and %U and %u are possible
1095 if (0 == sTmp
.Replace ( wxT("%f"), wxT("%s") ))
1096 sTmp
= sTmp
+ wxT(" %s");
1097 entry
->AddOrReplaceVerb (wxString(wxT("open")), sTmp
);
1100 AddToMimeData (mimetype
, strIcon
, entry
, sExts
, mime_desc
);
1103 void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString
& dirbase
,
1104 const wxString
& subdir
,
1105 const wxArrayString
& icondirs
)
1107 wxString dirname
= dirbase
;
1110 if ( !dir
.IsOpened() )
1113 wxLogTrace(TRACE_MIME
, wxT("--- Loading from KDE directory %s ---"),
1119 bool cont
= dir
.GetFirst(&filename
, _T("*.kdelnk"), wxDIR_FILES
);
1122 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1124 cont
= dir
.GetNext(&filename
);
1126 // new standard for Gnome and KDE
1127 cont
= dir
.GetFirst(&filename
, _T("*.desktop"), wxDIR_FILES
);
1130 LoadKDELinksForMimeSubtype(dirname
, subdir
, filename
, icondirs
);
1132 cont
= dir
.GetNext(&filename
);
1136 void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString
& dirbase
,
1137 const wxArrayString
& icondirs
)
1139 wxASSERT_MSG( !dirbase
.empty() && !wxEndsWithPathSeparator(dirbase
),
1140 _T("base directory shouldn't end with a slash") );
1142 wxString dirname
= dirbase
;
1143 dirname
<< _T("/mimelnk");
1145 if ( !wxDir::Exists(dirname
) )
1149 if ( !dir
.IsOpened() )
1152 // we will concatenate it with dir name to get the full path below
1156 bool cont
= dir
.GetFirst(&subdir
, wxEmptyString
, wxDIR_DIRS
);
1159 LoadKDELinksForMimeType(dirname
, subdir
, icondirs
);
1161 cont
= dir
.GetNext(&subdir
);
1165 void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString
& sExtraDir
)
1168 wxArrayString icondirs
;
1170 // FIXME: This code is heavily broken. There are three bugs in it:
1171 // 1) it uses only KDEDIR, which is deprecated, instead of using
1172 // list of paths from KDEDIRS and using KDEDIR only if KDEDIRS
1174 // 2) it doesn't look into ~/.kde/share/config/kdeglobals where
1175 // user's settings are stored and thus *ignores* user's settings
1176 // instead of respecting them
1177 // 3) it "tries to guess KDEDIR" and "tries a few likely theme
1178 // names", both of which is completely arbitrary; instead, the
1179 // code should give up if KDEDIR(S) is not set and/or the icon
1180 // theme cannot be determined, because it means that the user is
1181 // not using KDE (and thus is not interested in KDE icons anyway)
1183 // the variable $KDEDIR is set when KDE is running
1184 wxString kdedir
= wxGetenv( wxT("KDEDIR") );
1186 if (!kdedir
.empty())
1188 // $(KDEDIR)/share/config/kdeglobals holds info
1189 // the current icons theme
1190 wxFileName
configFile( kdedir
, wxEmptyString
);
1191 configFile
.AppendDir( wxT("share") );
1192 configFile
.AppendDir( wxT("config") );
1193 configFile
.SetName( wxT("kdeglobals") );
1196 if (configFile
.FileExists() && config
.Open(configFile
.GetFullPath()))
1198 // $(KDEDIR)/share/config -> $(KDEDIR)/share
1199 configFile
.RemoveDir( configFile
.GetDirCount()-1 );
1200 // $(KDEDIR)/share/ -> $(KDEDIR)/share/icons
1201 configFile
.AppendDir( wxT("icons") );
1204 wxString
theme(wxT("default.kde"));
1205 size_t cnt
= config
.GetLineCount();
1206 for (size_t i
= 0; i
< cnt
; i
++)
1208 if (config
[i
].StartsWith(wxT("Theme="), &theme
/*rest*/))
1211 configFile
.AppendDir(theme
);
1215 // $(KDEDIR)/share/config -> $(KDEDIR)/share
1216 configFile
.RemoveDir( configFile
.GetDirCount()-1 );
1217 // $(KDEDIR)/share/ -> $(KDEDIR)/share/icons
1218 configFile
.AppendDir( wxT("icons") );
1219 // $(KDEDIR)/share/icons -> $(KDEDIR)/share/icons/default.kde
1220 configFile
.AppendDir( wxT("default.kde") );
1223 configFile
.SetName( wxEmptyString
);
1224 configFile
.AppendDir( wxT("32x32") );
1225 configFile
.AppendDir( wxT("mimetypes") );
1227 // Just try a few likely icons theme names
1229 int pos
= configFile
.GetDirCount()-3;
1231 if (!wxDir::Exists(configFile
.GetPath()))
1233 configFile
.RemoveDir( pos
);
1234 configFile
.InsertDir( pos
, wxT("default.kde") );
1237 if (!wxDir::Exists(configFile
.GetPath()))
1239 configFile
.RemoveDir( pos
);
1240 configFile
.InsertDir( pos
, wxT("default") );
1243 if (!wxDir::Exists(configFile
.GetPath()))
1245 configFile
.RemoveDir( pos
);
1246 configFile
.InsertDir( pos
, wxT("crystalsvg") );
1249 if (!wxDir::Exists(configFile
.GetPath()))
1251 configFile
.RemoveDir( pos
);
1252 configFile
.InsertDir( pos
, wxT("crystal") );
1255 if (wxDir::Exists(configFile
.GetPath()))
1256 icondirs
.Add( configFile
.GetFullPath() );
1259 // settings in ~/.kde have maximal priority
1260 dirs
.Add(wxGetHomeDir() + wxT("/.kde/share"));
1261 icondirs
.Add(wxGetHomeDir() + wxT("/.kde/share/icons/"));
1265 dirs
.Add( wxString(kdedir
) + wxT("/share") );
1266 icondirs
.Add( wxString(kdedir
) + wxT("/share/icons/") );
1270 // try to guess KDEDIR
1271 dirs
.Add(_T("/usr/share"));
1272 dirs
.Add(_T("/opt/kde/share"));
1273 icondirs
.Add(_T("/usr/share/icons/"));
1274 icondirs
.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
1275 icondirs
.Add(_T("/opt/kde/share/icons/"));
1278 if (!sExtraDir
.empty()) dirs
.Add (sExtraDir
);
1279 icondirs
.Add(sExtraDir
+ wxT("/icons"));
1281 size_t nDirs
= dirs
.GetCount();
1282 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1284 LoadKDELinkFilesFromDir(dirs
[nDir
], icondirs
);
1288 // ----------------------------------------------------------------------------
1289 // wxFileTypeImpl (Unix)
1290 // ----------------------------------------------------------------------------
1292 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
1296 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1298 sTmp
= m_manager
->GetCommand ( verb
, m_index
[i
] );
1302 return wxFileType::ExpandCommand(sTmp
, params
);
1305 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
1310 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
1312 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
1315 if ( sTmp
.empty () )
1320 iconLoc
->SetFileName(sTmp
);
1328 wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
1331 for (size_t i
= 0; i
< m_index
.GetCount(); i
++)
1332 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
1337 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
1338 wxArrayString
*commands
,
1339 const wxFileType::MessageParameters
& params
) const
1342 wxString vrb
, cmd
, sTmp
;
1344 wxMimeTypeCommands
* sPairs
;
1346 // verbs and commands have been cleared already in mimecmn.cpp...
1347 // if we find no entries in the exact match, try the inexact match
1348 for (size_t n
= 0; ((count
==0) && (n
< m_index
.GetCount())); n
++)
1350 // list of verb = command pairs for this mimetype
1351 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
1353 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
1355 vrb
= sPairs
->GetVerb(i
);
1356 // some gnome entries have . inside
1357 vrb
= vrb
.AfterLast(wxT('.'));
1358 cmd
= sPairs
->GetCmd (i
);
1361 cmd
= wxFileType::ExpandCommand(cmd
, params
);
1363 if ( vrb
.IsSameAs (wxT("open")))
1365 verbs
->Insert(vrb
,0u);
1366 commands
->Insert(cmd
,0u);
1371 commands
->Add (cmd
);
1382 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
1384 wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
1387 // one extension in the space or comma delimitid list
1389 for ( const wxChar
*p
= strExtensions
;; p
++ ) {
1390 if ( *p
== wxT(' ') || *p
== wxT(',') || *p
== wxT('\0') ) {
1391 if ( !strExt
.empty() ) {
1392 extensions
.Add(strExt
);
1395 //else: repeated spaces (shouldn't happen, but it's not that
1396 // important if it does happen)
1398 if ( *p
== wxT('\0') )
1401 else if ( *p
== wxT('.') ) {
1402 // remove the dot from extension (but only if it's the first char)
1403 if ( !strExt
.empty() ) {
1406 //else: no, don't append it
1416 // set an arbitrary command,
1417 // could adjust the code to ask confirmation if it already exists and
1418 // overwriteprompt is true, but this is currently ignored as *Associate* has
1419 // no overwrite prompt
1420 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
, const wxString
& verb
, bool overwriteprompt
/*= true*/)
1422 wxArrayString strExtensions
;
1423 wxString strDesc
, strIcon
;
1425 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1426 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
1428 wxArrayString strTypes
;
1429 GetMimeTypes (strTypes
);
1430 if (strTypes
.GetCount() < 1) return false;
1434 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1436 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1443 // ignore index on the grouds that we only have one icon in a Unix file
1444 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
/*= wxEmptyString*/, int /*index = 0*/)
1446 if (strIcon
.empty()) return false;
1447 wxArrayString strExtensions
;
1450 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1452 wxArrayString strTypes
;
1453 GetMimeTypes (strTypes
);
1454 if (strTypes
.GetCount() < 1) return false;
1458 for (i
= 0; i
< strTypes
.GetCount(); i
++)
1460 if (!m_manager
->DoAssociation (strTypes
[i
], strIcon
, entry
, strExtensions
, strDesc
))
1467 // ----------------------------------------------------------------------------
1468 // wxMimeTypesManagerImpl (Unix)
1469 // ----------------------------------------------------------------------------
1472 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1474 m_initialized
= false;
1475 m_mailcapStylesInited
= 0;
1478 void wxMimeTypesManagerImpl::InitIfNeeded()
1480 if ( !m_initialized
)
1482 // set the flag first to prevent recursion
1483 m_initialized
= true;
1486 wxString wm
= wxGetenv( wxT("WINDOWMANAGER") );
1488 if (wm
.Find( wxT("kde") ) != wxNOT_FOUND
)
1489 Initialize( wxMAILCAP_KDE
|wxMAILCAP_STANDARD
);
1490 else if (wm
.Find( wxT("gnome") ) != wxNOT_FOUND
)
1491 Initialize( wxMAILCAP_GNOME
|wxMAILCAP_STANDARD
);
1498 // read system and user mailcaps and other files
1499 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles
,
1500 const wxString
& sExtraDir
)
1502 // read mimecap amd mime.types
1503 if ( (mailcapStyles
& wxMAILCAP_NETSCAPE
) ||
1504 (mailcapStyles
& wxMAILCAP_STANDARD
) )
1505 GetMimeInfo(sExtraDir
);
1507 // read GNOME tables
1508 if (mailcapStyles
& wxMAILCAP_GNOME
)
1509 GetGnomeMimeInfo(sExtraDir
);
1512 if (mailcapStyles
& wxMAILCAP_KDE
)
1513 GetKDEMimeInfo(sExtraDir
);
1515 m_mailcapStylesInited
|= mailcapStyles
;
1518 // clear data so you can read another group of WM files
1519 void wxMimeTypesManagerImpl::ClearData()
1523 m_aExtensions
.Clear ();
1524 m_aDescriptions
.Clear ();
1526 WX_CLEAR_ARRAY(m_aEntries
);
1529 m_mailcapStylesInited
= 0;
1532 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1538 void wxMimeTypesManagerImpl::GetMimeInfo (const wxString
& sExtraDir
)
1540 // read this for netscape or Metamail formats
1542 // directories where we look for mailcap and mime.types by default
1543 // used by netscape and pine and other mailers, using 2 different formats!
1545 // (taken from metamail(1) sources)
1547 // although RFC 1524 specifies the search path of
1548 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1549 // places - OTOH, the RFC also says that this path can be changed with
1550 // MAILCAPS environment variable (containing the colon separated full
1551 // filenames to try) which is not done yet (TODO?)
1553 wxString strHome
= wxGetenv(wxT("HOME"));
1556 dirs
.Add ( strHome
+ wxT("/.") );
1557 dirs
.Add ( wxT("/etc/") );
1558 dirs
.Add ( wxT("/usr/etc/") );
1559 dirs
.Add ( wxT("/usr/local/etc/") );
1560 dirs
.Add ( wxT("/etc/mail/") );
1561 dirs
.Add ( wxT("/usr/public/lib/") );
1562 if (!sExtraDir
.empty()) dirs
.Add ( sExtraDir
+ wxT("/") );
1564 size_t nDirs
= dirs
.GetCount();
1565 for ( size_t nDir
= 0; nDir
< nDirs
; nDir
++ )
1567 wxString file
= dirs
[nDir
] + wxT("mailcap");
1568 if ( wxFile::Exists(file
) ) {
1572 file
= dirs
[nDir
] + wxT("mime.types");
1573 if ( wxFile::Exists(file
) ) {
1574 ReadMimeTypes(file
);
1580 bool wxMimeTypesManagerImpl::WriteToMimeTypes (int index
, bool delete_index
)
1582 // check we have the right manager
1583 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1587 wxString strHome
= wxGetenv(wxT("HOME"));
1589 // and now the users mailcap
1590 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1592 wxMimeTextFile file
;
1593 if ( wxFile::Exists(strUserMailcap
) )
1595 bTemp
= file
.Open(strUserMailcap
);
1599 if (delete_index
) return false;
1600 bTemp
= file
.Create(strUserMailcap
);
1605 // test for netscape's header and return false if its found
1606 nIndex
= file
.pIndexOf (wxT("#--Netscape"));
1607 if (nIndex
!= wxNOT_FOUND
)
1609 wxASSERT_MSG(false,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1612 // write it in alternative format
1613 // get rid of unwanted entries
1614 wxString strType
= m_aTypes
[index
];
1615 nIndex
= file
.pIndexOf (strType
);
1616 // get rid of all the unwanted entries...
1617 if (nIndex
!= wxNOT_FOUND
) file
.CommentLine (nIndex
);
1621 // add the new entries in
1622 wxString sTmp
= strType
.Append (wxT(' '), 40-strType
.Len() );
1623 sTmp
= sTmp
+ m_aExtensions
[index
];
1624 file
.AddLine (sTmp
);
1628 bTemp
= file
.Write ();
1634 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes (int index
, bool delete_index
)
1636 //check we have the right managers
1637 if (! ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) )
1641 wxString strHome
= wxGetenv(wxT("HOME"));
1643 // and now the users mailcap
1644 wxString strUserMailcap
= strHome
+ wxT("/.mime.types");
1646 wxMimeTextFile file
;
1647 if ( wxFile::Exists(strUserMailcap
) )
1649 bTemp
= file
.Open(strUserMailcap
);
1653 if (delete_index
) return false;
1654 bTemp
= file
.Create(strUserMailcap
);
1659 // write it in the format that Netscape uses
1661 // test for netscape's header and insert if required...
1662 // this is a comment so use true
1663 nIndex
= file
.pIndexOf (wxT("#--Netscape"), true);
1664 if (nIndex
== wxNOT_FOUND
)
1666 // either empty file or metamail format
1667 // at present we can't cope with mixed formats, so exit to preseve
1668 // metamail entreies
1669 if (file
.GetLineCount () > 0)
1671 wxASSERT_MSG(false, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1674 file
.InsertLine (wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1678 wxString strType
= wxT("type=") + m_aTypes
[index
];
1679 nIndex
= file
.pIndexOf (strType
);
1680 // get rid of all the unwanted entries...
1681 if (nIndex
!= wxNOT_FOUND
)
1683 wxString sOld
= file
[nIndex
];
1684 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1686 file
.CommentLine(nIndex
);
1687 sOld
= file
[nIndex
];
1688 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex
, sOld
.c_str());
1691 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1693 else nIndex
= (int) file
.GetLineCount();
1695 wxString sTmp
= strType
+ wxT(" \\");
1696 if (!delete_index
) file
.InsertLine (sTmp
, nIndex
);
1697 if ( ! m_aDescriptions
.Item(index
).empty() )
1699 sTmp
= wxT("desc=\"") + m_aDescriptions
[index
]+ wxT("\" \\"); //.trim ??
1703 file
.InsertLine (sTmp
, nIndex
);
1706 wxString sExts
= m_aExtensions
.Item(index
);
1707 sTmp
= wxT("exts=\"") + sExts
.Trim(false).Trim() + wxT("\"");
1711 file
.InsertLine (sTmp
, nIndex
);
1714 bTemp
= file
.Write ();
1721 bool wxMimeTypesManagerImpl::WriteToMailCap (int index
, bool delete_index
)
1723 //check we have the right managers
1724 if ( !( ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
) ||
1725 ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) ) )
1729 wxString strHome
= wxGetenv(wxT("HOME"));
1731 // and now the users mailcap
1732 wxString strUserMailcap
= strHome
+ wxT("/.mailcap");
1734 wxMimeTextFile file
;
1735 if ( wxFile::Exists(strUserMailcap
) )
1737 bTemp
= file
.Open(strUserMailcap
);
1741 if (delete_index
) return false;
1742 bTemp
= file
.Create(strUserMailcap
);
1746 // now got a file we can write to ....
1747 wxMimeTypeCommands
* entries
= m_aEntries
[index
];
1749 wxString sCmd
= entries
->GetCommandForVerb(_T("open"), &iOpen
);
1752 sTmp
= m_aTypes
[index
];
1754 int nIndex
= file
.pIndexOf(sTmp
);
1755 // get rid of all the unwanted entries...
1756 if (nIndex
== wxNOT_FOUND
)
1758 nIndex
= (int) file
.GetLineCount();
1762 sOld
= file
[nIndex
];
1763 wxLogTrace(TRACE_MIME
, wxT("--- Deleting from mailcap line '%d' ---"), nIndex
);
1765 while ( (sOld
.Contains(wxT("\\"))) && (nIndex
< (int) file
.GetLineCount()) )
1767 file
.CommentLine(nIndex
);
1768 if (nIndex
< (int) file
.GetLineCount()) sOld
= sOld
+ file
[nIndex
];
1770 if (nIndex
< (int) file
.GetLineCount()) file
.CommentLine (nIndex
);
1773 sTmp
= sTmp
+ wxT(";") + sCmd
; //includes wxT(" %s ");
1775 // write it in the format that Netscape uses (default)
1776 if (! ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
) )
1778 if (! delete_index
) file
.InsertLine (sTmp
, nIndex
);
1782 // write extended format
1785 // todo FIX this code;
1787 // sOld holds all the entries, but our data store only has some
1788 // eg test= is not stored
1790 // so far we have written the mimetype and command out
1791 wxStringTokenizer
sT (sOld
, wxT(";\\"));
1792 if (sT
.CountTokens () > 2)
1794 // first one mimetype; second one command, rest unknown...
1796 s
= sT
.GetNextToken();
1797 s
= sT
.GetNextToken();
1800 s
= sT
.GetNextToken();
1801 while ( ! s
.empty() )
1803 bool bKnownToken
= false;
1804 if (s
.Contains(wxT("description="))) bKnownToken
= true;
1805 if (s
.Contains(wxT("x11-bitmap="))) bKnownToken
= true;
1807 for (i
=0; i
< entries
->GetCount(); i
++)
1809 if (s
.Contains(entries
->GetVerb(i
))) bKnownToken
= true;
1813 sTmp
= sTmp
+ wxT("; \\");
1814 file
.InsertLine (sTmp
, nIndex
);
1817 s
= sT
.GetNextToken ();
1822 if (! m_aDescriptions
[index
].empty() )
1824 sTmp
= sTmp
+ wxT("; \\");
1825 file
.InsertLine (sTmp
, nIndex
);
1827 sTmp
= wxT(" description=\"") + m_aDescriptions
[index
] + wxT("\"");
1830 if (! m_aIcons
[index
].empty() )
1832 sTmp
= sTmp
+ wxT("; \\");
1833 file
.InsertLine (sTmp
, nIndex
);
1835 sTmp
= wxT(" x11-bitmap=\"") + m_aIcons
[index
] + wxT("\"");
1837 if ( entries
->GetCount() > 1 )
1841 for (i
=0; i
< entries
->GetCount(); i
++)
1844 sTmp
= sTmp
+ wxT("; \\");
1845 file
.InsertLine (sTmp
, nIndex
);
1847 sTmp
= wxT(" ") + entries
->GetVerbCmd(i
);
1851 file
.InsertLine (sTmp
, nIndex
);
1855 bTemp
= file
.Write ();
1862 wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
1866 wxString strType
= ftInfo
.GetMimeType ();
1867 wxString strDesc
= ftInfo
.GetDescription ();
1868 wxString strIcon
= ftInfo
.GetIconFile ();
1870 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands ();
1872 if ( ! ftInfo
.GetOpenCommand().empty())
1873 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand () + wxT(" %s "));
1874 if ( ! ftInfo
.GetPrintCommand ().empty())
1875 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand () + wxT(" %s "));
1877 // now find where these extensions are in the data store and remove them
1878 wxArrayString sA_Exts
= ftInfo
.GetExtensions ();
1879 wxString sExt
, sExtStore
;
1881 for (i
=0; i
< sA_Exts
.GetCount(); i
++)
1883 sExt
= sA_Exts
.Item(i
);
1884 //clean up to just a space before and after
1885 sExt
.Trim().Trim(false);
1886 sExt
= wxT(' ') + sExt
+ wxT(' ');
1887 for (nIndex
= 0; nIndex
< m_aExtensions
.GetCount(); nIndex
++)
1889 sExtStore
= m_aExtensions
.Item(nIndex
);
1890 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0) m_aExtensions
.Item(nIndex
) = sExtStore
;
1895 if ( !DoAssociation (strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
1898 return GetFileTypeFromMimeType(strType
);
1902 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
1903 const wxString
& strIcon
,
1904 wxMimeTypeCommands
*entry
,
1905 const wxArrayString
& strExtensions
,
1906 const wxString
& strDesc
)
1908 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
1910 if ( nIndex
== wxNOT_FOUND
)
1913 return WriteMimeInfo (nIndex
, false);
1916 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex
, bool delete_mime
)
1920 if ( m_mailcapStylesInited
& wxMAILCAP_STANDARD
)
1922 // write in metamail format;
1923 if (WriteToMimeTypes (nIndex
, delete_mime
) )
1924 if ( WriteToMailCap (nIndex
, delete_mime
) )
1927 if ( m_mailcapStylesInited
& wxMAILCAP_NETSCAPE
)
1929 // write in netsacpe format;
1930 if (WriteToNSMimeTypes (nIndex
, delete_mime
) )
1931 if ( WriteToMailCap (nIndex
, delete_mime
) )
1934 if (m_mailcapStylesInited
& wxMAILCAP_GNOME
)
1936 // write in Gnome format;
1937 if (WriteGnomeMimeFile (nIndex
, delete_mime
) )
1938 if (WriteGnomeKeyFile (nIndex
, delete_mime
) )
1941 if (m_mailcapStylesInited
& wxMAILCAP_KDE
)
1943 // write in KDE format;
1944 if (WriteKDEMimeFile (nIndex
, delete_mime
) )
1951 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
1952 const wxString
& strIcon
,
1953 wxMimeTypeCommands
*entry
,
1954 const wxArrayString
& strExtensions
,
1955 const wxString
& strDesc
,
1956 bool replaceExisting
)
1960 // ensure mimetype is always lower case
1961 wxString mimeType
= strType
.Lower();
1963 // is this a known MIME type?
1964 int nIndex
= m_aTypes
.Index(mimeType
);
1965 if ( nIndex
== wxNOT_FOUND
)
1968 m_aTypes
.Add(mimeType
);
1969 m_aIcons
.Add(strIcon
);
1970 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
1972 // change nIndex so we can use it below to add the extensions
1973 m_aExtensions
.Add(wxEmptyString
);
1974 nIndex
= m_aExtensions
.size() - 1;
1976 m_aDescriptions
.Add(strDesc
);
1978 else // yes, we already have it
1980 if ( replaceExisting
)
1982 // if new description change it
1983 if ( !strDesc
.empty())
1984 m_aDescriptions
[nIndex
] = strDesc
;
1986 // if new icon change it
1987 if ( !strIcon
.empty())
1988 m_aIcons
[nIndex
] = strIcon
;
1992 delete m_aEntries
[nIndex
];
1993 m_aEntries
[nIndex
] = entry
;
1996 else // add data we don't already have ...
1998 // if new description add only if none
1999 if ( m_aDescriptions
[nIndex
].empty() )
2000 m_aDescriptions
[nIndex
] = strDesc
;
2002 // if new icon and no existing icon
2003 if ( m_aIcons
[nIndex
].empty () )
2004 m_aIcons
[nIndex
] = strIcon
;
2006 // add any new entries...
2009 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
2011 size_t count
= entry
->GetCount();
2012 for ( size_t i
= 0; i
< count
; i
++ )
2014 const wxString
& verb
= entry
->GetVerb(i
);
2015 if ( !entryOld
->HasVerb(verb
) )
2017 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
2021 // as we don't store it anywhere, it won't be deleted later as
2022 // usual -- do it immediately instead
2028 // always add the extensions to this mimetype
2029 wxString
& exts
= m_aExtensions
[nIndex
];
2031 // add all extensions we don't have yet
2032 size_t count
= strExtensions
.GetCount();
2033 for ( size_t i
= 0; i
< count
; i
++ )
2035 wxString ext
= strExtensions
[i
] + _T(' ');
2037 if ( exts
.Find(ext
) == wxNOT_FOUND
)
2043 // check data integrity
2044 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2045 m_aTypes
.Count() == m_aExtensions
.Count() &&
2046 m_aTypes
.Count() == m_aIcons
.Count() &&
2047 m_aTypes
.Count() == m_aDescriptions
.Count() );
2054 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
2061 size_t count
= m_aExtensions
.GetCount();
2062 for ( size_t n
= 0; n
< count
; n
++ )
2064 wxStringTokenizer
tk(m_aExtensions
[n
], _T(' '));
2066 while ( tk
.HasMoreTokens() )
2068 // consider extensions as not being case-sensitive
2069 if ( tk
.GetNextToken().IsSameAs(ext
, false /* no case */) )
2072 wxFileType
*fileType
= new wxFileType
;
2073 fileType
->m_impl
->Init(this, n
);
2084 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
2088 wxFileType
* fileType
= NULL
;
2089 // mime types are not case-sensitive
2090 wxString
mimetype(mimeType
);
2091 mimetype
.MakeLower();
2093 // first look for an exact match
2094 int index
= m_aTypes
.Index(mimetype
);
2095 if ( index
!= wxNOT_FOUND
)
2097 fileType
= new wxFileType
;
2098 fileType
->m_impl
->Init(this, index
);
2101 // then try to find "text/*" as match for "text/plain" (for example)
2102 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
2103 // the whole string - ok.
2105 index
= wxNOT_FOUND
;
2106 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
2108 size_t nCount
= m_aTypes
.Count();
2109 for ( size_t n
= 0; n
< nCount
; n
++ ) {
2110 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
2111 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") ) {
2118 if ( index
!= wxNOT_FOUND
)
2120 fileType
= new wxFileType
;
2121 fileType
->m_impl
->Init(this, index
);
2127 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
2129 wxString command
, testcmd
, sV
, sTmp
;
2130 sV
= verb
+ wxT("=");
2131 // list of verb = command pairs for this mimetype
2132 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
2135 for ( i
= 0; i
< sPairs
->GetCount (); i
++ )
2137 sTmp
= sPairs
->GetVerbCmd (i
);
2138 if ( sTmp
.Contains(sV
) )
2139 command
= sTmp
.AfterFirst(wxT('='));
2144 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
2148 wxString extensions
;
2149 const wxArrayString
& exts
= filetype
.GetExtensions();
2150 size_t nExts
= exts
.GetCount();
2151 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ ) {
2153 extensions
+= wxT(' ');
2155 extensions
+= exts
[nExt
];
2158 AddMimeTypeInfo(filetype
.GetMimeType(),
2160 filetype
.GetDescription());
2162 AddMailcapInfo(filetype
.GetMimeType(),
2163 filetype
.GetOpenCommand(),
2164 filetype
.GetPrintCommand(),
2166 filetype
.GetDescription());
2169 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
2170 const wxString
& strExtensions
,
2171 const wxString
& strDesc
)
2173 // reading mailcap may find image/* , while
2174 // reading mime.types finds image/gif and no match is made
2175 // this means all the get functions don't work fix this
2177 wxString sTmp
= strExtensions
;
2179 wxArrayString sExts
;
2180 sTmp
.Trim().Trim(false);
2182 while (!sTmp
.empty())
2184 sExts
.Add (sTmp
.AfterLast(wxT(' ')));
2185 sTmp
= sTmp
.BeforeLast(wxT(' '));
2188 AddToMimeData (strMimeType
, strIcon
, NULL
, sExts
, strDesc
, true);
2191 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString
& strType
,
2192 const wxString
& strOpenCmd
,
2193 const wxString
& strPrintCmd
,
2194 const wxString
& strTest
,
2195 const wxString
& strDesc
)
2199 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands
;
2200 entry
->Add(wxT("open=") + strOpenCmd
);
2201 entry
->Add(wxT("print=") + strPrintCmd
);
2202 entry
->Add(wxT("test=") + strTest
);
2205 wxArrayString strExtensions
;
2207 AddToMimeData (strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
2211 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString
& strFileName
)
2213 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mime.types file '%s' ---"),
2214 strFileName
.c_str());
2216 wxTextFile
file(strFileName
);
2217 #if defined(__WXGTK20__) && wxUSE_UNICODE
2218 if ( !file
.Open( wxConvUTF8
) )
2224 // the information we extract
2225 wxString strMimeType
, strDesc
, strExtensions
;
2227 size_t nLineCount
= file
.GetLineCount();
2228 const wxChar
*pc
= NULL
;
2229 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2232 // now we're at the start of the line
2233 pc
= file
[nLine
].c_str();
2236 // we didn't finish with the previous line yet
2241 while ( wxIsspace(*pc
) )
2244 // comment or blank line?
2245 if ( *pc
== wxT('#') || !*pc
) {
2246 // skip the whole line
2251 // detect file format
2252 const wxChar
*pEqualSign
= wxStrchr(pc
, wxT('='));
2253 if ( pEqualSign
== NULL
) {
2257 // first field is mime type
2258 for ( strMimeType
.Empty(); !wxIsspace(*pc
) && *pc
!= wxT('\0'); pc
++ ) {
2263 while ( wxIsspace(*pc
) )
2266 // take all the rest of the string
2269 // no description...
2276 // the string on the left of '=' is the field name
2277 wxString
strLHS(pc
, pEqualSign
- pc
);
2280 for ( pc
= pEqualSign
+ 1; wxIsspace(*pc
); pc
++ )
2284 if ( *pc
== wxT('"') ) {
2285 // the string is quoted and ends at the matching quote
2286 pEnd
= wxStrchr(++pc
, wxT('"'));
2287 if ( pEnd
== NULL
) {
2288 wxLogWarning(_("Mime.types file %s, line %d: unterminated quoted string."),
2289 strFileName
.c_str(), nLine
+ 1);
2293 // unquoted string ends at the first space or at the end of
2295 for ( pEnd
= pc
; *pEnd
&& !wxIsspace(*pEnd
); pEnd
++ )
2299 // now we have the RHS (field value)
2300 wxString
strRHS(pc
, pEnd
- pc
);
2302 // check what follows this entry
2303 if ( *pEnd
== wxT('"') ) {
2308 for ( pc
= pEnd
; wxIsspace(*pc
); pc
++ )
2311 // if there is something left, it may be either a '\\' to continue
2312 // the line or the next field of the same entry
2313 bool entryEnded
= *pc
== wxT('\0'),
2314 nextFieldOnSameLine
= false;
2315 if ( !entryEnded
) {
2316 nextFieldOnSameLine
= ((*pc
!= wxT('\\')) || (pc
[1] != wxT('\0')));
2319 // now see what we got
2320 if ( strLHS
== wxT("type") ) {
2321 strMimeType
= strRHS
;
2323 else if ( strLHS
.StartsWith(wxT("desc")) ) {
2326 else if ( strLHS
== wxT("exts") ) {
2327 strExtensions
= strRHS
;
2329 else if ( strLHS
== _T("icon") )
2331 // this one is simply ignored: it usually refers to Netscape
2332 // built in icons which are useless for us anyhow
2334 else if ( !strLHS
.StartsWith(_T("x-")) )
2336 // we suppose that all fields starting with "X-" are
2337 // unregistered extensions according to the standard practice,
2338 // but it may be worth telling the user about other junk in
2339 // his mime.types file
2340 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2341 strFileName
.c_str(), nLine
+ 1, strLHS
.c_str());
2344 if ( !entryEnded
) {
2345 if ( !nextFieldOnSameLine
)
2347 //else: don't reset it
2349 // as we don't reset strMimeType, the next field in this entry
2350 // will be interpreted correctly.
2356 // depending on the format (Mosaic or Netscape) either space or comma
2357 // is used to separate the extensions
2358 strExtensions
.Replace(wxT(","), wxT(" "));
2360 // also deal with the leading dot
2361 if ( !strExtensions
.empty() && strExtensions
[0u] == wxT('.') )
2363 strExtensions
.erase(0, 1);
2366 wxLogTrace(TRACE_MIME
, wxT("mime.types: '%s' => '%s' (%s)"),
2367 strExtensions
.c_str(),
2368 strMimeType
.c_str(),
2371 AddMimeTypeInfo(strMimeType
, strExtensions
, strDesc
);
2373 // finished with this line
2380 // ----------------------------------------------------------------------------
2381 // UNIX mailcap files parsing
2382 // ----------------------------------------------------------------------------
2384 // the data for a single MIME type
2385 struct MailcapLineData
2394 wxArrayString verbs
,
2402 MailcapLineData() { testfailed
= needsterminal
= copiousoutput
= false; }
2405 // process a non-standard (i.e. not the first or second one) mailcap field
2407 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData
& data
,
2408 const wxString
& curField
)
2410 if ( curField
.empty() )
2416 // is this something of the form foo=bar?
2417 const wxChar
*pEq
= wxStrchr(curField
, wxT('='));
2420 // split "LHS = RHS" in 2
2421 wxString lhs
= curField
.BeforeFirst(wxT('=')),
2422 rhs
= curField
.AfterFirst(wxT('='));
2424 lhs
.Trim(true); // from right
2425 rhs
.Trim(false); // from left
2427 // it might be quoted
2428 if ( !rhs
.empty() && rhs
[0u] == wxT('"') && rhs
.Last() == wxT('"') )
2430 rhs
= rhs
.Mid(1, rhs
.length() - 2);
2433 // is it a command verb or something else?
2434 if ( lhs
== wxT("test") )
2436 if ( wxSystem(rhs
) == 0 )
2439 wxLogTrace(TRACE_MIME_TEST
,
2440 wxT("Test '%s' for mime type '%s' succeeded."),
2441 rhs
.c_str(), data
.type
.c_str());
2446 wxLogTrace(TRACE_MIME_TEST
,
2447 wxT("Test '%s' for mime type '%s' failed, skipping."),
2448 rhs
.c_str(), data
.type
.c_str());
2450 data
.testfailed
= true;
2453 else if ( lhs
== wxT("desc") )
2457 else if ( lhs
== wxT("x11-bitmap") )
2461 else if ( lhs
== wxT("notes") )
2465 else // not a (recognized) special case, must be a verb (e.g. "print")
2467 data
.verbs
.Add(lhs
);
2468 data
.commands
.Add(rhs
);
2471 else // '=' not found
2473 // so it must be a simple flag
2474 if ( curField
== wxT("needsterminal") )
2476 data
.needsterminal
= true;
2478 else if ( curField
== wxT("copiousoutput"))
2480 // copiousoutput impies that the viewer is a console program
2481 data
.needsterminal
=
2482 data
.copiousoutput
= true;
2484 else if ( !IsKnownUnimportantField(curField
) )
2493 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString
& strFileName
,
2496 wxLogTrace(TRACE_MIME
, wxT("--- Parsing mailcap file '%s' ---"),
2497 strFileName
.c_str());
2499 wxTextFile
file(strFileName
);
2500 #if defined(__WXGTK20__) && wxUSE_UNICODE
2501 if ( !file
.Open( wxConvUTF8
) )
2507 // indices of MIME types (in m_aTypes) we already found in this file
2509 // (see the comments near the end of function for the reason we need this)
2510 wxArrayInt aIndicesSeenHere
;
2512 // accumulator for the current field
2514 curField
.reserve(1024);
2516 size_t nLineCount
= file
.GetLineCount();
2517 for ( size_t nLine
= 0; nLine
< nLineCount
; nLine
++ )
2519 // now we're at the start of the line
2520 const wxChar
*pc
= file
[nLine
].c_str();
2523 while ( wxIsspace(*pc
) )
2526 // comment or empty string?
2527 if ( *pc
== wxT('#') || *pc
== wxT('\0') )
2533 // what field are we currently in? The first 2 are fixed and there may
2534 // be an arbitrary number of other fields parsed by
2535 // ProcessOtherMailcapField()
2537 // the first field is the MIME type
2543 } currentToken
= Field_Type
;
2545 // the flags and field values on the current line
2546 MailcapLineData data
;
2554 // interpret the next character literally (notice that
2555 // backslash can be used for line continuation)
2556 if ( *++pc
== wxT('\0') )
2558 // fetch the next line if there is one
2559 if ( nLine
== nLineCount
- 1 )
2561 // something is wrong, bail out
2564 wxLogDebug(wxT("Mailcap file %s, line %lu: '\\' on the end of the last line ignored."),
2565 strFileName
.c_str(),
2566 (unsigned long)nLine
+ 1);
2570 // pass to the beginning of the next line
2571 pc
= file
[++nLine
].c_str();
2573 // skip pc++ at the end of the loop
2579 // just a normal character
2585 cont
= false; // end of line reached, exit the loop
2587 // fall through to still process this field
2590 // trim whitespaces from both sides
2591 curField
.Trim(true).Trim(false);
2593 switch ( currentToken
)
2596 data
.type
= curField
.Lower();
2597 if ( data
.type
.empty() )
2599 // I don't think that this is a valid mailcap
2600 // entry, but try to interpret it somehow
2601 data
.type
= _T('*');
2604 if ( data
.type
.Find(wxT('/')) == wxNOT_FOUND
)
2606 // we interpret "type" as "type/*"
2607 data
.type
+= wxT("/*");
2610 currentToken
= Field_OpenCmd
;
2614 data
.cmdOpen
= curField
;
2616 currentToken
= Field_Other
;
2620 if ( !ProcessOtherMailcapField(data
, curField
) )
2622 // don't flood the user with error messages if
2623 // we don't understand something in his
2624 // mailcap, but give them in debug mode because
2625 // this might be useful for the programmer
2628 wxT("Mailcap file %s, line %lu: unknown field '%s' for the MIME type '%s' ignored."),
2629 strFileName
.c_str(),
2630 (unsigned long)nLine
+ 1,
2635 else if ( data
.testfailed
)
2637 // skip this entry entirely
2641 // it already has this value
2642 //currentToken = Field_Other;
2646 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2649 // next token starts immediately after ';'
2657 // continue in the same line
2661 // we read the entire entry, check what have we got
2662 // ------------------------------------------------
2664 // check that we really read something reasonable
2665 if ( currentToken
< Field_Other
)
2667 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry ignored."),
2668 strFileName
.c_str(), nLine
+ 1);
2673 // if the test command failed, it's as if the entry were not there at
2675 if ( data
.testfailed
)
2680 // support for flags:
2681 // 1. create an xterm for 'needsterminal'
2682 // 2. append "| $PAGER" for 'copiousoutput'
2684 // Note that the RFC says that having both needsterminal and
2685 // copiousoutput is probably a mistake, so it seems that running
2686 // programs with copiousoutput inside an xterm as it is done now
2687 // is a bad idea (FIXME)
2688 if ( data
.copiousoutput
)
2690 const wxChar
*p
= wxGetenv(_T("PAGER"));
2691 data
.cmdOpen
<< _T(" | ") << (p
? p
: _T("more"));
2694 if ( data
.needsterminal
)
2696 data
.cmdOpen
= wxString::Format(_T("xterm -e sh -c '%s'"),
2697 data
.cmdOpen
.c_str());
2700 if ( !data
.cmdOpen
.empty() )
2702 data
.verbs
.Insert(_T("open"), 0);
2703 data
.commands
.Insert(data
.cmdOpen
, 0);
2706 // we have to decide whether the new entry should replace any entries
2707 // for the same MIME type we had previously found or not
2710 // the fall back entries have the lowest priority, by definition
2717 // have we seen this one before?
2718 int nIndex
= m_aTypes
.Index(data
.type
);
2720 // and if we have, was it in this file? if not, we should
2721 // overwrite the previously seen one
2722 overwrite
= nIndex
== wxNOT_FOUND
||
2723 aIndicesSeenHere
.Index(nIndex
) == wxNOT_FOUND
;
2726 wxLogTrace(TRACE_MIME
, _T("mailcap %s: %s [%s]"),
2727 data
.type
.c_str(), data
.cmdOpen
.c_str(),
2728 overwrite
? _T("replace") : _T("add"));
2730 int n
= AddToMimeData
2734 new wxMimeTypeCommands(data
.verbs
, data
.commands
),
2735 wxArrayString() /* extensions */,
2742 aIndicesSeenHere
.Add(n
);
2749 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
2756 size_t count
= m_aTypes
.GetCount();
2757 for ( size_t n
= 0; n
< count
; n
++ )
2759 // don't return template types from here (i.e. anything containg '*')
2761 if ( type
.Find(_T('*')) == wxNOT_FOUND
)
2763 mimetypes
.Add(type
);
2767 return mimetypes
.GetCount();
2770 // ----------------------------------------------------------------------------
2771 // writing to MIME type files
2772 // ----------------------------------------------------------------------------
2774 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
2776 wxArrayString sMimeTypes
;
2777 ft
->GetMimeTypes (sMimeTypes
);
2781 for (i
= 0; i
< sMimeTypes
.GetCount(); i
++)
2783 sMime
= sMimeTypes
.Item(i
);
2784 int nIndex
= m_aTypes
.Index (sMime
);
2785 if ( nIndex
== wxNOT_FOUND
)
2787 // error if we get here ??
2792 WriteMimeInfo(nIndex
, true );
2793 m_aTypes
.RemoveAt(nIndex
);
2794 m_aEntries
.RemoveAt(nIndex
);
2795 m_aExtensions
.RemoveAt(nIndex
);
2796 m_aDescriptions
.RemoveAt(nIndex
);
2797 m_aIcons
.RemoveAt(nIndex
);
2800 // check data integrity
2801 wxASSERT( m_aTypes
.Count() == m_aEntries
.Count() &&
2802 m_aTypes
.Count() == m_aExtensions
.Count() &&
2803 m_aTypes
.Count() == m_aIcons
.Count() &&
2804 m_aTypes
.Count() == m_aDescriptions
.Count() );
2809 // ----------------------------------------------------------------------------
2810 // private functions
2811 // ----------------------------------------------------------------------------
2813 static bool IsKnownUnimportantField(const wxString
& fieldAll
)
2815 static const wxChar
*knownFields
[] =
2817 _T("x-mozilla-flags"),
2819 _T("textualnewlines"),
2822 wxString field
= fieldAll
.BeforeFirst(_T('='));
2823 for ( size_t n
= 0; n
< WXSIZEOF(knownFields
); n
++ )
2825 if ( field
.CmpNoCase(knownFields
[n
]) == 0 )
2833 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE