Only use text/xxx, skip application/xxx in MIME database
[wxWidgets.git] / src / unix / mimetype.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 23.09.98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
11
12 // for compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
14
15 #ifdef __BORLANDC__
16 #pragma hdrstop
17 #endif
18
19 #if wxUSE_MIMETYPE && wxUSE_FILE
20
21 #include "wx/unix/mimetype.h"
22
23 #ifndef WX_PRECOMP
24 #include "wx/dynarray.h"
25 #include "wx/string.h"
26 #include "wx/intl.h"
27 #include "wx/log.h"
28 #include "wx/utils.h"
29 #endif
30
31 #include "wx/file.h"
32 #include "wx/confbase.h"
33
34 #include "wx/ffile.h"
35 #include "wx/dir.h"
36 #include "wx/tokenzr.h"
37 #include "wx/iconloc.h"
38 #include "wx/filename.h"
39 #include "wx/app.h"
40 #include "wx/apptrait.h"
41
42 // other standard headers
43 #include <ctype.h>
44
45 class wxMimeTextFile
46 {
47 public:
48 wxMimeTextFile()
49 {
50 }
51
52 wxMimeTextFile(const wxString& fname)
53 {
54 m_fname = fname;
55 }
56
57 bool Open()
58 {
59 wxFFile file( m_fname );
60 if (!file.IsOpened())
61 return false;
62
63 size_t size = file.Length();
64 wxCharBuffer buffer( size );
65 file.Read( (void*) (const char*) buffer, size );
66
67 // Check for valid UTF-8 here?
68 wxString all = wxString::FromUTF8( buffer, size );
69
70 wxStringTokenizer tok( all, "\n" );
71 while (tok.HasMoreTokens())
72 {
73 wxString t = tok.GetNextToken();
74 t.MakeLower();
75 if ((!!t) && (t.Find( "comment" ) != 0) && (t.Find( "#" ) != 0) && (t.Find( "generic" ) != 0))
76 m_text.Add( t );
77 }
78 return true;
79 }
80
81 unsigned int GetLineCount() const { return m_text.GetCount(); }
82 wxString &GetLine( unsigned int line ) { return m_text[line]; }
83
84 int pIndexOf(const wxString& sSearch,
85 bool bIncludeComments = false,
86 int iStart = 0)
87 {
88 wxString sTest = sSearch;
89 sTest.MakeLower();
90 for(size_t i = iStart; i < GetLineCount(); i++)
91 {
92 wxString sLine = GetLine(i);
93 if(bIncludeComments || ! sLine.StartsWith(wxT("#")))
94 {
95 if(sLine.StartsWith(sTest))
96 return (int)i;
97 }
98 }
99 return wxNOT_FOUND;
100 }
101
102 wxString GetVerb(size_t i)
103 {
104 if (i > GetLineCount() )
105 return wxEmptyString;
106
107 wxString sTmp = GetLine(i).BeforeFirst(wxT('='));
108 return sTmp;
109 }
110
111 wxString GetCmd(size_t i)
112 {
113 if (i > GetLineCount() )
114 return wxEmptyString;
115
116 wxString sTmp = GetLine(i).AfterFirst(wxT('='));
117 return sTmp;
118 }
119
120 private:
121 wxArrayString m_text;
122 wxString m_fname;
123 };
124
125 // ----------------------------------------------------------------------------
126 // constants
127 // ----------------------------------------------------------------------------
128
129 // MIME code tracing mask
130 #define TRACE_MIME wxT("mime")
131
132
133 // Read a XDG *.desktop file of type 'Application'
134 void wxMimeTypesManagerImpl::LoadXDGApp(const wxString& filename)
135 {
136 wxLogTrace(TRACE_MIME, wxT("loading XDG file %s"), filename.c_str());
137
138 wxMimeTextFile file(filename);
139 if ( !file.Open() )
140 return;
141
142 // Here, only type 'Application' should be considered.
143 int nIndex = file.pIndexOf( "Type=" );
144 if (nIndex != wxNOT_FOUND && file.GetCmd(nIndex) != "application")
145 return;
146
147 // The hidden entry specifies a file to be ignored.
148 nIndex = file.pIndexOf( "Hidden=" );
149 if (nIndex != wxNOT_FOUND && file.GetCmd(nIndex) == "true")
150 return;
151
152 // Semicolon separated list of mime types handled by the application.
153 nIndex = file.pIndexOf( wxT("MimeType=") );
154 if (nIndex == wxNOT_FOUND)
155 return;
156 wxString mimetypes = file.GetCmd (nIndex);
157
158 // Name of the application
159 wxString nameapp;
160 nIndex = wxNOT_FOUND;
161 #if wxUSE_INTL // try "Name[locale name]" first
162 wxLocale *locale = wxGetLocale();
163 if ( locale )
164 nIndex = file.pIndexOf(_T("Name[")+locale->GetName()+_T("]="));
165 #endif // wxUSE_INTL
166 if(nIndex == wxNOT_FOUND)
167 nIndex = file.pIndexOf( wxT("Name=") );
168 if(nIndex != wxNOT_FOUND)
169 nameapp = file.GetCmd(nIndex);
170
171 // Icon of the application.
172 wxString nameicon, namemini;
173 nIndex = wxNOT_FOUND;
174 #if wxUSE_INTL // try "Icon[locale name]" first
175 if ( locale )
176 nIndex = file.pIndexOf(_T("Icon[")+locale->GetName()+_T("]="));
177 #endif // wxUSE_INTL
178 if(nIndex == wxNOT_FOUND)
179 nIndex = file.pIndexOf( wxT("Icon=") );
180 if(nIndex != wxNOT_FOUND) {
181 nameicon = wxString(wxT("--icon ")) + file.GetCmd(nIndex);
182 namemini = wxString(wxT("--miniicon ")) + file.GetCmd(nIndex);
183 }
184
185 // Replace some of the field code in the 'Exec' entry.
186 // TODO: deal with %d, %D, %n, %N, %k and %v (but last one is deprecated)
187 nIndex = file.pIndexOf( wxT("Exec=") );
188 if (nIndex == wxNOT_FOUND)
189 return;
190 wxString sCmd = file.GetCmd(nIndex);
191 // we expect %f; others including %F and %U and %u are possible
192 sCmd.Replace(wxT("%F"), wxT("%f"));
193 sCmd.Replace(wxT("%U"), wxT("%f"));
194 sCmd.Replace(wxT("%u"), wxT("%f"));
195 if (0 == sCmd.Replace ( wxT("%f"), wxT("%s") ))
196 sCmd = sCmd + wxT(" %s");
197 sCmd.Replace(wxT("%c"), nameapp);
198 sCmd.Replace(wxT("%i"), nameicon);
199 sCmd.Replace(wxT("%m"), namemini);
200
201 wxStringTokenizer tokenizer(mimetypes, _T(";"));
202 while(tokenizer.HasMoreTokens()) {
203 wxString mimetype = tokenizer.GetNextToken().Lower();
204 nIndex = m_aTypes.Index(mimetype);
205 if(nIndex != wxNOT_FOUND) { // is this a known MIME type?
206 wxMimeTypeCommands* entry = m_aEntries[nIndex];
207 entry->AddOrReplaceVerb(wxT("open"), sCmd);
208 }
209 }
210 }
211
212 void wxMimeTypesManagerImpl::LoadXDGAppsFilesFromDir(const wxString& dirname)
213 {
214 // Don't complain if we don't have permissions to read - it confuses users
215 wxLogNull logNull;
216
217 if(! wxDir::Exists(dirname))
218 return;
219 wxDir dir(dirname);
220 if ( !dir.IsOpened() )
221 return;
222
223 wxString filename;
224 // Look into .desktop files
225 bool cont = dir.GetFirst(&filename, _T("*.desktop"), wxDIR_FILES);
226 while (cont)
227 {
228 wxFileName p(dirname, filename);
229 LoadXDGApp( p.GetFullPath() );
230 cont = dir.GetNext(&filename);
231 }
232
233 #if 0
234 // RR: I'm not sure this makes any sense. On my system we'll just
235 // scan the YAST2 and other useless directories
236
237 // Look recursively into subdirs
238 cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_DIRS);
239 while (cont)
240 {
241 wxFileName p(dirname, wxEmptyString);
242 p.AppendDir(filename);
243 LoadXDGAppsFilesFromDir( p.GetPath() );
244 cont = dir.GetNext(&filename);
245 }
246 #endif
247 }
248
249
250 void wxMimeTypesManagerImpl::LoadXDGGlobs(const wxString& filename)
251 {
252 if ( !wxFileName::FileExists(filename) )
253 return;
254
255 wxLogTrace(TRACE_MIME, wxT("loading XDG globs file from %s"), filename.c_str());
256
257 wxMimeTextFile file(filename);
258 if ( !file.Open() )
259 return;
260
261 size_t i;
262 for (i = 0; i < file.GetLineCount(); i++)
263 {
264 wxStringTokenizer tok( file.GetLine(i), ":" );
265 wxString mime = tok.GetNextToken();
266 wxString ext = tok.GetNextToken();
267 ext.Remove( 0, 2 );
268 wxArrayString exts;
269 exts.Add( ext );
270
271 if (mime.Find( "application" ) != 0)
272 AddToMimeData(mime, wxEmptyString, NULL, exts, wxEmptyString, true );
273 }
274 }
275
276 // ----------------------------------------------------------------------------
277 // wxFileTypeImpl (Unix)
278 // ----------------------------------------------------------------------------
279
280 wxString wxFileTypeImpl::GetExpandedCommand(const wxString & verb, const wxFileType::MessageParameters& params) const
281 {
282 wxString sTmp;
283 size_t i = 0;
284 while ( (i < m_index.GetCount() ) && sTmp.empty() )
285 {
286 sTmp = m_manager->GetCommand( verb, m_index[i] );
287 i++;
288 }
289
290 return wxFileType::ExpandCommand(sTmp, params);
291 }
292
293 bool wxFileTypeImpl::GetIcon(wxIconLocation *iconLoc) const
294 {
295 wxString sTmp;
296 size_t i = 0;
297 while ( (i < m_index.GetCount() ) && sTmp.empty() )
298 {
299 sTmp = m_manager->m_aIcons[m_index[i]];
300 i++;
301 }
302
303 if ( sTmp.empty() )
304 return false;
305
306 if ( iconLoc )
307 {
308 iconLoc->SetFileName(sTmp);
309 }
310
311 return true;
312 }
313
314 bool wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
315 {
316 mimeTypes.Clear();
317 size_t nCount = m_index.GetCount();
318 for (size_t i = 0; i < nCount; i++)
319 mimeTypes.Add(m_manager->m_aTypes[m_index[i]]);
320
321 return true;
322 }
323
324 size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
325 wxArrayString *commands,
326 const wxFileType::MessageParameters& params) const
327 {
328 wxString vrb, cmd, sTmp;
329 size_t count = 0;
330 wxMimeTypeCommands * sPairs;
331
332 // verbs and commands have been cleared already in mimecmn.cpp...
333 // if we find no entries in the exact match, try the inexact match
334 for (size_t n = 0; ((count == 0) && (n < m_index.GetCount())); n++)
335 {
336 // list of verb = command pairs for this mimetype
337 sPairs = m_manager->m_aEntries [m_index[n]];
338 size_t i;
339 for ( i = 0; i < sPairs->GetCount(); i++ )
340 {
341 vrb = sPairs->GetVerb(i);
342 // some gnome entries have "." inside
343 vrb = vrb.AfterLast(wxT('.'));
344 cmd = sPairs->GetCmd(i);
345 if (! cmd.empty() )
346 {
347 cmd = wxFileType::ExpandCommand(cmd, params);
348 count++;
349 if ( vrb.IsSameAs(wxT("open")))
350 {
351 if ( verbs )
352 verbs->Insert(vrb, 0u);
353 if ( commands )
354 commands ->Insert(cmd, 0u);
355 }
356 else
357 {
358 if ( verbs )
359 verbs->Add(vrb);
360 if ( commands )
361 commands->Add(cmd);
362 }
363 }
364 }
365 }
366
367 return count;
368 }
369
370 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
371 {
372 const wxString strExtensions = m_manager->GetExtension(m_index[0]);
373 extensions.Empty();
374
375 // one extension in the space or comma-delimited list
376 wxString strExt;
377 wxString::const_iterator end = strExtensions.end();
378 for ( wxString::const_iterator p = strExtensions.begin(); /* nothing */; ++p )
379 {
380 if ( p == end || *p == wxT(' ') || *p == wxT(',') )
381 {
382 if ( !strExt.empty() )
383 {
384 extensions.Add(strExt);
385 strExt.Empty();
386 }
387 //else: repeated spaces
388 // (shouldn't happen, but it's not that important if it does happen)
389
390 if ( p == end )
391 break;
392 }
393 else if ( *p == wxT('.') )
394 {
395 // remove the dot from extension (but only if it's the first char)
396 if ( !strExt.empty() )
397 {
398 strExt += wxT('.');
399 }
400 //else: no, don't append it
401 }
402 else
403 {
404 strExt += *p;
405 }
406 }
407
408 return true;
409 }
410
411 // set an arbitrary command:
412 // could adjust the code to ask confirmation if it already exists and
413 // overwriteprompt is true, but this is currently ignored as *Associate* has
414 // no overwrite prompt
415 bool
416 wxFileTypeImpl::SetCommand(const wxString& cmd,
417 const wxString& verb,
418 bool WXUNUSED(overwriteprompt))
419 {
420 wxArrayString strExtensions;
421 wxString strDesc, strIcon;
422
423 wxArrayString strTypes;
424 GetMimeTypes(strTypes);
425 if ( strTypes.IsEmpty() )
426 return false;
427
428 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
429 entry->Add(verb + wxT("=") + cmd + wxT(" %s "));
430
431 bool ok = false;
432 size_t nCount = strTypes.GetCount();
433 for ( size_t i = 0; i < nCount; i++ )
434 {
435 if ( m_manager->DoAssociation
436 (
437 strTypes[i],
438 strIcon,
439 entry,
440 strExtensions,
441 strDesc
442 ) )
443 {
444 // DoAssociation() took ownership of entry, don't delete it below
445 ok = true;
446 }
447 }
448
449 if ( !ok )
450 delete entry;
451
452 return ok;
453 }
454
455 // ignore index on the grounds that we only have one icon in a Unix file
456 bool wxFileTypeImpl::SetDefaultIcon(const wxString& strIcon, int WXUNUSED(index))
457 {
458 if (strIcon.empty())
459 return false;
460
461 wxArrayString strExtensions;
462 wxString strDesc;
463
464 wxArrayString strTypes;
465 GetMimeTypes(strTypes);
466 if ( strTypes.IsEmpty() )
467 return false;
468
469 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
470 bool ok = false;
471 size_t nCount = strTypes.GetCount();
472 for ( size_t i = 0; i < nCount; i++ )
473 {
474 if ( m_manager->DoAssociation
475 (
476 strTypes[i],
477 strIcon,
478 entry,
479 strExtensions,
480 strDesc
481 ) )
482 {
483 // we don't need to free entry now, DoAssociation() took ownership
484 // of it
485 ok = true;
486 }
487 }
488
489 if ( !ok )
490 delete entry;
491
492 return ok;
493 }
494
495 // ----------------------------------------------------------------------------
496 // wxMimeTypesManagerImpl (Unix)
497 // ----------------------------------------------------------------------------
498
499 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
500 {
501 m_initialized = false;
502 }
503
504 void wxMimeTypesManagerImpl::InitIfNeeded()
505 {
506 if ( !m_initialized )
507 {
508 // set the flag first to prevent recursion
509 m_initialized = true;
510
511 wxString wm = wxTheApp->GetTraits()->GetDesktopEnvironment();
512
513 if (wm == wxT("KDE"))
514 Initialize( wxMAILCAP_KDE );
515 else if (wm == wxT("GNOME"))
516 Initialize( wxMAILCAP_GNOME );
517 else
518 Initialize();
519 }
520 }
521
522
523
524 // read system and user mailcaps and other files
525 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles,
526 const wxString& sExtraDir)
527 {
528 #ifdef __VMS
529 // XDG tables are never installed on OpenVMS
530 return;
531 #else
532
533 // Read MIME type - extension associations
534 LoadXDGGlobs( "/usr/share/mime/globs" );
535 LoadXDGGlobs( "/usr/local/share/mime/globs" );
536
537 // Load desktop files for XDG, and then override them with the defaults.
538 // We will override them one desktop file at a time, rather
539 // than one mime type at a time, but it should be a reasonable
540 // heuristic.
541 {
542 wxString xdgDataHome = wxGetenv("XDG_DATA_HOME");
543 if ( xdgDataHome.empty() )
544 xdgDataHome = wxGetHomeDir() + "/.local/share";
545 wxString xdgDataDirs = wxGetenv("XDG_DATA_DIRS");
546 if ( xdgDataDirs.empty() )
547 {
548 xdgDataDirs = "/usr/local/share:/usr/share";
549 if (mailcapStyles & wxMAILCAP_GNOME)
550 xdgDataDirs += ":/usr/share/gnome:/opt/gnome/share";
551 if (mailcapStyles & wxMAILCAP_KDE)
552 xdgDataDirs += ":/usr/share/kde3:/opt/kde3/share";
553 }
554 if ( !sExtraDir.empty() )
555 {
556 xdgDataDirs += ':';
557 xdgDataDirs += sExtraDir;
558 }
559
560 wxArrayString dirs;
561 wxStringTokenizer tokenizer(xdgDataDirs, ":");
562 while ( tokenizer.HasMoreTokens() )
563 {
564 wxString p = tokenizer.GetNextToken();
565 dirs.Add(p);
566 }
567 dirs.insert(dirs.begin(), xdgDataHome);
568
569 wxString defaultsList;
570 size_t i;
571 for (i = 0; i < dirs.GetCount(); i++)
572 {
573 wxString f = dirs[i];
574 if (f.Last() != '/') f += '/';
575 f += "applications/defaults.list";
576 if (wxFileExists(f))
577 {
578 defaultsList = f;
579 break;
580 }
581 }
582
583 // Load application files and associate them to corresponding mime types.
584 size_t nDirs = dirs.GetCount();
585 for (size_t nDir = 0; nDir < nDirs; nDir++)
586 {
587 wxString dirStr = dirs[nDir];
588 if (dirStr.Last() != '/') dirStr += '/';
589 dirStr += "applications";
590 LoadXDGAppsFilesFromDir(dirStr);
591 }
592
593 if (!defaultsList.IsEmpty())
594 {
595 wxArrayString deskTopFilesSeen;
596
597 wxMimeTextFile textfile(defaultsList);
598 if ( textfile.Open() )
599 {
600 int nIndex = textfile.pIndexOf( wxT("[Default Applications]") );
601 if (nIndex != wxNOT_FOUND)
602 {
603 for (i = nIndex+1; i < textfile.GetLineCount(); i++)
604 {
605 if (textfile.GetLine(i).Find(wxT("=")) != wxNOT_FOUND)
606 {
607 wxString desktopFile = textfile.GetCmd(i);
608
609 if (deskTopFilesSeen.Index(desktopFile) == wxNOT_FOUND)
610 {
611 deskTopFilesSeen.Add(desktopFile);
612 size_t j;
613 for (j = 0; j < dirs.GetCount(); j++)
614 {
615 wxString desktopPath = dirs[j];
616 if (desktopPath.Last() != '/') desktopPath += '/';
617 desktopPath += "applications/";
618 desktopPath += desktopFile;
619
620 if (wxFileExists(desktopPath))
621 LoadXDGApp(desktopPath);
622 }
623 }
624 }
625 }
626 }
627 }
628 }
629 }
630 #endif
631 }
632
633 // clear data so you can read another group of WM files
634 void wxMimeTypesManagerImpl::ClearData()
635 {
636 m_aTypes.Clear();
637 m_aIcons.Clear();
638 m_aExtensions.Clear();
639 m_aDescriptions.Clear();
640
641 WX_CLEAR_ARRAY(m_aEntries);
642 m_aEntries.Empty();
643 }
644
645 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
646 {
647 ClearData();
648 }
649
650 wxFileType * wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
651 {
652 InitIfNeeded();
653
654 wxString strType = ftInfo.GetMimeType();
655 wxString strDesc = ftInfo.GetDescription();
656 wxString strIcon = ftInfo.GetIconFile();
657
658 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
659
660 if ( ! ftInfo.GetOpenCommand().empty())
661 entry->Add(wxT("open=") + ftInfo.GetOpenCommand() + wxT(" %s "));
662 if ( ! ftInfo.GetPrintCommand().empty())
663 entry->Add(wxT("print=") + ftInfo.GetPrintCommand() + wxT(" %s "));
664
665 // now find where these extensions are in the data store and remove them
666 wxArrayString sA_Exts = ftInfo.GetExtensions();
667 wxString sExt, sExtStore;
668 size_t i, nIndex;
669 size_t nExtCount = sA_Exts.GetCount();
670 for (i=0; i < nExtCount; i++)
671 {
672 sExt = sA_Exts.Item(i);
673
674 // clean up to just a space before and after
675 sExt.Trim().Trim(false);
676 sExt = wxT(' ') + sExt + wxT(' ');
677 size_t nCount = m_aExtensions.GetCount();
678 for (nIndex = 0; nIndex < nCount; nIndex++)
679 {
680 sExtStore = m_aExtensions.Item(nIndex);
681 if (sExtStore.Replace(sExt, wxT(" ") ) > 0)
682 m_aExtensions.Item(nIndex) = sExtStore;
683 }
684 }
685
686 if ( !DoAssociation(strType, strIcon, entry, sA_Exts, strDesc) )
687 return NULL;
688
689 return GetFileTypeFromMimeType(strType);
690 }
691
692 bool wxMimeTypesManagerImpl::DoAssociation(const wxString& strType,
693 const wxString& strIcon,
694 wxMimeTypeCommands *entry,
695 const wxArrayString& strExtensions,
696 const wxString& strDesc)
697 {
698 int nIndex = AddToMimeData(strType, strIcon, entry, strExtensions, strDesc, true);
699
700 if ( nIndex == wxNOT_FOUND )
701 return false;
702
703 return true;
704 }
705
706 int wxMimeTypesManagerImpl::AddToMimeData(const wxString& strType,
707 const wxString& strIcon,
708 wxMimeTypeCommands *entry,
709 const wxArrayString& strExtensions,
710 const wxString& strDesc,
711 bool replaceExisting)
712 {
713 InitIfNeeded();
714
715 // ensure mimetype is always lower case
716 wxString mimeType = strType.Lower();
717
718 // is this a known MIME type?
719 int nIndex = m_aTypes.Index(mimeType);
720 if ( nIndex == wxNOT_FOUND )
721 {
722 // new file type
723 m_aTypes.Add(mimeType);
724 m_aIcons.Add(strIcon);
725 m_aEntries.Add(entry ? entry : new wxMimeTypeCommands);
726
727 // change nIndex so we can use it below to add the extensions
728 m_aExtensions.Add(wxEmptyString);
729 nIndex = m_aExtensions.size() - 1;
730
731 m_aDescriptions.Add(strDesc);
732 }
733 else // yes, we already have it
734 {
735 if ( replaceExisting )
736 {
737 // if new description change it
738 if ( !strDesc.empty())
739 m_aDescriptions[nIndex] = strDesc;
740
741 // if new icon change it
742 if ( !strIcon.empty())
743 m_aIcons[nIndex] = strIcon;
744
745 if ( entry )
746 {
747 delete m_aEntries[nIndex];
748 m_aEntries[nIndex] = entry;
749 }
750 }
751 else // add data we don't already have ...
752 {
753 // if new description add only if none
754 if ( m_aDescriptions[nIndex].empty() )
755 m_aDescriptions[nIndex] = strDesc;
756
757 // if new icon and no existing icon
758 if ( m_aIcons[nIndex].empty() )
759 m_aIcons[nIndex] = strIcon;
760
761 // add any new entries...
762 if ( entry )
763 {
764 wxMimeTypeCommands *entryOld = m_aEntries[nIndex];
765
766 size_t count = entry->GetCount();
767 for ( size_t i = 0; i < count; i++ )
768 {
769 const wxString& verb = entry->GetVerb(i);
770 if ( !entryOld->HasVerb(verb) )
771 {
772 entryOld->AddOrReplaceVerb(verb, entry->GetCmd(i));
773 }
774 }
775
776 // as we don't store it anywhere, it won't be deleted later as
777 // usual -- do it immediately instead
778 delete entry;
779 }
780 }
781 }
782
783 // always add the extensions to this mimetype
784 wxString& exts = m_aExtensions[nIndex];
785
786 // add all extensions we don't have yet
787 wxString ext;
788 size_t count = strExtensions.GetCount();
789 for ( size_t i = 0; i < count; i++ )
790 {
791 ext = strExtensions[i];
792 ext += wxT(' ');
793
794 if ( exts.Find(ext) == wxNOT_FOUND )
795 {
796 exts += ext;
797 }
798 }
799
800 // check data integrity
801 wxASSERT( m_aTypes.GetCount() == m_aEntries.GetCount() &&
802 m_aTypes.GetCount() == m_aExtensions.GetCount() &&
803 m_aTypes.GetCount() == m_aIcons.GetCount() &&
804 m_aTypes.GetCount() == m_aDescriptions.GetCount() );
805
806 return nIndex;
807 }
808
809 wxFileType * wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
810 {
811 if (ext.empty() )
812 return NULL;
813
814 InitIfNeeded();
815
816 size_t count = m_aExtensions.GetCount();
817 for ( size_t n = 0; n < count; n++ )
818 {
819 wxStringTokenizer tk(m_aExtensions[n], wxT(' '));
820
821 while ( tk.HasMoreTokens() )
822 {
823 // consider extensions as not being case-sensitive
824 if ( tk.GetNextToken().IsSameAs(ext, false /* no case */) )
825 {
826 // found
827 wxFileType *fileType = new wxFileType;
828 fileType->m_impl->Init(this, n);
829
830 return fileType;
831 }
832 }
833 }
834
835 return NULL;
836 }
837
838 wxFileType * wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
839 {
840 InitIfNeeded();
841
842 wxFileType * fileType = NULL;
843 // mime types are not case-sensitive
844 wxString mimetype(mimeType);
845 mimetype.MakeLower();
846
847 // first look for an exact match
848 int index = m_aTypes.Index(mimetype);
849
850 if ( index != wxNOT_FOUND )
851 {
852 fileType = new wxFileType;
853 fileType->m_impl->Init(this, index);
854 }
855
856 // then try to find "text/*" as match for "text/plain" (for example)
857 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
858 // the whole string - ok.
859
860 index = wxNOT_FOUND;
861 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
862
863 size_t nCount = m_aTypes.GetCount();
864 for ( size_t n = 0; n < nCount; n++ )
865 {
866 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
867 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") )
868 {
869 index = n;
870 break;
871 }
872 }
873
874 if ( index != wxNOT_FOUND )
875 {
876 // don't throw away fileType that was already found
877 if (!fileType)
878 fileType = new wxFileType;
879 fileType->m_impl->Init(this, index);
880 }
881
882 return fileType;
883 }
884
885 wxString wxMimeTypesManagerImpl::GetCommand(const wxString & verb, size_t nIndex) const
886 {
887 wxString command, testcmd, sV, sTmp;
888 sV = verb + wxT("=");
889
890 // list of verb = command pairs for this mimetype
891 wxMimeTypeCommands * sPairs = m_aEntries [nIndex];
892
893 size_t i;
894 size_t nCount = sPairs->GetCount();
895 for ( i = 0; i < nCount; i++ )
896 {
897 sTmp = sPairs->GetVerbCmd (i);
898 if ( sTmp.Contains(sV) )
899 command = sTmp.AfterFirst(wxT('='));
900 }
901
902 return command;
903 }
904
905 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
906 {
907 InitIfNeeded();
908
909 wxString extensions;
910 const wxArrayString& exts = filetype.GetExtensions();
911 size_t nExts = exts.GetCount();
912 for ( size_t nExt = 0; nExt < nExts; nExt++ )
913 {
914 if ( nExt > 0 )
915 extensions += wxT(' ');
916
917 extensions += exts[nExt];
918 }
919
920 AddMimeTypeInfo(filetype.GetMimeType(),
921 extensions,
922 filetype.GetDescription());
923 }
924
925 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
926 const wxString& strExtensions,
927 const wxString& strDesc)
928 {
929 // reading mailcap may find image/* , while
930 // reading mime.types finds image/gif and no match is made
931 // this means all the get functions don't work fix this
932 wxString strIcon;
933 wxString sTmp = strExtensions;
934
935 wxArrayString sExts;
936 sTmp.Trim().Trim(false);
937
938 while (!sTmp.empty())
939 {
940 sExts.Add(sTmp.AfterLast(wxT(' ')));
941 sTmp = sTmp.BeforeLast(wxT(' '));
942 }
943
944 AddToMimeData(strMimeType, strIcon, NULL, sExts, strDesc, true);
945 }
946
947 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
948 {
949 InitIfNeeded();
950
951 mimetypes.Empty();
952
953 size_t count = m_aTypes.GetCount();
954 for ( size_t n = 0; n < count; n++ )
955 {
956 // don't return template types from here (i.e. anything containg '*')
957 const wxString &type = m_aTypes[n];
958 if ( type.Find(wxT('*')) == wxNOT_FOUND )
959 {
960 mimetypes.Add(type);
961 }
962 }
963
964 return mimetypes.GetCount();
965 }
966
967 // ----------------------------------------------------------------------------
968 // writing to MIME type files
969 // ----------------------------------------------------------------------------
970
971 bool wxMimeTypesManagerImpl::Unassociate(wxFileType *ft)
972 {
973 InitIfNeeded();
974
975 wxArrayString sMimeTypes;
976 ft->GetMimeTypes(sMimeTypes);
977
978 size_t i;
979 size_t nCount = sMimeTypes.GetCount();
980 for (i = 0; i < nCount; i ++)
981 {
982 const wxString &sMime = sMimeTypes.Item(i);
983 int nIndex = m_aTypes.Index(sMime);
984 if ( nIndex == wxNOT_FOUND)
985 {
986 // error if we get here ??
987 return false;
988 }
989 else
990 {
991 m_aTypes.RemoveAt(nIndex);
992 m_aEntries.RemoveAt(nIndex);
993 m_aExtensions.RemoveAt(nIndex);
994 m_aDescriptions.RemoveAt(nIndex);
995 m_aIcons.RemoveAt(nIndex);
996 }
997 }
998 // check data integrity
999 wxASSERT( m_aTypes.GetCount() == m_aEntries.GetCount() &&
1000 m_aTypes.GetCount() == m_aExtensions.GetCount() &&
1001 m_aTypes.GetCount() == m_aIcons.GetCount() &&
1002 m_aTypes.GetCount() == m_aDescriptions.GetCount() );
1003
1004 return true;
1005 }
1006
1007 #endif
1008 // wxUSE_MIMETYPE && wxUSE_FILE