added GNOME mimeinfo parsing & some fixes for non-XPM icons
[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 license (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "mimetype.h"
14 #endif
15
16 // for compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #ifndef WX_PRECOMP
24 #include "wx/defs.h"
25 #endif
26
27 #if (wxUSE_FILE && wxUSE_TEXTFILE) || defined(__WXMSW__)
28
29 #ifndef WX_PRECOMP
30 #include "wx/string.h"
31 #if wxUSE_GUI
32 #include "wx/icon.h"
33 #endif
34 #endif //WX_PRECOMP
35
36
37 #include "wx/log.h"
38 #include "wx/file.h"
39 #include "wx/intl.h"
40 #include "wx/dynarray.h"
41 #include "wx/confbase.h"
42
43 #include "wx/ffile.h"
44 #include "wx/textfile.h"
45 #include "wx/dir.h"
46 #include "wx/utils.h"
47 #include "wx/tokenzr.h"
48
49 #include "wx/unix/mimetype.h"
50
51 // other standard headers
52 #include <ctype.h>
53
54 // in case we're compiling in non-GUI mode
55 class WXDLLEXPORT wxIcon;
56
57 // ----------------------------------------------------------------------------
58 // private classes
59 // ----------------------------------------------------------------------------
60
61
62 // this class uses both mailcap and mime.types to gather information about file
63 // types.
64 //
65 // The information about mailcap file was extracted from metamail(1) sources and
66 // documentation.
67 //
68 // Format of mailcap file: spaces are ignored, each line is either a comment
69 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
70 // A backslash can be used to quote semicolons and newlines (and, in fact,
71 // anything else including itself).
72 //
73 // The first field is always the MIME type in the form of type/subtype (see RFC
74 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
75 // "type" which means the same as "type/*", although I'm not sure whether this
76 // is standard.
77 //
78 // The second field is always the command to run. It is subject to
79 // parameter/filename expansion described below.
80 //
81 // All the following fields are optional and may not be present at all. If
82 // they're present they may appear in any order, although each of them should
83 // appear only once. The optional fields are the following:
84 // * notes=xxx is an uninterpreted string which is silently ignored
85 // * test=xxx is the command to be used to determine whether this mailcap line
86 // applies to our data or not. The RHS of this field goes through the
87 // parameter/filename expansion (as the 2nd field) and the resulting string
88 // is executed. The line applies only if the command succeeds, i.e. returns 0
89 // exit code.
90 // * print=xxx is the command to be used to print (and not view) the data of
91 // this type (parameter/filename expansion is done here too)
92 // * edit=xxx is the command to open/edit the data of this type
93 // * needsterminal means that a new console must be created for the viewer
94 // * copiousoutput means that the viewer doesn't interact with the user but
95 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
96 // good example), thus it might be a good idea to use some kind of paging
97 // mechanism.
98 // * textualnewlines means not to perform CR/LF translation (not honored)
99 // * compose and composetyped fields are used to determine the program to be
100 // called to create a new message pert in the specified format (unused).
101 //
102 // Parameter/filename xpansion:
103 // * %s is replaced with the (full) file name
104 // * %t is replaced with MIME type/subtype of the entry
105 // * for multipart type only %n is replaced with the nnumber of parts and %F is
106 // replaced by an array of (content-type, temporary file name) pairs for all
107 // message parts (TODO)
108 // * %{parameter} is replaced with the value of parameter taken from
109 // Content-type header line of the message.
110 //
111 // FIXME any docs with real descriptions of these files??
112 //
113 // There are 2 possible formats for mime.types file, one entry per line (used
114 // for global mime.types) and "expanded" format where an entry takes multiple
115 // lines (used for users mime.types).
116 //
117 // For both formats spaces are ignored and lines starting with a '#' are
118 // comments. Each record has one of two following forms:
119 // a) for "brief" format:
120 // <mime type> <space separated list of extensions>
121 // b) for "expanded" format:
122 // type=<mime type> \ desc="<description>" \ exts="ext"
123 //
124 // We try to autodetect the format of mime.types: if a non-comment line starts
125 // with "type=" we assume the second format, otherwise the first one.
126
127 // there may be more than one entry for one and the same mime type, to
128 // choose the right one we have to run the command specified in the test
129 // field on our data.
130 class MailCapEntry
131 {
132 public:
133 // ctor
134 MailCapEntry(const wxString& openCmd,
135 const wxString& printCmd,
136 const wxString& testCmd)
137 : m_openCmd(openCmd), m_printCmd(printCmd), m_testCmd(testCmd)
138 {
139 m_next = NULL;
140 }
141
142 // accessors
143 const wxString& GetOpenCmd() const { return m_openCmd; }
144 const wxString& GetPrintCmd() const { return m_printCmd; }
145 const wxString& GetTestCmd() const { return m_testCmd; }
146
147 MailCapEntry *GetNext() const { return m_next; }
148
149 // operations
150 // prepend this element to the list
151 void Prepend(MailCapEntry *next) { m_next = next; }
152 // insert into the list at given position
153 void Insert(MailCapEntry *next, size_t pos)
154 {
155 // FIXME slooow...
156 MailCapEntry *cur;
157 size_t n = 0;
158 for ( cur = next; cur != NULL; cur = cur->m_next, n++ ) {
159 if ( n == pos )
160 break;
161 }
162
163 wxASSERT_MSG( n == pos, wxT("invalid position in MailCapEntry::Insert") );
164
165 m_next = cur->m_next;
166 cur->m_next = this;
167 }
168 // append this element to the list
169 void Append(MailCapEntry *next)
170 {
171 wxCHECK_RET( next != NULL, wxT("Append()ing to what?") );
172
173 // FIXME slooow...
174 MailCapEntry *cur;
175 for ( cur = next; cur->m_next != NULL; cur = cur->m_next )
176 ;
177
178 cur->m_next = this;
179
180 wxASSERT_MSG( !m_next, wxT("Append()ing element already in the list?") );
181 }
182
183 private:
184 wxString m_openCmd, // command to use to open/view the file
185 m_printCmd, // print
186 m_testCmd; // only apply this entry if test yields
187 // true (i.e. the command returns 0)
188
189 MailCapEntry *m_next; // in the linked list
190 };
191
192
193 // the base class which may be used to find an icon for the MIME type
194 class wxMimeTypeIconHandler
195 {
196 public:
197 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon) = 0;
198
199 // this function fills manager with MIME types information gathered
200 // (as side effect) when searching for icons. This may be particularly
201 // useful if mime.types is incomplete (e.g. RedHat distributions).
202 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager) = 0;
203 };
204
205
206 // the icon handler which uses GNOME MIME database
207 class wxGNOMEIconHandler : public wxMimeTypeIconHandler
208 {
209 public:
210 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon);
211 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager) {}
212
213 private:
214 void Init();
215 void LoadIconsFromKeyFile(const wxString& filename);
216 void LoadKeyFilesFromDir(const wxString& dirbase);
217
218 static bool m_inited;
219
220 static wxSortedArrayString ms_mimetypes;
221 static wxArrayString ms_icons;
222 };
223
224 // the icon handler which uses KDE MIME database
225 class wxKDEIconHandler : public wxMimeTypeIconHandler
226 {
227 public:
228 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon);
229 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager);
230
231 private:
232 void LoadLinksForMimeSubtype(const wxString& dirbase,
233 const wxString& subdir,
234 const wxString& filename,
235 const wxArrayString& icondirs);
236 void LoadLinksForMimeType(const wxString& dirbase,
237 const wxString& subdir,
238 const wxArrayString& icondirs);
239 void LoadLinkFilesFromDir(const wxString& dirbase,
240 const wxArrayString& icondirs);
241 void Init();
242
243 static bool m_inited;
244
245 static wxSortedArrayString ms_mimetypes;
246 static wxArrayString ms_icons;
247
248 static wxArrayString ms_infoTypes;
249 static wxArrayString ms_infoDescriptions;
250 static wxArrayString ms_infoExtensions;
251 };
252
253
254
255 // ----------------------------------------------------------------------------
256 // various statics
257 // ----------------------------------------------------------------------------
258
259 static wxGNOMEIconHandler gs_iconHandlerGNOME;
260 static wxKDEIconHandler gs_iconHandlerKDE;
261
262 bool wxGNOMEIconHandler::m_inited = FALSE;
263 wxSortedArrayString wxGNOMEIconHandler::ms_mimetypes;
264 wxArrayString wxGNOMEIconHandler::ms_icons;
265
266 bool wxKDEIconHandler::m_inited = FALSE;
267 wxSortedArrayString wxKDEIconHandler::ms_mimetypes;
268 wxArrayString wxKDEIconHandler::ms_icons;
269
270 wxArrayString wxKDEIconHandler::ms_infoTypes;
271 wxArrayString wxKDEIconHandler::ms_infoDescriptions;
272 wxArrayString wxKDEIconHandler::ms_infoExtensions;
273
274
275 ArrayIconHandlers wxMimeTypesManagerImpl::ms_iconHandlers;
276
277 // ----------------------------------------------------------------------------
278 // wxGNOMEIconHandler
279 // ----------------------------------------------------------------------------
280
281 // GNOME stores the info we're interested in in several locations:
282 // 1. xxx.keys files under /usr/share/mime-info
283 // 2. xxx.keys files under ~/.gnome/mime-info
284 //
285 // The format of xxx.keys file is the following:
286 //
287 // mimetype/subtype:
288 // field=value
289 //
290 // with blank lines separating the entries and indented lines starting with
291 // TABs. We're interested in the field icon-filename whose value is the path
292 // containing the icon.
293
294 void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString& filename)
295 {
296 wxTextFile textfile(filename);
297 if ( !textfile.Open() )
298 return;
299
300 // values for the entry being parsed
301 wxString curMimeType, curIconFile;
302
303 const wxChar *pc;
304 size_t nLineCount = textfile.GetLineCount();
305 for ( size_t nLine = 0; ; nLine++ )
306 {
307 if ( nLine < nLineCount )
308 {
309 pc = textfile[nLine].c_str();
310 if ( *pc == _T('#') )
311 {
312 // skip comments
313 continue;
314 }
315 }
316 else
317 {
318 // so that we will fall into the "if" below
319 pc = NULL;
320 }
321
322 if ( !pc || !*pc )
323 {
324 // end of the entry
325 if ( !!curMimeType && !!curIconFile )
326 {
327 // do we already know this mimetype?
328 int i = ms_mimetypes.Index(curMimeType);
329 if ( i == wxNOT_FOUND )
330 {
331 // add a new entry
332 size_t n = ms_mimetypes.Add(curMimeType);
333 ms_icons.Insert(curIconFile, n);
334 }
335 else
336 {
337 // replace the existing one (this means that the directories
338 // should be searched in order of increased priority!)
339 ms_icons[(size_t)i] = curIconFile;
340 }
341 }
342
343 if ( !pc )
344 {
345 // the end - this can only happen if nLine == nLineCount
346 break;
347 }
348
349 curIconFile.Empty();
350
351 continue;
352 }
353
354 // what do we have here?
355 if ( *pc == _T('\t') )
356 {
357 // this is a field=value ling
358 pc++; // skip leading TAB
359
360 static const int lenField = 13; // strlen("icon-filename")
361 if ( wxStrncmp(pc, _T("icon-filename"), lenField) == 0 )
362 {
363 // skip '=' which follows and take everything left until the end
364 // of line
365 curIconFile = pc + lenField + 1;
366 }
367 //else: some other field, we don't care
368 }
369 else
370 {
371 // this is the start of the new section
372 curMimeType.Empty();
373
374 while ( *pc != _T(':') && *pc != _T('\0') )
375 {
376 curMimeType += *pc++;
377 }
378
379 if ( !*pc )
380 {
381 // we reached the end of line without finding the colon,
382 // something is wrong - ignore this line completely
383 wxLogDebug(_T("Unreckognized line %d in file '%s' ignored"),
384 nLine + 1, filename.c_str());
385
386 break;
387 }
388 }
389 }
390 }
391
392 void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString& dirbase)
393 {
394 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
395 _T("base directory shouldn't end with a slash") );
396
397 wxString dirname = dirbase;
398 dirname << _T("/mime-info");
399
400 if ( !wxDir::Exists(dirname) )
401 return;
402
403 wxDir dir(dirname);
404 if ( !dir.IsOpened() )
405 return;
406
407 // we will concatenate it with filename to get the full path below
408 dirname += _T('/');
409
410 wxString filename;
411 bool cont = dir.GetFirst(&filename, _T("*.keys"), wxDIR_FILES);
412 while ( cont )
413 {
414 LoadIconsFromKeyFile(dirname + filename);
415
416 cont = dir.GetNext(&filename);
417 }
418 }
419
420 void wxGNOMEIconHandler::Init()
421 {
422 wxArrayString dirs;
423 dirs.Add(_T("/usr/share"));
424 dirs.Add(_T("/usr/local/share"));
425
426 wxString gnomedir;
427 wxGetHomeDir( &gnomedir );
428 gnomedir += _T("/.gnome");
429 dirs.Add( gnomedir );
430
431 size_t nDirs = dirs.GetCount();
432 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
433 {
434 LoadKeyFilesFromDir(dirs[nDir]);
435 }
436
437 m_inited = TRUE;
438 }
439
440 bool wxGNOMEIconHandler::GetIcon(const wxString& mimetype, wxIcon *icon)
441 {
442 if ( !m_inited )
443 {
444 Init();
445 }
446
447 int index = ms_mimetypes.Index(mimetype);
448 if ( index == wxNOT_FOUND )
449 return FALSE;
450
451 wxString iconname = ms_icons[(size_t)index];
452
453 #if wxUSE_GUI
454 wxLogNull nolog;
455 wxIcon icn;
456 if (iconname.Right(4).MakeUpper() == _T(".XPM"))
457 icn = wxIcon(iconname);
458 else
459 icn = wxIcon(iconname, wxBITMAP_TYPE_ANY);
460 if (icn.Ok()) *icon = icn;
461 else return FALSE;
462 #else
463 // helpful for testing in console mode
464 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
465 mimetype.c_str(), iconname.c_str());
466 #endif
467
468 return TRUE;
469 }
470
471 // ----------------------------------------------------------------------------
472 // wxKDEIconHandler
473 // ----------------------------------------------------------------------------
474
475 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
476 // may be found in either of the following locations
477 //
478 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
479 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
480 //
481 // The format of a .kdelnk file is almost the same as the one used by
482 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
483 // value for the entry "Type"
484
485 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString& dirbase,
486 const wxString& subdir,
487 const wxString& filename,
488 const wxArrayString& icondirs)
489 {
490 wxFFile file(dirbase + filename);
491 if ( !file.IsOpened() )
492 return;
493
494 // construct mimetype from the directory name and the basename of the
495 // file (it always has .kdelnk extension)
496 wxString mimetype;
497 mimetype << subdir << _T('/') << filename.BeforeLast(_T('.'));
498
499 // these files are small, slurp the entire file at once
500 wxString text;
501 if ( !file.ReadAll(&text) )
502 return;
503
504 int pos;
505 const wxChar *pc;
506
507 // before trying to find an icon, grab mimetype information
508 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
509 // have edited it in control panel...)
510
511 wxString mime_extension, mime_desc;
512
513 pos = wxNOT_FOUND;
514 if (wxGetLocale() != NULL)
515 mime_desc = _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
516 if (pos == wxNOT_FOUND) mime_desc = _T("Comment=");
517 pos = text.Find(mime_desc);
518 if (pos == wxNOT_FOUND) mime_desc = wxEmptyString;
519 else
520 {
521 pc = text.c_str() + pos + mime_desc.Length();
522 mime_desc = wxEmptyString;
523 while ( *pc && *pc != _T('\n') ) mime_desc += *pc++;
524 }
525
526 pos = text.Find(_T("Patterns="));
527 if (pos != wxNOT_FOUND)
528 {
529 wxString exts;
530 pc = text.c_str() + pos + 9;
531 while ( *pc && *pc != _T('\n') ) exts += *pc++;
532 wxStringTokenizer tokenizer(exts, _T(";"));
533 wxString e;
534
535 while (tokenizer.HasMoreTokens())
536 {
537 e = tokenizer.GetNextToken();
538 if (e.Left(2) != _T("*.")) continue; // don't support too difficult patterns
539 mime_extension << e.Mid(2);
540 mime_extension << _T(' ');
541 }
542 mime_extension.RemoveLast();
543 }
544
545 ms_infoTypes.Add(mimetype);
546 ms_infoDescriptions.Add(mime_desc);
547 ms_infoExtensions.Add(mime_extension);
548
549 // ok, now we can take care of icon:
550
551 pos = text.Find(_T("Icon="));
552 if ( pos == wxNOT_FOUND )
553 {
554 // no icon info
555 return;
556 }
557
558 wxString icon;
559
560 pc = text.c_str() + pos + 5; // 5 == strlen("Icon=")
561 while ( *pc && *pc != _T('\n') )
562 {
563 icon += *pc++;
564 }
565
566 if ( !!icon )
567 {
568 // we must check if the file exists because it may be stored
569 // in many locations, at least ~/.kde and $KDEDIR
570 size_t nDir, nDirs = icondirs.GetCount();
571 for ( nDir = 0; nDir < nDirs; nDir++ )
572 if (wxFileExists(icondirs[nDir] + icon))
573 {
574 icon.Prepend(icondirs[nDir]);
575 break;
576 }
577 if (nDir == nDirs) return; //does not exist
578
579 // do we already have this MIME type?
580 int i = ms_mimetypes.Index(mimetype);
581 if ( i == wxNOT_FOUND )
582 {
583 // add it
584 size_t n = ms_mimetypes.Add(mimetype);
585 ms_icons.Insert(icon, n);
586 }
587 else
588 {
589 // replace the old value
590 ms_icons[(size_t)i] = icon;
591 }
592 }
593 }
594
595 void wxKDEIconHandler::LoadLinksForMimeType(const wxString& dirbase,
596 const wxString& subdir,
597 const wxArrayString& icondirs)
598 {
599 wxString dirname = dirbase;
600 dirname += subdir;
601 wxDir dir(dirname);
602 if ( !dir.IsOpened() )
603 return;
604
605 dirname += _T('/');
606
607 wxString filename;
608 bool cont = dir.GetFirst(&filename, _T("*.kdelnk"), wxDIR_FILES);
609 while ( cont )
610 {
611 LoadLinksForMimeSubtype(dirname, subdir, filename, icondirs);
612
613 cont = dir.GetNext(&filename);
614 }
615 }
616
617 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString& dirbase,
618 const wxArrayString& icondirs)
619 {
620 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
621 _T("base directory shouldn't end with a slash") );
622
623 wxString dirname = dirbase;
624 dirname << _T("/mimelnk");
625
626 if ( !wxDir::Exists(dirname) )
627 return;
628
629 wxDir dir(dirname);
630 if ( !dir.IsOpened() )
631 return;
632
633 // we will concatenate it with dir name to get the full path below
634 dirname += _T('/');
635
636 wxString subdir;
637 bool cont = dir.GetFirst(&subdir, wxEmptyString, wxDIR_DIRS);
638 while ( cont )
639 {
640 LoadLinksForMimeType(dirname, subdir, icondirs);
641
642 cont = dir.GetNext(&subdir);
643 }
644 }
645
646 void wxKDEIconHandler::Init()
647 {
648 wxArrayString dirs;
649 wxArrayString icondirs;
650
651 // settings in ~/.kde have maximal priority
652 dirs.Add(wxGetHomeDir() + _T("/.kde/share"));
653 icondirs.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
654
655 // the variable KDEDIR is set when KDE is running
656 const char *kdedir = getenv("KDEDIR");
657 if ( kdedir )
658 {
659 dirs.Add(wxString(kdedir) + _T("/share"));
660 icondirs.Add(wxString(kdedir) + _T("/share/icons/"));
661 }
662 else
663 {
664 // try to guess KDEDIR
665 dirs.Add(_T("/usr/share"));
666 dirs.Add(_T("/opt/kde/share"));
667 icondirs.Add(_T("/usr/share/icons/"));
668 icondirs.Add(_T("/opt/kde/share/icons/"));
669 }
670
671 size_t nDirs = dirs.GetCount();
672 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
673 {
674 LoadLinkFilesFromDir(dirs[nDir], icondirs);
675 }
676
677 m_inited = TRUE;
678 }
679
680 bool wxKDEIconHandler::GetIcon(const wxString& mimetype, wxIcon *icon)
681 {
682 if ( !m_inited )
683 {
684 Init();
685 }
686
687 int index = ms_mimetypes.Index(mimetype);
688 if ( index == wxNOT_FOUND )
689 return FALSE;
690
691 wxString iconname = ms_icons[(size_t)index];
692
693 #if wxUSE_GUI
694 wxLogNull nolog;
695 wxIcon icn;
696 if (iconname.Right(4).MakeUpper() == _T(".XPM"))
697 icn = wxIcon(iconname);
698 else
699 icn = wxIcon(iconname, wxBITMAP_TYPE_ANY);
700 if (icn.Ok()) *icon = icn;
701 else return FALSE;
702 #else
703 // helpful for testing in console mode
704 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
705 mimetype.c_str(), iconname.c_str());
706 #endif
707
708 return TRUE;
709 }
710
711
712 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl *manager)
713 {
714 if ( !m_inited ) Init();
715
716 size_t cnt = ms_infoTypes.GetCount();
717 for (unsigned i = 0; i < cnt; i++)
718 manager -> AddMimeTypeInfo(ms_infoTypes[i], ms_infoExtensions[i], ms_infoDescriptions[i]);
719 }
720
721
722 // ----------------------------------------------------------------------------
723 // wxFileTypeImpl (Unix)
724 // ----------------------------------------------------------------------------
725
726 MailCapEntry *
727 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
728 {
729 wxString command;
730 MailCapEntry *entry = m_manager->m_aEntries[m_index];
731 while ( entry != NULL ) {
732 // notice that an empty command would always succeed (it's ok)
733 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
734
735 if ( command.IsEmpty() || (wxSystem(command) == 0) ) {
736 // ok, passed
737 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
738 command.c_str(), params.GetMimeType().c_str());
739 break;
740 }
741 else {
742 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
743 command.c_str(), params.GetMimeType().c_str());
744 }
745
746 entry = entry->GetNext();
747 }
748
749 return entry;
750 }
751
752 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
753 {
754 wxString mimetype;
755 (void)GetMimeType(&mimetype);
756
757 ArrayIconHandlers& handlers = m_manager->GetIconHandlers();
758 size_t count = handlers.GetCount();
759 for ( size_t n = 0; n < count; n++ )
760 {
761 if ( handlers[n]->GetIcon(mimetype, icon) )
762 return TRUE;
763 }
764
765 return FALSE;
766 }
767
768 bool
769 wxFileTypeImpl::GetExpandedCommand(wxString *expandedCmd,
770 const wxFileType::MessageParameters& params,
771 bool open) const
772 {
773 MailCapEntry *entry = GetEntry(params);
774 if ( entry == NULL ) {
775 // all tests failed...
776 return FALSE;
777 }
778
779 wxString cmd = open ? entry->GetOpenCmd() : entry->GetPrintCmd();
780 if ( cmd.IsEmpty() ) {
781 // may happen, especially for "print"
782 return FALSE;
783 }
784
785 *expandedCmd = wxFileType::ExpandCommand(cmd, params);
786 return TRUE;
787 }
788
789 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
790 {
791 wxString strExtensions = m_manager->GetExtension(m_index);
792 extensions.Empty();
793
794 // one extension in the space or comma delimitid list
795 wxString strExt;
796 for ( const wxChar *p = strExtensions; ; p++ ) {
797 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
798 if ( !strExt.IsEmpty() ) {
799 extensions.Add(strExt);
800 strExt.Empty();
801 }
802 //else: repeated spaces (shouldn't happen, but it's not that
803 // important if it does happen)
804
805 if ( *p == wxT('\0') )
806 break;
807 }
808 else if ( *p == wxT('.') ) {
809 // remove the dot from extension (but only if it's the first char)
810 if ( !strExt.IsEmpty() ) {
811 strExt += wxT('.');
812 }
813 //else: no, don't append it
814 }
815 else {
816 strExt += *p;
817 }
818 }
819
820 return TRUE;
821 }
822
823 // ----------------------------------------------------------------------------
824 // wxMimeTypesManagerImpl (Unix)
825 // ----------------------------------------------------------------------------
826
827 /* static */
828 ArrayIconHandlers& wxMimeTypesManagerImpl::GetIconHandlers()
829 {
830 if ( ms_iconHandlers.GetCount() == 0 )
831 {
832 ms_iconHandlers.Add(&gs_iconHandlerKDE);
833 ms_iconHandlers.Add(&gs_iconHandlerGNOME);
834 }
835
836 return ms_iconHandlers;
837 }
838
839 // read system and user mailcaps (TODO implement mime.types support)
840 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
841 {
842 // read KDE/GNOME tables
843 ArrayIconHandlers& handlers = GetIconHandlers();
844 size_t count = handlers.GetCount();
845 for ( size_t hn = 0; hn < count; hn++ )
846 handlers[hn]->GetMimeInfoRecords(this);
847
848 // directories where we look for mailcap and mime.types by default
849 // (taken from metamail(1) sources)
850 static const wxChar *aStandardLocations[] =
851 {
852 wxT("/etc"),
853 wxT("/usr/etc"),
854 wxT("/usr/local/etc"),
855 wxT("/etc/mail"),
856 wxT("/usr/public/lib")
857 };
858
859 // first read the system wide file(s)
860 size_t n;
861 for ( n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
862 wxString dir = aStandardLocations[n];
863
864 wxString file = dir + wxT("/mailcap");
865 if ( wxFile::Exists(file) ) {
866 ReadMailcap(file);
867 }
868
869 file = dir + wxT("/mime.types");
870 if ( wxFile::Exists(file) ) {
871 ReadMimeTypes(file);
872 }
873 }
874
875 wxString strHome = wxGetenv(wxT("HOME"));
876
877 // and now the users mailcap
878 wxString strUserMailcap = strHome + wxT("/.mailcap");
879 if ( wxFile::Exists(strUserMailcap) ) {
880 ReadMailcap(strUserMailcap);
881 }
882
883 // read the users mime.types
884 wxString strUserMimeTypes = strHome + wxT("/.mime.types");
885 if ( wxFile::Exists(strUserMimeTypes) ) {
886 ReadMimeTypes(strUserMimeTypes);
887 }
888 }
889
890 wxFileType *
891 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
892 {
893 size_t count = m_aExtensions.GetCount();
894 for ( size_t n = 0; n < count; n++ ) {
895 wxString extensions = m_aExtensions[n];
896 while ( !extensions.IsEmpty() ) {
897 wxString field = extensions.BeforeFirst(wxT(' '));
898 extensions = extensions.AfterFirst(wxT(' '));
899
900 // consider extensions as not being case-sensitive
901 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
902 // found
903 wxFileType *fileType = new wxFileType;
904 fileType->m_impl->Init(this, n);
905
906 return fileType;
907 }
908 }
909 }
910
911 // not found
912 return NULL;
913 }
914
915 wxFileType *
916 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
917 {
918 // mime types are not case-sensitive
919 wxString mimetype(mimeType);
920 mimetype.MakeLower();
921
922 // first look for an exact match
923 int index = m_aTypes.Index(mimetype);
924 if ( index == wxNOT_FOUND ) {
925 // then try to find "text/*" as match for "text/plain" (for example)
926 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
927 // the whole string - ok.
928 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
929
930 size_t nCount = m_aTypes.Count();
931 for ( size_t n = 0; n < nCount; n++ ) {
932 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
933 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
934 index = n;
935 break;
936 }
937 }
938 }
939
940 if ( index != wxNOT_FOUND ) {
941 wxFileType *fileType = new wxFileType;
942 fileType->m_impl->Init(this, index);
943
944 return fileType;
945 }
946 else {
947 // not found...
948 return NULL;
949 }
950 }
951
952 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
953 {
954 wxString extensions;
955 const wxArrayString& exts = filetype.GetExtensions();
956 size_t nExts = exts.GetCount();
957 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
958 if ( nExt > 0 ) {
959 extensions += wxT(' ');
960 }
961 extensions += exts[nExt];
962 }
963
964 AddMimeTypeInfo(filetype.GetMimeType(),
965 extensions,
966 filetype.GetDescription());
967
968 AddMailcapInfo(filetype.GetMimeType(),
969 filetype.GetOpenCommand(),
970 filetype.GetPrintCommand(),
971 wxT(""),
972 filetype.GetDescription());
973 }
974
975 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
976 const wxString& strExtensions,
977 const wxString& strDesc)
978 {
979 int index = m_aTypes.Index(strMimeType);
980 if ( index == wxNOT_FOUND ) {
981 // add a new entry
982 m_aTypes.Add(strMimeType);
983 m_aEntries.Add(NULL);
984 m_aExtensions.Add(strExtensions);
985 m_aDescriptions.Add(strDesc);
986 }
987 else {
988 // modify an existing one
989 if ( !strDesc.IsEmpty() ) {
990 m_aDescriptions[index] = strDesc; // replace old value
991 }
992 m_aExtensions[index] += ' ' + strExtensions;
993 }
994 }
995
996 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
997 const wxString& strOpenCmd,
998 const wxString& strPrintCmd,
999 const wxString& strTest,
1000 const wxString& strDesc)
1001 {
1002 MailCapEntry *entry = new MailCapEntry(strOpenCmd, strPrintCmd, strTest);
1003
1004 int nIndex = m_aTypes.Index(strType);
1005 if ( nIndex == wxNOT_FOUND ) {
1006 // new file type
1007 m_aTypes.Add(strType);
1008
1009 m_aEntries.Add(entry);
1010 m_aExtensions.Add(wxT(""));
1011 m_aDescriptions.Add(strDesc);
1012 }
1013 else {
1014 // always append the entry in the tail of the list - info added with
1015 // this function can only come from AddFallbacks()
1016 MailCapEntry *entryOld = m_aEntries[nIndex];
1017 if ( entryOld )
1018 entry->Append(entryOld);
1019 else
1020 m_aEntries[nIndex] = entry;
1021 }
1022 }
1023
1024 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
1025 {
1026 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName.c_str());
1027
1028 wxTextFile file(strFileName);
1029 if ( !file.Open() )
1030 return FALSE;
1031
1032 // the information we extract
1033 wxString strMimeType, strDesc, strExtensions;
1034
1035 size_t nLineCount = file.GetLineCount();
1036 const wxChar *pc = NULL;
1037 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1038 if ( pc == NULL ) {
1039 // now we're at the start of the line
1040 pc = file[nLine].c_str();
1041 }
1042 else {
1043 // we didn't finish with the previous line yet
1044 nLine--;
1045 }
1046
1047 // skip whitespace
1048 while ( wxIsspace(*pc) )
1049 pc++;
1050
1051 // comment or blank line?
1052 if ( *pc == wxT('#') || !*pc ) {
1053 // skip the whole line
1054 pc = NULL;
1055 continue;
1056 }
1057
1058 // detect file format
1059 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
1060 if ( pEqualSign == NULL ) {
1061 // brief format
1062 // ------------
1063
1064 // first field is mime type
1065 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
1066 strMimeType += *pc;
1067 }
1068
1069 // skip whitespace
1070 while ( wxIsspace(*pc) )
1071 pc++;
1072
1073 // take all the rest of the string
1074 strExtensions = pc;
1075
1076 // no description...
1077 strDesc.Empty();
1078 }
1079 else {
1080 // expanded format
1081 // ---------------
1082
1083 // the string on the left of '=' is the field name
1084 wxString strLHS(pc, pEqualSign - pc);
1085
1086 // eat whitespace
1087 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
1088 ;
1089
1090 const wxChar *pEnd;
1091 if ( *pc == wxT('"') ) {
1092 // the string is quoted and ends at the matching quote
1093 pEnd = wxStrchr(++pc, wxT('"'));
1094 if ( pEnd == NULL ) {
1095 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1096 "quoted string."),
1097 strFileName.c_str(), nLine + 1);
1098 }
1099 }
1100 else {
1101 // unquoted string ends at the first space
1102 for ( pEnd = pc; !wxIsspace(*pEnd); pEnd++ )
1103 ;
1104 }
1105
1106 // now we have the RHS (field value)
1107 wxString strRHS(pc, pEnd - pc);
1108
1109 // check what follows this entry
1110 if ( *pEnd == wxT('"') ) {
1111 // skip this quote
1112 pEnd++;
1113 }
1114
1115 for ( pc = pEnd; wxIsspace(*pc); pc++ )
1116 ;
1117
1118 // if there is something left, it may be either a '\\' to continue
1119 // the line or the next field of the same entry
1120 bool entryEnded = *pc == wxT('\0'),
1121 nextFieldOnSameLine = FALSE;
1122 if ( !entryEnded ) {
1123 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
1124 }
1125
1126 // now see what we got
1127 if ( strLHS == wxT("type") ) {
1128 strMimeType = strRHS;
1129 }
1130 else if ( strLHS == wxT("desc") ) {
1131 strDesc = strRHS;
1132 }
1133 else if ( strLHS == wxT("exts") ) {
1134 strExtensions = strRHS;
1135 }
1136 else {
1137 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1138 strFileName.c_str(), nLine + 1, strLHS.c_str());
1139 }
1140
1141 if ( !entryEnded ) {
1142 if ( !nextFieldOnSameLine )
1143 pc = NULL;
1144 //else: don't reset it
1145
1146 // as we don't reset strMimeType, the next field in this entry
1147 // will be interpreted correctly.
1148
1149 continue;
1150 }
1151 }
1152
1153 // although it doesn't seem to be covered by RFCs, some programs
1154 // (notably Netscape) create their entries with several comma
1155 // separated extensions (RFC mention the spaces only)
1156 strExtensions.Replace(wxT(","), wxT(" "));
1157
1158 // also deal with the leading dot
1159 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
1160 {
1161 strExtensions.erase(0, 1);
1162 }
1163
1164 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
1165
1166 // finished with this line
1167 pc = NULL;
1168 }
1169
1170 // check our data integriry
1171 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1172 m_aTypes.Count() == m_aExtensions.Count() &&
1173 m_aTypes.Count() == m_aDescriptions.Count() );
1174
1175 return TRUE;
1176 }
1177
1178 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
1179 bool fallback)
1180 {
1181 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName.c_str());
1182
1183 wxTextFile file(strFileName);
1184 if ( !file.Open() )
1185 return FALSE;
1186
1187 // see the comments near the end of function for the reason we need these
1188 // variables (search for the next occurence of them)
1189 // indices of MIME types (in m_aTypes) we already found in this file
1190 wxArrayInt aEntryIndices;
1191 // aLastIndices[n] is the index of last element in
1192 // m_aEntries[aEntryIndices[n]] from this file
1193 wxArrayInt aLastIndices;
1194
1195 size_t nLineCount = file.GetLineCount();
1196 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1197 // now we're at the start of the line
1198 const wxChar *pc = file[nLine].c_str();
1199
1200 // skip whitespace
1201 while ( wxIsspace(*pc) )
1202 pc++;
1203
1204 // comment or empty string?
1205 if ( *pc == wxT('#') || *pc == wxT('\0') )
1206 continue;
1207
1208 // no, do parse
1209
1210 // what field are we currently in? The first 2 are fixed and there may
1211 // be an arbitrary number of other fields -- currently, we are not
1212 // interested in any of them, but we should parse them as well...
1213 enum
1214 {
1215 Field_Type,
1216 Field_OpenCmd,
1217 Field_Other
1218 } currentToken = Field_Type;
1219
1220 // the flags and field values on the current line
1221 bool needsterminal = FALSE,
1222 copiousoutput = FALSE;
1223 wxString strType,
1224 strOpenCmd,
1225 strPrintCmd,
1226 strTest,
1227 strDesc,
1228 curField; // accumulator
1229 for ( bool cont = TRUE; cont; pc++ ) {
1230 switch ( *pc ) {
1231 case wxT('\\'):
1232 // interpret the next character literally (notice that
1233 // backslash can be used for line continuation)
1234 if ( *++pc == wxT('\0') ) {
1235 // fetch the next line.
1236
1237 // pc currently points to nowhere, but after the next
1238 // pc++ in the for line it will point to the beginning
1239 // of the next line in the file
1240 pc = file[++nLine].c_str() - 1;
1241 }
1242 else {
1243 // just a normal character
1244 curField += *pc;
1245 }
1246 break;
1247
1248 case wxT('\0'):
1249 cont = FALSE; // end of line reached, exit the loop
1250
1251 // fall through
1252
1253 case wxT(';'):
1254 // store this field and start looking for the next one
1255
1256 // trim whitespaces from both sides
1257 curField.Trim(TRUE).Trim(FALSE);
1258
1259 switch ( currentToken ) {
1260 case Field_Type:
1261 strType = curField;
1262 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
1263 // we interpret "type" as "type/*"
1264 strType += wxT("/*");
1265 }
1266
1267 currentToken = Field_OpenCmd;
1268 break;
1269
1270 case Field_OpenCmd:
1271 strOpenCmd = curField;
1272
1273 currentToken = Field_Other;
1274 break;
1275
1276 case Field_Other:
1277 {
1278 // "good" mailcap entry?
1279 bool ok = TRUE;
1280
1281 // is this something of the form foo=bar?
1282 const wxChar *pEq = wxStrchr(curField, wxT('='));
1283 if ( pEq != NULL ) {
1284 wxString lhs = curField.BeforeFirst(wxT('=')),
1285 rhs = curField.AfterFirst(wxT('='));
1286
1287 lhs.Trim(TRUE); // from right
1288 rhs.Trim(FALSE); // from left
1289
1290 if ( lhs == wxT("print") )
1291 strPrintCmd = rhs;
1292 else if ( lhs == wxT("test") )
1293 strTest = rhs;
1294 else if ( lhs == wxT("description") ) {
1295 // it might be quoted
1296 if ( rhs[0u] == wxT('"') &&
1297 rhs.Last() == wxT('"') ) {
1298 strDesc = wxString(rhs.c_str() + 1,
1299 rhs.Len() - 2);
1300 }
1301 else {
1302 strDesc = rhs;
1303 }
1304 }
1305 else if ( lhs == wxT("compose") ||
1306 lhs == wxT("composetyped") ||
1307 lhs == wxT("notes") ||
1308 lhs == wxT("edit") )
1309 ; // ignore
1310 else
1311 ok = FALSE;
1312
1313 }
1314 else {
1315 // no, it's a simple flag
1316 // TODO support the flags:
1317 // 1. create an xterm for 'needsterminal'
1318 // 2. append "| $PAGER" for 'copiousoutput'
1319 if ( curField == wxT("needsterminal") )
1320 needsterminal = TRUE;
1321 else if ( curField == wxT("copiousoutput") )
1322 copiousoutput = TRUE;
1323 else if ( curField == wxT("textualnewlines") )
1324 ; // ignore
1325 else
1326 ok = FALSE;
1327 }
1328
1329 if ( !ok )
1330 {
1331 // we don't understand this field, but
1332 // Netscape stores info in it, so don't warn
1333 // about it
1334 if ( curField.Left(16u) != "x-mozilla-flags=" )
1335 {
1336 // don't flood the user with error
1337 // messages if we don't understand
1338 // something in his mailcap, but give
1339 // them in debug mode because this might
1340 // be useful for the programmer
1341 wxLogDebug
1342 (
1343 wxT("Mailcap file %s, line %d: "
1344 "unknown field '%s' for the "
1345 "MIME type '%s' ignored."),
1346 strFileName.c_str(),
1347 nLine + 1,
1348 curField.c_str(),
1349 strType.c_str()
1350 );
1351 }
1352 }
1353 }
1354
1355 // it already has this value
1356 //currentToken = Field_Other;
1357 break;
1358
1359 default:
1360 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1361 }
1362
1363 // next token starts immediately after ';'
1364 curField.Empty();
1365 break;
1366
1367 default:
1368 curField += *pc;
1369 }
1370 }
1371
1372 // check that we really read something reasonable
1373 if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
1374 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1375 "ignored."),
1376 strFileName.c_str(), nLine + 1);
1377 }
1378 else {
1379 MailCapEntry *entry = new MailCapEntry(strOpenCmd,
1380 strPrintCmd,
1381 strTest);
1382
1383 // NB: because of complications below (we must get entries priority
1384 // right), we can't use AddMailcapInfo() here, unfortunately.
1385 strType.MakeLower();
1386 int nIndex = m_aTypes.Index(strType);
1387 if ( nIndex == wxNOT_FOUND ) {
1388 // new file type
1389 m_aTypes.Add(strType);
1390
1391 m_aEntries.Add(entry);
1392 m_aExtensions.Add(wxT(""));
1393 m_aDescriptions.Add(strDesc);
1394 }
1395 else {
1396 // modify the existing entry: the entries in one and the same
1397 // file are read in top-to-bottom order, i.e. the entries read
1398 // first should be tried before the entries below. However,
1399 // the files read later should override the settings in the
1400 // files read before (except if fallback is TRUE), thus we
1401 // Insert() the new entry to the list if it has already
1402 // occured in _this_ file, but Prepend() it if it occured in
1403 // some of the previous ones and Append() to it in the
1404 // fallback case
1405
1406 if ( fallback ) {
1407 // 'fallback' parameter prevents the entries from this
1408 // file from overriding the other ones - always append
1409 MailCapEntry *entryOld = m_aEntries[nIndex];
1410 if ( entryOld )
1411 entry->Append(entryOld);
1412 else
1413 m_aEntries[nIndex] = entry;
1414 }
1415 else {
1416 int entryIndex = aEntryIndices.Index(nIndex);
1417 if ( entryIndex == wxNOT_FOUND ) {
1418 // first time in this file
1419 aEntryIndices.Add(nIndex);
1420 aLastIndices.Add(0);
1421
1422 entry->Prepend(m_aEntries[nIndex]);
1423 m_aEntries[nIndex] = entry;
1424 }
1425 else {
1426 // not the first time in _this_ file
1427 size_t nEntryIndex = (size_t)entryIndex;
1428 MailCapEntry *entryOld = m_aEntries[nIndex];
1429 if ( entryOld )
1430 entry->Insert(entryOld, aLastIndices[nEntryIndex]);
1431 else
1432 m_aEntries[nIndex] = entry;
1433
1434 // the indices were shifted by 1
1435 aLastIndices[nEntryIndex]++;
1436 }
1437 }
1438
1439 if ( !strDesc.IsEmpty() ) {
1440 // replace the old one - what else can we do??
1441 m_aDescriptions[nIndex] = strDesc;
1442 }
1443 }
1444 }
1445
1446 // check our data integriry
1447 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1448 m_aTypes.Count() == m_aExtensions.Count() &&
1449 m_aTypes.Count() == m_aDescriptions.Count() );
1450 }
1451
1452 return TRUE;
1453 }
1454
1455 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1456 {
1457 mimetypes.Empty();
1458
1459 wxString type;
1460 size_t count = m_aTypes.GetCount();
1461 for ( size_t n = 0; n < count; n++ )
1462 {
1463 // don't return template types from here (i.e. anything containg '*')
1464 type = m_aTypes[n];
1465 if ( type.Find(_T('*')) == wxNOT_FOUND )
1466 {
1467 mimetypes.Add(type);
1468 }
1469 }
1470
1471 return mimetypes.GetCount();
1472 }
1473
1474 #endif
1475 // wxUSE_FILE && wxUSE_TEXTFILE
1476