mimetype.cpp/.h split into unix,mac,msw
[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
425 wxString gnomedir;
426 wxGetHomeDir( &gnomedir );
427 gnomedir += _T("/.gnome");
428 dirs.Add( gnomedir );
429
430 size_t nDirs = dirs.GetCount();
431 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
432 {
433 LoadKeyFilesFromDir(dirs[nDir]);
434 }
435
436 m_inited = TRUE;
437 }
438
439 bool wxGNOMEIconHandler::GetIcon(const wxString& mimetype, wxIcon *icon)
440 {
441 if ( !m_inited )
442 {
443 Init();
444 }
445
446 int index = ms_mimetypes.Index(mimetype);
447 if ( index == wxNOT_FOUND )
448 return FALSE;
449
450 wxString iconname = ms_icons[(size_t)index];
451
452 #if wxUSE_GUI
453 *icon = wxIcon(iconname);
454 #else
455 // helpful for testing in console mode
456 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
457 mimetype.c_str(), iconname.c_str());
458 #endif
459
460 return TRUE;
461 }
462
463 // ----------------------------------------------------------------------------
464 // wxKDEIconHandler
465 // ----------------------------------------------------------------------------
466
467 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
468 // may be found in either of the following locations
469 //
470 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
471 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
472 //
473 // The format of a .kdelnk file is almost the same as the one used by
474 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
475 // value for the entry "Type"
476
477 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString& dirbase,
478 const wxString& subdir,
479 const wxString& filename,
480 const wxArrayString& icondirs)
481 {
482 wxFFile file(dirbase + filename);
483 if ( !file.IsOpened() )
484 return;
485
486 // construct mimetype from the directory name and the basename of the
487 // file (it always has .kdelnk extension)
488 wxString mimetype;
489 mimetype << subdir << _T('/') << filename.BeforeLast(_T('.'));
490
491 // these files are small, slurp the entire file at once
492 wxString text;
493 if ( !file.ReadAll(&text) )
494 return;
495
496 int pos;
497 const wxChar *pc;
498
499 // before trying to find an icon, grab mimetype information
500 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
501 // have edited it in control panel...)
502
503 wxString mime_extension, mime_desc;
504
505 pos = wxNOT_FOUND;
506 if (wxGetLocale() != NULL)
507 mime_desc = _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
508 if (pos == wxNOT_FOUND) mime_desc = _T("Comment=");
509 pos = text.Find(mime_desc);
510 if (pos == wxNOT_FOUND) mime_desc = wxEmptyString;
511 else
512 {
513 pc = text.c_str() + pos + mime_desc.Length();
514 mime_desc = wxEmptyString;
515 while ( *pc && *pc != _T('\n') ) mime_desc += *pc++;
516 }
517
518 pos = text.Find(_T("Patterns="));
519 if (pos != wxNOT_FOUND)
520 {
521 wxString exts;
522 pc = text.c_str() + pos + 9;
523 while ( *pc && *pc != _T('\n') ) exts += *pc++;
524 wxStringTokenizer tokenizer(exts, _T(";"));
525 wxString e;
526
527 while (tokenizer.HasMoreTokens())
528 {
529 e = tokenizer.GetNextToken();
530 if (e.Left(2) != _T("*.")) continue; // don't support too difficult patterns
531 mime_extension << e.Mid(2);
532 mime_extension << _T(' ');
533 }
534 mime_extension.RemoveLast();
535 }
536
537 ms_infoTypes.Add(mimetype);
538 ms_infoDescriptions.Add(mime_desc);
539 ms_infoExtensions.Add(mime_extension);
540
541 // ok, now we can take care of icon:
542
543 pos = text.Find(_T("Icon="));
544 if ( pos == wxNOT_FOUND )
545 {
546 // no icon info
547 return;
548 }
549
550 wxString icon;
551
552 pc = text.c_str() + pos + 5; // 5 == strlen("Icon=")
553 while ( *pc && *pc != _T('\n') )
554 {
555 icon += *pc++;
556 }
557
558 if ( !!icon )
559 {
560 // we must check if the file exists because it may be stored
561 // in many locations, at least ~/.kde and $KDEDIR
562 size_t nDir, nDirs = icondirs.GetCount();
563 for ( nDir = 0; nDir < nDirs; nDir++ )
564 if (wxFileExists(icondirs[nDir] + icon))
565 {
566 icon.Prepend(icondirs[nDir]);
567 break;
568 }
569 if (nDir == nDirs) return; //does not exist
570
571 // do we already have this MIME type?
572 int i = ms_mimetypes.Index(mimetype);
573 if ( i == wxNOT_FOUND )
574 {
575 // add it
576 size_t n = ms_mimetypes.Add(mimetype);
577 ms_icons.Insert(icon, n);
578 }
579 else
580 {
581 // replace the old value
582 ms_icons[(size_t)i] = icon;
583 }
584 }
585 }
586
587 void wxKDEIconHandler::LoadLinksForMimeType(const wxString& dirbase,
588 const wxString& subdir,
589 const wxArrayString& icondirs)
590 {
591 wxString dirname = dirbase;
592 dirname += subdir;
593 wxDir dir(dirname);
594 if ( !dir.IsOpened() )
595 return;
596
597 dirname += _T('/');
598
599 wxString filename;
600 bool cont = dir.GetFirst(&filename, _T("*.kdelnk"), wxDIR_FILES);
601 while ( cont )
602 {
603 LoadLinksForMimeSubtype(dirname, subdir, filename, icondirs);
604
605 cont = dir.GetNext(&filename);
606 }
607 }
608
609 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString& dirbase,
610 const wxArrayString& icondirs)
611 {
612 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
613 _T("base directory shouldn't end with a slash") );
614
615 wxString dirname = dirbase;
616 dirname << _T("/mimelnk");
617
618 if ( !wxDir::Exists(dirname) )
619 return;
620
621 wxDir dir(dirname);
622 if ( !dir.IsOpened() )
623 return;
624
625 // we will concatenate it with dir name to get the full path below
626 dirname += _T('/');
627
628 wxString subdir;
629 bool cont = dir.GetFirst(&subdir, wxEmptyString, wxDIR_DIRS);
630 while ( cont )
631 {
632 LoadLinksForMimeType(dirname, subdir, icondirs);
633
634 cont = dir.GetNext(&subdir);
635 }
636 }
637
638 void wxKDEIconHandler::Init()
639 {
640 wxArrayString dirs;
641 wxArrayString icondirs;
642
643 // settings in ~/.kde have maximal priority
644 dirs.Add(wxGetHomeDir() + _T("/.kde/share"));
645 icondirs.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
646
647 // the variable KDEDIR is set when KDE is running
648 const char *kdedir = getenv("KDEDIR");
649 if ( kdedir )
650 {
651 dirs.Add(wxString(kdedir) + _T("/share"));
652 icondirs.Add(wxString(kdedir) + _T("/share/icons/"));
653 }
654 else
655 {
656 // try to guess KDEDIR
657 dirs.Add(_T("/usr/share"));
658 dirs.Add(_T("/opt/kde/share"));
659 icondirs.Add(_T("/usr/share/icons/"));
660 icondirs.Add(_T("/opt/kde/share/icons/"));
661 }
662
663 size_t nDirs = dirs.GetCount();
664 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
665 {
666 LoadLinkFilesFromDir(dirs[nDir], icondirs);
667 }
668
669 m_inited = TRUE;
670 }
671
672 bool wxKDEIconHandler::GetIcon(const wxString& mimetype, wxIcon *icon)
673 {
674 if ( !m_inited )
675 {
676 Init();
677 }
678
679 int index = ms_mimetypes.Index(mimetype);
680 if ( index == wxNOT_FOUND )
681 return FALSE;
682
683 wxString iconname = ms_icons[(size_t)index];
684
685 #if wxUSE_GUI
686 *icon = wxIcon(iconname);
687 #else
688 // helpful for testing in console mode
689 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
690 mimetype.c_str(), iconname.c_str());
691 #endif
692
693 return TRUE;
694 }
695
696
697 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl *manager)
698 {
699 if ( !m_inited ) Init();
700
701 size_t cnt = ms_infoTypes.GetCount();
702 for (unsigned i = 0; i < cnt; i++)
703 manager -> AddMimeTypeInfo(ms_infoTypes[i], ms_infoExtensions[i], ms_infoDescriptions[i]);
704 }
705
706
707 // ----------------------------------------------------------------------------
708 // wxFileTypeImpl (Unix)
709 // ----------------------------------------------------------------------------
710
711 MailCapEntry *
712 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
713 {
714 wxString command;
715 MailCapEntry *entry = m_manager->m_aEntries[m_index];
716 while ( entry != NULL ) {
717 // notice that an empty command would always succeed (it's ok)
718 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
719
720 if ( command.IsEmpty() || (wxSystem(command) == 0) ) {
721 // ok, passed
722 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
723 command.c_str(), params.GetMimeType().c_str());
724 break;
725 }
726 else {
727 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
728 command.c_str(), params.GetMimeType().c_str());
729 }
730
731 entry = entry->GetNext();
732 }
733
734 return entry;
735 }
736
737 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
738 {
739 wxString mimetype;
740 (void)GetMimeType(&mimetype);
741
742 ArrayIconHandlers& handlers = m_manager->GetIconHandlers();
743 size_t count = handlers.GetCount();
744 for ( size_t n = 0; n < count; n++ )
745 {
746 if ( handlers[n]->GetIcon(mimetype, icon) )
747 return TRUE;
748 }
749
750 return FALSE;
751 }
752
753 bool
754 wxFileTypeImpl::GetExpandedCommand(wxString *expandedCmd,
755 const wxFileType::MessageParameters& params,
756 bool open) const
757 {
758 MailCapEntry *entry = GetEntry(params);
759 if ( entry == NULL ) {
760 // all tests failed...
761 return FALSE;
762 }
763
764 wxString cmd = open ? entry->GetOpenCmd() : entry->GetPrintCmd();
765 if ( cmd.IsEmpty() ) {
766 // may happen, especially for "print"
767 return FALSE;
768 }
769
770 *expandedCmd = wxFileType::ExpandCommand(cmd, params);
771 return TRUE;
772 }
773
774 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
775 {
776 wxString strExtensions = m_manager->GetExtension(m_index);
777 extensions.Empty();
778
779 // one extension in the space or comma delimitid list
780 wxString strExt;
781 for ( const wxChar *p = strExtensions; ; p++ ) {
782 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
783 if ( !strExt.IsEmpty() ) {
784 extensions.Add(strExt);
785 strExt.Empty();
786 }
787 //else: repeated spaces (shouldn't happen, but it's not that
788 // important if it does happen)
789
790 if ( *p == wxT('\0') )
791 break;
792 }
793 else if ( *p == wxT('.') ) {
794 // remove the dot from extension (but only if it's the first char)
795 if ( !strExt.IsEmpty() ) {
796 strExt += wxT('.');
797 }
798 //else: no, don't append it
799 }
800 else {
801 strExt += *p;
802 }
803 }
804
805 return TRUE;
806 }
807
808 // ----------------------------------------------------------------------------
809 // wxMimeTypesManagerImpl (Unix)
810 // ----------------------------------------------------------------------------
811
812 /* static */
813 ArrayIconHandlers& wxMimeTypesManagerImpl::GetIconHandlers()
814 {
815 if ( ms_iconHandlers.GetCount() == 0 )
816 {
817 ms_iconHandlers.Add(&gs_iconHandlerGNOME);
818 ms_iconHandlers.Add(&gs_iconHandlerKDE);
819 }
820
821 return ms_iconHandlers;
822 }
823
824 // read system and user mailcaps (TODO implement mime.types support)
825 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
826 {
827 // directories where we look for mailcap and mime.types by default
828 // (taken from metamail(1) sources)
829 static const wxChar *aStandardLocations[] =
830 {
831 wxT("/etc"),
832 wxT("/usr/etc"),
833 wxT("/usr/local/etc"),
834 wxT("/etc/mail"),
835 wxT("/usr/public/lib")
836 };
837
838 // first read the system wide file(s)
839 size_t n;
840 for ( n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
841 wxString dir = aStandardLocations[n];
842
843 wxString file = dir + wxT("/mailcap");
844 if ( wxFile::Exists(file) ) {
845 ReadMailcap(file);
846 }
847
848 file = dir + wxT("/mime.types");
849 if ( wxFile::Exists(file) ) {
850 ReadMimeTypes(file);
851 }
852 }
853
854 wxString strHome = wxGetenv(wxT("HOME"));
855
856 // and now the users mailcap
857 wxString strUserMailcap = strHome + wxT("/.mailcap");
858 if ( wxFile::Exists(strUserMailcap) ) {
859 ReadMailcap(strUserMailcap);
860 }
861
862 // read the users mime.types
863 wxString strUserMimeTypes = strHome + wxT("/.mime.types");
864 if ( wxFile::Exists(strUserMimeTypes) ) {
865 ReadMimeTypes(strUserMimeTypes);
866 }
867
868 // read KDE/GNOME tables
869 ArrayIconHandlers& handlers = GetIconHandlers();
870 size_t count = handlers.GetCount();
871 for ( n = 0; n < count; n++ )
872 handlers[n]->GetMimeInfoRecords(this);
873 }
874
875 wxFileType *
876 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
877 {
878 size_t count = m_aExtensions.GetCount();
879 for ( size_t n = 0; n < count; n++ ) {
880 wxString extensions = m_aExtensions[n];
881 while ( !extensions.IsEmpty() ) {
882 wxString field = extensions.BeforeFirst(wxT(' '));
883 extensions = extensions.AfterFirst(wxT(' '));
884
885 // consider extensions as not being case-sensitive
886 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
887 // found
888 wxFileType *fileType = new wxFileType;
889 fileType->m_impl->Init(this, n);
890
891 return fileType;
892 }
893 }
894 }
895
896 // not found
897 return NULL;
898 }
899
900 wxFileType *
901 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
902 {
903 // mime types are not case-sensitive
904 wxString mimetype(mimeType);
905 mimetype.MakeLower();
906
907 // first look for an exact match
908 int index = m_aTypes.Index(mimetype);
909 if ( index == wxNOT_FOUND ) {
910 // then try to find "text/*" as match for "text/plain" (for example)
911 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
912 // the whole string - ok.
913 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
914
915 size_t nCount = m_aTypes.Count();
916 for ( size_t n = 0; n < nCount; n++ ) {
917 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
918 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
919 index = n;
920 break;
921 }
922 }
923 }
924
925 if ( index != wxNOT_FOUND ) {
926 wxFileType *fileType = new wxFileType;
927 fileType->m_impl->Init(this, index);
928
929 return fileType;
930 }
931 else {
932 // not found...
933 return NULL;
934 }
935 }
936
937 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
938 {
939 wxString extensions;
940 const wxArrayString& exts = filetype.GetExtensions();
941 size_t nExts = exts.GetCount();
942 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
943 if ( nExt > 0 ) {
944 extensions += wxT(' ');
945 }
946 extensions += exts[nExt];
947 }
948
949 AddMimeTypeInfo(filetype.GetMimeType(),
950 extensions,
951 filetype.GetDescription());
952
953 AddMailcapInfo(filetype.GetMimeType(),
954 filetype.GetOpenCommand(),
955 filetype.GetPrintCommand(),
956 wxT(""),
957 filetype.GetDescription());
958 }
959
960 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
961 const wxString& strExtensions,
962 const wxString& strDesc)
963 {
964 int index = m_aTypes.Index(strMimeType);
965 if ( index == wxNOT_FOUND ) {
966 // add a new entry
967 m_aTypes.Add(strMimeType);
968 m_aEntries.Add(NULL);
969 m_aExtensions.Add(strExtensions);
970 m_aDescriptions.Add(strDesc);
971 }
972 else {
973 // modify an existing one
974 if ( !strDesc.IsEmpty() ) {
975 m_aDescriptions[index] = strDesc; // replace old value
976 }
977 m_aExtensions[index] += ' ' + strExtensions;
978 }
979 }
980
981 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
982 const wxString& strOpenCmd,
983 const wxString& strPrintCmd,
984 const wxString& strTest,
985 const wxString& strDesc)
986 {
987 MailCapEntry *entry = new MailCapEntry(strOpenCmd, strPrintCmd, strTest);
988
989 int nIndex = m_aTypes.Index(strType);
990 if ( nIndex == wxNOT_FOUND ) {
991 // new file type
992 m_aTypes.Add(strType);
993
994 m_aEntries.Add(entry);
995 m_aExtensions.Add(wxT(""));
996 m_aDescriptions.Add(strDesc);
997 }
998 else {
999 // always append the entry in the tail of the list - info added with
1000 // this function can only come from AddFallbacks()
1001 MailCapEntry *entryOld = m_aEntries[nIndex];
1002 if ( entryOld )
1003 entry->Append(entryOld);
1004 else
1005 m_aEntries[nIndex] = entry;
1006 }
1007 }
1008
1009 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
1010 {
1011 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName.c_str());
1012
1013 wxTextFile file(strFileName);
1014 if ( !file.Open() )
1015 return FALSE;
1016
1017 // the information we extract
1018 wxString strMimeType, strDesc, strExtensions;
1019
1020 size_t nLineCount = file.GetLineCount();
1021 const wxChar *pc = NULL;
1022 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1023 if ( pc == NULL ) {
1024 // now we're at the start of the line
1025 pc = file[nLine].c_str();
1026 }
1027 else {
1028 // we didn't finish with the previous line yet
1029 nLine--;
1030 }
1031
1032 // skip whitespace
1033 while ( wxIsspace(*pc) )
1034 pc++;
1035
1036 // comment or blank line?
1037 if ( *pc == wxT('#') || !*pc ) {
1038 // skip the whole line
1039 pc = NULL;
1040 continue;
1041 }
1042
1043 // detect file format
1044 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
1045 if ( pEqualSign == NULL ) {
1046 // brief format
1047 // ------------
1048
1049 // first field is mime type
1050 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
1051 strMimeType += *pc;
1052 }
1053
1054 // skip whitespace
1055 while ( wxIsspace(*pc) )
1056 pc++;
1057
1058 // take all the rest of the string
1059 strExtensions = pc;
1060
1061 // no description...
1062 strDesc.Empty();
1063 }
1064 else {
1065 // expanded format
1066 // ---------------
1067
1068 // the string on the left of '=' is the field name
1069 wxString strLHS(pc, pEqualSign - pc);
1070
1071 // eat whitespace
1072 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
1073 ;
1074
1075 const wxChar *pEnd;
1076 if ( *pc == wxT('"') ) {
1077 // the string is quoted and ends at the matching quote
1078 pEnd = wxStrchr(++pc, wxT('"'));
1079 if ( pEnd == NULL ) {
1080 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1081 "quoted string."),
1082 strFileName.c_str(), nLine + 1);
1083 }
1084 }
1085 else {
1086 // unquoted string ends at the first space
1087 for ( pEnd = pc; !wxIsspace(*pEnd); pEnd++ )
1088 ;
1089 }
1090
1091 // now we have the RHS (field value)
1092 wxString strRHS(pc, pEnd - pc);
1093
1094 // check what follows this entry
1095 if ( *pEnd == wxT('"') ) {
1096 // skip this quote
1097 pEnd++;
1098 }
1099
1100 for ( pc = pEnd; wxIsspace(*pc); pc++ )
1101 ;
1102
1103 // if there is something left, it may be either a '\\' to continue
1104 // the line or the next field of the same entry
1105 bool entryEnded = *pc == wxT('\0'),
1106 nextFieldOnSameLine = FALSE;
1107 if ( !entryEnded ) {
1108 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
1109 }
1110
1111 // now see what we got
1112 if ( strLHS == wxT("type") ) {
1113 strMimeType = strRHS;
1114 }
1115 else if ( strLHS == wxT("desc") ) {
1116 strDesc = strRHS;
1117 }
1118 else if ( strLHS == wxT("exts") ) {
1119 strExtensions = strRHS;
1120 }
1121 else {
1122 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1123 strFileName.c_str(), nLine + 1, strLHS.c_str());
1124 }
1125
1126 if ( !entryEnded ) {
1127 if ( !nextFieldOnSameLine )
1128 pc = NULL;
1129 //else: don't reset it
1130
1131 // as we don't reset strMimeType, the next field in this entry
1132 // will be interpreted correctly.
1133
1134 continue;
1135 }
1136 }
1137
1138 // although it doesn't seem to be covered by RFCs, some programs
1139 // (notably Netscape) create their entries with several comma
1140 // separated extensions (RFC mention the spaces only)
1141 strExtensions.Replace(wxT(","), wxT(" "));
1142
1143 // also deal with the leading dot
1144 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
1145 {
1146 strExtensions.erase(0, 1);
1147 }
1148
1149 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
1150
1151 // finished with this line
1152 pc = NULL;
1153 }
1154
1155 // check our data integriry
1156 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1157 m_aTypes.Count() == m_aExtensions.Count() &&
1158 m_aTypes.Count() == m_aDescriptions.Count() );
1159
1160 return TRUE;
1161 }
1162
1163 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
1164 bool fallback)
1165 {
1166 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName.c_str());
1167
1168 wxTextFile file(strFileName);
1169 if ( !file.Open() )
1170 return FALSE;
1171
1172 // see the comments near the end of function for the reason we need these
1173 // variables (search for the next occurence of them)
1174 // indices of MIME types (in m_aTypes) we already found in this file
1175 wxArrayInt aEntryIndices;
1176 // aLastIndices[n] is the index of last element in
1177 // m_aEntries[aEntryIndices[n]] from this file
1178 wxArrayInt aLastIndices;
1179
1180 size_t nLineCount = file.GetLineCount();
1181 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1182 // now we're at the start of the line
1183 const wxChar *pc = file[nLine].c_str();
1184
1185 // skip whitespace
1186 while ( wxIsspace(*pc) )
1187 pc++;
1188
1189 // comment or empty string?
1190 if ( *pc == wxT('#') || *pc == wxT('\0') )
1191 continue;
1192
1193 // no, do parse
1194
1195 // what field are we currently in? The first 2 are fixed and there may
1196 // be an arbitrary number of other fields -- currently, we are not
1197 // interested in any of them, but we should parse them as well...
1198 enum
1199 {
1200 Field_Type,
1201 Field_OpenCmd,
1202 Field_Other
1203 } currentToken = Field_Type;
1204
1205 // the flags and field values on the current line
1206 bool needsterminal = FALSE,
1207 copiousoutput = FALSE;
1208 wxString strType,
1209 strOpenCmd,
1210 strPrintCmd,
1211 strTest,
1212 strDesc,
1213 curField; // accumulator
1214 for ( bool cont = TRUE; cont; pc++ ) {
1215 switch ( *pc ) {
1216 case wxT('\\'):
1217 // interpret the next character literally (notice that
1218 // backslash can be used for line continuation)
1219 if ( *++pc == wxT('\0') ) {
1220 // fetch the next line.
1221
1222 // pc currently points to nowhere, but after the next
1223 // pc++ in the for line it will point to the beginning
1224 // of the next line in the file
1225 pc = file[++nLine].c_str() - 1;
1226 }
1227 else {
1228 // just a normal character
1229 curField += *pc;
1230 }
1231 break;
1232
1233 case wxT('\0'):
1234 cont = FALSE; // end of line reached, exit the loop
1235
1236 // fall through
1237
1238 case wxT(';'):
1239 // store this field and start looking for the next one
1240
1241 // trim whitespaces from both sides
1242 curField.Trim(TRUE).Trim(FALSE);
1243
1244 switch ( currentToken ) {
1245 case Field_Type:
1246 strType = curField;
1247 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
1248 // we interpret "type" as "type/*"
1249 strType += wxT("/*");
1250 }
1251
1252 currentToken = Field_OpenCmd;
1253 break;
1254
1255 case Field_OpenCmd:
1256 strOpenCmd = curField;
1257
1258 currentToken = Field_Other;
1259 break;
1260
1261 case Field_Other:
1262 {
1263 // "good" mailcap entry?
1264 bool ok = TRUE;
1265
1266 // is this something of the form foo=bar?
1267 const wxChar *pEq = wxStrchr(curField, wxT('='));
1268 if ( pEq != NULL ) {
1269 wxString lhs = curField.BeforeFirst(wxT('=')),
1270 rhs = curField.AfterFirst(wxT('='));
1271
1272 lhs.Trim(TRUE); // from right
1273 rhs.Trim(FALSE); // from left
1274
1275 if ( lhs == wxT("print") )
1276 strPrintCmd = rhs;
1277 else if ( lhs == wxT("test") )
1278 strTest = rhs;
1279 else if ( lhs == wxT("description") ) {
1280 // it might be quoted
1281 if ( rhs[0u] == wxT('"') &&
1282 rhs.Last() == wxT('"') ) {
1283 strDesc = wxString(rhs.c_str() + 1,
1284 rhs.Len() - 2);
1285 }
1286 else {
1287 strDesc = rhs;
1288 }
1289 }
1290 else if ( lhs == wxT("compose") ||
1291 lhs == wxT("composetyped") ||
1292 lhs == wxT("notes") ||
1293 lhs == wxT("edit") )
1294 ; // ignore
1295 else
1296 ok = FALSE;
1297
1298 }
1299 else {
1300 // no, it's a simple flag
1301 // TODO support the flags:
1302 // 1. create an xterm for 'needsterminal'
1303 // 2. append "| $PAGER" for 'copiousoutput'
1304 if ( curField == wxT("needsterminal") )
1305 needsterminal = TRUE;
1306 else if ( curField == wxT("copiousoutput") )
1307 copiousoutput = TRUE;
1308 else if ( curField == wxT("textualnewlines") )
1309 ; // ignore
1310 else
1311 ok = FALSE;
1312 }
1313
1314 if ( !ok )
1315 {
1316 // we don't understand this field, but
1317 // Netscape stores info in it, so don't warn
1318 // about it
1319 if ( curField.Left(16u) != "x-mozilla-flags=" )
1320 {
1321 // don't flood the user with error
1322 // messages if we don't understand
1323 // something in his mailcap, but give
1324 // them in debug mode because this might
1325 // be useful for the programmer
1326 wxLogDebug
1327 (
1328 wxT("Mailcap file %s, line %d: "
1329 "unknown field '%s' for the "
1330 "MIME type '%s' ignored."),
1331 strFileName.c_str(),
1332 nLine + 1,
1333 curField.c_str(),
1334 strType.c_str()
1335 );
1336 }
1337 }
1338 }
1339
1340 // it already has this value
1341 //currentToken = Field_Other;
1342 break;
1343
1344 default:
1345 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1346 }
1347
1348 // next token starts immediately after ';'
1349 curField.Empty();
1350 break;
1351
1352 default:
1353 curField += *pc;
1354 }
1355 }
1356
1357 // check that we really read something reasonable
1358 if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
1359 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1360 "ignored."),
1361 strFileName.c_str(), nLine + 1);
1362 }
1363 else {
1364 MailCapEntry *entry = new MailCapEntry(strOpenCmd,
1365 strPrintCmd,
1366 strTest);
1367
1368 // NB: because of complications below (we must get entries priority
1369 // right), we can't use AddMailcapInfo() here, unfortunately.
1370 strType.MakeLower();
1371 int nIndex = m_aTypes.Index(strType);
1372 if ( nIndex == wxNOT_FOUND ) {
1373 // new file type
1374 m_aTypes.Add(strType);
1375
1376 m_aEntries.Add(entry);
1377 m_aExtensions.Add(wxT(""));
1378 m_aDescriptions.Add(strDesc);
1379 }
1380 else {
1381 // modify the existing entry: the entries in one and the same
1382 // file are read in top-to-bottom order, i.e. the entries read
1383 // first should be tried before the entries below. However,
1384 // the files read later should override the settings in the
1385 // files read before (except if fallback is TRUE), thus we
1386 // Insert() the new entry to the list if it has already
1387 // occured in _this_ file, but Prepend() it if it occured in
1388 // some of the previous ones and Append() to it in the
1389 // fallback case
1390
1391 if ( fallback ) {
1392 // 'fallback' parameter prevents the entries from this
1393 // file from overriding the other ones - always append
1394 MailCapEntry *entryOld = m_aEntries[nIndex];
1395 if ( entryOld )
1396 entry->Append(entryOld);
1397 else
1398 m_aEntries[nIndex] = entry;
1399 }
1400 else {
1401 int entryIndex = aEntryIndices.Index(nIndex);
1402 if ( entryIndex == wxNOT_FOUND ) {
1403 // first time in this file
1404 aEntryIndices.Add(nIndex);
1405 aLastIndices.Add(0);
1406
1407 entry->Prepend(m_aEntries[nIndex]);
1408 m_aEntries[nIndex] = entry;
1409 }
1410 else {
1411 // not the first time in _this_ file
1412 size_t nEntryIndex = (size_t)entryIndex;
1413 MailCapEntry *entryOld = m_aEntries[nIndex];
1414 if ( entryOld )
1415 entry->Insert(entryOld, aLastIndices[nEntryIndex]);
1416 else
1417 m_aEntries[nIndex] = entry;
1418
1419 // the indices were shifted by 1
1420 aLastIndices[nEntryIndex]++;
1421 }
1422 }
1423
1424 if ( !strDesc.IsEmpty() ) {
1425 // replace the old one - what else can we do??
1426 m_aDescriptions[nIndex] = strDesc;
1427 }
1428 }
1429 }
1430
1431 // check our data integriry
1432 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1433 m_aTypes.Count() == m_aExtensions.Count() &&
1434 m_aTypes.Count() == m_aDescriptions.Count() );
1435 }
1436
1437 return TRUE;
1438 }
1439
1440 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1441 {
1442 mimetypes.Empty();
1443
1444 wxString type;
1445 size_t count = m_aTypes.GetCount();
1446 for ( size_t n = 0; n < count; n++ )
1447 {
1448 // don't return template types from here (i.e. anything containg '*')
1449 type = m_aTypes[n];
1450 if ( type.Find(_T('*')) == wxNOT_FOUND )
1451 {
1452 mimetypes.Add(type);
1453 }
1454 }
1455
1456 return mimetypes.GetCount();
1457 }
1458
1459 #endif
1460 // wxUSE_FILE && wxUSE_TEXTFILE
1461