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