1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/core/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin, Stefan Csomor
7 // RCS-ID: $Id: mimetype.cpp 54734 2008-07-21 01:33:51Z VZ $
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
12 // for compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
19 #if wxUSE_MIMETYPE && wxUSE_FILE
21 #include "wx/unix/mimetype.h"
24 #include "wx/dynarray.h"
25 #include "wx/string.h"
32 #include "wx/confbase.h"
36 #include "wx/tokenzr.h"
37 #include "wx/iconloc.h"
38 #include "wx/filename.h"
40 #include "wx/apptrait.h"
42 // other standard headers
45 // ----------------------------------------------------------------------------
47 // ----------------------------------------------------------------------------
49 // MIME code tracing mask
50 #define TRACE_MIME wxT("mime")
52 // ----------------------------------------------------------------------------
53 // wxFileTypeImpl (Unix)
54 // ----------------------------------------------------------------------------
56 wxString
wxFileTypeImpl::GetExpandedCommand(const wxString
& verb
, const wxFileType::MessageParameters
& params
) const
60 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
62 sTmp
= m_manager
->GetCommand( verb
, m_index
[i
] );
66 return wxFileType::ExpandCommand(sTmp
, params
);
69 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
73 while ( (i
< m_index
.GetCount() ) && sTmp
.empty() )
75 sTmp
= m_manager
->m_aIcons
[m_index
[i
]];
84 iconLoc
->SetFileName(sTmp
);
90 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
93 size_t nCount
= m_index
.GetCount();
94 for (size_t i
= 0; i
< nCount
; i
++)
95 mimeTypes
.Add(m_manager
->m_aTypes
[m_index
[i
]]);
100 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
101 wxArrayString
*commands
,
102 const wxFileType::MessageParameters
& params
) const
104 wxString vrb
, cmd
, sTmp
;
106 wxMimeTypeCommands
* sPairs
;
108 // verbs and commands have been cleared already in mimecmn.cpp...
109 // if we find no entries in the exact match, try the inexact match
110 for (size_t n
= 0; ((count
== 0) && (n
< m_index
.GetCount())); n
++)
112 // list of verb = command pairs for this mimetype
113 sPairs
= m_manager
->m_aEntries
[m_index
[n
]];
115 for ( i
= 0; i
< sPairs
->GetCount(); i
++ )
117 vrb
= sPairs
->GetVerb(i
);
118 // some gnome entries have "." inside
119 vrb
= vrb
.AfterLast(wxT('.'));
120 cmd
= sPairs
->GetCmd(i
);
123 cmd
= wxFileType::ExpandCommand(cmd
, params
);
125 if ( vrb
.IsSameAs(wxT("open")))
128 verbs
->Insert(vrb
, 0u);
130 commands
->Insert(cmd
, 0u);
146 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
148 const wxString strExtensions
= m_manager
->GetExtension(m_index
[0]);
151 // one extension in the space or comma-delimited list
153 wxString::const_iterator end
= strExtensions
.end();
154 for ( wxString::const_iterator p
= strExtensions
.begin(); /* nothing */; ++p
)
156 if ( p
== end
|| *p
== wxT(' ') || *p
== wxT(',') )
158 if ( !strExt
.empty() )
160 extensions
.Add(strExt
);
163 //else: repeated spaces
164 // (shouldn't happen, but it's not that important if it does happen)
169 else if ( *p
== wxT('.') )
171 // remove the dot from extension (but only if it's the first char)
172 if ( !strExt
.empty() )
176 //else: no, don't append it
187 // set an arbitrary command:
188 // could adjust the code to ask confirmation if it already exists and
189 // overwriteprompt is true, but this is currently ignored as *Associate* has
190 // no overwrite prompt
192 wxFileTypeImpl::SetCommand(const wxString
& cmd
,
193 const wxString
& verb
,
194 bool WXUNUSED(overwriteprompt
))
196 wxArrayString strExtensions
;
197 wxString strDesc
, strIcon
;
199 wxArrayString strTypes
;
200 GetMimeTypes(strTypes
);
201 if ( strTypes
.IsEmpty() )
204 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
205 entry
->Add(verb
+ wxT("=") + cmd
+ wxT(" %s "));
208 size_t nCount
= strTypes
.GetCount();
209 for ( size_t i
= 0; i
< nCount
; i
++ )
211 if ( m_manager
->DoAssociation
220 // DoAssociation() took ownership of entry, don't delete it below
231 // ignore index on the grounds that we only have one icon in a Unix file
232 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& strIcon
, int WXUNUSED(index
))
237 wxArrayString strExtensions
;
240 wxArrayString strTypes
;
241 GetMimeTypes(strTypes
);
242 if ( strTypes
.IsEmpty() )
245 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
247 size_t nCount
= strTypes
.GetCount();
248 for ( size_t i
= 0; i
< nCount
; i
++ )
250 if ( m_manager
->DoAssociation
259 // we don't need to free entry now, DoAssociation() took ownership
271 // ----------------------------------------------------------------------------
272 // wxMimeTypesManagerImpl (Unix)
273 // ----------------------------------------------------------------------------
275 wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
277 m_initialized
= false;
280 void wxMimeTypesManagerImpl::InitIfNeeded()
282 if ( !m_initialized
)
284 // set the flag first to prevent recursion
285 m_initialized
= true;
287 wxString wm
= wxTheApp
->GetTraits()->GetDesktopEnvironment();
289 if (wm
== wxT("KDE"))
290 Initialize( wxMAILCAP_KDE
);
291 else if (wm
== wxT("GNOME"))
292 Initialize( wxMAILCAP_GNOME
);
300 // read system and user mailcaps and other files
301 void wxMimeTypesManagerImpl::Initialize(int WXUNUSED(mailcapStyles
),
302 const wxString
& WXUNUSED(sExtraDir
))
305 // XDG tables are never installed on OpenVMS
309 // Read MIME type - extension associations
310 LoadXDGGlobs( "/usr/share/mime/globs" );
311 LoadXDGGlobs( "/usr/local/share/mime/globs" );
313 // Load desktop files for XDG, and then override them with the defaults.
314 // We will override them one desktop file at a time, rather
315 // than one mime type at a time, but it should be a reasonable
318 wxString xdgDataHome
= wxGetenv("XDG_DATA_HOME");
319 if ( xdgDataHome
.empty() )
320 xdgDataHome
= wxGetHomeDir() + "/.local/share";
321 wxString xdgDataDirs
= wxGetenv("XDG_DATA_DIRS");
322 if ( xdgDataDirs
.empty() )
324 xdgDataDirs
= "/usr/local/share:/usr/share";
325 if (mailcapStyles
& wxMAILCAP_GNOME
)
326 xdgDataDirs
+= ":/usr/share/gnome:/opt/gnome/share";
327 if (mailcapStyles
& wxMAILCAP_KDE
)
328 xdgDataDirs
+= ":/usr/share/kde3:/opt/kde3/share";
330 if ( !sExtraDir
.empty() )
333 xdgDataDirs
+= sExtraDir
;
337 wxStringTokenizer
tokenizer(xdgDataDirs
, ":");
338 while ( tokenizer
.HasMoreTokens() )
340 wxString p
= tokenizer
.GetNextToken();
343 dirs
.insert(dirs
.begin(), xdgDataHome
);
345 wxString defaultsList
;
347 for (i
= 0; i
< dirs
.GetCount(); i
++)
349 wxString f
= dirs
[i
];
350 if (f
.Last() != '/') f
+= '/';
351 f
+= "applications/defaults.list";
359 // Load application files and associate them to corresponding mime types.
360 size_t nDirs
= dirs
.GetCount();
361 for (size_t nDir
= 0; nDir
< nDirs
; nDir
++)
363 wxString dirStr
= dirs
[nDir
];
364 if (dirStr
.Last() != '/') dirStr
+= '/';
365 dirStr
+= "applications";
366 LoadXDGAppsFilesFromDir(dirStr
);
369 if (!defaultsList
.IsEmpty())
371 wxArrayString deskTopFilesSeen
;
373 wxMimeTextFile
textfile(defaultsList
);
374 if ( textfile
.Open() )
376 int nIndex
= textfile
.pIndexOf( wxT("[Default Applications]") );
377 if (nIndex
!= wxNOT_FOUND
)
379 for (i
= nIndex
+1; i
< textfile
.GetLineCount(); i
++)
381 if (textfile
.GetLine(i
).Find(wxT("=")) != wxNOT_FOUND
)
383 wxString mimeType
= textfile
.GetVerb(i
);
384 wxString desktopFile
= textfile
.GetCmd(i
);
386 if (deskTopFilesSeen
.Index(desktopFile
) == wxNOT_FOUND
)
388 deskTopFilesSeen
.Add(desktopFile
);
390 for (j
= 0; j
< dirs
.GetCount(); j
++)
392 wxString desktopPath
= dirs
[j
];
393 if (desktopPath
.Last() != '/') desktopPath
+= '/';
394 desktopPath
+= "applications/";
395 desktopPath
+= desktopFile
;
397 if (wxFileExists(desktopPath
))
398 LoadXDGApp(desktopPath
);
410 // clear data so you can read another group of WM files
411 void wxMimeTypesManagerImpl::ClearData()
415 m_aExtensions
.Clear();
416 m_aDescriptions
.Clear();
418 WX_CLEAR_ARRAY(m_aEntries
);
422 wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
427 wxFileType
* wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
431 wxString strType
= ftInfo
.GetMimeType();
432 wxString strDesc
= ftInfo
.GetDescription();
433 wxString strIcon
= ftInfo
.GetIconFile();
435 wxMimeTypeCommands
*entry
= new wxMimeTypeCommands();
437 if ( ! ftInfo
.GetOpenCommand().empty())
438 entry
->Add(wxT("open=") + ftInfo
.GetOpenCommand() + wxT(" %s "));
439 if ( ! ftInfo
.GetPrintCommand().empty())
440 entry
->Add(wxT("print=") + ftInfo
.GetPrintCommand() + wxT(" %s "));
442 // now find where these extensions are in the data store and remove them
443 wxArrayString sA_Exts
= ftInfo
.GetExtensions();
444 wxString sExt
, sExtStore
;
446 size_t nExtCount
= sA_Exts
.GetCount();
447 for (i
=0; i
< nExtCount
; i
++)
449 sExt
= sA_Exts
.Item(i
);
451 // clean up to just a space before and after
452 sExt
.Trim().Trim(false);
453 sExt
= wxT(' ') + sExt
+ wxT(' ');
454 size_t nCount
= m_aExtensions
.GetCount();
455 for (nIndex
= 0; nIndex
< nCount
; nIndex
++)
457 sExtStore
= m_aExtensions
.Item(nIndex
);
458 if (sExtStore
.Replace(sExt
, wxT(" ") ) > 0)
459 m_aExtensions
.Item(nIndex
) = sExtStore
;
463 if ( !DoAssociation(strType
, strIcon
, entry
, sA_Exts
, strDesc
) )
466 return GetFileTypeFromMimeType(strType
);
469 bool wxMimeTypesManagerImpl::DoAssociation(const wxString
& strType
,
470 const wxString
& strIcon
,
471 wxMimeTypeCommands
*entry
,
472 const wxArrayString
& strExtensions
,
473 const wxString
& strDesc
)
475 int nIndex
= AddToMimeData(strType
, strIcon
, entry
, strExtensions
, strDesc
, true);
477 if ( nIndex
== wxNOT_FOUND
)
483 int wxMimeTypesManagerImpl::AddToMimeData(const wxString
& strType
,
484 const wxString
& strIcon
,
485 wxMimeTypeCommands
*entry
,
486 const wxArrayString
& strExtensions
,
487 const wxString
& strDesc
,
488 bool replaceExisting
)
492 // ensure mimetype is always lower case
493 wxString mimeType
= strType
.Lower();
495 // is this a known MIME type?
496 int nIndex
= m_aTypes
.Index(mimeType
);
497 if ( nIndex
== wxNOT_FOUND
)
500 m_aTypes
.Add(mimeType
);
501 m_aIcons
.Add(strIcon
);
502 m_aEntries
.Add(entry
? entry
: new wxMimeTypeCommands
);
504 // change nIndex so we can use it below to add the extensions
505 m_aExtensions
.Add(wxEmptyString
);
506 nIndex
= m_aExtensions
.size() - 1;
508 m_aDescriptions
.Add(strDesc
);
510 else // yes, we already have it
512 if ( replaceExisting
)
514 // if new description change it
515 if ( !strDesc
.empty())
516 m_aDescriptions
[nIndex
] = strDesc
;
518 // if new icon change it
519 if ( !strIcon
.empty())
520 m_aIcons
[nIndex
] = strIcon
;
524 delete m_aEntries
[nIndex
];
525 m_aEntries
[nIndex
] = entry
;
528 else // add data we don't already have ...
530 // if new description add only if none
531 if ( m_aDescriptions
[nIndex
].empty() )
532 m_aDescriptions
[nIndex
] = strDesc
;
534 // if new icon and no existing icon
535 if ( m_aIcons
[nIndex
].empty() )
536 m_aIcons
[nIndex
] = strIcon
;
538 // add any new entries...
541 wxMimeTypeCommands
*entryOld
= m_aEntries
[nIndex
];
543 size_t count
= entry
->GetCount();
544 for ( size_t i
= 0; i
< count
; i
++ )
546 const wxString
& verb
= entry
->GetVerb(i
);
547 if ( !entryOld
->HasVerb(verb
) )
549 entryOld
->AddOrReplaceVerb(verb
, entry
->GetCmd(i
));
553 // as we don't store it anywhere, it won't be deleted later as
554 // usual -- do it immediately instead
560 // always add the extensions to this mimetype
561 wxString
& exts
= m_aExtensions
[nIndex
];
563 // add all extensions we don't have yet
565 size_t count
= strExtensions
.GetCount();
566 for ( size_t i
= 0; i
< count
; i
++ )
568 ext
= strExtensions
[i
];
571 if ( exts
.Find(ext
) == wxNOT_FOUND
)
577 // check data integrity
578 wxASSERT( m_aTypes
.GetCount() == m_aEntries
.GetCount() &&
579 m_aTypes
.GetCount() == m_aExtensions
.GetCount() &&
580 m_aTypes
.GetCount() == m_aIcons
.GetCount() &&
581 m_aTypes
.GetCount() == m_aDescriptions
.GetCount() );
586 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
593 size_t count
= m_aExtensions
.GetCount();
594 for ( size_t n
= 0; n
< count
; n
++ )
596 wxStringTokenizer
tk(m_aExtensions
[n
], wxT(' '));
598 while ( tk
.HasMoreTokens() )
600 // consider extensions as not being case-sensitive
601 if ( tk
.GetNextToken().IsSameAs(ext
, false /* no case */) )
604 wxFileType
*fileType
= new wxFileType
;
605 fileType
->m_impl
->Init(this, n
);
615 wxFileType
* wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
619 wxFileType
* fileType
= NULL
;
620 // mime types are not case-sensitive
621 wxString
mimetype(mimeType
);
622 mimetype
.MakeLower();
624 // first look for an exact match
625 int index
= m_aTypes
.Index(mimetype
);
627 if ( index
!= wxNOT_FOUND
)
629 fileType
= new wxFileType
;
630 fileType
->m_impl
->Init(this, index
);
633 // then try to find "text/*" as match for "text/plain" (for example)
634 // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
635 // the whole string - ok.
638 wxString strCategory
= mimetype
.BeforeFirst(wxT('/'));
640 size_t nCount
= m_aTypes
.GetCount();
641 for ( size_t n
= 0; n
< nCount
; n
++ )
643 if ( (m_aTypes
[n
].BeforeFirst(wxT('/')) == strCategory
) &&
644 m_aTypes
[n
].AfterFirst(wxT('/')) == wxT("*") )
651 if ( index
!= wxNOT_FOUND
)
653 // don't throw away fileType that was already found
655 fileType
= new wxFileType
;
656 fileType
->m_impl
->Init(this, index
);
662 wxString
wxMimeTypesManagerImpl::GetCommand(const wxString
& verb
, size_t nIndex
) const
664 wxString command
, testcmd
, sV
, sTmp
;
665 sV
= verb
+ wxT("=");
667 // list of verb = command pairs for this mimetype
668 wxMimeTypeCommands
* sPairs
= m_aEntries
[nIndex
];
671 size_t nCount
= sPairs
->GetCount();
672 for ( i
= 0; i
< nCount
; i
++ )
674 sTmp
= sPairs
->GetVerbCmd (i
);
675 if ( sTmp
.Contains(sV
) )
676 command
= sTmp
.AfterFirst(wxT('='));
682 void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo
& filetype
)
687 const wxArrayString
& exts
= filetype
.GetExtensions();
688 size_t nExts
= exts
.GetCount();
689 for ( size_t nExt
= 0; nExt
< nExts
; nExt
++ )
692 extensions
+= wxT(' ');
694 extensions
+= exts
[nExt
];
697 AddMimeTypeInfo(filetype
.GetMimeType(),
699 filetype
.GetDescription());
702 void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString
& strMimeType
,
703 const wxString
& strExtensions
,
704 const wxString
& strDesc
)
706 // reading mailcap may find image/* , while
707 // reading mime.types finds image/gif and no match is made
708 // this means all the get functions don't work fix this
710 wxString sTmp
= strExtensions
;
713 sTmp
.Trim().Trim(false);
715 while (!sTmp
.empty())
717 sExts
.Add(sTmp
.AfterLast(wxT(' ')));
718 sTmp
= sTmp
.BeforeLast(wxT(' '));
721 AddToMimeData(strMimeType
, strIcon
, NULL
, sExts
, strDesc
, true);
724 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
730 size_t count
= m_aTypes
.GetCount();
731 for ( size_t n
= 0; n
< count
; n
++ )
733 // don't return template types from here (i.e. anything containg '*')
734 const wxString
&type
= m_aTypes
[n
];
735 if ( type
.Find(wxT('*')) == wxNOT_FOUND
)
741 return mimetypes
.GetCount();
744 // ----------------------------------------------------------------------------
745 // writing to MIME type files
746 // ----------------------------------------------------------------------------
748 bool wxMimeTypesManagerImpl::Unassociate(wxFileType
*ft
)
752 wxArrayString sMimeTypes
;
753 ft
->GetMimeTypes(sMimeTypes
);
756 size_t nCount
= sMimeTypes
.GetCount();
757 for (i
= 0; i
< nCount
; i
++)
759 const wxString
&sMime
= sMimeTypes
.Item(i
);
760 int nIndex
= m_aTypes
.Index(sMime
);
761 if ( nIndex
== wxNOT_FOUND
)
763 // error if we get here ??
768 m_aTypes
.RemoveAt(nIndex
);
769 m_aEntries
.RemoveAt(nIndex
);
770 m_aExtensions
.RemoveAt(nIndex
);
771 m_aDescriptions
.RemoveAt(nIndex
);
772 m_aIcons
.RemoveAt(nIndex
);
775 // check data integrity
776 wxASSERT( m_aTypes
.GetCount() == m_aEntries
.GetCount() &&
777 m_aTypes
.GetCount() == m_aExtensions
.GetCount() &&
778 m_aTypes
.GetCount() == m_aIcons
.GetCount() &&
779 m_aTypes
.GetCount() == m_aDescriptions
.GetCount() );
785 // wxUSE_MIMETYPE && wxUSE_FILE