including header once is enough
[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/module.h"
36 #endif
37
38 #ifndef WX_PRECOMP
39 #include "wx/string.h"
40 #endif //WX_PRECOMP
41
42 #include "wx/log.h"
43 #include "wx/file.h"
44 #include "wx/iconloc.h"
45 #include "wx/intl.h"
46 #include "wx/dynarray.h"
47 #include "wx/confbase.h"
48
49 #include "wx/mimetype.h"
50
51 // other standard headers
52 #include <ctype.h>
53
54 // implementation classes:
55 #if defined(__WXMSW__)
56 #include "wx/msw/mimetype.h"
57 #elif defined(__WXMAC__)
58 #include "wx/mac/mimetype.h"
59 #elif defined(__WXPM__)
60 #include "wx/os2/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.IsEmpty()
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__) && !defined(__WXPM__)
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, const wxString& verb,
416 bool overwriteprompt)
417 {
418 #if defined (__WXMSW__) || defined(__UNIX__)
419 return m_impl->SetCommand(cmd, verb, overwriteprompt);
420 #else
421 wxFAIL_MSG(_T("not implemented"));
422 return FALSE;
423 #endif
424 }
425
426 bool wxFileType::SetDefaultIcon(const wxString& cmd, int index)
427 {
428 wxString sTmp = cmd;
429 #ifdef __WXMSW__
430 // VZ: should we do this?
431 // chris elliott : only makes sense in MS windows
432 if ( sTmp.empty() )
433 GetOpenCommand(&sTmp, wxFileType::MessageParameters(wxT(""), wxT("")));
434 #endif
435 wxCHECK_MSG( !sTmp.empty(), FALSE, _T("need the icon file") );
436
437 #if defined (__WXMSW__) || defined(__UNIX__)
438 return m_impl->SetDefaultIcon (cmd, index);
439 #else
440 wxFAIL_MSG(_T("not implemented"));
441
442 return FALSE;
443 #endif
444 }
445
446
447 // ----------------------------------------------------------------------------
448 // wxMimeTypesManager
449 // ----------------------------------------------------------------------------
450
451 void wxMimeTypesManager::EnsureImpl()
452 {
453 if ( !m_impl )
454 m_impl = new wxMimeTypesManagerImpl;
455 }
456
457 bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
458 const wxString& wildcard)
459 {
460 wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
461 wxT("first MIME type can't contain wildcards") );
462
463 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
464 if ( wildcard.BeforeFirst(wxT('/')).
465 IsSameAs(mimeType.BeforeFirst(wxT('/')), FALSE) )
466 {
467 wxString strSubtype = wildcard.AfterFirst(wxT('/'));
468
469 if ( strSubtype == wxT("*") ||
470 strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), FALSE) )
471 {
472 // matches (either exactly or it's a wildcard)
473 return TRUE;
474 }
475 }
476
477 return FALSE;
478 }
479
480 wxMimeTypesManager::wxMimeTypesManager()
481 {
482 m_impl = NULL;
483 }
484
485 wxMimeTypesManager::~wxMimeTypesManager()
486 {
487 if ( m_impl )
488 delete m_impl;
489 }
490
491 bool wxMimeTypesManager::Unassociate(wxFileType *ft)
492 {
493 #if defined(__UNIX__) && !defined(__WXPM__) && !defined(__CYGWIN__) && !defined(__WINE__)
494 return m_impl->Unassociate(ft);
495 #else
496 return ft->Unassociate();
497 #endif
498 }
499
500
501 wxFileType *
502 wxMimeTypesManager::Associate(const wxFileTypeInfo& ftInfo)
503 {
504 EnsureImpl();
505
506 #if defined(__WXMSW__) || (defined(__UNIX__) && !defined(__WXPM__))
507 return m_impl->Associate(ftInfo);
508 #else // other platforms
509 wxFAIL_MSG( _T("not implemented") ); // TODO
510 return NULL;
511 #endif // platforms
512 }
513
514 wxFileType *
515 wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
516 {
517 EnsureImpl();
518 wxFileType *ft = m_impl->GetFileTypeFromExtension(ext);
519
520 if ( !ft ) {
521 // check the fallbacks
522 //
523 // TODO linear search is potentially slow, perhaps we should use a
524 // sorted array?
525 size_t count = m_fallbacks.GetCount();
526 for ( size_t n = 0; n < count; n++ ) {
527 if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
528 ft = new wxFileType(m_fallbacks[n]);
529
530 break;
531 }
532 }
533 }
534
535 return ft;
536 }
537
538 wxFileType *
539 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
540 {
541 EnsureImpl();
542 wxFileType *ft = m_impl->GetFileTypeFromMimeType(mimeType);
543
544 if ( !ft ) {
545 // check the fallbacks
546 //
547 // TODO linear search is potentially slow, perhaps we should use a
548 // sorted array?
549 size_t count = m_fallbacks.GetCount();
550 for ( size_t n = 0; n < count; n++ ) {
551 if ( wxMimeTypesManager::IsOfType(mimeType,
552 m_fallbacks[n].GetMimeType()) ) {
553 ft = new wxFileType(m_fallbacks[n]);
554
555 break;
556 }
557 }
558 }
559
560 return ft;
561 }
562
563 bool wxMimeTypesManager::ReadMailcap(const wxString& filename, bool fallback)
564 {
565 EnsureImpl();
566 return m_impl->ReadMailcap(filename, fallback);
567 }
568
569 bool wxMimeTypesManager::ReadMimeTypes(const wxString& filename)
570 {
571 EnsureImpl();
572 return m_impl->ReadMimeTypes(filename);
573 }
574
575 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
576 {
577 EnsureImpl();
578 for ( const wxFileTypeInfo *ft = filetypes; ft && ft->IsValid(); ft++ ) {
579 AddFallback(*ft);
580 }
581 }
582
583 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
584 {
585 EnsureImpl();
586 size_t countAll = m_impl->EnumAllFileTypes(mimetypes);
587
588 // add the fallback filetypes
589 size_t count = m_fallbacks.GetCount();
590 for ( size_t n = 0; n < count; n++ ) {
591 if ( mimetypes.Index(m_fallbacks[n].GetMimeType()) == wxNOT_FOUND ) {
592 mimetypes.Add(m_fallbacks[n].GetMimeType());
593 countAll++;
594 }
595 }
596
597 return countAll;
598 }
599
600 void wxMimeTypesManager::Initialize(int mcapStyle,
601 const wxString& sExtraDir)
602 {
603 #if defined(__UNIX__) && !defined(__WXPM__) && !defined(__CYGWIN__) && !defined(__WINE__)
604 EnsureImpl();
605
606 m_impl->Initialize(mcapStyle, sExtraDir);
607 #else
608 (void)mcapStyle;
609 (void)sExtraDir;
610 #endif // Unix
611 }
612
613 // and this function clears all the data from the manager
614 void wxMimeTypesManager::ClearData()
615 {
616 #if defined(__UNIX__) && !defined(__WXPM__) && !defined(__CYGWIN__) && !defined(__WINE__)
617 EnsureImpl();
618
619 m_impl->ClearData();
620 #endif // Unix
621 }
622
623 // ----------------------------------------------------------------------------
624 // global data and wxMimeTypeCmnModule
625 // ----------------------------------------------------------------------------
626
627 // private object
628 static wxMimeTypesManager gs_mimeTypesManager;
629
630 // and public pointer
631 wxMimeTypesManager *wxTheMimeTypesManager = &gs_mimeTypesManager;
632
633 class wxMimeTypeCmnModule: public wxModule
634 {
635 public:
636 wxMimeTypeCmnModule() : wxModule() { }
637 virtual bool OnInit() { return TRUE; }
638 virtual void OnExit()
639 {
640 // this avoids false memory leak allerts:
641 if ( gs_mimeTypesManager.m_impl != NULL )
642 {
643 delete gs_mimeTypesManager.m_impl;
644 gs_mimeTypesManager.m_impl = NULL;
645 gs_mimeTypesManager.m_fallbacks.Clear();
646 }
647 }
648
649 DECLARE_DYNAMIC_CLASS(wxMimeTypeCmnModule)
650 };
651
652 IMPLEMENT_DYNAMIC_CLASS(wxMimeTypeCmnModule, wxModule)
653
654 #endif // wxUSE_MIMETYPE