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