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