]> git.saurik.com Git - wxWidgets.git/blob - src/common/mimecmn.cpp
Better sizing in wxDataViewSpinRenderer and wxDataViewChoiceRenderer.
[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__) )
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 // 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
286 wxFileType::wxFileType(const wxFileTypeInfo& info)
287 {
288 m_info = &info;
289 m_impl = NULL;
290 }
291
292 wxFileType::wxFileType()
293 {
294 m_info = NULL;
295 m_impl = new wxFileTypeImpl;
296 }
297
298 wxFileType::~wxFileType()
299 {
300 if ( m_impl )
301 delete m_impl;
302 }
303
304 bool 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
315 bool 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
329 bool 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
342 bool 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
360 bool
361 wxFileType::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
379 bool 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
393 bool
394 wxFileType::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
409 wxString 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
421 bool
422 wxFileType::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
438 size_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
477 bool 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
489 bool 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
504 bool 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
528 wxMimeTypesManagerFactory *wxMimeTypesManagerFactory::m_factory = NULL;
529
530 /* static */
531 void wxMimeTypesManagerFactory::Set(wxMimeTypesManagerFactory *factory)
532 {
533 delete m_factory;
534
535 m_factory = factory;
536 }
537
538 /* static */
539 wxMimeTypesManagerFactory *wxMimeTypesManagerFactory::Get()
540 {
541 if ( !m_factory )
542 m_factory = new wxMimeTypesManagerFactory;
543
544 return m_factory;
545 }
546
547 wxMimeTypesManagerImpl *wxMimeTypesManagerFactory::CreateMimeTypesManagerImpl()
548 {
549 return new wxMimeTypesManagerImpl;
550 }
551
552 // ----------------------------------------------------------------------------
553 // wxMimeTypesManager
554 // ----------------------------------------------------------------------------
555
556 void wxMimeTypesManager::EnsureImpl()
557 {
558 if ( !m_impl )
559 m_impl = wxMimeTypesManagerFactory::Get()->CreateMimeTypesManagerImpl();
560 }
561
562 bool 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
585 wxMimeTypesManager::wxMimeTypesManager()
586 {
587 m_impl = NULL;
588 }
589
590 wxMimeTypesManager::~wxMimeTypesManager()
591 {
592 if ( m_impl )
593 delete m_impl;
594 }
595
596 bool 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
608 wxFileType *
609 wxMimeTypesManager::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
622 wxFileType *
623 wxMimeTypesManager::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
657 wxFileType *
658 wxMimeTypesManager::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
682 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
683 {
684 EnsureImpl();
685 for ( const wxFileTypeInfo *ft = filetypes; ft && ft->IsValid(); ft++ ) {
686 AddFallback(*ft);
687 }
688 }
689
690 size_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
707 void 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
721 void 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
735 static wxMimeTypesManager gs_mimeTypesManager;
736
737 // and public pointer
738 wxMimeTypesManager *wxTheMimeTypesManager = &gs_mimeTypesManager;
739
740 class wxMimeTypeCmnModule: public wxModule
741 {
742 public:
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
760 IMPLEMENT_DYNAMIC_CLASS(wxMimeTypeCmnModule, wxModule)
761
762 #endif // wxUSE_MIMETYPE