]> git.saurik.com Git - wxWidgets.git/blob - src/common/mimetype.cpp
Makeproj.cpp corrections; wxTextCtrl resource loading font bug cured
[wxWidgets.git] / src / common / mimetype.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: common/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 // Doesn't compile in WIN16 mode
37 #ifndef __WIN16__
38
39 #include "wx/log.h"
40 #include "wx/file.h"
41 #include "wx/intl.h"
42 #include "wx/dynarray.h"
43 #include "wx/confbase.h"
44
45 #ifdef __WXMSW__
46 #include "wx/msw/registry.h"
47 #include "windows.h"
48 #elif defined(__UNIX__) || defined(__WXPM__)
49 #include "wx/ffile.h"
50 #include "wx/textfile.h"
51 #include "wx/dir.h"
52 #include "wx/utils.h"
53 #include "wx/tokenzr.h"
54 #endif // OS
55
56 #include "wx/mimetype.h"
57
58 // other standard headers
59 #include <ctype.h>
60
61 // in case we're compiling in non-GUI mode
62 class WXDLLEXPORT wxIcon;
63
64 // ----------------------------------------------------------------------------
65 // private classes
66 // ----------------------------------------------------------------------------
67
68 // implementation classes, platform dependent
69 #ifdef __WXMSW__
70
71 // These classes use Windows registry to retrieve the required information.
72 //
73 // Keys used (not all of them are documented, so it might actually stop working
74 // in futur versions of Windows...):
75 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
76 // types, each key has a string value "Extension" which gives (dot preceded)
77 // extension for the files of this MIME type.
78 //
79 // 2. "HKCR\.ext" contains
80 // a) unnamed value containing the "filetype"
81 // b) value "Content Type" containing the MIME type
82 //
83 // 3. "HKCR\filetype" contains
84 // a) unnamed value containing the description
85 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
86 // an icon file
87 // c) shell\open\command and shell\open\print subkeys containing the commands
88 // to open/print the file (the positional parameters are introduced by %1,
89 // %2, ... in these strings, we change them to %s ourselves)
90
91 // although I don't know of any official documentation which mentions this
92 // location, uses it, so it isn't likely to change
93 static const wxChar *MIME_DATABASE_KEY = wxT("MIME\\Database\\Content Type\\");
94
95 class wxFileTypeImpl
96 {
97 public:
98 // ctor
99 wxFileTypeImpl() { m_info = NULL; }
100
101 // one of these Init() function must be called (ctor can't take any
102 // arguments because it's common)
103
104 // initialize us with our file type name and extension - in this case
105 // we will read all other data from the registry
106 void Init(const wxString& strFileType, const wxString& ext)
107 { m_strFileType = strFileType; m_ext = ext; }
108
109 // initialize us with a wxFileTypeInfo object - it contains all the
110 // data
111 void Init(const wxFileTypeInfo& info)
112 { m_info = &info; }
113
114 // implement accessor functions
115 bool GetExtensions(wxArrayString& extensions);
116 bool GetMimeType(wxString *mimeType) const;
117 bool GetIcon(wxIcon *icon) const;
118 bool GetDescription(wxString *desc) const;
119 bool GetOpenCommand(wxString *openCmd,
120 const wxFileType::MessageParameters& params) const;
121 bool GetPrintCommand(wxString *printCmd,
122 const wxFileType::MessageParameters& params) const;
123
124 private:
125 // helper function: reads the command corresponding to the specified verb
126 // from the registry (returns an empty string if not found)
127 wxString GetCommand(const wxChar *verb) const;
128
129 // we use either m_info or read the data from the registry if m_info == NULL
130 const wxFileTypeInfo *m_info;
131 wxString m_strFileType, // may be empty
132 m_ext;
133 };
134
135 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
136 #include "wx/arrimpl.cpp"
137 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
138
139 class wxMimeTypesManagerImpl
140 {
141 public:
142 // nothing to do here, we don't load any data but just go and fetch it from
143 // the registry when asked for
144 wxMimeTypesManagerImpl() { }
145
146 // implement containing class functions
147 wxFileType *GetFileTypeFromExtension(const wxString& ext);
148 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
149
150 size_t EnumAllFileTypes(wxArrayString& mimetypes);
151
152 // this are NOPs under Windows
153 bool ReadMailcap(const wxString& filename, bool fallback = TRUE)
154 { return TRUE; }
155 bool ReadMimeTypes(const wxString& filename)
156 { return TRUE; }
157
158 void AddFallback(const wxFileTypeInfo& ft) { m_fallbacks.Add(ft); }
159
160 private:
161 wxArrayFileTypeInfo m_fallbacks;
162 };
163
164 #elif defined( __WXMAC__ )
165
166 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
167 #include "wx/arrimpl.cpp"
168 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
169
170 class wxMimeTypesManagerImpl
171 {
172 public :
173 wxMimeTypesManagerImpl() { }
174
175 // implement containing class functions
176 wxFileType *GetFileTypeFromExtension(const wxString& ext);
177 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
178
179 size_t EnumAllFileTypes(wxArrayString& mimetypes);
180
181 // this are NOPs under MacOS
182 bool ReadMailcap(const wxString& filename, bool fallback = TRUE) { return TRUE; }
183 bool ReadMimeTypes(const wxString& filename) { return TRUE; }
184
185 void AddFallback(const wxFileTypeInfo& ft) { m_fallbacks.Add(ft); }
186
187 private:
188 wxArrayFileTypeInfo m_fallbacks;
189 };
190
191 class wxFileTypeImpl
192 {
193 public:
194 // initialize us with our file type name
195 void SetFileType(const wxString& strFileType)
196 { m_strFileType = strFileType; }
197 void SetExt(const wxString& ext)
198 { m_ext = ext; }
199
200 // implement accessor functions
201 bool GetExtensions(wxArrayString& extensions);
202 bool GetMimeType(wxString *mimeType) const;
203 bool GetIcon(wxIcon *icon) const;
204 bool GetDescription(wxString *desc) const;
205 bool GetOpenCommand(wxString *openCmd,
206 const wxFileType::MessageParameters&) const
207 { return GetCommand(openCmd, "open"); }
208 bool GetPrintCommand(wxString *printCmd,
209 const wxFileType::MessageParameters&) const
210 { return GetCommand(printCmd, "print"); }
211
212 private:
213 // helper function
214 bool GetCommand(wxString *command, const char *verb) const;
215
216 wxString m_strFileType, m_ext;
217 };
218
219 #else // Unix
220
221 // this class uses both mailcap and mime.types to gather information about file
222 // types.
223 //
224 // The information about mailcap file was extracted from metamail(1) sources and
225 // documentation.
226 //
227 // Format of mailcap file: spaces are ignored, each line is either a comment
228 // (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
229 // A backslash can be used to quote semicolons and newlines (and, in fact,
230 // anything else including itself).
231 //
232 // The first field is always the MIME type in the form of type/subtype (see RFC
233 // 822) where subtype may be '*' meaning "any". Following metamail, we accept
234 // "type" which means the same as "type/*", although I'm not sure whether this
235 // is standard.
236 //
237 // The second field is always the command to run. It is subject to
238 // parameter/filename expansion described below.
239 //
240 // All the following fields are optional and may not be present at all. If
241 // they're present they may appear in any order, although each of them should
242 // appear only once. The optional fields are the following:
243 // * notes=xxx is an uninterpreted string which is silently ignored
244 // * test=xxx is the command to be used to determine whether this mailcap line
245 // applies to our data or not. The RHS of this field goes through the
246 // parameter/filename expansion (as the 2nd field) and the resulting string
247 // is executed. The line applies only if the command succeeds, i.e. returns 0
248 // exit code.
249 // * print=xxx is the command to be used to print (and not view) the data of
250 // this type (parameter/filename expansion is done here too)
251 // * edit=xxx is the command to open/edit the data of this type
252 // * needsterminal means that a new console must be created for the viewer
253 // * copiousoutput means that the viewer doesn't interact with the user but
254 // produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
255 // good example), thus it might be a good idea to use some kind of paging
256 // mechanism.
257 // * textualnewlines means not to perform CR/LF translation (not honored)
258 // * compose and composetyped fields are used to determine the program to be
259 // called to create a new message pert in the specified format (unused).
260 //
261 // Parameter/filename xpansion:
262 // * %s is replaced with the (full) file name
263 // * %t is replaced with MIME type/subtype of the entry
264 // * for multipart type only %n is replaced with the nnumber of parts and %F is
265 // replaced by an array of (content-type, temporary file name) pairs for all
266 // message parts (TODO)
267 // * %{parameter} is replaced with the value of parameter taken from
268 // Content-type header line of the message.
269 //
270 // FIXME any docs with real descriptions of these files??
271 //
272 // There are 2 possible formats for mime.types file, one entry per line (used
273 // for global mime.types) and "expanded" format where an entry takes multiple
274 // lines (used for users mime.types).
275 //
276 // For both formats spaces are ignored and lines starting with a '#' are
277 // comments. Each record has one of two following forms:
278 // a) for "brief" format:
279 // <mime type> <space separated list of extensions>
280 // b) for "expanded" format:
281 // type=<mime type> \ desc="<description>" \ exts="ext"
282 //
283 // We try to autodetect the format of mime.types: if a non-comment line starts
284 // with "type=" we assume the second format, otherwise the first one.
285
286 // there may be more than one entry for one and the same mime type, to
287 // choose the right one we have to run the command specified in the test
288 // field on our data.
289 class MailCapEntry
290 {
291 public:
292 // ctor
293 MailCapEntry(const wxString& openCmd,
294 const wxString& printCmd,
295 const wxString& testCmd)
296 : m_openCmd(openCmd), m_printCmd(printCmd), m_testCmd(testCmd)
297 {
298 m_next = NULL;
299 }
300
301 // accessors
302 const wxString& GetOpenCmd() const { return m_openCmd; }
303 const wxString& GetPrintCmd() const { return m_printCmd; }
304 const wxString& GetTestCmd() const { return m_testCmd; }
305
306 MailCapEntry *GetNext() const { return m_next; }
307
308 // operations
309 // prepend this element to the list
310 void Prepend(MailCapEntry *next) { m_next = next; }
311 // insert into the list at given position
312 void Insert(MailCapEntry *next, size_t pos)
313 {
314 // FIXME slooow...
315 MailCapEntry *cur;
316 size_t n = 0;
317 for ( cur = next; cur != NULL; cur = cur->m_next, n++ ) {
318 if ( n == pos )
319 break;
320 }
321
322 wxASSERT_MSG( n == pos, wxT("invalid position in MailCapEntry::Insert") );
323
324 m_next = cur->m_next;
325 cur->m_next = this;
326 }
327 // append this element to the list
328 void Append(MailCapEntry *next)
329 {
330 wxCHECK_RET( next != NULL, wxT("Append()ing to what?") );
331
332 // FIXME slooow...
333 MailCapEntry *cur;
334 for ( cur = next; cur->m_next != NULL; cur = cur->m_next )
335 ;
336
337 cur->m_next = this;
338
339 wxASSERT_MSG( !m_next, wxT("Append()ing element already in the list?") );
340 }
341
342 private:
343 wxString m_openCmd, // command to use to open/view the file
344 m_printCmd, // print
345 m_testCmd; // only apply this entry if test yields
346 // true (i.e. the command returns 0)
347
348 MailCapEntry *m_next; // in the linked list
349 };
350
351 WX_DEFINE_ARRAY(MailCapEntry *, ArrayTypeEntries);
352
353 // the base class which may be used to find an icon for the MIME type
354 class wxMimeTypeIconHandler
355 {
356 public:
357 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon) = 0;
358
359 // this function fills manager with MIME types information gathered
360 // (as side effect) when searching for icons. This may be particularly
361 // useful if mime.types is incomplete (e.g. RedHat distributions).
362 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager) = 0;
363 };
364
365 WX_DEFINE_ARRAY(wxMimeTypeIconHandler *, ArrayIconHandlers);
366
367 // the icon handler which uses GNOME MIME database
368 class wxGNOMEIconHandler : public wxMimeTypeIconHandler
369 {
370 public:
371 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon);
372 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager) {}
373
374 private:
375 void Init();
376 void LoadIconsFromKeyFile(const wxString& filename);
377 void LoadKeyFilesFromDir(const wxString& dirbase);
378
379 static bool m_inited;
380
381 static wxSortedArrayString ms_mimetypes;
382 static wxArrayString ms_icons;
383 };
384
385 // the icon handler which uses KDE MIME database
386 class wxKDEIconHandler : public wxMimeTypeIconHandler
387 {
388 public:
389 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon);
390 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager);
391
392 private:
393 void LoadLinksForMimeSubtype(const wxString& dirbase,
394 const wxString& subdir,
395 const wxString& filename,
396 const wxArrayString& icondirs);
397 void LoadLinksForMimeType(const wxString& dirbase,
398 const wxString& subdir,
399 const wxArrayString& icondirs);
400 void LoadLinkFilesFromDir(const wxString& dirbase,
401 const wxArrayString& icondirs);
402 void Init();
403
404 static bool m_inited;
405
406 static wxSortedArrayString ms_mimetypes;
407 static wxArrayString ms_icons;
408
409 static wxArrayString ms_infoTypes;
410 static wxArrayString ms_infoDescriptions;
411 static wxArrayString ms_infoExtensions;
412 };
413
414 // this is the real wxMimeTypesManager for Unix
415 class wxMimeTypesManagerImpl
416 {
417 friend class wxFileTypeImpl; // give it access to m_aXXX variables
418
419 public:
420 // ctor loads all info into memory for quicker access later on
421 // TODO it would be nice to load them all, but parse on demand only...
422 wxMimeTypesManagerImpl();
423
424 // implement containing class functions
425 wxFileType *GetFileTypeFromExtension(const wxString& ext);
426 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
427
428 size_t EnumAllFileTypes(wxArrayString& mimetypes);
429
430 bool ReadMailcap(const wxString& filename, bool fallback = FALSE);
431 bool ReadMimeTypes(const wxString& filename);
432
433 void AddFallback(const wxFileTypeInfo& filetype);
434
435 // add information about the given mimetype
436 void AddMimeTypeInfo(const wxString& mimetype,
437 const wxString& extensions,
438 const wxString& description);
439 void AddMailcapInfo(const wxString& strType,
440 const wxString& strOpenCmd,
441 const wxString& strPrintCmd,
442 const wxString& strTest,
443 const wxString& strDesc);
444
445 // accessors
446 // get the string containing space separated extensions for the given
447 // file type
448 wxString GetExtension(size_t index) { return m_aExtensions[index]; }
449
450 // get the array of icon handlers
451 static ArrayIconHandlers& GetIconHandlers();
452
453 private:
454 wxArrayString m_aTypes, // MIME types
455 m_aDescriptions, // descriptions (just some text)
456 m_aExtensions; // space separated list of extensions
457 ArrayTypeEntries m_aEntries; // commands and tests for this file type
458
459 // head of the linked list of the icon handlers
460 static ArrayIconHandlers ms_iconHandlers;
461 };
462
463 class wxFileTypeImpl
464 {
465 public:
466 // initialization functions
467 void Init(wxMimeTypesManagerImpl *manager, size_t index)
468 { m_manager = manager; m_index = index; }
469
470 // accessors
471 bool GetExtensions(wxArrayString& extensions);
472 bool GetMimeType(wxString *mimeType) const
473 { *mimeType = m_manager->m_aTypes[m_index]; return TRUE; }
474 bool GetIcon(wxIcon *icon) const;
475 bool GetDescription(wxString *desc) const
476 { *desc = m_manager->m_aDescriptions[m_index]; return TRUE; }
477
478 bool GetOpenCommand(wxString *openCmd,
479 const wxFileType::MessageParameters& params) const
480 {
481 return GetExpandedCommand(openCmd, params, TRUE);
482 }
483
484 bool GetPrintCommand(wxString *printCmd,
485 const wxFileType::MessageParameters& params) const
486 {
487 return GetExpandedCommand(printCmd, params, FALSE);
488 }
489
490 private:
491 // get the entry which passes the test (may return NULL)
492 MailCapEntry *GetEntry(const wxFileType::MessageParameters& params) const;
493
494 // choose the correct entry to use and expand the command
495 bool GetExpandedCommand(wxString *expandedCmd,
496 const wxFileType::MessageParameters& params,
497 bool open) const;
498
499 wxMimeTypesManagerImpl *m_manager;
500 size_t m_index; // in the wxMimeTypesManagerImpl arrays
501 };
502
503 #endif // OS type
504
505 // ============================================================================
506 // common classes
507 // ============================================================================
508
509 // ----------------------------------------------------------------------------
510 // wxFileTypeInfo
511 // ----------------------------------------------------------------------------
512
513 wxFileTypeInfo::wxFileTypeInfo(const char *mimeType,
514 const char *openCmd,
515 const char *printCmd,
516 const char *desc,
517 ...)
518 : m_mimeType(mimeType),
519 m_openCmd(openCmd),
520 m_printCmd(printCmd),
521 m_desc(desc)
522 {
523 va_list argptr;
524 va_start(argptr, desc);
525
526 for ( ;; )
527 {
528 const char *ext = va_arg(argptr, const char *);
529 if ( !ext )
530 {
531 // NULL terminates the list
532 break;
533 }
534
535 m_exts.Add(ext);
536 }
537
538 va_end(argptr);
539 }
540
541 // ============================================================================
542 // implementation of the wrapper classes
543 // ============================================================================
544
545 // ----------------------------------------------------------------------------
546 // wxFileType
547 // ----------------------------------------------------------------------------
548
549 wxString wxFileType::ExpandCommand(const wxString& command,
550 const wxFileType::MessageParameters& params)
551 {
552 bool hasFilename = FALSE;
553
554 wxString str;
555 for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
556 if ( *pc == wxT('%') ) {
557 switch ( *++pc ) {
558 case wxT('s'):
559 // '%s' expands into file name (quoted because it might
560 // contain spaces) - except if there are already quotes
561 // there because otherwise some programs may get confused
562 // by double double quotes
563 #if 0
564 if ( *(pc - 2) == wxT('"') )
565 str << params.GetFileName();
566 else
567 str << wxT('"') << params.GetFileName() << wxT('"');
568 #endif
569 str << params.GetFileName();
570 hasFilename = TRUE;
571 break;
572
573 case wxT('t'):
574 // '%t' expands into MIME type (quote it too just to be
575 // consistent)
576 str << wxT('\'') << params.GetMimeType() << wxT('\'');
577 break;
578
579 case wxT('{'):
580 {
581 const wxChar *pEnd = wxStrchr(pc, wxT('}'));
582 if ( pEnd == NULL ) {
583 wxString mimetype;
584 wxLogWarning(_("Unmatched '{' in an entry for "
585 "mime type %s."),
586 params.GetMimeType().c_str());
587 str << wxT("%{");
588 }
589 else {
590 wxString param(pc + 1, pEnd - pc - 1);
591 str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
592 pc = pEnd;
593 }
594 }
595 break;
596
597 case wxT('n'):
598 case wxT('F'):
599 // TODO %n is the number of parts, %F is an array containing
600 // the names of temp files these parts were written to
601 // and their mime types.
602 break;
603
604 default:
605 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
606 *pc, command.c_str());
607 str << *pc;
608 }
609 }
610 else {
611 str << *pc;
612 }
613 }
614
615 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
616 // the program will accept the data on stdin: so give it to it!
617 if ( !hasFilename && !str.IsEmpty() ) {
618 str << wxT(" < '") << params.GetFileName() << wxT('\'');
619 }
620
621 return str;
622 }
623
624 wxFileType::wxFileType()
625 {
626 m_impl = new wxFileTypeImpl;
627 }
628
629 wxFileType::~wxFileType()
630 {
631 delete m_impl;
632 }
633
634 bool wxFileType::GetExtensions(wxArrayString& extensions)
635 {
636 return m_impl->GetExtensions(extensions);
637 }
638
639 bool wxFileType::GetMimeType(wxString *mimeType) const
640 {
641 return m_impl->GetMimeType(mimeType);
642 }
643
644 bool wxFileType::GetIcon(wxIcon *icon) const
645 {
646 return m_impl->GetIcon(icon);
647 }
648
649 bool wxFileType::GetDescription(wxString *desc) const
650 {
651 return m_impl->GetDescription(desc);
652 }
653
654 bool
655 wxFileType::GetOpenCommand(wxString *openCmd,
656 const wxFileType::MessageParameters& params) const
657 {
658 return m_impl->GetOpenCommand(openCmd, params);
659 }
660
661 bool
662 wxFileType::GetPrintCommand(wxString *printCmd,
663 const wxFileType::MessageParameters& params) const
664 {
665 return m_impl->GetPrintCommand(printCmd, params);
666 }
667
668 // ----------------------------------------------------------------------------
669 // wxMimeTypesManager
670 // ----------------------------------------------------------------------------
671
672 bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
673 const wxString& wildcard)
674 {
675 wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
676 wxT("first MIME type can't contain wildcards") );
677
678 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
679 if ( wildcard.BeforeFirst(wxT('/')).IsSameAs(mimeType.BeforeFirst(wxT('/')), FALSE) )
680 {
681 wxString strSubtype = wildcard.AfterFirst(wxT('/'));
682
683 if ( strSubtype == wxT("*") ||
684 strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), FALSE) )
685 {
686 // matches (either exactly or it's a wildcard)
687 return TRUE;
688 }
689 }
690
691 return FALSE;
692 }
693
694 wxMimeTypesManager::wxMimeTypesManager()
695 {
696 m_impl = new wxMimeTypesManagerImpl;
697 }
698
699 wxMimeTypesManager::~wxMimeTypesManager()
700 {
701 delete m_impl;
702 }
703
704 wxFileType *
705 wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
706 {
707 return m_impl->GetFileTypeFromExtension(ext);
708 }
709
710 wxFileType *
711 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
712 {
713 return m_impl->GetFileTypeFromMimeType(mimeType);
714 }
715
716 bool wxMimeTypesManager::ReadMailcap(const wxString& filename, bool fallback)
717 {
718 return m_impl->ReadMailcap(filename, fallback);
719 }
720
721 bool wxMimeTypesManager::ReadMimeTypes(const wxString& filename)
722 {
723 return m_impl->ReadMimeTypes(filename);
724 }
725
726 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
727 {
728 for ( const wxFileTypeInfo *ft = filetypes; ft->IsValid(); ft++ ) {
729 m_impl->AddFallback(*ft);
730 }
731 }
732
733 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
734 {
735 return m_impl->EnumAllFileTypes(mimetypes);
736 }
737
738 // ============================================================================
739 // real (OS specific) implementation
740 // ============================================================================
741
742 #ifdef __WXMSW__
743
744 wxString wxFileTypeImpl::GetCommand(const wxChar *verb) const
745 {
746 // suppress possible error messages
747 wxLogNull nolog;
748 wxString strKey;
749
750 if ( wxRegKey(wxRegKey::HKCR, m_ext + _T("\\shell")).Exists() )
751 strKey = m_ext;
752 if ( wxRegKey(wxRegKey::HKCR, m_strFileType + _T("\\shell")).Exists() )
753 strKey = m_strFileType;
754
755 if ( !strKey )
756 {
757 // no info
758 return wxEmptyString;
759 }
760
761 strKey << wxT("\\shell\\") << verb << wxT("\\command");
762 wxRegKey key(wxRegKey::HKCR, strKey);
763 wxString command;
764 if ( key.Open() ) {
765 // it's the default value of the key
766 if ( key.QueryValue(wxT(""), command) ) {
767 // transform it from '%1' to '%s' style format string
768
769 // NB: we don't make any attempt to verify that the string is valid,
770 // i.e. doesn't contain %2, or second %1 or .... But we do make
771 // sure that we return a string with _exactly_ one '%s'!
772 bool foundFilename = FALSE;
773 size_t len = command.Len();
774 for ( size_t n = 0; (n < len) && !foundFilename; n++ ) {
775 if ( command[n] == wxT('%') &&
776 (n + 1 < len) && command[n + 1] == wxT('1') ) {
777 // replace it with '%s'
778 command[n + 1] = wxT('s');
779
780 foundFilename = TRUE;
781 }
782 }
783
784 if ( !foundFilename ) {
785 // we didn't find any '%1'!
786 // HACK: append the filename at the end, hope that it will do
787 command << wxT(" %s");
788 }
789 }
790 }
791 //else: no such file type or no value, will return empty string
792
793 return command;
794 }
795
796 bool
797 wxFileTypeImpl::GetOpenCommand(wxString *openCmd,
798 const wxFileType::MessageParameters& params)
799 const
800 {
801 wxString cmd;
802 if ( m_info ) {
803 cmd = m_info->GetOpenCommand();
804 }
805 else {
806 cmd = GetCommand(wxT("open"));
807 }
808
809 *openCmd = wxFileType::ExpandCommand(cmd, params);
810
811 return !openCmd->IsEmpty();
812 }
813
814 bool
815 wxFileTypeImpl::GetPrintCommand(wxString *printCmd,
816 const wxFileType::MessageParameters& params)
817 const
818 {
819 wxString cmd;
820 if ( m_info ) {
821 cmd = m_info->GetPrintCommand();
822 }
823 else {
824 cmd = GetCommand(wxT("print"));
825 }
826
827 *printCmd = wxFileType::ExpandCommand(cmd, params);
828
829 return !printCmd->IsEmpty();
830 }
831
832 // TODO this function is half implemented
833 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
834 {
835 if ( m_info ) {
836 extensions = m_info->GetExtensions();
837
838 return TRUE;
839 }
840 else if ( m_ext.IsEmpty() ) {
841 // the only way to get the list of extensions from the file type is to
842 // scan through all extensions in the registry - too slow...
843 return FALSE;
844 }
845 else {
846 extensions.Empty();
847 extensions.Add(m_ext);
848
849 // it's a lie too, we don't return _all_ extensions...
850 return TRUE;
851 }
852 }
853
854 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
855 {
856 if ( m_info ) {
857 // we already have it
858 *mimeType = m_info->GetMimeType();
859
860 return TRUE;
861 }
862
863 // suppress possible error messages
864 wxLogNull nolog;
865 wxRegKey key(wxRegKey::HKCR, wxT(".") + m_ext);
866 if ( key.Open() && key.QueryValue(wxT("Content Type"), *mimeType) ) {
867 return TRUE;
868 }
869 else {
870 return FALSE;
871 }
872 }
873
874 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
875 {
876 #if wxUSE_GUI
877 if ( m_info ) {
878 // we don't have icons in the fallback resources
879 return FALSE;
880 }
881
882 wxString strIconKey;
883 strIconKey << m_strFileType << wxT("\\DefaultIcon");
884
885 // suppress possible error messages
886 wxLogNull nolog;
887 wxRegKey key(wxRegKey::HKCR, strIconKey);
888
889 if ( key.Open() ) {
890 wxString strIcon;
891 // it's the default value of the key
892 if ( key.QueryValue(wxT(""), strIcon) ) {
893 // the format is the following: <full path to file>, <icon index>
894 // NB: icon index may be negative as well as positive and the full
895 // path may contain the environment variables inside '%'
896 wxString strFullPath = strIcon.BeforeLast(wxT(',')),
897 strIndex = strIcon.AfterLast(wxT(','));
898
899 // index may be omitted, in which case BeforeLast(',') is empty and
900 // AfterLast(',') is the whole string
901 if ( strFullPath.IsEmpty() ) {
902 strFullPath = strIndex;
903 strIndex = wxT("0");
904 }
905
906 wxString strExpPath = wxExpandEnvVars(strFullPath);
907 int nIndex = wxAtoi(strIndex);
908
909 HICON hIcon = ExtractIcon(GetModuleHandle(NULL), strExpPath, nIndex);
910 switch ( (int)hIcon ) {
911 case 0: // means no icons were found
912 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
913 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
914 key.GetName().c_str());
915 break;
916
917 default:
918 icon->SetHICON((WXHICON)hIcon);
919 return TRUE;
920 }
921 }
922 }
923
924 // no such file type or no value or incorrect icon entry
925 #endif // wxUSE_GUI
926
927 return FALSE;
928 }
929
930 bool wxFileTypeImpl::GetDescription(wxString *desc) const
931 {
932 if ( m_info ) {
933 // we already have it
934 *desc = m_info->GetDescription();
935
936 return TRUE;
937 }
938
939 // suppress possible error messages
940 wxLogNull nolog;
941 wxRegKey key(wxRegKey::HKCR, m_strFileType);
942
943 if ( key.Open() ) {
944 // it's the default value of the key
945 if ( key.QueryValue(wxT(""), *desc) ) {
946 return TRUE;
947 }
948 }
949
950 return FALSE;
951 }
952
953 // extension -> file type
954 wxFileType *
955 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
956 {
957 // add the leading point if necessary
958 wxString str;
959 if ( ext[0u] != wxT('.') ) {
960 str = wxT('.');
961 }
962 str << ext;
963
964 // suppress possible error messages
965 wxLogNull nolog;
966
967 bool knownExtension = FALSE;
968
969 wxString strFileType;
970 wxRegKey key(wxRegKey::HKCR, str);
971 if ( key.Open() ) {
972 // it's the default value of the key
973 if ( key.QueryValue(wxT(""), strFileType) ) {
974 // create the new wxFileType object
975 wxFileType *fileType = new wxFileType;
976 fileType->m_impl->Init(strFileType, ext);
977
978 return fileType;
979 }
980 else {
981 // this extension doesn't have a filetype, but it's known to the
982 // system and may be has some other useful keys (open command or
983 // content-type), so still return a file type object for it
984 knownExtension = TRUE;
985 }
986 }
987
988 // check the fallbacks
989 // TODO linear search is potentially slow, perhaps we should use a sorted
990 // array?
991 size_t count = m_fallbacks.GetCount();
992 for ( size_t n = 0; n < count; n++ ) {
993 if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
994 wxFileType *fileType = new wxFileType;
995 fileType->m_impl->Init(m_fallbacks[n]);
996
997 return fileType;
998 }
999 }
1000
1001 if ( knownExtension )
1002 {
1003 wxFileType *fileType = new wxFileType;
1004 fileType->m_impl->Init(wxEmptyString, ext);
1005
1006 return fileType;
1007 }
1008 else
1009 {
1010 // unknown extension
1011 return NULL;
1012 }
1013 }
1014
1015 // MIME type -> extension -> file type
1016 wxFileType *
1017 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1018 {
1019 wxString strKey = MIME_DATABASE_KEY;
1020 strKey << mimeType;
1021
1022 // suppress possible error messages
1023 wxLogNull nolog;
1024
1025 wxString ext;
1026 wxRegKey key(wxRegKey::HKCR, strKey);
1027 if ( key.Open() ) {
1028 if ( key.QueryValue(wxT("Extension"), ext) ) {
1029 return GetFileTypeFromExtension(ext);
1030 }
1031 }
1032
1033 // check the fallbacks
1034 // TODO linear search is potentially slow, perhaps we should use a sorted
1035 // array?
1036 size_t count = m_fallbacks.GetCount();
1037 for ( size_t n = 0; n < count; n++ ) {
1038 if ( wxMimeTypesManager::IsOfType(mimeType,
1039 m_fallbacks[n].GetMimeType()) ) {
1040 wxFileType *fileType = new wxFileType;
1041 fileType->m_impl->Init(m_fallbacks[n]);
1042
1043 return fileType;
1044 }
1045 }
1046
1047 // unknown MIME type
1048 return NULL;
1049 }
1050
1051 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1052 {
1053 // enumerate all keys under MIME_DATABASE_KEY
1054 wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
1055
1056 wxString type;
1057 long cookie;
1058 bool cont = key.GetFirstKey(type, cookie);
1059 while ( cont )
1060 {
1061 mimetypes.Add(type);
1062
1063 cont = key.GetNextKey(type, cookie);
1064 }
1065
1066 return mimetypes.GetCount();
1067 }
1068
1069 #elif defined ( __WXMAC__ )
1070
1071 bool wxFileTypeImpl::GetCommand(wxString *command, const char *verb) const
1072 {
1073 return FALSE;
1074 }
1075
1076 // @@ this function is half implemented
1077 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1078 {
1079 return FALSE;
1080 }
1081
1082 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
1083 {
1084 if ( m_strFileType.Length() > 0 )
1085 {
1086 *mimeType = m_strFileType ;
1087 return TRUE ;
1088 }
1089 else
1090 return FALSE;
1091 }
1092
1093 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
1094 {
1095 // no such file type or no value or incorrect icon entry
1096 return FALSE;
1097 }
1098
1099 bool wxFileTypeImpl::GetDescription(wxString *desc) const
1100 {
1101 return FALSE;
1102 }
1103
1104 // extension -> file type
1105 wxFileType *
1106 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& e)
1107 {
1108 wxString ext = e ;
1109 ext = ext.Lower() ;
1110 if ( ext == "txt" )
1111 {
1112 wxFileType *fileType = new wxFileType;
1113 fileType->m_impl->SetFileType("text/text");
1114 fileType->m_impl->SetExt(ext);
1115 return fileType;
1116 }
1117 else if ( ext == "htm" || ext == "html" )
1118 {
1119 wxFileType *fileType = new wxFileType;
1120 fileType->m_impl->SetFileType("text/html");
1121 fileType->m_impl->SetExt(ext);
1122 return fileType;
1123 }
1124 else if ( ext == "gif" )
1125 {
1126 wxFileType *fileType = new wxFileType;
1127 fileType->m_impl->SetFileType("image/gif");
1128 fileType->m_impl->SetExt(ext);
1129 return fileType;
1130 }
1131 else if ( ext == "png" )
1132 {
1133 wxFileType *fileType = new wxFileType;
1134 fileType->m_impl->SetFileType("image/png");
1135 fileType->m_impl->SetExt(ext);
1136 return fileType;
1137 }
1138 else if ( ext == "jpg" || ext == "jpeg" )
1139 {
1140 wxFileType *fileType = new wxFileType;
1141 fileType->m_impl->SetFileType("image/jpeg");
1142 fileType->m_impl->SetExt(ext);
1143 return fileType;
1144 }
1145 else if ( ext == "bmp" )
1146 {
1147 wxFileType *fileType = new wxFileType;
1148 fileType->m_impl->SetFileType("image/bmp");
1149 fileType->m_impl->SetExt(ext);
1150 return fileType;
1151 }
1152 else if ( ext == "tif" || ext == "tiff" )
1153 {
1154 wxFileType *fileType = new wxFileType;
1155 fileType->m_impl->SetFileType("image/tiff");
1156 fileType->m_impl->SetExt(ext);
1157 return fileType;
1158 }
1159 else if ( ext == "xpm" )
1160 {
1161 wxFileType *fileType = new wxFileType;
1162 fileType->m_impl->SetFileType("image/xpm");
1163 fileType->m_impl->SetExt(ext);
1164 return fileType;
1165 }
1166 else if ( ext == "xbm" )
1167 {
1168 wxFileType *fileType = new wxFileType;
1169 fileType->m_impl->SetFileType("image/xbm");
1170 fileType->m_impl->SetExt(ext);
1171 return fileType;
1172 }
1173
1174 // unknown extension
1175 return NULL;
1176 }
1177
1178 // MIME type -> extension -> file type
1179 wxFileType *
1180 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1181 {
1182 return NULL;
1183 }
1184
1185 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1186 {
1187 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1188
1189 return 0;
1190 }
1191
1192 #else // Unix
1193
1194 // ============================================================================
1195 // Unix implementation
1196 // ============================================================================
1197
1198 // ----------------------------------------------------------------------------
1199 // various statics
1200 // ----------------------------------------------------------------------------
1201
1202 static wxGNOMEIconHandler gs_iconHandlerGNOME;
1203 static wxKDEIconHandler gs_iconHandlerKDE;
1204
1205 bool wxGNOMEIconHandler::m_inited = FALSE;
1206 wxSortedArrayString wxGNOMEIconHandler::ms_mimetypes;
1207 wxArrayString wxGNOMEIconHandler::ms_icons;
1208
1209 bool wxKDEIconHandler::m_inited = FALSE;
1210 wxSortedArrayString wxKDEIconHandler::ms_mimetypes;
1211 wxArrayString wxKDEIconHandler::ms_icons;
1212
1213 wxArrayString wxKDEIconHandler::ms_infoTypes;
1214 wxArrayString wxKDEIconHandler::ms_infoDescriptions;
1215 wxArrayString wxKDEIconHandler::ms_infoExtensions;
1216
1217
1218 ArrayIconHandlers wxMimeTypesManagerImpl::ms_iconHandlers;
1219
1220 // ----------------------------------------------------------------------------
1221 // wxGNOMEIconHandler
1222 // ----------------------------------------------------------------------------
1223
1224 // GNOME stores the info we're interested in in several locations:
1225 // 1. xxx.keys files under /usr/share/mime-info
1226 // 2. xxx.keys files under ~/.gnome/mime-info
1227 //
1228 // The format of xxx.keys file is the following:
1229 //
1230 // mimetype/subtype:
1231 // field=value
1232 //
1233 // with blank lines separating the entries and indented lines starting with
1234 // TABs. We're interested in the field icon-filename whose value is the path
1235 // containing the icon.
1236
1237 void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString& filename)
1238 {
1239 wxTextFile textfile(filename);
1240 if ( !textfile.Open() )
1241 return;
1242
1243 // values for the entry being parsed
1244 wxString curMimeType, curIconFile;
1245
1246 const wxChar *pc;
1247 size_t nLineCount = textfile.GetLineCount();
1248 for ( size_t nLine = 0; ; nLine++ )
1249 {
1250 if ( nLine < nLineCount )
1251 {
1252 pc = textfile[nLine].c_str();
1253 if ( *pc == _T('#') )
1254 {
1255 // skip comments
1256 continue;
1257 }
1258 }
1259 else
1260 {
1261 // so that we will fall into the "if" below
1262 pc = NULL;
1263 }
1264
1265 if ( !pc || !*pc )
1266 {
1267 // end of the entry
1268 if ( !!curMimeType && !!curIconFile )
1269 {
1270 // do we already know this mimetype?
1271 int i = ms_mimetypes.Index(curMimeType);
1272 if ( i == wxNOT_FOUND )
1273 {
1274 // add a new entry
1275 size_t n = ms_mimetypes.Add(curMimeType);
1276 ms_icons.Insert(curIconFile, n);
1277 }
1278 else
1279 {
1280 // replace the existing one (this means that the directories
1281 // should be searched in order of increased priority!)
1282 ms_icons[(size_t)i] = curIconFile;
1283 }
1284 }
1285
1286 if ( !pc )
1287 {
1288 // the end - this can only happen if nLine == nLineCount
1289 break;
1290 }
1291
1292 curIconFile.Empty();
1293
1294 continue;
1295 }
1296
1297 // what do we have here?
1298 if ( *pc == _T('\t') )
1299 {
1300 // this is a field=value ling
1301 pc++; // skip leading TAB
1302
1303 static const int lenField = 13; // strlen("icon-filename")
1304 if ( wxStrncmp(pc, _T("icon-filename"), lenField) == 0 )
1305 {
1306 // skip '=' which follows and take everything left until the end
1307 // of line
1308 curIconFile = pc + lenField + 1;
1309 }
1310 //else: some other field, we don't care
1311 }
1312 else
1313 {
1314 // this is the start of the new section
1315 curMimeType.Empty();
1316
1317 while ( *pc != _T(':') && *pc != _T('\0') )
1318 {
1319 curMimeType += *pc++;
1320 }
1321
1322 if ( !*pc )
1323 {
1324 // we reached the end of line without finding the colon,
1325 // something is wrong - ignore this line completely
1326 wxLogDebug(_T("Unreckognized line %d in file '%s' ignored"),
1327 nLine + 1, filename.c_str());
1328
1329 break;
1330 }
1331 }
1332 }
1333 }
1334
1335 void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString& dirbase)
1336 {
1337 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
1338 _T("base directory shouldn't end with a slash") );
1339
1340 wxString dirname = dirbase;
1341 dirname << _T("/mime-info");
1342
1343 if ( !wxDir::Exists(dirname) )
1344 return;
1345
1346 wxDir dir(dirname);
1347 if ( !dir.IsOpened() )
1348 return;
1349
1350 // we will concatenate it with filename to get the full path below
1351 dirname += _T('/');
1352
1353 wxString filename;
1354 bool cont = dir.GetFirst(&filename, _T("*.keys"), wxDIR_FILES);
1355 while ( cont )
1356 {
1357 LoadIconsFromKeyFile(dirname + filename);
1358
1359 cont = dir.GetNext(&filename);
1360 }
1361 }
1362
1363 void wxGNOMEIconHandler::Init()
1364 {
1365 wxArrayString dirs;
1366 dirs.Add(_T("/usr/share"));
1367
1368 wxString gnomedir;
1369 wxGetHomeDir( &gnomedir );
1370 gnomedir += _T("/.gnome");
1371 dirs.Add( gnomedir );
1372
1373 size_t nDirs = dirs.GetCount();
1374 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1375 {
1376 LoadKeyFilesFromDir(dirs[nDir]);
1377 }
1378
1379 m_inited = TRUE;
1380 }
1381
1382 bool wxGNOMEIconHandler::GetIcon(const wxString& mimetype, wxIcon *icon)
1383 {
1384 if ( !m_inited )
1385 {
1386 Init();
1387 }
1388
1389 int index = ms_mimetypes.Index(mimetype);
1390 if ( index == wxNOT_FOUND )
1391 return FALSE;
1392
1393 wxString iconname = ms_icons[(size_t)index];
1394
1395 #if wxUSE_GUI
1396 *icon = wxIcon(iconname);
1397 #else
1398 // helpful for testing in console mode
1399 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
1400 mimetype.c_str(), iconname.c_str());
1401 #endif
1402
1403 return TRUE;
1404 }
1405
1406 // ----------------------------------------------------------------------------
1407 // wxKDEIconHandler
1408 // ----------------------------------------------------------------------------
1409
1410 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
1411 // may be found in either of the following locations
1412 //
1413 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
1414 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
1415 //
1416 // The format of a .kdelnk file is almost the same as the one used by
1417 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
1418 // value for the entry "Type"
1419
1420 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString& dirbase,
1421 const wxString& subdir,
1422 const wxString& filename,
1423 const wxArrayString& icondirs)
1424 {
1425 wxFFile file(dirbase + filename);
1426 if ( !file.IsOpened() )
1427 return;
1428
1429 // construct mimetype from the directory name and the basename of the
1430 // file (it always has .kdelnk extension)
1431 wxString mimetype;
1432 mimetype << subdir << _T('/') << filename.BeforeLast(_T('.'));
1433
1434 // these files are small, slurp the entire file at once
1435 wxString text;
1436 if ( !file.ReadAll(&text) )
1437 return;
1438
1439 int pos;
1440 const wxChar *pc;
1441
1442 // before trying to find an icon, grab mimetype information
1443 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
1444 // have edited it in control panel...)
1445
1446 wxString mime_extension, mime_desc;
1447
1448 pos = wxNOT_FOUND;
1449 if (wxGetLocale() != NULL)
1450 mime_desc = _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
1451 if (pos == wxNOT_FOUND) mime_desc = _T("Comment=");
1452 pos = text.Find(mime_desc);
1453 if (pos == wxNOT_FOUND) mime_desc = wxEmptyString;
1454 else
1455 {
1456 pc = text.c_str() + pos + mime_desc.Length();
1457 mime_desc = wxEmptyString;
1458 while ( *pc && *pc != _T('\n') ) mime_desc += *pc++;
1459 }
1460
1461 pos = text.Find(_T("Patterns="));
1462 if (pos != wxNOT_FOUND)
1463 {
1464 wxString exts;
1465 pc = text.c_str() + pos + 9;
1466 while ( *pc && *pc != _T('\n') ) exts += *pc++;
1467 wxStringTokenizer tokenizer(exts, _T(";"));
1468 wxString e;
1469
1470 while (tokenizer.HasMoreTokens())
1471 {
1472 e = tokenizer.GetNextToken();
1473 if (e.Left(2) != _T("*.")) continue; // don't support too difficult patterns
1474 mime_extension << e.Mid(2);
1475 mime_extension << _T(' ');
1476 }
1477 mime_extension.RemoveLast();
1478 }
1479
1480 ms_infoTypes.Add(mimetype);
1481 ms_infoDescriptions.Add(mime_desc);
1482 ms_infoExtensions.Add(mime_extension);
1483
1484 // ok, now we can take care of icon:
1485
1486 pos = text.Find(_T("Icon="));
1487 if ( pos == wxNOT_FOUND )
1488 {
1489 // no icon info
1490 return;
1491 }
1492
1493 wxString icon;
1494
1495 pc = text.c_str() + pos + 5; // 5 == strlen("Icon=")
1496 while ( *pc && *pc != _T('\n') )
1497 {
1498 icon += *pc++;
1499 }
1500
1501 if ( !!icon )
1502 {
1503 // we must check if the file exists because it may be stored
1504 // in many locations, at least ~/.kde and $KDEDIR
1505 size_t nDir, nDirs = icondirs.GetCount();
1506 for ( nDir = 0; nDir < nDirs; nDir++ )
1507 if (wxFileExists(icondirs[nDir] + icon))
1508 {
1509 icon.Prepend(icondirs[nDir]);
1510 break;
1511 }
1512 if (nDir == nDirs) return; //does not exist
1513
1514 // do we already have this MIME type?
1515 int i = ms_mimetypes.Index(mimetype);
1516 if ( i == wxNOT_FOUND )
1517 {
1518 // add it
1519 size_t n = ms_mimetypes.Add(mimetype);
1520 ms_icons.Insert(icon, n);
1521 }
1522 else
1523 {
1524 // replace the old value
1525 ms_icons[(size_t)i] = icon;
1526 }
1527 }
1528 }
1529
1530 void wxKDEIconHandler::LoadLinksForMimeType(const wxString& dirbase,
1531 const wxString& subdir,
1532 const wxArrayString& icondirs)
1533 {
1534 wxString dirname = dirbase;
1535 dirname += subdir;
1536 wxDir dir(dirname);
1537 if ( !dir.IsOpened() )
1538 return;
1539
1540 dirname += _T('/');
1541
1542 wxString filename;
1543 bool cont = dir.GetFirst(&filename, _T("*.kdelnk"), wxDIR_FILES);
1544 while ( cont )
1545 {
1546 LoadLinksForMimeSubtype(dirname, subdir, filename, icondirs);
1547
1548 cont = dir.GetNext(&filename);
1549 }
1550 }
1551
1552 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString& dirbase,
1553 const wxArrayString& icondirs)
1554 {
1555 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
1556 _T("base directory shouldn't end with a slash") );
1557
1558 wxString dirname = dirbase;
1559 dirname << _T("/mimelnk");
1560
1561 if ( !wxDir::Exists(dirname) )
1562 return;
1563
1564 wxDir dir(dirname);
1565 if ( !dir.IsOpened() )
1566 return;
1567
1568 // we will concatenate it with dir name to get the full path below
1569 dirname += _T('/');
1570
1571 wxString subdir;
1572 bool cont = dir.GetFirst(&subdir, wxEmptyString, wxDIR_DIRS);
1573 while ( cont )
1574 {
1575 LoadLinksForMimeType(dirname, subdir, icondirs);
1576
1577 cont = dir.GetNext(&subdir);
1578 }
1579 }
1580
1581 void wxKDEIconHandler::Init()
1582 {
1583 wxArrayString dirs;
1584 wxArrayString icondirs;
1585
1586 // settings in ~/.kde have maximal priority
1587 dirs.Add(wxGetHomeDir() + _T("/.kde/share"));
1588 icondirs.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
1589
1590 // the variable KDEDIR is set when KDE is running
1591 const char *kdedir = getenv("KDEDIR");
1592 if ( kdedir )
1593 {
1594 dirs.Add(wxString(kdedir) + _T("/share"));
1595 icondirs.Add(wxString(kdedir) + _T("/share/icons/"));
1596 }
1597 else
1598 {
1599 // try to guess KDEDIR
1600 dirs.Add(_T("/usr/share"));
1601 dirs.Add(_T("/opt/kde/share"));
1602 icondirs.Add(_T("/usr/share/icons/"));
1603 icondirs.Add(_T("/opt/kde/share/icons/"));
1604 }
1605
1606 size_t nDirs = dirs.GetCount();
1607 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1608 {
1609 LoadLinkFilesFromDir(dirs[nDir], icondirs);
1610 }
1611
1612 m_inited = TRUE;
1613 }
1614
1615 bool wxKDEIconHandler::GetIcon(const wxString& mimetype, wxIcon *icon)
1616 {
1617 if ( !m_inited )
1618 {
1619 Init();
1620 }
1621
1622 int index = ms_mimetypes.Index(mimetype);
1623 if ( index == wxNOT_FOUND )
1624 return FALSE;
1625
1626 wxString iconname = ms_icons[(size_t)index];
1627
1628 #if wxUSE_GUI
1629 *icon = wxIcon(iconname);
1630 #else
1631 // helpful for testing in console mode
1632 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
1633 mimetype.c_str(), iconname.c_str());
1634 #endif
1635
1636 return TRUE;
1637 }
1638
1639
1640 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl *manager)
1641 {
1642 if ( !m_inited ) Init();
1643
1644 size_t cnt = ms_infoTypes.GetCount();
1645 for (unsigned i = 0; i < cnt; i++)
1646 manager -> AddMimeTypeInfo(ms_infoTypes[i], ms_infoExtensions[i], ms_infoDescriptions[i]);
1647 }
1648
1649
1650 // ----------------------------------------------------------------------------
1651 // wxFileTypeImpl (Unix)
1652 // ----------------------------------------------------------------------------
1653
1654 MailCapEntry *
1655 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
1656 {
1657 wxString command;
1658 MailCapEntry *entry = m_manager->m_aEntries[m_index];
1659 while ( entry != NULL ) {
1660 // notice that an empty command would always succeed (it's ok)
1661 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
1662
1663 if ( command.IsEmpty() || (wxSystem(command) == 0) ) {
1664 // ok, passed
1665 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1666 command.c_str(), params.GetMimeType().c_str());
1667 break;
1668 }
1669 else {
1670 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1671 command.c_str(), params.GetMimeType().c_str());
1672 }
1673
1674 entry = entry->GetNext();
1675 }
1676
1677 return entry;
1678 }
1679
1680 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
1681 {
1682 wxString mimetype;
1683 (void)GetMimeType(&mimetype);
1684
1685 ArrayIconHandlers& handlers = m_manager->GetIconHandlers();
1686 size_t count = handlers.GetCount();
1687 for ( size_t n = 0; n < count; n++ )
1688 {
1689 if ( handlers[n]->GetIcon(mimetype, icon) )
1690 return TRUE;
1691 }
1692
1693 return FALSE;
1694 }
1695
1696 bool
1697 wxFileTypeImpl::GetExpandedCommand(wxString *expandedCmd,
1698 const wxFileType::MessageParameters& params,
1699 bool open) const
1700 {
1701 MailCapEntry *entry = GetEntry(params);
1702 if ( entry == NULL ) {
1703 // all tests failed...
1704 return FALSE;
1705 }
1706
1707 wxString cmd = open ? entry->GetOpenCmd() : entry->GetPrintCmd();
1708 if ( cmd.IsEmpty() ) {
1709 // may happen, especially for "print"
1710 return FALSE;
1711 }
1712
1713 *expandedCmd = wxFileType::ExpandCommand(cmd, params);
1714 return TRUE;
1715 }
1716
1717 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1718 {
1719 wxString strExtensions = m_manager->GetExtension(m_index);
1720 extensions.Empty();
1721
1722 // one extension in the space or comma delimitid list
1723 wxString strExt;
1724 for ( const wxChar *p = strExtensions; ; p++ ) {
1725 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
1726 if ( !strExt.IsEmpty() ) {
1727 extensions.Add(strExt);
1728 strExt.Empty();
1729 }
1730 //else: repeated spaces (shouldn't happen, but it's not that
1731 // important if it does happen)
1732
1733 if ( *p == wxT('\0') )
1734 break;
1735 }
1736 else if ( *p == wxT('.') ) {
1737 // remove the dot from extension (but only if it's the first char)
1738 if ( !strExt.IsEmpty() ) {
1739 strExt += wxT('.');
1740 }
1741 //else: no, don't append it
1742 }
1743 else {
1744 strExt += *p;
1745 }
1746 }
1747
1748 return TRUE;
1749 }
1750
1751 // ----------------------------------------------------------------------------
1752 // wxMimeTypesManagerImpl (Unix)
1753 // ----------------------------------------------------------------------------
1754
1755 /* static */
1756 ArrayIconHandlers& wxMimeTypesManagerImpl::GetIconHandlers()
1757 {
1758 if ( ms_iconHandlers.GetCount() == 0 )
1759 {
1760 ms_iconHandlers.Add(&gs_iconHandlerGNOME);
1761 ms_iconHandlers.Add(&gs_iconHandlerKDE);
1762 }
1763
1764 return ms_iconHandlers;
1765 }
1766
1767 // read system and user mailcaps (TODO implement mime.types support)
1768 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1769 {
1770 // directories where we look for mailcap and mime.types by default
1771 // (taken from metamail(1) sources)
1772 static const wxChar *aStandardLocations[] =
1773 {
1774 wxT("/etc"),
1775 wxT("/usr/etc"),
1776 wxT("/usr/local/etc"),
1777 wxT("/etc/mail"),
1778 wxT("/usr/public/lib")
1779 };
1780
1781 // first read the system wide file(s)
1782 for ( size_t n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
1783 wxString dir = aStandardLocations[n];
1784
1785 wxString file = dir + wxT("/mailcap");
1786 if ( wxFile::Exists(file) ) {
1787 ReadMailcap(file);
1788 }
1789
1790 file = dir + wxT("/mime.types");
1791 if ( wxFile::Exists(file) ) {
1792 ReadMimeTypes(file);
1793 }
1794 }
1795
1796 wxString strHome = wxGetenv(wxT("HOME"));
1797
1798 // and now the users mailcap
1799 wxString strUserMailcap = strHome + wxT("/.mailcap");
1800 if ( wxFile::Exists(strUserMailcap) ) {
1801 ReadMailcap(strUserMailcap);
1802 }
1803
1804 // read the users mime.types
1805 wxString strUserMimeTypes = strHome + wxT("/.mime.types");
1806 if ( wxFile::Exists(strUserMimeTypes) ) {
1807 ReadMimeTypes(strUserMimeTypes);
1808 }
1809
1810 // read KDE/GNOME tables
1811 ArrayIconHandlers& handlers = GetIconHandlers();
1812 size_t count = handlers.GetCount();
1813 for ( size_t n = 0; n < count; n++ )
1814 handlers[n]->GetMimeInfoRecords(this);
1815 }
1816
1817 wxFileType *
1818 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1819 {
1820 size_t count = m_aExtensions.GetCount();
1821 for ( size_t n = 0; n < count; n++ ) {
1822 wxString extensions = m_aExtensions[n];
1823 while ( !extensions.IsEmpty() ) {
1824 wxString field = extensions.BeforeFirst(wxT(' '));
1825 extensions = extensions.AfterFirst(wxT(' '));
1826
1827 // consider extensions as not being case-sensitive
1828 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
1829 // found
1830 wxFileType *fileType = new wxFileType;
1831 fileType->m_impl->Init(this, n);
1832
1833 return fileType;
1834 }
1835 }
1836 }
1837
1838 // not found
1839 return NULL;
1840 }
1841
1842 wxFileType *
1843 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1844 {
1845 // mime types are not case-sensitive
1846 wxString mimetype(mimeType);
1847 mimetype.MakeLower();
1848
1849 // first look for an exact match
1850 int index = m_aTypes.Index(mimetype);
1851 if ( index == wxNOT_FOUND ) {
1852 // then try to find "text/*" as match for "text/plain" (for example)
1853 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1854 // the whole string - ok.
1855 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
1856
1857 size_t nCount = m_aTypes.Count();
1858 for ( size_t n = 0; n < nCount; n++ ) {
1859 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
1860 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
1861 index = n;
1862 break;
1863 }
1864 }
1865 }
1866
1867 if ( index != wxNOT_FOUND ) {
1868 wxFileType *fileType = new wxFileType;
1869 fileType->m_impl->Init(this, index);
1870
1871 return fileType;
1872 }
1873 else {
1874 // not found...
1875 return NULL;
1876 }
1877 }
1878
1879 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
1880 {
1881 wxString extensions;
1882 const wxArrayString& exts = filetype.GetExtensions();
1883 size_t nExts = exts.GetCount();
1884 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
1885 if ( nExt > 0 ) {
1886 extensions += wxT(' ');
1887 }
1888 extensions += exts[nExt];
1889 }
1890
1891 AddMimeTypeInfo(filetype.GetMimeType(),
1892 extensions,
1893 filetype.GetDescription());
1894
1895 AddMailcapInfo(filetype.GetMimeType(),
1896 filetype.GetOpenCommand(),
1897 filetype.GetPrintCommand(),
1898 wxT(""),
1899 filetype.GetDescription());
1900 }
1901
1902 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
1903 const wxString& strExtensions,
1904 const wxString& strDesc)
1905 {
1906 int index = m_aTypes.Index(strMimeType);
1907 if ( index == wxNOT_FOUND ) {
1908 // add a new entry
1909 m_aTypes.Add(strMimeType);
1910 m_aEntries.Add(NULL);
1911 m_aExtensions.Add(strExtensions);
1912 m_aDescriptions.Add(strDesc);
1913 }
1914 else {
1915 // modify an existing one
1916 if ( !strDesc.IsEmpty() ) {
1917 m_aDescriptions[index] = strDesc; // replace old value
1918 }
1919 m_aExtensions[index] += ' ' + strExtensions;
1920 }
1921 }
1922
1923 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
1924 const wxString& strOpenCmd,
1925 const wxString& strPrintCmd,
1926 const wxString& strTest,
1927 const wxString& strDesc)
1928 {
1929 MailCapEntry *entry = new MailCapEntry(strOpenCmd, strPrintCmd, strTest);
1930
1931 int nIndex = m_aTypes.Index(strType);
1932 if ( nIndex == wxNOT_FOUND ) {
1933 // new file type
1934 m_aTypes.Add(strType);
1935
1936 m_aEntries.Add(entry);
1937 m_aExtensions.Add(wxT(""));
1938 m_aDescriptions.Add(strDesc);
1939 }
1940 else {
1941 // always append the entry in the tail of the list - info added with
1942 // this function can only come from AddFallbacks()
1943 MailCapEntry *entryOld = m_aEntries[nIndex];
1944 if ( entryOld )
1945 entry->Append(entryOld);
1946 else
1947 m_aEntries[nIndex] = entry;
1948 }
1949 }
1950
1951 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
1952 {
1953 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName.c_str());
1954
1955 wxTextFile file(strFileName);
1956 if ( !file.Open() )
1957 return FALSE;
1958
1959 // the information we extract
1960 wxString strMimeType, strDesc, strExtensions;
1961
1962 size_t nLineCount = file.GetLineCount();
1963 const wxChar *pc = NULL;
1964 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1965 if ( pc == NULL ) {
1966 // now we're at the start of the line
1967 pc = file[nLine].c_str();
1968 }
1969 else {
1970 // we didn't finish with the previous line yet
1971 nLine--;
1972 }
1973
1974 // skip whitespace
1975 while ( wxIsspace(*pc) )
1976 pc++;
1977
1978 // comment or blank line?
1979 if ( *pc == wxT('#') || !*pc ) {
1980 // skip the whole line
1981 pc = NULL;
1982 continue;
1983 }
1984
1985 // detect file format
1986 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
1987 if ( pEqualSign == NULL ) {
1988 // brief format
1989 // ------------
1990
1991 // first field is mime type
1992 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
1993 strMimeType += *pc;
1994 }
1995
1996 // skip whitespace
1997 while ( wxIsspace(*pc) )
1998 pc++;
1999
2000 // take all the rest of the string
2001 strExtensions = pc;
2002
2003 // no description...
2004 strDesc.Empty();
2005 }
2006 else {
2007 // expanded format
2008 // ---------------
2009
2010 // the string on the left of '=' is the field name
2011 wxString strLHS(pc, pEqualSign - pc);
2012
2013 // eat whitespace
2014 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
2015 ;
2016
2017 const wxChar *pEnd;
2018 if ( *pc == wxT('"') ) {
2019 // the string is quoted and ends at the matching quote
2020 pEnd = wxStrchr(++pc, wxT('"'));
2021 if ( pEnd == NULL ) {
2022 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2023 "quoted string."),
2024 strFileName.c_str(), nLine + 1);
2025 }
2026 }
2027 else {
2028 // unquoted string ends at the first space
2029 for ( pEnd = pc; !wxIsspace(*pEnd); pEnd++ )
2030 ;
2031 }
2032
2033 // now we have the RHS (field value)
2034 wxString strRHS(pc, pEnd - pc);
2035
2036 // check what follows this entry
2037 if ( *pEnd == wxT('"') ) {
2038 // skip this quote
2039 pEnd++;
2040 }
2041
2042 for ( pc = pEnd; wxIsspace(*pc); pc++ )
2043 ;
2044
2045 // if there is something left, it may be either a '\\' to continue
2046 // the line or the next field of the same entry
2047 bool entryEnded = *pc == wxT('\0'),
2048 nextFieldOnSameLine = FALSE;
2049 if ( !entryEnded ) {
2050 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
2051 }
2052
2053 // now see what we got
2054 if ( strLHS == wxT("type") ) {
2055 strMimeType = strRHS;
2056 }
2057 else if ( strLHS == wxT("desc") ) {
2058 strDesc = strRHS;
2059 }
2060 else if ( strLHS == wxT("exts") ) {
2061 strExtensions = strRHS;
2062 }
2063 else {
2064 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2065 strFileName.c_str(), nLine + 1, strLHS.c_str());
2066 }
2067
2068 if ( !entryEnded ) {
2069 if ( !nextFieldOnSameLine )
2070 pc = NULL;
2071 //else: don't reset it
2072
2073 // as we don't reset strMimeType, the next field in this entry
2074 // will be interpreted correctly.
2075
2076 continue;
2077 }
2078 }
2079
2080 // although it doesn't seem to be covered by RFCs, some programs
2081 // (notably Netscape) create their entries with several comma
2082 // separated extensions (RFC mention the spaces only)
2083 strExtensions.Replace(wxT(","), wxT(" "));
2084
2085 // also deal with the leading dot
2086 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
2087 {
2088 strExtensions.erase(0, 1);
2089 }
2090
2091 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
2092
2093 // finished with this line
2094 pc = NULL;
2095 }
2096
2097 // check our data integriry
2098 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
2099 m_aTypes.Count() == m_aExtensions.Count() &&
2100 m_aTypes.Count() == m_aDescriptions.Count() );
2101
2102 return TRUE;
2103 }
2104
2105 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
2106 bool fallback)
2107 {
2108 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName.c_str());
2109
2110 wxTextFile file(strFileName);
2111 if ( !file.Open() )
2112 return FALSE;
2113
2114 // see the comments near the end of function for the reason we need these
2115 // variables (search for the next occurence of them)
2116 // indices of MIME types (in m_aTypes) we already found in this file
2117 wxArrayInt aEntryIndices;
2118 // aLastIndices[n] is the index of last element in
2119 // m_aEntries[aEntryIndices[n]] from this file
2120 wxArrayInt aLastIndices;
2121
2122 size_t nLineCount = file.GetLineCount();
2123 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
2124 // now we're at the start of the line
2125 const wxChar *pc = file[nLine].c_str();
2126
2127 // skip whitespace
2128 while ( wxIsspace(*pc) )
2129 pc++;
2130
2131 // comment or empty string?
2132 if ( *pc == wxT('#') || *pc == wxT('\0') )
2133 continue;
2134
2135 // no, do parse
2136
2137 // what field are we currently in? The first 2 are fixed and there may
2138 // be an arbitrary number of other fields -- currently, we are not
2139 // interested in any of them, but we should parse them as well...
2140 enum
2141 {
2142 Field_Type,
2143 Field_OpenCmd,
2144 Field_Other
2145 } currentToken = Field_Type;
2146
2147 // the flags and field values on the current line
2148 bool needsterminal = FALSE,
2149 copiousoutput = FALSE;
2150 wxString strType,
2151 strOpenCmd,
2152 strPrintCmd,
2153 strTest,
2154 strDesc,
2155 curField; // accumulator
2156 for ( bool cont = TRUE; cont; pc++ ) {
2157 switch ( *pc ) {
2158 case wxT('\\'):
2159 // interpret the next character literally (notice that
2160 // backslash can be used for line continuation)
2161 if ( *++pc == wxT('\0') ) {
2162 // fetch the next line.
2163
2164 // pc currently points to nowhere, but after the next
2165 // pc++ in the for line it will point to the beginning
2166 // of the next line in the file
2167 pc = file[++nLine].c_str() - 1;
2168 }
2169 else {
2170 // just a normal character
2171 curField += *pc;
2172 }
2173 break;
2174
2175 case wxT('\0'):
2176 cont = FALSE; // end of line reached, exit the loop
2177
2178 // fall through
2179
2180 case wxT(';'):
2181 // store this field and start looking for the next one
2182
2183 // trim whitespaces from both sides
2184 curField.Trim(TRUE).Trim(FALSE);
2185
2186 switch ( currentToken ) {
2187 case Field_Type:
2188 strType = curField;
2189 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
2190 // we interpret "type" as "type/*"
2191 strType += wxT("/*");
2192 }
2193
2194 currentToken = Field_OpenCmd;
2195 break;
2196
2197 case Field_OpenCmd:
2198 strOpenCmd = curField;
2199
2200 currentToken = Field_Other;
2201 break;
2202
2203 case Field_Other:
2204 {
2205 // "good" mailcap entry?
2206 bool ok = TRUE;
2207
2208 // is this something of the form foo=bar?
2209 const wxChar *pEq = wxStrchr(curField, wxT('='));
2210 if ( pEq != NULL ) {
2211 wxString lhs = curField.BeforeFirst(wxT('=')),
2212 rhs = curField.AfterFirst(wxT('='));
2213
2214 lhs.Trim(TRUE); // from right
2215 rhs.Trim(FALSE); // from left
2216
2217 if ( lhs == wxT("print") )
2218 strPrintCmd = rhs;
2219 else if ( lhs == wxT("test") )
2220 strTest = rhs;
2221 else if ( lhs == wxT("description") ) {
2222 // it might be quoted
2223 if ( rhs[0u] == wxT('"') &&
2224 rhs.Last() == wxT('"') ) {
2225 strDesc = wxString(rhs.c_str() + 1,
2226 rhs.Len() - 2);
2227 }
2228 else {
2229 strDesc = rhs;
2230 }
2231 }
2232 else if ( lhs == wxT("compose") ||
2233 lhs == wxT("composetyped") ||
2234 lhs == wxT("notes") ||
2235 lhs == wxT("edit") )
2236 ; // ignore
2237 else
2238 ok = FALSE;
2239
2240 }
2241 else {
2242 // no, it's a simple flag
2243 // TODO support the flags:
2244 // 1. create an xterm for 'needsterminal'
2245 // 2. append "| $PAGER" for 'copiousoutput'
2246 if ( curField == wxT("needsterminal") )
2247 needsterminal = TRUE;
2248 else if ( curField == wxT("copiousoutput") )
2249 copiousoutput = TRUE;
2250 else if ( curField == wxT("textualnewlines") )
2251 ; // ignore
2252 else
2253 ok = FALSE;
2254 }
2255
2256 if ( !ok )
2257 {
2258 // we don't understand this field, but
2259 // Netscape stores info in it, so don't warn
2260 // about it
2261 if ( curField.Left(16u) != "x-mozilla-flags=" )
2262 {
2263 // don't flood the user with error
2264 // messages if we don't understand
2265 // something in his mailcap, but give
2266 // them in debug mode because this might
2267 // be useful for the programmer
2268 wxLogDebug
2269 (
2270 wxT("Mailcap file %s, line %d: "
2271 "unknown field '%s' for the "
2272 "MIME type '%s' ignored."),
2273 strFileName.c_str(),
2274 nLine + 1,
2275 curField.c_str(),
2276 strType.c_str()
2277 );
2278 }
2279 }
2280 }
2281
2282 // it already has this value
2283 //currentToken = Field_Other;
2284 break;
2285
2286 default:
2287 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2288 }
2289
2290 // next token starts immediately after ';'
2291 curField.Empty();
2292 break;
2293
2294 default:
2295 curField += *pc;
2296 }
2297 }
2298
2299 // check that we really read something reasonable
2300 if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
2301 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2302 "ignored."),
2303 strFileName.c_str(), nLine + 1);
2304 }
2305 else {
2306 MailCapEntry *entry = new MailCapEntry(strOpenCmd,
2307 strPrintCmd,
2308 strTest);
2309
2310 // NB: because of complications below (we must get entries priority
2311 // right), we can't use AddMailcapInfo() here, unfortunately.
2312 strType.MakeLower();
2313 int nIndex = m_aTypes.Index(strType);
2314 if ( nIndex == wxNOT_FOUND ) {
2315 // new file type
2316 m_aTypes.Add(strType);
2317
2318 m_aEntries.Add(entry);
2319 m_aExtensions.Add(wxT(""));
2320 m_aDescriptions.Add(strDesc);
2321 }
2322 else {
2323 // modify the existing entry: the entries in one and the same
2324 // file are read in top-to-bottom order, i.e. the entries read
2325 // first should be tried before the entries below. However,
2326 // the files read later should override the settings in the
2327 // files read before (except if fallback is TRUE), thus we
2328 // Insert() the new entry to the list if it has already
2329 // occured in _this_ file, but Prepend() it if it occured in
2330 // some of the previous ones and Append() to it in the
2331 // fallback case
2332
2333 if ( fallback ) {
2334 // 'fallback' parameter prevents the entries from this
2335 // file from overriding the other ones - always append
2336 MailCapEntry *entryOld = m_aEntries[nIndex];
2337 if ( entryOld )
2338 entry->Append(entryOld);
2339 else
2340 m_aEntries[nIndex] = entry;
2341 }
2342 else {
2343 int entryIndex = aEntryIndices.Index(nIndex);
2344 if ( entryIndex == wxNOT_FOUND ) {
2345 // first time in this file
2346 aEntryIndices.Add(nIndex);
2347 aLastIndices.Add(0);
2348
2349 entry->Prepend(m_aEntries[nIndex]);
2350 m_aEntries[nIndex] = entry;
2351 }
2352 else {
2353 // not the first time in _this_ file
2354 size_t nEntryIndex = (size_t)entryIndex;
2355 MailCapEntry *entryOld = m_aEntries[nIndex];
2356 if ( entryOld )
2357 entry->Insert(entryOld, aLastIndices[nEntryIndex]);
2358 else
2359 m_aEntries[nIndex] = entry;
2360
2361 // the indices were shifted by 1
2362 aLastIndices[nEntryIndex]++;
2363 }
2364 }
2365
2366 if ( !strDesc.IsEmpty() ) {
2367 // replace the old one - what else can we do??
2368 m_aDescriptions[nIndex] = strDesc;
2369 }
2370 }
2371 }
2372
2373 // check our data integriry
2374 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
2375 m_aTypes.Count() == m_aExtensions.Count() &&
2376 m_aTypes.Count() == m_aDescriptions.Count() );
2377 }
2378
2379 return TRUE;
2380 }
2381
2382 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
2383 {
2384 mimetypes.Empty();
2385
2386 wxString type;
2387 size_t count = m_aTypes.GetCount();
2388 for ( size_t n = 0; n < count; n++ )
2389 {
2390 // don't return template types from here (i.e. anything containg '*')
2391 type = m_aTypes[n];
2392 if ( type.Find(_T('*')) == wxNOT_FOUND )
2393 {
2394 mimetypes.Add(type);
2395 }
2396 }
2397
2398 return mimetypes.GetCount();
2399 }
2400
2401 #endif
2402 // OS type
2403
2404 #endif
2405 // wxUSE_FILE && wxUSE_TEXTFILE
2406
2407 #endif
2408 // __WIN16__