MIME type manager fixes described earlier on the list:
[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 #include "wx/arrimpl.cpp"
103 WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
104
105 // ============================================================================
106 // implementation of the wrapper classes
107 // ============================================================================
108
109 // ----------------------------------------------------------------------------
110 // wxFileType
111 // ----------------------------------------------------------------------------
112
113 /* static */
114 wxString wxFileType::ExpandCommand(const wxString& command,
115 const wxFileType::MessageParameters& params)
116 {
117 bool hasFilename = FALSE;
118
119 wxString str;
120 for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
121 if ( *pc == wxT('%') ) {
122 switch ( *++pc ) {
123 case wxT('s'):
124 // '%s' expands into file name (quoted because it might
125 // contain spaces) - except if there are already quotes
126 // there because otherwise some programs may get confused
127 // by double double quotes
128 #if 0
129 if ( *(pc - 2) == wxT('"') )
130 str << params.GetFileName();
131 else
132 str << wxT('"') << params.GetFileName() << wxT('"');
133 #endif
134 str << params.GetFileName();
135 hasFilename = TRUE;
136 break;
137
138 case wxT('t'):
139 // '%t' expands into MIME type (quote it too just to be
140 // consistent)
141 str << wxT('\'') << params.GetMimeType() << wxT('\'');
142 break;
143
144 case wxT('{'):
145 {
146 const wxChar *pEnd = wxStrchr(pc, wxT('}'));
147 if ( pEnd == NULL ) {
148 wxString mimetype;
149 wxLogWarning(_("Unmatched '{' in an entry for mime type %s."),
150 params.GetMimeType().c_str());
151 str << wxT("%{");
152 }
153 else {
154 wxString param(pc + 1, pEnd - pc - 1);
155 str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
156 pc = pEnd;
157 }
158 }
159 break;
160
161 case wxT('n'):
162 case wxT('F'):
163 // TODO %n is the number of parts, %F is an array containing
164 // the names of temp files these parts were written to
165 // and their mime types.
166 break;
167
168 default:
169 wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
170 *pc, command.c_str());
171 str << *pc;
172 }
173 }
174 else {
175 str << *pc;
176 }
177 }
178
179 // metamail(1) man page states that if the mailcap entry doesn't have '%s'
180 // the program will accept the data on stdin so normally we should append
181 // "< %s" to the end of the command in such case, but not all commands
182 // behave like this, in particular a common test is 'test -n "$DISPLAY"'
183 // and appending "< %s" to this command makes the test fail... I don't
184 // know of the correct solution, try to guess what we have to do.
185 if ( !hasFilename && !str.IsEmpty()
186 #ifdef __UNIX__
187 && !str.StartsWith(_T("test "))
188 #endif // Unix
189 ) {
190 str << wxT(" < '") << params.GetFileName() << wxT('\'');
191 }
192
193 return str;
194 }
195
196 wxFileType::wxFileType(const wxFileTypeInfo& info)
197 {
198 m_info = &info;
199 m_impl = NULL;
200 }
201
202 wxFileType::wxFileType()
203 {
204 m_info = NULL;
205 m_impl = new wxFileTypeImpl;
206 }
207
208 wxFileType::~wxFileType()
209 {
210 delete m_impl;
211 }
212
213 bool wxFileType::GetExtensions(wxArrayString& extensions)
214 {
215 if ( m_info )
216 {
217 extensions = m_info->GetExtensions();
218 return TRUE;
219 }
220
221 return m_impl->GetExtensions(extensions);
222 }
223
224 bool wxFileType::GetMimeType(wxString *mimeType) const
225 {
226 wxCHECK_MSG( mimeType, FALSE, _T("invalid parameter in GetMimeType") );
227
228 if ( m_info )
229 {
230 *mimeType = m_info->GetMimeType();
231
232 return TRUE;
233 }
234
235 return m_impl->GetMimeType(mimeType);
236 }
237
238 bool wxFileType::GetMimeTypes(wxArrayString& mimeTypes) const
239 {
240 if ( m_info )
241 {
242 mimeTypes.Clear();
243 mimeTypes.Add(m_info->GetMimeType());
244
245 return TRUE;
246 }
247
248 return m_impl->GetMimeTypes(mimeTypes);
249 }
250
251 bool wxFileType::GetIcon(wxIcon *icon,
252 wxString *iconFile,
253 int *iconIndex) const
254 {
255 if ( m_info )
256 {
257 if ( iconFile )
258 *iconFile = m_info->GetIconFile();
259 if ( iconIndex )
260 *iconIndex = m_info->GetIconIndex();
261
262 #if wxUSE_GUI
263 if ( icon && !m_info->GetIconFile().empty() )
264 {
265 // FIXME: what about the index?
266 icon->LoadFile(m_info->GetIconFile());
267 }
268 #endif // wxUSE_GUI
269
270 return TRUE;
271 }
272
273 #ifdef __WXMSW__
274 return m_impl->GetIcon(icon, iconFile, iconIndex);
275 #else
276 return m_impl->GetIcon(icon);
277 #endif
278 }
279
280 bool wxFileType::GetDescription(wxString *desc) const
281 {
282 wxCHECK_MSG( desc, FALSE, _T("invalid parameter in GetDescription") );
283
284 if ( m_info )
285 {
286 *desc = m_info->GetDescription();
287
288 return TRUE;
289 }
290
291 return m_impl->GetDescription(desc);
292 }
293
294 bool
295 wxFileType::GetOpenCommand(wxString *openCmd,
296 const wxFileType::MessageParameters& params) const
297 {
298 wxCHECK_MSG( openCmd, FALSE, _T("invalid parameter in GetOpenCommand") );
299
300 if ( m_info )
301 {
302 *openCmd = ExpandCommand(m_info->GetOpenCommand(), params);
303
304 return TRUE;
305 }
306
307 return m_impl->GetOpenCommand(openCmd, params);
308 }
309
310 bool
311 wxFileType::GetPrintCommand(wxString *printCmd,
312 const wxFileType::MessageParameters& params) const
313 {
314 wxCHECK_MSG( printCmd, FALSE, _T("invalid parameter in GetPrintCommand") );
315
316 if ( m_info )
317 {
318 *printCmd = ExpandCommand(m_info->GetPrintCommand(), params);
319
320 return TRUE;
321 }
322
323 return m_impl->GetPrintCommand(printCmd, params);
324 }
325
326
327 size_t wxFileType::GetAllCommands(wxArrayString *verbs,
328 wxArrayString *commands,
329 const wxFileType::MessageParameters& params) const
330 {
331 if ( verbs )
332 verbs->Clear();
333 if ( commands )
334 commands->Clear();
335
336 #ifdef __WXMSW__
337 return m_impl->GetAllCommands(verbs, commands, params);
338 #else // !__WXMSW__
339 // we don't know how to retrieve all commands, so just try the 2 we know
340 // about
341 size_t count = 0;
342 wxString cmd;
343 if ( GetOpenCommand(&cmd, params) )
344 {
345 if ( verbs )
346 verbs->Add(_T("Open"));
347 if ( commands )
348 commands->Add(cmd);
349 count++;
350 }
351
352 if ( GetPrintCommand(&cmd, params) )
353 {
354 if ( verbs )
355 verbs->Add(_T("Print"));
356 if ( commands )
357 commands->Add(cmd);
358
359 count++;
360 }
361
362 return count;
363 #endif // __WXMSW__/!__WXMSW__
364 }
365
366 bool wxFileType::Unassociate()
367 {
368 #if defined(__WXMSW__) || defined(__UNIX__)
369 return m_impl->Unassociate();
370 #else
371 wxFAIL_MSG( _T("not implemented") ); // TODO
372 return FALSE;
373 #endif
374 }
375
376 // ----------------------------------------------------------------------------
377 // wxMimeTypesManager
378 // ----------------------------------------------------------------------------
379
380 void wxMimeTypesManager::EnsureImpl()
381 {
382 if ( !m_impl )
383 m_impl = new wxMimeTypesManagerImpl;
384 }
385
386 bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
387 const wxString& wildcard)
388 {
389 wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
390 wxT("first MIME type can't contain wildcards") );
391
392 // all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
393 if ( wildcard.BeforeFirst(wxT('/')).
394 IsSameAs(mimeType.BeforeFirst(wxT('/')), FALSE) )
395 {
396 wxString strSubtype = wildcard.AfterFirst(wxT('/'));
397
398 if ( strSubtype == wxT("*") ||
399 strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), FALSE) )
400 {
401 // matches (either exactly or it's a wildcard)
402 return TRUE;
403 }
404 }
405
406 return FALSE;
407 }
408
409 wxMimeTypesManager::wxMimeTypesManager()
410 {
411 m_impl = NULL;
412 }
413
414 wxMimeTypesManager::~wxMimeTypesManager()
415 {
416 delete m_impl;
417 }
418
419 wxFileType *
420 wxMimeTypesManager::Associate(const wxFileTypeInfo& ftInfo)
421 {
422 EnsureImpl();
423
424 #if defined(__WXMSW__) || defined(__UNIX__)
425 return m_impl->Associate(ftInfo);
426 #else // other platforms
427 wxFAIL_MSG( _T("not implemented") ); // TODO
428 return NULL;
429 #endif // platforms
430 }
431
432 wxFileType *
433 wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
434 {
435 EnsureImpl();
436 wxFileType *ft = m_impl->GetFileTypeFromExtension(ext);
437
438 if ( !ft ) {
439 // check the fallbacks
440 //
441 // TODO linear search is potentially slow, perhaps we should use a
442 // sorted array?
443 size_t count = m_fallbacks.GetCount();
444 for ( size_t n = 0; n < count; n++ ) {
445 if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
446 ft = new wxFileType(m_fallbacks[n]);
447
448 break;
449 }
450 }
451 }
452
453 return ft;
454 }
455
456 wxFileType *
457 wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
458 {
459 EnsureImpl();
460 wxFileType *ft = m_impl->GetFileTypeFromMimeType(mimeType);
461
462 if ( ft ) {
463 // check the fallbacks
464 //
465 // TODO linear search is potentially slow, perhaps we should use a sorted
466 // array?
467 size_t count = m_fallbacks.GetCount();
468 for ( size_t n = 0; n < count; n++ ) {
469 if ( wxMimeTypesManager::IsOfType(mimeType,
470 m_fallbacks[n].GetMimeType()) ) {
471 ft = new wxFileType(m_fallbacks[n]);
472
473 break;
474 }
475 }
476 }
477
478 return ft;
479 }
480
481 bool wxMimeTypesManager::ReadMailcap(const wxString& filename, bool fallback)
482 {
483 EnsureImpl();
484 return m_impl->ReadMailcap(filename, fallback);
485 }
486
487 bool wxMimeTypesManager::ReadMimeTypes(const wxString& filename)
488 {
489 EnsureImpl();
490 return m_impl->ReadMimeTypes(filename);
491 }
492
493 void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
494 {
495 EnsureImpl();
496 for ( const wxFileTypeInfo *ft = filetypes; ft && ft->IsValid(); ft++ ) {
497 AddFallback(*ft);
498 }
499 }
500
501 size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
502 {
503 EnsureImpl();
504 size_t countAll = m_impl->EnumAllFileTypes(mimetypes);
505
506 // add the fallback filetypes
507 size_t count = m_fallbacks.GetCount();
508 for ( size_t n = 0; n < count; n++ ) {
509 if ( mimetypes.Index(m_fallbacks[n].GetMimeType()) == wxNOT_FOUND ) {
510 mimetypes.Add(m_fallbacks[n].GetMimeType());
511 countAll++;
512 }
513 }
514
515 return countAll;
516 }
517
518 // ----------------------------------------------------------------------------
519 // global data and wxMimeTypeCmnModule
520 // ----------------------------------------------------------------------------
521
522 // private object
523 static wxMimeTypesManager gs_mimeTypesManager;
524
525 // and public pointer
526 wxMimeTypesManager *wxTheMimeTypesManager = &gs_mimeTypesManager;
527
528 class wxMimeTypeCmnModule: public wxModule
529 {
530 public:
531 wxMimeTypeCmnModule() : wxModule() { }
532 virtual bool OnInit() { return TRUE; }
533 virtual void OnExit()
534 {
535 // this avoids false memory leak allerts:
536 if ( gs_mimeTypesManager.m_impl != NULL )
537 {
538 delete gs_mimeTypesManager.m_impl;
539 gs_mimeTypesManager.m_impl = NULL;
540 }
541 }
542
543 DECLARE_DYNAMIC_CLASS(wxMimeTypeCmnModule)
544 };
545
546 IMPLEMENT_DYNAMIC_CLASS(wxMimeTypeCmnModule, wxModule)
547