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