]> git.saurik.com Git - wxWidgets.git/blame - src/common/mimetype.cpp
Test for XIM support in gdk added, relevant code for window.cpp follows this
[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"
31 #include "wx/icon.h"
b13d92d1
VZ
32#endif //WX_PRECOMP
33
3d05544e
JS
34// Doesn't compile in WIN16 mode
35#ifndef __WIN16__
36
b13d92d1 37#include "wx/log.h"
ce4169a4 38#include "wx/file.h"
b13d92d1
VZ
39#include "wx/intl.h"
40#include "wx/dynarray.h"
2432b92d 41#include "wx/confbase.h"
b13d92d1
VZ
42
43#ifdef __WXMSW__
44 #include "wx/msw/registry.h"
2432b92d 45 #include "windows.h"
b13d92d1
VZ
46#else // Unix
47 #include "wx/textfile.h"
48#endif // OS
49
50#include "wx/mimetype.h"
51
52// other standard headers
53#include <ctype.h>
54
55// ----------------------------------------------------------------------------
56// private classes
57// ----------------------------------------------------------------------------
58
59// implementation classes, platform dependent
60#ifdef __WXMSW__
61
62// These classes use Windows registry to retrieve the required information.
63//
64// Keys used (not all of them are documented, so it might actually stop working
65// in futur versions of Windows...):
66// 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
67// types, each key has a string value "Extension" which gives (dot preceded)
68// extension for the files of this MIME type.
69//
70// 2. "HKCR\.ext" contains
71// a) unnamed value containing the "filetype"
72// b) value "Content Type" containing the MIME type
73//
74// 3. "HKCR\filetype" contains
75// a) unnamed value containing the description
76// b) subkey "DefaultIcon" with single unnamed value giving the icon index in
77// an icon file
78// c) shell\open\command and shell\open\print subkeys containing the commands
79// to open/print the file (the positional parameters are introduced by %1,
80// %2, ... in these strings, we change them to %s ourselves)
81
1b986aef
VZ
82// although I don't know of any official documentation which mentions this
83// location, uses it, so it isn't likely to change
84static const wxChar *MIME_DATABASE_KEY = wxT("MIME\\Database\\Content Type\\");
85
b13d92d1
VZ
86class wxFileTypeImpl
87{
88public:
89 // ctor
8e124873 90 wxFileTypeImpl() { m_info = NULL; }
b13d92d1 91
8e124873
VZ
92 // one of these Init() function must be called (ctor can't take any
93 // arguments because it's common)
94
95 // initialize us with our file type name and extension - in this case
96 // we will read all other data from the registry
97 void Init(const wxString& strFileType, const wxString& ext)
98 { m_strFileType = strFileType; m_ext = ext; }
99
100 // initialize us with a wxFileTypeInfo object - it contains all the
101 // data
102 void Init(const wxFileTypeInfo& info)
103 { m_info = &info; }
b13d92d1
VZ
104
105 // implement accessor functions
106 bool GetExtensions(wxArrayString& extensions);
107 bool GetMimeType(wxString *mimeType) const;
108 bool GetIcon(wxIcon *icon) const;
109 bool GetDescription(wxString *desc) const;
110 bool GetOpenCommand(wxString *openCmd,
8e124873 111 const wxFileType::MessageParameters& params) const;
b13d92d1 112 bool GetPrintCommand(wxString *printCmd,
8e124873 113 const wxFileType::MessageParameters& params) const;
b13d92d1
VZ
114
115private:
8e124873
VZ
116 // helper function: reads the command corresponding to the specified verb
117 // from the registry (returns an empty string if not found)
118 wxString GetCommand(const wxChar *verb) const;
119
120 // we use either m_info or read the data from the registry if m_info == NULL
121 const wxFileTypeInfo *m_info;
c61f4f6d
VZ
122 wxString m_strFileType, // may be empty
123 m_ext;
b13d92d1
VZ
124};
125
a497618a 126WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
8e124873
VZ
127#include "wx/arrimpl.cpp"
128WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
129
b13d92d1
VZ
130class wxMimeTypesManagerImpl
131{
132public:
133 // nothing to do here, we don't load any data but just go and fetch it from
134 // the registry when asked for
135 wxMimeTypesManagerImpl() { }
136
137 // implement containing class functions
138 wxFileType *GetFileTypeFromExtension(const wxString& ext);
139 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
140
696e1ea0 141 size_t EnumAllFileTypes(wxArrayString& mimetypes);
1b986aef 142
b13d92d1 143 // this are NOPs under Windows
be1023d5
VZ
144 bool ReadMailcap(const wxString& filename, bool fallback = TRUE)
145 { return TRUE; }
146 bool ReadMimeTypes(const wxString& filename)
147 { return TRUE; }
8e124873
VZ
148
149 void AddFallback(const wxFileTypeInfo& ft) { m_fallbacks.Add(ft); }
150
151private:
152 wxArrayFileTypeInfo m_fallbacks;
b13d92d1
VZ
153};
154
7c74e7fe
SC
155#elif defined( __WXMAC__ )
156
157WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
158#include "wx/arrimpl.cpp"
159WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
160
161class wxMimeTypesManagerImpl
162{
163public :
164 wxMimeTypesManagerImpl() { }
165
166 // implement containing class functions
167 wxFileType *GetFileTypeFromExtension(const wxString& ext);
168 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
169
696e1ea0 170 size_t EnumAllFileTypes(wxArrayString& mimetypes);
1b986aef 171
7c74e7fe
SC
172 // this are NOPs under MacOS
173 bool ReadMailcap(const wxString& filename, bool fallback = TRUE) { return TRUE; }
174 bool ReadMimeTypes(const wxString& filename) { return TRUE; }
175
176 void AddFallback(const wxFileTypeInfo& ft) { m_fallbacks.Add(ft); }
177
178private:
179 wxArrayFileTypeInfo m_fallbacks;
180};
181
182class wxFileTypeImpl
183{
184public:
185 // initialize us with our file type name
186 void SetFileType(const wxString& strFileType)
187 { m_strFileType = strFileType; }
188 void SetExt(const wxString& ext)
189 { m_ext = ext; }
190
191 // implement accessor functions
192 bool GetExtensions(wxArrayString& extensions);
193 bool GetMimeType(wxString *mimeType) const;
194 bool GetIcon(wxIcon *icon) const;
195 bool GetDescription(wxString *desc) const;
196 bool GetOpenCommand(wxString *openCmd,
197 const wxFileType::MessageParameters&) const
198 { return GetCommand(openCmd, "open"); }
199 bool GetPrintCommand(wxString *printCmd,
200 const wxFileType::MessageParameters&) const
201 { return GetCommand(printCmd, "print"); }
202
203private:
204 // helper function
205 bool GetCommand(wxString *command, const char *verb) const;
206
207 wxString m_strFileType, m_ext;
208};
209
b13d92d1
VZ
210#else // Unix
211
212// this class uses both mailcap and mime.types to gather information about file
213// types.
214//
215// The information about mailcap file was extracted from metamail(1) sources and
216// documentation.
217//
218// Format of mailcap file: spaces are ignored, each line is either a comment
219// (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
220// A backslash can be used to quote semicolons and newlines (and, in fact,
221// anything else including itself).
222//
223// The first field is always the MIME type in the form of type/subtype (see RFC
224// 822) where subtype may be '*' meaning "any". Following metamail, we accept
225// "type" which means the same as "type/*", although I'm not sure whether this
226// is standard.
227//
228// The second field is always the command to run. It is subject to
229// parameter/filename expansion described below.
230//
231// All the following fields are optional and may not be present at all. If
232// they're present they may appear in any order, although each of them should
233// appear only once. The optional fields are the following:
234// * notes=xxx is an uninterpreted string which is silently ignored
235// * test=xxx is the command to be used to determine whether this mailcap line
236// applies to our data or not. The RHS of this field goes through the
237// parameter/filename expansion (as the 2nd field) and the resulting string
238// is executed. The line applies only if the command succeeds, i.e. returns 0
239// exit code.
240// * print=xxx is the command to be used to print (and not view) the data of
241// this type (parameter/filename expansion is done here too)
242// * edit=xxx is the command to open/edit the data of this type
243// * needsterminal means that a new console must be created for the viewer
244// * copiousoutput means that the viewer doesn't interact with the user but
245// produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
246// good example), thus it might be a good idea to use some kind of paging
247// mechanism.
248// * textualnewlines means not to perform CR/LF translation (not honored)
249// * compose and composetyped fields are used to determine the program to be
250// called to create a new message pert in the specified format (unused).
251//
ec4768ef 252// Parameter/filename xpansion:
b13d92d1
VZ
253// * %s is replaced with the (full) file name
254// * %t is replaced with MIME type/subtype of the entry
255// * for multipart type only %n is replaced with the nnumber of parts and %F is
256// replaced by an array of (content-type, temporary file name) pairs for all
257// message parts (TODO)
258// * %{parameter} is replaced with the value of parameter taken from
259// Content-type header line of the message.
260//
261// FIXME any docs with real descriptions of these files??
262//
263// There are 2 possible formats for mime.types file, one entry per line (used
264// for global mime.types) and "expanded" format where an entry takes multiple
265// lines (used for users mime.types).
266//
267// For both formats spaces are ignored and lines starting with a '#' are
268// comments. Each record has one of two following forms:
269// a) for "brief" format:
270// <mime type> <space separated list of extensions>
ec4768ef 271// b) for "expanded" format:
b13d92d1
VZ
272// type=<mime type> \ desc="<description>" \ exts="ext"
273//
274// We try to autodetect the format of mime.types: if a non-comment line starts
275// with "type=" we assume the second format, otherwise the first one.
276
277// there may be more than one entry for one and the same mime type, to
278// choose the right one we have to run the command specified in the test
279// field on our data.
280class MailCapEntry
281{
282public:
283 // ctor
284 MailCapEntry(const wxString& openCmd,
285 const wxString& printCmd,
286 const wxString& testCmd)
287 : m_openCmd(openCmd), m_printCmd(printCmd), m_testCmd(testCmd)
288 {
289 m_next = NULL;
290 }
291
292 // accessors
293 const wxString& GetOpenCmd() const { return m_openCmd; }
294 const wxString& GetPrintCmd() const { return m_printCmd; }
295 const wxString& GetTestCmd() const { return m_testCmd; }
296
297 MailCapEntry *GetNext() const { return m_next; }
298
299 // operations
300 // prepend this element to the list
301 void Prepend(MailCapEntry *next) { m_next = next; }
cc385968
VZ
302 // insert into the list at given position
303 void Insert(MailCapEntry *next, size_t pos)
304 {
305 // FIXME slooow...
306 MailCapEntry *cur;
307 size_t n = 0;
308 for ( cur = next; cur != NULL; cur = cur->m_next, n++ ) {
309 if ( n == pos )
310 break;
311 }
312
223d09f6 313 wxASSERT_MSG( n == pos, wxT("invalid position in MailCapEntry::Insert") );
cc385968
VZ
314
315 m_next = cur->m_next;
316 cur->m_next = this;
317 }
318 // append this element to the list
b13d92d1
VZ
319 void Append(MailCapEntry *next)
320 {
223d09f6 321 wxCHECK_RET( next != NULL, wxT("Append()ing to what?") );
cc385968 322
b13d92d1
VZ
323 // FIXME slooow...
324 MailCapEntry *cur;
325 for ( cur = next; cur->m_next != NULL; cur = cur->m_next )
326 ;
327
328 cur->m_next = this;
329
223d09f6 330 wxASSERT_MSG( !m_next, wxT("Append()ing element already in the list?") );
b13d92d1
VZ
331 }
332
333private:
334 wxString m_openCmd, // command to use to open/view the file
335 m_printCmd, // print
336 m_testCmd; // only apply this entry if test yields
337 // true (i.e. the command returns 0)
338
339 MailCapEntry *m_next; // in the linked list
340};
341
342WX_DEFINE_ARRAY(MailCapEntry *, ArrayTypeEntries);
343
344class wxMimeTypesManagerImpl
345{
346friend class wxFileTypeImpl; // give it access to m_aXXX variables
347
348public:
349 // ctor loads all info into memory for quicker access later on
cc385968 350 // TODO it would be nice to load them all, but parse on demand only...
b13d92d1
VZ
351 wxMimeTypesManagerImpl();
352
353 // implement containing class functions
354 wxFileType *GetFileTypeFromExtension(const wxString& ext);
355 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
356
696e1ea0 357 size_t EnumAllFileTypes(wxArrayString& mimetypes);
1b986aef 358
cc385968
VZ
359 bool ReadMailcap(const wxString& filename, bool fallback = FALSE);
360 bool ReadMimeTypes(const wxString& filename);
b13d92d1 361
8e124873
VZ
362 void AddFallback(const wxFileTypeInfo& filetype);
363
364 // add information about the given mimetype
365 void AddMimeTypeInfo(const wxString& mimetype,
366 const wxString& extensions,
367 const wxString& description);
368 void AddMailcapInfo(const wxString& strType,
369 const wxString& strOpenCmd,
370 const wxString& strPrintCmd,
371 const wxString& strTest,
372 const wxString& strDesc);
373
b13d92d1
VZ
374 // accessors
375 // get the string containing space separated extensions for the given
376 // file type
377 wxString GetExtension(size_t index) { return m_aExtensions[index]; }
378
379private:
380 wxArrayString m_aTypes, // MIME types
381 m_aDescriptions, // descriptions (just some text)
382 m_aExtensions; // space separated list of extensions
383 ArrayTypeEntries m_aEntries; // commands and tests for this file type
384};
385
386class wxFileTypeImpl
387{
388public:
389 // initialization functions
390 void Init(wxMimeTypesManagerImpl *manager, size_t index)
391 { m_manager = manager; m_index = index; }
392
393 // accessors
394 bool GetExtensions(wxArrayString& extensions);
395 bool GetMimeType(wxString *mimeType) const
396 { *mimeType = m_manager->m_aTypes[m_index]; return TRUE; }
ac91b9d2 397 bool GetIcon(wxIcon * WXUNUSED(icon)) const
cc385968 398 { return FALSE; } // TODO maybe with Gnome/KDE integration...
b13d92d1
VZ
399 bool GetDescription(wxString *desc) const
400 { *desc = m_manager->m_aDescriptions[m_index]; return TRUE; }
401
402 bool GetOpenCommand(wxString *openCmd,
403 const wxFileType::MessageParameters& params) const
404 {
405 return GetExpandedCommand(openCmd, params, TRUE);
406 }
407
408 bool GetPrintCommand(wxString *printCmd,
409 const wxFileType::MessageParameters& params) const
410 {
411 return GetExpandedCommand(printCmd, params, FALSE);
412 }
413
414private:
415 // get the entry which passes the test (may return NULL)
416 MailCapEntry *GetEntry(const wxFileType::MessageParameters& params) const;
417
418 // choose the correct entry to use and expand the command
419 bool GetExpandedCommand(wxString *expandedCmd,
420 const wxFileType::MessageParameters& params,
421 bool open) const;
422
423 wxMimeTypesManagerImpl *m_manager;
424 size_t m_index; // in the wxMimeTypesManagerImpl arrays
425};
426
427#endif // OS type
428
8e124873
VZ
429// ============================================================================
430// common classes
431// ============================================================================
432
433// ----------------------------------------------------------------------------
434// wxFileTypeInfo
435// ----------------------------------------------------------------------------
436
437wxFileTypeInfo::wxFileTypeInfo(const char *mimeType,
438 const char *openCmd,
439 const char *printCmd,
440 const char *desc,
441 ...)
442 : m_mimeType(mimeType),
443 m_openCmd(openCmd),
444 m_printCmd(printCmd),
445 m_desc(desc)
446{
447 va_list argptr;
448 va_start(argptr, desc);
449
450 for ( ;; )
451 {
452 const char *ext = va_arg(argptr, const char *);
453 if ( !ext )
454 {
455 // NULL terminates the list
456 break;
457 }
458
459 m_exts.Add(ext);
460 }
461
462 va_end(argptr);
463}
464
b13d92d1
VZ
465// ============================================================================
466// implementation of the wrapper classes
467// ============================================================================
468
469// ----------------------------------------------------------------------------
470// wxFileType
471// ----------------------------------------------------------------------------
472
473wxString wxFileType::ExpandCommand(const wxString& command,
474 const wxFileType::MessageParameters& params)
475{
476 bool hasFilename = FALSE;
477
478 wxString str;
223d09f6
KB
479 for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
480 if ( *pc == wxT('%') ) {
b13d92d1 481 switch ( *++pc ) {
223d09f6 482 case wxT('s'):
b13d92d1
VZ
483 // '%s' expands into file name (quoted because it might
484 // contain spaces) - except if there are already quotes
341c92a8
VZ
485 // there because otherwise some programs may get confused
486 // by double double quotes
b13d92d1 487#if 0
223d09f6 488 if ( *(pc - 2) == wxT('"') )
b13d92d1
VZ
489 str << params.GetFileName();
490 else
223d09f6 491 str << wxT('"') << params.GetFileName() << wxT('"');
b13d92d1
VZ
492#endif
493 str << params.GetFileName();
494 hasFilename = TRUE;
495 break;
496
223d09f6 497 case wxT('t'):
b13d92d1
VZ
498 // '%t' expands into MIME type (quote it too just to be
499 // consistent)
223d09f6 500 str << wxT('\'') << params.GetMimeType() << wxT('\'');
b13d92d1
VZ
501 break;
502
223d09f6 503 case wxT('{'):
b13d92d1 504 {
223d09f6 505 const wxChar *pEnd = wxStrchr(pc, wxT('}'));
b13d92d1
VZ
506 if ( pEnd == NULL ) {
507 wxString mimetype;
508 wxLogWarning(_("Unmatched '{' in an entry for "
509 "mime type %s."),
510 params.GetMimeType().c_str());
223d09f6 511 str << wxT("%{");
b13d92d1
VZ
512 }
513 else {
514 wxString param(pc + 1, pEnd - pc - 1);
223d09f6 515 str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
b13d92d1
VZ
516 pc = pEnd;
517 }
518 }
519 break;
520
223d09f6
KB
521 case wxT('n'):
522 case wxT('F'):
b13d92d1
VZ
523 // TODO %n is the number of parts, %F is an array containing
524 // the names of temp files these parts were written to
525 // and their mime types.
526 break;
527
528 default:
223d09f6 529 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
b13d92d1
VZ
530 *pc, command.c_str());
531 str << *pc;
532 }
533 }
534 else {
535 str << *pc;
536 }
537 }
538
539 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
540 // the program will accept the data on stdin: so give it to it!
541 if ( !hasFilename && !str.IsEmpty() ) {
223d09f6 542 str << wxT(" < '") << params.GetFileName() << wxT('\'');
b13d92d1
VZ
543 }
544
545 return str;
546}
547
548wxFileType::wxFileType()
549{
550 m_impl = new wxFileTypeImpl;
551}
552
553wxFileType::~wxFileType()
554{
555 delete m_impl;
556}
557
558bool wxFileType::GetExtensions(wxArrayString& extensions)
559{
560 return m_impl->GetExtensions(extensions);
561}
562
563bool wxFileType::GetMimeType(wxString *mimeType) const
564{
565 return m_impl->GetMimeType(mimeType);
566}
567
568bool wxFileType::GetIcon(wxIcon *icon) const
569{
570 return m_impl->GetIcon(icon);
571}
572
573bool wxFileType::GetDescription(wxString *desc) const
574{
575 return m_impl->GetDescription(desc);
576}
577
578bool
579wxFileType::GetOpenCommand(wxString *openCmd,
580 const wxFileType::MessageParameters& params) const
581{
582 return m_impl->GetOpenCommand(openCmd, params);
583}
584
585bool
586wxFileType::GetPrintCommand(wxString *printCmd,
587 const wxFileType::MessageParameters& params) const
588{
589 return m_impl->GetPrintCommand(printCmd, params);
590}
591
592// ----------------------------------------------------------------------------
593// wxMimeTypesManager
594// ----------------------------------------------------------------------------
595
a5a19b83
VZ
596bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
597 const wxString& wildcard)
598{
223d09f6
KB
599 wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
600 wxT("first MIME type can't contain wildcards") );
a5a19b83
VZ
601
602 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
223d09f6 603 if ( wildcard.BeforeFirst(wxT('/')).IsSameAs(mimeType.BeforeFirst(wxT('/')), FALSE) )
a5a19b83 604 {
223d09f6 605 wxString strSubtype = wildcard.AfterFirst(wxT('/'));
a5a19b83 606
223d09f6
KB
607 if ( strSubtype == wxT("*") ||
608 strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), FALSE) )
a5a19b83
VZ
609 {
610 // matches (either exactly or it's a wildcard)
611 return TRUE;
612 }
613 }
614
615 return FALSE;
616}
617
b13d92d1
VZ
618wxMimeTypesManager::wxMimeTypesManager()
619{
620 m_impl = new wxMimeTypesManagerImpl;
621}
622
623wxMimeTypesManager::~wxMimeTypesManager()
624{
625 delete m_impl;
626}
627
628wxFileType *
629wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
630{
631 return m_impl->GetFileTypeFromExtension(ext);
632}
633
634wxFileType *
635wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
636{
637 return m_impl->GetFileTypeFromMimeType(mimeType);
638}
639
cc385968 640bool wxMimeTypesManager::ReadMailcap(const wxString& filename, bool fallback)
22b4634c 641{
cc385968 642 return m_impl->ReadMailcap(filename, fallback);
22b4634c
VZ
643}
644
cc385968 645bool wxMimeTypesManager::ReadMimeTypes(const wxString& filename)
22b4634c 646{
cc385968 647 return m_impl->ReadMimeTypes(filename);
22b4634c
VZ
648}
649
8e124873
VZ
650void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
651{
652 for ( const wxFileTypeInfo *ft = filetypes; ft->IsValid(); ft++ ) {
653 m_impl->AddFallback(*ft);
654 }
655}
656
696e1ea0 657size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef 658{
696e1ea0 659 return m_impl->EnumAllFileTypes(mimetypes);
1b986aef
VZ
660}
661
b13d92d1
VZ
662// ============================================================================
663// real (OS specific) implementation
664// ============================================================================
665
666#ifdef __WXMSW__
667
8e124873 668wxString wxFileTypeImpl::GetCommand(const wxChar *verb) const
b13d92d1
VZ
669{
670 // suppress possible error messages
671 wxLogNull nolog;
672 wxString strKey;
b13d92d1 673
c61f4f6d
VZ
674 if ( wxRegKey(wxRegKey::HKCR, m_ext + _T("\\shell")).Exists() )
675 strKey = m_ext;
676 if ( wxRegKey(wxRegKey::HKCR, m_strFileType + _T("\\shell")).Exists() )
677 strKey = m_strFileType;
678
679 if ( !strKey )
680 {
681 // no info
682 return wxEmptyString;
683 }
684
685 strKey << wxT("\\shell\\") << verb << wxT("\\command");
686 wxRegKey key(wxRegKey::HKCR, strKey);
8e124873 687 wxString command;
b13d92d1
VZ
688 if ( key.Open() ) {
689 // it's the default value of the key
223d09f6 690 if ( key.QueryValue(wxT(""), command) ) {
b13d92d1 691 // transform it from '%1' to '%s' style format string
8e124873 692
cc385968
VZ
693 // NB: we don't make any attempt to verify that the string is valid,
694 // i.e. doesn't contain %2, or second %1 or .... But we do make
695 // sure that we return a string with _exactly_ one '%s'!
8e124873
VZ
696 bool foundFilename = FALSE;
697 size_t len = command.Len();
698 for ( size_t n = 0; (n < len) && !foundFilename; n++ ) {
223d09f6
KB
699 if ( command[n] == wxT('%') &&
700 (n + 1 < len) && command[n + 1] == wxT('1') ) {
b13d92d1 701 // replace it with '%s'
223d09f6 702 command[n + 1] = wxT('s');
b13d92d1 703
8e124873 704 foundFilename = TRUE;
b13d92d1
VZ
705 }
706 }
707
8e124873
VZ
708 if ( !foundFilename ) {
709 // we didn't find any '%1'!
710 // HACK: append the filename at the end, hope that it will do
223d09f6 711 command << wxT(" %s");
8e124873 712 }
b13d92d1
VZ
713 }
714 }
c61f4f6d 715 //else: no such file type or no value, will return empty string
b13d92d1 716
8e124873
VZ
717 return command;
718}
719
720bool
721wxFileTypeImpl::GetOpenCommand(wxString *openCmd,
722 const wxFileType::MessageParameters& params)
723 const
724{
725 wxString cmd;
726 if ( m_info ) {
727 cmd = m_info->GetOpenCommand();
728 }
729 else {
223d09f6 730 cmd = GetCommand(wxT("open"));
8e124873
VZ
731 }
732
733 *openCmd = wxFileType::ExpandCommand(cmd, params);
734
735 return !openCmd->IsEmpty();
736}
737
738bool
739wxFileTypeImpl::GetPrintCommand(wxString *printCmd,
740 const wxFileType::MessageParameters& params)
741 const
742{
743 wxString cmd;
744 if ( m_info ) {
745 cmd = m_info->GetPrintCommand();
746 }
747 else {
223d09f6 748 cmd = GetCommand(wxT("print"));
8e124873
VZ
749 }
750
751 *printCmd = wxFileType::ExpandCommand(cmd, params);
752
753 return !printCmd->IsEmpty();
b13d92d1
VZ
754}
755
cc385968 756// TODO this function is half implemented
b13d92d1
VZ
757bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
758{
8e124873
VZ
759 if ( m_info ) {
760 extensions = m_info->GetExtensions();
761
762 return TRUE;
763 }
764 else if ( m_ext.IsEmpty() ) {
b13d92d1
VZ
765 // the only way to get the list of extensions from the file type is to
766 // scan through all extensions in the registry - too slow...
767 return FALSE;
768 }
769 else {
770 extensions.Empty();
771 extensions.Add(m_ext);
772
773 // it's a lie too, we don't return _all_ extensions...
774 return TRUE;
775 }
776}
777
778bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
779{
8e124873
VZ
780 if ( m_info ) {
781 // we already have it
782 *mimeType = m_info->GetMimeType();
783
784 return TRUE;
785 }
786
b13d92d1
VZ
787 // suppress possible error messages
788 wxLogNull nolog;
c61f4f6d 789 wxRegKey key(wxRegKey::HKCR, wxT(".") + m_ext);
223d09f6 790 if ( key.Open() && key.QueryValue(wxT("Content Type"), *mimeType) ) {
b13d92d1
VZ
791 return TRUE;
792 }
793 else {
794 return FALSE;
795 }
796}
797
798bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
799{
b568d04f 800#if wxUSE_GUI
8e124873
VZ
801 if ( m_info ) {
802 // we don't have icons in the fallback resources
803 return FALSE;
804 }
805
b13d92d1 806 wxString strIconKey;
223d09f6 807 strIconKey << m_strFileType << wxT("\\DefaultIcon");
b13d92d1
VZ
808
809 // suppress possible error messages
810 wxLogNull nolog;
811 wxRegKey key(wxRegKey::HKCR, strIconKey);
812
813 if ( key.Open() ) {
814 wxString strIcon;
815 // it's the default value of the key
223d09f6 816 if ( key.QueryValue(wxT(""), strIcon) ) {
b13d92d1
VZ
817 // the format is the following: <full path to file>, <icon index>
818 // NB: icon index may be negative as well as positive and the full
819 // path may contain the environment variables inside '%'
223d09f6
KB
820 wxString strFullPath = strIcon.BeforeLast(wxT(',')),
821 strIndex = strIcon.AfterLast(wxT(','));
b13d92d1 822
3c67202d
VZ
823 // index may be omitted, in which case BeforeLast(',') is empty and
824 // AfterLast(',') is the whole string
b13d92d1
VZ
825 if ( strFullPath.IsEmpty() ) {
826 strFullPath = strIndex;
223d09f6 827 strIndex = wxT("0");
b13d92d1
VZ
828 }
829
830 wxString strExpPath = wxExpandEnvVars(strFullPath);
4de6207a 831 int nIndex = wxAtoi(strIndex);
b13d92d1
VZ
832
833 HICON hIcon = ExtractIcon(GetModuleHandle(NULL), strExpPath, nIndex);
834 switch ( (int)hIcon ) {
835 case 0: // means no icons were found
836 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
223d09f6 837 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
b13d92d1
VZ
838 key.GetName().c_str());
839 break;
840
841 default:
842 icon->SetHICON((WXHICON)hIcon);
843 return TRUE;
844 }
845 }
846 }
847
848 // no such file type or no value or incorrect icon entry
b568d04f
VZ
849#endif // wxUSE_GUI
850
b13d92d1
VZ
851 return FALSE;
852}
853
854bool wxFileTypeImpl::GetDescription(wxString *desc) const
855{
8e124873
VZ
856 if ( m_info ) {
857 // we already have it
858 *desc = m_info->GetDescription();
859
860 return TRUE;
861 }
862
b13d92d1
VZ
863 // suppress possible error messages
864 wxLogNull nolog;
865 wxRegKey key(wxRegKey::HKCR, m_strFileType);
866
867 if ( key.Open() ) {
868 // it's the default value of the key
223d09f6 869 if ( key.QueryValue(wxT(""), *desc) ) {
b13d92d1
VZ
870 return TRUE;
871 }
872 }
873
874 return FALSE;
875}
876
877// extension -> file type
878wxFileType *
879wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
880{
881 // add the leading point if necessary
882 wxString str;
223d09f6
KB
883 if ( ext[0u] != wxT('.') ) {
884 str = wxT('.');
b13d92d1
VZ
885 }
886 str << ext;
887
888 // suppress possible error messages
889 wxLogNull nolog;
890
c61f4f6d
VZ
891 bool knownExtension = FALSE;
892
b13d92d1
VZ
893 wxString strFileType;
894 wxRegKey key(wxRegKey::HKCR, str);
895 if ( key.Open() ) {
896 // it's the default value of the key
223d09f6 897 if ( key.QueryValue(wxT(""), strFileType) ) {
b13d92d1
VZ
898 // create the new wxFileType object
899 wxFileType *fileType = new wxFileType;
8e124873
VZ
900 fileType->m_impl->Init(strFileType, ext);
901
902 return fileType;
903 }
c61f4f6d
VZ
904 else {
905 // this extension doesn't have a filetype, but it's known to the
906 // system and may be has some other useful keys (open command or
907 // content-type), so still return a file type object for it
908 knownExtension = TRUE;
909 }
8e124873
VZ
910 }
911
912 // check the fallbacks
913 // TODO linear search is potentially slow, perhaps we should use a sorted
914 // array?
915 size_t count = m_fallbacks.GetCount();
916 for ( size_t n = 0; n < count; n++ ) {
917 if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
918 wxFileType *fileType = new wxFileType;
919 fileType->m_impl->Init(m_fallbacks[n]);
b13d92d1
VZ
920
921 return fileType;
922 }
923 }
924
c61f4f6d
VZ
925 if ( knownExtension )
926 {
927 wxFileType *fileType = new wxFileType;
928 fileType->m_impl->Init(wxEmptyString, ext);
929
930 return fileType;
931 }
932 else
933 {
934 // unknown extension
935 return NULL;
936 }
b13d92d1
VZ
937}
938
939// MIME type -> extension -> file type
940wxFileType *
941wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
942{
1b986aef 943 wxString strKey = MIME_DATABASE_KEY;
b13d92d1
VZ
944 strKey << mimeType;
945
946 // suppress possible error messages
947 wxLogNull nolog;
948
949 wxString ext;
950 wxRegKey key(wxRegKey::HKCR, strKey);
951 if ( key.Open() ) {
223d09f6 952 if ( key.QueryValue(wxT("Extension"), ext) ) {
b13d92d1
VZ
953 return GetFileTypeFromExtension(ext);
954 }
955 }
956
8e124873
VZ
957 // check the fallbacks
958 // TODO linear search is potentially slow, perhaps we should use a sorted
959 // array?
960 size_t count = m_fallbacks.GetCount();
961 for ( size_t n = 0; n < count; n++ ) {
962 if ( wxMimeTypesManager::IsOfType(mimeType,
963 m_fallbacks[n].GetMimeType()) ) {
964 wxFileType *fileType = new wxFileType;
965 fileType->m_impl->Init(m_fallbacks[n]);
966
967 return fileType;
968 }
969 }
970
b13d92d1
VZ
971 // unknown MIME type
972 return NULL;
973}
974
696e1ea0 975size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef
VZ
976{
977 // enumerate all keys under MIME_DATABASE_KEY
978 wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
7c74e7fe 979
696e1ea0
VZ
980 wxString type;
981 long cookie;
982 bool cont = key.GetFirstKey(type, cookie);
983 while ( cont )
984 {
985 mimetypes.Add(type);
986
987 cont = key.GetNextKey(type, cookie);
988 }
989
990 return mimetypes.GetCount();
1b986aef
VZ
991}
992
993#elif defined ( __WXMAC__ )
7c74e7fe
SC
994
995bool wxFileTypeImpl::GetCommand(wxString *command, const char *verb) const
996{
997 return FALSE;
998}
999
1000// @@ this function is half implemented
1001bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1002{
1003 return FALSE;
1004}
1005
1006bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
1007{
1b986aef
VZ
1008 if ( m_strFileType.Length() > 0 )
1009 {
1010 *mimeType = m_strFileType ;
1011 return TRUE ;
1012 }
1013 else
7c74e7fe
SC
1014 return FALSE;
1015}
1016
1017bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
1018{
1019 // no such file type or no value or incorrect icon entry
1020 return FALSE;
1021}
1022
1023bool wxFileTypeImpl::GetDescription(wxString *desc) const
1024{
1025 return FALSE;
1026}
1027
1028// extension -> file type
1029wxFileType *
1030wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& e)
1031{
1b986aef
VZ
1032 wxString ext = e ;
1033 ext = ext.Lower() ;
1034 if ( ext == "txt" )
1035 {
1036 wxFileType *fileType = new wxFileType;
1037 fileType->m_impl->SetFileType("text/text");
1038 fileType->m_impl->SetExt(ext);
1039 return fileType;
1040 }
1041 else if ( ext == "htm" || ext == "html" )
1042 {
1043 wxFileType *fileType = new wxFileType;
1044 fileType->m_impl->SetFileType("text/html");
1045 fileType->m_impl->SetExt(ext);
1046 return fileType;
1047 }
1048 else if ( ext == "gif" )
1049 {
1050 wxFileType *fileType = new wxFileType;
1051 fileType->m_impl->SetFileType("image/gif");
1052 fileType->m_impl->SetExt(ext);
1053 return fileType;
1054 }
1055 else if ( ext == "png" )
1056 {
1057 wxFileType *fileType = new wxFileType;
1058 fileType->m_impl->SetFileType("image/png");
1059 fileType->m_impl->SetExt(ext);
1060 return fileType;
1061 }
1062 else if ( ext == "jpg" || ext == "jpeg" )
1063 {
1064 wxFileType *fileType = new wxFileType;
1065 fileType->m_impl->SetFileType("image/jpeg");
1066 fileType->m_impl->SetExt(ext);
1067 return fileType;
1068 }
1069 else if ( ext == "bmp" )
1070 {
1071 wxFileType *fileType = new wxFileType;
1072 fileType->m_impl->SetFileType("image/bmp");
1073 fileType->m_impl->SetExt(ext);
1074 return fileType;
1075 }
1076 else if ( ext == "tif" || ext == "tiff" )
1077 {
1078 wxFileType *fileType = new wxFileType;
1079 fileType->m_impl->SetFileType("image/tiff");
1080 fileType->m_impl->SetExt(ext);
1081 return fileType;
1082 }
1083 else if ( ext == "xpm" )
1084 {
1085 wxFileType *fileType = new wxFileType;
1086 fileType->m_impl->SetFileType("image/xpm");
1087 fileType->m_impl->SetExt(ext);
1088 return fileType;
1089 }
1090 else if ( ext == "xbm" )
1091 {
1092 wxFileType *fileType = new wxFileType;
1093 fileType->m_impl->SetFileType("image/xbm");
1094 fileType->m_impl->SetExt(ext);
1095 return fileType;
1096 }
1097
1098 // unknown extension
1099 return NULL;
7c74e7fe
SC
1100}
1101
1102// MIME type -> extension -> file type
1103wxFileType *
1104wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1105{
1106 return NULL;
1107}
1b986aef 1108
696e1ea0 1109size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef
VZ
1110{
1111 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1112
1113 return 0;
1114}
1115
b13d92d1
VZ
1116#else // Unix
1117
1118MailCapEntry *
1119wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
1120{
1121 wxString command;
1122 MailCapEntry *entry = m_manager->m_aEntries[m_index];
1123 while ( entry != NULL ) {
cc385968 1124 // notice that an empty command would always succeed (it's ok)
b13d92d1
VZ
1125 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
1126
50920146 1127 if ( command.IsEmpty() || (wxSystem(command) == 0) ) {
b13d92d1 1128 // ok, passed
223d09f6 1129 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
b13d92d1
VZ
1130 command.c_str(), params.GetMimeType().c_str());
1131 break;
1132 }
1133 else {
223d09f6 1134 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
b13d92d1
VZ
1135 command.c_str(), params.GetMimeType().c_str());
1136 }
1137
1138 entry = entry->GetNext();
1139 }
1140
1141 return entry;
1142}
1143
1144bool
1145wxFileTypeImpl::GetExpandedCommand(wxString *expandedCmd,
1146 const wxFileType::MessageParameters& params,
1147 bool open) const
1148{
1149 MailCapEntry *entry = GetEntry(params);
1150 if ( entry == NULL ) {
1151 // all tests failed...
1152 return FALSE;
1153 }
1154
1155 wxString cmd = open ? entry->GetOpenCmd() : entry->GetPrintCmd();
1156 if ( cmd.IsEmpty() ) {
1157 // may happen, especially for "print"
1158 return FALSE;
1159 }
1160
1161 *expandedCmd = wxFileType::ExpandCommand(cmd, params);
1162 return TRUE;
1163}
1164
1165bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1166{
1167 wxString strExtensions = m_manager->GetExtension(m_index);
1168 extensions.Empty();
1169
1170 // one extension in the space or comma delimitid list
1171 wxString strExt;
50920146 1172 for ( const wxChar *p = strExtensions; ; p++ ) {
223d09f6 1173 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
b13d92d1
VZ
1174 if ( !strExt.IsEmpty() ) {
1175 extensions.Add(strExt);
1176 strExt.Empty();
1177 }
1178 //else: repeated spaces (shouldn't happen, but it's not that
1179 // important if it does happen)
1180
223d09f6 1181 if ( *p == wxT('\0') )
b13d92d1
VZ
1182 break;
1183 }
223d09f6 1184 else if ( *p == wxT('.') ) {
b13d92d1
VZ
1185 // remove the dot from extension (but only if it's the first char)
1186 if ( !strExt.IsEmpty() ) {
223d09f6 1187 strExt += wxT('.');
b13d92d1
VZ
1188 }
1189 //else: no, don't append it
1190 }
1191 else {
1192 strExt += *p;
1193 }
1194 }
1195
1196 return TRUE;
1197}
1198
1199// read system and user mailcaps (TODO implement mime.types support)
1200wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1201{
1202 // directories where we look for mailcap and mime.types by default
1203 // (taken from metamail(1) sources)
50920146 1204 static const wxChar *aStandardLocations[] =
b13d92d1 1205 {
223d09f6
KB
1206 wxT("/etc"),
1207 wxT("/usr/etc"),
1208 wxT("/usr/local/etc"),
1209 wxT("/etc/mail"),
1210 wxT("/usr/public/lib")
b13d92d1
VZ
1211 };
1212
1213 // first read the system wide file(s)
1214 for ( size_t n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
1215 wxString dir = aStandardLocations[n];
1216
223d09f6 1217 wxString file = dir + wxT("/mailcap");
b13d92d1
VZ
1218 if ( wxFile::Exists(file) ) {
1219 ReadMailcap(file);
1220 }
1221
223d09f6 1222 file = dir + wxT("/mime.types");
b13d92d1
VZ
1223 if ( wxFile::Exists(file) ) {
1224 ReadMimeTypes(file);
1225 }
1226 }
1227
223d09f6 1228 wxString strHome = wxGetenv(wxT("HOME"));
b13d92d1
VZ
1229
1230 // and now the users mailcap
223d09f6 1231 wxString strUserMailcap = strHome + wxT("/.mailcap");
b13d92d1
VZ
1232 if ( wxFile::Exists(strUserMailcap) ) {
1233 ReadMailcap(strUserMailcap);
1234 }
1235
1236 // read the users mime.types
223d09f6 1237 wxString strUserMimeTypes = strHome + wxT("/.mime.types");
b13d92d1
VZ
1238 if ( wxFile::Exists(strUserMimeTypes) ) {
1239 ReadMimeTypes(strUserMimeTypes);
1240 }
1241}
1242
1243wxFileType *
1244wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1245{
1ee17e1c
VZ
1246 size_t count = m_aExtensions.GetCount();
1247 for ( size_t n = 0; n < count; n++ ) {
1248 wxString extensions = m_aExtensions[n];
1249 while ( !extensions.IsEmpty() ) {
223d09f6
KB
1250 wxString field = extensions.BeforeFirst(wxT(' '));
1251 extensions = extensions.AfterFirst(wxT(' '));
1ee17e1c
VZ
1252
1253 // consider extensions as not being case-sensitive
ec4768ef 1254 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
1ee17e1c
VZ
1255 // found
1256 wxFileType *fileType = new wxFileType;
1257 fileType->m_impl->Init(this, n);
ec4768ef 1258
1ee17e1c
VZ
1259 return fileType;
1260 }
1261 }
1262 }
b13d92d1 1263
1ee17e1c 1264 // not found
b13d92d1
VZ
1265 return NULL;
1266}
1267
1268wxFileType *
1269wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1270{
1271 // mime types are not case-sensitive
1272 wxString mimetype(mimeType);
1273 mimetype.MakeLower();
1274
1275 // first look for an exact match
1276 int index = m_aTypes.Index(mimetype);
3c67202d 1277 if ( index == wxNOT_FOUND ) {
b13d92d1 1278 // then try to find "text/*" as match for "text/plain" (for example)
3c67202d
VZ
1279 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1280 // the whole string - ok.
223d09f6 1281 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
b13d92d1
VZ
1282
1283 size_t nCount = m_aTypes.Count();
1284 for ( size_t n = 0; n < nCount; n++ ) {
223d09f6
KB
1285 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
1286 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
b13d92d1
VZ
1287 index = n;
1288 break;
1289 }
1290 }
1291 }
1292
3c67202d 1293 if ( index != wxNOT_FOUND ) {
b13d92d1
VZ
1294 wxFileType *fileType = new wxFileType;
1295 fileType->m_impl->Init(this, index);
1296
1297 return fileType;
1298 }
1299 else {
1300 // not found...
1301 return NULL;
1302 }
1303}
1304
8e124873
VZ
1305void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
1306{
3f1aaa16 1307 wxString extensions;
8e124873
VZ
1308 const wxArrayString& exts = filetype.GetExtensions();
1309 size_t nExts = exts.GetCount();
1310 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
1311 if ( nExt > 0 ) {
223d09f6 1312 extensions += wxT(' ');
8e124873
VZ
1313 }
1314 extensions += exts[nExt];
1315 }
1316
1317 AddMimeTypeInfo(filetype.GetMimeType(),
1318 extensions,
1319 filetype.GetDescription());
1320
1321 AddMailcapInfo(filetype.GetMimeType(),
1322 filetype.GetOpenCommand(),
1323 filetype.GetPrintCommand(),
223d09f6 1324 wxT(""),
8e124873
VZ
1325 filetype.GetDescription());
1326}
1327
1328void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
1329 const wxString& strExtensions,
1330 const wxString& strDesc)
1331{
1332 int index = m_aTypes.Index(strMimeType);
1333 if ( index == wxNOT_FOUND ) {
1334 // add a new entry
1335 m_aTypes.Add(strMimeType);
1336 m_aEntries.Add(NULL);
1337 m_aExtensions.Add(strExtensions);
1338 m_aDescriptions.Add(strDesc);
1339 }
1340 else {
1341 // modify an existing one
1342 if ( !strDesc.IsEmpty() ) {
1343 m_aDescriptions[index] = strDesc; // replace old value
1344 }
c15d098c 1345 m_aExtensions[index] += ' ' + strExtensions;
8e124873
VZ
1346 }
1347}
1348
1349void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
1350 const wxString& strOpenCmd,
1351 const wxString& strPrintCmd,
1352 const wxString& strTest,
1353 const wxString& strDesc)
1354{
1355 MailCapEntry *entry = new MailCapEntry(strOpenCmd, strPrintCmd, strTest);
1356
1357 int nIndex = m_aTypes.Index(strType);
1358 if ( nIndex == wxNOT_FOUND ) {
1359 // new file type
1360 m_aTypes.Add(strType);
1361
1362 m_aEntries.Add(entry);
223d09f6 1363 m_aExtensions.Add(wxT(""));
8e124873
VZ
1364 m_aDescriptions.Add(strDesc);
1365 }
1366 else {
1367 // always append the entry in the tail of the list - info added with
1368 // this function can only come from AddFallbacks()
1369 MailCapEntry *entryOld = m_aEntries[nIndex];
1370 if ( entryOld )
1371 entry->Append(entryOld);
1372 else
1373 m_aEntries[nIndex] = entry;
1374 }
1375}
1376
cc385968 1377bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
b13d92d1 1378{
223d09f6 1379 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName.c_str());
b13d92d1
VZ
1380
1381 wxTextFile file(strFileName);
1382 if ( !file.Open() )
cc385968 1383 return FALSE;
b13d92d1
VZ
1384
1385 // the information we extract
1386 wxString strMimeType, strDesc, strExtensions;
1387
1388 size_t nLineCount = file.GetLineCount();
50920146 1389 const wxChar *pc = NULL;
b13d92d1 1390 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
22b4634c
VZ
1391 if ( pc == NULL ) {
1392 // now we're at the start of the line
1393 pc = file[nLine].c_str();
1394 }
1395 else {
1396 // we didn't finish with the previous line yet
1397 nLine--;
1398 }
b13d92d1
VZ
1399
1400 // skip whitespace
50920146 1401 while ( wxIsspace(*pc) )
b13d92d1
VZ
1402 pc++;
1403
1404 // comment?
223d09f6 1405 if ( *pc == wxT('#') ) {
22b4634c
VZ
1406 // skip the whole line
1407 pc = NULL;
b13d92d1 1408 continue;
22b4634c 1409 }
b13d92d1
VZ
1410
1411 // detect file format
223d09f6 1412 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
b13d92d1
VZ
1413 if ( pEqualSign == NULL ) {
1414 // brief format
1415 // ------------
1416
1417 // first field is mime type
223d09f6 1418 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
b13d92d1
VZ
1419 strMimeType += *pc;
1420 }
1421
1422 // skip whitespace
50920146 1423 while ( wxIsspace(*pc) )
b13d92d1
VZ
1424 pc++;
1425
1426 // take all the rest of the string
1427 strExtensions = pc;
1428
1429 // no description...
1430 strDesc.Empty();
1431 }
1432 else {
1433 // expanded format
1434 // ---------------
1435
1436 // the string on the left of '=' is the field name
1437 wxString strLHS(pc, pEqualSign - pc);
1438
1439 // eat whitespace
50920146 1440 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
b13d92d1
VZ
1441 ;
1442
50920146 1443 const wxChar *pEnd;
223d09f6 1444 if ( *pc == wxT('"') ) {
b13d92d1 1445 // the string is quoted and ends at the matching quote
223d09f6 1446 pEnd = wxStrchr(++pc, wxT('"'));
b13d92d1
VZ
1447 if ( pEnd == NULL ) {
1448 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1449 "quoted string."),
1450 strFileName.c_str(), nLine + 1);
1451 }
1452 }
1453 else {
22b4634c 1454 // unquoted string ends at the first space
50920146 1455 for ( pEnd = pc; !wxIsspace(*pEnd); pEnd++ )
b13d92d1
VZ
1456 ;
1457 }
1458
1459 // now we have the RHS (field value)
1460 wxString strRHS(pc, pEnd - pc);
1461
22b4634c 1462 // check what follows this entry
223d09f6 1463 if ( *pEnd == wxT('"') ) {
b13d92d1
VZ
1464 // skip this quote
1465 pEnd++;
1466 }
1467
50920146 1468 for ( pc = pEnd; wxIsspace(*pc); pc++ )
b13d92d1
VZ
1469 ;
1470
22b4634c
VZ
1471 // if there is something left, it may be either a '\\' to continue
1472 // the line or the next field of the same entry
223d09f6 1473 bool entryEnded = *pc == wxT('\0'),
22b4634c
VZ
1474 nextFieldOnSameLine = FALSE;
1475 if ( !entryEnded ) {
223d09f6 1476 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
b13d92d1 1477 }
b13d92d1
VZ
1478
1479 // now see what we got
223d09f6 1480 if ( strLHS == wxT("type") ) {
b13d92d1
VZ
1481 strMimeType = strRHS;
1482 }
223d09f6 1483 else if ( strLHS == wxT("desc") ) {
b13d92d1
VZ
1484 strDesc = strRHS;
1485 }
223d09f6 1486 else if ( strLHS == wxT("exts") ) {
b13d92d1
VZ
1487 strExtensions = strRHS;
1488 }
1489 else {
1490 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1491 strFileName.c_str(), nLine + 1, strLHS.c_str());
1492 }
1493
1494 if ( !entryEnded ) {
22b4634c
VZ
1495 if ( !nextFieldOnSameLine )
1496 pc = NULL;
1497 //else: don't reset it
1498
1499 // as we don't reset strMimeType, the next field in this entry
b13d92d1 1500 // will be interpreted correctly.
22b4634c 1501
b13d92d1
VZ
1502 continue;
1503 }
1504 }
1505
a1d8eaf7
VZ
1506 // although it doesn't seem to be covered by RFCs, some programs
1507 // (notably Netscape) create their entries with several comma
1508 // separated extensions (RFC mention the spaces only)
223d09f6 1509 strExtensions.Replace(wxT(","), wxT(" "));
a1d8eaf7
VZ
1510
1511 // also deal with the leading dot
1b986aef
VZ
1512 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
1513 {
a1d8eaf7
VZ
1514 strExtensions.erase(0, 1);
1515 }
1516
8e124873 1517 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
22b4634c
VZ
1518
1519 // finished with this line
1520 pc = NULL;
b13d92d1
VZ
1521 }
1522
1523 // check our data integriry
1524 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1525 m_aTypes.Count() == m_aExtensions.Count() &&
1526 m_aTypes.Count() == m_aDescriptions.Count() );
cc385968
VZ
1527
1528 return TRUE;
b13d92d1
VZ
1529}
1530
cc385968
VZ
1531bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
1532 bool fallback)
b13d92d1 1533{
223d09f6 1534 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName.c_str());
b13d92d1
VZ
1535
1536 wxTextFile file(strFileName);
1537 if ( !file.Open() )
cc385968 1538 return FALSE;
b13d92d1 1539
cc385968
VZ
1540 // see the comments near the end of function for the reason we need these
1541 // variables (search for the next occurence of them)
1542 // indices of MIME types (in m_aTypes) we already found in this file
b13d92d1 1543 wxArrayInt aEntryIndices;
cc385968
VZ
1544 // aLastIndices[n] is the index of last element in
1545 // m_aEntries[aEntryIndices[n]] from this file
1546 wxArrayInt aLastIndices;
b13d92d1
VZ
1547
1548 size_t nLineCount = file.GetLineCount();
1549 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1550 // now we're at the start of the line
50920146 1551 const wxChar *pc = file[nLine].c_str();
b13d92d1
VZ
1552
1553 // skip whitespace
50920146 1554 while ( wxIsspace(*pc) )
b13d92d1
VZ
1555 pc++;
1556
1557 // comment or empty string?
223d09f6 1558 if ( *pc == wxT('#') || *pc == wxT('\0') )
b13d92d1
VZ
1559 continue;
1560
1561 // no, do parse
1562
1563 // what field are we currently in? The first 2 are fixed and there may
1564 // be an arbitrary number of other fields -- currently, we are not
1565 // interested in any of them, but we should parse them as well...
1566 enum
1567 {
1568 Field_Type,
1569 Field_OpenCmd,
1570 Field_Other
1571 } currentToken = Field_Type;
1572
1573 // the flags and field values on the current line
8fc613f1
RR
1574 bool needsterminal = FALSE,
1575 copiousoutput = FALSE;
b13d92d1
VZ
1576 wxString strType,
1577 strOpenCmd,
1578 strPrintCmd,
1579 strTest,
1580 strDesc,
1581 curField; // accumulator
1582 for ( bool cont = TRUE; cont; pc++ ) {
1583 switch ( *pc ) {
223d09f6 1584 case wxT('\\'):
b13d92d1
VZ
1585 // interpret the next character literally (notice that
1586 // backslash can be used for line continuation)
223d09f6 1587 if ( *++pc == wxT('\0') ) {
b13d92d1
VZ
1588 // fetch the next line.
1589
1590 // pc currently points to nowhere, but after the next
1591 // pc++ in the for line it will point to the beginning
1592 // of the next line in the file
1593 pc = file[++nLine].c_str() - 1;
1594 }
1595 else {
1596 // just a normal character
1597 curField += *pc;
1598 }
1599 break;
1600
223d09f6 1601 case wxT('\0'):
b13d92d1
VZ
1602 cont = FALSE; // end of line reached, exit the loop
1603
1604 // fall through
1605
223d09f6 1606 case wxT(';'):
b13d92d1
VZ
1607 // store this field and start looking for the next one
1608
1609 // trim whitespaces from both sides
1610 curField.Trim(TRUE).Trim(FALSE);
1611
1612 switch ( currentToken ) {
1613 case Field_Type:
1614 strType = curField;
223d09f6 1615 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
b13d92d1 1616 // we interpret "type" as "type/*"
223d09f6 1617 strType += wxT("/*");
b13d92d1
VZ
1618 }
1619
1620 currentToken = Field_OpenCmd;
1621 break;
1622
1623 case Field_OpenCmd:
1624 strOpenCmd = curField;
1625
1626 currentToken = Field_Other;
1627 break;
1628
1629 case Field_Other:
1630 {
1631 // "good" mailcap entry?
1632 bool ok = TRUE;
1633
1634 // is this something of the form foo=bar?
223d09f6 1635 const wxChar *pEq = wxStrchr(curField, wxT('='));
b13d92d1 1636 if ( pEq != NULL ) {
223d09f6
KB
1637 wxString lhs = curField.BeforeFirst(wxT('=')),
1638 rhs = curField.AfterFirst(wxT('='));
b13d92d1
VZ
1639
1640 lhs.Trim(TRUE); // from right
1641 rhs.Trim(FALSE); // from left
1642
223d09f6 1643 if ( lhs == wxT("print") )
b13d92d1 1644 strPrintCmd = rhs;
223d09f6 1645 else if ( lhs == wxT("test") )
b13d92d1 1646 strTest = rhs;
223d09f6 1647 else if ( lhs == wxT("description") ) {
b13d92d1 1648 // it might be quoted
223d09f6
KB
1649 if ( rhs[0u] == wxT('"') &&
1650 rhs.Last() == wxT('"') ) {
b13d92d1
VZ
1651 strDesc = wxString(rhs.c_str() + 1,
1652 rhs.Len() - 2);
1653 }
1654 else {
1655 strDesc = rhs;
1656 }
1657 }
223d09f6
KB
1658 else if ( lhs == wxT("compose") ||
1659 lhs == wxT("composetyped") ||
1660 lhs == wxT("notes") ||
1661 lhs == wxT("edit") )
b13d92d1
VZ
1662 ; // ignore
1663 else
1664 ok = FALSE;
1665
1666 }
1667 else {
1668 // no, it's a simple flag
1669 // TODO support the flags:
1670 // 1. create an xterm for 'needsterminal'
1671 // 2. append "| $PAGER" for 'copiousoutput'
223d09f6 1672 if ( curField == wxT("needsterminal") )
b13d92d1 1673 needsterminal = TRUE;
223d09f6 1674 else if ( curField == wxT("copiousoutput") )
b13d92d1 1675 copiousoutput = TRUE;
223d09f6 1676 else if ( curField == wxT("textualnewlines") )
b13d92d1
VZ
1677 ; // ignore
1678 else
1679 ok = FALSE;
1680 }
1681
1682 if ( !ok )
1683 {
1684 // don't flood the user with error messages
1685 // if we don't understand something in his
ec4768ef
VZ
1686 // mailcap, but give them in debug mode
1687 // because this might be useful for the
1688 // programmer
b13d92d1
VZ
1689 wxLogDebug
1690 (
223d09f6 1691 wxT("Mailcap file %s, line %d: unknown "
dd0e574a 1692 "field '%s' for the MIME type "
50920146 1693 "'%s' ignored."),
b13d92d1
VZ
1694 strFileName.c_str(),
1695 nLine + 1,
1696 curField.c_str(),
1697 strType.c_str()
1698 );
1699 }
1700 }
1701
1702 // it already has this value
1703 //currentToken = Field_Other;
1704 break;
1705
1706 default:
223d09f6 1707 wxFAIL_MSG(wxT("unknown field type in mailcap"));
b13d92d1
VZ
1708 }
1709
1710 // next token starts immediately after ';'
1711 curField.Empty();
1712 break;
1713
1714 default:
1715 curField += *pc;
1716 }
1717 }
1718
1719 // check that we really read something reasonable
1720 if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
1721 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1722 "ignored."),
1723 strFileName.c_str(), nLine + 1);
1724 }
1725 else {
1726 MailCapEntry *entry = new MailCapEntry(strOpenCmd,
1727 strPrintCmd,
1728 strTest);
1729
8e124873
VZ
1730 // NB: because of complications below (we must get entries priority
1731 // right), we can't use AddMailcapInfo() here, unfortunately.
b13d92d1
VZ
1732 strType.MakeLower();
1733 int nIndex = m_aTypes.Index(strType);
3c67202d 1734 if ( nIndex == wxNOT_FOUND ) {
b13d92d1
VZ
1735 // new file type
1736 m_aTypes.Add(strType);
1737
1738 m_aEntries.Add(entry);
223d09f6 1739 m_aExtensions.Add(wxT(""));
b13d92d1
VZ
1740 m_aDescriptions.Add(strDesc);
1741 }
1742 else {
cc385968
VZ
1743 // modify the existing entry: the entries in one and the same
1744 // file are read in top-to-bottom order, i.e. the entries read
1745 // first should be tried before the entries below. However,
1746 // the files read later should override the settings in the
1747 // files read before (except if fallback is TRUE), thus we
1748 // Insert() the new entry to the list if it has already
1749 // occured in _this_ file, but Prepend() it if it occured in
1750 // some of the previous ones and Append() to it in the
1751 // fallback case
1752
1753 if ( fallback ) {
1754 // 'fallback' parameter prevents the entries from this
1755 // file from overriding the other ones - always append
1756 MailCapEntry *entryOld = m_aEntries[nIndex];
1757 if ( entryOld )
1758 entry->Append(entryOld);
1759 else
1760 m_aEntries[nIndex] = entry;
b13d92d1
VZ
1761 }
1762 else {
cc385968
VZ
1763 int entryIndex = aEntryIndices.Index(nIndex);
1764 if ( entryIndex == wxNOT_FOUND ) {
1765 // first time in this file
1766 aEntryIndices.Add(nIndex);
1767 aLastIndices.Add(0);
1768
1769 entry->Prepend(m_aEntries[nIndex]);
1770 m_aEntries[nIndex] = entry;
1771 }
1772 else {
1773 // not the first time in _this_ file
1774 size_t nEntryIndex = (size_t)entryIndex;
1775 MailCapEntry *entryOld = m_aEntries[nIndex];
1776 if ( entryOld )
1777 entry->Insert(entryOld, aLastIndices[nEntryIndex]);
1778 else
1779 m_aEntries[nIndex] = entry;
1780
1781 // the indices were shifted by 1
1782 aLastIndices[nEntryIndex]++;
1783 }
b13d92d1
VZ
1784 }
1785
1786 if ( !strDesc.IsEmpty() ) {
cc385968 1787 // replace the old one - what else can we do??
b13d92d1
VZ
1788 m_aDescriptions[nIndex] = strDesc;
1789 }
1790 }
1791 }
1792
1793 // check our data integriry
1794 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1795 m_aTypes.Count() == m_aExtensions.Count() &&
1796 m_aTypes.Count() == m_aDescriptions.Count() );
1797 }
cc385968
VZ
1798
1799 return TRUE;
b13d92d1
VZ
1800}
1801
696e1ea0 1802size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1b986aef 1803{
696e1ea0 1804 mimetypes = m_aTypes;
1b986aef 1805
696e1ea0 1806 return m_aTypes.GetCount();
1b986aef
VZ
1807}
1808
8e124873 1809#endif
ce4169a4
RR
1810 // OS type
1811
8e124873 1812#endif
ce4169a4 1813 // wxUSE_FILE && wxUSE_TEXTFILE
b13d92d1 1814
3d05544e
JS
1815#endif
1816 // __WIN16__