]> git.saurik.com Git - wxWidgets.git/blob - src/common/mimetype.cpp
1. fixes for DrawRotatedText(), drawing sample extended to show it
[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,
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 strKey << m_strFileType << wxT("\\shell\\") << verb << wxT("\\command");
674 wxRegKey key(wxRegKey::HKCR, strKey);
675
676 wxString command;
677 if ( key.Open() ) {
678 // it's the default value of the key
679 if ( key.QueryValue(wxT(""), command) ) {
680 // transform it from '%1' to '%s' style format string
681
682 // NB: we don't make any attempt to verify that the string is valid,
683 // i.e. doesn't contain %2, or second %1 or .... But we do make
684 // sure that we return a string with _exactly_ one '%s'!
685 bool foundFilename = FALSE;
686 size_t len = command.Len();
687 for ( size_t n = 0; (n < len) && !foundFilename; n++ ) {
688 if ( command[n] == wxT('%') &&
689 (n + 1 < len) && command[n + 1] == wxT('1') ) {
690 // replace it with '%s'
691 command[n + 1] = wxT('s');
692
693 foundFilename = TRUE;
694 }
695 }
696
697 if ( !foundFilename ) {
698 // we didn't find any '%1'!
699 // HACK: append the filename at the end, hope that it will do
700 command << wxT(" %s");
701 }
702 }
703 }
704
705 // no such file type or no value
706 return command;
707 }
708
709 bool
710 wxFileTypeImpl::GetOpenCommand(wxString *openCmd,
711 const wxFileType::MessageParameters& params)
712 const
713 {
714 wxString cmd;
715 if ( m_info ) {
716 cmd = m_info->GetOpenCommand();
717 }
718 else {
719 cmd = GetCommand(wxT("open"));
720 }
721
722 *openCmd = wxFileType::ExpandCommand(cmd, params);
723
724 return !openCmd->IsEmpty();
725 }
726
727 bool
728 wxFileTypeImpl::GetPrintCommand(wxString *printCmd,
729 const wxFileType::MessageParameters& params)
730 const
731 {
732 wxString cmd;
733 if ( m_info ) {
734 cmd = m_info->GetPrintCommand();
735 }
736 else {
737 cmd = GetCommand(wxT("print"));
738 }
739
740 *printCmd = wxFileType::ExpandCommand(cmd, params);
741
742 return !printCmd->IsEmpty();
743 }
744
745 // TODO this function is half implemented
746 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
747 {
748 if ( m_info ) {
749 extensions = m_info->GetExtensions();
750
751 return TRUE;
752 }
753 else if ( m_ext.IsEmpty() ) {
754 // the only way to get the list of extensions from the file type is to
755 // scan through all extensions in the registry - too slow...
756 return FALSE;
757 }
758 else {
759 extensions.Empty();
760 extensions.Add(m_ext);
761
762 // it's a lie too, we don't return _all_ extensions...
763 return TRUE;
764 }
765 }
766
767 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
768 {
769 if ( m_info ) {
770 // we already have it
771 *mimeType = m_info->GetMimeType();
772
773 return TRUE;
774 }
775
776 // suppress possible error messages
777 wxLogNull nolog;
778 wxRegKey key(wxRegKey::HKCR, /*m_strFileType*/ wxT(".") + m_ext);
779 if ( key.Open() && key.QueryValue(wxT("Content Type"), *mimeType) ) {
780 return TRUE;
781 }
782 else {
783 return FALSE;
784 }
785 }
786
787 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
788 {
789 #if wxUSE_GUI
790 if ( m_info ) {
791 // we don't have icons in the fallback resources
792 return FALSE;
793 }
794
795 wxString strIconKey;
796 strIconKey << m_strFileType << wxT("\\DefaultIcon");
797
798 // suppress possible error messages
799 wxLogNull nolog;
800 wxRegKey key(wxRegKey::HKCR, strIconKey);
801
802 if ( key.Open() ) {
803 wxString strIcon;
804 // it's the default value of the key
805 if ( key.QueryValue(wxT(""), strIcon) ) {
806 // the format is the following: <full path to file>, <icon index>
807 // NB: icon index may be negative as well as positive and the full
808 // path may contain the environment variables inside '%'
809 wxString strFullPath = strIcon.BeforeLast(wxT(',')),
810 strIndex = strIcon.AfterLast(wxT(','));
811
812 // index may be omitted, in which case BeforeLast(',') is empty and
813 // AfterLast(',') is the whole string
814 if ( strFullPath.IsEmpty() ) {
815 strFullPath = strIndex;
816 strIndex = wxT("0");
817 }
818
819 wxString strExpPath = wxExpandEnvVars(strFullPath);
820 int nIndex = wxAtoi(strIndex);
821
822 HICON hIcon = ExtractIcon(GetModuleHandle(NULL), strExpPath, nIndex);
823 switch ( (int)hIcon ) {
824 case 0: // means no icons were found
825 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
826 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
827 key.GetName().c_str());
828 break;
829
830 default:
831 icon->SetHICON((WXHICON)hIcon);
832 return TRUE;
833 }
834 }
835 }
836
837 // no such file type or no value or incorrect icon entry
838 #endif // wxUSE_GUI
839
840 return FALSE;
841 }
842
843 bool wxFileTypeImpl::GetDescription(wxString *desc) const
844 {
845 if ( m_info ) {
846 // we already have it
847 *desc = m_info->GetDescription();
848
849 return TRUE;
850 }
851
852 // suppress possible error messages
853 wxLogNull nolog;
854 wxRegKey key(wxRegKey::HKCR, m_strFileType);
855
856 if ( key.Open() ) {
857 // it's the default value of the key
858 if ( key.QueryValue(wxT(""), *desc) ) {
859 return TRUE;
860 }
861 }
862
863 return FALSE;
864 }
865
866 // extension -> file type
867 wxFileType *
868 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
869 {
870 // add the leading point if necessary
871 wxString str;
872 if ( ext[0u] != wxT('.') ) {
873 str = wxT('.');
874 }
875 str << ext;
876
877 // suppress possible error messages
878 wxLogNull nolog;
879
880 wxString strFileType;
881 wxRegKey key(wxRegKey::HKCR, str);
882 if ( key.Open() ) {
883 // it's the default value of the key
884 if ( key.QueryValue(wxT(""), strFileType) ) {
885 // create the new wxFileType object
886 wxFileType *fileType = new wxFileType;
887 fileType->m_impl->Init(strFileType, ext);
888
889 return fileType;
890 }
891 }
892
893 // check the fallbacks
894 // TODO linear search is potentially slow, perhaps we should use a sorted
895 // array?
896 size_t count = m_fallbacks.GetCount();
897 for ( size_t n = 0; n < count; n++ ) {
898 if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
899 wxFileType *fileType = new wxFileType;
900 fileType->m_impl->Init(m_fallbacks[n]);
901
902 return fileType;
903 }
904 }
905
906 // unknown extension
907 return NULL;
908 }
909
910 // MIME type -> extension -> file type
911 wxFileType *
912 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
913 {
914 wxString strKey = MIME_DATABASE_KEY;
915 strKey << mimeType;
916
917 // suppress possible error messages
918 wxLogNull nolog;
919
920 wxString ext;
921 wxRegKey key(wxRegKey::HKCR, strKey);
922 if ( key.Open() ) {
923 if ( key.QueryValue(wxT("Extension"), ext) ) {
924 return GetFileTypeFromExtension(ext);
925 }
926 }
927
928 // check the fallbacks
929 // TODO linear search is potentially slow, perhaps we should use a sorted
930 // array?
931 size_t count = m_fallbacks.GetCount();
932 for ( size_t n = 0; n < count; n++ ) {
933 if ( wxMimeTypesManager::IsOfType(mimeType,
934 m_fallbacks[n].GetMimeType()) ) {
935 wxFileType *fileType = new wxFileType;
936 fileType->m_impl->Init(m_fallbacks[n]);
937
938 return fileType;
939 }
940 }
941
942 // unknown MIME type
943 return NULL;
944 }
945
946 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
947 {
948 // enumerate all keys under MIME_DATABASE_KEY
949 wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
950
951 wxString type;
952 long cookie;
953 bool cont = key.GetFirstKey(type, cookie);
954 while ( cont )
955 {
956 mimetypes.Add(type);
957
958 cont = key.GetNextKey(type, cookie);
959 }
960
961 return mimetypes.GetCount();
962 }
963
964 #elif defined ( __WXMAC__ )
965
966 bool wxFileTypeImpl::GetCommand(wxString *command, const char *verb) const
967 {
968 return FALSE;
969 }
970
971 // @@ this function is half implemented
972 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
973 {
974 return FALSE;
975 }
976
977 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
978 {
979 if ( m_strFileType.Length() > 0 )
980 {
981 *mimeType = m_strFileType ;
982 return TRUE ;
983 }
984 else
985 return FALSE;
986 }
987
988 bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
989 {
990 // no such file type or no value or incorrect icon entry
991 return FALSE;
992 }
993
994 bool wxFileTypeImpl::GetDescription(wxString *desc) const
995 {
996 return FALSE;
997 }
998
999 // extension -> file type
1000 wxFileType *
1001 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& e)
1002 {
1003 wxString ext = e ;
1004 ext = ext.Lower() ;
1005 if ( ext == "txt" )
1006 {
1007 wxFileType *fileType = new wxFileType;
1008 fileType->m_impl->SetFileType("text/text");
1009 fileType->m_impl->SetExt(ext);
1010 return fileType;
1011 }
1012 else if ( ext == "htm" || ext == "html" )
1013 {
1014 wxFileType *fileType = new wxFileType;
1015 fileType->m_impl->SetFileType("text/html");
1016 fileType->m_impl->SetExt(ext);
1017 return fileType;
1018 }
1019 else if ( ext == "gif" )
1020 {
1021 wxFileType *fileType = new wxFileType;
1022 fileType->m_impl->SetFileType("image/gif");
1023 fileType->m_impl->SetExt(ext);
1024 return fileType;
1025 }
1026 else if ( ext == "png" )
1027 {
1028 wxFileType *fileType = new wxFileType;
1029 fileType->m_impl->SetFileType("image/png");
1030 fileType->m_impl->SetExt(ext);
1031 return fileType;
1032 }
1033 else if ( ext == "jpg" || ext == "jpeg" )
1034 {
1035 wxFileType *fileType = new wxFileType;
1036 fileType->m_impl->SetFileType("image/jpeg");
1037 fileType->m_impl->SetExt(ext);
1038 return fileType;
1039 }
1040 else if ( ext == "bmp" )
1041 {
1042 wxFileType *fileType = new wxFileType;
1043 fileType->m_impl->SetFileType("image/bmp");
1044 fileType->m_impl->SetExt(ext);
1045 return fileType;
1046 }
1047 else if ( ext == "tif" || ext == "tiff" )
1048 {
1049 wxFileType *fileType = new wxFileType;
1050 fileType->m_impl->SetFileType("image/tiff");
1051 fileType->m_impl->SetExt(ext);
1052 return fileType;
1053 }
1054 else if ( ext == "xpm" )
1055 {
1056 wxFileType *fileType = new wxFileType;
1057 fileType->m_impl->SetFileType("image/xpm");
1058 fileType->m_impl->SetExt(ext);
1059 return fileType;
1060 }
1061 else if ( ext == "xbm" )
1062 {
1063 wxFileType *fileType = new wxFileType;
1064 fileType->m_impl->SetFileType("image/xbm");
1065 fileType->m_impl->SetExt(ext);
1066 return fileType;
1067 }
1068
1069 // unknown extension
1070 return NULL;
1071 }
1072
1073 // MIME type -> extension -> file type
1074 wxFileType *
1075 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1076 {
1077 return NULL;
1078 }
1079
1080 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1081 {
1082 wxFAIL_MSG( _T("TODO") ); // VZ: don't know anything about this for Mac
1083
1084 return 0;
1085 }
1086
1087 #else // Unix
1088
1089 MailCapEntry *
1090 wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
1091 {
1092 wxString command;
1093 MailCapEntry *entry = m_manager->m_aEntries[m_index];
1094 while ( entry != NULL ) {
1095 // notice that an empty command would always succeed (it's ok)
1096 command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
1097
1098 if ( command.IsEmpty() || (wxSystem(command) == 0) ) {
1099 // ok, passed
1100 wxLogTrace(wxT("Test '%s' for mime type '%s' succeeded."),
1101 command.c_str(), params.GetMimeType().c_str());
1102 break;
1103 }
1104 else {
1105 wxLogTrace(wxT("Test '%s' for mime type '%s' failed."),
1106 command.c_str(), params.GetMimeType().c_str());
1107 }
1108
1109 entry = entry->GetNext();
1110 }
1111
1112 return entry;
1113 }
1114
1115 bool
1116 wxFileTypeImpl::GetExpandedCommand(wxString *expandedCmd,
1117 const wxFileType::MessageParameters& params,
1118 bool open) const
1119 {
1120 MailCapEntry *entry = GetEntry(params);
1121 if ( entry == NULL ) {
1122 // all tests failed...
1123 return FALSE;
1124 }
1125
1126 wxString cmd = open ? entry->GetOpenCmd() : entry->GetPrintCmd();
1127 if ( cmd.IsEmpty() ) {
1128 // may happen, especially for "print"
1129 return FALSE;
1130 }
1131
1132 *expandedCmd = wxFileType::ExpandCommand(cmd, params);
1133 return TRUE;
1134 }
1135
1136 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
1137 {
1138 wxString strExtensions = m_manager->GetExtension(m_index);
1139 extensions.Empty();
1140
1141 // one extension in the space or comma delimitid list
1142 wxString strExt;
1143 for ( const wxChar *p = strExtensions; ; p++ ) {
1144 if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
1145 if ( !strExt.IsEmpty() ) {
1146 extensions.Add(strExt);
1147 strExt.Empty();
1148 }
1149 //else: repeated spaces (shouldn't happen, but it's not that
1150 // important if it does happen)
1151
1152 if ( *p == wxT('\0') )
1153 break;
1154 }
1155 else if ( *p == wxT('.') ) {
1156 // remove the dot from extension (but only if it's the first char)
1157 if ( !strExt.IsEmpty() ) {
1158 strExt += wxT('.');
1159 }
1160 //else: no, don't append it
1161 }
1162 else {
1163 strExt += *p;
1164 }
1165 }
1166
1167 return TRUE;
1168 }
1169
1170 // read system and user mailcaps (TODO implement mime.types support)
1171 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
1172 {
1173 // directories where we look for mailcap and mime.types by default
1174 // (taken from metamail(1) sources)
1175 static const wxChar *aStandardLocations[] =
1176 {
1177 wxT("/etc"),
1178 wxT("/usr/etc"),
1179 wxT("/usr/local/etc"),
1180 wxT("/etc/mail"),
1181 wxT("/usr/public/lib")
1182 };
1183
1184 // first read the system wide file(s)
1185 for ( size_t n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
1186 wxString dir = aStandardLocations[n];
1187
1188 wxString file = dir + wxT("/mailcap");
1189 if ( wxFile::Exists(file) ) {
1190 ReadMailcap(file);
1191 }
1192
1193 file = dir + wxT("/mime.types");
1194 if ( wxFile::Exists(file) ) {
1195 ReadMimeTypes(file);
1196 }
1197 }
1198
1199 wxString strHome = wxGetenv(wxT("HOME"));
1200
1201 // and now the users mailcap
1202 wxString strUserMailcap = strHome + wxT("/.mailcap");
1203 if ( wxFile::Exists(strUserMailcap) ) {
1204 ReadMailcap(strUserMailcap);
1205 }
1206
1207 // read the users mime.types
1208 wxString strUserMimeTypes = strHome + wxT("/.mime.types");
1209 if ( wxFile::Exists(strUserMimeTypes) ) {
1210 ReadMimeTypes(strUserMimeTypes);
1211 }
1212 }
1213
1214 wxFileType *
1215 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
1216 {
1217 size_t count = m_aExtensions.GetCount();
1218 for ( size_t n = 0; n < count; n++ ) {
1219 wxString extensions = m_aExtensions[n];
1220 while ( !extensions.IsEmpty() ) {
1221 wxString field = extensions.BeforeFirst(wxT(' '));
1222 extensions = extensions.AfterFirst(wxT(' '));
1223
1224 // consider extensions as not being case-sensitive
1225 if ( field.IsSameAs(ext, FALSE /* no case */) ) {
1226 // found
1227 wxFileType *fileType = new wxFileType;
1228 fileType->m_impl->Init(this, n);
1229
1230 return fileType;
1231 }
1232 }
1233 }
1234
1235 // not found
1236 return NULL;
1237 }
1238
1239 wxFileType *
1240 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
1241 {
1242 // mime types are not case-sensitive
1243 wxString mimetype(mimeType);
1244 mimetype.MakeLower();
1245
1246 // first look for an exact match
1247 int index = m_aTypes.Index(mimetype);
1248 if ( index == wxNOT_FOUND ) {
1249 // then try to find "text/*" as match for "text/plain" (for example)
1250 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
1251 // the whole string - ok.
1252 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
1253
1254 size_t nCount = m_aTypes.Count();
1255 for ( size_t n = 0; n < nCount; n++ ) {
1256 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
1257 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
1258 index = n;
1259 break;
1260 }
1261 }
1262 }
1263
1264 if ( index != wxNOT_FOUND ) {
1265 wxFileType *fileType = new wxFileType;
1266 fileType->m_impl->Init(this, index);
1267
1268 return fileType;
1269 }
1270 else {
1271 // not found...
1272 return NULL;
1273 }
1274 }
1275
1276 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
1277 {
1278 wxString extensions;
1279 const wxArrayString& exts = filetype.GetExtensions();
1280 size_t nExts = exts.GetCount();
1281 for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
1282 if ( nExt > 0 ) {
1283 extensions += wxT(' ');
1284 }
1285 extensions += exts[nExt];
1286 }
1287
1288 AddMimeTypeInfo(filetype.GetMimeType(),
1289 extensions,
1290 filetype.GetDescription());
1291
1292 AddMailcapInfo(filetype.GetMimeType(),
1293 filetype.GetOpenCommand(),
1294 filetype.GetPrintCommand(),
1295 wxT(""),
1296 filetype.GetDescription());
1297 }
1298
1299 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
1300 const wxString& strExtensions,
1301 const wxString& strDesc)
1302 {
1303 int index = m_aTypes.Index(strMimeType);
1304 if ( index == wxNOT_FOUND ) {
1305 // add a new entry
1306 m_aTypes.Add(strMimeType);
1307 m_aEntries.Add(NULL);
1308 m_aExtensions.Add(strExtensions);
1309 m_aDescriptions.Add(strDesc);
1310 }
1311 else {
1312 // modify an existing one
1313 if ( !strDesc.IsEmpty() ) {
1314 m_aDescriptions[index] = strDesc; // replace old value
1315 }
1316 m_aExtensions[index] += ' ' + strExtensions;
1317 }
1318 }
1319
1320 void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
1321 const wxString& strOpenCmd,
1322 const wxString& strPrintCmd,
1323 const wxString& strTest,
1324 const wxString& strDesc)
1325 {
1326 MailCapEntry *entry = new MailCapEntry(strOpenCmd, strPrintCmd, strTest);
1327
1328 int nIndex = m_aTypes.Index(strType);
1329 if ( nIndex == wxNOT_FOUND ) {
1330 // new file type
1331 m_aTypes.Add(strType);
1332
1333 m_aEntries.Add(entry);
1334 m_aExtensions.Add(wxT(""));
1335 m_aDescriptions.Add(strDesc);
1336 }
1337 else {
1338 // always append the entry in the tail of the list - info added with
1339 // this function can only come from AddFallbacks()
1340 MailCapEntry *entryOld = m_aEntries[nIndex];
1341 if ( entryOld )
1342 entry->Append(entryOld);
1343 else
1344 m_aEntries[nIndex] = entry;
1345 }
1346 }
1347
1348 bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
1349 {
1350 wxLogTrace(wxT("--- Parsing mime.types file '%s' ---"), strFileName.c_str());
1351
1352 wxTextFile file(strFileName);
1353 if ( !file.Open() )
1354 return FALSE;
1355
1356 // the information we extract
1357 wxString strMimeType, strDesc, strExtensions;
1358
1359 size_t nLineCount = file.GetLineCount();
1360 const wxChar *pc = NULL;
1361 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1362 if ( pc == NULL ) {
1363 // now we're at the start of the line
1364 pc = file[nLine].c_str();
1365 }
1366 else {
1367 // we didn't finish with the previous line yet
1368 nLine--;
1369 }
1370
1371 // skip whitespace
1372 while ( wxIsspace(*pc) )
1373 pc++;
1374
1375 // comment?
1376 if ( *pc == wxT('#') ) {
1377 // skip the whole line
1378 pc = NULL;
1379 continue;
1380 }
1381
1382 // detect file format
1383 const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
1384 if ( pEqualSign == NULL ) {
1385 // brief format
1386 // ------------
1387
1388 // first field is mime type
1389 for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
1390 strMimeType += *pc;
1391 }
1392
1393 // skip whitespace
1394 while ( wxIsspace(*pc) )
1395 pc++;
1396
1397 // take all the rest of the string
1398 strExtensions = pc;
1399
1400 // no description...
1401 strDesc.Empty();
1402 }
1403 else {
1404 // expanded format
1405 // ---------------
1406
1407 // the string on the left of '=' is the field name
1408 wxString strLHS(pc, pEqualSign - pc);
1409
1410 // eat whitespace
1411 for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
1412 ;
1413
1414 const wxChar *pEnd;
1415 if ( *pc == wxT('"') ) {
1416 // the string is quoted and ends at the matching quote
1417 pEnd = wxStrchr(++pc, wxT('"'));
1418 if ( pEnd == NULL ) {
1419 wxLogWarning(_("Mime.types file %s, line %d: unterminated "
1420 "quoted string."),
1421 strFileName.c_str(), nLine + 1);
1422 }
1423 }
1424 else {
1425 // unquoted string ends at the first space
1426 for ( pEnd = pc; !wxIsspace(*pEnd); pEnd++ )
1427 ;
1428 }
1429
1430 // now we have the RHS (field value)
1431 wxString strRHS(pc, pEnd - pc);
1432
1433 // check what follows this entry
1434 if ( *pEnd == wxT('"') ) {
1435 // skip this quote
1436 pEnd++;
1437 }
1438
1439 for ( pc = pEnd; wxIsspace(*pc); pc++ )
1440 ;
1441
1442 // if there is something left, it may be either a '\\' to continue
1443 // the line or the next field of the same entry
1444 bool entryEnded = *pc == wxT('\0'),
1445 nextFieldOnSameLine = FALSE;
1446 if ( !entryEnded ) {
1447 nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
1448 }
1449
1450 // now see what we got
1451 if ( strLHS == wxT("type") ) {
1452 strMimeType = strRHS;
1453 }
1454 else if ( strLHS == wxT("desc") ) {
1455 strDesc = strRHS;
1456 }
1457 else if ( strLHS == wxT("exts") ) {
1458 strExtensions = strRHS;
1459 }
1460 else {
1461 wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
1462 strFileName.c_str(), nLine + 1, strLHS.c_str());
1463 }
1464
1465 if ( !entryEnded ) {
1466 if ( !nextFieldOnSameLine )
1467 pc = NULL;
1468 //else: don't reset it
1469
1470 // as we don't reset strMimeType, the next field in this entry
1471 // will be interpreted correctly.
1472
1473 continue;
1474 }
1475 }
1476
1477 // although it doesn't seem to be covered by RFCs, some programs
1478 // (notably Netscape) create their entries with several comma
1479 // separated extensions (RFC mention the spaces only)
1480 strExtensions.Replace(wxT(","), wxT(" "));
1481
1482 // also deal with the leading dot
1483 if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
1484 {
1485 strExtensions.erase(0, 1);
1486 }
1487
1488 AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
1489
1490 // finished with this line
1491 pc = NULL;
1492 }
1493
1494 // check our data integriry
1495 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1496 m_aTypes.Count() == m_aExtensions.Count() &&
1497 m_aTypes.Count() == m_aDescriptions.Count() );
1498
1499 return TRUE;
1500 }
1501
1502 bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
1503 bool fallback)
1504 {
1505 wxLogTrace(wxT("--- Parsing mailcap file '%s' ---"), strFileName.c_str());
1506
1507 wxTextFile file(strFileName);
1508 if ( !file.Open() )
1509 return FALSE;
1510
1511 // see the comments near the end of function for the reason we need these
1512 // variables (search for the next occurence of them)
1513 // indices of MIME types (in m_aTypes) we already found in this file
1514 wxArrayInt aEntryIndices;
1515 // aLastIndices[n] is the index of last element in
1516 // m_aEntries[aEntryIndices[n]] from this file
1517 wxArrayInt aLastIndices;
1518
1519 size_t nLineCount = file.GetLineCount();
1520 for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
1521 // now we're at the start of the line
1522 const wxChar *pc = file[nLine].c_str();
1523
1524 // skip whitespace
1525 while ( wxIsspace(*pc) )
1526 pc++;
1527
1528 // comment or empty string?
1529 if ( *pc == wxT('#') || *pc == wxT('\0') )
1530 continue;
1531
1532 // no, do parse
1533
1534 // what field are we currently in? The first 2 are fixed and there may
1535 // be an arbitrary number of other fields -- currently, we are not
1536 // interested in any of them, but we should parse them as well...
1537 enum
1538 {
1539 Field_Type,
1540 Field_OpenCmd,
1541 Field_Other
1542 } currentToken = Field_Type;
1543
1544 // the flags and field values on the current line
1545 bool needsterminal = FALSE,
1546 copiousoutput = FALSE;
1547 wxString strType,
1548 strOpenCmd,
1549 strPrintCmd,
1550 strTest,
1551 strDesc,
1552 curField; // accumulator
1553 for ( bool cont = TRUE; cont; pc++ ) {
1554 switch ( *pc ) {
1555 case wxT('\\'):
1556 // interpret the next character literally (notice that
1557 // backslash can be used for line continuation)
1558 if ( *++pc == wxT('\0') ) {
1559 // fetch the next line.
1560
1561 // pc currently points to nowhere, but after the next
1562 // pc++ in the for line it will point to the beginning
1563 // of the next line in the file
1564 pc = file[++nLine].c_str() - 1;
1565 }
1566 else {
1567 // just a normal character
1568 curField += *pc;
1569 }
1570 break;
1571
1572 case wxT('\0'):
1573 cont = FALSE; // end of line reached, exit the loop
1574
1575 // fall through
1576
1577 case wxT(';'):
1578 // store this field and start looking for the next one
1579
1580 // trim whitespaces from both sides
1581 curField.Trim(TRUE).Trim(FALSE);
1582
1583 switch ( currentToken ) {
1584 case Field_Type:
1585 strType = curField;
1586 if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
1587 // we interpret "type" as "type/*"
1588 strType += wxT("/*");
1589 }
1590
1591 currentToken = Field_OpenCmd;
1592 break;
1593
1594 case Field_OpenCmd:
1595 strOpenCmd = curField;
1596
1597 currentToken = Field_Other;
1598 break;
1599
1600 case Field_Other:
1601 {
1602 // "good" mailcap entry?
1603 bool ok = TRUE;
1604
1605 // is this something of the form foo=bar?
1606 const wxChar *pEq = wxStrchr(curField, wxT('='));
1607 if ( pEq != NULL ) {
1608 wxString lhs = curField.BeforeFirst(wxT('=')),
1609 rhs = curField.AfterFirst(wxT('='));
1610
1611 lhs.Trim(TRUE); // from right
1612 rhs.Trim(FALSE); // from left
1613
1614 if ( lhs == wxT("print") )
1615 strPrintCmd = rhs;
1616 else if ( lhs == wxT("test") )
1617 strTest = rhs;
1618 else if ( lhs == wxT("description") ) {
1619 // it might be quoted
1620 if ( rhs[0u] == wxT('"') &&
1621 rhs.Last() == wxT('"') ) {
1622 strDesc = wxString(rhs.c_str() + 1,
1623 rhs.Len() - 2);
1624 }
1625 else {
1626 strDesc = rhs;
1627 }
1628 }
1629 else if ( lhs == wxT("compose") ||
1630 lhs == wxT("composetyped") ||
1631 lhs == wxT("notes") ||
1632 lhs == wxT("edit") )
1633 ; // ignore
1634 else
1635 ok = FALSE;
1636
1637 }
1638 else {
1639 // no, it's a simple flag
1640 // TODO support the flags:
1641 // 1. create an xterm for 'needsterminal'
1642 // 2. append "| $PAGER" for 'copiousoutput'
1643 if ( curField == wxT("needsterminal") )
1644 needsterminal = TRUE;
1645 else if ( curField == wxT("copiousoutput") )
1646 copiousoutput = TRUE;
1647 else if ( curField == wxT("textualnewlines") )
1648 ; // ignore
1649 else
1650 ok = FALSE;
1651 }
1652
1653 if ( !ok )
1654 {
1655 // don't flood the user with error messages
1656 // if we don't understand something in his
1657 // mailcap, but give them in debug mode
1658 // because this might be useful for the
1659 // programmer
1660 wxLogDebug
1661 (
1662 wxT("Mailcap file %s, line %d: unknown "
1663 "field '%s' for the MIME type "
1664 "'%s' ignored."),
1665 strFileName.c_str(),
1666 nLine + 1,
1667 curField.c_str(),
1668 strType.c_str()
1669 );
1670 }
1671 }
1672
1673 // it already has this value
1674 //currentToken = Field_Other;
1675 break;
1676
1677 default:
1678 wxFAIL_MSG(wxT("unknown field type in mailcap"));
1679 }
1680
1681 // next token starts immediately after ';'
1682 curField.Empty();
1683 break;
1684
1685 default:
1686 curField += *pc;
1687 }
1688 }
1689
1690 // check that we really read something reasonable
1691 if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
1692 wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
1693 "ignored."),
1694 strFileName.c_str(), nLine + 1);
1695 }
1696 else {
1697 MailCapEntry *entry = new MailCapEntry(strOpenCmd,
1698 strPrintCmd,
1699 strTest);
1700
1701 // NB: because of complications below (we must get entries priority
1702 // right), we can't use AddMailcapInfo() here, unfortunately.
1703 strType.MakeLower();
1704 int nIndex = m_aTypes.Index(strType);
1705 if ( nIndex == wxNOT_FOUND ) {
1706 // new file type
1707 m_aTypes.Add(strType);
1708
1709 m_aEntries.Add(entry);
1710 m_aExtensions.Add(wxT(""));
1711 m_aDescriptions.Add(strDesc);
1712 }
1713 else {
1714 // modify the existing entry: the entries in one and the same
1715 // file are read in top-to-bottom order, i.e. the entries read
1716 // first should be tried before the entries below. However,
1717 // the files read later should override the settings in the
1718 // files read before (except if fallback is TRUE), thus we
1719 // Insert() the new entry to the list if it has already
1720 // occured in _this_ file, but Prepend() it if it occured in
1721 // some of the previous ones and Append() to it in the
1722 // fallback case
1723
1724 if ( fallback ) {
1725 // 'fallback' parameter prevents the entries from this
1726 // file from overriding the other ones - always append
1727 MailCapEntry *entryOld = m_aEntries[nIndex];
1728 if ( entryOld )
1729 entry->Append(entryOld);
1730 else
1731 m_aEntries[nIndex] = entry;
1732 }
1733 else {
1734 int entryIndex = aEntryIndices.Index(nIndex);
1735 if ( entryIndex == wxNOT_FOUND ) {
1736 // first time in this file
1737 aEntryIndices.Add(nIndex);
1738 aLastIndices.Add(0);
1739
1740 entry->Prepend(m_aEntries[nIndex]);
1741 m_aEntries[nIndex] = entry;
1742 }
1743 else {
1744 // not the first time in _this_ file
1745 size_t nEntryIndex = (size_t)entryIndex;
1746 MailCapEntry *entryOld = m_aEntries[nIndex];
1747 if ( entryOld )
1748 entry->Insert(entryOld, aLastIndices[nEntryIndex]);
1749 else
1750 m_aEntries[nIndex] = entry;
1751
1752 // the indices were shifted by 1
1753 aLastIndices[nEntryIndex]++;
1754 }
1755 }
1756
1757 if ( !strDesc.IsEmpty() ) {
1758 // replace the old one - what else can we do??
1759 m_aDescriptions[nIndex] = strDesc;
1760 }
1761 }
1762 }
1763
1764 // check our data integriry
1765 wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
1766 m_aTypes.Count() == m_aExtensions.Count() &&
1767 m_aTypes.Count() == m_aDescriptions.Count() );
1768 }
1769
1770 return TRUE;
1771 }
1772
1773 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
1774 {
1775 mimetypes = m_aTypes;
1776
1777 return m_aTypes.GetCount();
1778 }
1779
1780 #endif
1781 // OS type
1782
1783 #endif
1784 // wxUSE_FILE && wxUSE_TEXTFILE
1785
1786 #endif
1787 // __WIN16__