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