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