]> git.saurik.com Git - wxWidgets.git/blame - src/unix/mimetype.cpp
don't assert when creating an initially empty wxCB_READONLY combobox
[wxWidgets.git] / src / unix / mimetype.cpp
CommitLineData
b13d92d1 1/////////////////////////////////////////////////////////////////////////////
7dc3cc31 2// Name: unix/mimetype.cpp
b13d92d1
VZ
3// Purpose: classes and functions to manage MIME types
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 23.09.98
7// RCS-ID: $Id$
8// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
6aa89a22 9// Licence: wxWindows licence (part of wxExtra library)
b13d92d1
VZ
10/////////////////////////////////////////////////////////////////////////////
11
2b813b73
VZ
12// known bugs; there may be others!! chris elliott, biol75@york.ac.uk 27 Mar 01
13
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
678ebfcd
VZ
28// 9) KDE does not yet handle multiple actions; Netscape mode never will
29
30/*
31 TODO: this file is a mess, we need to split it and reformet/review
32 everything (VZ)
33 */
2b813b73 34
f6bcfd97
BP
35// ============================================================================
36// declarations
37// ============================================================================
38
39// ----------------------------------------------------------------------------
40// headers
41// ----------------------------------------------------------------------------
42
14f355c2 43#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
f6bcfd97 44 #pragma implementation "mimetype.h"
b13d92d1
VZ
45#endif
46
b13d92d1
VZ
47// for compilers that support precompilation, includes "wx.h".
48#include "wx/wxprec.h"
49
50#ifdef __BORLANDC__
ce4169a4 51 #pragma hdrstop
b13d92d1
VZ
52#endif
53
b13d92d1 54#ifndef WX_PRECOMP
ce4169a4
RR
55 #include "wx/defs.h"
56#endif
57
b79e32cc 58#if wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE
ce4169a4
RR
59
60#ifndef WX_PRECOMP
61 #include "wx/string.h"
b13d92d1
VZ
62#endif //WX_PRECOMP
63
3d05544e 64
b13d92d1 65#include "wx/log.h"
ce4169a4 66#include "wx/file.h"
b13d92d1
VZ
67#include "wx/intl.h"
68#include "wx/dynarray.h"
2432b92d 69#include "wx/confbase.h"
b13d92d1 70
7dc3cc31
VS
71#include "wx/ffile.h"
72#include "wx/textfile.h"
73#include "wx/dir.h"
74#include "wx/utils.h"
75#include "wx/tokenzr.h"
c41dbc20 76#include "wx/iconloc.h"
b13d92d1 77
7dc3cc31 78#include "wx/unix/mimetype.h"
b13d92d1
VZ
79
80// other standard headers
81#include <ctype.h>
82
2900bd1c
JJ
83#ifdef __VMS
84/* silence warnings for comparing unsigned int's <0 */
85# pragma message disable unscomzer
86#endif
87
678ebfcd
VZ
88// wxMimeTypeCommands stores the verbs defined for the given MIME type with
89// their values
90class wxMimeTypeCommands
2b813b73
VZ
91{
92public:
678ebfcd
VZ
93 wxMimeTypeCommands() { }
94
95 wxMimeTypeCommands(const wxArrayString& verbs,
96 const wxArrayString& commands)
97 : m_verbs(verbs),
98 m_commands(commands)
2b813b73 99 {
2b813b73
VZ
100 }
101
678ebfcd
VZ
102 // add a new verb with the command or replace the old value
103 void AddOrReplaceVerb(const wxString& verb, const wxString& cmd)
2b813b73 104 {
678ebfcd
VZ
105 int n = m_verbs.Index(verb, FALSE /* ignore case */);
106 if ( n == wxNOT_FOUND )
2b813b73 107 {
678ebfcd
VZ
108 m_verbs.Add(verb);
109 m_commands.Add(cmd);
110 }
111 else
112 {
113 m_commands[n] = cmd;
2b813b73 114 }
2b813b73
VZ
115 }
116
678ebfcd 117 void Add(const wxString& s)
2b813b73 118 {
678ebfcd
VZ
119 m_verbs.Add(s.BeforeFirst(_T('=')));
120 m_commands.Add(s.AfterFirst(_T('=')));
2b813b73
VZ
121 }
122
678ebfcd
VZ
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]; }
127
128 bool HasVerb(const wxString& verb) const
129 { return m_verbs.Index(verb) != wxNOT_FOUND; }
130
131 wxString GetCommandForVerb(const wxString& verb, size_t *idx = NULL) const
2b813b73 132 {
678ebfcd
VZ
133 wxString s;
134
135 int n = m_verbs.Index(verb);
136 if ( n != wxNOT_FOUND )
137 {
138 s = m_commands[(size_t)n];
139 if ( idx )
140 *idx = n;
141 }
142
143 return s;
2b813b73
VZ
144 }
145
678ebfcd
VZ
146 // get a "verb=command" string
147 wxString GetVerbCmd(size_t n) const
2b813b73 148 {
678ebfcd 149 return m_verbs[n] + _T('=') + m_commands[n];
2b813b73 150 }
678ebfcd
VZ
151
152private:
153 wxArrayString m_verbs,
154 m_commands;
2b813b73
VZ
155};
156
678ebfcd
VZ
157// this class extends wxTextFile
158//
159// VZ: ???
2b813b73
VZ
160class wxMimeTextFile : public wxTextFile
161{
162public:
163 // constructors
164 wxMimeTextFile () : wxTextFile () {};
165 wxMimeTextFile (const wxString& strFile) : wxTextFile (strFile) { };
166
167 int pIndexOf(const wxString & sSearch, bool bIncludeComments = FALSE, int iStart = 0)
168 {
169 size_t i = iStart;
170 int nResult = wxNOT_FOUND;
171 if (i>=GetLineCount()) return wxNOT_FOUND;
172
173 wxString sTest = sSearch;
174 sTest.MakeLower();
175 wxString sLine;
176
177 if (bIncludeComments)
178 {
179 while ( (i < GetLineCount()) )
180 {
181 sLine = GetLine (i);
182 sLine.MakeLower();
183 if (sLine.Contains(sTest)) nResult = (int) i;
184 i++;
185 }
186 }
187 else
188 {
189 while ( (i < GetLineCount()) )
190 {
191 sLine = GetLine (i);
192 sLine.MakeLower();
193 if ( ! sLine.StartsWith(wxT("#")))
194 {
195 if (sLine.Contains(sTest)) nResult = (int) i;
196 }
197 i++;
198 }
199 }
200 return nResult;
201 }
202
203 bool CommentLine(int nIndex)
204 {
205 if (nIndex <0) return FALSE;
206 if (nIndex >= (int)GetLineCount() ) return FALSE;
207 GetLine(nIndex) = GetLine(nIndex).Prepend(wxT("#"));
208 return TRUE;
209 }
210
211 bool CommentLine(const wxString & sTest)
212 {
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("#"));
217 return TRUE;
218 }
219
220 wxString GetVerb (size_t i)
221 {
2b813b73
VZ
222 if (i > GetLineCount() ) return wxEmptyString;
223 wxString sTmp = GetLine(i).BeforeFirst(wxT('='));
224 return sTmp;
225 }
226
227 wxString GetCmd (size_t i)
228 {
2b813b73
VZ
229 if (i > GetLineCount() ) return wxEmptyString;
230 wxString sTmp = GetLine(i).AfterFirst(wxT('='));
231 return sTmp;
232 }
233};
234
b12915c1
VZ
235// in case we're compiling in non-GUI mode
236class WXDLLEXPORT wxIcon;
237
f6bcfd97
BP
238// ----------------------------------------------------------------------------
239// constants
240// ----------------------------------------------------------------------------
241
242// MIME code tracing mask
243#define TRACE_MIME _T("mime")
244
678ebfcd
VZ
245// give trace messages about the results of mailcap tests
246#define TRACE_MIME_TEST _T("mimetest")
247
f6bcfd97
BP
248// ----------------------------------------------------------------------------
249// private functions
250// ----------------------------------------------------------------------------
251
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
254// test for them
255static bool IsKnownUnimportantField(const wxString& field);
256
b13d92d1
VZ
257// ----------------------------------------------------------------------------
258// private classes
259// ----------------------------------------------------------------------------
260
2b813b73 261
a6c65e88 262// This class uses both mailcap and mime.types to gather information about file
b13d92d1
VZ
263// types.
264//
a6c65e88
VZ
265// The information about mailcap file was extracted from metamail(1) sources
266// and documentation and subsequently revised when I found the RFC 1524
267// describing it.
b13d92d1
VZ
268//
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).
273//
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
277// is standard.
278//
279// The second field is always the command to run. It is subject to
280// parameter/filename expansion described below.
281//
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
290// exit code.
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
a6c65e88
VZ
294// * needsterminal means that a new interactive console must be created for
295// the viewer
b13d92d1
VZ
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
299// mechanism.
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).
303//
a6c65e88 304// Parameter/filename expansion:
b13d92d1
VZ
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.
312//
b13d92d1
VZ
313//
314// There are 2 possible formats for mime.types file, one entry per line (used
a6c65e88
VZ
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
317// Netscape format).
b13d92d1
VZ
318//
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>
ec4768ef 323// b) for "expanded" format:
1457c903
VZ
324// type=<mime type> BACKSLASH
325// desc="<description>" BACKSLASH
a6c65e88 326// exts="<comma separated list of extensions>"
b13d92d1 327//
1457c903
VZ
328// (where BACKSLASH is a literal '\\' which we can't put here because cpp
329// misinterprets it)
330//
b13d92d1
VZ
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.
333
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.
b9517a0a
VZ
337
338// ----------------------------------------------------------------------------
2b813b73 339// wxGNOME
b9517a0a
VZ
340// ----------------------------------------------------------------------------
341
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
345//
346// The format of xxx.keys file is the following:
347//
348// mimetype/subtype:
349// field=value
350//
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.
afaee315
VZ
354//
355// Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
356// just before the field name.
b9517a0a 357
b9517a0a 358
2b813b73 359bool wxMimeTypesManagerImpl::CheckGnomeDirsExist ()
678ebfcd 360{
2b813b73
VZ
361 wxString gnomedir;
362 wxGetHomeDir( &gnomedir );
363 wxString sTmp = gnomedir;
2b5f62a0 364 sTmp = sTmp + wxT("/.gnome");
2b813b73 365 if (! wxDir::Exists ( sTmp ) )
678ebfcd 366 {
2b813b73 367 if (!wxMkdir ( sTmp ))
678ebfcd 368 {
2b5f62a0 369 wxLogError(_("Failed to create directory %s/.gnome."), sTmp.c_str());
2b813b73 370 return FALSE;
b9517a0a 371 }
678ebfcd 372 }
2b5f62a0 373 sTmp = sTmp + wxT("/mime-info");
2b813b73 374 if (! wxDir::Exists ( sTmp ) )
678ebfcd 375 {
2b813b73
VZ
376 if (!wxMkdir ( sTmp ))
377 {
2b5f62a0 378 wxLogError(_("Failed to create directory %s/mime-info."), sTmp.c_str());
2b813b73 379 return FALSE;
b9517a0a 380 }
2b813b73
VZ
381 }
382 return TRUE;
b9517a0a 383
2b813b73
VZ
384}
385
386
387
388bool wxMimeTypesManagerImpl::WriteGnomeKeyFile(int index, bool delete_index)
678ebfcd 389{
2b813b73
VZ
390 wxString gnomedir;
391 wxGetHomeDir( &gnomedir );
392
2b5f62a0 393 wxMimeTextFile outfile ( gnomedir + wxT("/.gnome/mime-info/user.keys"));
2b813b73
VZ
394 // if this fails probably Gnome is not installed ??
395 // create it anyway as a private mime store
396
2b5f62a0
VZ
397#if defined(__WXGTK20__) && wxUSE_UNICODE
398 if (! outfile.Open ( wxConvUTF8) )
399#else
2b813b73 400 if (! outfile.Open () )
2b5f62a0 401#endif
2b813b73
VZ
402 {
403 if (delete_index) return FALSE;
404 if (!CheckGnomeDirsExist() ) return FALSE;
405 outfile.Create ();
406 }
407
408 wxString sTmp, strType = m_aTypes[index];
409 int nIndex = outfile.pIndexOf(strType);
410 if ( nIndex == wxNOT_FOUND )
678ebfcd 411 {
2b813b73
VZ
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");
678ebfcd
VZ
416 wxMimeTypeCommands * entries = m_aEntries[index];
417 size_t count = entries->GetCount();
418 for ( size_t i = 0; i < count; i++ )
419 {
420 sTmp = entries->GetVerbCmd(i);
2b813b73
VZ
421 sTmp.Replace( wxT("%s"), wxT("%f") );
422 sTmp = wxT ( "\t") + sTmp;
423 outfile.AddLine ( sTmp );
678ebfcd 424 }
2b813b73
VZ
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] );
678ebfcd
VZ
428 }
429 else
430 {
431 if (delete_index)
432 outfile.CommentLine(nIndex);
433
434 wxMimeTypeCommands sOld;
2b813b73
VZ
435 size_t nOld = nIndex + 1;
436 bool oldEntryEnd = FALSE;
437 while ( (nOld < outfile.GetLineCount() )&& (oldEntryEnd == FALSE ))
678ebfcd 438 {
2b813b73
VZ
439 sTmp = outfile.GetLine(nOld);
440 if ( (sTmp[0u] == wxT('\t')) || (sTmp[0u] == wxT('#')) )
678ebfcd 441 {
2b813b73
VZ
442 // we have another line to deal with
443 outfile.CommentLine(nOld);
444 nOld ++;
445 // add the line to our store
678ebfcd
VZ
446 if ((!delete_index) && (sTmp[0u] == wxT('\t')))
447 sOld.Add(sTmp);
b9517a0a 448 }
678ebfcd
VZ
449 // next mimetpye ??or blank line
450 else
451 oldEntryEnd = TRUE;
452 }
2b813b73
VZ
453 // list of entries in our data; these should all be in sOld,
454 // though sOld may also contain other entries , eg flags
455 if (!delete_index)
678ebfcd
VZ
456 {
457 wxMimeTypeCommands * entries = m_aEntries[index];
2b813b73
VZ
458 size_t i;
459 for (i=0; i < entries->GetCount(); i++)
678ebfcd 460 {
2b813b73 461 // replace any entries in sold that match verbs we know
678ebfcd 462 sOld.AddOrReplaceVerb ( entries->GetVerb(i), entries->GetCmd (i) );
b9517a0a 463 }
2b813b73 464 //sOld should also contain the icon
678ebfcd 465 if ( !m_aIcons[index].empty() )
2b5f62a0 466 sOld.AddOrReplaceVerb ( wxT("icon-filename"), m_aIcons[index] );
b9517a0a 467
2b813b73 468 for (i=0; i < sOld.GetCount(); i++)
678ebfcd
VZ
469 {
470 sTmp = sOld.GetVerbCmd(i);
2b813b73 471 sTmp.Replace( wxT("%s"), wxT("%f") );
2b5f62a0 472 sTmp = wxT("\t") + sTmp;
2b813b73
VZ
473 nIndex ++;
474 outfile.InsertLine ( sTmp, nIndex );
2b813b73
VZ
475 }
476 }
678ebfcd 477 }
2b813b73
VZ
478 bool bTmp = outfile.Write ();
479 return bTmp;
678ebfcd 480}
b9517a0a 481
b9517a0a 482
2b813b73 483bool wxMimeTypesManagerImpl::WriteGnomeMimeFile(int index, bool delete_index)
678ebfcd 484{
2b813b73
VZ
485 wxString gnomedir;
486 wxGetHomeDir( &gnomedir );
afaee315 487
2b5f62a0 488 wxMimeTextFile outfile ( gnomedir + wxT("/.gnome/mime-info/user.mime"));
2b813b73
VZ
489 // if this fails probably Gnome is not installed ??
490 // create it anyway as a private mime store
491 if (! outfile.Open () )
492 {
493 if (delete_index) return FALSE;
494 if (!CheckGnomeDirsExist() ) return FALSE;
495 outfile.Create ();
496 }
497 wxString strType = m_aTypes[index];
498 int nIndex = outfile.pIndexOf(strType);
499 if ( nIndex == wxNOT_FOUND )
678ebfcd 500 {
2b813b73 501 outfile.AddLine ( strType );
2b5f62a0 502 outfile.AddLine ( wxT("\text:") + m_aExtensions.Item(index) );
678ebfcd 503 }
2b813b73 504 else
678ebfcd 505 {
2b813b73 506 if (delete_index)
678ebfcd 507 {
2b813b73
VZ
508 outfile.CommentLine(nIndex);
509 outfile.CommentLine(nIndex+1);
b9517a0a
VZ
510 }
511 else
678ebfcd 512 {// check for next line being the right one to replace ??
2b813b73 513 wxString sOld = outfile.GetLine(nIndex+1);
2b5f62a0 514 if (sOld.Contains( wxT("\text: ")))
678ebfcd 515 {
2b5f62a0 516 outfile.GetLine(nIndex+1) = wxT("\text: ") + m_aExtensions.Item(index);
678ebfcd 517 }
2b813b73 518 else
b9517a0a 519 {
2b5f62a0 520 outfile.InsertLine( wxT("\text: ") + m_aExtensions.Item(index), nIndex + 1 );
b9517a0a 521 }
4d2976ad
VS
522 }
523 }
2b813b73
VZ
524 bool bTmp = outfile.Write ();
525 return bTmp;
4d2976ad
VS
526}
527
2b813b73 528
25d599ae
VS
529void wxMimeTypesManagerImpl::LoadGnomeDataFromKeyFile(const wxString& filename,
530 const wxArrayString& dirs)
4d2976ad 531{
2b813b73 532 wxTextFile textfile(filename);
2b5f62a0
VZ
533#if defined(__WXGTK20__) && wxUSE_UNICODE
534 if ( !textfile.Open( wxConvUTF8) )
535#else
2b813b73 536 if ( !textfile.Open() )
2b5f62a0 537#endif
2b813b73
VZ
538 return;
539 wxLogTrace(TRACE_MIME, wxT("--- Opened Gnome file %s ---"),
678ebfcd 540 filename.c_str());
4d2976ad 541
2b813b73
VZ
542 // values for the entry being parsed
543 wxString curMimeType, curIconFile;
678ebfcd 544 wxMimeTypeCommands * entry = new wxMimeTypeCommands;
4d2976ad 545
2b813b73
VZ
546 // these are always empty in this file
547 wxArrayString strExtensions;
548 wxString strDesc;
4d2976ad 549
2b813b73
VZ
550 const wxChar *pc;
551 size_t nLineCount = textfile.GetLineCount();
552 size_t nLine = 0;
553 while ( nLine < nLineCount)
678ebfcd 554 {
2b813b73
VZ
555 pc = textfile[nLine].c_str();
556 if ( *pc != _T('#') )
678ebfcd 557 {
4d2976ad 558
2b813b73 559 wxLogTrace(TRACE_MIME, wxT("--- Reading from Gnome file %s '%s' ---"),
678ebfcd 560 filename.c_str(),pc);
4d2976ad 561
2b813b73
VZ
562 wxString sTmp(pc);
563 if (sTmp.Contains(wxT("=")) )
564 {
25d599ae 565 // GNOME 1:
678ebfcd 566 if (sTmp.Contains( wxT("icon-filename=") ) )
2b813b73 567 {
678ebfcd 568 curIconFile = sTmp.AfterFirst(wxT('='));
2b813b73 569 }
25d599ae
VS
570 // GNOME 2:
571 else if (sTmp.Contains( wxT("icon_filename=") ) )
572 {
573 curIconFile = sTmp.AfterFirst(wxT('='));
574 if (!wxFileExists(curIconFile))
575 {
576 size_t nDirs = dirs.GetCount();
577 for (size_t nDir = 0; nDir < nDirs; nDir++)
578 {
579 wxString newFile;
580 newFile.Printf(wxT("%s/pixmaps/document-icons/%s.png"),
581 dirs[nDir].c_str(),
582 curIconFile.c_str());
583 if (wxFileExists(newFile))
584 curIconFile = newFile;
585 }
586 }
587 }
678ebfcd
VZ
588 else //: some other field,
589 {
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
595
596 // \topen=xdvi %f
597 // \tview=xdvi %f
598 // \topen.convert.Convert file to Postscript=dvips %f -o `basename %f .dvi`.ps
599
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");
605 entry->Add(sTmp);
4d2976ad 606
2b813b73
VZ
607 }
608
609 } // emd of has an equals sign
610 else
678ebfcd 611 {
2b813b73
VZ
612 // not a comment and not an equals sign
613 if (sTmp.Contains(wxT('/')))
678ebfcd 614 {
2b813b73
VZ
615 // this is the start of the new mimetype
616 // overwrite any existing data
678ebfcd
VZ
617 if (! curMimeType.empty())
618 {
2b813b73
VZ
619 AddToMimeData ( curMimeType, curIconFile, entry, strExtensions, strDesc);
620
621 // now get ready for next bit
678ebfcd 622 entry = new wxMimeTypeCommands;
2b813b73 623 }
678ebfcd
VZ
624 curMimeType = sTmp.BeforeFirst(wxT(':'));
625 }
626 }
2b813b73 627 } // end of not a comment
678ebfcd
VZ
628 // ignore blank lines
629 nLine ++;
2b813b73 630 } // end of while, save any data
678ebfcd
VZ
631 if (! curMimeType.empty())
632 {
2b813b73 633 AddToMimeData ( curMimeType, curIconFile, entry, strExtensions, strDesc);
678ebfcd 634 }
2b813b73 635
4d2976ad
VS
636}
637
638
2b813b73
VZ
639
640void wxMimeTypesManagerImpl::LoadGnomeMimeTypesFromMimeFile(const wxString& filename)
4d2976ad
VS
641{
642 wxTextFile textfile(filename);
643 if ( !textfile.Open() )
644 return;
2b6d8c00
VZ
645
646 wxLogTrace(TRACE_MIME,
647 wxT("--- Opened Gnome file %s ---"),
648 filename.c_str());
4d2976ad
VS
649
650 // values for the entry being parsed
651 wxString curMimeType, curExtList;
652
653 const wxChar *pc;
654 size_t nLineCount = textfile.GetLineCount();
678ebfcd 655 for ( size_t nLine = 0;; nLine++ )
4d2976ad
VS
656 {
657 if ( nLine < nLineCount )
658 {
659 pc = textfile[nLine].c_str();
2b5f62a0 660 if ( *pc == wxT('#') )
4d2976ad
VS
661 {
662 // skip comments
663 continue;
664 }
665 }
666 else
667 {
668 // so that we will fall into the "if" below
669 pc = NULL;
670 }
b9517a0a 671
4d2976ad
VS
672 if ( !pc || !*pc )
673 {
674 // end of the entry
675 if ( !!curMimeType && !!curExtList )
b9517a0a 676 {
2b6d8c00
VZ
677 wxLogTrace(TRACE_MIME,
678 wxT("--- At end of Gnome file finding mimetype %s ---"),
679 curMimeType.c_str());
2b813b73
VZ
680
681 AddMimeTypeInfo(curMimeType, curExtList, wxEmptyString);
4d2976ad 682 }
b9517a0a 683
4d2976ad
VS
684 if ( !pc )
685 {
686 // the end - this can only happen if nLine == nLineCount
b9517a0a
VZ
687 break;
688 }
4d2976ad
VS
689
690 curExtList.Empty();
691
692 continue;
693 }
694
695 // what do we have here?
2b5f62a0 696 if ( *pc == wxT('\t') )
4d2976ad
VS
697 {
698 // this is a field=value ling
699 pc++; // skip leading TAB
700
2b6d8c00
VZ
701 static const int lenField = 5; // strlen("ext: ")
702 if ( wxStrncmp(pc, wxT("ext: "), lenField) == 0 )
4d2976ad 703 {
2b6d8c00
VZ
704 // skip it and take everything left until the end of line
705 curExtList = pc + lenField;
4d2976ad
VS
706 }
707 //else: some other field, we don't care
708 }
709 else
710 {
711 // this is the start of the new section
2b6d8c00
VZ
712 wxLogTrace(TRACE_MIME,
713 wxT("--- In Gnome file finding mimetype %s ---"),
714 curMimeType.c_str());
2b813b73 715
678ebfcd
VZ
716 if (! curMimeType.empty())
717 AddMimeTypeInfo(curMimeType, curExtList, wxEmptyString);
2b813b73 718
4d2976ad
VS
719 curMimeType.Empty();
720
2b5f62a0 721 while ( *pc != wxT(':') && *pc != wxT('\0') )
4d2976ad
VS
722 {
723 curMimeType += *pc++;
724 }
b9517a0a
VZ
725 }
726 }
727}
728
4d2976ad 729
25d599ae
VS
730void wxMimeTypesManagerImpl::LoadGnomeMimeFilesFromDir(
731 const wxString& dirbase, const wxArrayString& dirs)
b9517a0a
VZ
732{
733 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
734 _T("base directory shouldn't end with a slash") );
735
736 wxString dirname = dirbase;
2b5f62a0 737 dirname << wxT("/mime-info");
b9517a0a
VZ
738
739 if ( !wxDir::Exists(dirname) )
740 return;
741
742 wxDir dir(dirname);
743 if ( !dir.IsOpened() )
744 return;
745
746 // we will concatenate it with filename to get the full path below
2b5f62a0 747 dirname += wxT('/');
b9517a0a
VZ
748
749 wxString filename;
4d2976ad 750 bool cont = dir.GetFirst(&filename, _T("*.mime"), wxDIR_FILES);
b9517a0a
VZ
751 while ( cont )
752 {
2b813b73 753 LoadGnomeMimeTypesFromMimeFile(dirname + filename);
b9517a0a
VZ
754
755 cont = dir.GetNext(&filename);
756 }
fb5ddb4c 757
2b813b73
VZ
758 cont = dir.GetFirst(&filename, _T("*.keys"), wxDIR_FILES);
759 while ( cont )
b9517a0a 760 {
25d599ae 761 LoadGnomeDataFromKeyFile(dirname + filename, dirs);
b9517a0a 762
2b813b73
VZ
763 cont = dir.GetNext(&filename);
764 }
b9517a0a
VZ
765}
766
4d2976ad 767
2b813b73
VZ
768
769
770void wxMimeTypesManagerImpl::GetGnomeMimeInfo(const wxString& sExtraDir)
4d2976ad 771{
4d2976ad 772 wxArrayString dirs;
2b5f62a0
VZ
773 dirs.Add(wxT("/usr/share"));
774 dirs.Add(wxT("/usr/local/share"));
4d2976ad
VS
775
776 wxString gnomedir;
777 wxGetHomeDir( &gnomedir );
2b5f62a0 778 gnomedir += wxT("/.gnome");
4d2976ad 779 dirs.Add( gnomedir );
678ebfcd 780 if (!sExtraDir.empty()) dirs.Add( sExtraDir );
4d2976ad
VS
781
782 size_t nDirs = dirs.GetCount();
783 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
784 {
25d599ae 785 LoadGnomeMimeFilesFromDir(dirs[nDir], dirs);
4d2976ad
VS
786 }
787}
788
b9517a0a 789// ----------------------------------------------------------------------------
678ebfcd 790// KDE
b9517a0a
VZ
791// ----------------------------------------------------------------------------
792
678ebfcd 793
b9517a0a
VZ
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
796//
509a6196 797// 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
b9517a0a
VZ
798// 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
799//
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"
803
2b813b73
VZ
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??)
806
807bool wxMimeTypesManagerImpl::CheckKDEDirsExist ( const wxString & sOK, const wxString & sTest )
808
809 {
678ebfcd 810 if (sTest.empty())
2b813b73
VZ
811 {
812 if (wxDir::Exists(sOK)) return TRUE;
813 else return FALSE;
814 }
815 else
816 {
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);
821 }
822}
823
824bool wxMimeTypesManagerImpl::WriteKDEMimeFile(int index, bool delete_index)
825{
826 wxMimeTextFile appoutfile, mimeoutfile;
827 wxString sHome = wxGetHomeDir();
828 wxString sTmp = wxT(".kde/share/mimelnk/");
678ebfcd 829 wxString sMime = m_aTypes[index];
2b813b73
VZ
830 CheckKDEDirsExist (sHome, sTmp + sMime.BeforeFirst(wxT('/')) );
831 sTmp = sHome + wxT('/') + sTmp + sMime + wxT(".kdelnk");
832
833 bool bTemp;
834 bool bMimeExists = mimeoutfile.Open (sTmp);
835 if (!bMimeExists)
836 {
678ebfcd
VZ
837 bTemp = mimeoutfile.Create (sTmp);
838 // some unknown error eg out of disk space
839 if (!bTemp) return FALSE;
2b813b73
VZ
840 }
841
842 sTmp = wxT(".kde/share/applnk/");
843 CheckKDEDirsExist (sHome, sTmp + sMime.AfterFirst(wxT('/')) );
844 sTmp = sHome + wxT('/') + sTmp + sMime.AfterFirst(wxT('/')) + wxT(".kdelnk");
845
846 bool bAppExists;
847 bAppExists = appoutfile.Open (sTmp);
848 if (!bAppExists)
849 {
850 bTemp = appoutfile.Create (sTmp);
851 // some unknown error eg out of disk space
852 if (!bTemp) return FALSE;
853 }
854
855 // fixed data; write if new file
856 if (!bMimeExists)
857 {
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);
863 }
864
865 if (!bAppExists)
866 {
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(';'));
872 }
873
874 // variable data
875 // ignore locale
876 mimeoutfile.CommentLine(wxT("Comment="));
877 if (!delete_index)
878 mimeoutfile.AddLine(wxT("Comment=") + m_aDescriptions[index]);
879 appoutfile.CommentLine(wxT("Name="));
880 if (!delete_index)
881 appoutfile.AddLine(wxT("Comment=") + m_aDescriptions[index]);
882
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 );
890
891 sTmp = wxT(" ") + m_aExtensions[index];
892
893 wxStringTokenizer tokenizer(sTmp, _T(" "));
894 sTmp = wxT("Patterns=");
895 mimeoutfile.CommentLine(sTmp);
896 while ( tokenizer.HasMoreTokens() )
897 {
898 // holds an extension; need to change it to *.ext;
899 wxString e = wxT("*.") + tokenizer.GetNextToken() + wxT(";");
900 sTmp = sTmp + e;
678ebfcd 901 }
2b813b73
VZ
902 if (!delete_index) mimeoutfile.AddLine(sTmp);
903
678ebfcd 904 wxMimeTypeCommands * entries = m_aEntries[index];
2b813b73 905 // if we don't find open just have an empty string ... FIX this
678ebfcd 906 sTmp = entries->GetCommandForVerb(_T("open"));
2b813b73
VZ
907 sTmp.Replace( wxT("%s"), wxT("%f") );
908
909 mimeoutfile.CommentLine(wxT("DefaultApp=") );
910 if (!delete_index) mimeoutfile.AddLine(wxT("DefaultApp=") + sTmp);
911
912 sTmp.Replace( wxT("%f"), wxT("") );
913 appoutfile.CommentLine(wxT("Exec="));
914 if (!delete_index) appoutfile.AddLine(wxT("Exec=") + sTmp);
915
916 if (entries->GetCount() > 1)
678ebfcd
VZ
917 {
918 //other actions as well as open
2b813b73 919
678ebfcd 920 }
2b813b73
VZ
921 bTemp = FALSE;
922 if (mimeoutfile.Write ()) bTemp = TRUE;
923 mimeoutfile.Close ();
924 if (appoutfile.Write ()) bTemp = TRUE;
925 appoutfile.Close ();
926
927 return bTemp;
928
929
930}
931
932void wxMimeTypesManagerImpl::LoadKDELinksForMimeSubtype(const wxString& dirbase,
b9517a0a 933 const wxString& subdir,
cdf339c9
VS
934 const wxString& filename,
935 const wxArrayString& icondirs)
b9517a0a 936{
2b813b73
VZ
937 wxMimeTextFile file;
938 if ( !file.Open(dirbase + filename) ) return;
b9517a0a 939
25d599ae
VS
940 wxLogTrace(TRACE_MIME, wxT("loading KDE file %s"),
941 (dirbase+filename).c_str());
942
678ebfcd 943 wxMimeTypeCommands * entry = new wxMimeTypeCommands;
2b813b73
VZ
944 wxArrayString sExts;
945 wxString mimetype, mime_desc, strIcon;
946
2b5f62a0 947 int nIndex = file.pIndexOf( wxT("MimeType=") );
2b813b73 948 if (nIndex == wxNOT_FOUND)
678ebfcd
VZ
949 {
950 // construct mimetype from the directory name and the basename of the
951 // file (it always has .kdelnk extension)
2b5f62a0 952 mimetype << subdir << wxT('/') << filename.BeforeLast( wxT('.') );
678ebfcd 953 }
2b813b73 954 else mimetype = file.GetCmd (nIndex);
b9517a0a 955
276c7463
VZ
956 // first find the description string: it is the value in either "Comment="
957 // line or "Comment[<locale_name>]=" one
2b813b73 958 nIndex = wxNOT_FOUND;
276c7463
VZ
959
960 wxString comment;
961#if wxUSE_INTL
962 wxLocale *locale = wxGetLocale();
963 if ( locale )
964 {
965 // try "Comment[locale name]" first
966 comment << _T("Comment[") + locale->GetName() + _T("]=");
2b813b73 967 nIndex = file.pIndexOf(comment);
276c7463
VZ
968 }
969#endif // wxUSE_INTL
cdf339c9 970
2b813b73 971 if ( nIndex == wxNOT_FOUND )
276c7463
VZ
972 {
973 comment = _T("Comment=");
2b813b73 974 nIndex = file.pIndexOf(comment);
276c7463
VZ
975 }
976
2b813b73 977 if ( nIndex != wxNOT_FOUND ) mime_desc = file.GetCmd(nIndex);
276c7463 978 //else: no description
cdf339c9 979
276c7463
VZ
980 // next find the extensions
981 wxString mime_extension;
982
2b813b73
VZ
983 nIndex = file.pIndexOf(_T("Patterns="));
984 if ( nIndex != wxNOT_FOUND )
678ebfcd
VZ
985 {
986 wxString exts = file.GetCmd (nIndex);;
5bd3a2da 987
276c7463
VZ
988 wxStringTokenizer tokenizer(exts, _T(";"));
989 while ( tokenizer.HasMoreTokens() )
cdf339c9 990 {
276c7463
VZ
991 wxString e = tokenizer.GetNextToken();
992 if ( e.Left(2) != _T("*.") )
993 continue; // don't support too difficult patterns
994
995 if ( !mime_extension.empty() )
996 {
997 // separate from the previous ext
998 mime_extension << _T(' ');
999 }
1000
cdf339c9 1001 mime_extension << e.Mid(2);
cdf339c9 1002 }
cdf339c9 1003 }
2b813b73 1004 sExts.Add(mime_extension);
5bd3a2da 1005
cdf339c9
VS
1006
1007 // ok, now we can take care of icon:
1008
2b813b73
VZ
1009 nIndex = file.pIndexOf(_T("Icon="));
1010 if ( nIndex != wxNOT_FOUND )
b9517a0a 1011 {
2b813b73 1012 strIcon = file.GetCmd(nIndex);
25d599ae 1013 wxLogTrace(TRACE_MIME, wxT(" icon %s"), strIcon.c_str());
2b813b73
VZ
1014 //it could be the real path, but more often a short name
1015 if (!wxFileExists(strIcon))
678ebfcd 1016 {
2b813b73 1017 // icon is just the short name
678ebfcd 1018 if ( !strIcon.empty() )
cdf339c9 1019 {
678ebfcd
VZ
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))
1025 {
2b813b73 1026 strIcon.Prepend(icondirs[nDir]);
25d599ae 1027 wxLogTrace(TRACE_MIME, wxT(" iconfile %s"), strIcon.c_str());
678ebfcd
VZ
1028 break;
1029 }
2b813b73 1030 }
678ebfcd
VZ
1031 }
1032 }
2b813b73
VZ
1033 // now look for lines which know about the application
1034 // exec= or DefaultApp=
1035
1036 nIndex = file.pIndexOf(wxT("DefaultApp"));
b9517a0a 1037
2b813b73 1038 if ( nIndex == wxNOT_FOUND )
678ebfcd 1039 {
2b813b73
VZ
1040 // no entry try exec
1041 nIndex = file.pIndexOf(wxT("Exec"));
678ebfcd 1042 }
2b813b73
VZ
1043
1044 if ( nIndex != wxNOT_FOUND )
678ebfcd 1045 {
2b813b73
VZ
1046 wxString sTmp = file.GetCmd(nIndex);
1047 // we expect %f; others including %F and %U and %u are possible
678ebfcd
VZ
1048 if (0 == sTmp.Replace ( wxT("%f"), wxT("%s") ))
1049 sTmp = sTmp + wxT(" %s");
1050 entry->AddOrReplaceVerb (wxString(wxT("open")), sTmp );
b9517a0a 1051 }
2b813b73
VZ
1052
1053 AddToMimeData (mimetype, strIcon, entry, sExts, mime_desc);
b9517a0a
VZ
1054}
1055
2b813b73 1056void wxMimeTypesManagerImpl::LoadKDELinksForMimeType(const wxString& dirbase,
cdf339c9
VS
1057 const wxString& subdir,
1058 const wxArrayString& icondirs)
b9517a0a
VZ
1059{
1060 wxString dirname = dirbase;
1061 dirname += subdir;
1062 wxDir dir(dirname);
1063 if ( !dir.IsOpened() )
1064 return;
1065
25d599ae
VS
1066 wxLogTrace(TRACE_MIME, wxT("--- Loading from KDE directory %s ---"),
1067 dirname.c_str());
1068
b9517a0a
VZ
1069 dirname += _T('/');
1070
1071 wxString filename;
1072 bool cont = dir.GetFirst(&filename, _T("*.kdelnk"), wxDIR_FILES);
1073 while ( cont )
1074 {
2b813b73
VZ
1075 LoadKDELinksForMimeSubtype(dirname, subdir, filename, icondirs);
1076
1077 cont = dir.GetNext(&filename);
1078 }
1079 // new standard for Gnome and KDE
1080 cont = dir.GetFirst(&filename, _T("*.desktop"), wxDIR_FILES);
1081 while ( cont )
1082 {
1083 LoadKDELinksForMimeSubtype(dirname, subdir, filename, icondirs);
b9517a0a
VZ
1084
1085 cont = dir.GetNext(&filename);
1086 }
1087}
1088
2b813b73 1089void wxMimeTypesManagerImpl::LoadKDELinkFilesFromDir(const wxString& dirbase,
cdf339c9 1090 const wxArrayString& icondirs)
b9517a0a
VZ
1091{
1092 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
1093 _T("base directory shouldn't end with a slash") );
1094
1095 wxString dirname = dirbase;
1096 dirname << _T("/mimelnk");
1097
1098 if ( !wxDir::Exists(dirname) )
1099 return;
1100
1101 wxDir dir(dirname);
1102 if ( !dir.IsOpened() )
1103 return;
1104
1105 // we will concatenate it with dir name to get the full path below
1106 dirname += _T('/');
1107
1108 wxString subdir;
1109 bool cont = dir.GetFirst(&subdir, wxEmptyString, wxDIR_DIRS);
1110 while ( cont )
1111 {
2b813b73 1112 LoadKDELinksForMimeType(dirname, subdir, icondirs);
b9517a0a
VZ
1113
1114 cont = dir.GetNext(&subdir);
1115 }
1116}
1117
2b813b73 1118void wxMimeTypesManagerImpl::GetKDEMimeInfo(const wxString& sExtraDir)
b9517a0a
VZ
1119{
1120 wxArrayString dirs;
cdf339c9
VS
1121 wxArrayString icondirs;
1122
1123 // settings in ~/.kde have maximal priority
2b5f62a0
VZ
1124 dirs.Add(wxGetHomeDir() + wxT("/.kde/share"));
1125 icondirs.Add(wxGetHomeDir() + wxT("/.kde/share/icons/"));
509a6196
VZ
1126
1127 // the variable KDEDIR is set when KDE is running
2b5f62a0 1128 const wxChar *kdedir = wxGetenv( wxT("KDEDIR") );
509a6196
VZ
1129 if ( kdedir )
1130 {
2b5f62a0
VZ
1131 dirs.Add( wxString(kdedir) + wxT("/share") );
1132 icondirs.Add( wxString(kdedir) + wxT("/share/icons/") );
509a6196
VZ
1133 }
1134 else
1135 {
1136 // try to guess KDEDIR
1137 dirs.Add(_T("/usr/share"));
1138 dirs.Add(_T("/opt/kde/share"));
cdf339c9 1139 icondirs.Add(_T("/usr/share/icons/"));
13e3b45a 1140 icondirs.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
cdf339c9 1141 icondirs.Add(_T("/opt/kde/share/icons/"));
509a6196
VZ
1142 }
1143
678ebfcd 1144 if (!sExtraDir.empty()) dirs.Add (sExtraDir);
2b813b73
VZ
1145 icondirs.Add(sExtraDir + wxT("/icons"));
1146
b9517a0a
VZ
1147 size_t nDirs = dirs.GetCount();
1148 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1149 {
2b813b73 1150 LoadKDELinkFilesFromDir(dirs[nDir], icondirs);
b9517a0a 1151 }
b9517a0a
VZ
1152}
1153
2b813b73
VZ
1154// ----------------------------------------------------------------------------
1155// wxFileTypeImpl (Unix)
1156// ----------------------------------------------------------------------------
1157
2b813b73 1158wxString wxFileTypeImpl::GetExpandedCommand(const wxString & verb, const wxFileType::MessageParameters& params) const
b9517a0a 1159{
2b813b73
VZ
1160 wxString sTmp;
1161 size_t i = 0;
678ebfcd 1162 while ( (i < m_index.GetCount() ) && sTmp.empty() )
b9517a0a 1163 {
2b813b73
VZ
1164 sTmp = m_manager->GetCommand ( verb, m_index[i] );
1165 i ++;
b9517a0a
VZ
1166 }
1167
2b813b73
VZ
1168 return wxFileType::ExpandCommand(sTmp, params);
1169}
b9517a0a 1170
da0766ab 1171bool wxFileTypeImpl::GetIcon(wxIconLocation *iconLoc) const
2b813b73
VZ
1172
1173{
1174 wxString sTmp;
1175 size_t i = 0;
678ebfcd 1176 while ( (i < m_index.GetCount() ) && sTmp.empty() )
c786f763
VZ
1177 {
1178 sTmp = m_manager->m_aIcons[m_index[i]];
1179 i ++;
1180 }
da0766ab
VZ
1181 if ( sTmp.empty () )
1182 return FALSE;
b9517a0a 1183
da0766ab 1184 if ( iconLoc )
c786f763 1185 {
a49686b4 1186 iconLoc->SetFileName(sTmp);
2b813b73 1187 }
c786f763 1188
da0766ab 1189 return TRUE;
c786f763 1190}
2b813b73
VZ
1191
1192
1193bool
1194wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
1195{
1196 mimeTypes.Clear();
1197 for (size_t i = 0; i < m_index.GetCount(); i++)
1198 mimeTypes.Add(m_manager->m_aTypes[m_index[i]]);
1199 return TRUE;
1200}
1201
1202
1203size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
1204 wxArrayString *commands,
1205 const wxFileType::MessageParameters& params) const
1206{
1207
1208 wxString vrb, cmd, sTmp;
1209 size_t count = 0;
678ebfcd 1210 wxMimeTypeCommands * sPairs;
2b813b73
VZ
1211
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++)
1215 {
1216 // list of verb = command pairs for this mimetype
1217 sPairs = m_manager->m_aEntries [m_index[n]];
1218 size_t i;
678ebfcd 1219 for ( i = 0; i < sPairs->GetCount (); i++ )
2b813b73
VZ
1220 {
1221 vrb = sPairs->GetVerb(i);
1222 // some gnome entries have . inside
1223 vrb = vrb.AfterLast(wxT('.'));
1224 cmd = sPairs->GetCmd (i);
678ebfcd 1225 if (! cmd.empty() )
2b813b73
VZ
1226 {
1227 cmd = wxFileType::ExpandCommand(cmd, params);
1228 count ++;
1229 if ( vrb.IsSameAs (wxT("open")))
1230 {
1231 verbs->Insert(vrb,0u);
1232 commands ->Insert(cmd,0u);
1233 }
1234 else
1235 {
1236 verbs->Add (vrb);
1237 commands->Add (cmd);
1238 }
1239 }
1240
1241 }
1242
1243 }
1244 return count;
1245
1246}
1247
1248bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1249{
1250 wxString strExtensions = m_manager->GetExtension(m_index[0]);
1251 extensions.Empty();
1252
1253 // one extension in the space or comma delimitid list
1254 wxString strExt;
678ebfcd 1255 for ( const wxChar *p = strExtensions;; p++ ) {
2b813b73 1256 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
678ebfcd 1257 if ( !strExt.empty() ) {
2b813b73
VZ
1258 extensions.Add(strExt);
1259 strExt.Empty();
1260 }
1261 //else: repeated spaces (shouldn't happen, but it's not that
1262 // important if it does happen)
1263
1264 if ( *p == wxT('\0') )
1265 break;
1266 }
1267 else if ( *p == wxT('.') ) {
1268 // remove the dot from extension (but only if it's the first char)
678ebfcd 1269 if ( !strExt.empty() ) {
2b813b73
VZ
1270 strExt += wxT('.');
1271 }
1272 //else: no, don't append it
1273 }
1274 else {
1275 strExt += *p;
1276 }
1277 }
1278
1279 return TRUE;
1280}
1281
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
1286bool wxFileTypeImpl::SetCommand(const wxString& cmd, const wxString& verb, bool overwriteprompt /*= TRUE*/)
d84afea9 1287{
2b813b73 1288 wxArrayString strExtensions;
678ebfcd 1289 wxString strDesc, strIcon;
2b813b73 1290
678ebfcd 1291 wxMimeTypeCommands *entry = new wxMimeTypeCommands ();
2b813b73
VZ
1292 entry->Add(verb + wxT("=") + cmd + wxT(" %s "));
1293
1294 wxArrayString strTypes;
1295 GetMimeTypes (strTypes);
1296 if (strTypes.GetCount() < 1) return FALSE;
1297
1298 size_t i;
1299 bool Ok = TRUE;
1300 for (i = 0; i < strTypes.GetCount(); i++)
d84afea9 1301 {
2b813b73 1302 if (!m_manager->DoAssociation (strTypes[i], strIcon, entry, strExtensions, strDesc))
d84afea9
GD
1303 Ok = FALSE;
1304 }
2b813b73
VZ
1305
1306 return Ok;
d84afea9 1307}
2b813b73
VZ
1308
1309// ignore index on the grouds that we only have one icon in a Unix file
1310bool wxFileTypeImpl::SetDefaultIcon(const wxString& strIcon /*= wxEmptyString*/, int /*index = 0*/)
d84afea9 1311{
678ebfcd 1312 if (strIcon.empty()) return FALSE;
2b813b73
VZ
1313 wxArrayString strExtensions;
1314 wxString strDesc;
1315
678ebfcd 1316 wxMimeTypeCommands *entry = new wxMimeTypeCommands ();
2b813b73
VZ
1317
1318 wxArrayString strTypes;
1319 GetMimeTypes (strTypes);
1320 if (strTypes.GetCount() < 1) return FALSE;
1321
1322 size_t i;
1323 bool Ok = TRUE;
1324 for (i = 0; i < strTypes.GetCount(); i++)
d84afea9 1325 {
2b813b73 1326 if (!m_manager->DoAssociation (strTypes[i], strIcon, entry, strExtensions, strDesc))
d84afea9
GD
1327 Ok = FALSE;
1328 }
2b813b73
VZ
1329
1330 return Ok;
d84afea9
GD
1331}
1332
2b813b73
VZ
1333// ----------------------------------------------------------------------------
1334// wxMimeTypesManagerImpl (Unix)
1335// ----------------------------------------------------------------------------
1336
1337
1338wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1339{
1340 m_initialized = FALSE;
1341 m_mailcapStylesInited = 0;
1342}
1343
1344// read system and user mailcaps and other files
1345void wxMimeTypesManagerImpl::Initialize(int mailcapStyles,
1346 const wxString& sExtraDir)
1347{
1348 // read mimecap amd mime.types
a06c1b9b
VZ
1349 if ( (mailcapStyles & wxMAILCAP_NETSCAPE) ||
1350 (mailcapStyles & wxMAILCAP_STANDARD) )
2b813b73
VZ
1351 GetMimeInfo(sExtraDir);
1352
1353 // read GNOME tables
1354 if ( mailcapStyles & wxMAILCAP_GNOME)
1355 GetGnomeMimeInfo(sExtraDir);
1356
1357 // read KDE tables
1358 if ( mailcapStyles & wxMAILCAP_KDE)
1359 GetKDEMimeInfo(sExtraDir);
1360
1361 m_mailcapStylesInited |= mailcapStyles;
1362}
1363
1364// clear data so you can read another group of WM files
1365void wxMimeTypesManagerImpl::ClearData()
1366{
1367 m_aTypes.Clear ();
1368 m_aIcons.Clear ();
1369 m_aExtensions.Clear ();
1370 m_aDescriptions.Clear ();
1371
2b5f62a0 1372 WX_CLEAR_ARRAY(m_aEntries);
678ebfcd
VZ
1373 m_aEntries.Empty();
1374
2b813b73
VZ
1375 m_mailcapStylesInited = 0;
1376}
1377
1378wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1379{
678ebfcd 1380 ClearData();
2b813b73
VZ
1381}
1382
1383
1384void wxMimeTypesManagerImpl::GetMimeInfo (const wxString& sExtraDir)
1385{
1386 // read this for netscape or Metamail formats
1387
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!
1390
1391 // (taken from metamail(1) sources)
1392 //
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?)
1398
1399 wxString strHome = wxGetenv(wxT("HOME"));
1400
1401 wxArrayString dirs;
d353bd45 1402 dirs.Add ( strHome + wxT("/.") );
2b813b73
VZ
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/") );
678ebfcd 1408 if (!sExtraDir.empty()) dirs.Add ( sExtraDir + wxT("/") );
2b813b73
VZ
1409
1410 size_t nDirs = dirs.GetCount();
1411 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1412 {
1413 wxString file = dirs[nDir] + wxT("mailcap");
1414 if ( wxFile::Exists(file) ) {
1415 ReadMailcap(file);
1416 }
1417
1418 file = dirs[nDir] + wxT("mime.types");
1419 if ( wxFile::Exists(file) ) {
1420 ReadMimeTypes(file);
1421 }
1422 }
1423
1424}
1425
1426bool wxMimeTypesManagerImpl::WriteToMimeTypes (int index, bool delete_index)
1427{
1428 // check we have the right manager
a06c1b9b 1429 if (! ( m_mailcapStylesInited & wxMAILCAP_STANDARD) )
2b813b73
VZ
1430 return FALSE;
1431
1432 bool bTemp;
1433 wxString strHome = wxGetenv(wxT("HOME"));
1434
1435 // and now the users mailcap
1436 wxString strUserMailcap = strHome + wxT("/.mime.types");
1437
1438 wxMimeTextFile file;
1439 if ( wxFile::Exists(strUserMailcap) )
1440 {
1441 bTemp = file.Open(strUserMailcap);
1442 }
1443 else
1444 {
1445 if (delete_index) return FALSE;
1446 bTemp = file.Create(strUserMailcap);
1447 }
1448 if (bTemp)
1449 {
1450 int nIndex;
1451 // test for netscape's header and return FALSE if its found
1452 nIndex = file.pIndexOf (wxT("#--Netscape"));
1453 if (nIndex != wxNOT_FOUND)
1454 {
1455 wxASSERT_MSG(FALSE,wxT("Error in .mime.types \nTrying to mix Netscape and Metamail formats\nFile not modiifed"));
1456 return FALSE;
1457 }
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);
1464
1465 if (!delete_index)
1466 {
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);
1471 }
1472
1473
1474 bTemp = file.Write ();
1475 file.Close ();
1476 }
1477 return bTemp;
1478}
1479
1480bool wxMimeTypesManagerImpl::WriteToNSMimeTypes (int index, bool delete_index)
1481{
1482 //check we have the right managers
1483 if (! ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE) )
1484 return FALSE;
1485
1486 bool bTemp;
1487 wxString strHome = wxGetenv(wxT("HOME"));
1488
1489 // and now the users mailcap
1490 wxString strUserMailcap = strHome + wxT("/.mime.types");
1491
1492 wxMimeTextFile file;
1493 if ( wxFile::Exists(strUserMailcap) )
1494 {
1495 bTemp = file.Open(strUserMailcap);
1496 }
1497 else
1498 {
1499 if (delete_index) return FALSE;
1500 bTemp = file.Create(strUserMailcap);
1501 }
1502 if (bTemp)
1503 {
1504
1505 // write it in the format that Netscape uses
1506 int nIndex;
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)
1511 {
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)
1516 {
1517 wxASSERT_MSG(FALSE, wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1518 return FALSE;
1519 }
1520 file.InsertLine (wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1521 nIndex = 0;
1522 }
1523
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)
1528 {
1529 wxString sOld = file[nIndex];
1530 while ( (sOld.Contains(wxT("\\"))) && (nIndex < (int) file.GetLineCount()) )
1531 {
1532 file.CommentLine(nIndex);
1533 sOld = file[nIndex];
1534 wxLogTrace(TRACE_MIME, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex, sOld.c_str());
1535 nIndex ++;
1536 }
1537 if (nIndex < (int) file.GetLineCount()) file.CommentLine (nIndex);
1538 }
1539 else nIndex = (int) file.GetLineCount();
1540
1541 wxString sTmp = strType + wxT(" \\");
1542 if (!delete_index) file.InsertLine (sTmp, nIndex);
678ebfcd 1543 if ( ! m_aDescriptions.Item(index).empty() )
2b813b73 1544 {
678ebfcd 1545 sTmp = wxT("desc=\"") + m_aDescriptions[index]+ wxT("\" \\"); //.trim ??
2b813b73
VZ
1546 if (!delete_index)
1547 {
1548 nIndex ++;
1549 file.InsertLine (sTmp, nIndex);
1550 }
1551 }
1552 wxString sExts = m_aExtensions.Item(index);
1553 sTmp = wxT("exts=\"") + sExts.Trim(FALSE).Trim() + wxT("\"");
1554 if (!delete_index)
1555 {
1556 nIndex ++;
1557 file.InsertLine (sTmp, nIndex);
1558 }
1559
1560 bTemp = file.Write ();
1561 file.Close ();
1562 }
1563 return bTemp;
1564}
1565
1566
1567bool wxMimeTypesManagerImpl::WriteToMailCap (int index, bool delete_index)
1568{
1569 //check we have the right managers
1570 if ( !( ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE) ||
a06c1b9b 1571 ( m_mailcapStylesInited & wxMAILCAP_STANDARD) ) )
2b813b73
VZ
1572 return FALSE;
1573
1574 bool bTemp;
1575 wxString strHome = wxGetenv(wxT("HOME"));
1576
1577 // and now the users mailcap
1578 wxString strUserMailcap = strHome + wxT("/.mailcap");
1579
1580 wxMimeTextFile file;
1581 if ( wxFile::Exists(strUserMailcap) )
1582 {
1583 bTemp = file.Open(strUserMailcap);
1584 }
be0a33fb 1585 else
2b813b73
VZ
1586 {
1587 if (delete_index) return FALSE;
1588 bTemp = file.Create(strUserMailcap);
1589 }
1590 if (bTemp)
1591 {
1592 // now got a file we can write to ....
678ebfcd
VZ
1593 wxMimeTypeCommands * entries = m_aEntries[index];
1594 size_t iOpen;
1595 wxString sCmd = entries->GetCommandForVerb(_T("open"), &iOpen);
2b813b73
VZ
1596 wxString sTmp;
1597
1598 sTmp = m_aTypes[index];
1599 wxString sOld;
1600 int nIndex = file.pIndexOf(sTmp);
1601 // get rid of all the unwanted entries...
1602 if (nIndex == wxNOT_FOUND)
1603 {
1604 nIndex = (int) file.GetLineCount();
1605 }
1606 else
1607 {
1608 sOld = file[nIndex];
1609 wxLogTrace(TRACE_MIME, wxT("--- Deleting from mailcap line '%d' ---"), nIndex);
6dc6fda6 1610
2b813b73
VZ
1611 while ( (sOld.Contains(wxT("\\"))) && (nIndex < (int) file.GetLineCount()) )
1612 {
1613 file.CommentLine(nIndex);
1614 if (nIndex < (int) file.GetLineCount()) sOld = sOld + file[nIndex];
1615 }
1616 if (nIndex < (int) file.GetLineCount()) file.CommentLine (nIndex);
1617 }
6dc6fda6 1618
678ebfcd 1619 sTmp = sTmp + wxT(";") + sCmd; //includes wxT(" %s ");
b9517a0a 1620
2b813b73 1621 // write it in the format that Netscape uses (default)
a06c1b9b 1622 if (! ( m_mailcapStylesInited & wxMAILCAP_STANDARD ) )
2b813b73
VZ
1623 {
1624 if (! delete_index) file.InsertLine (sTmp, nIndex);
1625 nIndex ++;
1626 }
b9517a0a 1627
2b813b73
VZ
1628 // write extended format
1629 else
1630 {
1631 // todo FIX this code;
1632 // ii) lost entries
1633 // sOld holds all the entries, but our data store only has some
1634 // eg test= is not stored
1635
1636 // so far we have written the mimetype and command out
1637 wxStringTokenizer sT (sOld, wxT(";\\"));
1638 if (sT.CountTokens () > 2)
1639 {
1640 // first one mimetype; second one command, rest unknown...
1641 wxString s;
1642 s = sT.GetNextToken();
1643 s = sT.GetNextToken();
1644
1645 // first unknown
1646 s = sT.GetNextToken();
678ebfcd 1647 while ( ! s.empty() )
2b813b73
VZ
1648 {
1649 bool bKnownToken = FALSE;
1650 if (s.Contains(wxT("description="))) bKnownToken = TRUE;
1651 if (s.Contains(wxT("x11-bitmap="))) bKnownToken = TRUE;
1652 size_t i;
1653 for (i=0; i < entries->GetCount(); i++)
1654 {
1655 if (s.Contains(entries->GetVerb(i))) bKnownToken = TRUE;
1656 }
1657 if (!bKnownToken)
1658 {
1659 sTmp = sTmp + wxT("; \\");
1660 file.InsertLine (sTmp, nIndex);
1661 sTmp = s;
1662 }
1663 s = sT.GetNextToken ();
1664 }
cdf339c9 1665
2b813b73 1666 }
5bd3a2da 1667
678ebfcd 1668 if (! m_aDescriptions[index].empty() )
2b813b73
VZ
1669 {
1670 sTmp = sTmp + wxT("; \\");
1671 file.InsertLine (sTmp, nIndex);
1672 nIndex ++;
1673 sTmp = wxT(" description=\"") + m_aDescriptions[index] + wxT("\"");
1674 }
cdf339c9 1675
678ebfcd 1676 if (! m_aIcons[index].empty() )
2b813b73
VZ
1677 {
1678 sTmp = sTmp + wxT("; \\");
1679 file.InsertLine (sTmp, nIndex);
1680 nIndex ++;
1681 sTmp = wxT(" x11-bitmap=\"") + m_aIcons[index] + wxT("\"");
1682 }
1683 if ( entries->GetCount() > 1 )
cdf339c9 1684
2b813b73
VZ
1685 {
1686 size_t i;
1687 for (i=0; i < entries->GetCount(); i++)
1688 if ( i != iOpen )
1689 {
1690 sTmp = sTmp + wxT("; \\");
1691 file.InsertLine (sTmp, nIndex);
1692 nIndex ++;
678ebfcd 1693 sTmp = wxT(" ") + entries->GetVerbCmd(i);
2b813b73
VZ
1694 }
1695 }
b9517a0a 1696
2b813b73
VZ
1697 file.InsertLine (sTmp, nIndex);
1698 nIndex ++;
c93d6770 1699
b13d92d1 1700 }
2b813b73
VZ
1701 bTemp = file.Write ();
1702 file.Close ();
b13d92d1 1703 }
2b813b73 1704 return bTemp;
b13d92d1
VZ
1705}
1706
2b813b73
VZ
1707wxFileType *
1708wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
b9517a0a 1709{
2b813b73 1710 InitIfNeeded();
b9517a0a 1711
2b813b73
VZ
1712 wxString strType = ftInfo.GetMimeType ();
1713 wxString strDesc = ftInfo.GetDescription ();
1714 wxString strIcon = ftInfo.GetIconFile ();
1715
678ebfcd 1716 wxMimeTypeCommands *entry = new wxMimeTypeCommands ();
2b813b73 1717
678ebfcd 1718 if ( ! ftInfo.GetOpenCommand().empty())
2b813b73 1719 entry->Add(wxT("open=") + ftInfo.GetOpenCommand () + wxT(" %s "));
678ebfcd 1720 if ( ! ftInfo.GetPrintCommand ().empty())
2b813b73
VZ
1721 entry->Add(wxT("print=") + ftInfo.GetPrintCommand () + wxT(" %s "));
1722
1723 // now find where these extensions are in the data store and remove them
1724 wxArrayString sA_Exts = ftInfo.GetExtensions ();
1725 wxString sExt, sExtStore;
1726 size_t i, nIndex;
1727 for (i=0; i < sA_Exts.GetCount(); i++)
4d2976ad 1728 {
2b813b73
VZ
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 ++)
1734 {
1735 sExtStore = m_aExtensions.Item(nIndex);
678ebfcd 1736 if (sExtStore.Replace(sExt, wxT(" ") ) > 0) m_aExtensions.Item(nIndex) = sExtStore;
b9517a0a
VZ
1737 }
1738
2b813b73 1739 }
b9517a0a 1740
2b813b73
VZ
1741 if ( !DoAssociation (strType, strIcon, entry, sA_Exts, strDesc) )
1742 return NULL;
4d2976ad 1743
2b813b73 1744 return GetFileTypeFromMimeType(strType);
4d2976ad
VS
1745}
1746
1747
2b813b73
VZ
1748bool wxMimeTypesManagerImpl::DoAssociation(const wxString& strType,
1749 const wxString& strIcon,
678ebfcd 1750 wxMimeTypeCommands *entry,
2b813b73
VZ
1751 const wxArrayString& strExtensions,
1752 const wxString& strDesc)
b13d92d1 1753{
2b813b73 1754 int nIndex = AddToMimeData(strType, strIcon, entry, strExtensions, strDesc, TRUE);
b13d92d1 1755
2b813b73 1756 if ( nIndex == wxNOT_FOUND )
b13d92d1 1757 return FALSE;
b13d92d1 1758
2b813b73 1759 return WriteMimeInfo (nIndex, FALSE);
b13d92d1
VZ
1760}
1761
2b813b73 1762bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex, bool delete_mime )
b13d92d1 1763{
2b813b73 1764 bool ok = TRUE;
b13d92d1 1765
a06c1b9b 1766 if ( m_mailcapStylesInited & wxMAILCAP_STANDARD )
2b813b73
VZ
1767 {
1768 // write in metamail format;
1769 if (WriteToMimeTypes (nIndex, delete_mime) )
1770 if ( WriteToMailCap (nIndex, delete_mime) )
1771 ok = FALSE;
b13d92d1 1772 }
2b813b73 1773 if ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE )
b9517a0a 1774 {
2b813b73
VZ
1775 // write in netsacpe format;
1776 if (WriteToNSMimeTypes (nIndex, delete_mime) )
1777 if ( WriteToMailCap (nIndex, delete_mime) )
1778 ok = FALSE;
1779 }
1780 if (m_mailcapStylesInited & wxMAILCAP_GNOME)
1781 {
1782 // write in Gnome format;
1783 if (WriteGnomeMimeFile (nIndex, delete_mime) )
1784 if (WriteGnomeKeyFile (nIndex, delete_mime) )
1785 ok = FALSE;
1786 }
1787 if (m_mailcapStylesInited & wxMAILCAP_KDE)
1788 {
1789 // write in KDE format;
1790 if (WriteKDEMimeFile (nIndex, delete_mime) )
1791 ok = FALSE;
b9517a0a
VZ
1792 }
1793
2b813b73 1794 return ok;
a6c65e88
VZ
1795}
1796
2b813b73
VZ
1797int wxMimeTypesManagerImpl::AddToMimeData(const wxString& strType,
1798 const wxString& strIcon,
678ebfcd 1799 wxMimeTypeCommands *entry,
2b813b73
VZ
1800 const wxArrayString& strExtensions,
1801 const wxString& strDesc,
678ebfcd 1802 bool replaceExisting)
b13d92d1 1803{
2b813b73 1804 InitIfNeeded();
b13d92d1 1805
2b813b73 1806 // ensure mimetype is always lower case
678ebfcd
VZ
1807 wxString mimeType = strType.Lower();
1808
1809 // is this a known MIME type?
2b813b73
VZ
1810 int nIndex = m_aTypes.Index(mimeType);
1811 if ( nIndex == wxNOT_FOUND )
1812 {
1813 // new file type
1814 m_aTypes.Add(mimeType);
1815 m_aIcons.Add(strIcon);
678ebfcd 1816 m_aEntries.Add(entry ? entry : new wxMimeTypeCommands);
b13d92d1 1817
678ebfcd 1818 // change nIndex so we can use it below to add the extensions
df5168c4 1819 m_aExtensions.Add(wxEmptyString);
b8d61021 1820 nIndex = m_aExtensions.size() - 1;
678ebfcd
VZ
1821
1822 m_aDescriptions.Add(strDesc);
b13d92d1 1823 }
678ebfcd 1824 else // yes, we already have it
2b813b73 1825 {
678ebfcd 1826 if ( replaceExisting )
2b813b73
VZ
1827 {
1828 // if new description change it
678ebfcd 1829 if ( !strDesc.empty())
2b813b73
VZ
1830 m_aDescriptions[nIndex] = strDesc;
1831
1832 // if new icon change it
678ebfcd 1833 if ( !strIcon.empty())
2b813b73
VZ
1834 m_aIcons[nIndex] = strIcon;
1835
678ebfcd
VZ
1836 if ( entry )
1837 {
1838 delete m_aEntries[nIndex];
1839 m_aEntries[nIndex] = entry;
1840 }
2b813b73 1841 }
678ebfcd 1842 else // add data we don't already have ...
2b813b73 1843 {
2b813b73 1844 // if new description add only if none
678ebfcd 1845 if ( m_aDescriptions[nIndex].empty() )
2b813b73
VZ
1846 m_aDescriptions[nIndex] = strDesc;
1847
1848 // if new icon and no existing icon
678ebfcd 1849 if ( m_aIcons[nIndex].empty () )
2b813b73
VZ
1850 m_aIcons[nIndex] = strIcon;
1851
2b813b73 1852 // add any new entries...
678ebfcd 1853 if ( entry )
2b813b73 1854 {
678ebfcd
VZ
1855 wxMimeTypeCommands *entryOld = m_aEntries[nIndex];
1856
1857 size_t count = entry->GetCount();
1858 for ( size_t i = 0; i < count; i++ )
1859 {
1860 const wxString& verb = entry->GetVerb(i);
1861 if ( !entryOld->HasVerb(verb) )
1862 {
1863 entryOld->AddOrReplaceVerb(verb, entry->GetCmd(i));
1864 }
1865 }
2b293fc7
VZ
1866
1867 // as we don't store it anywhere, it won't be deleted later as
1868 // usual -- do it immediately instead
1869 delete entry;
2b813b73
VZ
1870 }
1871 }
b13d92d1 1872 }
4d2976ad 1873
678ebfcd
VZ
1874 // always add the extensions to this mimetype
1875 wxString& exts = m_aExtensions[nIndex];
1876
1877 // add all extensions we don't have yet
1878 size_t count = strExtensions.GetCount();
1879 for ( size_t i = 0; i < count; i++ )
1880 {
1881 wxString ext = strExtensions[i] + _T(' ');
1882
1883 if ( exts.Find(ext) == wxNOT_FOUND )
1884 {
1885 exts += ext;
1886 }
1887 }
1888
2b813b73
VZ
1889 // check data integrity
1890 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
678ebfcd
VZ
1891 m_aTypes.Count() == m_aExtensions.Count() &&
1892 m_aTypes.Count() == m_aIcons.Count() &&
1893 m_aTypes.Count() == m_aDescriptions.Count() );
cf471cab 1894
2b813b73 1895 return nIndex;
cf471cab
VS
1896}
1897
1898
b13d92d1
VZ
1899wxFileType *
1900wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1901{
678ebfcd 1902 if (ext.empty() )
2b813b73
VZ
1903 return NULL;
1904
a6c65e88
VZ
1905 InitIfNeeded();
1906
1ee17e1c 1907 size_t count = m_aExtensions.GetCount();
2b813b73 1908 for ( size_t n = 0; n < count; n++ )
678ebfcd
VZ
1909 {
1910 wxStringTokenizer tk(m_aExtensions[n], _T(' '));
1ee17e1c 1911
678ebfcd
VZ
1912 while ( tk.HasMoreTokens() )
1913 {
1ee17e1c 1914 // consider extensions as not being case-sensitive
678ebfcd
VZ
1915 if ( tk.GetNextToken().IsSameAs(ext, FALSE /* no case */) )
1916 {
1ee17e1c 1917 // found
678ebfcd 1918 wxFileType *fileType = new wxFileType;
1ee17e1c 1919 fileType->m_impl->Init(this, n);
678ebfcd
VZ
1920
1921 return fileType;
1ee17e1c
VZ
1922 }
1923 }
1924 }
b13d92d1 1925
678ebfcd 1926 return NULL;
b13d92d1
VZ
1927}
1928
1929wxFileType *
1930wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1931{
a6c65e88
VZ
1932 InitIfNeeded();
1933
2b813b73 1934 wxFileType * fileType = NULL;
b13d92d1
VZ
1935 // mime types are not case-sensitive
1936 wxString mimetype(mimeType);
1937 mimetype.MakeLower();
1938
1939 // first look for an exact match
1940 int index = m_aTypes.Index(mimetype);
2b813b73
VZ
1941 if ( index != wxNOT_FOUND )
1942 {
1943 fileType = new wxFileType;
1944 fileType->m_impl->Init(this, index);
1945 }
1946
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.
1950
1951 index = wxNOT_FOUND;
1952 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
1953
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("*") ) {
1958 index = n;
1959 break;
b13d92d1 1960 }
2b813b73 1961
b13d92d1
VZ
1962 }
1963
2b813b73
VZ
1964 if ( index != wxNOT_FOUND )
1965 {
1966 fileType = new wxFileType;
b13d92d1 1967 fileType->m_impl->Init(this, index);
b13d92d1 1968 }
2b813b73
VZ
1969 return fileType;
1970}
1971
1972
1973wxString wxMimeTypesManagerImpl::GetCommand(const wxString & verb, size_t nIndex) const
1974{
1975 wxString command, testcmd, sV, sTmp;
1976 sV = verb + wxT("=");
1977 // list of verb = command pairs for this mimetype
678ebfcd 1978 wxMimeTypeCommands * sPairs = m_aEntries [nIndex];
2b813b73
VZ
1979
1980 size_t i;
678ebfcd 1981 for ( i = 0; i < sPairs->GetCount (); i++ )
2b813b73 1982 {
678ebfcd
VZ
1983 sTmp = sPairs->GetVerbCmd (i);
1984 if ( sTmp.Contains(sV) )
1985 command = sTmp.AfterFirst(wxT('='));
b13d92d1 1986 }
2b813b73 1987 return command;
b13d92d1
VZ
1988}
1989
8e124873
VZ
1990void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
1991{
a6c65e88
VZ
1992 InitIfNeeded();
1993
3f1aaa16 1994 wxString extensions;
8e124873
VZ
1995 const wxArrayString& exts = filetype.GetExtensions();
1996 size_t nExts = exts.GetCount();
1997 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
1998 if ( nExt > 0 ) {
223d09f6 1999 extensions += wxT(' ');
8e124873
VZ
2000 }
2001 extensions += exts[nExt];
2002 }
2003
2004 AddMimeTypeInfo(filetype.GetMimeType(),
2005 extensions,
2006 filetype.GetDescription());
2007
2008 AddMailcapInfo(filetype.GetMimeType(),
2009 filetype.GetOpenCommand(),
2010 filetype.GetPrintCommand(),
223d09f6 2011 wxT(""),
8e124873
VZ
2012 filetype.GetDescription());
2013}
2014
2015void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
2016 const wxString& strExtensions,
2017 const wxString& strDesc)
2018{
2b813b73
VZ
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
2022 wxString strIcon;
2023 wxString sTmp = strExtensions;
a6c65e88 2024
2b813b73
VZ
2025 wxArrayString sExts;
2026 sTmp.Trim().Trim(FALSE);
2027
678ebfcd 2028 while (!sTmp.empty())
2b813b73
VZ
2029 {
2030 sExts.Add (sTmp.AfterLast(wxT(' ')));
2031 sTmp = sTmp.BeforeLast(wxT(' '));
8e124873 2032 }
2b813b73 2033
678ebfcd 2034 AddToMimeData (strMimeType, strIcon, NULL, sExts, strDesc, TRUE);
8e124873
VZ
2035}
2036
2037void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
2038 const wxString& strOpenCmd,
2039 const wxString& strPrintCmd,
2040 const wxString& strTest,
2041 const wxString& strDesc)
2042{
a6c65e88
VZ
2043 InitIfNeeded();
2044
678ebfcd 2045 wxMimeTypeCommands *entry = new wxMimeTypeCommands;
2b813b73
VZ
2046 entry->Add(wxT("open=") + strOpenCmd);
2047 entry->Add(wxT("print=") + strPrintCmd);
2048 entry->Add(wxT("test=") + strTest);
8e124873 2049
2b813b73
VZ
2050 wxString strIcon;
2051 wxArrayString strExtensions;
2052
2053 AddToMimeData (strType, strIcon, entry, strExtensions, strDesc, TRUE);
8e124873 2054
8e124873
VZ
2055}
2056
cc385968 2057bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
b13d92d1 2058{
f6bcfd97
BP
2059 wxLogTrace(TRACE_MIME, wxT("--- Parsing mime.types file '%s' ---"),
2060 strFileName.c_str());
b13d92d1
VZ
2061
2062 wxTextFile file(strFileName);
2b5f62a0
VZ
2063#if defined(__WXGTK20__) && wxUSE_UNICODE
2064 if ( !file.Open( wxConvUTF8) )
2065#else
b13d92d1 2066 if ( !file.Open() )
2b5f62a0 2067#endif
cc385968 2068 return FALSE;
b13d92d1
VZ
2069
2070 // the information we extract
2071 wxString strMimeType, strDesc, strExtensions;
2072
2073 size_t nLineCount = file.GetLineCount();
50920146 2074 const wxChar *pc = NULL;
2b5f62a0
VZ
2075 for ( size_t nLine = 0; nLine < nLineCount; nLine++ )
2076 {
22b4634c
VZ
2077 if ( pc == NULL ) {
2078 // now we're at the start of the line
2079 pc = file[nLine].c_str();
2080 }
2081 else {
2082 // we didn't finish with the previous line yet
2083 nLine--;
2084 }
b13d92d1
VZ
2085
2086 // skip whitespace
50920146 2087 while ( wxIsspace(*pc) )
b13d92d1
VZ
2088 pc++;
2089
54acce90
VZ
2090 // comment or blank line?
2091 if ( *pc == wxT('#') || !*pc ) {
22b4634c
VZ
2092 // skip the whole line
2093 pc = NULL;
b13d92d1 2094 continue;
22b4634c 2095 }
b13d92d1
VZ
2096
2097 // detect file format
223d09f6 2098 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
b13d92d1
VZ
2099 if ( pEqualSign == NULL ) {
2100 // brief format
2101 // ------------
2102
2103 // first field is mime type
223d09f6 2104 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
b13d92d1
VZ
2105 strMimeType += *pc;
2106 }
2107
2108 // skip whitespace
50920146 2109 while ( wxIsspace(*pc) )
b13d92d1
VZ
2110 pc++;
2111
2112 // take all the rest of the string
2113 strExtensions = pc;
2114
2115 // no description...
2116 strDesc.Empty();
2117 }
2118 else {
2119 // expanded format
2120 // ---------------
2121
2122 // the string on the left of '=' is the field name
2123 wxString strLHS(pc, pEqualSign - pc);
2124
2125 // eat whitespace
50920146 2126 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
678ebfcd 2127 ;
b13d92d1 2128
50920146 2129 const wxChar *pEnd;
223d09f6 2130 if ( *pc == wxT('"') ) {
b13d92d1 2131 // the string is quoted and ends at the matching quote
223d09f6 2132 pEnd = wxStrchr(++pc, wxT('"'));
b13d92d1
VZ
2133 if ( pEnd == NULL ) {
2134 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2135 "quoted string."),
2136 strFileName.c_str(), nLine + 1);
2137 }
2138 }
2139 else {
8862e11b
VZ
2140 // unquoted string ends at the first space or at the end of
2141 // line
2142 for ( pEnd = pc; *pEnd && !wxIsspace(*pEnd); pEnd++ )
678ebfcd 2143 ;
b13d92d1
VZ
2144 }
2145
2146 // now we have the RHS (field value)
2147 wxString strRHS(pc, pEnd - pc);
2148
22b4634c 2149 // check what follows this entry
223d09f6 2150 if ( *pEnd == wxT('"') ) {
b13d92d1
VZ
2151 // skip this quote
2152 pEnd++;
2153 }
2154
50920146 2155 for ( pc = pEnd; wxIsspace(*pc); pc++ )
678ebfcd 2156 ;
b13d92d1 2157
22b4634c
VZ
2158 // if there is something left, it may be either a '\\' to continue
2159 // the line or the next field of the same entry
223d09f6 2160 bool entryEnded = *pc == wxT('\0'),
22b4634c
VZ
2161 nextFieldOnSameLine = FALSE;
2162 if ( !entryEnded ) {
223d09f6 2163 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
b13d92d1 2164 }
b13d92d1
VZ
2165
2166 // now see what we got
223d09f6 2167 if ( strLHS == wxT("type") ) {
b13d92d1
VZ
2168 strMimeType = strRHS;
2169 }
678ebfcd 2170 else if ( strLHS.StartsWith(wxT("desc")) ) {
b13d92d1
VZ
2171 strDesc = strRHS;
2172 }
223d09f6 2173 else if ( strLHS == wxT("exts") ) {
b13d92d1
VZ
2174 strExtensions = strRHS;
2175 }
70247ce3 2176 else if ( strLHS == _T("icon") )
70687b63 2177 {
a2717c3d
VZ
2178 // this one is simply ignored: it usually refers to Netscape
2179 // built in icons which are useless for us anyhow
70687b63
VZ
2180 }
2181 else if ( !strLHS.StartsWith(_T("x-")) )
2182 {
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());
b13d92d1
VZ
2189 }
2190
2191 if ( !entryEnded ) {
22b4634c
VZ
2192 if ( !nextFieldOnSameLine )
2193 pc = NULL;
2194 //else: don't reset it
2195
2196 // as we don't reset strMimeType, the next field in this entry
b13d92d1 2197 // will be interpreted correctly.
22b4634c 2198
b13d92d1
VZ
2199 continue;
2200 }
2201 }
2202
a6c65e88
VZ
2203 // depending on the format (Mosaic or Netscape) either space or comma
2204 // is used to separate the extensions
223d09f6 2205 strExtensions.Replace(wxT(","), wxT(" "));
a1d8eaf7
VZ
2206
2207 // also deal with the leading dot
678ebfcd 2208 if ( !strExtensions.empty() && strExtensions[0u] == wxT('.') )
1b986aef 2209 {
a1d8eaf7
VZ
2210 strExtensions.erase(0, 1);
2211 }
2212
678ebfcd
VZ
2213 wxLogTrace(TRACE_MIME, wxT("mime.types: '%s' => '%s' (%s)"),
2214 strExtensions.c_str(),
2215 strMimeType.c_str(),
2216 strDesc.c_str());
2b813b73 2217
8e124873 2218 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
22b4634c
VZ
2219
2220 // finished with this line
2221 pc = NULL;
b13d92d1
VZ
2222 }
2223
cc385968 2224 return TRUE;
b13d92d1
VZ
2225}
2226
678ebfcd
VZ
2227// ----------------------------------------------------------------------------
2228// UNIX mailcap files parsing
2229// ----------------------------------------------------------------------------
2230
2231// the data for a single MIME type
2232struct MailcapLineData
2233{
2234 // field values
2235 wxString type,
2236 cmdOpen,
2237 test,
2238 icon,
2239 desc;
2240
2241 wxArrayString verbs,
2242 commands;
2243
2244 // flags
2245 bool testfailed,
2246 needsterminal,
2247 copiousoutput;
2248
2249 MailcapLineData() { testfailed = needsterminal = copiousoutput = FALSE; }
2250};
2251
2252// process a non-standard (i.e. not the first or second one) mailcap field
2253bool
2254wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData& data,
2255 const wxString& curField)
2256{
2257 if ( curField.empty() )
2258 {
2259 // we don't care
2260 return TRUE;
2261 }
2262
2263 // is this something of the form foo=bar?
2264 const wxChar *pEq = wxStrchr(curField, wxT('='));
2265 if ( pEq != NULL )
2266 {
2267 // split "LHS = RHS" in 2
2268 wxString lhs = curField.BeforeFirst(wxT('=')),
2269 rhs = curField.AfterFirst(wxT('='));
2270
2271 lhs.Trim(TRUE); // from right
2272 rhs.Trim(FALSE); // from left
2273
2274 // it might be quoted
2275 if ( !rhs.empty() && rhs[0u] == wxT('"') && rhs.Last() == wxT('"') )
2276 {
2277 rhs = rhs.Mid(1, rhs.length() - 2);
2278 }
2279
2280 // is it a command verb or something else?
2281 if ( lhs == wxT("test") )
2282 {
2283 if ( wxSystem(rhs) == 0 )
2284 {
2285 // ok, test passed
2286 wxLogTrace(TRACE_MIME_TEST,
2287 wxT("Test '%s' for mime type '%s' succeeded."),
2288 rhs.c_str(), data.type.c_str());
2289
2290 }
2291 else
2292 {
2293 wxLogTrace(TRACE_MIME_TEST,
2294 wxT("Test '%s' for mime type '%s' failed, skipping."),
2295 rhs.c_str(), data.type.c_str());
2296
2297 data.testfailed = TRUE;
2298 }
2299 }
2300 else if ( lhs == wxT("desc") )
2301 {
2302 data.desc = rhs;
2303 }
2304 else if ( lhs == wxT("x11-bitmap") )
2305 {
2306 data.icon = rhs;
2307 }
2308 else if ( lhs == wxT("notes") )
2309 {
2310 // ignore
2311 }
2312 else // not a (recognized) special case, must be a verb (e.g. "print")
2313 {
2314 data.verbs.Add(lhs);
2315 data.commands.Add(rhs);
2316 }
2317 }
2318 else // '=' not found
2319 {
2320 // so it must be a simple flag
2321 if ( curField == wxT("needsterminal") )
2322 {
2323 data.needsterminal = TRUE;
2324 }
2325 else if ( curField == wxT("copiousoutput"))
2326 {
2327 // copiousoutput impies that the viewer is a console program
2328 data.needsterminal =
2329 data.copiousoutput = TRUE;
2330 }
2331 else if ( !IsKnownUnimportantField(curField) )
2332 {
2333 return FALSE;
2334 }
2335 }
2336
2337 return TRUE;
2338}
2339
cc385968
VZ
2340bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
2341 bool fallback)
b13d92d1 2342{
f6bcfd97
BP
2343 wxLogTrace(TRACE_MIME, wxT("--- Parsing mailcap file '%s' ---"),
2344 strFileName.c_str());
b13d92d1
VZ
2345
2346 wxTextFile file(strFileName);
2b5f62a0
VZ
2347#if defined(__WXGTK20__) && wxUSE_UNICODE
2348 if ( !file.Open( wxConvUTF8) )
2349#else
b13d92d1 2350 if ( !file.Open() )
2b5f62a0 2351#endif
cc385968 2352 return FALSE;
b13d92d1 2353
678ebfcd
VZ
2354 // indices of MIME types (in m_aTypes) we already found in this file
2355 //
2356 // (see the comments near the end of function for the reason we need this)
2357 wxArrayInt aIndicesSeenHere;
2358
2359 // accumulator for the current field
2360 wxString curField;
2361 curField.reserve(1024);
b13d92d1
VZ
2362
2363 size_t nLineCount = file.GetLineCount();
678ebfcd
VZ
2364 for ( size_t nLine = 0; nLine < nLineCount; nLine++ )
2365 {
b13d92d1 2366 // now we're at the start of the line
50920146 2367 const wxChar *pc = file[nLine].c_str();
b13d92d1
VZ
2368
2369 // skip whitespace
50920146 2370 while ( wxIsspace(*pc) )
b13d92d1
VZ
2371 pc++;
2372
2373 // comment or empty string?
223d09f6 2374 if ( *pc == wxT('#') || *pc == wxT('\0') )
b13d92d1
VZ
2375 continue;
2376
2377 // no, do parse
678ebfcd 2378 // ------------
b13d92d1
VZ
2379
2380 // what field are we currently in? The first 2 are fixed and there may
678ebfcd
VZ
2381 // be an arbitrary number of other fields parsed by
2382 // ProcessOtherMailcapField()
2383 //
2384 // the first field is the MIME type
b13d92d1
VZ
2385 enum
2386 {
2387 Field_Type,
2388 Field_OpenCmd,
2389 Field_Other
2390 } currentToken = Field_Type;
2391
2392 // the flags and field values on the current line
678ebfcd
VZ
2393 MailcapLineData data;
2394
6e358ae7 2395 bool cont = TRUE;
678ebfcd
VZ
2396 while ( cont )
2397 {
2398 switch ( *pc )
2399 {
223d09f6 2400 case wxT('\\'):
b13d92d1
VZ
2401 // interpret the next character literally (notice that
2402 // backslash can be used for line continuation)
678ebfcd
VZ
2403 if ( *++pc == wxT('\0') )
2404 {
6e358ae7 2405 // fetch the next line if there is one
678ebfcd
VZ
2406 if ( nLine == nLineCount - 1 )
2407 {
6e358ae7
VZ
2408 // something is wrong, bail out
2409 cont = FALSE;
2410
2b5f62a0 2411 wxLogDebug(wxT("Mailcap file %s, line %lu: "
6e358ae7
VZ
2412 "'\\' on the end of the last line "
2413 "ignored."),
2414 strFileName.c_str(),
2b5f62a0 2415 (unsigned long)nLine + 1);
6e358ae7 2416 }
678ebfcd
VZ
2417 else
2418 {
6e358ae7
VZ
2419 // pass to the beginning of the next line
2420 pc = file[++nLine].c_str();
2421
2422 // skip pc++ at the end of the loop
2423 continue;
2424 }
b13d92d1 2425 }
678ebfcd
VZ
2426 else
2427 {
b13d92d1
VZ
2428 // just a normal character
2429 curField += *pc;
2430 }
2431 break;
2432
223d09f6 2433 case wxT('\0'):
b13d92d1
VZ
2434 cont = FALSE; // end of line reached, exit the loop
2435
678ebfcd 2436 // fall through to still process this field
b13d92d1 2437
223d09f6 2438 case wxT(';'):
b13d92d1
VZ
2439 // trim whitespaces from both sides
2440 curField.Trim(TRUE).Trim(FALSE);
2441
678ebfcd
VZ
2442 switch ( currentToken )
2443 {
b13d92d1 2444 case Field_Type:
678ebfcd
VZ
2445 data.type = curField.Lower();
2446 if ( data.type.empty() )
2447 {
6e358ae7
VZ
2448 // I don't think that this is a valid mailcap
2449 // entry, but try to interpret it somehow
678ebfcd 2450 data.type = _T('*');
6e358ae7
VZ
2451 }
2452
678ebfcd
VZ
2453 if ( data.type.Find(wxT('/')) == wxNOT_FOUND )
2454 {
b13d92d1 2455 // we interpret "type" as "type/*"
678ebfcd 2456 data.type += wxT("/*");
b13d92d1
VZ
2457 }
2458
2459 currentToken = Field_OpenCmd;
2460 break;
2461
2462 case Field_OpenCmd:
678ebfcd 2463 data.cmdOpen = curField;
b13d92d1
VZ
2464
2465 currentToken = Field_Other;
2466 break;
2467
2468 case Field_Other:
678ebfcd
VZ
2469 if ( !ProcessOtherMailcapField(data, curField) )
2470 {
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
2475 wxLogDebug
2476 (
2b5f62a0 2477 wxT("Mailcap file %s, line %lu: "
678ebfcd
VZ
2478 "unknown field '%s' for the "
2479 "MIME type '%s' ignored."),
2480 strFileName.c_str(),
2b5f62a0 2481 (unsigned long)nLine + 1,
678ebfcd
VZ
2482 curField.c_str(),
2483 data.type.c_str()
2484 );
2485 }
2486 else if ( data.testfailed )
2487 {
2488 // skip this entry entirely
2489 cont = FALSE;
b13d92d1
VZ
2490 }
2491
2492 // it already has this value
2493 //currentToken = Field_Other;
2494 break;
2495
2496 default:
223d09f6 2497 wxFAIL_MSG(wxT("unknown field type in mailcap"));
b13d92d1
VZ
2498 }
2499
2500 // next token starts immediately after ';'
2501 curField.Empty();
2502 break;
2503
2504 default:
2505 curField += *pc;
2506 }
6e358ae7
VZ
2507
2508 // continue in the same line
2509 pc++;
b13d92d1
VZ
2510 }
2511
678ebfcd
VZ
2512 // we read the entire entry, check what have we got
2513 // ------------------------------------------------
2514
b13d92d1 2515 // check that we really read something reasonable
678ebfcd
VZ
2516 if ( currentToken < Field_Other )
2517 {
b13d92d1
VZ
2518 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2519 "ignored."),
2520 strFileName.c_str(), nLine + 1);
678ebfcd
VZ
2521
2522 continue;
b13d92d1 2523 }
e1e9ea40 2524
678ebfcd
VZ
2525 // if the test command failed, it's as if the entry were not there at
2526 // all
2527 if ( data.testfailed )
2528 {
2529 continue;
2530 }
2b813b73 2531
678ebfcd
VZ
2532 // support for flags:
2533 // 1. create an xterm for 'needsterminal'
2534 // 2. append "| $PAGER" for 'copiousoutput'
2535 //
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 )
2541 {
2542 const wxChar *p = wxGetenv(_T("PAGER"));
2543 data.cmdOpen << _T(" | ") << (p ? p : _T("more"));
2544 }
b13d92d1 2545
678ebfcd
VZ
2546 if ( data.needsterminal )
2547 {
2b5f62a0
VZ
2548 data.cmdOpen = wxString::Format(_T("xterm -e sh -c '%s'"),
2549 data.cmdOpen.c_str());
678ebfcd 2550 }
b13d92d1 2551
678ebfcd
VZ
2552 if ( !data.cmdOpen.empty() )
2553 {
2554 data.verbs.Insert(_T("open"), 0);
2555 data.commands.Insert(data.cmdOpen, 0);
2556 }
2b813b73 2557
678ebfcd
VZ
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
2560 bool overwrite;
2561
2562 // the fall back entries have the lowest priority, by definition
2563 if ( fallback )
2564 {
2565 overwrite = FALSE;
2566 }
2567 else
2568 {
2569 // have we seen this one before?
2570 int nIndex = m_aTypes.Index(data.type);
2571
2572 // and if we have, was it in this file?
2573 overwrite = nIndex == wxNOT_FOUND ||
2574 aIndicesSeenHere.Index(nIndex) != wxNOT_FOUND;
b13d92d1
VZ
2575 }
2576
678ebfcd
VZ
2577 wxLogTrace(TRACE_MIME, _T("mailcap %s: %s [%s]"),
2578 data.type.c_str(), data.cmdOpen.c_str(),
2579 overwrite ? _T("replace") : _T("add"));
2580
2581 int n = AddToMimeData
2582 (
2583 data.type,
2584 data.icon,
2585 new wxMimeTypeCommands(data.verbs, data.commands),
2586 wxArrayString() /* extensions */,
2587 data.desc,
2588 overwrite
2589 );
2590
2591 if ( overwrite )
2592 {
2593 aIndicesSeenHere.Add(n);
2594 }
b13d92d1 2595 }
cc385968
VZ
2596
2597 return TRUE;
b13d92d1
VZ
2598}
2599
696e1ea0 2600size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef 2601{
a6c65e88
VZ
2602 InitIfNeeded();
2603
54acce90
VZ
2604 mimetypes.Empty();
2605
2606 wxString type;
2607 size_t count = m_aTypes.GetCount();
2608 for ( size_t n = 0; n < count; n++ )
2609 {
2610 // don't return template types from here (i.e. anything containg '*')
2611 type = m_aTypes[n];
2612 if ( type.Find(_T('*')) == wxNOT_FOUND )
2613 {
2614 mimetypes.Add(type);
2615 }
2616 }
1b986aef 2617
54acce90 2618 return mimetypes.GetCount();
1b986aef
VZ
2619}
2620
a6c65e88
VZ
2621// ----------------------------------------------------------------------------
2622// writing to MIME type files
2623// ----------------------------------------------------------------------------
2624
2b813b73 2625bool wxMimeTypesManagerImpl::Unassociate(wxFileType *ft)
a6c65e88 2626{
2b813b73
VZ
2627 wxArrayString sMimeTypes;
2628 ft->GetMimeTypes (sMimeTypes);
a6c65e88 2629
2b813b73
VZ
2630 wxString sMime;
2631 size_t i;
2632 for (i = 0; i < sMimeTypes.GetCount(); i ++)
2633 {
2634 sMime = sMimeTypes.Item(i);
2635 int nIndex = m_aTypes.Index (sMime);
2636 if ( nIndex == wxNOT_FOUND)
2637 {
2638 // error if we get here ??
2639 return FALSE;
2640 }
2641 else
2642 {
2643 WriteMimeInfo(nIndex, TRUE );
e9d9f136
VZ
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);
2b813b73
VZ
2649 }
2650 }
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() );
2656
2657 return TRUE;
a6c65e88
VZ
2658}
2659
f6bcfd97
BP
2660// ----------------------------------------------------------------------------
2661// private functions
2662// ----------------------------------------------------------------------------
2663
2664static bool IsKnownUnimportantField(const wxString& fieldAll)
2665{
2666 static const wxChar *knownFields[] =
2667 {
2668 _T("x-mozilla-flags"),
2669 _T("nametemplate"),
2670 _T("textualnewlines"),
2671 };
2672
2673 wxString field = fieldAll.BeforeFirst(_T('='));
2674 for ( size_t n = 0; n < WXSIZEOF(knownFields); n++ )
2675 {
2676 if ( field.CmpNoCase(knownFields[n]) == 0 )
2677 return TRUE;
2678 }
2679
2680 return FALSE;
2681}
2682
8e124873 2683#endif
b79e32cc 2684 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE
b13d92d1 2685