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