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