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