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