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