]> git.saurik.com Git - wxWidgets.git/blob - src/common/mimetype.cpp
Some more bug reports
[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;
762 wxRegKey key(wxRegKey::HKCR, strKey + _T("\\command"));
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 (now also
768 // test for %L - apparently MS started using it as well for the
769 // same purpose)
770
771 // NB: we don't make any attempt to verify that the string is valid,
772 // i.e. doesn't contain %2, or second %1 or .... But we do make
773 // sure that we return a string with _exactly_ one '%s'!
774 bool foundFilename = FALSE;
775 size_t len = command.Len();
776 for ( size_t n = 0; (n < len) && !foundFilename; n++ ) {
777 if ( command[n] == wxT('%') &&
778 (n + 1 < len) &&
779 (command[n + 1] == wxT('1') ||
780 command[n + 1] == wxT('L')) ) {
781 // replace it with '%s'
782 command[n + 1] = wxT('s');
783
784 foundFilename = TRUE;
785 }
786 }
787
788 // look whether we must issue some DDE requests to the application
789 // (and not just launch it)
790 strKey += _T("\\DDEExec");
791 wxRegKey keyDDE(wxRegKey::HKCR, strKey);
792 if ( keyDDE.Open() ) {
793 wxString ddeCommand, ddeServer, ddeTopic;
794 keyDDE.QueryValue(_T(""), ddeCommand);
795 ddeCommand.Replace(_T("%1"), _T("%s"));
796
797 wxRegKey(wxRegKey::HKCR, strKey + _T("\\Application")).
798 QueryValue(_T(""), ddeServer);
799 wxRegKey(wxRegKey::HKCR, strKey + _T("\\Topic")).
800 QueryValue(_T(""), ddeTopic);
801
802 // HACK: we use a special feature of wxExecute which exists
803 // just because we need it here: it will establish DDE
804 // conversation with the program it just launched
805 command.Prepend(_T("WX_DDE#"));
806 command << _T('#') << ddeServer
807 << _T('#') << ddeTopic
808 << _T('#') << ddeCommand;
809 }
810 else if ( !foundFilename ) {
811 // we didn't find any '%1' - the application doesn't know which
812 // file to open (note that we only do it if there is no DDEExec
813 // subkey)
814 //
815 // HACK: append the filename at the end, hope that it will do
816 command << wxT(" %s");
817 }
818 }
819 }
820 //else: no such file type or no value, will return empty string
821
822 return command;
823 }
824
825 bool
826 wxFileTypeImpl::GetOpenCommand(wxString *openCmd,
827 const wxFileType::MessageParameters& params)
828 const
829 {
830 wxString cmd;
831 if ( m_info ) {
832 cmd = m_info->GetOpenCommand();
833 }
834 else {
835 cmd = GetCommand(wxT("open"));
836 }
837
838 *openCmd = wxFileType::ExpandCommand(cmd, params);
839
840 return !openCmd->IsEmpty();
841 }
842
843 bool
844 wxFileTypeImpl::GetPrintCommand(wxString *printCmd,
845 const wxFileType::MessageParameters& params)
846 const
847 {
848 wxString cmd;
849 if ( m_info ) {
850 cmd = m_info->GetPrintCommand();
851 }
852 else {
853 cmd = GetCommand(wxT("print"));
854 }
855
856 *printCmd = wxFileType::ExpandCommand(cmd, params);
857
858 return !printCmd->IsEmpty();
859 }
860
861 // TODO this function is half implemented
862 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
863 {
864 if ( m_info ) {
865 extensions = m_info->GetExtensions();
866
867 return TRUE;
868 }
869 else if ( m_ext.IsEmpty() ) {
870 // the only way to get the list of extensions from the file type is to
871 // scan through all extensions in the registry - too slow...
872 return FALSE;
873 }
874 else {
875 extensions.Empty();
876 extensions.Add(m_ext);
877
878 // it's a lie too, we don't return _all_ extensions...
879 return TRUE;
880 }
881 }
882
883 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
884 {
885 if ( m_info ) {
886 // we already have it
887 *mimeType = m_info->GetMimeType();
888
889 return TRUE;
890 }
891
892 // suppress possible error messages
893 wxLogNull nolog;
894 wxRegKey key(wxRegKey::HKCR, wxT(".") + m_ext);
895 if ( key.Open() && key.QueryValue(wxT("Content Type"), *mimeType) ) {
896 return TRUE;
897 }
898 else {
899 return FALSE;
900 }
901 }
902
903 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
904 {
905 #if wxUSE_GUI
906 if ( m_info ) {
907 // we don't have icons in the fallback resources
908 return FALSE;
909 }
910
911 wxString strIconKey;
912 strIconKey << m_strFileType << wxT("\\DefaultIcon");
913
914 // suppress possible error messages
915 wxLogNull nolog;
916 wxRegKey key(wxRegKey::HKCR, strIconKey);
917
918 if ( key.Open() ) {
919 wxString strIcon;
920 // it's the default value of the key
921 if ( key.QueryValue(wxT(""), strIcon) ) {
922 // the format is the following: <full path to file>, <icon index>
923 // NB: icon index may be negative as well as positive and the full
924 // path may contain the environment variables inside '%'
925 wxString strFullPath = strIcon.BeforeLast(wxT(',')),
926 strIndex = strIcon.AfterLast(wxT(','));
927
928 // index may be omitted, in which case BeforeLast(',') is empty and
929 // AfterLast(',') is the whole string
930 if ( strFullPath.IsEmpty() ) {
931 strFullPath = strIndex;
932 strIndex = wxT("0");
933 }
934
935 wxString strExpPath = wxExpandEnvVars(strFullPath);
936 int nIndex = wxAtoi(strIndex);
937
938 HICON hIcon = ExtractIcon(GetModuleHandle(NULL), strExpPath, nIndex);
939 switch ( (int)hIcon ) {
940 case 0: // means no icons were found
941 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
942 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
943 key.GetName().c_str());
944 break;
945
946 default:
947 icon->SetHICON((WXHICON)hIcon);
948 return TRUE;
949 }
950 }
951 }
952
953 // no such file type or no value or incorrect icon entry
954 #endif // wxUSE_GUI
955
956 return FALSE;
957 }
958
959 bool wxFileTypeImpl::GetDescription(wxString *desc) const
960 {
961 if ( m_info ) {
962 // we already have it
963 *desc = m_info->GetDescription();
964
965 return TRUE;
966 }
967
968 // suppress possible error messages
969 wxLogNull nolog;
970 wxRegKey key(wxRegKey::HKCR, m_strFileType);
971
972 if ( key.Open() ) {
973 // it's the default value of the key
974 if ( key.QueryValue(wxT(""), *desc) ) {
975 return TRUE;
976 }
977 }
978
979 return FALSE;
980 }
981
982 // extension -> file type
983 wxFileType *
984 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
985 {
986 // add the leading point if necessary
987 wxString str;
988 if ( ext[0u] != wxT('.') ) {
989 str = wxT('.');
990 }
991 str << ext;
992
993 // suppress possible error messages
994 wxLogNull nolog;
995
996 bool knownExtension = FALSE;
997
998 wxString strFileType;
999 wxRegKey key(wxRegKey::HKCR, str);
1000 if ( key.Open() ) {
1001 // it's the default value of the key
1002 if ( key.QueryValue(wxT(""), strFileType) ) {
1003 // create the new wxFileType object
1004 wxFileType *fileType = new wxFileType;
1005 fileType->m_impl->Init(strFileType, ext);
1006
1007 return fileType;
1008 }
1009 else {
1010 // this extension doesn't have a filetype, but it's known to the
1011 // system and may be has some other useful keys (open command or
1012 // content-type), so still return a file type object for it
1013 knownExtension = TRUE;
1014 }
1015 }
1016
1017 // check the fallbacks
1018 // TODO linear search is potentially slow, perhaps we should use a sorted
1019 // array?
1020 size_t count = m_fallbacks.GetCount();
1021 for ( size_t n = 0; n < count; n++ ) {
1022 if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
1023 wxFileType *fileType = new wxFileType;
1024 fileType->m_impl->Init(m_fallbacks[n]);
1025
1026 return fileType;
1027 }
1028 }
1029
1030 if ( knownExtension )
1031 {
1032 wxFileType *fileType = new wxFileType;
1033 fileType->m_impl->Init(wxEmptyString, ext);
1034
1035 return fileType;
1036 }
1037 else
1038 {
1039 // unknown extension
1040 return NULL;
1041 }
1042 }
1043
1044 // MIME type -> extension -> file type
1045 wxFileType *
1046 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1047 {
1048 wxString strKey = MIME_DATABASE_KEY;
1049 strKey << mimeType;
1050
1051 // suppress possible error messages
1052 wxLogNull nolog;
1053
1054 wxString ext;
1055 wxRegKey key(wxRegKey::HKCR, strKey);
1056 if ( key.Open() ) {
1057 if ( key.QueryValue(wxT("Extension"), ext) ) {
1058 return GetFileTypeFromExtension(ext);
1059 }
1060 }
1061
1062 // check the fallbacks
1063 // TODO linear search is potentially slow, perhaps we should use a sorted
1064 // array?
1065 size_t count = m_fallbacks.GetCount();
1066 for ( size_t n = 0; n < count; n++ ) {
1067 if ( wxMimeTypesManager::IsOfType(mimeType,
1068 m_fallbacks[n].GetMimeType()) ) {
1069 wxFileType *fileType = new wxFileType;
1070 fileType->m_impl->Init(m_fallbacks[n]);
1071
1072 return fileType;
1073 }
1074 }
1075
1076 // unknown MIME type
1077 return NULL;
1078 }
1079
1080 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1081 {
1082 // enumerate all keys under MIME_DATABASE_KEY
1083 wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
1084
1085 wxString type;
1086 long cookie;
1087 bool cont = key.GetFirstKey(type, cookie);
1088 while ( cont )
1089 {
1090 mimetypes.Add(type);
1091
1092 cont = key.GetNextKey(type, cookie);
1093 }
1094
1095 return mimetypes.GetCount();
1096 }
1097
1098 #elif defined ( __WXMAC__ )
1099
1100 bool wxFileTypeImpl::GetCommand(wxString *command, const char *verb) const
1101 {
1102 return FALSE;
1103 }
1104
1105 // @@ this function is half implemented
1106 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1107 {
1108 return FALSE;
1109 }
1110
1111 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
1112 {
1113 if ( m_strFileType.Length() > 0 )
1114 {
1115 *mimeType = m_strFileType ;
1116 return TRUE ;
1117 }
1118 else
1119 return FALSE;
1120 }
1121
1122 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
1123 {
1124 // no such file type or no value or incorrect icon entry
1125 return FALSE;
1126 }
1127
1128 bool wxFileTypeImpl::GetDescription(wxString *desc) const
1129 {
1130 return FALSE;
1131 }
1132
1133 // extension -> file type
1134 wxFileType *
1135 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& e)
1136 {
1137 wxString ext = e ;
1138 ext = ext.Lower() ;
1139 if ( ext == "txt" )
1140 {
1141 wxFileType *fileType = new wxFileType;
1142 fileType->m_impl->SetFileType("text/text");
1143 fileType->m_impl->SetExt(ext);
1144 return fileType;
1145 }
1146 else if ( ext == "htm" || ext == "html" )
1147 {
1148 wxFileType *fileType = new wxFileType;
1149 fileType->m_impl->SetFileType("text/html");
1150 fileType->m_impl->SetExt(ext);
1151 return fileType;
1152 }
1153 else if ( ext == "gif" )
1154 {
1155 wxFileType *fileType = new wxFileType;
1156 fileType->m_impl->SetFileType("image/gif");
1157 fileType->m_impl->SetExt(ext);
1158 return fileType;
1159 }
1160 else if ( ext == "png" )
1161 {
1162 wxFileType *fileType = new wxFileType;
1163 fileType->m_impl->SetFileType("image/png");
1164 fileType->m_impl->SetExt(ext);
1165 return fileType;
1166 }
1167 else if ( ext == "jpg" || ext == "jpeg" )
1168 {
1169 wxFileType *fileType = new wxFileType;
1170 fileType->m_impl->SetFileType("image/jpeg");
1171 fileType->m_impl->SetExt(ext);
1172 return fileType;
1173 }
1174 else if ( ext == "bmp" )
1175 {
1176 wxFileType *fileType = new wxFileType;
1177 fileType->m_impl->SetFileType("image/bmp");
1178 fileType->m_impl->SetExt(ext);
1179 return fileType;
1180 }
1181 else if ( ext == "tif" || ext == "tiff" )
1182 {
1183 wxFileType *fileType = new wxFileType;
1184 fileType->m_impl->SetFileType("image/tiff");
1185 fileType->m_impl->SetExt(ext);
1186 return fileType;
1187 }
1188 else if ( ext == "xpm" )
1189 {
1190 wxFileType *fileType = new wxFileType;
1191 fileType->m_impl->SetFileType("image/xpm");
1192 fileType->m_impl->SetExt(ext);
1193 return fileType;
1194 }
1195 else if ( ext == "xbm" )
1196 {
1197 wxFileType *fileType = new wxFileType;
1198 fileType->m_impl->SetFileType("image/xbm");
1199 fileType->m_impl->SetExt(ext);
1200 return fileType;
1201 }
1202
1203 // unknown extension
1204 return NULL;
1205 }
1206
1207 // MIME type -> extension -> file type
1208 wxFileType *
1209 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1210 {
1211 return NULL;
1212 }
1213
1214 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1215 {
1216 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1217
1218 return 0;
1219 }
1220
1221 #else // Unix
1222
1223 // ============================================================================
1224 // Unix implementation
1225 // ============================================================================
1226
1227 // ----------------------------------------------------------------------------
1228 // various statics
1229 // ----------------------------------------------------------------------------
1230
1231 static wxGNOMEIconHandler gs_iconHandlerGNOME;
1232 static wxKDEIconHandler gs_iconHandlerKDE;
1233
1234 bool wxGNOMEIconHandler::m_inited = FALSE;
1235 wxSortedArrayString wxGNOMEIconHandler::ms_mimetypes;
1236 wxArrayString wxGNOMEIconHandler::ms_icons;
1237
1238 bool wxKDEIconHandler::m_inited = FALSE;
1239 wxSortedArrayString wxKDEIconHandler::ms_mimetypes;
1240 wxArrayString wxKDEIconHandler::ms_icons;
1241
1242 wxArrayString wxKDEIconHandler::ms_infoTypes;
1243 wxArrayString wxKDEIconHandler::ms_infoDescriptions;
1244 wxArrayString wxKDEIconHandler::ms_infoExtensions;
1245
1246
1247 ArrayIconHandlers wxMimeTypesManagerImpl::ms_iconHandlers;
1248
1249 // ----------------------------------------------------------------------------
1250 // wxGNOMEIconHandler
1251 // ----------------------------------------------------------------------------
1252
1253 // GNOME stores the info we're interested in in several locations:
1254 // 1. xxx.keys files under /usr/share/mime-info
1255 // 2. xxx.keys files under ~/.gnome/mime-info
1256 //
1257 // The format of xxx.keys file is the following:
1258 //
1259 // mimetype/subtype:
1260 // field=value
1261 //
1262 // with blank lines separating the entries and indented lines starting with
1263 // TABs. We're interested in the field icon-filename whose value is the path
1264 // containing the icon.
1265
1266 void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString& filename)
1267 {
1268 wxTextFile textfile(filename);
1269 if ( !textfile.Open() )
1270 return;
1271
1272 // values for the entry being parsed
1273 wxString curMimeType, curIconFile;
1274
1275 const wxChar *pc;
1276 size_t nLineCount = textfile.GetLineCount();
1277 for ( size_t nLine = 0; ; nLine++ )
1278 {
1279 if ( nLine < nLineCount )
1280 {
1281 pc = textfile[nLine].c_str();
1282 if ( *pc == _T('#') )
1283 {
1284 // skip comments
1285 continue;
1286 }
1287 }
1288 else
1289 {
1290 // so that we will fall into the "if" below
1291 pc = NULL;
1292 }
1293
1294 if ( !pc || !*pc )
1295 {
1296 // end of the entry
1297 if ( !!curMimeType && !!curIconFile )
1298 {
1299 // do we already know this mimetype?
1300 int i = ms_mimetypes.Index(curMimeType);
1301 if ( i == wxNOT_FOUND )
1302 {
1303 // add a new entry
1304 size_t n = ms_mimetypes.Add(curMimeType);
1305 ms_icons.Insert(curIconFile, n);
1306 }
1307 else
1308 {
1309 // replace the existing one (this means that the directories
1310 // should be searched in order of increased priority!)
1311 ms_icons[(size_t)i] = curIconFile;
1312 }
1313 }
1314
1315 if ( !pc )
1316 {
1317 // the end - this can only happen if nLine == nLineCount
1318 break;
1319 }
1320
1321 curIconFile.Empty();
1322
1323 continue;
1324 }
1325
1326 // what do we have here?
1327 if ( *pc == _T('\t') )
1328 {
1329 // this is a field=value ling
1330 pc++; // skip leading TAB
1331
1332 static const int lenField = 13; // strlen("icon-filename")
1333 if ( wxStrncmp(pc, _T("icon-filename"), lenField) == 0 )
1334 {
1335 // skip '=' which follows and take everything left until the end
1336 // of line
1337 curIconFile = pc + lenField + 1;
1338 }
1339 //else: some other field, we don't care
1340 }
1341 else
1342 {
1343 // this is the start of the new section
1344 curMimeType.Empty();
1345
1346 while ( *pc != _T(':') && *pc != _T('\0') )
1347 {
1348 curMimeType += *pc++;
1349 }
1350
1351 if ( !*pc )
1352 {
1353 // we reached the end of line without finding the colon,
1354 // something is wrong - ignore this line completely
1355 wxLogDebug(_T("Unreckognized line %d in file '%s' ignored"),
1356 nLine + 1, filename.c_str());
1357
1358 break;
1359 }
1360 }
1361 }
1362 }
1363
1364 void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString& dirbase)
1365 {
1366 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
1367 _T("base directory shouldn't end with a slash") );
1368
1369 wxString dirname = dirbase;
1370 dirname << _T("/mime-info");
1371
1372 if ( !wxDir::Exists(dirname) )
1373 return;
1374
1375 wxDir dir(dirname);
1376 if ( !dir.IsOpened() )
1377 return;
1378
1379 // we will concatenate it with filename to get the full path below
1380 dirname += _T('/');
1381
1382 wxString filename;
1383 bool cont = dir.GetFirst(&filename, _T("*.keys"), wxDIR_FILES);
1384 while ( cont )
1385 {
1386 LoadIconsFromKeyFile(dirname + filename);
1387
1388 cont = dir.GetNext(&filename);
1389 }
1390 }
1391
1392 void wxGNOMEIconHandler::Init()
1393 {
1394 wxArrayString dirs;
1395 dirs.Add(_T("/usr/share"));
1396
1397 wxString gnomedir;
1398 wxGetHomeDir( &gnomedir );
1399 gnomedir += _T("/.gnome");
1400 dirs.Add( gnomedir );
1401
1402 size_t nDirs = dirs.GetCount();
1403 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1404 {
1405 LoadKeyFilesFromDir(dirs[nDir]);
1406 }
1407
1408 m_inited = TRUE;
1409 }
1410
1411 bool wxGNOMEIconHandler::GetIcon(const wxString& mimetype, wxIcon *icon)
1412 {
1413 if ( !m_inited )
1414 {
1415 Init();
1416 }
1417
1418 int index = ms_mimetypes.Index(mimetype);
1419 if ( index == wxNOT_FOUND )
1420 return FALSE;
1421
1422 wxString iconname = ms_icons[(size_t)index];
1423
1424 #if wxUSE_GUI
1425 *icon = wxIcon(iconname);
1426 #else
1427 // helpful for testing in console mode
1428 wxLogDebug(_T("Found GNOME icon for '%s': '%s'\n"),
1429 mimetype.c_str(), iconname.c_str());
1430 #endif
1431
1432 return TRUE;
1433 }
1434
1435 // ----------------------------------------------------------------------------
1436 // wxKDEIconHandler
1437 // ----------------------------------------------------------------------------
1438
1439 // KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
1440 // may be found in either of the following locations
1441 //
1442 // 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
1443 // 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
1444 //
1445 // The format of a .kdelnk file is almost the same as the one used by
1446 // wxFileConfig, i.e. there are groups, comments and entries. The icon is the
1447 // value for the entry "Type"
1448
1449 void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString& dirbase,
1450 const wxString& subdir,
1451 const wxString& filename,
1452 const wxArrayString& icondirs)
1453 {
1454 wxFFile file(dirbase + filename);
1455 if ( !file.IsOpened() )
1456 return;
1457
1458 // construct mimetype from the directory name and the basename of the
1459 // file (it always has .kdelnk extension)
1460 wxString mimetype;
1461 mimetype << subdir << _T('/') << filename.BeforeLast(_T('.'));
1462
1463 // these files are small, slurp the entire file at once
1464 wxString text;
1465 if ( !file.ReadAll(&text) )
1466 return;
1467
1468 int pos;
1469 const wxChar *pc;
1470
1471 // before trying to find an icon, grab mimetype information
1472 // (because BFU's machine would hardly have well-edited mime.types but (s)he might
1473 // have edited it in control panel...)
1474
1475 wxString mime_extension, mime_desc;
1476
1477 pos = wxNOT_FOUND;
1478 if (wxGetLocale() != NULL)
1479 mime_desc = _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
1480 if (pos == wxNOT_FOUND) mime_desc = _T("Comment=");
1481 pos = text.Find(mime_desc);
1482 if (pos == wxNOT_FOUND) mime_desc = wxEmptyString;
1483 else
1484 {
1485 pc = text.c_str() + pos + mime_desc.Length();
1486 mime_desc = wxEmptyString;
1487 while ( *pc && *pc != _T('\n') ) mime_desc += *pc++;
1488 }
1489
1490 pos = text.Find(_T("Patterns="));
1491 if (pos != wxNOT_FOUND)
1492 {
1493 wxString exts;
1494 pc = text.c_str() + pos + 9;
1495 while ( *pc && *pc != _T('\n') ) exts += *pc++;
1496 wxStringTokenizer tokenizer(exts, _T(";"));
1497 wxString e;
1498
1499 while (tokenizer.HasMoreTokens())
1500 {
1501 e = tokenizer.GetNextToken();
1502 if (e.Left(2) != _T("*.")) continue; // don't support too difficult patterns
1503 mime_extension << e.Mid(2);
1504 mime_extension << _T(' ');
1505 }
1506 mime_extension.RemoveLast();
1507 }
1508
1509 ms_infoTypes.Add(mimetype);
1510 ms_infoDescriptions.Add(mime_desc);
1511 ms_infoExtensions.Add(mime_extension);
1512
1513 // ok, now we can take care of icon:
1514
1515 pos = text.Find(_T("Icon="));
1516 if ( pos == wxNOT_FOUND )
1517 {
1518 // no icon info
1519 return;
1520 }
1521
1522 wxString icon;
1523
1524 pc = text.c_str() + pos + 5; // 5 == strlen("Icon=")
1525 while ( *pc && *pc != _T('\n') )
1526 {
1527 icon += *pc++;
1528 }
1529
1530 if ( !!icon )
1531 {
1532 // we must check if the file exists because it may be stored
1533 // in many locations, at least ~/.kde and $KDEDIR
1534 size_t nDir, nDirs = icondirs.GetCount();
1535 for ( nDir = 0; nDir < nDirs; nDir++ )
1536 if (wxFileExists(icondirs[nDir] + icon))
1537 {
1538 icon.Prepend(icondirs[nDir]);
1539 break;
1540 }
1541 if (nDir == nDirs) return; //does not exist
1542
1543 // do we already have this MIME type?
1544 int i = ms_mimetypes.Index(mimetype);
1545 if ( i == wxNOT_FOUND )
1546 {
1547 // add it
1548 size_t n = ms_mimetypes.Add(mimetype);
1549 ms_icons.Insert(icon, n);
1550 }
1551 else
1552 {
1553 // replace the old value
1554 ms_icons[(size_t)i] = icon;
1555 }
1556 }
1557 }
1558
1559 void wxKDEIconHandler::LoadLinksForMimeType(const wxString& dirbase,
1560 const wxString& subdir,
1561 const wxArrayString& icondirs)
1562 {
1563 wxString dirname = dirbase;
1564 dirname += subdir;
1565 wxDir dir(dirname);
1566 if ( !dir.IsOpened() )
1567 return;
1568
1569 dirname += _T('/');
1570
1571 wxString filename;
1572 bool cont = dir.GetFirst(&filename, _T("*.kdelnk"), wxDIR_FILES);
1573 while ( cont )
1574 {
1575 LoadLinksForMimeSubtype(dirname, subdir, filename, icondirs);
1576
1577 cont = dir.GetNext(&filename);
1578 }
1579 }
1580
1581 void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString& dirbase,
1582 const wxArrayString& icondirs)
1583 {
1584 wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
1585 _T("base directory shouldn't end with a slash") );
1586
1587 wxString dirname = dirbase;
1588 dirname << _T("/mimelnk");
1589
1590 if ( !wxDir::Exists(dirname) )
1591 return;
1592
1593 wxDir dir(dirname);
1594 if ( !dir.IsOpened() )
1595 return;
1596
1597 // we will concatenate it with dir name to get the full path below
1598 dirname += _T('/');
1599
1600 wxString subdir;
1601 bool cont = dir.GetFirst(&subdir, wxEmptyString, wxDIR_DIRS);
1602 while ( cont )
1603 {
1604 LoadLinksForMimeType(dirname, subdir, icondirs);
1605
1606 cont = dir.GetNext(&subdir);
1607 }
1608 }
1609
1610 void wxKDEIconHandler::Init()
1611 {
1612 wxArrayString dirs;
1613 wxArrayString icondirs;
1614
1615 // settings in ~/.kde have maximal priority
1616 dirs.Add(wxGetHomeDir() + _T("/.kde/share"));
1617 icondirs.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
1618
1619 // the variable KDEDIR is set when KDE is running
1620 const char *kdedir = getenv("KDEDIR");
1621 if ( kdedir )
1622 {
1623 dirs.Add(wxString(kdedir) + _T("/share"));
1624 icondirs.Add(wxString(kdedir) + _T("/share/icons/"));
1625 }
1626 else
1627 {
1628 // try to guess KDEDIR
1629 dirs.Add(_T("/usr/share"));
1630 dirs.Add(_T("/opt/kde/share"));
1631 icondirs.Add(_T("/usr/share/icons/"));
1632 icondirs.Add(_T("/opt/kde/share/icons/"));
1633 }
1634
1635 size_t nDirs = dirs.GetCount();
1636 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1637 {
1638 LoadLinkFilesFromDir(dirs[nDir], icondirs);
1639 }
1640
1641 m_inited = TRUE;
1642 }
1643
1644 bool wxKDEIconHandler::GetIcon(const wxString& mimetype, wxIcon *icon)
1645 {
1646 if ( !m_inited )
1647 {
1648 Init();
1649 }
1650
1651 int index = ms_mimetypes.Index(mimetype);
1652 if ( index == wxNOT_FOUND )
1653 return FALSE;
1654
1655 wxString iconname = ms_icons[(size_t)index];
1656
1657 #if wxUSE_GUI
1658 *icon = wxIcon(iconname);
1659 #else
1660 // helpful for testing in console mode
1661 wxLogDebug(_T("Found KDE icon for '%s': '%s'\n"),
1662 mimetype.c_str(), iconname.c_str());
1663 #endif
1664
1665 return TRUE;
1666 }
1667
1668
1669 void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl *manager)
1670 {
1671 if ( !m_inited ) Init();
1672
1673 size_t cnt = ms_infoTypes.GetCount();
1674 for (unsigned i = 0; i < cnt; i++)
1675 manager -> AddMimeTypeInfo(ms_infoTypes[i], ms_infoExtensions[i], ms_infoDescriptions[i]);
1676 }
1677
1678
1679 // ----------------------------------------------------------------------------
1680 // wxFileTypeImpl (Unix)
1681 // ----------------------------------------------------------------------------
1682
1683 MailCapEntry *
1684 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
1685 {
1686 wxString command;
1687 MailCapEntry *entry = m_manager->m_aEntries[m_index];
1688 while ( entry != NULL ) {
1689 // notice that an empty command would always succeed (it's ok)
1690 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
1691
1692 if ( command.IsEmpty() || (wxSystem(command) == 0) ) {
1693 // ok, passed
1694 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1695 command.c_str(), params.GetMimeType().c_str());
1696 break;
1697 }
1698 else {
1699 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1700 command.c_str(), params.GetMimeType().c_str());
1701 }
1702
1703 entry = entry->GetNext();
1704 }
1705
1706 return entry;
1707 }
1708
1709 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
1710 {
1711 wxString mimetype;
1712 (void)GetMimeType(&mimetype);
1713
1714 ArrayIconHandlers& handlers = m_manager->GetIconHandlers();
1715 size_t count = handlers.GetCount();
1716 for ( size_t n = 0; n < count; n++ )
1717 {
1718 if ( handlers[n]->GetIcon(mimetype, icon) )
1719 return TRUE;
1720 }
1721
1722 return FALSE;
1723 }
1724
1725 bool
1726 wxFileTypeImpl::GetExpandedCommand(wxString *expandedCmd,
1727 const wxFileType::MessageParameters& params,
1728 bool open) const
1729 {
1730 MailCapEntry *entry = GetEntry(params);
1731 if ( entry == NULL ) {
1732 // all tests failed...
1733 return FALSE;
1734 }
1735
1736 wxString cmd = open ? entry->GetOpenCmd() : entry->GetPrintCmd();
1737 if ( cmd.IsEmpty() ) {
1738 // may happen, especially for "print"
1739 return FALSE;
1740 }
1741
1742 *expandedCmd = wxFileType::ExpandCommand(cmd, params);
1743 return TRUE;
1744 }
1745
1746 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1747 {
1748 wxString strExtensions = m_manager->GetExtension(m_index);
1749 extensions.Empty();
1750
1751 // one extension in the space or comma delimitid list
1752 wxString strExt;
1753 for ( const wxChar *p = strExtensions; ; p++ ) {
1754 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
1755 if ( !strExt.IsEmpty() ) {
1756 extensions.Add(strExt);
1757 strExt.Empty();
1758 }
1759 //else: repeated spaces (shouldn't happen, but it's not that
1760 // important if it does happen)
1761
1762 if ( *p == wxT('\0') )
1763 break;
1764 }
1765 else if ( *p == wxT('.') ) {
1766 // remove the dot from extension (but only if it's the first char)
1767 if ( !strExt.IsEmpty() ) {
1768 strExt += wxT('.');
1769 }
1770 //else: no, don't append it
1771 }
1772 else {
1773 strExt += *p;
1774 }
1775 }
1776
1777 return TRUE;
1778 }
1779
1780 // ----------------------------------------------------------------------------
1781 // wxMimeTypesManagerImpl (Unix)
1782 // ----------------------------------------------------------------------------
1783
1784 /* static */
1785 ArrayIconHandlers& wxMimeTypesManagerImpl::GetIconHandlers()
1786 {
1787 if ( ms_iconHandlers.GetCount() == 0 )
1788 {
1789 ms_iconHandlers.Add(&gs_iconHandlerGNOME);
1790 ms_iconHandlers.Add(&gs_iconHandlerKDE);
1791 }
1792
1793 return ms_iconHandlers;
1794 }
1795
1796 // read system and user mailcaps (TODO implement mime.types support)
1797 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1798 {
1799 // directories where we look for mailcap and mime.types by default
1800 // (taken from metamail(1) sources)
1801 static const wxChar *aStandardLocations[] =
1802 {
1803 wxT("/etc"),
1804 wxT("/usr/etc"),
1805 wxT("/usr/local/etc"),
1806 wxT("/etc/mail"),
1807 wxT("/usr/public/lib")
1808 };
1809
1810 // first read the system wide file(s)
1811 size_t n;
1812 for ( n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
1813 wxString dir = aStandardLocations[n];
1814
1815 wxString file = dir + wxT("/mailcap");
1816 if ( wxFile::Exists(file) ) {
1817 ReadMailcap(file);
1818 }
1819
1820 file = dir + wxT("/mime.types");
1821 if ( wxFile::Exists(file) ) {
1822 ReadMimeTypes(file);
1823 }
1824 }
1825
1826 wxString strHome = wxGetenv(wxT("HOME"));
1827
1828 // and now the users mailcap
1829 wxString strUserMailcap = strHome + wxT("/.mailcap");
1830 if ( wxFile::Exists(strUserMailcap) ) {
1831 ReadMailcap(strUserMailcap);
1832 }
1833
1834 // read the users mime.types
1835 wxString strUserMimeTypes = strHome + wxT("/.mime.types");
1836 if ( wxFile::Exists(strUserMimeTypes) ) {
1837 ReadMimeTypes(strUserMimeTypes);
1838 }
1839
1840 // read KDE/GNOME tables
1841 ArrayIconHandlers& handlers = GetIconHandlers();
1842 size_t count = handlers.GetCount();
1843 for ( n = 0; n < count; n++ )
1844 handlers[n]->GetMimeInfoRecords(this);
1845 }
1846
1847 wxFileType *
1848 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1849 {
1850 size_t count = m_aExtensions.GetCount();
1851 for ( size_t n = 0; n < count; n++ ) {
1852 wxString extensions = m_aExtensions[n];
1853 while ( !extensions.IsEmpty() ) {
1854 wxString field = extensions.BeforeFirst(wxT(' '));
1855 extensions = extensions.AfterFirst(wxT(' '));
1856
1857 // consider extensions as not being case-sensitive
1858 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
1859 // found
1860 wxFileType *fileType = new wxFileType;
1861 fileType->m_impl->Init(this, n);
1862
1863 return fileType;
1864 }
1865 }
1866 }
1867
1868 // not found
1869 return NULL;
1870 }
1871
1872 wxFileType *
1873 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1874 {
1875 // mime types are not case-sensitive
1876 wxString mimetype(mimeType);
1877 mimetype.MakeLower();
1878
1879 // first look for an exact match
1880 int index = m_aTypes.Index(mimetype);
1881 if ( index == wxNOT_FOUND ) {
1882 // then try to find "text/*" as match for "text/plain" (for example)
1883 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1884 // the whole string - ok.
1885 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
1886
1887 size_t nCount = m_aTypes.Count();
1888 for ( size_t n = 0; n < nCount; n++ ) {
1889 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
1890 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
1891 index = n;
1892 break;
1893 }
1894 }
1895 }
1896
1897 if ( index != wxNOT_FOUND ) {
1898 wxFileType *fileType = new wxFileType;
1899 fileType->m_impl->Init(this, index);
1900
1901 return fileType;
1902 }
1903 else {
1904 // not found...
1905 return NULL;
1906 }
1907 }
1908
1909 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
1910 {
1911 wxString extensions;
1912 const wxArrayString& exts = filetype.GetExtensions();
1913 size_t nExts = exts.GetCount();
1914 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
1915 if ( nExt > 0 ) {
1916 extensions += wxT(' ');
1917 }
1918 extensions += exts[nExt];
1919 }
1920
1921 AddMimeTypeInfo(filetype.GetMimeType(),
1922 extensions,
1923 filetype.GetDescription());
1924
1925 AddMailcapInfo(filetype.GetMimeType(),
1926 filetype.GetOpenCommand(),
1927 filetype.GetPrintCommand(),
1928 wxT(""),
1929 filetype.GetDescription());
1930 }
1931
1932 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
1933 const wxString& strExtensions,
1934 const wxString& strDesc)
1935 {
1936 int index = m_aTypes.Index(strMimeType);
1937 if ( index == wxNOT_FOUND ) {
1938 // add a new entry
1939 m_aTypes.Add(strMimeType);
1940 m_aEntries.Add(NULL);
1941 m_aExtensions.Add(strExtensions);
1942 m_aDescriptions.Add(strDesc);
1943 }
1944 else {
1945 // modify an existing one
1946 if ( !strDesc.IsEmpty() ) {
1947 m_aDescriptions[index] = strDesc; // replace old value
1948 }
1949 m_aExtensions[index] += ' ' + strExtensions;
1950 }
1951 }
1952
1953 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
1954 const wxString& strOpenCmd,
1955 const wxString& strPrintCmd,
1956 const wxString& strTest,
1957 const wxString& strDesc)
1958 {
1959 MailCapEntry *entry = new MailCapEntry(strOpenCmd, strPrintCmd, strTest);
1960
1961 int nIndex = m_aTypes.Index(strType);
1962 if ( nIndex == wxNOT_FOUND ) {
1963 // new file type
1964 m_aTypes.Add(strType);
1965
1966 m_aEntries.Add(entry);
1967 m_aExtensions.Add(wxT(""));
1968 m_aDescriptions.Add(strDesc);
1969 }
1970 else {
1971 // always append the entry in the tail of the list - info added with
1972 // this function can only come from AddFallbacks()
1973 MailCapEntry *entryOld = m_aEntries[nIndex];
1974 if ( entryOld )
1975 entry->Append(entryOld);
1976 else
1977 m_aEntries[nIndex] = entry;
1978 }
1979 }
1980
1981 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
1982 {
1983 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName.c_str());
1984
1985 wxTextFile file(strFileName);
1986 if ( !file.Open() )
1987 return FALSE;
1988
1989 // the information we extract
1990 wxString strMimeType, strDesc, strExtensions;
1991
1992 size_t nLineCount = file.GetLineCount();
1993 const wxChar *pc = NULL;
1994 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1995 if ( pc == NULL ) {
1996 // now we're at the start of the line
1997 pc = file[nLine].c_str();
1998 }
1999 else {
2000 // we didn't finish with the previous line yet
2001 nLine--;
2002 }
2003
2004 // skip whitespace
2005 while ( wxIsspace(*pc) )
2006 pc++;
2007
2008 // comment or blank line?
2009 if ( *pc == wxT('#') || !*pc ) {
2010 // skip the whole line
2011 pc = NULL;
2012 continue;
2013 }
2014
2015 // detect file format
2016 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
2017 if ( pEqualSign == NULL ) {
2018 // brief format
2019 // ------------
2020
2021 // first field is mime type
2022 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
2023 strMimeType += *pc;
2024 }
2025
2026 // skip whitespace
2027 while ( wxIsspace(*pc) )
2028 pc++;
2029
2030 // take all the rest of the string
2031 strExtensions = pc;
2032
2033 // no description...
2034 strDesc.Empty();
2035 }
2036 else {
2037 // expanded format
2038 // ---------------
2039
2040 // the string on the left of '=' is the field name
2041 wxString strLHS(pc, pEqualSign - pc);
2042
2043 // eat whitespace
2044 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
2045 ;
2046
2047 const wxChar *pEnd;
2048 if ( *pc == wxT('"') ) {
2049 // the string is quoted and ends at the matching quote
2050 pEnd = wxStrchr(++pc, wxT('"'));
2051 if ( pEnd == NULL ) {
2052 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
2053 "quoted string."),
2054 strFileName.c_str(), nLine + 1);
2055 }
2056 }
2057 else {
2058 // unquoted string ends at the first space
2059 for ( pEnd = pc; !wxIsspace(*pEnd); pEnd++ )
2060 ;
2061 }
2062
2063 // now we have the RHS (field value)
2064 wxString strRHS(pc, pEnd - pc);
2065
2066 // check what follows this entry
2067 if ( *pEnd == wxT('"') ) {
2068 // skip this quote
2069 pEnd++;
2070 }
2071
2072 for ( pc = pEnd; wxIsspace(*pc); pc++ )
2073 ;
2074
2075 // if there is something left, it may be either a '\\' to continue
2076 // the line or the next field of the same entry
2077 bool entryEnded = *pc == wxT('\0'),
2078 nextFieldOnSameLine = FALSE;
2079 if ( !entryEnded ) {
2080 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
2081 }
2082
2083 // now see what we got
2084 if ( strLHS == wxT("type") ) {
2085 strMimeType = strRHS;
2086 }
2087 else if ( strLHS == wxT("desc") ) {
2088 strDesc = strRHS;
2089 }
2090 else if ( strLHS == wxT("exts") ) {
2091 strExtensions = strRHS;
2092 }
2093 else {
2094 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
2095 strFileName.c_str(), nLine + 1, strLHS.c_str());
2096 }
2097
2098 if ( !entryEnded ) {
2099 if ( !nextFieldOnSameLine )
2100 pc = NULL;
2101 //else: don't reset it
2102
2103 // as we don't reset strMimeType, the next field in this entry
2104 // will be interpreted correctly.
2105
2106 continue;
2107 }
2108 }
2109
2110 // although it doesn't seem to be covered by RFCs, some programs
2111 // (notably Netscape) create their entries with several comma
2112 // separated extensions (RFC mention the spaces only)
2113 strExtensions.Replace(wxT(","), wxT(" "));
2114
2115 // also deal with the leading dot
2116 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
2117 {
2118 strExtensions.erase(0, 1);
2119 }
2120
2121 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
2122
2123 // finished with this line
2124 pc = NULL;
2125 }
2126
2127 // check our data integriry
2128 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
2129 m_aTypes.Count() == m_aExtensions.Count() &&
2130 m_aTypes.Count() == m_aDescriptions.Count() );
2131
2132 return TRUE;
2133 }
2134
2135 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
2136 bool fallback)
2137 {
2138 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName.c_str());
2139
2140 wxTextFile file(strFileName);
2141 if ( !file.Open() )
2142 return FALSE;
2143
2144 // see the comments near the end of function for the reason we need these
2145 // variables (search for the next occurence of them)
2146 // indices of MIME types (in m_aTypes) we already found in this file
2147 wxArrayInt aEntryIndices;
2148 // aLastIndices[n] is the index of last element in
2149 // m_aEntries[aEntryIndices[n]] from this file
2150 wxArrayInt aLastIndices;
2151
2152 size_t nLineCount = file.GetLineCount();
2153 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
2154 // now we're at the start of the line
2155 const wxChar *pc = file[nLine].c_str();
2156
2157 // skip whitespace
2158 while ( wxIsspace(*pc) )
2159 pc++;
2160
2161 // comment or empty string?
2162 if ( *pc == wxT('#') || *pc == wxT('\0') )
2163 continue;
2164
2165 // no, do parse
2166
2167 // what field are we currently in? The first 2 are fixed and there may
2168 // be an arbitrary number of other fields -- currently, we are not
2169 // interested in any of them, but we should parse them as well...
2170 enum
2171 {
2172 Field_Type,
2173 Field_OpenCmd,
2174 Field_Other
2175 } currentToken = Field_Type;
2176
2177 // the flags and field values on the current line
2178 bool needsterminal = FALSE,
2179 copiousoutput = FALSE;
2180 wxString strType,
2181 strOpenCmd,
2182 strPrintCmd,
2183 strTest,
2184 strDesc,
2185 curField; // accumulator
2186 for ( bool cont = TRUE; cont; pc++ ) {
2187 switch ( *pc ) {
2188 case wxT('\\'):
2189 // interpret the next character literally (notice that
2190 // backslash can be used for line continuation)
2191 if ( *++pc == wxT('\0') ) {
2192 // fetch the next line.
2193
2194 // pc currently points to nowhere, but after the next
2195 // pc++ in the for line it will point to the beginning
2196 // of the next line in the file
2197 pc = file[++nLine].c_str() - 1;
2198 }
2199 else {
2200 // just a normal character
2201 curField += *pc;
2202 }
2203 break;
2204
2205 case wxT('\0'):
2206 cont = FALSE; // end of line reached, exit the loop
2207
2208 // fall through
2209
2210 case wxT(';'):
2211 // store this field and start looking for the next one
2212
2213 // trim whitespaces from both sides
2214 curField.Trim(TRUE).Trim(FALSE);
2215
2216 switch ( currentToken ) {
2217 case Field_Type:
2218 strType = curField;
2219 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
2220 // we interpret "type" as "type/*"
2221 strType += wxT("/*");
2222 }
2223
2224 currentToken = Field_OpenCmd;
2225 break;
2226
2227 case Field_OpenCmd:
2228 strOpenCmd = curField;
2229
2230 currentToken = Field_Other;
2231 break;
2232
2233 case Field_Other:
2234 {
2235 // "good" mailcap entry?
2236 bool ok = TRUE;
2237
2238 // is this something of the form foo=bar?
2239 const wxChar *pEq = wxStrchr(curField, wxT('='));
2240 if ( pEq != NULL ) {
2241 wxString lhs = curField.BeforeFirst(wxT('=')),
2242 rhs = curField.AfterFirst(wxT('='));
2243
2244 lhs.Trim(TRUE); // from right
2245 rhs.Trim(FALSE); // from left
2246
2247 if ( lhs == wxT("print") )
2248 strPrintCmd = rhs;
2249 else if ( lhs == wxT("test") )
2250 strTest = rhs;
2251 else if ( lhs == wxT("description") ) {
2252 // it might be quoted
2253 if ( rhs[0u] == wxT('"') &&
2254 rhs.Last() == wxT('"') ) {
2255 strDesc = wxString(rhs.c_str() + 1,
2256 rhs.Len() - 2);
2257 }
2258 else {
2259 strDesc = rhs;
2260 }
2261 }
2262 else if ( lhs == wxT("compose") ||
2263 lhs == wxT("composetyped") ||
2264 lhs == wxT("notes") ||
2265 lhs == wxT("edit") )
2266 ; // ignore
2267 else
2268 ok = FALSE;
2269
2270 }
2271 else {
2272 // no, it's a simple flag
2273 // TODO support the flags:
2274 // 1. create an xterm for 'needsterminal'
2275 // 2. append "| $PAGER" for 'copiousoutput'
2276 if ( curField == wxT("needsterminal") )
2277 needsterminal = TRUE;
2278 else if ( curField == wxT("copiousoutput") )
2279 copiousoutput = TRUE;
2280 else if ( curField == wxT("textualnewlines") )
2281 ; // ignore
2282 else
2283 ok = FALSE;
2284 }
2285
2286 if ( !ok )
2287 {
2288 // we don't understand this field, but
2289 // Netscape stores info in it, so don't warn
2290 // about it
2291 if ( curField.Left(16u) != "x-mozilla-flags=" )
2292 {
2293 // don't flood the user with error
2294 // messages if we don't understand
2295 // something in his mailcap, but give
2296 // them in debug mode because this might
2297 // be useful for the programmer
2298 wxLogDebug
2299 (
2300 wxT("Mailcap file %s, line %d: "
2301 "unknown field '%s' for the "
2302 "MIME type '%s' ignored."),
2303 strFileName.c_str(),
2304 nLine + 1,
2305 curField.c_str(),
2306 strType.c_str()
2307 );
2308 }
2309 }
2310 }
2311
2312 // it already has this value
2313 //currentToken = Field_Other;
2314 break;
2315
2316 default:
2317 wxFAIL_MSG(wxT("unknown field type in mailcap"));
2318 }
2319
2320 // next token starts immediately after ';'
2321 curField.Empty();
2322 break;
2323
2324 default:
2325 curField += *pc;
2326 }
2327 }
2328
2329 // check that we really read something reasonable
2330 if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
2331 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
2332 "ignored."),
2333 strFileName.c_str(), nLine + 1);
2334 }
2335 else {
2336 MailCapEntry *entry = new MailCapEntry(strOpenCmd,
2337 strPrintCmd,
2338 strTest);
2339
2340 // NB: because of complications below (we must get entries priority
2341 // right), we can't use AddMailcapInfo() here, unfortunately.
2342 strType.MakeLower();
2343 int nIndex = m_aTypes.Index(strType);
2344 if ( nIndex == wxNOT_FOUND ) {
2345 // new file type
2346 m_aTypes.Add(strType);
2347
2348 m_aEntries.Add(entry);
2349 m_aExtensions.Add(wxT(""));
2350 m_aDescriptions.Add(strDesc);
2351 }
2352 else {
2353 // modify the existing entry: the entries in one and the same
2354 // file are read in top-to-bottom order, i.e. the entries read
2355 // first should be tried before the entries below. However,
2356 // the files read later should override the settings in the
2357 // files read before (except if fallback is TRUE), thus we
2358 // Insert() the new entry to the list if it has already
2359 // occured in _this_ file, but Prepend() it if it occured in
2360 // some of the previous ones and Append() to it in the
2361 // fallback case
2362
2363 if ( fallback ) {
2364 // 'fallback' parameter prevents the entries from this
2365 // file from overriding the other ones - always append
2366 MailCapEntry *entryOld = m_aEntries[nIndex];
2367 if ( entryOld )
2368 entry->Append(entryOld);
2369 else
2370 m_aEntries[nIndex] = entry;
2371 }
2372 else {
2373 int entryIndex = aEntryIndices.Index(nIndex);
2374 if ( entryIndex == wxNOT_FOUND ) {
2375 // first time in this file
2376 aEntryIndices.Add(nIndex);
2377 aLastIndices.Add(0);
2378
2379 entry->Prepend(m_aEntries[nIndex]);
2380 m_aEntries[nIndex] = entry;
2381 }
2382 else {
2383 // not the first time in _this_ file
2384 size_t nEntryIndex = (size_t)entryIndex;
2385 MailCapEntry *entryOld = m_aEntries[nIndex];
2386 if ( entryOld )
2387 entry->Insert(entryOld, aLastIndices[nEntryIndex]);
2388 else
2389 m_aEntries[nIndex] = entry;
2390
2391 // the indices were shifted by 1
2392 aLastIndices[nEntryIndex]++;
2393 }
2394 }
2395
2396 if ( !strDesc.IsEmpty() ) {
2397 // replace the old one - what else can we do??
2398 m_aDescriptions[nIndex] = strDesc;
2399 }
2400 }
2401 }
2402
2403 // check our data integriry
2404 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
2405 m_aTypes.Count() == m_aExtensions.Count() &&
2406 m_aTypes.Count() == m_aDescriptions.Count() );
2407 }
2408
2409 return TRUE;
2410 }
2411
2412 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
2413 {
2414 mimetypes.Empty();
2415
2416 wxString type;
2417 size_t count = m_aTypes.GetCount();
2418 for ( size_t n = 0; n < count; n++ )
2419 {
2420 // don't return template types from here (i.e. anything containg '*')
2421 type = m_aTypes[n];
2422 if ( type.Find(_T('*')) == wxNOT_FOUND )
2423 {
2424 mimetypes.Add(type);
2425 }
2426 }
2427
2428 return mimetypes.GetCount();
2429 }
2430
2431 #endif
2432 // OS type
2433
2434 #endif
2435 // wxUSE_FILE && wxUSE_TEXTFILE
2436
2437 #endif
2438 // __WIN16__