]> git.saurik.com Git - wxWidgets.git/blob - src/common/mimecmn.cpp
Committing in .
[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__) || defined(__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 #elif defined(__UNIX__)
389 return m_impl->Unassociate(this);
390 #else
391
392 wxFAIL_MSG( _T("not implemented") ); // TODO
393 return FALSE;
394 #endif
395 }
396
397 bool wxFileType::SetCommand(const wxString& cmd, const wxString& verb,
398 bool overwriteprompt)
399 {
400 #if defined (__WXMSW__) || defined(__UNIX__)
401 return m_impl->SetCommand(cmd, verb, overwriteprompt);
402 #else
403 wxFAIL_MSG(_T("not implemented"));
404
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("", ""));
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__)
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__)
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 sorted
531 // 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 #ifdef __UNIX__
587 EnsureImpl();
588
589 m_impl->Initialize(mcapStyle, sExtraDir);
590 #endif // Unix
591 }
592
593 // and this function clears all the data from the manager
594 void wxMimeTypesManager::ClearData()
595 {
596 #ifdef __UNIX__
597 EnsureImpl();
598
599 m_impl->ClearData();
600 #endif // Unix
601 }
602
603 // ----------------------------------------------------------------------------
604 // global data and wxMimeTypeCmnModule
605 // ----------------------------------------------------------------------------
606
607 // private object
608 static wxMimeTypesManager gs_mimeTypesManager;
609
610 // and public pointer
611 wxMimeTypesManager *wxTheMimeTypesManager = &gs_mimeTypesManager;
612
613 class wxMimeTypeCmnModule: public wxModule
614 {
615 public:
616 wxMimeTypeCmnModule() : wxModule() { }
617 virtual bool OnInit() { return TRUE; }
618 virtual void OnExit()
619 {
620 // this avoids false memory leak allerts:
621 if ( gs_mimeTypesManager.m_impl != NULL )
622 {
623 delete gs_mimeTypesManager.m_impl;
624 gs_mimeTypesManager.m_impl = NULL;
625 }
626 }
627
628 DECLARE_DYNAMIC_CLASS(wxMimeTypeCmnModule)
629 };
630
631 IMPLEMENT_DYNAMIC_CLASS(wxMimeTypeCmnModule, wxModule)