]> git.saurik.com Git - wxWidgets.git/blob - src/unix/mimetype.cpp
Correct wxPickerBase size calculation.
[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 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(wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_OCTAL)) )
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 const 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 += 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 += 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 nCount = config.GetLineCount();
1013 for (size_t i = 0; i < nCount; 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 size_t nCount = m_index.GetCount();
1141 for (size_t i = 0; i < nCount; i++)
1142 mimeTypes.Add(m_manager->m_aTypes[m_index[i]]);
1143
1144 return true;
1145 }
1146
1147 size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
1148 wxArrayString *commands,
1149 const wxFileType::MessageParameters& params) const
1150 {
1151 wxString vrb, cmd, sTmp;
1152 size_t count = 0;
1153 wxMimeTypeCommands * sPairs;
1154
1155 // verbs and commands have been cleared already in mimecmn.cpp...
1156 // if we find no entries in the exact match, try the inexact match
1157 for (size_t n = 0; ((count == 0) && (n < m_index.GetCount())); n++)
1158 {
1159 // list of verb = command pairs for this mimetype
1160 sPairs = m_manager->m_aEntries [m_index[n]];
1161 size_t i;
1162 for ( i = 0; i < sPairs->GetCount(); i++ )
1163 {
1164 vrb = sPairs->GetVerb(i);
1165 // some gnome entries have "." inside
1166 vrb = vrb.AfterLast(wxT('.'));
1167 cmd = sPairs->GetCmd(i);
1168 if (! cmd.empty() )
1169 {
1170 cmd = wxFileType::ExpandCommand(cmd, params);
1171 count++;
1172 if ( vrb.IsSameAs(wxT("open")))
1173 {
1174 if ( verbs )
1175 verbs->Insert(vrb, 0u);
1176 if ( commands )
1177 commands ->Insert(cmd, 0u);
1178 }
1179 else
1180 {
1181 if ( verbs )
1182 verbs->Add(vrb);
1183 if ( commands )
1184 commands->Add(cmd);
1185 }
1186 }
1187 }
1188 }
1189
1190 return count;
1191 }
1192
1193 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1194 {
1195 wxString strExtensions = m_manager->GetExtension(m_index[0]);
1196 extensions.Empty();
1197
1198 // one extension in the space or comma-delimited list
1199 wxString strExt;
1200 for ( const wxChar *p = strExtensions; /* nothing */; p++ )
1201 {
1202 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') )
1203 {
1204 if ( !strExt.empty() )
1205 {
1206 extensions.Add(strExt);
1207 strExt.Empty();
1208 }
1209 //else: repeated spaces
1210 // (shouldn't happen, but it's not that important if it does happen)
1211
1212 if ( *p == wxT('\0') )
1213 break;
1214 }
1215 else if ( *p == wxT('.') )
1216 {
1217 // remove the dot from extension (but only if it's the first char)
1218 if ( !strExt.empty() )
1219 {
1220 strExt += wxT('.');
1221 }
1222 //else: no, don't append it
1223 }
1224 else
1225 {
1226 strExt += *p;
1227 }
1228 }
1229
1230 return true;
1231 }
1232
1233 // set an arbitrary command:
1234 // could adjust the code to ask confirmation if it already exists and
1235 // overwriteprompt is true, but this is currently ignored as *Associate* has
1236 // no overwrite prompt
1237 bool
1238 wxFileTypeImpl::SetCommand(const wxString& cmd,
1239 const wxString& verb,
1240 bool WXUNUSED(overwriteprompt))
1241 {
1242 wxArrayString strExtensions;
1243 wxString strDesc, strIcon;
1244
1245 wxArrayString strTypes;
1246 GetMimeTypes(strTypes);
1247 if ( strTypes.IsEmpty() )
1248 return false;
1249
1250 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
1251 entry->Add(verb + wxT("=") + cmd + wxT(" %s "));
1252
1253 bool ok = true;
1254 size_t nCount = strTypes.GetCount();
1255 for ( size_t i = 0; i < nCount; i++ )
1256 {
1257 if (!m_manager->DoAssociation(strTypes[i], strIcon, entry, strExtensions, strDesc))
1258 ok = false;
1259 }
1260
1261 return ok;
1262 }
1263
1264 // ignore index on the grounds that we only have one icon in a Unix file
1265 bool wxFileTypeImpl::SetDefaultIcon(const wxString& strIcon, int WXUNUSED(index))
1266 {
1267 if (strIcon.empty())
1268 return false;
1269
1270 wxArrayString strExtensions;
1271 wxString strDesc;
1272
1273 wxArrayString strTypes;
1274 GetMimeTypes(strTypes);
1275 if ( strTypes.IsEmpty() )
1276 return false;
1277
1278 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
1279 bool ok = true;
1280 size_t nCount = strTypes.GetCount();
1281 for ( size_t i = 0; i < nCount; i++ )
1282 {
1283 if ( !m_manager->DoAssociation
1284 (
1285 strTypes[i],
1286 strIcon,
1287 entry,
1288 strExtensions,
1289 strDesc
1290 ) )
1291 {
1292 ok = false;
1293 }
1294 }
1295
1296 return ok;
1297 }
1298
1299 // ----------------------------------------------------------------------------
1300 // wxMimeTypesManagerImpl (Unix)
1301 // ----------------------------------------------------------------------------
1302
1303 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1304 {
1305 m_initialized = false;
1306 m_mailcapStylesInited = 0;
1307 }
1308
1309 void wxMimeTypesManagerImpl::InitIfNeeded()
1310 {
1311 if ( !m_initialized )
1312 {
1313 // set the flag first to prevent recursion
1314 m_initialized = true;
1315
1316 wxString wm = wxTheApp->GetTraits()->GetDesktopEnvironment();
1317
1318 if (wm == wxT("KDE"))
1319 Initialize( wxMAILCAP_KDE );
1320 else if (wm == wxT("GNOME"))
1321 Initialize( wxMAILCAP_GNOME );
1322 else
1323 Initialize();
1324 }
1325 }
1326
1327 // read system and user mailcaps and other files
1328 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles,
1329 const wxString& sExtraDir)
1330 {
1331 // read mimecap amd mime.types
1332 if ( (mailcapStyles & wxMAILCAP_NETSCAPE) ||
1333 (mailcapStyles & wxMAILCAP_STANDARD) )
1334 GetMimeInfo(sExtraDir);
1335
1336 // read GNOME tables
1337 if (mailcapStyles & wxMAILCAP_GNOME)
1338 GetGnomeMimeInfo(sExtraDir);
1339
1340 // read KDE tables
1341 if (mailcapStyles & wxMAILCAP_KDE)
1342 GetKDEMimeInfo(sExtraDir);
1343
1344 m_mailcapStylesInited |= mailcapStyles;
1345 }
1346
1347 // clear data so you can read another group of WM files
1348 void wxMimeTypesManagerImpl::ClearData()
1349 {
1350 m_aTypes.Clear();
1351 m_aIcons.Clear();
1352 m_aExtensions.Clear();
1353 m_aDescriptions.Clear();
1354
1355 WX_CLEAR_ARRAY(m_aEntries);
1356 m_aEntries.Empty();
1357
1358 m_mailcapStylesInited = 0;
1359 }
1360
1361 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
1362 {
1363 ClearData();
1364 }
1365
1366 void wxMimeTypesManagerImpl::GetMimeInfo(const wxString& sExtraDir)
1367 {
1368 // read this for netscape or Metamail formats
1369
1370 // directories where we look for mailcap and mime.types by default
1371 // used by netscape and pine and other mailers, using 2 different formats!
1372
1373 // (taken from metamail(1) sources)
1374 //
1375 // although RFC 1524 specifies the search path of
1376 // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
1377 // places - OTOH, the RFC also says that this path can be changed with
1378 // MAILCAPS environment variable (containing the colon separated full
1379 // filenames to try) which is not done yet (TODO?)
1380
1381 wxString strHome = wxGetenv(wxT("HOME"));
1382
1383 wxArrayString dirs;
1384 dirs.Add( strHome + wxT("/.") );
1385 dirs.Add( wxT("/etc/") );
1386 dirs.Add( wxT("/usr/etc/") );
1387 dirs.Add( wxT("/usr/local/etc/") );
1388 dirs.Add( wxT("/etc/mail/") );
1389 dirs.Add( wxT("/usr/public/lib/") );
1390 if (!sExtraDir.empty())
1391 dirs.Add( sExtraDir + wxT("/") );
1392
1393 wxString file;
1394 size_t nDirs = dirs.GetCount();
1395 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1396 {
1397 file = dirs[nDir];
1398 file += wxT("mailcap");
1399 if ( wxFile::Exists(file) )
1400 {
1401 ReadMailcap(file);
1402 }
1403
1404 file = dirs[nDir];
1405 file += wxT("mime.types");
1406 if ( wxFile::Exists(file) )
1407 ReadMimeTypes(file);
1408 }
1409 }
1410
1411 bool wxMimeTypesManagerImpl::WriteToMimeTypes(int index, bool delete_index)
1412 {
1413 // check we have the right manager
1414 if (! ( m_mailcapStylesInited & wxMAILCAP_STANDARD) )
1415 return false;
1416
1417 bool bTemp;
1418 wxString strHome = wxGetenv(wxT("HOME"));
1419
1420 // and now the users mailcap
1421 wxString strUserMailcap = strHome + wxT("/.mime.types");
1422
1423 wxMimeTextFile file;
1424 if ( wxFile::Exists(strUserMailcap) )
1425 {
1426 bTemp = file.Open(strUserMailcap);
1427 }
1428 else
1429 {
1430 if (delete_index)
1431 return false;
1432
1433 bTemp = file.Create(strUserMailcap);
1434 }
1435
1436 if (bTemp)
1437 {
1438 int nIndex;
1439 // test for netscape's header and return false if its found
1440 nIndex = file.pIndexOf(wxT("#--Netscape"));
1441 if (nIndex != wxNOT_FOUND)
1442 {
1443 wxFAIL_MSG(wxT("Error in .mime.types\nTrying to mix Netscape and Metamail formats\nFile not modified"));
1444 return false;
1445 }
1446
1447 // write it in alternative format
1448 // get rid of unwanted entries
1449 wxString strType = m_aTypes[index];
1450 nIndex = file.pIndexOf(strType);
1451
1452 // get rid of all the unwanted entries...
1453 if (nIndex != wxNOT_FOUND)
1454 file.CommentLine(nIndex);
1455
1456 if (!delete_index)
1457 {
1458 // add the new entries in
1459 wxString sTmp = strType.Append( wxT(' '), 40 - strType.Len() );
1460 sTmp += m_aExtensions[index];
1461 file.AddLine(sTmp);
1462 }
1463
1464 bTemp = file.Write();
1465 file.Close();
1466 }
1467
1468 return bTemp;
1469 }
1470
1471 bool wxMimeTypesManagerImpl::WriteToNSMimeTypes(int index, bool delete_index)
1472 {
1473 //check we have the right managers
1474 if (! ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE) )
1475 return false;
1476
1477 bool bTemp;
1478 wxString strHome = wxGetenv(wxT("HOME"));
1479
1480 // and now the users mailcap
1481 wxString strUserMailcap = strHome + wxT("/.mime.types");
1482
1483 wxMimeTextFile file;
1484 if ( wxFile::Exists(strUserMailcap) )
1485 {
1486 bTemp = file.Open(strUserMailcap);
1487 }
1488 else
1489 {
1490 if (delete_index)
1491 return false;
1492
1493 bTemp = file.Create(strUserMailcap);
1494 }
1495
1496 if (bTemp)
1497 {
1498 // write it in the format that Netscape uses
1499 int nIndex;
1500 // test for netscape's header and insert if required...
1501 // this is a comment so use true
1502 nIndex = file.pIndexOf(wxT("#--Netscape"), true);
1503 if (nIndex == wxNOT_FOUND)
1504 {
1505 // either empty file or metamail format
1506 // at present we can't cope with mixed formats, so exit to preseve
1507 // metamail entreies
1508 if (file.GetLineCount() > 0)
1509 {
1510 wxFAIL_MSG(wxT(".mime.types File not in Netscape format\nNo entries written to\n.mime.types or to .mailcap"));
1511 return false;
1512 }
1513
1514 file.InsertLine(wxT( "#--Netscape Communications Corporation MIME Information" ), 0);
1515 nIndex = 0;
1516 }
1517
1518 wxString strType = wxT("type=") + m_aTypes[index];
1519 nIndex = file.pIndexOf(strType);
1520
1521 // get rid of all the unwanted entries...
1522 if (nIndex != wxNOT_FOUND)
1523 {
1524 wxString sOld = file[nIndex];
1525 while ( (sOld.Contains(wxT("\\"))) && (nIndex < (int) file.GetLineCount()) )
1526 {
1527 file.CommentLine(nIndex);
1528 sOld = file[nIndex];
1529
1530 wxLogTrace(TRACE_MIME, wxT("--- Deleting from mime.types line '%d %s' ---"), nIndex, sOld.c_str());
1531
1532 nIndex++;
1533 }
1534
1535 if (nIndex < (int) file.GetLineCount())
1536 file.CommentLine(nIndex);
1537 }
1538 else
1539 nIndex = (int) file.GetLineCount();
1540
1541 wxString sTmp = strType + wxT(" \\");
1542 if (!delete_index)
1543 file.InsertLine(sTmp, nIndex);
1544
1545 if ( ! m_aDescriptions.Item(index).empty() )
1546 {
1547 sTmp = wxT("desc=\"") + m_aDescriptions[index]+ wxT("\" \\"); //.trim ??
1548 if (!delete_index)
1549 {
1550 nIndex++;
1551 file.InsertLine(sTmp, nIndex);
1552 }
1553 }
1554
1555 wxString sExts = m_aExtensions.Item(index);
1556 sTmp = wxT("exts=\"") + sExts.Trim(false).Trim() + wxT("\"");
1557 if (!delete_index)
1558 {
1559 nIndex++;
1560 file.InsertLine(sTmp, nIndex);
1561 }
1562
1563 bTemp = file.Write();
1564 file.Close();
1565 }
1566
1567 return bTemp;
1568 }
1569
1570 bool wxMimeTypesManagerImpl::WriteToMailCap(int index, bool delete_index)
1571 {
1572 //check we have the right managers
1573 if ( !( ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE) ||
1574 ( m_mailcapStylesInited & wxMAILCAP_STANDARD) ) )
1575 return false;
1576
1577 bool bTemp = false;
1578 wxString strHome = wxGetenv(wxT("HOME"));
1579
1580 // and now the users mailcap
1581 wxString strUserMailcap = strHome + wxT("/.mailcap");
1582
1583 wxMimeTextFile file;
1584 if ( wxFile::Exists(strUserMailcap) )
1585 {
1586 bTemp = file.Open(strUserMailcap);
1587 }
1588 else
1589 {
1590 if (delete_index)
1591 return false;
1592
1593 bTemp = file.Create(strUserMailcap);
1594 }
1595
1596 if (bTemp)
1597 {
1598 // now got a file we can write to ....
1599 wxMimeTypeCommands * entries = m_aEntries[index];
1600 size_t iOpen;
1601 wxString sCmd = entries->GetCommandForVerb(wxT("open"), &iOpen);
1602 wxString sTmp;
1603
1604 sTmp = m_aTypes[index];
1605 wxString sOld;
1606 int nIndex = file.pIndexOf(sTmp);
1607
1608 // get rid of all the unwanted entries...
1609 if (nIndex == wxNOT_FOUND)
1610 {
1611 nIndex = (int) file.GetLineCount();
1612 }
1613 else
1614 {
1615 sOld = file[nIndex];
1616 wxLogTrace(TRACE_MIME, wxT("--- Deleting from mailcap line '%d' ---"), nIndex);
1617
1618 while ( (sOld.Contains(wxT("\\"))) && (nIndex < (int) file.GetLineCount()) )
1619 {
1620 file.CommentLine(nIndex);
1621 if (nIndex < (int) file.GetLineCount())
1622 sOld = sOld + file[nIndex];
1623 }
1624
1625 if (nIndex < (int)
1626 file.GetLineCount()) file.CommentLine(nIndex);
1627 }
1628
1629 sTmp += wxT(";") + sCmd; //includes wxT(" %s ");
1630
1631 // write it in the format that Netscape uses (default)
1632 if (! ( m_mailcapStylesInited & wxMAILCAP_STANDARD ) )
1633 {
1634 if (! delete_index)
1635 file.InsertLine(sTmp, nIndex);
1636 nIndex++;
1637 }
1638 else
1639 {
1640 // write extended format
1641
1642 // TODO - FIX this code:
1643 // ii) lost entries
1644 // sOld holds all the entries, but our data store only has some
1645 // eg test= is not stored
1646
1647 // so far we have written the mimetype and command out
1648 wxStringTokenizer sT(sOld, wxT(";\\"));
1649 if (sT.CountTokens() > 2)
1650 {
1651 // first one mimetype; second one command, rest unknown...
1652 wxString s;
1653 s = sT.GetNextToken();
1654 s = sT.GetNextToken();
1655
1656 // first unknown
1657 s = sT.GetNextToken();
1658 while ( ! s.empty() )
1659 {
1660 bool bKnownToken = false;
1661 if (s.Contains(wxT("description=")))
1662 bKnownToken = true;
1663 if (s.Contains(wxT("x11-bitmap=")))
1664 bKnownToken = true;
1665
1666 size_t i;
1667 size_t nCount = entries->GetCount();
1668 for (i=0; i < nCount; i++)
1669 {
1670 if (s.Contains(entries->GetVerb(i)))
1671 bKnownToken = true;
1672 }
1673
1674 if (!bKnownToken)
1675 {
1676 sTmp += wxT("; \\");
1677 file.InsertLine(sTmp, nIndex);
1678 sTmp = s;
1679 }
1680
1681 s = sT.GetNextToken();
1682 }
1683 }
1684
1685 if (! m_aDescriptions[index].empty() )
1686 {
1687 sTmp += wxT("; \\");
1688 file.InsertLine(sTmp, nIndex);
1689 nIndex++;
1690 sTmp = wxT(" description=\"") + m_aDescriptions[index] + wxT("\"");
1691 }
1692
1693 if (! m_aIcons[index].empty() )
1694 {
1695 sTmp += wxT("; \\");
1696 file.InsertLine(sTmp, nIndex);
1697 nIndex++;
1698 sTmp = wxT(" x11-bitmap=\"") + m_aIcons[index] + wxT("\"");
1699 }
1700
1701 if ( entries->GetCount() > 1 )
1702 {
1703 size_t i;
1704 for (i=0; i < entries->GetCount(); i++)
1705 if ( i != iOpen )
1706 {
1707 sTmp += wxT("; \\");
1708 file.InsertLine(sTmp, nIndex);
1709 nIndex++;
1710 sTmp = wxT(" ") + entries->GetVerbCmd(i);
1711 }
1712 }
1713
1714 file.InsertLine(sTmp, nIndex);
1715 nIndex++;
1716 }
1717
1718 bTemp = file.Write();
1719 file.Close();
1720 }
1721
1722 return bTemp;
1723 }
1724
1725 wxFileType * wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
1726 {
1727 InitIfNeeded();
1728
1729 wxString strType = ftInfo.GetMimeType();
1730 wxString strDesc = ftInfo.GetDescription();
1731 wxString strIcon = ftInfo.GetIconFile();
1732
1733 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
1734
1735 if ( ! ftInfo.GetOpenCommand().empty())
1736 entry->Add(wxT("open=") + ftInfo.GetOpenCommand() + wxT(" %s "));
1737 if ( ! ftInfo.GetPrintCommand().empty())
1738 entry->Add(wxT("print=") + ftInfo.GetPrintCommand() + wxT(" %s "));
1739
1740 // now find where these extensions are in the data store and remove them
1741 wxArrayString sA_Exts = ftInfo.GetExtensions();
1742 wxString sExt, sExtStore;
1743 size_t i, nIndex;
1744 size_t nExtCount = sA_Exts.GetCount();
1745 for (i=0; i < nExtCount; i++)
1746 {
1747 sExt = sA_Exts.Item(i);
1748
1749 // clean up to just a space before and after
1750 sExt.Trim().Trim(false);
1751 sExt = wxT(' ') + sExt + wxT(' ');
1752 size_t nCount = m_aExtensions.GetCount();
1753 for (nIndex = 0; nIndex < nCount; nIndex++)
1754 {
1755 sExtStore = m_aExtensions.Item(nIndex);
1756 if (sExtStore.Replace(sExt, wxT(" ") ) > 0)
1757 m_aExtensions.Item(nIndex) = sExtStore;
1758 }
1759 }
1760
1761 if ( !DoAssociation(strType, strIcon, entry, sA_Exts, strDesc) )
1762 return NULL;
1763
1764 return GetFileTypeFromMimeType(strType);
1765 }
1766
1767 bool wxMimeTypesManagerImpl::DoAssociation(const wxString& strType,
1768 const wxString& strIcon,
1769 wxMimeTypeCommands *entry,
1770 const wxArrayString& strExtensions,
1771 const wxString& strDesc)
1772 {
1773 int nIndex = AddToMimeData(strType, strIcon, entry, strExtensions, strDesc, true);
1774
1775 if ( nIndex == wxNOT_FOUND )
1776 return false;
1777
1778 return WriteMimeInfo(nIndex, false);
1779 }
1780
1781 bool wxMimeTypesManagerImpl::WriteMimeInfo(int nIndex, bool delete_mime )
1782 {
1783 bool ok = true;
1784
1785 if ( m_mailcapStylesInited & wxMAILCAP_STANDARD )
1786 {
1787 // write in metamail format;
1788 if (WriteToMimeTypes(nIndex, delete_mime) )
1789 if ( WriteToMailCap(nIndex, delete_mime) )
1790 ok = false;
1791 }
1792
1793 if ( m_mailcapStylesInited & wxMAILCAP_NETSCAPE )
1794 {
1795 // write in netsacpe format;
1796 if (WriteToNSMimeTypes(nIndex, delete_mime) )
1797 if ( WriteToMailCap(nIndex, delete_mime) )
1798 ok = false;
1799 }
1800
1801 // Don't write GNOME files here as this is not
1802 // allowed and simply doesn't work
1803
1804 if (m_mailcapStylesInited & wxMAILCAP_KDE)
1805 {
1806 // write in KDE format;
1807 if (WriteKDEMimeFile(nIndex, delete_mime) )
1808 ok = false;
1809 }
1810
1811 return ok;
1812 }
1813
1814 int wxMimeTypesManagerImpl::AddToMimeData(const wxString& strType,
1815 const wxString& strIcon,
1816 wxMimeTypeCommands *entry,
1817 const wxArrayString& strExtensions,
1818 const wxString& strDesc,
1819 bool replaceExisting)
1820 {
1821 InitIfNeeded();
1822
1823 // ensure mimetype is always lower case
1824 wxString mimeType = strType.Lower();
1825
1826 // is this a known MIME type?
1827 int nIndex = m_aTypes.Index(mimeType);
1828 if ( nIndex == wxNOT_FOUND )
1829 {
1830 // new file type
1831 m_aTypes.Add(mimeType);
1832 m_aIcons.Add(strIcon);
1833 m_aEntries.Add(entry ? entry : new wxMimeTypeCommands);
1834
1835 // change nIndex so we can use it below to add the extensions
1836 m_aExtensions.Add(wxEmptyString);
1837 nIndex = m_aExtensions.size() - 1;
1838
1839 m_aDescriptions.Add(strDesc);
1840 }
1841 else // yes, we already have it
1842 {
1843 if ( replaceExisting )
1844 {
1845 // if new description change it
1846 if ( !strDesc.empty())
1847 m_aDescriptions[nIndex] = strDesc;
1848
1849 // if new icon change it
1850 if ( !strIcon.empty())
1851 m_aIcons[nIndex] = strIcon;
1852
1853 if ( entry )
1854 {
1855 delete m_aEntries[nIndex];
1856 m_aEntries[nIndex] = entry;
1857 }
1858 }
1859 else // add data we don't already have ...
1860 {
1861 // if new description add only if none
1862 if ( m_aDescriptions[nIndex].empty() )
1863 m_aDescriptions[nIndex] = strDesc;
1864
1865 // if new icon and no existing icon
1866 if ( m_aIcons[nIndex].empty() )
1867 m_aIcons[nIndex] = strIcon;
1868
1869 // add any new entries...
1870 if ( entry )
1871 {
1872 wxMimeTypeCommands *entryOld = m_aEntries[nIndex];
1873
1874 size_t count = entry->GetCount();
1875 for ( size_t i = 0; i < count; i++ )
1876 {
1877 const wxString& verb = entry->GetVerb(i);
1878 if ( !entryOld->HasVerb(verb) )
1879 {
1880 entryOld->AddOrReplaceVerb(verb, entry->GetCmd(i));
1881 }
1882 }
1883
1884 // as we don't store it anywhere, it won't be deleted later as
1885 // usual -- do it immediately instead
1886 delete entry;
1887 }
1888 }
1889 }
1890
1891 // always add the extensions to this mimetype
1892 wxString& exts = m_aExtensions[nIndex];
1893
1894 // add all extensions we don't have yet
1895 wxString ext;
1896 size_t count = strExtensions.GetCount();
1897 for ( size_t i = 0; i < count; i++ )
1898 {
1899 ext = strExtensions[i];
1900 ext += wxT(' ');
1901
1902 if ( exts.Find(ext) == wxNOT_FOUND )
1903 {
1904 exts += ext;
1905 }
1906 }
1907
1908 // check data integrity
1909 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1910 m_aTypes.Count() == m_aExtensions.Count() &&
1911 m_aTypes.Count() == m_aIcons.Count() &&
1912 m_aTypes.Count() == m_aDescriptions.Count() );
1913
1914 return nIndex;
1915 }
1916
1917 wxFileType * wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1918 {
1919 if (ext.empty() )
1920 return NULL;
1921
1922 InitIfNeeded();
1923
1924 size_t count = m_aExtensions.GetCount();
1925 for ( size_t n = 0; n < count; n++ )
1926 {
1927 wxStringTokenizer tk(m_aExtensions[n], wxT(' '));
1928
1929 while ( tk.HasMoreTokens() )
1930 {
1931 // consider extensions as not being case-sensitive
1932 if ( tk.GetNextToken().IsSameAs(ext, false /* no case */) )
1933 {
1934 // found
1935 wxFileType *fileType = new wxFileType;
1936 fileType->m_impl->Init(this, n);
1937
1938 return fileType;
1939 }
1940 }
1941 }
1942
1943 return NULL;
1944 }
1945
1946 wxFileType * wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1947 {
1948 InitIfNeeded();
1949
1950 wxFileType * fileType = NULL;
1951 // mime types are not case-sensitive
1952 wxString mimetype(mimeType);
1953 mimetype.MakeLower();
1954
1955 // first look for an exact match
1956 int index = m_aTypes.Index(mimetype);
1957 if ( index != wxNOT_FOUND )
1958 {
1959 fileType = new wxFileType;
1960 fileType->m_impl->Init(this, index);
1961 }
1962
1963 // then try to find "text/*" as match for "text/plain" (for example)
1964 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1965 // the whole string - ok.
1966
1967 index = wxNOT_FOUND;
1968 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
1969
1970 size_t nCount = m_aTypes.Count();
1971 for ( size_t n = 0; n < nCount; n++ )
1972 {
1973 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
1974 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") )
1975 {
1976 index = n;
1977 break;
1978 }
1979 }
1980
1981 if ( index != wxNOT_FOUND )
1982 {
1983 // don't throw away fileType that was already found
1984 if (!fileType)
1985 fileType = new wxFileType;
1986 fileType->m_impl->Init(this, index);
1987 }
1988
1989 return fileType;
1990 }
1991
1992 wxString wxMimeTypesManagerImpl::GetCommand(const wxString & verb, size_t nIndex) const
1993 {
1994 wxString command, testcmd, sV, sTmp;
1995 sV = verb + wxT("=");
1996
1997 // list of verb = command pairs for this mimetype
1998 wxMimeTypeCommands * sPairs = m_aEntries [nIndex];
1999
2000 size_t i;
2001 size_t nCount = sPairs->GetCount();
2002 for ( i = 0; i < nCount; i++ )
2003 {
2004 sTmp = sPairs->GetVerbCmd (i);
2005 if ( sTmp.Contains(sV) )
2006 command = sTmp.AfterFirst(wxT('='));
2007 }
2008
2009 return command;
2010 }
2011
2012 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
2013 {
2014 InitIfNeeded();
2015
2016 wxString extensions;
2017 const wxArrayString& exts = filetype.GetExtensions();
2018 size_t nExts = exts.GetCount();
2019 for ( size_t nExt = 0; nExt < nExts; nExt++ )
2020 {
2021 if ( nExt > 0 )
2022 extensions += wxT(' ');
2023
2024 extensions += exts[nExt];
2025 }
2026
2027 AddMimeTypeInfo(filetype.GetMimeType(),
2028 extensions,
2029 filetype.GetDescription());
2030
2031 AddMailcapInfo(filetype.GetMimeType(),
2032 filetype.GetOpenCommand(),
2033 filetype.GetPrintCommand(),
2034 wxT(""),
2035 filetype.GetDescription());
2036 }
2037
2038 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
2039 const wxString& strExtensions,
2040 const wxString& strDesc)
2041 {
2042 // reading mailcap may find image/* , while
2043 // reading mime.types finds image/gif and no match is made
2044 // this means all the get functions don't work fix this
2045 wxString strIcon;
2046 wxString sTmp = strExtensions;
2047
2048 wxArrayString sExts;
2049 sTmp.Trim().Trim(false);
2050
2051 while (!sTmp.empty())
2052 {
2053 sExts.Add(sTmp.AfterLast(wxT(' ')));
2054 sTmp = sTmp.BeforeLast(wxT(' '));
2055 }
2056
2057 AddToMimeData(strMimeType, strIcon, NULL, sExts, strDesc, true);
2058 }
2059
2060 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
2061 const wxString& strOpenCmd,
2062 const wxString& strPrintCmd,
2063 const wxString& strTest,
2064 const wxString& strDesc)
2065 {
2066 InitIfNeeded();
2067
2068 wxMimeTypeCommands *entry = new wxMimeTypeCommands;
2069 entry->Add(wxT("open=") + strOpenCmd);
2070 entry->Add(wxT("print=") + strPrintCmd);
2071 entry->Add(wxT("test=") + strTest);
2072
2073 wxString strIcon;
2074 wxArrayString strExtensions;
2075
2076 AddToMimeData(strType, strIcon, entry, strExtensions, strDesc, true);
2077 }
2078
2079 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
2080 {
2081 wxLogTrace(TRACE_MIME, wxT("--- Parsing mime.types file '%s' ---"),
2082 strFileName.c_str());
2083
2084 wxTextFile file(strFileName);
2085 #if defined(__WXGTK20__) && wxUSE_UNICODE
2086 if ( !file.Open(wxConvUTF8) )
2087 #else
2088 if ( !file.Open() )
2089 #endif
2090 return false;
2091
2092 // the information we extract
2093 wxString strMimeType, strDesc, strExtensions;
2094
2095 size_t nLineCount = file.GetLineCount();
2096 const wxChar *pc = NULL;
2097 for ( size_t nLine = 0; nLine < nLineCount; nLine++ )
2098 {
2099 if ( pc == NULL )
2100 {
2101 // now we're at the start of the line
2102 pc = file[nLine].c_str();
2103 }
2104 else
2105 {
2106 // we didn't finish with the previous line yet
2107 nLine--;
2108 }
2109
2110 // skip whitespace
2111 while ( wxIsspace(*pc) )
2112 pc++;
2113
2114 // comment or blank line?
2115 if ( *pc == wxT('#') || !*pc )
2116 {
2117 // skip the whole line
2118 pc = NULL;
2119 continue;
2120 }
2121
2122 // detect file format
2123 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
2124 if ( pEqualSign == NULL )
2125 {
2126 // brief format
2127 // ------------
2128
2129 // first field is mime type
2130 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ )
2131 {
2132 strMimeType += *pc;
2133 }
2134
2135 // skip whitespace
2136 while ( wxIsspace(*pc) )
2137 pc++;
2138
2139 // take all the rest of the string
2140 strExtensions = pc;
2141
2142 // no description...
2143 strDesc.Empty();
2144 }
2145 else
2146 {
2147 // expanded format
2148 // ---------------
2149
2150 // the string on the left of '=' is the field name
2151 wxString strLHS(pc, pEqualSign - pc);
2152
2153 // eat whitespace
2154 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
2155 ;
2156
2157 const wxChar *pEnd;
2158 if ( *pc == wxT('"') )
2159 {
2160 // the string is quoted and ends at the matching quote
2161 pEnd = wxStrchr(++pc, wxT('"'));
2162 if ( pEnd == NULL )
2163 {
2164 wxLogWarning(wxT("Mime.types file %s, line %lu: unterminated quoted string."),
2165 strFileName.c_str(), nLine + 1L);
2166 }
2167 }
2168 else
2169 {
2170 // unquoted string ends at the first space or at the end of
2171 // line
2172 for ( pEnd = pc; *pEnd && !wxIsspace(*pEnd); pEnd++ )
2173 ;
2174 }
2175
2176 // now we have the RHS (field value)
2177 wxString strRHS(pc, pEnd - pc);
2178
2179 // check what follows this entry
2180 if ( *pEnd == wxT('"') )
2181 {
2182 // skip this quote
2183 pEnd++;
2184 }
2185
2186 for ( pc = pEnd; wxIsspace(*pc); pc++ )
2187 ;
2188
2189 // if there is something left, it may be either a '\\' to continue
2190 // the line or the next field of the same entry
2191 bool entryEnded = *pc == wxT('\0');
2192 bool nextFieldOnSameLine = false;
2193 if ( !entryEnded )
2194 {
2195 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
2196 }
2197
2198 // now see what we got
2199 if ( strLHS == wxT("type") )
2200 {
2201 strMimeType = strRHS;
2202 }
2203 else if ( strLHS.StartsWith(wxT("desc")) )
2204 {
2205 strDesc = strRHS;
2206 }
2207 else if ( strLHS == wxT("exts") )
2208 {
2209 strExtensions = strRHS;
2210 }
2211 else if ( strLHS == wxT("icon") )
2212 {
2213 // this one is simply ignored: it usually refers to Netscape
2214 // built in icons which are useless for us anyhow
2215 }
2216 else if ( !strLHS.StartsWith(wxT("x-")) )
2217 {
2218 // we suppose that all fields starting with "X-" are
2219 // unregistered extensions according to the standard practice,
2220 // but it may be worth telling the user about other junk in
2221 // his mime.types file
2222 wxLogWarning(wxT("Unknown field in file %s, line %lu: '%s'."),
2223 strFileName.c_str(), nLine + 1L, strLHS.c_str());
2224 }
2225
2226 if ( !entryEnded )
2227 {
2228 if ( !nextFieldOnSameLine )
2229 pc = NULL;
2230 //else: don't reset it
2231
2232 // as we don't reset strMimeType, the next field in this entry
2233 // will be interpreted correctly.
2234
2235 continue;
2236 }
2237 }
2238
2239 // depending on the format (Mosaic or Netscape) either space or comma
2240 // is used to separate the extensions
2241 strExtensions.Replace(wxT(","), wxT(" "));
2242
2243 // also deal with the leading dot
2244 if ( !strExtensions.empty() && strExtensions[0u] == wxT('.') )
2245 {
2246 strExtensions.erase(0, 1);
2247 }
2248
2249 wxLogTrace(TRACE_MIME, wxT("mime.types: '%s' => '%s' (%s)"),
2250 strExtensions.c_str(),
2251 strMimeType.c_str(),
2252 strDesc.c_str());
2253
2254 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
2255
2256 // finished with this line
2257 pc = NULL;
2258 }
2259
2260 return true;
2261 }
2262
2263 // ----------------------------------------------------------------------------
2264 // UNIX mailcap files parsing
2265 // ----------------------------------------------------------------------------
2266
2267 // the data for a single MIME type
2268 struct MailcapLineData
2269 {
2270 // field values
2271 wxString type,
2272 cmdOpen,
2273 test,
2274 icon,
2275 desc;
2276
2277 wxArrayString verbs,
2278 commands;
2279
2280 // flags
2281 bool testfailed,
2282 needsterminal,
2283 copiousoutput;
2284
2285 MailcapLineData() { testfailed = needsterminal = copiousoutput = false; }
2286 };
2287
2288 // process a non-standard (i.e. not the first or second one) mailcap field
2289 bool
2290 wxMimeTypesManagerImpl::ProcessOtherMailcapField(MailcapLineData& data,
2291 const wxString& curField)
2292 {
2293 if ( curField.empty() )
2294 {
2295 // we don't care
2296 return true;
2297 }
2298
2299 // is this something of the form foo=bar?
2300 const wxChar *pEq = wxStrchr(curField, wxT('='));
2301 if ( pEq != NULL )
2302 {
2303 // split "LHS = RHS" in 2
2304 wxString lhs = curField.BeforeFirst(wxT('=')),
2305 rhs = curField.AfterFirst(wxT('='));
2306
2307 lhs.Trim(true); // from right
2308 rhs.Trim(false); // from left
2309
2310 // it might be quoted
2311 if ( !rhs.empty() && rhs[0u] == wxT('"') && rhs.Last() == wxT('"') )
2312 {
2313 rhs = rhs.Mid(1, rhs.length() - 2);
2314 }
2315
2316 // is it a command verb or something else?
2317 if ( lhs == wxT("test") )
2318 {
2319 if ( wxSystem(rhs) == 0 )
2320 {
2321 // ok, test passed
2322 wxLogTrace(TRACE_MIME_TEST,
2323 wxT("Test '%s' for mime type '%s' succeeded."),
2324 rhs.c_str(), data.type.c_str());
2325 }
2326 else
2327 {
2328 wxLogTrace(TRACE_MIME_TEST,
2329 wxT("Test '%s' for mime type '%s' failed, skipping."),
2330 rhs.c_str(), data.type.c_str());
2331
2332 data.testfailed = true;
2333 }
2334 }
2335 else if ( lhs == wxT("desc") )
2336 {
2337 data.desc = rhs;
2338 }
2339 else if ( lhs == wxT("x11-bitmap") )
2340 {
2341 data.icon = rhs;
2342 }
2343 else if ( lhs == wxT("notes") )
2344 {
2345 // ignore
2346 }
2347 else // not a (recognized) special case, must be a verb (e.g. "print")
2348 {
2349 data.verbs.Add(lhs);
2350 data.commands.Add(rhs);
2351 }
2352 }
2353 else // '=' not found
2354 {
2355 // so it must be a simple flag
2356 if ( curField == wxT("needsterminal") )
2357 {
2358 data.needsterminal = true;
2359 }
2360 else if ( curField == wxT("copiousoutput"))
2361 {
2362 // copiousoutput impies that the viewer is a console program
2363 data.needsterminal =
2364 data.copiousoutput = true;
2365 }
2366 else if ( !IsKnownUnimportantField(curField) )
2367 {
2368 return false;
2369 }
2370 }
2371
2372 return true;
2373 }
2374
2375 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
2376 bool fallback)
2377 {
2378 wxLogTrace(TRACE_MIME, wxT("--- Parsing mailcap file '%s' ---"),
2379 strFileName.c_str());
2380
2381 wxTextFile file(strFileName);
2382 #if defined(__WXGTK20__) && wxUSE_UNICODE
2383 if ( !file.Open(wxConvUTF8) )
2384 #else
2385 if ( !file.Open() )
2386 #endif
2387 return false;
2388
2389 // indices of MIME types (in m_aTypes) we already found in this file
2390 //
2391 // (see the comments near the end of function for the reason we need this)
2392 wxArrayInt aIndicesSeenHere;
2393
2394 // accumulator for the current field
2395 wxString curField;
2396 curField.reserve(1024);
2397
2398 const wxChar *pPagerEnv = wxGetenv(wxT("PAGER"));
2399
2400 const wxArrayString empty_extensions_list;
2401
2402 size_t nLineCount = file.GetLineCount();
2403 for ( size_t nLine = 0; nLine < nLineCount; nLine++ )
2404 {
2405 // now we're at the start of the line
2406 const wxChar *pc = file[nLine].c_str();
2407
2408 // skip whitespace
2409 while ( wxIsspace(*pc) )
2410 pc++;
2411
2412 // comment or empty string?
2413 if ( *pc == wxT('#') || *pc == wxT('\0') )
2414 continue;
2415
2416 // no, do parse
2417 // ------------
2418
2419 // what field are we currently in? The first 2 are fixed and there may
2420 // be an arbitrary number of other fields parsed by
2421 // ProcessOtherMailcapField()
2422 //
2423 // the first field is the MIME type
2424 enum
2425 {
2426 Field_Type,
2427 Field_OpenCmd,
2428 Field_Other
2429 }
2430 currentToken = Field_Type;
2431
2432 // the flags and field values on the current line
2433 MailcapLineData data;
2434
2435 bool cont = true;
2436 while ( cont )
2437 {
2438 switch ( *pc )
2439 {
2440 case wxT('\\'):
2441 // interpret the next character literally (notice that
2442 // backslash can be used for line continuation)
2443 if ( *++pc == wxT('\0') )
2444 {
2445 // fetch the next line if there is one
2446 if ( nLine == nLineCount - 1 )
2447 {
2448 // something is wrong, bail out
2449 cont = false;
2450
2451 wxLogDebug(wxT("Mailcap file %s, line %lu: '\\' on the end of the last line ignored."),
2452 strFileName.c_str(),
2453 nLine + 1L);
2454 }
2455 else
2456 {
2457 // pass to the beginning of the next line
2458 pc = file[++nLine].c_str();
2459
2460 // skip pc++ at the end of the loop
2461 continue;
2462 }
2463 }
2464 else
2465 {
2466 // just a normal character
2467 curField += *pc;
2468 }
2469 break;
2470
2471 case wxT('\0'):
2472 cont = false; // end of line reached, exit the loop
2473
2474 // fall through to still process this field
2475
2476 case wxT(';'):
2477 // trim whitespaces from both sides
2478 curField.Trim(true).Trim(false);
2479
2480 switch ( currentToken )
2481 {
2482 case Field_Type:
2483 data.type = curField.Lower();
2484 if ( data.type.empty() )
2485 {
2486 // I don't think that this is a valid mailcap
2487 // entry, but try to interpret it somehow
2488 data.type = wxT('*');
2489 }
2490
2491 if ( data.type.Find(wxT('/')) == wxNOT_FOUND )
2492 {
2493 // we interpret "type" as "type/*"
2494 data.type += wxT("/*");
2495 }
2496
2497 currentToken = Field_OpenCmd;
2498 break;
2499
2500 case Field_OpenCmd:
2501 data.cmdOpen = curField;
2502
2503 currentToken = Field_Other;
2504 break;
2505
2506 case Field_Other:
2507 if ( !ProcessOtherMailcapField(data, curField) )
2508 {
2509 // don't flood the user with error messages if
2510 // we don't understand something in his
2511 // mailcap, but give them in debug mode because
2512 // this might be useful for the programmer
2513 wxLogDebug
2514 (
2515 wxT("Mailcap file %s, line %lu: unknown field '%s' for the MIME type '%s' ignored."),
2516 strFileName.c_str(),
2517 nLine + 1L,
2518 curField.c_str(),
2519 data.type.c_str()
2520 );
2521 }
2522 else if ( data.testfailed )
2523 {
2524 // skip this entry entirely
2525 cont = false;
2526 }
2527
2528 // it already has this value
2529 //currentToken = Field_Other;
2530 break;
2531
2532 default:
2533 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2534 }
2535
2536 // next token starts immediately after ';'
2537 curField.Empty();
2538 break;
2539
2540 default:
2541 curField += *pc;
2542 }
2543
2544 // continue in the same line
2545 pc++;
2546 }
2547
2548 // we read the entire entry, check what have we got
2549 // ------------------------------------------------
2550
2551 // check that we really read something reasonable
2552 if ( currentToken < Field_Other )
2553 {
2554 wxLogWarning(wxT("Mailcap file %s, line %lu: incomplete entry ignored."),
2555 strFileName.c_str(), nLine + 1L);
2556
2557 continue;
2558 }
2559
2560 // if the test command failed, it's as if the entry were not there at all
2561 if ( data.testfailed )
2562 {
2563 continue;
2564 }
2565
2566 // support for flags:
2567 // 1. create an xterm for 'needsterminal'
2568 // 2. append "| $PAGER" for 'copiousoutput'
2569 //
2570 // Note that the RFC says that having both needsterminal and
2571 // copiousoutput is probably a mistake, so it seems that running
2572 // programs with copiousoutput inside an xterm as it is done now
2573 // is a bad idea (FIXME)
2574 if ( data.copiousoutput )
2575 {
2576 data.cmdOpen << wxT(" | ") << (pPagerEnv ? pPagerEnv : wxT("more"));
2577 }
2578
2579 if ( data.needsterminal )
2580 {
2581 data.cmdOpen.Printf(wxT("xterm -e sh -c '%s'"),
2582 data.cmdOpen.c_str());
2583 }
2584
2585 if ( !data.cmdOpen.empty() )
2586 {
2587 data.verbs.Insert(wxT("open"), 0);
2588 data.commands.Insert(data.cmdOpen, 0);
2589 }
2590
2591 // we have to decide whether the new entry should replace any entries
2592 // for the same MIME type we had previously found or not
2593 bool overwrite;
2594
2595 // the fall back entries have the lowest priority, by definition
2596 if ( fallback )
2597 {
2598 overwrite = false;
2599 }
2600 else
2601 {
2602 // have we seen this one before?
2603 int nIndex = m_aTypes.Index(data.type);
2604
2605 // and if we have, was it in this file? if not, we should
2606 // overwrite the previously seen one
2607 overwrite = nIndex == wxNOT_FOUND ||
2608 aIndicesSeenHere.Index(nIndex) == wxNOT_FOUND;
2609 }
2610
2611 wxLogTrace(TRACE_MIME, wxT("mailcap %s: %s [%s]"),
2612 data.type.c_str(), data.cmdOpen.c_str(),
2613 overwrite ? wxT("replace") : wxT("add"));
2614
2615 int n = AddToMimeData
2616 (
2617 data.type,
2618 data.icon,
2619 new wxMimeTypeCommands(data.verbs, data.commands),
2620 empty_extensions_list,
2621 data.desc,
2622 overwrite
2623 );
2624
2625 if ( overwrite )
2626 {
2627 aIndicesSeenHere.Add(n);
2628 }
2629 }
2630
2631 return true;
2632 }
2633
2634 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
2635 {
2636 InitIfNeeded();
2637
2638 mimetypes.Empty();
2639
2640 size_t count = m_aTypes.GetCount();
2641 for ( size_t n = 0; n < count; n++ )
2642 {
2643 // don't return template types from here (i.e. anything containg '*')
2644 const wxString &type = m_aTypes[n];
2645 if ( type.Find(wxT('*')) == wxNOT_FOUND )
2646 {
2647 mimetypes.Add(type);
2648 }
2649 }
2650
2651 return mimetypes.GetCount();
2652 }
2653
2654 // ----------------------------------------------------------------------------
2655 // writing to MIME type files
2656 // ----------------------------------------------------------------------------
2657
2658 bool wxMimeTypesManagerImpl::Unassociate(wxFileType *ft)
2659 {
2660 InitIfNeeded();
2661
2662 wxArrayString sMimeTypes;
2663 ft->GetMimeTypes(sMimeTypes);
2664
2665 size_t i;
2666 size_t nCount = sMimeTypes.GetCount();
2667 for (i = 0; i < nCount; i ++)
2668 {
2669 const wxString &sMime = sMimeTypes.Item(i);
2670 int nIndex = m_aTypes.Index(sMime);
2671 if ( nIndex == wxNOT_FOUND)
2672 {
2673 // error if we get here ??
2674 return false;
2675 }
2676 else
2677 {
2678 WriteMimeInfo(nIndex, true);
2679 m_aTypes.RemoveAt(nIndex);
2680 m_aEntries.RemoveAt(nIndex);
2681 m_aExtensions.RemoveAt(nIndex);
2682 m_aDescriptions.RemoveAt(nIndex);
2683 m_aIcons.RemoveAt(nIndex);
2684 }
2685 }
2686 // check data integrity
2687 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
2688 m_aTypes.Count() == m_aExtensions.Count() &&
2689 m_aTypes.Count() == m_aIcons.Count() &&
2690 m_aTypes.Count() == m_aDescriptions.Count() );
2691
2692 return true;
2693 }
2694
2695 // ----------------------------------------------------------------------------
2696 // private functions
2697 // ----------------------------------------------------------------------------
2698
2699 static bool IsKnownUnimportantField(const wxString& fieldAll)
2700 {
2701 static const wxChar * const knownFields[] =
2702 {
2703 wxT("x-mozilla-flags"),
2704 wxT("nametemplate"),
2705 wxT("textualnewlines"),
2706 };
2707
2708 wxString field = fieldAll.BeforeFirst(wxT('='));
2709 for ( size_t n = 0; n < WXSIZEOF(knownFields); n++ )
2710 {
2711 if ( field.CmpNoCase(knownFields[n]) == 0 )
2712 return true;
2713 }
2714
2715 return false;
2716 }
2717
2718 #endif
2719 // wxUSE_MIMETYPE && wxUSE_FILE && wxUSE_TEXTFILE