Update OpenVMS makefile
[wxWidgets.git] / src / common / mimecmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/mimecmn.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Chris Elliott (biol75@york.ac.uk) 5 Dec 00: write support for Win32
7 // Created: 23.09.98
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_MIMETYPE
28
29 #include "wx/mimetype.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/dynarray.h"
33 #include "wx/string.h"
34 #include "wx/intl.h"
35 #include "wx/log.h"
36 #include "wx/module.h"
37 #include "wx/crt.h"
38 #endif //WX_PRECOMP
39
40 #include "wx/file.h"
41 #include "wx/iconloc.h"
42 #include "wx/confbase.h"
43
44 // other standard headers
45 #include <ctype.h>
46
47 // implementation classes:
48 #if defined(__WINDOWS__)
49 #include "wx/msw/mimetype.h"
50 #elif ( defined(__DARWIN__) )
51 #include "wx/osx/mimetype.h"
52 #elif defined(__WXPM__) || defined (__EMX__)
53 #include "wx/os2/mimetype.h"
54 #undef __UNIX__
55 #elif defined(__DOS__)
56 #include "wx/msdos/mimetype.h"
57 #else // Unix
58 #include "wx/unix/mimetype.h"
59 #endif
60
61 // ============================================================================
62 // common classes
63 // ============================================================================
64
65 // ----------------------------------------------------------------------------
66 // wxMimeTypeCommands
67 // ----------------------------------------------------------------------------
68
69 void
70 wxMimeTypeCommands::AddOrReplaceVerb(const wxString& verb, const wxString& cmd)
71 {
72 int n = m_verbs.Index(verb, false /* ignore case */);
73 if ( n == wxNOT_FOUND )
74 {
75 m_verbs.Add(verb);
76 m_commands.Add(cmd);
77 }
78 else
79 {
80 m_commands[n] = cmd;
81 }
82 }
83
84 wxString
85 wxMimeTypeCommands::GetCommandForVerb(const wxString& verb, size_t *idx) const
86 {
87 wxString s;
88
89 int n = m_verbs.Index(verb);
90 if ( n != wxNOT_FOUND )
91 {
92 s = m_commands[(size_t)n];
93 if ( idx )
94 *idx = n;
95 }
96 else if ( idx )
97 {
98 // different from any valid index
99 *idx = (size_t)-1;
100 }
101
102 return s;
103 }
104
105 wxString wxMimeTypeCommands::GetVerbCmd(size_t n) const
106 {
107 return m_verbs[n] + wxT('=') + m_commands[n];
108 }
109
110 // ----------------------------------------------------------------------------
111 // wxFileTypeInfo
112 // ----------------------------------------------------------------------------
113
114 void wxFileTypeInfo::DoVarArgInit(const wxString& mimeType,
115 const wxString& openCmd,
116 const wxString& printCmd,
117 const wxString& desc,
118 va_list argptr)
119 {
120 m_mimeType = mimeType;
121 m_openCmd = openCmd;
122 m_printCmd = printCmd;
123 m_desc = desc;
124
125 for ( ;; )
126 {
127 // icc gives this warning in its own va_arg() macro, argh
128 #ifdef __INTELC__
129 #pragma warning(push)
130 #pragma warning(disable: 1684)
131 #endif
132
133 wxArgNormalizedString ext(WX_VA_ARG_STRING(argptr));
134
135 #ifdef __INTELC__
136 #pragma warning(pop)
137 #endif
138 if ( !ext )
139 {
140 // NULL terminates the list
141 break;
142 }
143
144 m_exts.Add(ext.GetString());
145 }
146 }
147
148 void wxFileTypeInfo::VarArgInit(const wxString *mimeType,
149 const wxString *openCmd,
150 const wxString *printCmd,
151 const wxString *desc,
152 ...)
153 {
154 va_list argptr;
155 va_start(argptr, desc);
156
157 DoVarArgInit(*mimeType, *openCmd, *printCmd, *desc, argptr);
158
159 va_end(argptr);
160 }
161
162
163 wxFileTypeInfo::wxFileTypeInfo(const wxArrayString& sArray)
164 {
165 m_mimeType = sArray [0u];
166 m_openCmd = sArray [1u];
167 m_printCmd = sArray [2u];
168 m_desc = sArray [3u];
169
170 size_t count = sArray.GetCount();
171 for ( size_t i = 4; i < count; i++ )
172 {
173 m_exts.Add(sArray[i]);
174 }
175 }
176
177 #include "wx/arrimpl.cpp"
178 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo)
179
180 // ============================================================================
181 // implementation of the wrapper classes
182 // ============================================================================
183
184 // ----------------------------------------------------------------------------
185 // wxFileType
186 // ----------------------------------------------------------------------------
187
188 /* static */
189 wxString wxFileType::ExpandCommand(const wxString& command,
190 const wxFileType::MessageParameters& params)
191 {
192 bool hasFilename = false;
193
194 // We consider that only the file names with spaces in them need to be
195 // handled specially. This is not perfect, but this can be done easily
196 // under all platforms while handling the file names with quotes in them,
197 // for example, needs to be done differently.
198 const bool needToQuoteFilename = params.GetFileName().find_first_of(" \t")
199 != wxString::npos;
200
201 wxString str;
202 for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
203 if ( *pc == wxT('%') ) {
204 switch ( *++pc ) {
205 case wxT('s'):
206 // don't quote the file name if it's already quoted: notice
207 // that we check for a quote following it and not preceding
208 // it as at least under Windows we can have commands
209 // containing "file://%s" (with quotes) in them so the
210 // argument may be quoted even if there is no quote
211 // directly before "%s" itself
212 if ( needToQuoteFilename && pc[1] != '"' )
213 str << wxT('"') << params.GetFileName() << wxT('"');
214 else
215 str << params.GetFileName();
216 hasFilename = true;
217 break;
218
219 case wxT('t'):
220 // '%t' expands into MIME type (quote it too just to be
221 // consistent)
222 str << wxT('\'') << params.GetMimeType() << wxT('\'');
223 break;
224
225 case wxT('{'):
226 {
227 const wxChar *pEnd = wxStrchr(pc, wxT('}'));
228 if ( pEnd == NULL ) {
229 wxString mimetype;
230 wxLogWarning(_("Unmatched '{' in an entry for mime type %s."),
231 params.GetMimeType().c_str());
232 str << wxT("%{");
233 }
234 else {
235 wxString param(pc + 1, pEnd - pc - 1);
236 str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
237 pc = pEnd;
238 }
239 }
240 break;
241
242 case wxT('n'):
243 case wxT('F'):
244 // TODO %n is the number of parts, %F is an array containing
245 // the names of temp files these parts were written to
246 // and their mime types.
247 break;
248
249 default:
250 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
251 *pc, command.c_str());
252 str << *pc;
253 }
254 }
255 else {
256 str << *pc;
257 }
258 }
259
260 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
261 // the program will accept the data on stdin so normally we should append
262 // "< %s" to the end of the command in such case, but not all commands
263 // behave like this, in particular a common test is 'test -n "$DISPLAY"'
264 // and appending "< %s" to this command makes the test fail... I don't
265 // know of the correct solution, try to guess what we have to do.
266
267 // test now carried out on reading file so test should never get here
268 if ( !hasFilename && !str.empty()
269 #ifdef __UNIX__
270 && !str.StartsWith(wxT("test "))
271 #endif // Unix
272 )
273 {
274 str << wxT(" < ");
275 if ( needToQuoteFilename )
276 str << '"';
277 str << params.GetFileName();
278 if ( needToQuoteFilename )
279 str << '"';
280 }
281
282 return str;
283 }
284
285 wxFileType::wxFileType(const wxFileTypeInfo& info)
286 {
287 m_info = &info;
288 m_impl = NULL;
289 }
290
291 wxFileType::wxFileType()
292 {
293 m_info = NULL;
294 m_impl = new wxFileTypeImpl;
295 }
296
297 wxFileType::~wxFileType()
298 {
299 if ( m_impl )
300 delete m_impl;
301 }
302
303 bool wxFileType::GetExtensions(wxArrayString& extensions)
304 {
305 if ( m_info )
306 {
307 extensions = m_info->GetExtensions();
308 return true;
309 }
310
311 return m_impl->GetExtensions(extensions);
312 }
313
314 bool wxFileType::GetMimeType(wxString *mimeType) const
315 {
316 wxCHECK_MSG( mimeType, false, wxT("invalid parameter in GetMimeType") );
317
318 if ( m_info )
319 {
320 *mimeType = m_info->GetMimeType();
321
322 return true;
323 }
324
325 return m_impl->GetMimeType(mimeType);
326 }
327
328 bool wxFileType::GetMimeTypes(wxArrayString& mimeTypes) const
329 {
330 if ( m_info )
331 {
332 mimeTypes.Clear();
333 mimeTypes.Add(m_info->GetMimeType());
334
335 return true;
336 }
337
338 return m_impl->GetMimeTypes(mimeTypes);
339 }
340
341 bool wxFileType::GetIcon(wxIconLocation *iconLoc) const
342 {
343 if ( m_info )
344 {
345 if ( iconLoc )
346 {
347 iconLoc->SetFileName(m_info->GetIconFile());
348 #ifdef __WINDOWS__
349 iconLoc->SetIndex(m_info->GetIconIndex());
350 #endif // __WINDOWS__
351 }
352
353 return true;
354 }
355
356 return m_impl->GetIcon(iconLoc);
357 }
358
359 bool
360 wxFileType::GetIcon(wxIconLocation *iconloc,
361 const MessageParameters& params) const
362 {
363 if ( !GetIcon(iconloc) )
364 {
365 return false;
366 }
367
368 // we may have "%s" in the icon location string, at least under Windows, so
369 // expand this
370 if ( iconloc )
371 {
372 iconloc->SetFileName(ExpandCommand(iconloc->GetFileName(), params));
373 }
374
375 return true;
376 }
377
378 bool wxFileType::GetDescription(wxString *desc) const
379 {
380 wxCHECK_MSG( desc, false, wxT("invalid parameter in GetDescription") );
381
382 if ( m_info )
383 {
384 *desc = m_info->GetDescription();
385
386 return true;
387 }
388
389 return m_impl->GetDescription(desc);
390 }
391
392 bool
393 wxFileType::GetOpenCommand(wxString *openCmd,
394 const wxFileType::MessageParameters& params) const
395 {
396 wxCHECK_MSG( openCmd, false, wxT("invalid parameter in GetOpenCommand") );
397
398 if ( m_info )
399 {
400 *openCmd = ExpandCommand(m_info->GetOpenCommand(), params);
401
402 return true;
403 }
404
405 return m_impl->GetOpenCommand(openCmd, params);
406 }
407
408 wxString wxFileType::GetOpenCommand(const wxString& filename) const
409 {
410 wxString cmd;
411 if ( !GetOpenCommand(&cmd, filename) )
412 {
413 // return empty string to indicate an error
414 cmd.clear();
415 }
416
417 return cmd;
418 }
419
420 bool
421 wxFileType::GetPrintCommand(wxString *printCmd,
422 const wxFileType::MessageParameters& params) const
423 {
424 wxCHECK_MSG( printCmd, false, wxT("invalid parameter in GetPrintCommand") );
425
426 if ( m_info )
427 {
428 *printCmd = ExpandCommand(m_info->GetPrintCommand(), params);
429
430 return true;
431 }
432
433 return m_impl->GetPrintCommand(printCmd, params);
434 }
435
436
437 size_t wxFileType::GetAllCommands(wxArrayString *verbs,
438 wxArrayString *commands,
439 const wxFileType::MessageParameters& params) const
440 {
441 if ( verbs )
442 verbs->Clear();
443 if ( commands )
444 commands->Clear();
445
446 #if defined (__WINDOWS__) || defined(__UNIX__)
447 return m_impl->GetAllCommands(verbs, commands, params);
448 #else // !__WINDOWS__ || __UNIX__
449 // we don't know how to retrieve all commands, so just try the 2 we know
450 // about
451 size_t count = 0;
452 wxString cmd;
453 if ( GetOpenCommand(&cmd, params) )
454 {
455 if ( verbs )
456 verbs->Add(wxT("Open"));
457 if ( commands )
458 commands->Add(cmd);
459 count++;
460 }
461
462 if ( GetPrintCommand(&cmd, params) )
463 {
464 if ( verbs )
465 verbs->Add(wxT("Print"));
466 if ( commands )
467 commands->Add(cmd);
468
469 count++;
470 }
471
472 return count;
473 #endif // __WINDOWS__/| __UNIX__
474 }
475
476 bool wxFileType::Unassociate()
477 {
478 #if defined(__WINDOWS__)
479 return m_impl->Unassociate();
480 #elif defined(__UNIX__)
481 return m_impl->Unassociate(this);
482 #else
483 wxFAIL_MSG( wxT("not implemented") ); // TODO
484 return false;
485 #endif
486 }
487
488 bool wxFileType::SetCommand(const wxString& cmd,
489 const wxString& verb,
490 bool overwriteprompt)
491 {
492 #if defined (__WINDOWS__) || defined(__UNIX__)
493 return m_impl->SetCommand(cmd, verb, overwriteprompt);
494 #else
495 wxUnusedVar(cmd);
496 wxUnusedVar(verb);
497 wxUnusedVar(overwriteprompt);
498 wxFAIL_MSG(wxT("not implemented"));
499 return false;
500 #endif
501 }
502
503 bool wxFileType::SetDefaultIcon(const wxString& cmd, int index)
504 {
505 wxString sTmp = cmd;
506 #ifdef __WINDOWS__
507 // VZ: should we do this?
508 // chris elliott : only makes sense in MS windows
509 if ( sTmp.empty() )
510 GetOpenCommand(&sTmp, wxFileType::MessageParameters(wxEmptyString, wxEmptyString));
511 #endif
512 wxCHECK_MSG( !sTmp.empty(), false, wxT("need the icon file") );
513
514 #if defined (__WINDOWS__) || defined(__UNIX__)
515 return m_impl->SetDefaultIcon (cmd, index);
516 #else
517 wxUnusedVar(index);
518 wxFAIL_MSG(wxT("not implemented"));
519 return false;
520 #endif
521 }
522
523 // ----------------------------------------------------------------------------
524 // wxMimeTypesManagerFactory
525 // ----------------------------------------------------------------------------
526
527 wxMimeTypesManagerFactory *wxMimeTypesManagerFactory::m_factory = NULL;
528
529 /* static */
530 void wxMimeTypesManagerFactory::Set(wxMimeTypesManagerFactory *factory)
531 {
532 delete m_factory;
533
534 m_factory = factory;
535 }
536
537 /* static */
538 wxMimeTypesManagerFactory *wxMimeTypesManagerFactory::Get()
539 {
540 if ( !m_factory )
541 m_factory = new wxMimeTypesManagerFactory;
542
543 return m_factory;
544 }
545
546 wxMimeTypesManagerImpl *wxMimeTypesManagerFactory::CreateMimeTypesManagerImpl()
547 {
548 return new wxMimeTypesManagerImpl;
549 }
550
551 // ----------------------------------------------------------------------------
552 // wxMimeTypesManager
553 // ----------------------------------------------------------------------------
554
555 void wxMimeTypesManager::EnsureImpl()
556 {
557 if ( !m_impl )
558 m_impl = wxMimeTypesManagerFactory::Get()->CreateMimeTypesManagerImpl();
559 }
560
561 bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
562 const wxString& wildcard)
563 {
564 wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
565 wxT("first MIME type can't contain wildcards") );
566
567 // all comparaisons are case insensitive (2nd arg of IsSameAs() is false)
568 if ( wildcard.BeforeFirst(wxT('/')).
569 IsSameAs(mimeType.BeforeFirst(wxT('/')), false) )
570 {
571 wxString strSubtype = wildcard.AfterFirst(wxT('/'));
572
573 if ( strSubtype == wxT("*") ||
574 strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), false) )
575 {
576 // matches (either exactly or it's a wildcard)
577 return true;
578 }
579 }
580
581 return false;
582 }
583
584 wxMimeTypesManager::wxMimeTypesManager()
585 {
586 m_impl = NULL;
587 }
588
589 wxMimeTypesManager::~wxMimeTypesManager()
590 {
591 if ( m_impl )
592 delete m_impl;
593 }
594
595 bool wxMimeTypesManager::Unassociate(wxFileType *ft)
596 {
597 EnsureImpl();
598
599 #if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
600 return m_impl->Unassociate(ft);
601 #else
602 return ft->Unassociate();
603 #endif
604 }
605
606
607 wxFileType *
608 wxMimeTypesManager::Associate(const wxFileTypeInfo& ftInfo)
609 {
610 EnsureImpl();
611
612 #if defined(__WINDOWS__) || defined(__UNIX__)
613 return m_impl->Associate(ftInfo);
614 #else // other platforms
615 wxUnusedVar(ftInfo);
616 wxFAIL_MSG( wxT("not implemented") ); // TODO
617 return NULL;
618 #endif // platforms
619 }
620
621 wxFileType *
622 wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
623 {
624 EnsureImpl();
625
626 wxString::const_iterator i = ext.begin();
627 const wxString::const_iterator end = ext.end();
628 wxString extWithoutDot;
629 if ( i != end && *i == '.' )
630 extWithoutDot.assign(++i, ext.end());
631 else
632 extWithoutDot = ext;
633
634 wxCHECK_MSG( !ext.empty(), NULL, wxT("extension can't be empty") );
635
636 wxFileType *ft = m_impl->GetFileTypeFromExtension(extWithoutDot);
637
638 if ( !ft ) {
639 // check the fallbacks
640 //
641 // TODO linear search is potentially slow, perhaps we should use a
642 // sorted array?
643 size_t count = m_fallbacks.GetCount();
644 for ( size_t n = 0; n < count; n++ ) {
645 if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
646 ft = new wxFileType(m_fallbacks[n]);
647
648 break;
649 }
650 }
651 }
652
653 return ft;
654 }
655
656 wxFileType *
657 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
658 {
659 EnsureImpl();
660 wxFileType *ft = m_impl->GetFileTypeFromMimeType(mimeType);
661
662 if ( !ft ) {
663 // check the fallbacks
664 //
665 // TODO linear search is potentially slow, perhaps we should use a
666 // sorted array?
667 size_t count = m_fallbacks.GetCount();
668 for ( size_t n = 0; n < count; n++ ) {
669 if ( wxMimeTypesManager::IsOfType(mimeType,
670 m_fallbacks[n].GetMimeType()) ) {
671 ft = new wxFileType(m_fallbacks[n]);
672
673 break;
674 }
675 }
676 }
677
678 return ft;
679 }
680
681 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
682 {
683 EnsureImpl();
684 for ( const wxFileTypeInfo *ft = filetypes; ft && ft->IsValid(); ft++ ) {
685 AddFallback(*ft);
686 }
687 }
688
689 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
690 {
691 EnsureImpl();
692 size_t countAll = m_impl->EnumAllFileTypes(mimetypes);
693
694 // add the fallback filetypes
695 size_t count = m_fallbacks.GetCount();
696 for ( size_t n = 0; n < count; n++ ) {
697 if ( mimetypes.Index(m_fallbacks[n].GetMimeType()) == wxNOT_FOUND ) {
698 mimetypes.Add(m_fallbacks[n].GetMimeType());
699 countAll++;
700 }
701 }
702
703 return countAll;
704 }
705
706 void wxMimeTypesManager::Initialize(int mcapStyle,
707 const wxString& sExtraDir)
708 {
709 #if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
710 EnsureImpl();
711
712 m_impl->Initialize(mcapStyle, sExtraDir);
713 #else
714 (void)mcapStyle;
715 (void)sExtraDir;
716 #endif // Unix
717 }
718
719 // and this function clears all the data from the manager
720 void wxMimeTypesManager::ClearData()
721 {
722 #if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
723 EnsureImpl();
724
725 m_impl->ClearData();
726 #endif // Unix
727 }
728
729 // ----------------------------------------------------------------------------
730 // global data and wxMimeTypeCmnModule
731 // ----------------------------------------------------------------------------
732
733 // private object
734 static wxMimeTypesManager gs_mimeTypesManager;
735
736 // and public pointer
737 wxMimeTypesManager *wxTheMimeTypesManager = &gs_mimeTypesManager;
738
739 class wxMimeTypeCmnModule: public wxModule
740 {
741 public:
742 wxMimeTypeCmnModule() : wxModule() { }
743
744 virtual bool OnInit() { return true; }
745 virtual void OnExit()
746 {
747 wxMimeTypesManagerFactory::Set(NULL);
748
749 if ( gs_mimeTypesManager.m_impl != NULL )
750 {
751 wxDELETE(gs_mimeTypesManager.m_impl);
752 gs_mimeTypesManager.m_fallbacks.Clear();
753 }
754 }
755
756 DECLARE_DYNAMIC_CLASS(wxMimeTypeCmnModule)
757 };
758
759 IMPLEMENT_DYNAMIC_CLASS(wxMimeTypeCmnModule, wxModule)
760
761 #endif // wxUSE_MIMETYPE