]> git.saurik.com Git - wxWidgets.git/blob - src/common/mimecmn.cpp
ensure that the copies of the bitmap passed to wxMemoryDC ctor are not modified when...
[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 // 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__) && wxOSX_USE_CARBON )
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
70 void
71 wxMimeTypeCommands::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
85 wxString
86 wxMimeTypeCommands::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
106 wxString wxMimeTypeCommands::GetVerbCmd(size_t n) const
107 {
108 return m_verbs[n] + wxT('=') + m_commands[n];
109 }
110
111 // ----------------------------------------------------------------------------
112 // wxFileTypeInfo
113 // ----------------------------------------------------------------------------
114
115 void 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
149 void 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
164 wxFileTypeInfo::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"
179 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo)
180
181 // ============================================================================
182 // implementation of the wrapper classes
183 // ============================================================================
184
185 // ----------------------------------------------------------------------------
186 // wxFileType
187 // ----------------------------------------------------------------------------
188
189 /* static */
190 wxString wxFileType::ExpandCommand(const wxString& command,
191 const wxFileType::MessageParameters& params)
192 {
193 bool hasFilename = false;
194
195 wxString str;
196 for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
197 if ( *pc == wxT('%') ) {
198 switch ( *++pc ) {
199 case wxT('s'):
200 // '%s' expands into file name (quoted because it might
201 // contain spaces) - except if there are already quotes
202 // there because otherwise some programs may get confused
203 // by double double quotes
204 #if 0
205 if ( *(pc - 2) == wxT('"') )
206 str << params.GetFileName();
207 else
208 str << wxT('"') << params.GetFileName() << wxT('"');
209 #endif
210 str << params.GetFileName();
211 hasFilename = true;
212 break;
213
214 case wxT('t'):
215 // '%t' expands into MIME type (quote it too just to be
216 // consistent)
217 str << wxT('\'') << params.GetMimeType() << wxT('\'');
218 break;
219
220 case wxT('{'):
221 {
222 const wxChar *pEnd = wxStrchr(pc, wxT('}'));
223 if ( pEnd == NULL ) {
224 wxString mimetype;
225 wxLogWarning(_("Unmatched '{' in an entry for mime type %s."),
226 params.GetMimeType().c_str());
227 str << wxT("%{");
228 }
229 else {
230 wxString param(pc + 1, pEnd - pc - 1);
231 str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
232 pc = pEnd;
233 }
234 }
235 break;
236
237 case wxT('n'):
238 case wxT('F'):
239 // TODO %n is the number of parts, %F is an array containing
240 // the names of temp files these parts were written to
241 // and their mime types.
242 break;
243
244 default:
245 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
246 *pc, command.c_str());
247 str << *pc;
248 }
249 }
250 else {
251 str << *pc;
252 }
253 }
254
255 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
256 // the program will accept the data on stdin so normally we should append
257 // "< %s" to the end of the command in such case, but not all commands
258 // behave like this, in particular a common test is 'test -n "$DISPLAY"'
259 // and appending "< %s" to this command makes the test fail... I don't
260 // know of the correct solution, try to guess what we have to do.
261
262 // test now carried out on reading file so test should never get here
263 if ( !hasFilename && !str.empty()
264 #ifdef __UNIX__
265 && !str.StartsWith(_T("test "))
266 #endif // Unix
267 ) {
268 str << wxT(" < '") << params.GetFileName() << wxT('\'');
269 }
270
271 return str;
272 }
273
274 wxFileType::wxFileType(const wxFileTypeInfo& info)
275 {
276 m_info = &info;
277 m_impl = NULL;
278 }
279
280 wxFileType::wxFileType()
281 {
282 m_info = NULL;
283 m_impl = new wxFileTypeImpl;
284 }
285
286 wxFileType::~wxFileType()
287 {
288 if ( m_impl )
289 delete m_impl;
290 }
291
292 bool wxFileType::GetExtensions(wxArrayString& extensions)
293 {
294 if ( m_info )
295 {
296 extensions = m_info->GetExtensions();
297 return true;
298 }
299
300 return m_impl->GetExtensions(extensions);
301 }
302
303 bool wxFileType::GetMimeType(wxString *mimeType) const
304 {
305 wxCHECK_MSG( mimeType, false, _T("invalid parameter in GetMimeType") );
306
307 if ( m_info )
308 {
309 *mimeType = m_info->GetMimeType();
310
311 return true;
312 }
313
314 return m_impl->GetMimeType(mimeType);
315 }
316
317 bool wxFileType::GetMimeTypes(wxArrayString& mimeTypes) const
318 {
319 if ( m_info )
320 {
321 mimeTypes.Clear();
322 mimeTypes.Add(m_info->GetMimeType());
323
324 return true;
325 }
326
327 return m_impl->GetMimeTypes(mimeTypes);
328 }
329
330 bool wxFileType::GetIcon(wxIconLocation *iconLoc) const
331 {
332 if ( m_info )
333 {
334 if ( iconLoc )
335 {
336 iconLoc->SetFileName(m_info->GetIconFile());
337 #ifdef __WXMSW__
338 iconLoc->SetIndex(m_info->GetIconIndex());
339 #endif // __WXMSW__
340 }
341
342 return true;
343 }
344
345 return m_impl->GetIcon(iconLoc);
346 }
347
348 bool
349 wxFileType::GetIcon(wxIconLocation *iconloc,
350 const MessageParameters& params) const
351 {
352 if ( !GetIcon(iconloc) )
353 {
354 return false;
355 }
356
357 // we may have "%s" in the icon location string, at least under Windows, so
358 // expand this
359 if ( iconloc )
360 {
361 iconloc->SetFileName(ExpandCommand(iconloc->GetFileName(), params));
362 }
363
364 return true;
365 }
366
367 bool wxFileType::GetDescription(wxString *desc) const
368 {
369 wxCHECK_MSG( desc, false, _T("invalid parameter in GetDescription") );
370
371 if ( m_info )
372 {
373 *desc = m_info->GetDescription();
374
375 return true;
376 }
377
378 return m_impl->GetDescription(desc);
379 }
380
381 bool
382 wxFileType::GetOpenCommand(wxString *openCmd,
383 const wxFileType::MessageParameters& params) const
384 {
385 wxCHECK_MSG( openCmd, false, _T("invalid parameter in GetOpenCommand") );
386
387 if ( m_info )
388 {
389 *openCmd = ExpandCommand(m_info->GetOpenCommand(), params);
390
391 return true;
392 }
393
394 return m_impl->GetOpenCommand(openCmd, params);
395 }
396
397 wxString wxFileType::GetOpenCommand(const wxString& filename) const
398 {
399 wxString cmd;
400 if ( !GetOpenCommand(&cmd, filename) )
401 {
402 // return empty string to indicate an error
403 cmd.clear();
404 }
405
406 return cmd;
407 }
408
409 bool
410 wxFileType::GetPrintCommand(wxString *printCmd,
411 const wxFileType::MessageParameters& params) const
412 {
413 wxCHECK_MSG( printCmd, false, _T("invalid parameter in GetPrintCommand") );
414
415 if ( m_info )
416 {
417 *printCmd = ExpandCommand(m_info->GetPrintCommand(), params);
418
419 return true;
420 }
421
422 return m_impl->GetPrintCommand(printCmd, params);
423 }
424
425
426 size_t wxFileType::GetAllCommands(wxArrayString *verbs,
427 wxArrayString *commands,
428 const wxFileType::MessageParameters& params) const
429 {
430 if ( verbs )
431 verbs->Clear();
432 if ( commands )
433 commands->Clear();
434
435 #if defined (__WXMSW__) || defined(__UNIX__)
436 return m_impl->GetAllCommands(verbs, commands, params);
437 #else // !__WXMSW__ || Unix
438 // we don't know how to retrieve all commands, so just try the 2 we know
439 // about
440 size_t count = 0;
441 wxString cmd;
442 if ( GetOpenCommand(&cmd, params) )
443 {
444 if ( verbs )
445 verbs->Add(_T("Open"));
446 if ( commands )
447 commands->Add(cmd);
448 count++;
449 }
450
451 if ( GetPrintCommand(&cmd, params) )
452 {
453 if ( verbs )
454 verbs->Add(_T("Print"));
455 if ( commands )
456 commands->Add(cmd);
457
458 count++;
459 }
460
461 return count;
462 #endif // __WXMSW__/| __UNIX__
463 }
464
465 bool wxFileType::Unassociate()
466 {
467 #if defined(__WXMSW__)
468 return m_impl->Unassociate();
469 #elif defined(__UNIX__)
470 return m_impl->Unassociate(this);
471 #else
472 wxFAIL_MSG( _T("not implemented") ); // TODO
473 return false;
474 #endif
475 }
476
477 bool wxFileType::SetCommand(const wxString& cmd,
478 const wxString& verb,
479 bool overwriteprompt)
480 {
481 #if defined (__WXMSW__) || defined(__UNIX__)
482 return m_impl->SetCommand(cmd, verb, overwriteprompt);
483 #else
484 wxUnusedVar(cmd);
485 wxUnusedVar(verb);
486 wxUnusedVar(overwriteprompt);
487 wxFAIL_MSG(_T("not implemented"));
488 return false;
489 #endif
490 }
491
492 bool wxFileType::SetDefaultIcon(const wxString& cmd, int index)
493 {
494 wxString sTmp = cmd;
495 #ifdef __WXMSW__
496 // VZ: should we do this?
497 // chris elliott : only makes sense in MS windows
498 if ( sTmp.empty() )
499 GetOpenCommand(&sTmp, wxFileType::MessageParameters(wxEmptyString, wxEmptyString));
500 #endif
501 wxCHECK_MSG( !sTmp.empty(), false, _T("need the icon file") );
502
503 #if defined (__WXMSW__) || defined(__UNIX__)
504 return m_impl->SetDefaultIcon (cmd, index);
505 #else
506 wxUnusedVar(index);
507 wxFAIL_MSG(_T("not implemented"));
508 return false;
509 #endif
510 }
511
512 // ----------------------------------------------------------------------------
513 // wxMimeTypesManagerFactory
514 // ----------------------------------------------------------------------------
515
516 wxMimeTypesManagerFactory *wxMimeTypesManagerFactory::m_factory = NULL;
517
518 /* static */
519 void wxMimeTypesManagerFactory::Set(wxMimeTypesManagerFactory *factory)
520 {
521 delete m_factory;
522
523 m_factory = factory;
524 }
525
526 /* static */
527 wxMimeTypesManagerFactory *wxMimeTypesManagerFactory::Get()
528 {
529 if ( !m_factory )
530 m_factory = new wxMimeTypesManagerFactory;
531
532 return m_factory;
533 }
534
535 wxMimeTypesManagerImpl *wxMimeTypesManagerFactory::CreateMimeTypesManagerImpl()
536 {
537 return new wxMimeTypesManagerImpl;
538 }
539
540 // ----------------------------------------------------------------------------
541 // wxMimeTypesManager
542 // ----------------------------------------------------------------------------
543
544 void wxMimeTypesManager::EnsureImpl()
545 {
546 if ( !m_impl )
547 m_impl = wxMimeTypesManagerFactory::Get()->CreateMimeTypesManagerImpl();
548 }
549
550 bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
551 const wxString& wildcard)
552 {
553 wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
554 wxT("first MIME type can't contain wildcards") );
555
556 // all comparaisons are case insensitive (2nd arg of IsSameAs() is false)
557 if ( wildcard.BeforeFirst(wxT('/')).
558 IsSameAs(mimeType.BeforeFirst(wxT('/')), false) )
559 {
560 wxString strSubtype = wildcard.AfterFirst(wxT('/'));
561
562 if ( strSubtype == wxT("*") ||
563 strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), false) )
564 {
565 // matches (either exactly or it's a wildcard)
566 return true;
567 }
568 }
569
570 return false;
571 }
572
573 wxMimeTypesManager::wxMimeTypesManager()
574 {
575 m_impl = NULL;
576 }
577
578 wxMimeTypesManager::~wxMimeTypesManager()
579 {
580 if ( m_impl )
581 delete m_impl;
582 }
583
584 bool wxMimeTypesManager::Unassociate(wxFileType *ft)
585 {
586 EnsureImpl();
587
588 #if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
589 return m_impl->Unassociate(ft);
590 #else
591 return ft->Unassociate();
592 #endif
593 }
594
595
596 wxFileType *
597 wxMimeTypesManager::Associate(const wxFileTypeInfo& ftInfo)
598 {
599 EnsureImpl();
600
601 #if defined(__WXMSW__) || defined(__UNIX__)
602 return m_impl->Associate(ftInfo);
603 #else // other platforms
604 wxUnusedVar(ftInfo);
605 wxFAIL_MSG( _T("not implemented") ); // TODO
606 return NULL;
607 #endif // platforms
608 }
609
610 wxFileType *
611 wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
612 {
613 EnsureImpl();
614
615 wxString::const_iterator i = ext.begin();
616 const wxString::const_iterator end = ext.end();
617 wxString extWithoutDot;
618 if ( i != end && *i == '.' )
619 extWithoutDot.assign(++i, ext.end());
620 else
621 extWithoutDot = ext;
622
623 wxCHECK_MSG( !ext.empty(), NULL, _T("extension can't be empty") );
624
625 wxFileType *ft = m_impl->GetFileTypeFromExtension(extWithoutDot);
626
627 if ( !ft ) {
628 // check the fallbacks
629 //
630 // TODO linear search is potentially slow, perhaps we should use a
631 // sorted array?
632 size_t count = m_fallbacks.GetCount();
633 for ( size_t n = 0; n < count; n++ ) {
634 if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
635 ft = new wxFileType(m_fallbacks[n]);
636
637 break;
638 }
639 }
640 }
641
642 return ft;
643 }
644
645 wxFileType *
646 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
647 {
648 EnsureImpl();
649 wxFileType *ft = m_impl->GetFileTypeFromMimeType(mimeType);
650
651 if ( !ft ) {
652 // check the fallbacks
653 //
654 // TODO linear search is potentially slow, perhaps we should use a
655 // sorted array?
656 size_t count = m_fallbacks.GetCount();
657 for ( size_t n = 0; n < count; n++ ) {
658 if ( wxMimeTypesManager::IsOfType(mimeType,
659 m_fallbacks[n].GetMimeType()) ) {
660 ft = new wxFileType(m_fallbacks[n]);
661
662 break;
663 }
664 }
665 }
666
667 return ft;
668 }
669
670 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
671 {
672 EnsureImpl();
673 for ( const wxFileTypeInfo *ft = filetypes; ft && ft->IsValid(); ft++ ) {
674 AddFallback(*ft);
675 }
676 }
677
678 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
679 {
680 EnsureImpl();
681 size_t countAll = m_impl->EnumAllFileTypes(mimetypes);
682
683 // add the fallback filetypes
684 size_t count = m_fallbacks.GetCount();
685 for ( size_t n = 0; n < count; n++ ) {
686 if ( mimetypes.Index(m_fallbacks[n].GetMimeType()) == wxNOT_FOUND ) {
687 mimetypes.Add(m_fallbacks[n].GetMimeType());
688 countAll++;
689 }
690 }
691
692 return countAll;
693 }
694
695 void wxMimeTypesManager::Initialize(int mcapStyle,
696 const wxString& sExtraDir)
697 {
698 #if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
699 EnsureImpl();
700
701 m_impl->Initialize(mcapStyle, sExtraDir);
702 #else
703 (void)mcapStyle;
704 (void)sExtraDir;
705 #endif // Unix
706 }
707
708 // and this function clears all the data from the manager
709 void wxMimeTypesManager::ClearData()
710 {
711 #if defined(__UNIX__) && !defined(__CYGWIN__) && !defined(__WINE__)
712 EnsureImpl();
713
714 m_impl->ClearData();
715 #endif // Unix
716 }
717
718 // ----------------------------------------------------------------------------
719 // global data and wxMimeTypeCmnModule
720 // ----------------------------------------------------------------------------
721
722 // private object
723 static wxMimeTypesManager gs_mimeTypesManager;
724
725 // and public pointer
726 wxMimeTypesManager *wxTheMimeTypesManager = &gs_mimeTypesManager;
727
728 class wxMimeTypeCmnModule: public wxModule
729 {
730 public:
731 wxMimeTypeCmnModule() : wxModule() { }
732
733 virtual bool OnInit() { return true; }
734 virtual void OnExit()
735 {
736 wxMimeTypesManagerFactory::Set(NULL);
737
738 if ( gs_mimeTypesManager.m_impl != NULL )
739 {
740 delete gs_mimeTypesManager.m_impl;
741 gs_mimeTypesManager.m_impl = NULL;
742 gs_mimeTypesManager.m_fallbacks.Clear();
743 }
744 }
745
746 DECLARE_DYNAMIC_CLASS(wxMimeTypeCmnModule)
747 };
748
749 IMPLEMENT_DYNAMIC_CLASS(wxMimeTypeCmnModule, wxModule)
750
751 #endif // wxUSE_MIMETYPE