Add comment explaining why we filter out application/x-blah-app like entries from...
[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 // The glob files have two kinds of associations: those, which
272 // link an extension to a file type (text/html) and those
273 // which link it to an application type (application/x-mozilla).
274 // We need the former.
275 if (mime.Find( "application" ) != 0)
276 AddToMimeData(mime, wxEmptyString, NULL, exts, wxEmptyString, true );
277 }
278 }
279
280 // ----------------------------------------------------------------------------
281 // wxFileTypeImpl (Unix)
282 // ----------------------------------------------------------------------------
283
284 wxString wxFileTypeImpl::GetExpandedCommand(const wxString & verb, const wxFileType::MessageParameters& params) const
285 {
286 wxString sTmp;
287 size_t i = 0;
288 while ( (i < m_index.GetCount() ) && sTmp.empty() )
289 {
290 sTmp = m_manager->GetCommand( verb, m_index[i] );
291 i++;
292 }
293
294 return wxFileType::ExpandCommand(sTmp, params);
295 }
296
297 bool wxFileTypeImpl::GetIcon(wxIconLocation *iconLoc) const
298 {
299 wxString sTmp;
300 size_t i = 0;
301 while ( (i < m_index.GetCount() ) && sTmp.empty() )
302 {
303 sTmp = m_manager->m_aIcons[m_index[i]];
304 i++;
305 }
306
307 if ( sTmp.empty() )
308 return false;
309
310 if ( iconLoc )
311 {
312 iconLoc->SetFileName(sTmp);
313 }
314
315 return true;
316 }
317
318 bool wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
319 {
320 mimeTypes.Clear();
321 size_t nCount = m_index.GetCount();
322 for (size_t i = 0; i < nCount; i++)
323 mimeTypes.Add(m_manager->m_aTypes[m_index[i]]);
324
325 return true;
326 }
327
328 size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
329 wxArrayString *commands,
330 const wxFileType::MessageParameters& params) const
331 {
332 wxString vrb, cmd, sTmp;
333 size_t count = 0;
334 wxMimeTypeCommands * sPairs;
335
336 // verbs and commands have been cleared already in mimecmn.cpp...
337 // if we find no entries in the exact match, try the inexact match
338 for (size_t n = 0; ((count == 0) && (n < m_index.GetCount())); n++)
339 {
340 // list of verb = command pairs for this mimetype
341 sPairs = m_manager->m_aEntries [m_index[n]];
342 size_t i;
343 for ( i = 0; i < sPairs->GetCount(); i++ )
344 {
345 vrb = sPairs->GetVerb(i);
346 // some gnome entries have "." inside
347 vrb = vrb.AfterLast(wxT('.'));
348 cmd = sPairs->GetCmd(i);
349 if (! cmd.empty() )
350 {
351 cmd = wxFileType::ExpandCommand(cmd, params);
352 count++;
353 if ( vrb.IsSameAs(wxT("open")))
354 {
355 if ( verbs )
356 verbs->Insert(vrb, 0u);
357 if ( commands )
358 commands ->Insert(cmd, 0u);
359 }
360 else
361 {
362 if ( verbs )
363 verbs->Add(vrb);
364 if ( commands )
365 commands->Add(cmd);
366 }
367 }
368 }
369 }
370
371 return count;
372 }
373
374 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
375 {
376 const wxString strExtensions = m_manager->GetExtension(m_index[0]);
377 extensions.Empty();
378
379 // one extension in the space or comma-delimited list
380 wxString strExt;
381 wxString::const_iterator end = strExtensions.end();
382 for ( wxString::const_iterator p = strExtensions.begin(); /* nothing */; ++p )
383 {
384 if ( p == end || *p == wxT(' ') || *p == wxT(',') )
385 {
386 if ( !strExt.empty() )
387 {
388 extensions.Add(strExt);
389 strExt.Empty();
390 }
391 //else: repeated spaces
392 // (shouldn't happen, but it's not that important if it does happen)
393
394 if ( p == end )
395 break;
396 }
397 else if ( *p == wxT('.') )
398 {
399 // remove the dot from extension (but only if it's the first char)
400 if ( !strExt.empty() )
401 {
402 strExt += wxT('.');
403 }
404 //else: no, don't append it
405 }
406 else
407 {
408 strExt += *p;
409 }
410 }
411
412 return true;
413 }
414
415 // set an arbitrary command:
416 // could adjust the code to ask confirmation if it already exists and
417 // overwriteprompt is true, but this is currently ignored as *Associate* has
418 // no overwrite prompt
419 bool
420 wxFileTypeImpl::SetCommand(const wxString& cmd,
421 const wxString& verb,
422 bool WXUNUSED(overwriteprompt))
423 {
424 wxArrayString strExtensions;
425 wxString strDesc, strIcon;
426
427 wxArrayString strTypes;
428 GetMimeTypes(strTypes);
429 if ( strTypes.IsEmpty() )
430 return false;
431
432 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
433 entry->Add(verb + wxT("=") + cmd + wxT(" %s "));
434
435 bool ok = false;
436 size_t nCount = strTypes.GetCount();
437 for ( size_t i = 0; i < nCount; i++ )
438 {
439 if ( m_manager->DoAssociation
440 (
441 strTypes[i],
442 strIcon,
443 entry,
444 strExtensions,
445 strDesc
446 ) )
447 {
448 // DoAssociation() took ownership of entry, don't delete it below
449 ok = true;
450 }
451 }
452
453 if ( !ok )
454 delete entry;
455
456 return ok;
457 }
458
459 // ignore index on the grounds that we only have one icon in a Unix file
460 bool wxFileTypeImpl::SetDefaultIcon(const wxString& strIcon, int WXUNUSED(index))
461 {
462 if (strIcon.empty())
463 return false;
464
465 wxArrayString strExtensions;
466 wxString strDesc;
467
468 wxArrayString strTypes;
469 GetMimeTypes(strTypes);
470 if ( strTypes.IsEmpty() )
471 return false;
472
473 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
474 bool ok = false;
475 size_t nCount = strTypes.GetCount();
476 for ( size_t i = 0; i < nCount; i++ )
477 {
478 if ( m_manager->DoAssociation
479 (
480 strTypes[i],
481 strIcon,
482 entry,
483 strExtensions,
484 strDesc
485 ) )
486 {
487 // we don't need to free entry now, DoAssociation() took ownership
488 // of it
489 ok = true;
490 }
491 }
492
493 if ( !ok )
494 delete entry;
495
496 return ok;
497 }
498
499 // ----------------------------------------------------------------------------
500 // wxMimeTypesManagerImpl (Unix)
501 // ----------------------------------------------------------------------------
502
503 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
504 {
505 m_initialized = false;
506 }
507
508 void wxMimeTypesManagerImpl::InitIfNeeded()
509 {
510 if ( !m_initialized )
511 {
512 // set the flag first to prevent recursion
513 m_initialized = true;
514
515 wxString wm = wxTheApp->GetTraits()->GetDesktopEnvironment();
516
517 if (wm == wxT("KDE"))
518 Initialize( wxMAILCAP_KDE );
519 else if (wm == wxT("GNOME"))
520 Initialize( wxMAILCAP_GNOME );
521 else
522 Initialize();
523 }
524 }
525
526
527
528 // read system and user mailcaps and other files
529 void wxMimeTypesManagerImpl::Initialize(int mailcapStyles,
530 const wxString& sExtraDir)
531 {
532 #ifdef __VMS
533 // XDG tables are never installed on OpenVMS
534 return;
535 #else
536
537 // Read MIME type - extension associations
538 LoadXDGGlobs( "/usr/share/mime/globs" );
539 LoadXDGGlobs( "/usr/local/share/mime/globs" );
540
541 // Load desktop files for XDG, and then override them with the defaults.
542 // We will override them one desktop file at a time, rather
543 // than one mime type at a time, but it should be a reasonable
544 // heuristic.
545 {
546 wxString xdgDataHome = wxGetenv("XDG_DATA_HOME");
547 if ( xdgDataHome.empty() )
548 xdgDataHome = wxGetHomeDir() + "/.local/share";
549 wxString xdgDataDirs = wxGetenv("XDG_DATA_DIRS");
550 if ( xdgDataDirs.empty() )
551 {
552 xdgDataDirs = "/usr/local/share:/usr/share";
553 if (mailcapStyles & wxMAILCAP_GNOME)
554 xdgDataDirs += ":/usr/share/gnome:/opt/gnome/share";
555 if (mailcapStyles & wxMAILCAP_KDE)
556 xdgDataDirs += ":/usr/share/kde3:/opt/kde3/share";
557 }
558 if ( !sExtraDir.empty() )
559 {
560 xdgDataDirs += ':';
561 xdgDataDirs += sExtraDir;
562 }
563
564 wxArrayString dirs;
565 wxStringTokenizer tokenizer(xdgDataDirs, ":");
566 while ( tokenizer.HasMoreTokens() )
567 {
568 wxString p = tokenizer.GetNextToken();
569 dirs.Add(p);
570 }
571 dirs.insert(dirs.begin(), xdgDataHome);
572
573 wxString defaultsList;
574 size_t i;
575 for (i = 0; i < dirs.GetCount(); i++)
576 {
577 wxString f = dirs[i];
578 if (f.Last() != '/') f += '/';
579 f += "applications/defaults.list";
580 if (wxFileExists(f))
581 {
582 defaultsList = f;
583 break;
584 }
585 }
586
587 // Load application files and associate them to corresponding mime types.
588 size_t nDirs = dirs.GetCount();
589 for (size_t nDir = 0; nDir < nDirs; nDir++)
590 {
591 wxString dirStr = dirs[nDir];
592 if (dirStr.Last() != '/') dirStr += '/';
593 dirStr += "applications";
594 LoadXDGAppsFilesFromDir(dirStr);
595 }
596
597 if (!defaultsList.IsEmpty())
598 {
599 wxArrayString deskTopFilesSeen;
600
601 wxMimeTextFile textfile(defaultsList);
602 if ( textfile.Open() )
603 {
604 int nIndex = textfile.pIndexOf( wxT("[Default Applications]") );
605 if (nIndex != wxNOT_FOUND)
606 {
607 for (i = nIndex+1; i < textfile.GetLineCount(); i++)
608 {
609 if (textfile.GetLine(i).Find(wxT("=")) != wxNOT_FOUND)
610 {
611 wxString desktopFile = textfile.GetCmd(i);
612
613 if (deskTopFilesSeen.Index(desktopFile) == wxNOT_FOUND)
614 {
615 deskTopFilesSeen.Add(desktopFile);
616 size_t j;
617 for (j = 0; j < dirs.GetCount(); j++)
618 {
619 wxString desktopPath = dirs[j];
620 if (desktopPath.Last() != '/') desktopPath += '/';
621 desktopPath += "applications/";
622 desktopPath += desktopFile;
623
624 if (wxFileExists(desktopPath))
625 LoadXDGApp(desktopPath);
626 }
627 }
628 }
629 }
630 }
631 }
632 }
633 }
634 #endif
635 }
636
637 // clear data so you can read another group of WM files
638 void wxMimeTypesManagerImpl::ClearData()
639 {
640 m_aTypes.Clear();
641 m_aIcons.Clear();
642 m_aExtensions.Clear();
643 m_aDescriptions.Clear();
644
645 WX_CLEAR_ARRAY(m_aEntries);
646 m_aEntries.Empty();
647 }
648
649 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
650 {
651 ClearData();
652 }
653
654 wxFileType * wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
655 {
656 InitIfNeeded();
657
658 wxString strType = ftInfo.GetMimeType();
659 wxString strDesc = ftInfo.GetDescription();
660 wxString strIcon = ftInfo.GetIconFile();
661
662 wxMimeTypeCommands *entry = new wxMimeTypeCommands();
663
664 if ( ! ftInfo.GetOpenCommand().empty())
665 entry->Add(wxT("open=") + ftInfo.GetOpenCommand() + wxT(" %s "));
666 if ( ! ftInfo.GetPrintCommand().empty())
667 entry->Add(wxT("print=") + ftInfo.GetPrintCommand() + wxT(" %s "));
668
669 // now find where these extensions are in the data store and remove them
670 wxArrayString sA_Exts = ftInfo.GetExtensions();
671 wxString sExt, sExtStore;
672 size_t i, nIndex;
673 size_t nExtCount = sA_Exts.GetCount();
674 for (i=0; i < nExtCount; i++)
675 {
676 sExt = sA_Exts.Item(i);
677
678 // clean up to just a space before and after
679 sExt.Trim().Trim(false);
680 sExt = wxT(' ') + sExt + wxT(' ');
681 size_t nCount = m_aExtensions.GetCount();
682 for (nIndex = 0; nIndex < nCount; nIndex++)
683 {
684 sExtStore = m_aExtensions.Item(nIndex);
685 if (sExtStore.Replace(sExt, wxT(" ") ) > 0)
686 m_aExtensions.Item(nIndex) = sExtStore;
687 }
688 }
689
690 if ( !DoAssociation(strType, strIcon, entry, sA_Exts, strDesc) )
691 return NULL;
692
693 return GetFileTypeFromMimeType(strType);
694 }
695
696 bool wxMimeTypesManagerImpl::DoAssociation(const wxString& strType,
697 const wxString& strIcon,
698 wxMimeTypeCommands *entry,
699 const wxArrayString& strExtensions,
700 const wxString& strDesc)
701 {
702 int nIndex = AddToMimeData(strType, strIcon, entry, strExtensions, strDesc, true);
703
704 if ( nIndex == wxNOT_FOUND )
705 return false;
706
707 return true;
708 }
709
710 int wxMimeTypesManagerImpl::AddToMimeData(const wxString& strType,
711 const wxString& strIcon,
712 wxMimeTypeCommands *entry,
713 const wxArrayString& strExtensions,
714 const wxString& strDesc,
715 bool replaceExisting)
716 {
717 InitIfNeeded();
718
719 // ensure mimetype is always lower case
720 wxString mimeType = strType.Lower();
721
722 // is this a known MIME type?
723 int nIndex = m_aTypes.Index(mimeType);
724 if ( nIndex == wxNOT_FOUND )
725 {
726 // new file type
727 m_aTypes.Add(mimeType);
728 m_aIcons.Add(strIcon);
729 m_aEntries.Add(entry ? entry : new wxMimeTypeCommands);
730
731 // change nIndex so we can use it below to add the extensions
732 m_aExtensions.Add(wxEmptyString);
733 nIndex = m_aExtensions.size() - 1;
734
735 m_aDescriptions.Add(strDesc);
736 }
737 else // yes, we already have it
738 {
739 if ( replaceExisting )
740 {
741 // if new description change it
742 if ( !strDesc.empty())
743 m_aDescriptions[nIndex] = strDesc;
744
745 // if new icon change it
746 if ( !strIcon.empty())
747 m_aIcons[nIndex] = strIcon;
748
749 if ( entry )
750 {
751 delete m_aEntries[nIndex];
752 m_aEntries[nIndex] = entry;
753 }
754 }
755 else // add data we don't already have ...
756 {
757 // if new description add only if none
758 if ( m_aDescriptions[nIndex].empty() )
759 m_aDescriptions[nIndex] = strDesc;
760
761 // if new icon and no existing icon
762 if ( m_aIcons[nIndex].empty() )
763 m_aIcons[nIndex] = strIcon;
764
765 // add any new entries...
766 if ( entry )
767 {
768 wxMimeTypeCommands *entryOld = m_aEntries[nIndex];
769
770 size_t count = entry->GetCount();
771 for ( size_t i = 0; i < count; i++ )
772 {
773 const wxString& verb = entry->GetVerb(i);
774 if ( !entryOld->HasVerb(verb) )
775 {
776 entryOld->AddOrReplaceVerb(verb, entry->GetCmd(i));
777 }
778 }
779
780 // as we don't store it anywhere, it won't be deleted later as
781 // usual -- do it immediately instead
782 delete entry;
783 }
784 }
785 }
786
787 // always add the extensions to this mimetype
788 wxString& exts = m_aExtensions[nIndex];
789
790 // add all extensions we don't have yet
791 wxString ext;
792 size_t count = strExtensions.GetCount();
793 for ( size_t i = 0; i < count; i++ )
794 {
795 ext = strExtensions[i];
796 ext += wxT(' ');
797
798 if ( exts.Find(ext) == wxNOT_FOUND )
799 {
800 exts += ext;
801 }
802 }
803
804 // check data integrity
805 wxASSERT( m_aTypes.GetCount() == m_aEntries.GetCount() &&
806 m_aTypes.GetCount() == m_aExtensions.GetCount() &&
807 m_aTypes.GetCount() == m_aIcons.GetCount() &&
808 m_aTypes.GetCount() == m_aDescriptions.GetCount() );
809
810 return nIndex;
811 }
812
813 wxFileType * wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
814 {
815 if (ext.empty() )
816 return NULL;
817
818 InitIfNeeded();
819
820 size_t count = m_aExtensions.GetCount();
821 for ( size_t n = 0; n < count; n++ )
822 {
823 wxStringTokenizer tk(m_aExtensions[n], wxT(' '));
824
825 while ( tk.HasMoreTokens() )
826 {
827 // consider extensions as not being case-sensitive
828 if ( tk.GetNextToken().IsSameAs(ext, false /* no case */) )
829 {
830 // found
831 wxFileType *fileType = new wxFileType;
832 fileType->m_impl->Init(this, n);
833
834 return fileType;
835 }
836 }
837 }
838
839 return NULL;
840 }
841
842 wxFileType * wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
843 {
844 InitIfNeeded();
845
846 wxFileType * fileType = NULL;
847 // mime types are not case-sensitive
848 wxString mimetype(mimeType);
849 mimetype.MakeLower();
850
851 // first look for an exact match
852 int index = m_aTypes.Index(mimetype);
853
854 if ( index != wxNOT_FOUND )
855 {
856 fileType = new wxFileType;
857 fileType->m_impl->Init(this, index);
858 }
859
860 // then try to find "text/*" as match for "text/plain" (for example)
861 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
862 // the whole string - ok.
863
864 index = wxNOT_FOUND;
865 wxString strCategory = mimetype.BeforeFirst(wxT('/'));
866
867 size_t nCount = m_aTypes.GetCount();
868 for ( size_t n = 0; n < nCount; n++ )
869 {
870 if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
871 m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") )
872 {
873 index = n;
874 break;
875 }
876 }
877
878 if ( index != wxNOT_FOUND )
879 {
880 // don't throw away fileType that was already found
881 if (!fileType)
882 fileType = new wxFileType;
883 fileType->m_impl->Init(this, index);
884 }
885
886 return fileType;
887 }
888
889 wxString wxMimeTypesManagerImpl::GetCommand(const wxString & verb, size_t nIndex) const
890 {
891 wxString command, testcmd, sV, sTmp;
892 sV = verb + wxT("=");
893
894 // list of verb = command pairs for this mimetype
895 wxMimeTypeCommands * sPairs = m_aEntries [nIndex];
896
897 size_t i;
898 size_t nCount = sPairs->GetCount();
899 for ( i = 0; i < nCount; i++ )
900 {
901 sTmp = sPairs->GetVerbCmd (i);
902 if ( sTmp.Contains(sV) )
903 command = sTmp.AfterFirst(wxT('='));
904 }
905
906 return command;
907 }
908
909 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
910 {
911 InitIfNeeded();
912
913 wxString extensions;
914 const wxArrayString& exts = filetype.GetExtensions();
915 size_t nExts = exts.GetCount();
916 for ( size_t nExt = 0; nExt < nExts; nExt++ )
917 {
918 if ( nExt > 0 )
919 extensions += wxT(' ');
920
921 extensions += exts[nExt];
922 }
923
924 AddMimeTypeInfo(filetype.GetMimeType(),
925 extensions,
926 filetype.GetDescription());
927 }
928
929 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
930 const wxString& strExtensions,
931 const wxString& strDesc)
932 {
933 // reading mailcap may find image/* , while
934 // reading mime.types finds image/gif and no match is made
935 // this means all the get functions don't work fix this
936 wxString strIcon;
937 wxString sTmp = strExtensions;
938
939 wxArrayString sExts;
940 sTmp.Trim().Trim(false);
941
942 while (!sTmp.empty())
943 {
944 sExts.Add(sTmp.AfterLast(wxT(' ')));
945 sTmp = sTmp.BeforeLast(wxT(' '));
946 }
947
948 AddToMimeData(strMimeType, strIcon, NULL, sExts, strDesc, true);
949 }
950
951 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
952 {
953 InitIfNeeded();
954
955 mimetypes.Empty();
956
957 size_t count = m_aTypes.GetCount();
958 for ( size_t n = 0; n < count; n++ )
959 {
960 // don't return template types from here (i.e. anything containg '*')
961 const wxString &type = m_aTypes[n];
962 if ( type.Find(wxT('*')) == wxNOT_FOUND )
963 {
964 mimetypes.Add(type);
965 }
966 }
967
968 return mimetypes.GetCount();
969 }
970
971 // ----------------------------------------------------------------------------
972 // writing to MIME type files
973 // ----------------------------------------------------------------------------
974
975 bool wxMimeTypesManagerImpl::Unassociate(wxFileType *ft)
976 {
977 InitIfNeeded();
978
979 wxArrayString sMimeTypes;
980 ft->GetMimeTypes(sMimeTypes);
981
982 size_t i;
983 size_t nCount = sMimeTypes.GetCount();
984 for (i = 0; i < nCount; i ++)
985 {
986 const wxString &sMime = sMimeTypes.Item(i);
987 int nIndex = m_aTypes.Index(sMime);
988 if ( nIndex == wxNOT_FOUND)
989 {
990 // error if we get here ??
991 return false;
992 }
993 else
994 {
995 m_aTypes.RemoveAt(nIndex);
996 m_aEntries.RemoveAt(nIndex);
997 m_aExtensions.RemoveAt(nIndex);
998 m_aDescriptions.RemoveAt(nIndex);
999 m_aIcons.RemoveAt(nIndex);
1000 }
1001 }
1002 // check data integrity
1003 wxASSERT( m_aTypes.GetCount() == m_aEntries.GetCount() &&
1004 m_aTypes.GetCount() == m_aExtensions.GetCount() &&
1005 m_aTypes.GetCount() == m_aIcons.GetCount() &&
1006 m_aTypes.GetCount() == m_aDescriptions.GetCount() );
1007
1008 return true;
1009 }
1010
1011 #endif
1012 // wxUSE_MIMETYPE && wxUSE_FILE