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