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