]> git.saurik.com Git - wxWidgets.git/blame - src/common/mimetype.cpp
wxProcess fixes (Detach() added), cleared/corrected wxExecute() documentation
[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__
13 #pragma implementation "mimetype.h"
14#endif
15
16// ============================================================================
17// declarations
18// ============================================================================
19
20// ----------------------------------------------------------------------------
21// headers
22// ----------------------------------------------------------------------------
23
24// for compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#ifdef __BORLANDC__
28 #pragma hdrstop
29#endif
30
31// wxWindows
32#ifndef WX_PRECOMP
33 #include "wx/string.h"
2432b92d 34 #include "wx/icon.h"
b13d92d1
VZ
35#endif //WX_PRECOMP
36
3d05544e
JS
37// Doesn't compile in WIN16 mode
38#ifndef __WIN16__
39
b13d92d1
VZ
40#include "wx/log.h"
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"
b13d92d1
VZ
48#else // Unix
49 #include "wx/textfile.h"
50#endif // OS
51
52#include "wx/mimetype.h"
53
54// other standard headers
55#include <ctype.h>
56
57// ----------------------------------------------------------------------------
58// private classes
59// ----------------------------------------------------------------------------
60
61// implementation classes, platform dependent
62#ifdef __WXMSW__
63
64// These classes use Windows registry to retrieve the required information.
65//
66// Keys used (not all of them are documented, so it might actually stop working
67// in futur versions of Windows...):
68// 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
69// types, each key has a string value "Extension" which gives (dot preceded)
70// extension for the files of this MIME type.
71//
72// 2. "HKCR\.ext" contains
73// a) unnamed value containing the "filetype"
74// b) value "Content Type" containing the MIME type
75//
76// 3. "HKCR\filetype" contains
77// a) unnamed value containing the description
78// b) subkey "DefaultIcon" with single unnamed value giving the icon index in
79// an icon file
80// c) shell\open\command and shell\open\print subkeys containing the commands
81// to open/print the file (the positional parameters are introduced by %1,
82// %2, ... in these strings, we change them to %s ourselves)
83
84class wxFileTypeImpl
85{
86public:
87 // ctor
88 wxFileTypeImpl() { }
89
90 // initialize us with our file type name
91 void SetFileType(const wxString& strFileType)
92 { m_strFileType = strFileType; }
93 void SetExt(const wxString& ext)
94 { m_ext = ext; }
95
96 // implement accessor functions
97 bool GetExtensions(wxArrayString& extensions);
98 bool GetMimeType(wxString *mimeType) const;
99 bool GetIcon(wxIcon *icon) const;
100 bool GetDescription(wxString *desc) const;
101 bool GetOpenCommand(wxString *openCmd,
102 const wxFileType::MessageParameters&) const
103 { return GetCommand(openCmd, "open"); }
104 bool GetPrintCommand(wxString *printCmd,
105 const wxFileType::MessageParameters&) const
106 { return GetCommand(printCmd, "print"); }
107
108private:
109 // helper function
110 bool GetCommand(wxString *command, const char *verb) const;
111
112 wxString m_strFileType, m_ext;
113};
114
115class wxMimeTypesManagerImpl
116{
117public:
118 // nothing to do here, we don't load any data but just go and fetch it from
119 // the registry when asked for
120 wxMimeTypesManagerImpl() { }
121
122 // implement containing class functions
123 wxFileType *GetFileTypeFromExtension(const wxString& ext);
124 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
125
126 // this are NOPs under Windows
127 void ReadMailcap(const wxString& filename) { }
128 void ReadMimeTypes(const wxString& filename) { }
129};
130
131#else // Unix
132
133// this class uses both mailcap and mime.types to gather information about file
134// types.
135//
136// The information about mailcap file was extracted from metamail(1) sources and
137// documentation.
138//
139// Format of mailcap file: spaces are ignored, each line is either a comment
140// (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
141// A backslash can be used to quote semicolons and newlines (and, in fact,
142// anything else including itself).
143//
144// The first field is always the MIME type in the form of type/subtype (see RFC
145// 822) where subtype may be '*' meaning "any". Following metamail, we accept
146// "type" which means the same as "type/*", although I'm not sure whether this
147// is standard.
148//
149// The second field is always the command to run. It is subject to
150// parameter/filename expansion described below.
151//
152// All the following fields are optional and may not be present at all. If
153// they're present they may appear in any order, although each of them should
154// appear only once. The optional fields are the following:
155// * notes=xxx is an uninterpreted string which is silently ignored
156// * test=xxx is the command to be used to determine whether this mailcap line
157// applies to our data or not. The RHS of this field goes through the
158// parameter/filename expansion (as the 2nd field) and the resulting string
159// is executed. The line applies only if the command succeeds, i.e. returns 0
160// exit code.
161// * print=xxx is the command to be used to print (and not view) the data of
162// this type (parameter/filename expansion is done here too)
163// * edit=xxx is the command to open/edit the data of this type
164// * needsterminal means that a new console must be created for the viewer
165// * copiousoutput means that the viewer doesn't interact with the user but
166// produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
167// good example), thus it might be a good idea to use some kind of paging
168// mechanism.
169// * textualnewlines means not to perform CR/LF translation (not honored)
170// * compose and composetyped fields are used to determine the program to be
171// called to create a new message pert in the specified format (unused).
172//
ec4768ef 173// Parameter/filename xpansion:
b13d92d1
VZ
174// * %s is replaced with the (full) file name
175// * %t is replaced with MIME type/subtype of the entry
176// * for multipart type only %n is replaced with the nnumber of parts and %F is
177// replaced by an array of (content-type, temporary file name) pairs for all
178// message parts (TODO)
179// * %{parameter} is replaced with the value of parameter taken from
180// Content-type header line of the message.
181//
182// FIXME any docs with real descriptions of these files??
183//
184// There are 2 possible formats for mime.types file, one entry per line (used
185// for global mime.types) and "expanded" format where an entry takes multiple
186// lines (used for users mime.types).
187//
188// For both formats spaces are ignored and lines starting with a '#' are
189// comments. Each record has one of two following forms:
190// a) for "brief" format:
191// <mime type> <space separated list of extensions>
ec4768ef 192// b) for "expanded" format:
b13d92d1
VZ
193// type=<mime type> \ desc="<description>" \ exts="ext"
194//
195// We try to autodetect the format of mime.types: if a non-comment line starts
196// with "type=" we assume the second format, otherwise the first one.
197
198// there may be more than one entry for one and the same mime type, to
199// choose the right one we have to run the command specified in the test
200// field on our data.
201class MailCapEntry
202{
203public:
204 // ctor
205 MailCapEntry(const wxString& openCmd,
206 const wxString& printCmd,
207 const wxString& testCmd)
208 : m_openCmd(openCmd), m_printCmd(printCmd), m_testCmd(testCmd)
209 {
210 m_next = NULL;
211 }
212
213 // accessors
214 const wxString& GetOpenCmd() const { return m_openCmd; }
215 const wxString& GetPrintCmd() const { return m_printCmd; }
216 const wxString& GetTestCmd() const { return m_testCmd; }
217
218 MailCapEntry *GetNext() const { return m_next; }
219
220 // operations
221 // prepend this element to the list
222 void Prepend(MailCapEntry *next) { m_next = next; }
223 // append to the list
224 void Append(MailCapEntry *next)
225 {
226 // FIXME slooow...
227 MailCapEntry *cur;
228 for ( cur = next; cur->m_next != NULL; cur = cur->m_next )
229 ;
230
231 cur->m_next = this;
232
233 // we initialize it in the ctor and there is no reason to both Prepend()
234 // and Append() one and the same entry
235 wxASSERT( m_next == NULL );
236 }
237
238private:
239 wxString m_openCmd, // command to use to open/view the file
240 m_printCmd, // print
241 m_testCmd; // only apply this entry if test yields
242 // true (i.e. the command returns 0)
243
244 MailCapEntry *m_next; // in the linked list
245};
246
247WX_DEFINE_ARRAY(MailCapEntry *, ArrayTypeEntries);
248
249class wxMimeTypesManagerImpl
250{
251friend class wxFileTypeImpl; // give it access to m_aXXX variables
252
253public:
254 // ctor loads all info into memory for quicker access later on
255 // @@ it would be nice to load them all, but parse on demand only...
256 wxMimeTypesManagerImpl();
257
258 // implement containing class functions
259 wxFileType *GetFileTypeFromExtension(const wxString& ext);
260 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
261
262 void ReadMailcap(const wxString& filename);
263 void ReadMimeTypes(const wxString& filename);
264
265 // accessors
266 // get the string containing space separated extensions for the given
267 // file type
268 wxString GetExtension(size_t index) { return m_aExtensions[index]; }
269
270private:
271 wxArrayString m_aTypes, // MIME types
272 m_aDescriptions, // descriptions (just some text)
273 m_aExtensions; // space separated list of extensions
274 ArrayTypeEntries m_aEntries; // commands and tests for this file type
275};
276
277class wxFileTypeImpl
278{
279public:
280 // initialization functions
281 void Init(wxMimeTypesManagerImpl *manager, size_t index)
282 { m_manager = manager; m_index = index; }
283
284 // accessors
285 bool GetExtensions(wxArrayString& extensions);
286 bool GetMimeType(wxString *mimeType) const
287 { *mimeType = m_manager->m_aTypes[m_index]; return TRUE; }
288 bool GetIcon(wxIcon *icon) const
289 { return FALSE; } // @@ maybe with Gnome/KDE integration...
290 bool GetDescription(wxString *desc) const
291 { *desc = m_manager->m_aDescriptions[m_index]; return TRUE; }
292
293 bool GetOpenCommand(wxString *openCmd,
294 const wxFileType::MessageParameters& params) const
295 {
296 return GetExpandedCommand(openCmd, params, TRUE);
297 }
298
299 bool GetPrintCommand(wxString *printCmd,
300 const wxFileType::MessageParameters& params) const
301 {
302 return GetExpandedCommand(printCmd, params, FALSE);
303 }
304
305private:
306 // get the entry which passes the test (may return NULL)
307 MailCapEntry *GetEntry(const wxFileType::MessageParameters& params) const;
308
309 // choose the correct entry to use and expand the command
310 bool GetExpandedCommand(wxString *expandedCmd,
311 const wxFileType::MessageParameters& params,
312 bool open) const;
313
314 wxMimeTypesManagerImpl *m_manager;
315 size_t m_index; // in the wxMimeTypesManagerImpl arrays
316};
317
318#endif // OS type
319
320// ============================================================================
321// implementation of the wrapper classes
322// ============================================================================
323
324// ----------------------------------------------------------------------------
325// wxFileType
326// ----------------------------------------------------------------------------
327
328wxString wxFileType::ExpandCommand(const wxString& command,
329 const wxFileType::MessageParameters& params)
330{
331 bool hasFilename = FALSE;
332
333 wxString str;
334 for ( const char *pc = command.c_str(); *pc != '\0'; pc++ ) {
335 if ( *pc == '%' ) {
336 switch ( *++pc ) {
337 case 's':
338 // '%s' expands into file name (quoted because it might
339 // contain spaces) - except if there are already quotes
341c92a8
VZ
340 // there because otherwise some programs may get confused
341 // by double double quotes
b13d92d1
VZ
342#if 0
343 if ( *(pc - 2) == '"' )
344 str << params.GetFileName();
345 else
346 str << '"' << params.GetFileName() << '"';
347#endif
348 str << params.GetFileName();
349 hasFilename = TRUE;
350 break;
351
352 case 't':
353 // '%t' expands into MIME type (quote it too just to be
354 // consistent)
355 str << '\'' << params.GetMimeType() << '\'';
356 break;
357
358 case '{':
359 {
360 const char *pEnd = strchr(pc, '}');
361 if ( pEnd == NULL ) {
362 wxString mimetype;
363 wxLogWarning(_("Unmatched '{' in an entry for "
364 "mime type %s."),
365 params.GetMimeType().c_str());
366 str << "%{";
367 }
368 else {
369 wxString param(pc + 1, pEnd - pc - 1);
370 str << '\'' << params.GetParamValue(param) << '\'';
371 pc = pEnd;
372 }
373 }
374 break;
375
376 case 'n':
377 case 'F':
378 // TODO %n is the number of parts, %F is an array containing
379 // the names of temp files these parts were written to
380 // and their mime types.
381 break;
382
383 default:
384 wxLogDebug("Unknown field %%%c in command '%s'.",
385 *pc, command.c_str());
386 str << *pc;
387 }
388 }
389 else {
390 str << *pc;
391 }
392 }
393
394 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
395 // the program will accept the data on stdin: so give it to it!
396 if ( !hasFilename && !str.IsEmpty() ) {
397 str << " < '" << params.GetFileName() << '\'';
398 }
399
400 return str;
401}
402
403wxFileType::wxFileType()
404{
405 m_impl = new wxFileTypeImpl;
406}
407
408wxFileType::~wxFileType()
409{
410 delete m_impl;
411}
412
413bool wxFileType::GetExtensions(wxArrayString& extensions)
414{
415 return m_impl->GetExtensions(extensions);
416}
417
418bool wxFileType::GetMimeType(wxString *mimeType) const
419{
420 return m_impl->GetMimeType(mimeType);
421}
422
423bool wxFileType::GetIcon(wxIcon *icon) const
424{
425 return m_impl->GetIcon(icon);
426}
427
428bool wxFileType::GetDescription(wxString *desc) const
429{
430 return m_impl->GetDescription(desc);
431}
432
433bool
434wxFileType::GetOpenCommand(wxString *openCmd,
435 const wxFileType::MessageParameters& params) const
436{
437 return m_impl->GetOpenCommand(openCmd, params);
438}
439
440bool
441wxFileType::GetPrintCommand(wxString *printCmd,
442 const wxFileType::MessageParameters& params) const
443{
444 return m_impl->GetPrintCommand(printCmd, params);
445}
446
447// ----------------------------------------------------------------------------
448// wxMimeTypesManager
449// ----------------------------------------------------------------------------
450
451wxMimeTypesManager::wxMimeTypesManager()
452{
453 m_impl = new wxMimeTypesManagerImpl;
454}
455
456wxMimeTypesManager::~wxMimeTypesManager()
457{
458 delete m_impl;
459}
460
461wxFileType *
462wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
463{
464 return m_impl->GetFileTypeFromExtension(ext);
465}
466
467wxFileType *
468wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
469{
470 return m_impl->GetFileTypeFromMimeType(mimeType);
471}
472
473// ============================================================================
474// real (OS specific) implementation
475// ============================================================================
476
477#ifdef __WXMSW__
478
479bool wxFileTypeImpl::GetCommand(wxString *command, const char *verb) const
480{
481 // suppress possible error messages
482 wxLogNull nolog;
483 wxString strKey;
484 strKey << m_strFileType << "\\shell\\" << verb << "\\command";
485 wxRegKey key(wxRegKey::HKCR, strKey);
486
487 if ( key.Open() ) {
488 // it's the default value of the key
489 if ( key.QueryValue("", *command) ) {
490 // transform it from '%1' to '%s' style format string
491 // @@ we don't make any attempt to verify that the string is valid,
492 // i.e. doesn't contain %2, or second %1 or .... But we do make
493 // sure that we return a string with _exactly_ one '%s'!
494 size_t len = command->Len();
495 for ( size_t n = 0; n < len; n++ ) {
496 if ( command->GetChar(n) == '%' &&
497 (n + 1 < len) && command->GetChar(n + 1) == '1' ) {
498 // replace it with '%s'
499 command->SetChar(n + 1, 's');
500
501 return TRUE;
502 }
503 }
504
505 // we didn't find any '%1'!
506 // @@@ hack: append the filename at the end, hope that it will do
507 *command << " %s";
508
509 return TRUE;
510 }
511 }
512
513 // no such file type or no value
514 return FALSE;
515}
516
517// @@ this function is half implemented
518bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
519{
520 if ( m_ext.IsEmpty() ) {
521 // the only way to get the list of extensions from the file type is to
522 // scan through all extensions in the registry - too slow...
523 return FALSE;
524 }
525 else {
526 extensions.Empty();
527 extensions.Add(m_ext);
528
529 // it's a lie too, we don't return _all_ extensions...
530 return TRUE;
531 }
532}
533
534bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
535{
536 // suppress possible error messages
537 wxLogNull nolog;
538 wxRegKey key(wxRegKey::HKCR, m_strFileType);
539 if ( key.Open() && key.QueryValue("Content Type", *mimeType) ) {
540 return TRUE;
541 }
542 else {
543 return FALSE;
544 }
545}
546
547bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
548{
549 wxString strIconKey;
550 strIconKey << m_strFileType << "\\DefaultIcon";
551
552 // suppress possible error messages
553 wxLogNull nolog;
554 wxRegKey key(wxRegKey::HKCR, strIconKey);
555
556 if ( key.Open() ) {
557 wxString strIcon;
558 // it's the default value of the key
559 if ( key.QueryValue("", strIcon) ) {
560 // the format is the following: <full path to file>, <icon index>
561 // NB: icon index may be negative as well as positive and the full
562 // path may contain the environment variables inside '%'
3c67202d
VZ
563 wxString strFullPath = strIcon.BeforeLast(','),
564 strIndex = strIcon.AfterLast(',');
b13d92d1 565
3c67202d
VZ
566 // index may be omitted, in which case BeforeLast(',') is empty and
567 // AfterLast(',') is the whole string
b13d92d1
VZ
568 if ( strFullPath.IsEmpty() ) {
569 strFullPath = strIndex;
570 strIndex = "0";
571 }
572
573 wxString strExpPath = wxExpandEnvVars(strFullPath);
574 int nIndex = atoi(strIndex);
575
576 HICON hIcon = ExtractIcon(GetModuleHandle(NULL), strExpPath, nIndex);
577 switch ( (int)hIcon ) {
578 case 0: // means no icons were found
579 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
580 wxLogDebug("incorrect registry entry '%s': no such icon.",
581 key.GetName().c_str());
582 break;
583
584 default:
585 icon->SetHICON((WXHICON)hIcon);
586 return TRUE;
587 }
588 }
589 }
590
591 // no such file type or no value or incorrect icon entry
592 return FALSE;
593}
594
595bool wxFileTypeImpl::GetDescription(wxString *desc) const
596{
597 // suppress possible error messages
598 wxLogNull nolog;
599 wxRegKey key(wxRegKey::HKCR, m_strFileType);
600
601 if ( key.Open() ) {
602 // it's the default value of the key
603 if ( key.QueryValue("", *desc) ) {
604 return TRUE;
605 }
606 }
607
608 return FALSE;
609}
610
611// extension -> file type
612wxFileType *
613wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
614{
615 // add the leading point if necessary
616 wxString str;
617 if ( ext[0u] != '.' ) {
618 str = '.';
619 }
620 str << ext;
621
622 // suppress possible error messages
623 wxLogNull nolog;
624
625 wxString strFileType;
626 wxRegKey key(wxRegKey::HKCR, str);
627 if ( key.Open() ) {
628 // it's the default value of the key
629 if ( key.QueryValue("", strFileType) ) {
630 // create the new wxFileType object
631 wxFileType *fileType = new wxFileType;
632 fileType->m_impl->SetFileType(strFileType);
633 fileType->m_impl->SetExt(ext);
634
635 return fileType;
636 }
637 }
638
639 // unknown extension
640 return NULL;
641}
642
643// MIME type -> extension -> file type
644wxFileType *
645wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
646{
647 // @@@ I don't know of any official documentation which mentions this
648 // location, but as a matter of fact IE uses it, so why not we?
649 static const char *szMimeDbase = "MIME\\Database\\Content Type\\";
650
651 wxString strKey = szMimeDbase;
652 strKey << mimeType;
653
654 // suppress possible error messages
655 wxLogNull nolog;
656
657 wxString ext;
658 wxRegKey key(wxRegKey::HKCR, strKey);
659 if ( key.Open() ) {
660 if ( key.QueryValue("Extension", ext) ) {
661 return GetFileTypeFromExtension(ext);
662 }
663 }
664
665 // unknown MIME type
666 return NULL;
667}
668
669#else // Unix
670
671MailCapEntry *
672wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
673{
674 wxString command;
675 MailCapEntry *entry = m_manager->m_aEntries[m_index];
676 while ( entry != NULL ) {
677 // notice that an empty command would always succeed (@@ is it ok?)
678 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
679
680 if ( command.IsEmpty() || (system(command) == 0) ) {
681 // ok, passed
682 wxLogTrace("Test '%s' for mime type '%s' succeeded.",
683 command.c_str(), params.GetMimeType().c_str());
684 break;
685 }
686 else {
687 wxLogTrace("Test '%s' for mime type '%s' failed.",
688 command.c_str(), params.GetMimeType().c_str());
689 }
690
691 entry = entry->GetNext();
692 }
693
694 return entry;
695}
696
697bool
698wxFileTypeImpl::GetExpandedCommand(wxString *expandedCmd,
699 const wxFileType::MessageParameters& params,
700 bool open) const
701{
702 MailCapEntry *entry = GetEntry(params);
703 if ( entry == NULL ) {
704 // all tests failed...
705 return FALSE;
706 }
707
708 wxString cmd = open ? entry->GetOpenCmd() : entry->GetPrintCmd();
709 if ( cmd.IsEmpty() ) {
710 // may happen, especially for "print"
711 return FALSE;
712 }
713
714 *expandedCmd = wxFileType::ExpandCommand(cmd, params);
715 return TRUE;
716}
717
718bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
719{
720 wxString strExtensions = m_manager->GetExtension(m_index);
721 extensions.Empty();
722
723 // one extension in the space or comma delimitid list
724 wxString strExt;
725 for ( const char *p = strExtensions; ; p++ ) {
726 if ( *p == ' ' || *p == ',' || *p == '\0' ) {
727 if ( !strExt.IsEmpty() ) {
728 extensions.Add(strExt);
729 strExt.Empty();
730 }
731 //else: repeated spaces (shouldn't happen, but it's not that
732 // important if it does happen)
733
734 if ( *p == '\0' )
735 break;
736 }
737 else if ( *p == '.' ) {
738 // remove the dot from extension (but only if it's the first char)
739 if ( !strExt.IsEmpty() ) {
740 strExt += '.';
741 }
742 //else: no, don't append it
743 }
744 else {
745 strExt += *p;
746 }
747 }
748
749 return TRUE;
750}
751
752// read system and user mailcaps (TODO implement mime.types support)
753wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
754{
755 // directories where we look for mailcap and mime.types by default
756 // (taken from metamail(1) sources)
757 static const char *aStandardLocations[] =
758 {
759 "/etc",
760 "/usr/etc",
761 "/usr/local/etc",
762 "/etc/mail",
763 "/usr/public/lib"
764 };
765
766 // first read the system wide file(s)
767 for ( size_t n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
768 wxString dir = aStandardLocations[n];
769
770 wxString file = dir + "/mailcap";
771 if ( wxFile::Exists(file) ) {
772 ReadMailcap(file);
773 }
774
775 file = dir + "/mime.types";
776 if ( wxFile::Exists(file) ) {
777 ReadMimeTypes(file);
778 }
779 }
780
781 wxString strHome = getenv("HOME");
782
783 // and now the users mailcap
784 wxString strUserMailcap = strHome + "/.mailcap";
785 if ( wxFile::Exists(strUserMailcap) ) {
786 ReadMailcap(strUserMailcap);
787 }
788
789 // read the users mime.types
790 wxString strUserMimeTypes = strHome + "/.mime.types";
791 if ( wxFile::Exists(strUserMimeTypes) ) {
792 ReadMimeTypes(strUserMimeTypes);
793 }
794}
795
796wxFileType *
797wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
798{
1ee17e1c
VZ
799 size_t count = m_aExtensions.GetCount();
800 for ( size_t n = 0; n < count; n++ ) {
801 wxString extensions = m_aExtensions[n];
802 while ( !extensions.IsEmpty() ) {
803 wxString field = extensions.BeforeFirst(' ');
804 extensions = extensions.AfterFirst(' ');
805
806 // consider extensions as not being case-sensitive
ec4768ef 807 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
1ee17e1c
VZ
808 // found
809 wxFileType *fileType = new wxFileType;
810 fileType->m_impl->Init(this, n);
ec4768ef 811
1ee17e1c
VZ
812 return fileType;
813 }
814 }
815 }
b13d92d1 816
1ee17e1c 817 // not found
b13d92d1
VZ
818 return NULL;
819}
820
821wxFileType *
822wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
823{
824 // mime types are not case-sensitive
825 wxString mimetype(mimeType);
826 mimetype.MakeLower();
827
828 // first look for an exact match
829 int index = m_aTypes.Index(mimetype);
3c67202d 830 if ( index == wxNOT_FOUND ) {
b13d92d1 831 // then try to find "text/*" as match for "text/plain" (for example)
3c67202d
VZ
832 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
833 // the whole string - ok.
834 wxString strCategory = mimetype.BeforeFirst('/');
b13d92d1
VZ
835
836 size_t nCount = m_aTypes.Count();
837 for ( size_t n = 0; n < nCount; n++ ) {
3c67202d
VZ
838 if ( (m_aTypes[n].BeforeFirst('/') == strCategory ) &&
839 m_aTypes[n].AfterFirst('/') == "*" ) {
b13d92d1
VZ
840 index = n;
841 break;
842 }
843 }
844 }
845
3c67202d 846 if ( index != wxNOT_FOUND ) {
b13d92d1
VZ
847 wxFileType *fileType = new wxFileType;
848 fileType->m_impl->Init(this, index);
849
850 return fileType;
851 }
852 else {
853 // not found...
854 return NULL;
855 }
856}
857
858void wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
859{
860 wxLogTrace("--- Parsing mime.types file '%s' ---", strFileName.c_str());
861
862 wxTextFile file(strFileName);
863 if ( !file.Open() )
864 return;
865
866 // the information we extract
867 wxString strMimeType, strDesc, strExtensions;
868
869 size_t nLineCount = file.GetLineCount();
870 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
871 // now we're at the start of the line
872 const char *pc = file[nLine].c_str();
873
874 // skip whitespace
875 while ( isspace(*pc) )
876 pc++;
877
878 // comment?
879 if ( *pc == '#' )
880 continue;
881
882 // detect file format
883 const char *pEqualSign = strchr(pc, '=');
884 if ( pEqualSign == NULL ) {
885 // brief format
886 // ------------
887
888 // first field is mime type
889 for ( strMimeType.Empty(); !isspace(*pc) && *pc != '\0'; pc++ ) {
890 strMimeType += *pc;
891 }
892
893 // skip whitespace
894 while ( isspace(*pc) )
895 pc++;
896
897 // take all the rest of the string
898 strExtensions = pc;
899
900 // no description...
901 strDesc.Empty();
902 }
903 else {
904 // expanded format
905 // ---------------
906
907 // the string on the left of '=' is the field name
908 wxString strLHS(pc, pEqualSign - pc);
909
910 // eat whitespace
911 for ( pc = pEqualSign + 1; isspace(*pc); pc++ )
912 ;
913
914 const char *pEnd;
915 if ( *pc == '"' ) {
916 // the string is quoted and ends at the matching quote
917 pEnd = strchr(++pc, '"');
918 if ( pEnd == NULL ) {
919 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
920 "quoted string."),
921 strFileName.c_str(), nLine + 1);
922 }
923 }
924 else {
925 // unquoted stringends at the first space
926 for ( pEnd = pc; !isspace(*pEnd); pEnd++ )
927 ;
928 }
929
930 // now we have the RHS (field value)
931 wxString strRHS(pc, pEnd - pc);
932
933 // check that it's more or less what we're waiting for, i.e. that
934 // only '\' is left on the line
935 if ( *pEnd == '"' ) {
936 // skip this quote
937 pEnd++;
938 }
939
940 for ( pc = pEnd; isspace(*pc); pc++ )
941 ;
942
943 // only '\\' may be left on the line normally
944 bool entryEnded = *pc == '\0';
945 if ( !entryEnded && ((*pc != '\\') || (*++pc != '\0')) ) {
946 wxLogWarning(_("Mime.types file %s, line %d: extra characters "
947 "after the field value ignored."),
948 strFileName.c_str(), nLine + 1);
949 }
950 // if there is a trailing backslash entryEnded = FALSE
951
952 // now see what we got
953 if ( strLHS == "type" ) {
954 strMimeType = strRHS;
955 }
956 else if ( strLHS == "desc" ) {
957 strDesc = strRHS;
958 }
959 else if ( strLHS == "exts" ) {
960 strExtensions = strRHS;
961 }
962 else {
963 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
964 strFileName.c_str(), nLine + 1, strLHS.c_str());
965 }
966
967 if ( !entryEnded ) {
968 // as we don't reset strMimeType, the next line in this entry
969 // will be interpreted correctly.
970 continue;
971 }
972 }
973
974 int index = m_aTypes.Index(strMimeType);
3c67202d 975 if ( index == wxNOT_FOUND ) {
b13d92d1
VZ
976 // add a new entry
977 m_aTypes.Add(strMimeType);
978 m_aEntries.Add(NULL);
979 m_aExtensions.Add(strExtensions);
980 m_aDescriptions.Add(strDesc);
981 }
982 else {
983 // modify an existing one
984 if ( !strDesc.IsEmpty() ) {
985 m_aDescriptions[index] = strDesc; // replace old value
986 }
987 m_aExtensions[index] += strExtensions;
988 }
989 }
990
991 // check our data integriry
992 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
993 m_aTypes.Count() == m_aExtensions.Count() &&
994 m_aTypes.Count() == m_aDescriptions.Count() );
995}
996
997void wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName)
998{
999 wxLogTrace("--- Parsing mailcap file '%s' ---", strFileName.c_str());
1000
1001 wxTextFile file(strFileName);
1002 if ( !file.Open() )
1003 return;
1004
1005 // see the comments near the end of function for the reason we need this
1006 wxArrayInt aEntryIndices;
1007
1008 size_t nLineCount = file.GetLineCount();
1009 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1010 // now we're at the start of the line
1011 const char *pc = file[nLine].c_str();
1012
1013 // skip whitespace
1014 while ( isspace(*pc) )
1015 pc++;
1016
1017 // comment or empty string?
1018 if ( *pc == '#' || *pc == '\0' )
1019 continue;
1020
1021 // no, do parse
1022
1023 // what field are we currently in? The first 2 are fixed and there may
1024 // be an arbitrary number of other fields -- currently, we are not
1025 // interested in any of them, but we should parse them as well...
1026 enum
1027 {
1028 Field_Type,
1029 Field_OpenCmd,
1030 Field_Other
1031 } currentToken = Field_Type;
1032
1033 // the flags and field values on the current line
8fc613f1
RR
1034 bool needsterminal = FALSE,
1035 copiousoutput = FALSE;
b13d92d1
VZ
1036 wxString strType,
1037 strOpenCmd,
1038 strPrintCmd,
1039 strTest,
1040 strDesc,
1041 curField; // accumulator
1042 for ( bool cont = TRUE; cont; pc++ ) {
1043 switch ( *pc ) {
1044 case '\\':
1045 // interpret the next character literally (notice that
1046 // backslash can be used for line continuation)
1047 if ( *++pc == '\0' ) {
1048 // fetch the next line.
1049
1050 // pc currently points to nowhere, but after the next
1051 // pc++ in the for line it will point to the beginning
1052 // of the next line in the file
1053 pc = file[++nLine].c_str() - 1;
1054 }
1055 else {
1056 // just a normal character
1057 curField += *pc;
1058 }
1059 break;
1060
1061 case '\0':
1062 cont = FALSE; // end of line reached, exit the loop
1063
1064 // fall through
1065
1066 case ';':
1067 // store this field and start looking for the next one
1068
1069 // trim whitespaces from both sides
1070 curField.Trim(TRUE).Trim(FALSE);
1071
1072 switch ( currentToken ) {
1073 case Field_Type:
1074 strType = curField;
3c67202d 1075 if ( strType.Find('/') == wxNOT_FOUND ) {
b13d92d1
VZ
1076 // we interpret "type" as "type/*"
1077 strType += "/*";
1078 }
1079
1080 currentToken = Field_OpenCmd;
1081 break;
1082
1083 case Field_OpenCmd:
1084 strOpenCmd = curField;
1085
1086 currentToken = Field_Other;
1087 break;
1088
1089 case Field_Other:
1090 {
1091 // "good" mailcap entry?
1092 bool ok = TRUE;
1093
1094 // is this something of the form foo=bar?
1095 const char *pEq = strchr(curField, '=');
1096 if ( pEq != NULL ) {
ec4768ef
VZ
1097 wxString lhs = curField.BeforeFirst('='),
1098 rhs = curField.AfterFirst('=');
b13d92d1
VZ
1099
1100 lhs.Trim(TRUE); // from right
1101 rhs.Trim(FALSE); // from left
1102
1103 if ( lhs == "print" )
1104 strPrintCmd = rhs;
1105 else if ( lhs == "test" )
1106 strTest = rhs;
1107 else if ( lhs == "description" ) {
1108 // it might be quoted
1109 if ( rhs[0u] == '"' &&
1110 rhs.Last() == '"' ) {
1111 strDesc = wxString(rhs.c_str() + 1,
1112 rhs.Len() - 2);
1113 }
1114 else {
1115 strDesc = rhs;
1116 }
1117 }
1118 else if ( lhs == "compose" ||
1119 lhs == "composetyped" ||
1120 lhs == "notes" ||
1121 lhs == "edit" )
1122 ; // ignore
1123 else
1124 ok = FALSE;
1125
1126 }
1127 else {
1128 // no, it's a simple flag
1129 // TODO support the flags:
1130 // 1. create an xterm for 'needsterminal'
1131 // 2. append "| $PAGER" for 'copiousoutput'
1132 if ( curField == "needsterminal" )
1133 needsterminal = TRUE;
1134 else if ( curField == "copiousoutput" )
1135 copiousoutput = TRUE;
1136 else if ( curField == "textualnewlines" )
1137 ; // ignore
1138 else
1139 ok = FALSE;
1140 }
1141
1142 if ( !ok )
1143 {
1144 // don't flood the user with error messages
1145 // if we don't understand something in his
ec4768ef
VZ
1146 // mailcap, but give them in debug mode
1147 // because this might be useful for the
1148 // programmer
b13d92d1
VZ
1149 wxLogDebug
1150 (
1151 _("Mailcap file %s, line %d: unknown "
1152 "field '%s' for the MIME type "
1153 "'%s' ignored."),
1154 strFileName.c_str(),
1155 nLine + 1,
1156 curField.c_str(),
1157 strType.c_str()
1158 );
1159 }
1160 }
1161
1162 // it already has this value
1163 //currentToken = Field_Other;
1164 break;
1165
1166 default:
1167 wxFAIL_MSG("unknown field type in mailcap");
1168 }
1169
1170 // next token starts immediately after ';'
1171 curField.Empty();
1172 break;
1173
1174 default:
1175 curField += *pc;
1176 }
1177 }
1178
1179 // check that we really read something reasonable
1180 if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
1181 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1182 "ignored."),
1183 strFileName.c_str(), nLine + 1);
1184 }
1185 else {
1186 MailCapEntry *entry = new MailCapEntry(strOpenCmd,
1187 strPrintCmd,
1188 strTest);
1189
1190 strType.MakeLower();
1191 int nIndex = m_aTypes.Index(strType);
3c67202d 1192 if ( nIndex == wxNOT_FOUND ) {
b13d92d1
VZ
1193 // new file type
1194 m_aTypes.Add(strType);
1195
1196 m_aEntries.Add(entry);
1197 m_aExtensions.Add("");
1198 m_aDescriptions.Add(strDesc);
1199 }
1200 else {
1201 // modify the existing entry: the entry in one and the same file
1202 // are read in top-to-bottom order, i.e. the entries read first
1203 // should be tried before the entries below. However, the files
1204 // read later should override the settings in the files read
1205 // before, thus we Append() the new entry to the list if it has
1206 // already occured in _this_ file, but Prepend() it if it
1207 // occured in some of the previous ones.
3c67202d 1208 if ( aEntryIndices.Index(nIndex) == wxNOT_FOUND ) {
b13d92d1
VZ
1209 // first time in this file
1210 aEntryIndices.Add(nIndex);
1211 entry->Prepend(m_aEntries[nIndex]);
1212 m_aEntries[nIndex] = entry;
1213 }
1214 else {
1215 // not the first time in _this_ file
1216 entry->Append(m_aEntries[nIndex]);
1217 }
1218
1219 if ( !strDesc.IsEmpty() ) {
1220 // @@ replace the old one - what else can we do??
1221 m_aDescriptions[nIndex] = strDesc;
1222 }
1223 }
1224 }
1225
1226 // check our data integriry
1227 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1228 m_aTypes.Count() == m_aExtensions.Count() &&
1229 m_aTypes.Count() == m_aDescriptions.Count() );
1230 }
1231}
1232
1233#endif // OS type
1234
3d05544e
JS
1235#endif
1236 // __WIN16__