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