]> git.saurik.com Git - wxWidgets.git/blame - src/common/mimetype.cpp
Some more bug reports
[wxWidgets.git] / src / common / mimetype.cpp
CommitLineData
b13d92d1
VZ
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__
ce4169a4 13#pragma implementation "mimetype.h"
b13d92d1
VZ
14#endif
15
b13d92d1
VZ
16// for compilers that support precompilation, includes "wx.h".
17#include "wx/wxprec.h"
18
19#ifdef __BORLANDC__
ce4169a4 20 #pragma hdrstop
b13d92d1
VZ
21#endif
22
b13d92d1 23#ifndef WX_PRECOMP
ce4169a4
RR
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"
b12915c1
VZ
31 #if wxUSE_GUI
32 #include "wx/icon.h"
33 #endif
b13d92d1
VZ
34#endif //WX_PRECOMP
35
3d05544e
JS
36// Doesn't compile in WIN16 mode
37#ifndef __WIN16__
38
b13d92d1 39#include "wx/log.h"
ce4169a4 40#include "wx/file.h"
b13d92d1
VZ
41#include "wx/intl.h"
42#include "wx/dynarray.h"
2432b92d 43#include "wx/confbase.h"
b13d92d1
VZ
44
45#ifdef __WXMSW__
46 #include "wx/msw/registry.h"
2432b92d 47 #include "windows.h"
fb5ddb4c 48#elif defined(__UNIX__) || defined(__WXPM__)
b9517a0a 49 #include "wx/ffile.h"
b13d92d1 50 #include "wx/textfile.h"
b9517a0a
VZ
51 #include "wx/dir.h"
52 #include "wx/utils.h"
cdf339c9 53 #include "wx/tokenzr.h"
b13d92d1
VZ
54#endif // OS
55
56#include "wx/mimetype.h"
57
58// other standard headers
59#include <ctype.h>
60
b12915c1
VZ
61// in case we're compiling in non-GUI mode
62class WXDLLEXPORT wxIcon;
63
b13d92d1
VZ
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
1b986aef
VZ
91// although I don't know of any official documentation which mentions this
92// location, uses it, so it isn't likely to change
93static const wxChar *MIME_DATABASE_KEY = wxT("MIME\\Database\\Content Type\\");
94
b13d92d1
VZ
95class wxFileTypeImpl
96{
97public:
98 // ctor
8e124873 99 wxFileTypeImpl() { m_info = NULL; }
b13d92d1 100
8e124873
VZ
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; }
b13d92d1
VZ
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,
8e124873 120 const wxFileType::MessageParameters& params) const;
b13d92d1 121 bool GetPrintCommand(wxString *printCmd,
8e124873 122 const wxFileType::MessageParameters& params) const;
b13d92d1
VZ
123
124private:
8e124873
VZ
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;
c61f4f6d
VZ
131 wxString m_strFileType, // may be empty
132 m_ext;
b13d92d1
VZ
133};
134
a497618a 135WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
8e124873
VZ
136#include "wx/arrimpl.cpp"
137WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
138
b13d92d1
VZ
139class wxMimeTypesManagerImpl
140{
141public:
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
696e1ea0 150 size_t EnumAllFileTypes(wxArrayString& mimetypes);
1b986aef 151
b13d92d1 152 // this are NOPs under Windows
be1023d5
VZ
153 bool ReadMailcap(const wxString& filename, bool fallback = TRUE)
154 { return TRUE; }
155 bool ReadMimeTypes(const wxString& filename)
156 { return TRUE; }
8e124873
VZ
157
158 void AddFallback(const wxFileTypeInfo& ft) { m_fallbacks.Add(ft); }
159
160private:
161 wxArrayFileTypeInfo m_fallbacks;
b13d92d1
VZ
162};
163
7c74e7fe
SC
164#elif defined( __WXMAC__ )
165
166WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
167#include "wx/arrimpl.cpp"
168WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
169
170class wxMimeTypesManagerImpl
171{
172public :
173 wxMimeTypesManagerImpl() { }
174
175 // implement containing class functions
176 wxFileType *GetFileTypeFromExtension(const wxString& ext);
177 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
178
696e1ea0 179 size_t EnumAllFileTypes(wxArrayString& mimetypes);
1b986aef 180
7c74e7fe
SC
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
187private:
188 wxArrayFileTypeInfo m_fallbacks;
189};
190
191class wxFileTypeImpl
192{
193public:
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
212private:
213 // helper function
214 bool GetCommand(wxString *command, const char *verb) const;
215
216 wxString m_strFileType, m_ext;
217};
218
b13d92d1
VZ
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//
ec4768ef 261// Parameter/filename xpansion:
b13d92d1
VZ
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>
ec4768ef 280// b) for "expanded" format:
b13d92d1
VZ
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.
289class MailCapEntry
290{
291public:
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; }
cc385968
VZ
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
223d09f6 322 wxASSERT_MSG( n == pos, wxT("invalid position in MailCapEntry::Insert") );
cc385968
VZ
323
324 m_next = cur->m_next;
325 cur->m_next = this;
326 }
327 // append this element to the list
b13d92d1
VZ
328 void Append(MailCapEntry *next)
329 {
223d09f6 330 wxCHECK_RET( next != NULL, wxT("Append()ing to what?") );
cc385968 331
b13d92d1
VZ
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
223d09f6 339 wxASSERT_MSG( !m_next, wxT("Append()ing element already in the list?") );
b13d92d1
VZ
340 }
341
342private:
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
351WX_DEFINE_ARRAY(MailCapEntry *, ArrayTypeEntries);
352
b9517a0a
VZ
353// the base class which may be used to find an icon for the MIME type
354class wxMimeTypeIconHandler
355{
356public:
357 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon) = 0;
5bd3a2da
VZ
358
359 // this function fills manager with MIME types information gathered
cdf339c9
VS
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;
b9517a0a
VZ
363};
364
365WX_DEFINE_ARRAY(wxMimeTypeIconHandler *, ArrayIconHandlers);
366
367// the icon handler which uses GNOME MIME database
368class wxGNOMEIconHandler : public wxMimeTypeIconHandler
369{
370public:
371 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon);
cdf339c9 372 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager) {}
5bd3a2da 373
b9517a0a
VZ
374private:
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
386class wxKDEIconHandler : public wxMimeTypeIconHandler
387{
388public:
389 virtual bool GetIcon(const wxString& mimetype, wxIcon *icon);
cdf339c9 390 virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager);
b9517a0a
VZ
391
392private:
393 void LoadLinksForMimeSubtype(const wxString& dirbase,
394 const wxString& subdir,
cdf339c9
VS
395 const wxString& filename,
396 const wxArrayString& icondirs);
b9517a0a 397 void LoadLinksForMimeType(const wxString& dirbase,
cdf339c9
VS
398 const wxString& subdir,
399 const wxArrayString& icondirs);
5bd3a2da 400 void LoadLinkFilesFromDir(const wxString& dirbase,
cdf339c9 401 const wxArrayString& icondirs);
b9517a0a
VZ
402 void Init();
403
404 static bool m_inited;
405
406 static wxSortedArrayString ms_mimetypes;
407 static wxArrayString ms_icons;
cdf339c9
VS
408
409 static wxArrayString ms_infoTypes;
410 static wxArrayString ms_infoDescriptions;
411 static wxArrayString ms_infoExtensions;
b9517a0a
VZ
412};
413
414// this is the real wxMimeTypesManager for Unix
b13d92d1
VZ
415class wxMimeTypesManagerImpl
416{
417friend class wxFileTypeImpl; // give it access to m_aXXX variables
418
419public:
420 // ctor loads all info into memory for quicker access later on
cc385968 421 // TODO it would be nice to load them all, but parse on demand only...
b13d92d1
VZ
422 wxMimeTypesManagerImpl();
423
424 // implement containing class functions
425 wxFileType *GetFileTypeFromExtension(const wxString& ext);
426 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
427
696e1ea0 428 size_t EnumAllFileTypes(wxArrayString& mimetypes);
1b986aef 429
cc385968
VZ
430 bool ReadMailcap(const wxString& filename, bool fallback = FALSE);
431 bool ReadMimeTypes(const wxString& filename);
b13d92d1 432
8e124873
VZ
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
b13d92d1
VZ
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
b9517a0a
VZ
450 // get the array of icon handlers
451 static ArrayIconHandlers& GetIconHandlers();
452
b13d92d1
VZ
453private:
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
b9517a0a
VZ
458
459 // head of the linked list of the icon handlers
460 static ArrayIconHandlers ms_iconHandlers;
b13d92d1
VZ
461};
462
463class wxFileTypeImpl
464{
465public:
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; }
b9517a0a 474 bool GetIcon(wxIcon *icon) const;
b13d92d1
VZ
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
490private:
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
8e124873
VZ
505// ============================================================================
506// common classes
507// ============================================================================
508
509// ----------------------------------------------------------------------------
510// wxFileTypeInfo
511// ----------------------------------------------------------------------------
512
513wxFileTypeInfo::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
b13d92d1
VZ
541// ============================================================================
542// implementation of the wrapper classes
543// ============================================================================
544
545// ----------------------------------------------------------------------------
546// wxFileType
547// ----------------------------------------------------------------------------
548
549wxString wxFileType::ExpandCommand(const wxString& command,
550 const wxFileType::MessageParameters& params)
551{
552 bool hasFilename = FALSE;
553
554 wxString str;
223d09f6
KB
555 for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
556 if ( *pc == wxT('%') ) {
b13d92d1 557 switch ( *++pc ) {
223d09f6 558 case wxT('s'):
b13d92d1
VZ
559 // '%s' expands into file name (quoted because it might
560 // contain spaces) - except if there are already quotes
341c92a8
VZ
561 // there because otherwise some programs may get confused
562 // by double double quotes
b13d92d1 563#if 0
223d09f6 564 if ( *(pc - 2) == wxT('"') )
b13d92d1
VZ
565 str << params.GetFileName();
566 else
223d09f6 567 str << wxT('"') << params.GetFileName() << wxT('"');
b13d92d1
VZ
568#endif
569 str << params.GetFileName();
570 hasFilename = TRUE;
571 break;
572
223d09f6 573 case wxT('t'):
b13d92d1
VZ
574 // '%t' expands into MIME type (quote it too just to be
575 // consistent)
223d09f6 576 str << wxT('\'') << params.GetMimeType() << wxT('\'');
b13d92d1
VZ
577 break;
578
223d09f6 579 case wxT('{'):
b13d92d1 580 {
223d09f6 581 const wxChar *pEnd = wxStrchr(pc, wxT('}'));
b13d92d1
VZ
582 if ( pEnd == NULL ) {
583 wxString mimetype;
584 wxLogWarning(_("Unmatched '{' in an entry for "
585 "mime type %s."),
586 params.GetMimeType().c_str());
223d09f6 587 str << wxT("%{");
b13d92d1
VZ
588 }
589 else {
590 wxString param(pc + 1, pEnd - pc - 1);
223d09f6 591 str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
b13d92d1
VZ
592 pc = pEnd;
593 }
594 }
595 break;
596
223d09f6
KB
597 case wxT('n'):
598 case wxT('F'):
b13d92d1
VZ
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:
223d09f6 605 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
b13d92d1
VZ
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() ) {
223d09f6 618 str << wxT(" < '") << params.GetFileName() << wxT('\'');
b13d92d1
VZ
619 }
620
621 return str;
622}
623
624wxFileType::wxFileType()
625{
626 m_impl = new wxFileTypeImpl;
627}
628
629wxFileType::~wxFileType()
630{
631 delete m_impl;
632}
633
634bool wxFileType::GetExtensions(wxArrayString& extensions)
635{
636 return m_impl->GetExtensions(extensions);
637}
638
639bool wxFileType::GetMimeType(wxString *mimeType) const
640{
641 return m_impl->GetMimeType(mimeType);
642}
643
644bool wxFileType::GetIcon(wxIcon *icon) const
645{
646 return m_impl->GetIcon(icon);
647}
648
649bool wxFileType::GetDescription(wxString *desc) const
650{
651 return m_impl->GetDescription(desc);
652}
653
654bool
655wxFileType::GetOpenCommand(wxString *openCmd,
656 const wxFileType::MessageParameters& params) const
657{
658 return m_impl->GetOpenCommand(openCmd, params);
659}
660
661bool
662wxFileType::GetPrintCommand(wxString *printCmd,
663 const wxFileType::MessageParameters& params) const
664{
665 return m_impl->GetPrintCommand(printCmd, params);
666}
667
668// ----------------------------------------------------------------------------
669// wxMimeTypesManager
670// ----------------------------------------------------------------------------
671
a5a19b83
VZ
672bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
673 const wxString& wildcard)
674{
223d09f6
KB
675 wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
676 wxT("first MIME type can't contain wildcards") );
a5a19b83
VZ
677
678 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
223d09f6 679 if ( wildcard.BeforeFirst(wxT('/')).IsSameAs(mimeType.BeforeFirst(wxT('/')), FALSE) )
a5a19b83 680 {
223d09f6 681 wxString strSubtype = wildcard.AfterFirst(wxT('/'));
a5a19b83 682
223d09f6
KB
683 if ( strSubtype == wxT("*") ||
684 strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), FALSE) )
a5a19b83
VZ
685 {
686 // matches (either exactly or it's a wildcard)
687 return TRUE;
688 }
689 }
690
691 return FALSE;
692}
693
b13d92d1
VZ
694wxMimeTypesManager::wxMimeTypesManager()
695{
696 m_impl = new wxMimeTypesManagerImpl;
697}
698
699wxMimeTypesManager::~wxMimeTypesManager()
700{
701 delete m_impl;
702}
703
704wxFileType *
705wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
706{
707 return m_impl->GetFileTypeFromExtension(ext);
708}
709
710wxFileType *
711wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
712{
713 return m_impl->GetFileTypeFromMimeType(mimeType);
714}
715
cc385968 716bool wxMimeTypesManager::ReadMailcap(const wxString& filename, bool fallback)
22b4634c 717{
cc385968 718 return m_impl->ReadMailcap(filename, fallback);
22b4634c
VZ
719}
720
cc385968 721bool wxMimeTypesManager::ReadMimeTypes(const wxString& filename)
22b4634c 722{
cc385968 723 return m_impl->ReadMimeTypes(filename);
22b4634c
VZ
724}
725
8e124873
VZ
726void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
727{
728 for ( const wxFileTypeInfo *ft = filetypes; ft->IsValid(); ft++ ) {
729 m_impl->AddFallback(*ft);
730 }
731}
732
696e1ea0 733size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef 734{
696e1ea0 735 return m_impl->EnumAllFileTypes(mimetypes);
1b986aef
VZ
736}
737
b13d92d1
VZ
738// ============================================================================
739// real (OS specific) implementation
740// ============================================================================
741
742#ifdef __WXMSW__
743
8e124873 744wxString wxFileTypeImpl::GetCommand(const wxChar *verb) const
b13d92d1
VZ
745{
746 // suppress possible error messages
747 wxLogNull nolog;
748 wxString strKey;
b13d92d1 749
c61f4f6d
VZ
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
5bd3a2da
VZ
761 strKey << wxT("\\shell\\") << verb;
762 wxRegKey key(wxRegKey::HKCR, strKey + _T("\\command"));
8e124873 763 wxString command;
b13d92d1
VZ
764 if ( key.Open() ) {
765 // it's the default value of the key
223d09f6 766 if ( key.QueryValue(wxT(""), command) ) {
5bd3a2da
VZ
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)
8e124873 770
cc385968
VZ
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'!
8e124873
VZ
774 bool foundFilename = FALSE;
775 size_t len = command.Len();
776 for ( size_t n = 0; (n < len) && !foundFilename; n++ ) {
223d09f6 777 if ( command[n] == wxT('%') &&
5bd3a2da
VZ
778 (n + 1 < len) &&
779 (command[n + 1] == wxT('1') ||
780 command[n + 1] == wxT('L')) ) {
b13d92d1 781 // replace it with '%s'
223d09f6 782 command[n + 1] = wxT('s');
b13d92d1 783
8e124873 784 foundFilename = TRUE;
b13d92d1
VZ
785 }
786 }
787
5bd3a2da
VZ
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 //
8e124873 815 // HACK: append the filename at the end, hope that it will do
223d09f6 816 command << wxT(" %s");
8e124873 817 }
b13d92d1
VZ
818 }
819 }
c61f4f6d 820 //else: no such file type or no value, will return empty string
b13d92d1 821
8e124873
VZ
822 return command;
823}
824
825bool
826wxFileTypeImpl::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 {
223d09f6 835 cmd = GetCommand(wxT("open"));
8e124873
VZ
836 }
837
838 *openCmd = wxFileType::ExpandCommand(cmd, params);
839
840 return !openCmd->IsEmpty();
841}
842
843bool
844wxFileTypeImpl::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 {
223d09f6 853 cmd = GetCommand(wxT("print"));
8e124873
VZ
854 }
855
856 *printCmd = wxFileType::ExpandCommand(cmd, params);
857
858 return !printCmd->IsEmpty();
b13d92d1
VZ
859}
860
cc385968 861// TODO this function is half implemented
b13d92d1
VZ
862bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
863{
8e124873
VZ
864 if ( m_info ) {
865 extensions = m_info->GetExtensions();
866
867 return TRUE;
868 }
869 else if ( m_ext.IsEmpty() ) {
b13d92d1
VZ
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
883bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
884{
8e124873
VZ
885 if ( m_info ) {
886 // we already have it
887 *mimeType = m_info->GetMimeType();
888
889 return TRUE;
890 }
891
b13d92d1
VZ
892 // suppress possible error messages
893 wxLogNull nolog;
c61f4f6d 894 wxRegKey key(wxRegKey::HKCR, wxT(".") + m_ext);
223d09f6 895 if ( key.Open() && key.QueryValue(wxT("Content Type"), *mimeType) ) {
b13d92d1
VZ
896 return TRUE;
897 }
898 else {
899 return FALSE;
900 }
901}
902
903bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
904{
b568d04f 905#if wxUSE_GUI
8e124873
VZ
906 if ( m_info ) {
907 // we don't have icons in the fallback resources
908 return FALSE;
909 }
910
b13d92d1 911 wxString strIconKey;
223d09f6 912 strIconKey << m_strFileType << wxT("\\DefaultIcon");
b13d92d1
VZ
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
223d09f6 921 if ( key.QueryValue(wxT(""), strIcon) ) {
b13d92d1
VZ
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 '%'
223d09f6
KB
925 wxString strFullPath = strIcon.BeforeLast(wxT(',')),
926 strIndex = strIcon.AfterLast(wxT(','));
b13d92d1 927
3c67202d
VZ
928 // index may be omitted, in which case BeforeLast(',') is empty and
929 // AfterLast(',') is the whole string
b13d92d1
VZ
930 if ( strFullPath.IsEmpty() ) {
931 strFullPath = strIndex;
223d09f6 932 strIndex = wxT("0");
b13d92d1
VZ
933 }
934
935 wxString strExpPath = wxExpandEnvVars(strFullPath);
4de6207a 936 int nIndex = wxAtoi(strIndex);
b13d92d1
VZ
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/...
223d09f6 942 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
b13d92d1
VZ
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
b568d04f
VZ
954#endif // wxUSE_GUI
955
b13d92d1
VZ
956 return FALSE;
957}
958
959bool wxFileTypeImpl::GetDescription(wxString *desc) const
960{
8e124873
VZ
961 if ( m_info ) {
962 // we already have it
963 *desc = m_info->GetDescription();
964
965 return TRUE;
966 }
967
b13d92d1
VZ
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
223d09f6 974 if ( key.QueryValue(wxT(""), *desc) ) {
b13d92d1
VZ
975 return TRUE;
976 }
977 }
978
979 return FALSE;
980}
981
982// extension -> file type
983wxFileType *
984wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
985{
986 // add the leading point if necessary
987 wxString str;
223d09f6
KB
988 if ( ext[0u] != wxT('.') ) {
989 str = wxT('.');
b13d92d1
VZ
990 }
991 str << ext;
992
993 // suppress possible error messages
994 wxLogNull nolog;
995
c61f4f6d
VZ
996 bool knownExtension = FALSE;
997
b13d92d1
VZ
998 wxString strFileType;
999 wxRegKey key(wxRegKey::HKCR, str);
1000 if ( key.Open() ) {
1001 // it's the default value of the key
223d09f6 1002 if ( key.QueryValue(wxT(""), strFileType) ) {
b13d92d1
VZ
1003 // create the new wxFileType object
1004 wxFileType *fileType = new wxFileType;
8e124873
VZ
1005 fileType->m_impl->Init(strFileType, ext);
1006
1007 return fileType;
1008 }
c61f4f6d
VZ
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 }
8e124873
VZ
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]);
b13d92d1
VZ
1025
1026 return fileType;
1027 }
1028 }
1029
c61f4f6d
VZ
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 }
b13d92d1
VZ
1042}
1043
1044// MIME type -> extension -> file type
1045wxFileType *
1046wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1047{
1b986aef 1048 wxString strKey = MIME_DATABASE_KEY;
b13d92d1
VZ
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() ) {
223d09f6 1057 if ( key.QueryValue(wxT("Extension"), ext) ) {
b13d92d1
VZ
1058 return GetFileTypeFromExtension(ext);
1059 }
1060 }
1061
8e124873
VZ
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
b13d92d1
VZ
1076 // unknown MIME type
1077 return NULL;
1078}
1079
696e1ea0 1080size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef
VZ
1081{
1082 // enumerate all keys under MIME_DATABASE_KEY
1083 wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
7c74e7fe 1084
696e1ea0
VZ
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();
1b986aef
VZ
1096}
1097
1098#elif defined ( __WXMAC__ )
7c74e7fe
SC
1099
1100bool wxFileTypeImpl::GetCommand(wxString *command, const char *verb) const
1101{
1102 return FALSE;
1103}
1104
1105// @@ this function is half implemented
1106bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1107{
1108 return FALSE;
1109}
1110
1111bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
1112{
1b986aef
VZ
1113 if ( m_strFileType.Length() > 0 )
1114 {
1115 *mimeType = m_strFileType ;
1116 return TRUE ;
1117 }
1118 else
7c74e7fe
SC
1119 return FALSE;
1120}
1121
1122bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
1123{
1124 // no such file type or no value or incorrect icon entry
1125 return FALSE;
1126}
1127
1128bool wxFileTypeImpl::GetDescription(wxString *desc) const
1129{
1130 return FALSE;
1131}
1132
1133// extension -> file type
1134wxFileType *
1135wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& e)
1136{
1b986aef
VZ
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;
7c74e7fe
SC
1205}
1206
1207// MIME type -> extension -> file type
1208wxFileType *
1209wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1210{
1211 return NULL;
1212}
1b986aef 1213
696e1ea0 1214size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef
VZ
1215{
1216 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1217
1218 return 0;
1219}
1220
b13d92d1
VZ
1221#else // Unix
1222
b9517a0a
VZ
1223// ============================================================================
1224// Unix implementation
1225// ============================================================================
1226
1227// ----------------------------------------------------------------------------
1228// various statics
1229// ----------------------------------------------------------------------------
1230
1231static wxGNOMEIconHandler gs_iconHandlerGNOME;
1232static wxKDEIconHandler gs_iconHandlerKDE;
1233
1234bool wxGNOMEIconHandler::m_inited = FALSE;
1235wxSortedArrayString wxGNOMEIconHandler::ms_mimetypes;
1236wxArrayString wxGNOMEIconHandler::ms_icons;
1237
1238bool wxKDEIconHandler::m_inited = FALSE;
1239wxSortedArrayString wxKDEIconHandler::ms_mimetypes;
1240wxArrayString wxKDEIconHandler::ms_icons;
1241
cdf339c9
VS
1242wxArrayString wxKDEIconHandler::ms_infoTypes;
1243wxArrayString wxKDEIconHandler::ms_infoDescriptions;
1244wxArrayString wxKDEIconHandler::ms_infoExtensions;
1245
1246
b9517a0a
VZ
1247ArrayIconHandlers 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
1266void 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
1364void 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
1392void wxGNOMEIconHandler::Init()
1393{
1394 wxArrayString dirs;
1395 dirs.Add(_T("/usr/share"));
fb5ddb4c 1396
af159c44
RR
1397 wxString gnomedir;
1398 wxGetHomeDir( &gnomedir );
1399 gnomedir += _T("/.gnome");
1400 dirs.Add( gnomedir );
b9517a0a
VZ
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
1411bool 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//
509a6196 1442// 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
b9517a0a
VZ
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
1449void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString& dirbase,
1450 const wxString& subdir,
cdf339c9
VS
1451 const wxString& filename,
1452 const wxArrayString& icondirs)
b9517a0a
VZ
1453{
1454 wxFFile file(dirbase + filename);
1455 if ( !file.IsOpened() )
1456 return;
1457
cdf339c9
VS
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
b9517a0a
VZ
1463 // these files are small, slurp the entire file at once
1464 wxString text;
1465 if ( !file.ReadAll(&text) )
1466 return;
1467
cdf339c9
VS
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
5bd3a2da 1477 pos = wxNOT_FOUND;
cdf339c9
VS
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;
5bd3a2da 1498
cdf339c9
VS
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 }
5bd3a2da 1508
cdf339c9
VS
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="));
b9517a0a
VZ
1516 if ( pos == wxNOT_FOUND )
1517 {
1518 // no icon info
1519 return;
1520 }
1521
1522 wxString icon;
1523
cdf339c9 1524 pc = text.c_str() + pos + 5; // 5 == strlen("Icon=")
b9517a0a
VZ
1525 while ( *pc && *pc != _T('\n') )
1526 {
1527 icon += *pc++;
1528 }
1529
1530 if ( !!icon )
1531 {
cdf339c9
VS
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
b9517a0a
VZ
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
1559void wxKDEIconHandler::LoadLinksForMimeType(const wxString& dirbase,
cdf339c9
VS
1560 const wxString& subdir,
1561 const wxArrayString& icondirs)
b9517a0a
VZ
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 {
cdf339c9 1575 LoadLinksForMimeSubtype(dirname, subdir, filename, icondirs);
b9517a0a
VZ
1576
1577 cont = dir.GetNext(&filename);
1578 }
1579}
1580
cdf339c9
VS
1581void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString& dirbase,
1582 const wxArrayString& icondirs)
b9517a0a
VZ
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 {
cdf339c9 1604 LoadLinksForMimeType(dirname, subdir, icondirs);
b9517a0a
VZ
1605
1606 cont = dir.GetNext(&subdir);
1607 }
1608}
1609
1610void wxKDEIconHandler::Init()
1611{
1612 wxArrayString dirs;
cdf339c9
VS
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/"));
509a6196
VZ
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"));
cdf339c9 1624 icondirs.Add(wxString(kdedir) + _T("/share/icons/"));
509a6196
VZ
1625 }
1626 else
1627 {
1628 // try to guess KDEDIR
1629 dirs.Add(_T("/usr/share"));
1630 dirs.Add(_T("/opt/kde/share"));
cdf339c9
VS
1631 icondirs.Add(_T("/usr/share/icons/"));
1632 icondirs.Add(_T("/opt/kde/share/icons/"));
509a6196
VZ
1633 }
1634
b9517a0a
VZ
1635 size_t nDirs = dirs.GetCount();
1636 for ( size_t nDir = 0; nDir < nDirs; nDir++ )
1637 {
cdf339c9 1638 LoadLinkFilesFromDir(dirs[nDir], icondirs);
b9517a0a
VZ
1639 }
1640
1641 m_inited = TRUE;
1642}
1643
1644bool 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
cdf339c9
VS
1668
1669void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl *manager)
1670{
1671 if ( !m_inited ) Init();
5bd3a2da 1672
cdf339c9
VS
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
b9517a0a
VZ
1679// ----------------------------------------------------------------------------
1680// wxFileTypeImpl (Unix)
1681// ----------------------------------------------------------------------------
1682
b13d92d1
VZ
1683MailCapEntry *
1684wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
1685{
1686 wxString command;
1687 MailCapEntry *entry = m_manager->m_aEntries[m_index];
1688 while ( entry != NULL ) {
cc385968 1689 // notice that an empty command would always succeed (it's ok)
b13d92d1
VZ
1690 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
1691
50920146 1692 if ( command.IsEmpty() || (wxSystem(command) == 0) ) {
b13d92d1 1693 // ok, passed
223d09f6 1694 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
b13d92d1
VZ
1695 command.c_str(), params.GetMimeType().c_str());
1696 break;
1697 }
1698 else {
223d09f6 1699 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
b13d92d1
VZ
1700 command.c_str(), params.GetMimeType().c_str());
1701 }
1702
1703 entry = entry->GetNext();
1704 }
1705
1706 return entry;
1707}
1708
b9517a0a
VZ
1709bool 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
b13d92d1
VZ
1725bool
1726wxFileTypeImpl::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
1746bool 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;
50920146 1753 for ( const wxChar *p = strExtensions; ; p++ ) {
223d09f6 1754 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
b13d92d1
VZ
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
223d09f6 1762 if ( *p == wxT('\0') )
b13d92d1
VZ
1763 break;
1764 }
223d09f6 1765 else if ( *p == wxT('.') ) {
b13d92d1
VZ
1766 // remove the dot from extension (but only if it's the first char)
1767 if ( !strExt.IsEmpty() ) {
223d09f6 1768 strExt += wxT('.');
b13d92d1
VZ
1769 }
1770 //else: no, don't append it
1771 }
1772 else {
1773 strExt += *p;
1774 }
1775 }
1776
1777 return TRUE;
1778}
1779
b9517a0a
VZ
1780// ----------------------------------------------------------------------------
1781// wxMimeTypesManagerImpl (Unix)
1782// ----------------------------------------------------------------------------
1783
1784/* static */
1785ArrayIconHandlers& 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
b13d92d1
VZ
1796// read system and user mailcaps (TODO implement mime.types support)
1797wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1798{
1799 // directories where we look for mailcap and mime.types by default
1800 // (taken from metamail(1) sources)
50920146 1801 static const wxChar *aStandardLocations[] =
b13d92d1 1802 {
223d09f6
KB
1803 wxT("/etc"),
1804 wxT("/usr/etc"),
1805 wxT("/usr/local/etc"),
1806 wxT("/etc/mail"),
1807 wxT("/usr/public/lib")
b13d92d1
VZ
1808 };
1809
1810 // first read the system wide file(s)
5bd3a2da
VZ
1811 size_t n;
1812 for ( n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
b13d92d1
VZ
1813 wxString dir = aStandardLocations[n];
1814
223d09f6 1815 wxString file = dir + wxT("/mailcap");
b13d92d1
VZ
1816 if ( wxFile::Exists(file) ) {
1817 ReadMailcap(file);
1818 }
1819
223d09f6 1820 file = dir + wxT("/mime.types");
b13d92d1
VZ
1821 if ( wxFile::Exists(file) ) {
1822 ReadMimeTypes(file);
1823 }
1824 }
1825
223d09f6 1826 wxString strHome = wxGetenv(wxT("HOME"));
b13d92d1
VZ
1827
1828 // and now the users mailcap
223d09f6 1829 wxString strUserMailcap = strHome + wxT("/.mailcap");
b13d92d1
VZ
1830 if ( wxFile::Exists(strUserMailcap) ) {
1831 ReadMailcap(strUserMailcap);
1832 }
1833
1834 // read the users mime.types
223d09f6 1835 wxString strUserMimeTypes = strHome + wxT("/.mime.types");
b13d92d1
VZ
1836 if ( wxFile::Exists(strUserMimeTypes) ) {
1837 ReadMimeTypes(strUserMimeTypes);
1838 }
5bd3a2da 1839
cdf339c9
VS
1840 // read KDE/GNOME tables
1841 ArrayIconHandlers& handlers = GetIconHandlers();
1842 size_t count = handlers.GetCount();
5bd3a2da 1843 for ( n = 0; n < count; n++ )
cdf339c9 1844 handlers[n]->GetMimeInfoRecords(this);
b13d92d1
VZ
1845}
1846
1847wxFileType *
1848wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1849{
1ee17e1c
VZ
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() ) {
223d09f6
KB
1854 wxString field = extensions.BeforeFirst(wxT(' '));
1855 extensions = extensions.AfterFirst(wxT(' '));
1ee17e1c
VZ
1856
1857 // consider extensions as not being case-sensitive
ec4768ef 1858 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
1ee17e1c
VZ
1859 // found
1860 wxFileType *fileType = new wxFileType;
1861 fileType->m_impl->Init(this, n);
ec4768ef 1862
1ee17e1c
VZ
1863 return fileType;
1864 }
1865 }
1866 }
b13d92d1 1867
1ee17e1c 1868 // not found
b13d92d1
VZ
1869 return NULL;
1870}
1871
1872wxFileType *
1873wxMimeTypesManagerImpl::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);
3c67202d 1881 if ( index == wxNOT_FOUND ) {
b13d92d1 1882 // then try to find "text/*" as match for "text/plain" (for example)
3c67202d
VZ
1883 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1884 // the whole string - ok.
223d09f6 1885 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
b13d92d1
VZ
1886
1887 size_t nCount = m_aTypes.Count();
1888 for ( size_t n = 0; n < nCount; n++ ) {
223d09f6
KB
1889 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
1890 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
b13d92d1
VZ
1891 index = n;
1892 break;
1893 }
1894 }
1895 }
1896
3c67202d 1897 if ( index != wxNOT_FOUND ) {
b13d92d1
VZ
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
8e124873
VZ
1909void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
1910{
3f1aaa16 1911 wxString extensions;
8e124873
VZ
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 ) {
223d09f6 1916 extensions += wxT(' ');
8e124873
VZ
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(),
223d09f6 1928 wxT(""),
8e124873
VZ
1929 filetype.GetDescription());
1930}
1931
1932void 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 }
c15d098c 1949 m_aExtensions[index] += ' ' + strExtensions;
8e124873
VZ
1950 }
1951}
1952
1953void 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);
223d09f6 1967 m_aExtensions.Add(wxT(""));
8e124873
VZ
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
cc385968 1981bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
b13d92d1 1982{
223d09f6 1983 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName.c_str());
b13d92d1
VZ
1984
1985 wxTextFile file(strFileName);
1986 if ( !file.Open() )
cc385968 1987 return FALSE;
b13d92d1
VZ
1988
1989 // the information we extract
1990 wxString strMimeType, strDesc, strExtensions;
1991
1992 size_t nLineCount = file.GetLineCount();
50920146 1993 const wxChar *pc = NULL;
b13d92d1 1994 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
22b4634c
VZ
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 }
b13d92d1
VZ
2003
2004 // skip whitespace
50920146 2005 while ( wxIsspace(*pc) )
b13d92d1
VZ
2006 pc++;
2007
54acce90
VZ
2008 // comment or blank line?
2009 if ( *pc == wxT('#') || !*pc ) {
22b4634c
VZ
2010 // skip the whole line
2011 pc = NULL;
b13d92d1 2012 continue;
22b4634c 2013 }
b13d92d1
VZ
2014
2015 // detect file format
223d09f6 2016 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
b13d92d1
VZ
2017 if ( pEqualSign == NULL ) {
2018 // brief format
2019 // ------------
2020
2021 // first field is mime type
223d09f6 2022 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
b13d92d1
VZ
2023 strMimeType += *pc;
2024 }
2025
2026 // skip whitespace
50920146 2027 while ( wxIsspace(*pc) )
b13d92d1
VZ
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
50920146 2044 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
b13d92d1
VZ
2045 ;
2046
50920146 2047 const wxChar *pEnd;
223d09f6 2048 if ( *pc == wxT('"') ) {
b13d92d1 2049 // the string is quoted and ends at the matching quote
223d09f6 2050 pEnd = wxStrchr(++pc, wxT('"'));
b13d92d1
VZ
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 {
22b4634c 2058 // unquoted string ends at the first space
50920146 2059 for ( pEnd = pc; !wxIsspace(*pEnd); pEnd++ )
b13d92d1
VZ
2060 ;
2061 }
2062
2063 // now we have the RHS (field value)
2064 wxString strRHS(pc, pEnd - pc);
2065
22b4634c 2066 // check what follows this entry
223d09f6 2067 if ( *pEnd == wxT('"') ) {
b13d92d1
VZ
2068 // skip this quote
2069 pEnd++;
2070 }
2071
50920146 2072 for ( pc = pEnd; wxIsspace(*pc); pc++ )
b13d92d1
VZ
2073 ;
2074
22b4634c
VZ
2075 // if there is something left, it may be either a '\\' to continue
2076 // the line or the next field of the same entry
223d09f6 2077 bool entryEnded = *pc == wxT('\0'),
22b4634c
VZ
2078 nextFieldOnSameLine = FALSE;
2079 if ( !entryEnded ) {
223d09f6 2080 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
b13d92d1 2081 }
b13d92d1
VZ
2082
2083 // now see what we got
223d09f6 2084 if ( strLHS == wxT("type") ) {
b13d92d1
VZ
2085 strMimeType = strRHS;
2086 }
223d09f6 2087 else if ( strLHS == wxT("desc") ) {
b13d92d1
VZ
2088 strDesc = strRHS;
2089 }
223d09f6 2090 else if ( strLHS == wxT("exts") ) {
b13d92d1
VZ
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 ) {
22b4634c
VZ
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
b13d92d1 2104 // will be interpreted correctly.
22b4634c 2105
b13d92d1
VZ
2106 continue;
2107 }
2108 }
2109
a1d8eaf7
VZ
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)
223d09f6 2113 strExtensions.Replace(wxT(","), wxT(" "));
a1d8eaf7
VZ
2114
2115 // also deal with the leading dot
1b986aef
VZ
2116 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
2117 {
a1d8eaf7
VZ
2118 strExtensions.erase(0, 1);
2119 }
2120
8e124873 2121 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
22b4634c
VZ
2122
2123 // finished with this line
2124 pc = NULL;
b13d92d1
VZ
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() );
cc385968
VZ
2131
2132 return TRUE;
b13d92d1
VZ
2133}
2134
cc385968
VZ
2135bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
2136 bool fallback)
b13d92d1 2137{
223d09f6 2138 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName.c_str());
b13d92d1
VZ
2139
2140 wxTextFile file(strFileName);
2141 if ( !file.Open() )
cc385968 2142 return FALSE;
b13d92d1 2143
cc385968
VZ
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
b13d92d1 2147 wxArrayInt aEntryIndices;
cc385968
VZ
2148 // aLastIndices[n] is the index of last element in
2149 // m_aEntries[aEntryIndices[n]] from this file
2150 wxArrayInt aLastIndices;
b13d92d1
VZ
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
50920146 2155 const wxChar *pc = file[nLine].c_str();
b13d92d1
VZ
2156
2157 // skip whitespace
50920146 2158 while ( wxIsspace(*pc) )
b13d92d1
VZ
2159 pc++;
2160
2161 // comment or empty string?
223d09f6 2162 if ( *pc == wxT('#') || *pc == wxT('\0') )
b13d92d1
VZ
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
8fc613f1
RR
2178 bool needsterminal = FALSE,
2179 copiousoutput = FALSE;
b13d92d1
VZ
2180 wxString strType,
2181 strOpenCmd,
2182 strPrintCmd,
2183 strTest,
2184 strDesc,
2185 curField; // accumulator
2186 for ( bool cont = TRUE; cont; pc++ ) {
2187 switch ( *pc ) {
223d09f6 2188 case wxT('\\'):
b13d92d1
VZ
2189 // interpret the next character literally (notice that
2190 // backslash can be used for line continuation)
223d09f6 2191 if ( *++pc == wxT('\0') ) {
b13d92d1
VZ
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
223d09f6 2205 case wxT('\0'):
b13d92d1
VZ
2206 cont = FALSE; // end of line reached, exit the loop
2207
2208 // fall through
2209
223d09f6 2210 case wxT(';'):
b13d92d1
VZ
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;
223d09f6 2219 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
b13d92d1 2220 // we interpret "type" as "type/*"
223d09f6 2221 strType += wxT("/*");
b13d92d1
VZ
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?
223d09f6 2239 const wxChar *pEq = wxStrchr(curField, wxT('='));
b13d92d1 2240 if ( pEq != NULL ) {
223d09f6
KB
2241 wxString lhs = curField.BeforeFirst(wxT('=')),
2242 rhs = curField.AfterFirst(wxT('='));
b13d92d1
VZ
2243
2244 lhs.Trim(TRUE); // from right
2245 rhs.Trim(FALSE); // from left
2246
223d09f6 2247 if ( lhs == wxT("print") )
b13d92d1 2248 strPrintCmd = rhs;
223d09f6 2249 else if ( lhs == wxT("test") )
b13d92d1 2250 strTest = rhs;
223d09f6 2251 else if ( lhs == wxT("description") ) {
b13d92d1 2252 // it might be quoted
223d09f6
KB
2253 if ( rhs[0u] == wxT('"') &&
2254 rhs.Last() == wxT('"') ) {
b13d92d1
VZ
2255 strDesc = wxString(rhs.c_str() + 1,
2256 rhs.Len() - 2);
2257 }
2258 else {
2259 strDesc = rhs;
2260 }
2261 }
223d09f6
KB
2262 else if ( lhs == wxT("compose") ||
2263 lhs == wxT("composetyped") ||
2264 lhs == wxT("notes") ||
2265 lhs == wxT("edit") )
b13d92d1
VZ
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'
223d09f6 2276 if ( curField == wxT("needsterminal") )
b13d92d1 2277 needsterminal = TRUE;
223d09f6 2278 else if ( curField == wxT("copiousoutput") )
b13d92d1 2279 copiousoutput = TRUE;
223d09f6 2280 else if ( curField == wxT("textualnewlines") )
b13d92d1
VZ
2281 ; // ignore
2282 else
2283 ok = FALSE;
2284 }
2285
2286 if ( !ok )
2287 {
54acce90
VZ
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 }
b13d92d1
VZ
2309 }
2310 }
2311
2312 // it already has this value
2313 //currentToken = Field_Other;
2314 break;
2315
2316 default:
223d09f6 2317 wxFAIL_MSG(wxT("unknown field type in mailcap"));
b13d92d1
VZ
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
8e124873
VZ
2340 // NB: because of complications below (we must get entries priority
2341 // right), we can't use AddMailcapInfo() here, unfortunately.
b13d92d1
VZ
2342 strType.MakeLower();
2343 int nIndex = m_aTypes.Index(strType);
3c67202d 2344 if ( nIndex == wxNOT_FOUND ) {
b13d92d1
VZ
2345 // new file type
2346 m_aTypes.Add(strType);
2347
2348 m_aEntries.Add(entry);
223d09f6 2349 m_aExtensions.Add(wxT(""));
b13d92d1
VZ
2350 m_aDescriptions.Add(strDesc);
2351 }
2352 else {
cc385968
VZ
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;
b13d92d1
VZ
2371 }
2372 else {
cc385968
VZ
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 }
b13d92d1
VZ
2394 }
2395
2396 if ( !strDesc.IsEmpty() ) {
cc385968 2397 // replace the old one - what else can we do??
b13d92d1
VZ
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 }
cc385968
VZ
2408
2409 return TRUE;
b13d92d1
VZ
2410}
2411
696e1ea0 2412size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef 2413{
54acce90
VZ
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 }
1b986aef 2427
54acce90 2428 return mimetypes.GetCount();
1b986aef
VZ
2429}
2430
8e124873 2431#endif
ce4169a4
RR
2432 // OS type
2433
8e124873 2434#endif
ce4169a4 2435 // wxUSE_FILE && wxUSE_TEXTFILE
b13d92d1 2436
3d05544e
JS
2437#endif
2438 // __WIN16__