]> git.saurik.com Git - wxWidgets.git/blob - src/common/mimetype.cpp
f3a4c6bd6455a7152b0b27d2b66b155a6bbf97b1
[wxWidgets.git] / src / common / mimetype.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: common/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 23.09.98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "mimetype.h"
14 #endif
15
16 // for compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #ifndef WX_PRECOMP
24 #include "wx/defs.h"
25 #endif
26
27 #if (wxUSE_FILE && wxUSE_TEXTFILE) || defined(__WXMSW__)
28
29 #ifndef WX_PRECOMP
30 #include "wx/string.h"
31 #include "wx/icon.h"
32 #endif //WX_PRECOMP
33
34 // Doesn't compile in WIN16 mode
35 #ifndef __WIN16__
36
37 #include "wx/log.h"
38 #include "wx/file.h"
39 #include "wx/intl.h"
40 #include "wx/dynarray.h"
41 #include "wx/confbase.h"
42
43 #ifdef __WXMSW__
44 #include "wx/msw/registry.h"
45 #include "windows.h"
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
82 // although I don't know of any official documentation which mentions this
83 // location, uses it, so it isn't likely to change
84 static const wxChar *MIME_DATABASE_KEY = wxT("MIME\\Database\\Content Type\\");
85
86 class wxFileTypeImpl
87 {
88 public:
89 // ctor
90 wxFileTypeImpl() { m_info = NULL; }
91
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; }
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,
111 const wxFileType::MessageParameters& params) const;
112 bool GetPrintCommand(wxString *printCmd,
113 const wxFileType::MessageParameters& params) const;
114
115 private:
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;
122 wxString m_strFileType, // may be empty
123 m_ext;
124 };
125
126 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
127 #include "wx/arrimpl.cpp"
128 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
129
130 class wxMimeTypesManagerImpl
131 {
132 public:
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
141 size_t EnumAllFileTypes(wxArrayString& mimetypes);
142
143 // this are NOPs under Windows
144 bool ReadMailcap(const wxString& filename, bool fallback = TRUE)
145 { return TRUE; }
146 bool ReadMimeTypes(const wxString& filename)
147 { return TRUE; }
148
149 void AddFallback(const wxFileTypeInfo& ft) { m_fallbacks.Add(ft); }
150
151 private:
152 wxArrayFileTypeInfo m_fallbacks;
153 };
154
155 #elif defined( __WXMAC__ )
156
157 WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
158 #include "wx/arrimpl.cpp"
159 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
160
161 class wxMimeTypesManagerImpl
162 {
163 public :
164 wxMimeTypesManagerImpl() { }
165
166 // implement containing class functions
167 wxFileType *GetFileTypeFromExtension(const wxString& ext);
168 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
169
170 size_t EnumAllFileTypes(wxArrayString& mimetypes);
171
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
178 private:
179 wxArrayFileTypeInfo m_fallbacks;
180 };
181
182 class wxFileTypeImpl
183 {
184 public:
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
203 private:
204 // helper function
205 bool GetCommand(wxString *command, const char *verb) const;
206
207 wxString m_strFileType, m_ext;
208 };
209
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 //
252 // Parameter/filename xpansion:
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>
271 // b) for "expanded" format:
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.
280 class MailCapEntry
281 {
282 public:
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; }
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
313 wxASSERT_MSG( n == pos, wxT("invalid position in MailCapEntry::Insert") );
314
315 m_next = cur->m_next;
316 cur->m_next = this;
317 }
318 // append this element to the list
319 void Append(MailCapEntry *next)
320 {
321 wxCHECK_RET( next != NULL, wxT("Append()ing to what?") );
322
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
330 wxASSERT_MSG( !m_next, wxT("Append()ing element already in the list?") );
331 }
332
333 private:
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
342 WX_DEFINE_ARRAY(MailCapEntry *, ArrayTypeEntries);
343
344 class wxMimeTypesManagerImpl
345 {
346 friend class wxFileTypeImpl; // give it access to m_aXXX variables
347
348 public:
349 // ctor loads all info into memory for quicker access later on
350 // TODO it would be nice to load them all, but parse on demand only...
351 wxMimeTypesManagerImpl();
352
353 // implement containing class functions
354 wxFileType *GetFileTypeFromExtension(const wxString& ext);
355 wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
356
357 size_t EnumAllFileTypes(wxArrayString& mimetypes);
358
359 bool ReadMailcap(const wxString& filename, bool fallback = FALSE);
360 bool ReadMimeTypes(const wxString& filename);
361
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
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
379 private:
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
386 class wxFileTypeImpl
387 {
388 public:
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; }
397 bool GetIcon(wxIcon * WXUNUSED(icon)) const
398 { return FALSE; } // TODO maybe with Gnome/KDE integration...
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
414 private:
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
429 // ============================================================================
430 // common classes
431 // ============================================================================
432
433 // ----------------------------------------------------------------------------
434 // wxFileTypeInfo
435 // ----------------------------------------------------------------------------
436
437 wxFileTypeInfo::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
465 // ============================================================================
466 // implementation of the wrapper classes
467 // ============================================================================
468
469 // ----------------------------------------------------------------------------
470 // wxFileType
471 // ----------------------------------------------------------------------------
472
473 wxString wxFileType::ExpandCommand(const wxString& command,
474 const wxFileType::MessageParameters& params)
475 {
476 bool hasFilename = FALSE;
477
478 wxString str;
479 for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
480 if ( *pc == wxT('%') ) {
481 switch ( *++pc ) {
482 case wxT('s'):
483 // '%s' expands into file name (quoted because it might
484 // contain spaces) - except if there are already quotes
485 // there because otherwise some programs may get confused
486 // by double double quotes
487 #if 0
488 if ( *(pc - 2) == wxT('"') )
489 str << params.GetFileName();
490 else
491 str << wxT('"') << params.GetFileName() << wxT('"');
492 #endif
493 str << params.GetFileName();
494 hasFilename = TRUE;
495 break;
496
497 case wxT('t'):
498 // '%t' expands into MIME type (quote it too just to be
499 // consistent)
500 str << wxT('\'') << params.GetMimeType() << wxT('\'');
501 break;
502
503 case wxT('{'):
504 {
505 const wxChar *pEnd = wxStrchr(pc, wxT('}'));
506 if ( pEnd == NULL ) {
507 wxString mimetype;
508 wxLogWarning(_("Unmatched '{' in an entry for "
509 "mime type %s."),
510 params.GetMimeType().c_str());
511 str << wxT("%{");
512 }
513 else {
514 wxString param(pc + 1, pEnd - pc - 1);
515 str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
516 pc = pEnd;
517 }
518 }
519 break;
520
521 case wxT('n'):
522 case wxT('F'):
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:
529 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
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() ) {
542 str << wxT(" < '") << params.GetFileName() << wxT('\'');
543 }
544
545 return str;
546 }
547
548 wxFileType::wxFileType()
549 {
550 m_impl = new wxFileTypeImpl;
551 }
552
553 wxFileType::~wxFileType()
554 {
555 delete m_impl;
556 }
557
558 bool wxFileType::GetExtensions(wxArrayString& extensions)
559 {
560 return m_impl->GetExtensions(extensions);
561 }
562
563 bool wxFileType::GetMimeType(wxString *mimeType) const
564 {
565 return m_impl->GetMimeType(mimeType);
566 }
567
568 bool wxFileType::GetIcon(wxIcon *icon) const
569 {
570 return m_impl->GetIcon(icon);
571 }
572
573 bool wxFileType::GetDescription(wxString *desc) const
574 {
575 return m_impl->GetDescription(desc);
576 }
577
578 bool
579 wxFileType::GetOpenCommand(wxString *openCmd,
580 const wxFileType::MessageParameters& params) const
581 {
582 return m_impl->GetOpenCommand(openCmd, params);
583 }
584
585 bool
586 wxFileType::GetPrintCommand(wxString *printCmd,
587 const wxFileType::MessageParameters& params) const
588 {
589 return m_impl->GetPrintCommand(printCmd, params);
590 }
591
592 // ----------------------------------------------------------------------------
593 // wxMimeTypesManager
594 // ----------------------------------------------------------------------------
595
596 bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
597 const wxString& wildcard)
598 {
599 wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
600 wxT("first MIME type can't contain wildcards") );
601
602 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
603 if ( wildcard.BeforeFirst(wxT('/')).IsSameAs(mimeType.BeforeFirst(wxT('/')), FALSE) )
604 {
605 wxString strSubtype = wildcard.AfterFirst(wxT('/'));
606
607 if ( strSubtype == wxT("*") ||
608 strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), FALSE) )
609 {
610 // matches (either exactly or it's a wildcard)
611 return TRUE;
612 }
613 }
614
615 return FALSE;
616 }
617
618 wxMimeTypesManager::wxMimeTypesManager()
619 {
620 m_impl = new wxMimeTypesManagerImpl;
621 }
622
623 wxMimeTypesManager::~wxMimeTypesManager()
624 {
625 delete m_impl;
626 }
627
628 wxFileType *
629 wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
630 {
631 return m_impl->GetFileTypeFromExtension(ext);
632 }
633
634 wxFileType *
635 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
636 {
637 return m_impl->GetFileTypeFromMimeType(mimeType);
638 }
639
640 bool wxMimeTypesManager::ReadMailcap(const wxString& filename, bool fallback)
641 {
642 return m_impl->ReadMailcap(filename, fallback);
643 }
644
645 bool wxMimeTypesManager::ReadMimeTypes(const wxString& filename)
646 {
647 return m_impl->ReadMimeTypes(filename);
648 }
649
650 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
651 {
652 for ( const wxFileTypeInfo *ft = filetypes; ft->IsValid(); ft++ ) {
653 m_impl->AddFallback(*ft);
654 }
655 }
656
657 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
658 {
659 return m_impl->EnumAllFileTypes(mimetypes);
660 }
661
662 // ============================================================================
663 // real (OS specific) implementation
664 // ============================================================================
665
666 #ifdef __WXMSW__
667
668 wxString wxFileTypeImpl::GetCommand(const wxChar *verb) const
669 {
670 // suppress possible error messages
671 wxLogNull nolog;
672 wxString strKey;
673
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);
687 wxString command;
688 if ( key.Open() ) {
689 // it's the default value of the key
690 if ( key.QueryValue(wxT(""), command) ) {
691 // transform it from '%1' to '%s' style format string
692
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'!
696 bool foundFilename = FALSE;
697 size_t len = command.Len();
698 for ( size_t n = 0; (n < len) && !foundFilename; n++ ) {
699 if ( command[n] == wxT('%') &&
700 (n + 1 < len) && command[n + 1] == wxT('1') ) {
701 // replace it with '%s'
702 command[n + 1] = wxT('s');
703
704 foundFilename = TRUE;
705 }
706 }
707
708 if ( !foundFilename ) {
709 // we didn't find any '%1'!
710 // HACK: append the filename at the end, hope that it will do
711 command << wxT(" %s");
712 }
713 }
714 }
715 //else: no such file type or no value, will return empty string
716
717 return command;
718 }
719
720 bool
721 wxFileTypeImpl::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 {
730 cmd = GetCommand(wxT("open"));
731 }
732
733 *openCmd = wxFileType::ExpandCommand(cmd, params);
734
735 return !openCmd->IsEmpty();
736 }
737
738 bool
739 wxFileTypeImpl::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 {
748 cmd = GetCommand(wxT("print"));
749 }
750
751 *printCmd = wxFileType::ExpandCommand(cmd, params);
752
753 return !printCmd->IsEmpty();
754 }
755
756 // TODO this function is half implemented
757 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
758 {
759 if ( m_info ) {
760 extensions = m_info->GetExtensions();
761
762 return TRUE;
763 }
764 else if ( m_ext.IsEmpty() ) {
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
778 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
779 {
780 if ( m_info ) {
781 // we already have it
782 *mimeType = m_info->GetMimeType();
783
784 return TRUE;
785 }
786
787 // suppress possible error messages
788 wxLogNull nolog;
789 wxRegKey key(wxRegKey::HKCR, wxT(".") + m_ext);
790 if ( key.Open() && key.QueryValue(wxT("Content Type"), *mimeType) ) {
791 return TRUE;
792 }
793 else {
794 return FALSE;
795 }
796 }
797
798 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
799 {
800 #if wxUSE_GUI
801 if ( m_info ) {
802 // we don't have icons in the fallback resources
803 return FALSE;
804 }
805
806 wxString strIconKey;
807 strIconKey << m_strFileType << wxT("\\DefaultIcon");
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
816 if ( key.QueryValue(wxT(""), strIcon) ) {
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 '%'
820 wxString strFullPath = strIcon.BeforeLast(wxT(',')),
821 strIndex = strIcon.AfterLast(wxT(','));
822
823 // index may be omitted, in which case BeforeLast(',') is empty and
824 // AfterLast(',') is the whole string
825 if ( strFullPath.IsEmpty() ) {
826 strFullPath = strIndex;
827 strIndex = wxT("0");
828 }
829
830 wxString strExpPath = wxExpandEnvVars(strFullPath);
831 int nIndex = wxAtoi(strIndex);
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/...
837 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
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
849 #endif // wxUSE_GUI
850
851 return FALSE;
852 }
853
854 bool wxFileTypeImpl::GetDescription(wxString *desc) const
855 {
856 if ( m_info ) {
857 // we already have it
858 *desc = m_info->GetDescription();
859
860 return TRUE;
861 }
862
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
869 if ( key.QueryValue(wxT(""), *desc) ) {
870 return TRUE;
871 }
872 }
873
874 return FALSE;
875 }
876
877 // extension -> file type
878 wxFileType *
879 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
880 {
881 // add the leading point if necessary
882 wxString str;
883 if ( ext[0u] != wxT('.') ) {
884 str = wxT('.');
885 }
886 str << ext;
887
888 // suppress possible error messages
889 wxLogNull nolog;
890
891 bool knownExtension = FALSE;
892
893 wxString strFileType;
894 wxRegKey key(wxRegKey::HKCR, str);
895 if ( key.Open() ) {
896 // it's the default value of the key
897 if ( key.QueryValue(wxT(""), strFileType) ) {
898 // create the new wxFileType object
899 wxFileType *fileType = new wxFileType;
900 fileType->m_impl->Init(strFileType, ext);
901
902 return fileType;
903 }
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 }
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]);
920
921 return fileType;
922 }
923 }
924
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 }
937 }
938
939 // MIME type -> extension -> file type
940 wxFileType *
941 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
942 {
943 wxString strKey = MIME_DATABASE_KEY;
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() ) {
952 if ( key.QueryValue(wxT("Extension"), ext) ) {
953 return GetFileTypeFromExtension(ext);
954 }
955 }
956
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
971 // unknown MIME type
972 return NULL;
973 }
974
975 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
976 {
977 // enumerate all keys under MIME_DATABASE_KEY
978 wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
979
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();
991 }
992
993 #elif defined ( __WXMAC__ )
994
995 bool wxFileTypeImpl::GetCommand(wxString *command, const char *verb) const
996 {
997 return FALSE;
998 }
999
1000 // @@ this function is half implemented
1001 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1002 {
1003 return FALSE;
1004 }
1005
1006 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
1007 {
1008 if ( m_strFileType.Length() > 0 )
1009 {
1010 *mimeType = m_strFileType ;
1011 return TRUE ;
1012 }
1013 else
1014 return FALSE;
1015 }
1016
1017 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
1018 {
1019 // no such file type or no value or incorrect icon entry
1020 return FALSE;
1021 }
1022
1023 bool wxFileTypeImpl::GetDescription(wxString *desc) const
1024 {
1025 return FALSE;
1026 }
1027
1028 // extension -> file type
1029 wxFileType *
1030 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& e)
1031 {
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;
1100 }
1101
1102 // MIME type -> extension -> file type
1103 wxFileType *
1104 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1105 {
1106 return NULL;
1107 }
1108
1109 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1110 {
1111 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1112
1113 return 0;
1114 }
1115
1116 #else // Unix
1117
1118 MailCapEntry *
1119 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
1120 {
1121 wxString command;
1122 MailCapEntry *entry = m_manager->m_aEntries[m_index];
1123 while ( entry != NULL ) {
1124 // notice that an empty command would always succeed (it's ok)
1125 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
1126
1127 if ( command.IsEmpty() || (wxSystem(command) == 0) ) {
1128 // ok, passed
1129 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1130 command.c_str(), params.GetMimeType().c_str());
1131 break;
1132 }
1133 else {
1134 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1135 command.c_str(), params.GetMimeType().c_str());
1136 }
1137
1138 entry = entry->GetNext();
1139 }
1140
1141 return entry;
1142 }
1143
1144 bool
1145 wxFileTypeImpl::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
1165 bool 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;
1172 for ( const wxChar *p = strExtensions; ; p++ ) {
1173 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
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
1181 if ( *p == wxT('\0') )
1182 break;
1183 }
1184 else if ( *p == wxT('.') ) {
1185 // remove the dot from extension (but only if it's the first char)
1186 if ( !strExt.IsEmpty() ) {
1187 strExt += wxT('.');
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)
1200 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1201 {
1202 // directories where we look for mailcap and mime.types by default
1203 // (taken from metamail(1) sources)
1204 static const wxChar *aStandardLocations[] =
1205 {
1206 wxT("/etc"),
1207 wxT("/usr/etc"),
1208 wxT("/usr/local/etc"),
1209 wxT("/etc/mail"),
1210 wxT("/usr/public/lib")
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
1217 wxString file = dir + wxT("/mailcap");
1218 if ( wxFile::Exists(file) ) {
1219 ReadMailcap(file);
1220 }
1221
1222 file = dir + wxT("/mime.types");
1223 if ( wxFile::Exists(file) ) {
1224 ReadMimeTypes(file);
1225 }
1226 }
1227
1228 wxString strHome = wxGetenv(wxT("HOME"));
1229
1230 // and now the users mailcap
1231 wxString strUserMailcap = strHome + wxT("/.mailcap");
1232 if ( wxFile::Exists(strUserMailcap) ) {
1233 ReadMailcap(strUserMailcap);
1234 }
1235
1236 // read the users mime.types
1237 wxString strUserMimeTypes = strHome + wxT("/.mime.types");
1238 if ( wxFile::Exists(strUserMimeTypes) ) {
1239 ReadMimeTypes(strUserMimeTypes);
1240 }
1241 }
1242
1243 wxFileType *
1244 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1245 {
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() ) {
1250 wxString field = extensions.BeforeFirst(wxT(' '));
1251 extensions = extensions.AfterFirst(wxT(' '));
1252
1253 // consider extensions as not being case-sensitive
1254 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
1255 // found
1256 wxFileType *fileType = new wxFileType;
1257 fileType->m_impl->Init(this, n);
1258
1259 return fileType;
1260 }
1261 }
1262 }
1263
1264 // not found
1265 return NULL;
1266 }
1267
1268 wxFileType *
1269 wxMimeTypesManagerImpl::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);
1277 if ( index == wxNOT_FOUND ) {
1278 // then try to find "text/*" as match for "text/plain" (for example)
1279 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1280 // the whole string - ok.
1281 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
1282
1283 size_t nCount = m_aTypes.Count();
1284 for ( size_t n = 0; n < nCount; n++ ) {
1285 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
1286 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
1287 index = n;
1288 break;
1289 }
1290 }
1291 }
1292
1293 if ( index != wxNOT_FOUND ) {
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
1305 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
1306 {
1307 wxString extensions;
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 ) {
1312 extensions += wxT(' ');
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(),
1324 wxT(""),
1325 filetype.GetDescription());
1326 }
1327
1328 void 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 }
1345 m_aExtensions[index] += ' ' + strExtensions;
1346 }
1347 }
1348
1349 void 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);
1363 m_aExtensions.Add(wxT(""));
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
1377 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
1378 {
1379 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName.c_str());
1380
1381 wxTextFile file(strFileName);
1382 if ( !file.Open() )
1383 return FALSE;
1384
1385 // the information we extract
1386 wxString strMimeType, strDesc, strExtensions;
1387
1388 size_t nLineCount = file.GetLineCount();
1389 const wxChar *pc = NULL;
1390 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
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 }
1399
1400 // skip whitespace
1401 while ( wxIsspace(*pc) )
1402 pc++;
1403
1404 // comment?
1405 if ( *pc == wxT('#') ) {
1406 // skip the whole line
1407 pc = NULL;
1408 continue;
1409 }
1410
1411 // detect file format
1412 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
1413 if ( pEqualSign == NULL ) {
1414 // brief format
1415 // ------------
1416
1417 // first field is mime type
1418 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
1419 strMimeType += *pc;
1420 }
1421
1422 // skip whitespace
1423 while ( wxIsspace(*pc) )
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
1440 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
1441 ;
1442
1443 const wxChar *pEnd;
1444 if ( *pc == wxT('"') ) {
1445 // the string is quoted and ends at the matching quote
1446 pEnd = wxStrchr(++pc, wxT('"'));
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 {
1454 // unquoted string ends at the first space
1455 for ( pEnd = pc; !wxIsspace(*pEnd); pEnd++ )
1456 ;
1457 }
1458
1459 // now we have the RHS (field value)
1460 wxString strRHS(pc, pEnd - pc);
1461
1462 // check what follows this entry
1463 if ( *pEnd == wxT('"') ) {
1464 // skip this quote
1465 pEnd++;
1466 }
1467
1468 for ( pc = pEnd; wxIsspace(*pc); pc++ )
1469 ;
1470
1471 // if there is something left, it may be either a '\\' to continue
1472 // the line or the next field of the same entry
1473 bool entryEnded = *pc == wxT('\0'),
1474 nextFieldOnSameLine = FALSE;
1475 if ( !entryEnded ) {
1476 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
1477 }
1478
1479 // now see what we got
1480 if ( strLHS == wxT("type") ) {
1481 strMimeType = strRHS;
1482 }
1483 else if ( strLHS == wxT("desc") ) {
1484 strDesc = strRHS;
1485 }
1486 else if ( strLHS == wxT("exts") ) {
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 ) {
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
1500 // will be interpreted correctly.
1501
1502 continue;
1503 }
1504 }
1505
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)
1509 strExtensions.Replace(wxT(","), wxT(" "));
1510
1511 // also deal with the leading dot
1512 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
1513 {
1514 strExtensions.erase(0, 1);
1515 }
1516
1517 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
1518
1519 // finished with this line
1520 pc = NULL;
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() );
1527
1528 return TRUE;
1529 }
1530
1531 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
1532 bool fallback)
1533 {
1534 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName.c_str());
1535
1536 wxTextFile file(strFileName);
1537 if ( !file.Open() )
1538 return FALSE;
1539
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
1543 wxArrayInt aEntryIndices;
1544 // aLastIndices[n] is the index of last element in
1545 // m_aEntries[aEntryIndices[n]] from this file
1546 wxArrayInt aLastIndices;
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
1551 const wxChar *pc = file[nLine].c_str();
1552
1553 // skip whitespace
1554 while ( wxIsspace(*pc) )
1555 pc++;
1556
1557 // comment or empty string?
1558 if ( *pc == wxT('#') || *pc == wxT('\0') )
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
1574 bool needsterminal = FALSE,
1575 copiousoutput = FALSE;
1576 wxString strType,
1577 strOpenCmd,
1578 strPrintCmd,
1579 strTest,
1580 strDesc,
1581 curField; // accumulator
1582 for ( bool cont = TRUE; cont; pc++ ) {
1583 switch ( *pc ) {
1584 case wxT('\\'):
1585 // interpret the next character literally (notice that
1586 // backslash can be used for line continuation)
1587 if ( *++pc == wxT('\0') ) {
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
1601 case wxT('\0'):
1602 cont = FALSE; // end of line reached, exit the loop
1603
1604 // fall through
1605
1606 case wxT(';'):
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;
1615 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
1616 // we interpret "type" as "type/*"
1617 strType += wxT("/*");
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?
1635 const wxChar *pEq = wxStrchr(curField, wxT('='));
1636 if ( pEq != NULL ) {
1637 wxString lhs = curField.BeforeFirst(wxT('=')),
1638 rhs = curField.AfterFirst(wxT('='));
1639
1640 lhs.Trim(TRUE); // from right
1641 rhs.Trim(FALSE); // from left
1642
1643 if ( lhs == wxT("print") )
1644 strPrintCmd = rhs;
1645 else if ( lhs == wxT("test") )
1646 strTest = rhs;
1647 else if ( lhs == wxT("description") ) {
1648 // it might be quoted
1649 if ( rhs[0u] == wxT('"') &&
1650 rhs.Last() == wxT('"') ) {
1651 strDesc = wxString(rhs.c_str() + 1,
1652 rhs.Len() - 2);
1653 }
1654 else {
1655 strDesc = rhs;
1656 }
1657 }
1658 else if ( lhs == wxT("compose") ||
1659 lhs == wxT("composetyped") ||
1660 lhs == wxT("notes") ||
1661 lhs == wxT("edit") )
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'
1672 if ( curField == wxT("needsterminal") )
1673 needsterminal = TRUE;
1674 else if ( curField == wxT("copiousoutput") )
1675 copiousoutput = TRUE;
1676 else if ( curField == wxT("textualnewlines") )
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
1686 // mailcap, but give them in debug mode
1687 // because this might be useful for the
1688 // programmer
1689 wxLogDebug
1690 (
1691 wxT("Mailcap file %s, line %d: unknown "
1692 "field '%s' for the MIME type "
1693 "'%s' ignored."),
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:
1707 wxFAIL_MSG(wxT("unknown field type in mailcap"));
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
1730 // NB: because of complications below (we must get entries priority
1731 // right), we can't use AddMailcapInfo() here, unfortunately.
1732 strType.MakeLower();
1733 int nIndex = m_aTypes.Index(strType);
1734 if ( nIndex == wxNOT_FOUND ) {
1735 // new file type
1736 m_aTypes.Add(strType);
1737
1738 m_aEntries.Add(entry);
1739 m_aExtensions.Add(wxT(""));
1740 m_aDescriptions.Add(strDesc);
1741 }
1742 else {
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;
1761 }
1762 else {
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 }
1784 }
1785
1786 if ( !strDesc.IsEmpty() ) {
1787 // replace the old one - what else can we do??
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 }
1798
1799 return TRUE;
1800 }
1801
1802 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1803 {
1804 mimetypes = m_aTypes;
1805
1806 return m_aTypes.GetCount();
1807 }
1808
1809 #endif
1810 // OS type
1811
1812 #endif
1813 // wxUSE_FILE && wxUSE_TEXTFILE
1814
1815 #endif
1816 // __WIN16__