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