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