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