/////////////////////////////////////////////////////////////////////////////
-// Name: unix/mimetype.cpp
+// Name: src/unix/mimetype.cpp
// Purpose: classes and functions to manage MIME types
// Author: Vadim Zeitlin
// Modified by:
// Created: 23.09.98
// RCS-ID: $Id$
// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
-// Licence: wxWindows license (part of wxExtra library)
+// Licence: wxWindows licence (part of wxExtra library)
/////////////////////////////////////////////////////////////////////////////
-// ============================================================================
-// declarations
-// ============================================================================
-
-// ----------------------------------------------------------------------------
-// headers
-// ----------------------------------------------------------------------------
-
-#ifdef __GNUG__
- #pragma implementation "mimetype.h"
-#endif
-
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
- #pragma hdrstop
+ #pragma hdrstop
#endif
-#ifndef WX_PRECOMP
- #include "wx/defs.h"
-#endif
+#if wxUSE_MIMETYPE && wxUSE_FILE
-#if wxUSE_FILE && wxUSE_TEXTFILE
+#include "wx/unix/mimetype.h"
#ifndef WX_PRECOMP
- #include "wx/string.h"
- #if wxUSE_GUI
- #include "wx/icon.h"
- #endif
-#endif //WX_PRECOMP
-
+ #include "wx/dynarray.h"
+ #include "wx/string.h"
+ #include "wx/intl.h"
+ #include "wx/log.h"
+ #include "wx/utils.h"
+#endif
-#include "wx/log.h"
#include "wx/file.h"
-#include "wx/intl.h"
-#include "wx/dynarray.h"
#include "wx/confbase.h"
#include "wx/ffile.h"
-#include "wx/textfile.h"
#include "wx/dir.h"
-#include "wx/utils.h"
#include "wx/tokenzr.h"
-
-#include "wx/unix/mimetype.h"
+#include "wx/iconloc.h"
+#include "wx/filename.h"
+#include "wx/app.h"
+#include "wx/apptrait.h"
// other standard headers
#include <ctype.h>
-// in case we're compiling in non-GUI mode
-class WXDLLEXPORT wxIcon;
-
-// ----------------------------------------------------------------------------
-// constants
-// ----------------------------------------------------------------------------
-
-// MIME code tracing mask
-#define TRACE_MIME _T("mime")
-
-// ----------------------------------------------------------------------------
-// private functions
-// ----------------------------------------------------------------------------
-
-// there are some fields which we don't understand but for which we don't give
-// warnings as we know that they're not important - this function is used to
-// test for them
-static bool IsKnownUnimportantField(const wxString& field);
-
-// ----------------------------------------------------------------------------
-// private classes
-// ----------------------------------------------------------------------------
-
-// This class uses both mailcap and mime.types to gather information about file
-// types.
-//
-// The information about mailcap file was extracted from metamail(1) sources
-// and documentation and subsequently revised when I found the RFC 1524
-// describing it.
-//
-// Format of mailcap file: spaces are ignored, each line is either a comment
-// (starts with '#') or a line of the form <field1>;<field2>;...;<fieldN>.
-// A backslash can be used to quote semicolons and newlines (and, in fact,
-// anything else including itself).
-//
-// The first field is always the MIME type in the form of type/subtype (see RFC
-// 822) where subtype may be '*' meaning "any". Following metamail, we accept
-// "type" which means the same as "type/*", although I'm not sure whether this
-// is standard.
-//
-// The second field is always the command to run. It is subject to
-// parameter/filename expansion described below.
-//
-// All the following fields are optional and may not be present at all. If
-// they're present they may appear in any order, although each of them should
-// appear only once. The optional fields are the following:
-// * notes=xxx is an uninterpreted string which is silently ignored
-// * test=xxx is the command to be used to determine whether this mailcap line
-// applies to our data or not. The RHS of this field goes through the
-// parameter/filename expansion (as the 2nd field) and the resulting string
-// is executed. The line applies only if the command succeeds, i.e. returns 0
-// exit code.
-// * print=xxx is the command to be used to print (and not view) the data of
-// this type (parameter/filename expansion is done here too)
-// * edit=xxx is the command to open/edit the data of this type
-// * needsterminal means that a new interactive console must be created for
-// the viewer
-// * copiousoutput means that the viewer doesn't interact with the user but
-// produces (possibly) a lof of lines of output on stdout (i.e. "cat" is a
-// good example), thus it might be a good idea to use some kind of paging
-// mechanism.
-// * textualnewlines means not to perform CR/LF translation (not honored)
-// * compose and composetyped fields are used to determine the program to be
-// called to create a new message pert in the specified format (unused).
-//
-// Parameter/filename expansion:
-// * %s is replaced with the (full) file name
-// * %t is replaced with MIME type/subtype of the entry
-// * for multipart type only %n is replaced with the nnumber of parts and %F is
-// replaced by an array of (content-type, temporary file name) pairs for all
-// message parts (TODO)
-// * %{parameter} is replaced with the value of parameter taken from
-// Content-type header line of the message.
-//
-//
-// There are 2 possible formats for mime.types file, one entry per line (used
-// for global mime.types and called Mosaic format) and "expanded" format where
-// an entry takes multiple lines (used for users mime.types and called
-// Netscape format).
-//
-// For both formats spaces are ignored and lines starting with a '#' are
-// comments. Each record has one of two following forms:
-// a) for "brief" format:
-// <mime type> <space separated list of extensions>
-// b) for "expanded" format:
-// type=<mime type> \
-// desc="<description>" \
-// exts="<comma separated list of extensions>"
-//
-// We try to autodetect the format of mime.types: if a non-comment line starts
-// with "type=" we assume the second format, otherwise the first one.
-
-// there may be more than one entry for one and the same mime type, to
-// choose the right one we have to run the command specified in the test
-// field on our data.
-class MailCapEntry
+class wxMimeTextFile
{
public:
- // ctor
- MailCapEntry(const wxString& openCmd,
- const wxString& printCmd,
- const wxString& testCmd)
- : m_openCmd(openCmd), m_printCmd(printCmd), m_testCmd(testCmd)
+ wxMimeTextFile()
{
- m_next = NULL;
}
-
- ~MailCapEntry()
+
+ wxMimeTextFile(const wxString& fname)
{
- if (m_next) delete m_next;
+ m_fname = fname;
}
- // accessors
- const wxString& GetOpenCmd() const { return m_openCmd; }
- const wxString& GetPrintCmd() const { return m_printCmd; }
- const wxString& GetTestCmd() const { return m_testCmd; }
+ bool Open()
+ {
+ wxFFile file( m_fname );
+ if (!file.IsOpened())
+ return false;
+
+ size_t size = file.Length();
+ wxCharBuffer buffer( size );
+ file.Read( (void*) (const char*) buffer, size );
+
+ // Check for valid UTF-8 here?
+ wxString all = wxString::FromUTF8( buffer, size );
+
+ wxStringTokenizer tok( all, "\n" );
+ while (tok.HasMoreTokens())
+ {
+ wxString t = tok.GetNextToken();
+ t.MakeLower();
+ if ((!!t) && (t.Find( "comment" ) != 0) && (t.Find( "#" ) != 0) && (t.Find( "generic" ) != 0))
+ m_text.Add( t );
+ }
+ return true;
+ }
- MailCapEntry *GetNext() const { return m_next; }
+ unsigned int GetLineCount() const { return m_text.GetCount(); }
+ wxString &GetLine( unsigned int line ) { return m_text[line]; }
- // operations
- // prepend this element to the list
- void Prepend(MailCapEntry *next) { m_next = next; }
- // insert into the list at given position
- void Insert(MailCapEntry *next, size_t pos)
+ int pIndexOf(const wxString& sSearch,
+ bool bIncludeComments = false,
+ int iStart = 0)
{
- // FIXME slooow...
- MailCapEntry *cur;
- size_t n = 0;
- for ( cur = next; cur != NULL; cur = cur->m_next, n++ ) {
- if ( n == pos )
- break;
+ wxString sTest = sSearch;
+ sTest.MakeLower();
+ for(size_t i = iStart; i < GetLineCount(); i++)
+ {
+ wxString sLine = GetLine(i);
+ if(bIncludeComments || ! sLine.StartsWith(wxT("#")))
+ {
+ if(sLine.StartsWith(sTest))
+ return (int)i;
+ }
}
-
- wxASSERT_MSG( n == pos, wxT("invalid position in MailCapEntry::Insert") );
-
- m_next = cur->m_next;
- cur->m_next = this;
+ return wxNOT_FOUND;
}
- // append this element to the list
- void Append(MailCapEntry *next)
- {
- wxCHECK_RET( next != NULL, wxT("Append()ing to what?") );
-
- // FIXME slooow...
- MailCapEntry *cur;
- for ( cur = next; cur->m_next != NULL; cur = cur->m_next )
- ;
- cur->m_next = this;
+ wxString GetVerb(size_t i)
+ {
+ if (i > GetLineCount() )
+ return wxEmptyString;
- wxASSERT_MSG( !m_next, wxT("Append()ing element already in the list?") );
+ wxString sTmp = GetLine(i).BeforeFirst(wxT('='));
+ return sTmp;
}
-private:
- wxString m_openCmd, // command to use to open/view the file
- m_printCmd, // print
- m_testCmd; // only apply this entry if test yields
- // true (i.e. the command returns 0)
-
- MailCapEntry *m_next; // in the linked list
-};
-
-
-// the base class which may be used to find an icon for the MIME type
-class wxMimeTypeIconHandler
-{
-public:
- virtual bool GetIcon(const wxString& mimetype, wxIcon *icon) = 0;
-
- // this function fills manager with MIME types information gathered
- // (as side effect) when searching for icons. This may be particularly
- // useful if mime.types is incomplete (e.g. RedHat distributions).
- virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager) = 0;
-};
-
-
-// the icon handler which uses GNOME MIME database
-class wxGNOMEIconHandler : public wxMimeTypeIconHandler
-{
-public:
- virtual bool GetIcon(const wxString& mimetype, wxIcon *icon);
- virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager);
-
-private:
- void Init();
- void LoadIconsFromKeyFile(const wxString& filename);
- void LoadKeyFilesFromDir(const wxString& dirbase);
-
- void LoadMimeTypesFromMimeFile(const wxString& filename, wxMimeTypesManagerImpl *manager);
- void LoadMimeFilesFromDir(const wxString& dirbase, wxMimeTypesManagerImpl *manager);
-
- static bool m_inited;
-
- static wxSortedArrayString ms_mimetypes;
- static wxArrayString ms_icons;
-};
+ wxString GetCmd(size_t i)
+ {
+ if (i > GetLineCount() )
+ return wxEmptyString;
-// the icon handler which uses KDE MIME database
-class wxKDEIconHandler : public wxMimeTypeIconHandler
-{
-public:
- virtual bool GetIcon(const wxString& mimetype, wxIcon *icon);
- virtual void GetMimeInfoRecords(wxMimeTypesManagerImpl *manager);
+ wxString sTmp = GetLine(i).AfterFirst(wxT('='));
+ return sTmp;
+ }
private:
- void LoadLinksForMimeSubtype(const wxString& dirbase,
- const wxString& subdir,
- const wxString& filename,
- const wxArrayString& icondirs);
- void LoadLinksForMimeType(const wxString& dirbase,
- const wxString& subdir,
- const wxArrayString& icondirs);
- void LoadLinkFilesFromDir(const wxString& dirbase,
- const wxArrayString& icondirs);
- void Init();
-
- static bool m_inited;
-
- static wxSortedArrayString ms_mimetypes;
- static wxArrayString ms_icons;
-
- static wxArrayString ms_infoTypes;
- static wxArrayString ms_infoDescriptions;
- static wxArrayString ms_infoExtensions;
+ wxArrayString m_text;
+ wxString m_fname;
};
-
-
-// ----------------------------------------------------------------------------
-// various statics
// ----------------------------------------------------------------------------
-
-static wxGNOMEIconHandler gs_iconHandlerGNOME;
-static wxKDEIconHandler gs_iconHandlerKDE;
-
-bool wxGNOMEIconHandler::m_inited = FALSE;
-wxSortedArrayString wxGNOMEIconHandler::ms_mimetypes;
-wxArrayString wxGNOMEIconHandler::ms_icons;
-
-bool wxKDEIconHandler::m_inited = FALSE;
-wxSortedArrayString wxKDEIconHandler::ms_mimetypes;
-wxArrayString wxKDEIconHandler::ms_icons;
-
-wxArrayString wxKDEIconHandler::ms_infoTypes;
-wxArrayString wxKDEIconHandler::ms_infoDescriptions;
-wxArrayString wxKDEIconHandler::ms_infoExtensions;
-
-
-ArrayIconHandlers wxMimeTypesManagerImpl::ms_iconHandlers;
-
-// ----------------------------------------------------------------------------
-// wxGNOMEIconHandler
+// constants
// ----------------------------------------------------------------------------
-// GNOME stores the info we're interested in in several locations:
-// 1. xxx.keys files under /usr/share/mime-info
-// 2. xxx.keys files under ~/.gnome/mime-info
-//
-// The format of xxx.keys file is the following:
-//
-// mimetype/subtype:
-// field=value
-//
-// with blank lines separating the entries and indented lines starting with
-// TABs. We're interested in the field icon-filename whose value is the path
-// containing the icon.
-//
-// Update (Chris Elliott): apparently there may be an optional "[lang]" prefix
-// just before the field name.
-
-void wxGNOMEIconHandler::LoadIconsFromKeyFile(const wxString& filename)
-{
- wxTextFile textfile(filename);
- if ( !textfile.Open() )
- return;
-
- // values for the entry being parsed
- wxString curMimeType, curIconFile;
-
- const wxChar *pc;
- size_t nLineCount = textfile.GetLineCount();
- for ( size_t nLine = 0; ; nLine++ )
- {
- if ( nLine < nLineCount )
- {
- pc = textfile[nLine].c_str();
- if ( *pc == _T('#') )
- {
- // skip comments
- continue;
- }
- }
- else
- {
- // so that we will fall into the "if" below
- pc = NULL;
- }
-
- if ( !pc || !*pc )
- {
- // end of the entry
- if ( !!curMimeType && !!curIconFile )
- {
- // do we already know this mimetype?
- int i = ms_mimetypes.Index(curMimeType);
- if ( i == wxNOT_FOUND )
- {
- // add a new entry
- size_t n = ms_mimetypes.Add(curMimeType);
- ms_icons.Insert(curIconFile, n);
- }
- else
- {
- // replace the existing one (this means that the directories
- // should be searched in order of increased priority!)
- ms_icons[(size_t)i] = curIconFile;
- }
- }
-
- if ( !pc )
- {
- // the end - this can only happen if nLine == nLineCount
- break;
- }
-
- curIconFile.Empty();
-
- continue;
- }
-
- // what do we have here?
- if ( *pc == _T('\t') )
- {
- // this is a field=value ling
- pc++; // skip leading TAB
-
- // skip optional "[lang]"
- if ( *pc == _T('[') )
- {
- while ( *pc )
- {
- if ( *pc++ == _T(']') )
- break;
- }
- }
-
- static const int lenField = 13; // strlen("icon-filename")
- if ( wxStrncmp(pc, _T("icon-filename"), lenField) == 0 )
- {
- // skip '=' which follows and take everything left until the end
- // of line
- curIconFile = pc + lenField + 1;
- }
- //else: some other field, we don't care
- }
- else
- {
- // this is the start of the new section
- curMimeType.Empty();
+// MIME code tracing mask
+#define TRACE_MIME wxT("mime")
- while ( *pc != _T(':') && *pc != _T('\0') )
- {
- curMimeType += *pc++;
- }
- }
- }
-}
-void wxGNOMEIconHandler::LoadKeyFilesFromDir(const wxString& dirbase)
+// Read a XDG *.desktop file of type 'Application'
+void wxMimeTypesManagerImpl::LoadXDGApp(const wxString& filename)
{
- wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
- _T("base directory shouldn't end with a slash") );
-
- wxString dirname = dirbase;
- dirname << _T("/mime-info");
+ wxLogTrace(TRACE_MIME, wxT("loading XDG file %s"), filename.c_str());
- if ( !wxDir::Exists(dirname) )
+ wxMimeTextFile file(filename);
+ if ( !file.Open() )
return;
- wxDir dir(dirname);
- if ( !dir.IsOpened() )
+ // Here, only type 'Application' should be considered.
+ int nIndex = file.pIndexOf( "Type=" );
+ if (nIndex != wxNOT_FOUND && file.GetCmd(nIndex) != "application")
return;
- // we will concatenate it with filename to get the full path below
- dirname += _T('/');
-
- wxString filename;
- bool cont = dir.GetFirst(&filename, _T("*.keys"), wxDIR_FILES);
- while ( cont )
- {
- LoadIconsFromKeyFile(dirname + filename);
+ // The hidden entry specifies a file to be ignored.
+ nIndex = file.pIndexOf( "Hidden=" );
+ if (nIndex != wxNOT_FOUND && file.GetCmd(nIndex) == "true")
+ return;
- cont = dir.GetNext(&filename);
+ // Semicolon separated list of mime types handled by the application.
+ nIndex = file.pIndexOf( wxT("MimeType=") );
+ if (nIndex == wxNOT_FOUND)
+ return;
+ wxString mimetypes = file.GetCmd (nIndex);
+
+ // Name of the application
+ wxString nameapp;
+ nIndex = wxNOT_FOUND;
+#if wxUSE_INTL // try "Name[locale name]" first
+ wxLocale *locale = wxGetLocale();
+ if ( locale )
+ nIndex = file.pIndexOf(wxT("Name[")+locale->GetName()+wxT("]="));
+#endif // wxUSE_INTL
+ if(nIndex == wxNOT_FOUND)
+ nIndex = file.pIndexOf( wxT("Name=") );
+ if(nIndex != wxNOT_FOUND)
+ nameapp = file.GetCmd(nIndex);
+
+ // Icon of the application.
+ wxString nameicon, namemini;
+ nIndex = wxNOT_FOUND;
+#if wxUSE_INTL // try "Icon[locale name]" first
+ if ( locale )
+ nIndex = file.pIndexOf(wxT("Icon[")+locale->GetName()+wxT("]="));
+#endif // wxUSE_INTL
+ if(nIndex == wxNOT_FOUND)
+ nIndex = file.pIndexOf( wxT("Icon=") );
+ if(nIndex != wxNOT_FOUND) {
+ nameicon = wxString(wxT("--icon ")) + file.GetCmd(nIndex);
+ namemini = wxString(wxT("--miniicon ")) + file.GetCmd(nIndex);
}
-}
-
-void wxGNOMEIconHandler::LoadMimeTypesFromMimeFile(const wxString& filename, wxMimeTypesManagerImpl *manager)
-{
- wxTextFile textfile(filename);
- if ( !textfile.Open() )
+ // Replace some of the field code in the 'Exec' entry.
+ // TODO: deal with %d, %D, %n, %N, %k and %v (but last one is deprecated)
+ nIndex = file.pIndexOf( wxT("Exec=") );
+ if (nIndex == wxNOT_FOUND)
return;
-
- // values for the entry being parsed
- wxString curMimeType, curExtList;
-
- const wxChar *pc;
- size_t nLineCount = textfile.GetLineCount();
- for ( size_t nLine = 0; ; nLine++ )
- {
- if ( nLine < nLineCount )
- {
- pc = textfile[nLine].c_str();
- if ( *pc == _T('#') )
- {
- // skip comments
- continue;
- }
- }
- else
- {
- // so that we will fall into the "if" below
- pc = NULL;
- }
-
- if ( !pc || !*pc )
- {
- // end of the entry
- if ( !!curMimeType && !!curExtList )
- {
- manager -> AddMimeTypeInfo(curMimeType, curExtList, wxEmptyString);
- }
-
- if ( !pc )
- {
- // the end - this can only happen if nLine == nLineCount
- break;
- }
-
- curExtList.Empty();
-
- continue;
- }
-
- // what do we have here?
- if ( *pc == _T('\t') )
- {
- // this is a field=value ling
- pc++; // skip leading TAB
-
- static const int lenField = 4; // strlen("ext:")
- if ( wxStrncmp(pc, _T("ext:"), lenField) == 0 )
- {
- // skip ' ' which follows and take everything left until the end
- // of line
- curExtList = pc + lenField + 1;
- }
- //else: some other field, we don't care
- }
- else
- {
- // this is the start of the new section
- curMimeType.Empty();
-
- while ( *pc != _T(':') && *pc != _T('\0') )
- {
- curMimeType += *pc++;
- }
+ wxString sCmd = file.GetCmd(nIndex);
+ // we expect %f; others including %F and %U and %u are possible
+ sCmd.Replace(wxT("%F"), wxT("%f"));
+ sCmd.Replace(wxT("%U"), wxT("%f"));
+ sCmd.Replace(wxT("%u"), wxT("%f"));
+ if (0 == sCmd.Replace ( wxT("%f"), wxT("%s") ))
+ sCmd = sCmd + wxT(" %s");
+ sCmd.Replace(wxT("%c"), nameapp);
+ sCmd.Replace(wxT("%i"), nameicon);
+ sCmd.Replace(wxT("%m"), namemini);
+
+ wxStringTokenizer tokenizer(mimetypes, wxT(";"));
+ while(tokenizer.HasMoreTokens()) {
+ wxString mimetype = tokenizer.GetNextToken().Lower();
+ nIndex = m_aTypes.Index(mimetype);
+ if(nIndex != wxNOT_FOUND) { // is this a known MIME type?
+ wxMimeTypeCommands* entry = m_aEntries[nIndex];
+ entry->AddOrReplaceVerb(wxT("open"), sCmd);
}
}
}
-
-void wxGNOMEIconHandler::LoadMimeFilesFromDir(const wxString& dirbase, wxMimeTypesManagerImpl *manager)
+void wxMimeTypesManagerImpl::LoadXDGAppsFilesFromDir(const wxString& dirname)
{
- wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
- _T("base directory shouldn't end with a slash") );
-
- wxString dirname = dirbase;
- dirname << _T("/mime-info");
+ // Don't complain if we don't have permissions to read - it confuses users
+ wxLogNull logNull;
- if ( !wxDir::Exists(dirname) )
+ if(! wxDir::Exists(dirname))
return;
-
wxDir dir(dirname);
if ( !dir.IsOpened() )
return;
- // we will concatenate it with filename to get the full path below
- dirname += _T('/');
-
wxString filename;
- bool cont = dir.GetFirst(&filename, _T("*.mime"), wxDIR_FILES);
- while ( cont )
+ // Look into .desktop files
+ bool cont = dir.GetFirst(&filename, wxT("*.desktop"), wxDIR_FILES);
+ while (cont)
{
- LoadMimeTypesFromMimeFile(dirname + filename, manager);
-
+ wxFileName p(dirname, filename);
+ LoadXDGApp( p.GetFullPath() );
cont = dir.GetNext(&filename);
}
-}
-
-
-void wxGNOMEIconHandler::Init()
-{
- wxArrayString dirs;
- dirs.Add(_T("/usr/share"));
- dirs.Add(_T("/usr/local/share"));
-
- wxString gnomedir;
- wxGetHomeDir( &gnomedir );
- gnomedir += _T("/.gnome");
- dirs.Add( gnomedir );
-
- size_t nDirs = dirs.GetCount();
- for ( size_t nDir = 0; nDir < nDirs; nDir++ )
- {
- LoadKeyFilesFromDir(dirs[nDir]);
- }
-
- m_inited = TRUE;
-}
-
-
-void wxGNOMEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl *manager)
-{
- if ( !m_inited )
- {
- Init();
- }
-
- wxArrayString dirs;
- dirs.Add(_T("/usr/share"));
- dirs.Add(_T("/usr/local/share"));
-
- wxString gnomedir;
- wxGetHomeDir( &gnomedir );
- gnomedir += _T("/.gnome");
- dirs.Add( gnomedir );
-
- size_t nDirs = dirs.GetCount();
- for ( size_t nDir = 0; nDir < nDirs; nDir++ )
- {
- LoadMimeFilesFromDir(dirs[nDir], manager);
- }
-}
-#if wxUSE_GUI
- #define WXUNUSED_UNLESS_GUI(p) p
-#else
- #define WXUNUSED_UNLESS_GUI(p)
-#endif
+#if 0
+ // RR: I'm not sure this makes any sense. On my system we'll just
+ // scan the YAST2 and other useless directories
-bool wxGNOMEIconHandler::GetIcon(const wxString& mimetype,
- wxIcon * WXUNUSED_UNLESS_GUI(icon))
-{
- if ( !m_inited )
+ // Look recursively into subdirs
+ cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_DIRS);
+ while (cont)
{
- Init();
+ wxFileName p(dirname, wxEmptyString);
+ p.AppendDir(filename);
+ LoadXDGAppsFilesFromDir( p.GetPath() );
+ cont = dir.GetNext(&filename);
}
-
- int index = ms_mimetypes.Index(mimetype);
- if ( index == wxNOT_FOUND )
- return FALSE;
-
- wxString iconname = ms_icons[(size_t)index];
-
-#if wxUSE_GUI
- wxLogNull nolog;
- wxIcon icn;
- if (iconname.Right(4).MakeUpper() == _T(".XPM"))
- icn = wxIcon(iconname);
- else
- icn = wxIcon(iconname, wxBITMAP_TYPE_ANY);
- if ( !icn.Ok() )
- return FALSE;
-
- if ( icon )
- *icon = icn;
-#else
- // helpful for testing in console mode
- wxLogTrace(TRACE_MIME, _T("Found GNOME icon for '%s': '%s'\n"),
- mimetype.c_str(), iconname.c_str());
#endif
-
- return TRUE;
}
-// ----------------------------------------------------------------------------
-// wxKDEIconHandler
-// ----------------------------------------------------------------------------
-// KDE stores the icon info in its .kdelnk files. The file for mimetype/subtype
-// may be found in either of the following locations
-//
-// 1. $KDEDIR/share/mimelnk/mimetype/subtype.kdelnk
-// 2. ~/.kde/share/mimelnk/mimetype/subtype.kdelnk
-//
-// The format of a .kdelnk file is almost the same as the one used by
-// wxFileConfig, i.e. there are groups, comments and entries. The icon is the
-// value for the entry "Type"
-
-void wxKDEIconHandler::LoadLinksForMimeSubtype(const wxString& dirbase,
- const wxString& subdir,
- const wxString& filename,
- const wxArrayString& icondirs)
+void wxMimeTypesManagerImpl::LoadXDGGlobs(const wxString& filename)
{
- wxFFile file(dirbase + filename);
- if ( !file.IsOpened() )
- return;
-
- // construct mimetype from the directory name and the basename of the
- // file (it always has .kdelnk extension)
- wxString mimetype;
- mimetype << subdir << _T('/') << filename.BeforeLast(_T('.'));
-
- // these files are small, slurp the entire file at once
- wxString text;
- if ( !file.ReadAll(&text) )
+ if ( !wxFileName::FileExists(filename) )
return;
- int pos;
- const wxChar *pc;
-
- // before trying to find an icon, grab mimetype information
- // (because BFU's machine would hardly have well-edited mime.types but (s)he might
- // have edited it in control panel...)
-
- wxString mime_extension, mime_desc;
-
- pos = wxNOT_FOUND;
- if (wxGetLocale() != NULL)
- mime_desc = _T("Comment[") + wxGetLocale()->GetName() + _T("]=");
- if (pos == wxNOT_FOUND) mime_desc = _T("Comment=");
- pos = text.Find(mime_desc);
- if (pos == wxNOT_FOUND) mime_desc = wxEmptyString;
- else
- {
- pc = text.c_str() + pos + mime_desc.Length();
- mime_desc = wxEmptyString;
- while ( *pc && *pc != _T('\n') ) mime_desc += *pc++;
- }
-
- pos = text.Find(_T("Patterns="));
- if (pos != wxNOT_FOUND)
- {
- wxString exts;
- pc = text.c_str() + pos + 9;
- while ( *pc && *pc != _T('\n') ) exts += *pc++;
- wxStringTokenizer tokenizer(exts, _T(";"));
- wxString e;
-
- while (tokenizer.HasMoreTokens())
- {
- e = tokenizer.GetNextToken();
- if (e.Left(2) != _T("*.")) continue; // don't support too difficult patterns
- mime_extension << e.Mid(2);
- mime_extension << _T(' ');
- }
- mime_extension.RemoveLast();
- }
-
- ms_infoTypes.Add(mimetype);
- ms_infoDescriptions.Add(mime_desc);
- ms_infoExtensions.Add(mime_extension);
+ wxLogTrace(TRACE_MIME, wxT("loading XDG globs file from %s"), filename.c_str());
- // ok, now we can take care of icon:
-
- pos = text.Find(_T("Icon="));
- if ( pos == wxNOT_FOUND )
- {
- // no icon info
+ wxMimeTextFile file(filename);
+ if ( !file.Open() )
return;
- }
-
- wxString icon;
- pc = text.c_str() + pos + 5; // 5 == strlen("Icon=")
- while ( *pc && *pc != _T('\n') )
+ size_t i;
+ for (i = 0; i < file.GetLineCount(); i++)
{
- icon += *pc++;
- }
-
- if ( !!icon )
- {
- // we must check if the file exists because it may be stored
- // in many locations, at least ~/.kde and $KDEDIR
- size_t nDir, nDirs = icondirs.GetCount();
- for ( nDir = 0; nDir < nDirs; nDir++ )
- if (wxFileExists(icondirs[nDir] + icon))
- {
- icon.Prepend(icondirs[nDir]);
- break;
- }
- if (nDir == nDirs) return; //does not exist
-
- // do we already have this MIME type?
- int i = ms_mimetypes.Index(mimetype);
- if ( i == wxNOT_FOUND )
- {
- // add it
- size_t n = ms_mimetypes.Add(mimetype);
- ms_icons.Insert(icon, n);
- }
- else
- {
- // replace the old value
- ms_icons[(size_t)i] = icon;
- }
+ wxStringTokenizer tok( file.GetLine(i), ":" );
+ wxString mime = tok.GetNextToken();
+ wxString ext = tok.GetNextToken();
+ ext.Remove( 0, 2 );
+ wxArrayString exts;
+ exts.Add( ext );
+
+ AddToMimeData(mime, wxEmptyString, NULL, exts, wxEmptyString, true );
}
}
-void wxKDEIconHandler::LoadLinksForMimeType(const wxString& dirbase,
- const wxString& subdir,
- const wxArrayString& icondirs)
-{
- wxString dirname = dirbase;
- dirname += subdir;
- wxDir dir(dirname);
- if ( !dir.IsOpened() )
- return;
-
- dirname += _T('/');
-
- wxString filename;
- bool cont = dir.GetFirst(&filename, _T("*.kdelnk"), wxDIR_FILES);
- while ( cont )
- {
- LoadLinksForMimeSubtype(dirname, subdir, filename, icondirs);
-
- cont = dir.GetNext(&filename);
- }
-}
+// ----------------------------------------------------------------------------
+// wxFileTypeImpl (Unix)
+// ----------------------------------------------------------------------------
-void wxKDEIconHandler::LoadLinkFilesFromDir(const wxString& dirbase,
- const wxArrayString& icondirs)
+wxString wxFileTypeImpl::GetExpandedCommand(const wxString & verb, const wxFileType::MessageParameters& params) const
{
- wxASSERT_MSG( !!dirbase && !wxEndsWithPathSeparator(dirbase),
- _T("base directory shouldn't end with a slash") );
-
- wxString dirname = dirbase;
- dirname << _T("/mimelnk");
-
- if ( !wxDir::Exists(dirname) )
- return;
-
- wxDir dir(dirname);
- if ( !dir.IsOpened() )
- return;
-
- // we will concatenate it with dir name to get the full path below
- dirname += _T('/');
-
- wxString subdir;
- bool cont = dir.GetFirst(&subdir, wxEmptyString, wxDIR_DIRS);
- while ( cont )
+ wxString sTmp;
+ size_t i = 0;
+ while ( (i < m_index.GetCount() ) && sTmp.empty() )
{
- LoadLinksForMimeType(dirname, subdir, icondirs);
-
- cont = dir.GetNext(&subdir);
+ sTmp = m_manager->GetCommand( verb, m_index[i] );
+ i++;
}
+
+ return wxFileType::ExpandCommand(sTmp, params);
}
-void wxKDEIconHandler::Init()
+bool wxFileTypeImpl::GetIcon(wxIconLocation *iconLoc) const
{
- wxArrayString dirs;
- wxArrayString icondirs;
-
- // settings in ~/.kde have maximal priority
- dirs.Add(wxGetHomeDir() + _T("/.kde/share"));
- icondirs.Add(wxGetHomeDir() + _T("/.kde/share/icons/"));
-
- // the variable KDEDIR is set when KDE is running
- const char *kdedir = getenv("KDEDIR");
- if ( kdedir )
- {
- dirs.Add(wxString(kdedir) + _T("/share"));
- icondirs.Add(wxString(kdedir) + _T("/share/icons/"));
- }
- else
+ wxString sTmp;
+ size_t i = 0;
+ while ( (i < m_index.GetCount() ) && sTmp.empty() )
{
- // try to guess KDEDIR
- dirs.Add(_T("/usr/share"));
- dirs.Add(_T("/opt/kde/share"));
- icondirs.Add(_T("/usr/share/icons/"));
- icondirs.Add(_T("/usr/X11R6/share/icons/")); // Debian/Corel linux
- icondirs.Add(_T("/opt/kde/share/icons/"));
+ sTmp = m_manager->m_aIcons[m_index[i]];
+ i++;
}
- size_t nDirs = dirs.GetCount();
- for ( size_t nDir = 0; nDir < nDirs; nDir++ )
- {
- LoadLinkFilesFromDir(dirs[nDir], icondirs);
- }
-
- m_inited = TRUE;
-}
+ if ( sTmp.empty() )
+ return false;
-bool wxKDEIconHandler::GetIcon(const wxString& mimetype,
- wxIcon * WXUNUSED_UNLESS_GUI(icon))
-{
- if ( !m_inited )
+ if ( iconLoc )
{
- Init();
+ iconLoc->SetFileName(sTmp);
}
- int index = ms_mimetypes.Index(mimetype);
- if ( index == wxNOT_FOUND )
- return FALSE;
-
- wxString iconname = ms_icons[(size_t)index];
-
-#if wxUSE_GUI
- wxLogNull nolog;
- wxIcon icn;
- if (iconname.Right(4).MakeUpper() == _T(".XPM"))
- icn = wxIcon(iconname);
- else
- icn = wxIcon(iconname, wxBITMAP_TYPE_ANY);
-
- if ( !icn.Ok() )
- return FALSE;
-
- if ( icon )
- *icon = icn;
-#else
- // helpful for testing in console mode
- wxLogTrace(TRACE_MIME, _T("Found KDE icon for '%s': '%s'\n"),
- mimetype.c_str(), iconname.c_str());
-#endif
-
- return TRUE;
-}
-
-
-void wxKDEIconHandler::GetMimeInfoRecords(wxMimeTypesManagerImpl *manager)
-{
- if ( !m_inited ) Init();
-
- size_t cnt = ms_infoTypes.GetCount();
- for (unsigned i = 0; i < cnt; i++)
- manager -> AddMimeTypeInfo(ms_infoTypes[i], ms_infoExtensions[i], ms_infoDescriptions[i]);
+ return true;
}
-
-// ----------------------------------------------------------------------------
-// wxFileTypeImpl (Unix)
-// ----------------------------------------------------------------------------
-
-MailCapEntry *
-wxFileTypeImpl::GetEntry(const wxFileType::MessageParameters& params) const
+bool wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
{
- wxString command;
- MailCapEntry *entry = m_manager->m_aEntries[m_index[0]];
- while ( entry != NULL ) {
- // get the command to run as the test for this entry
- command = wxFileType::ExpandCommand(entry->GetTestCmd(), params);
-
- // don't trace the test result if there is no test at all
- if ( command.IsEmpty() )
- {
- // no test at all, ok
- break;
- }
-
- if ( wxSystem(command) == 0 ) {
- // ok, test passed
- wxLogTrace(TRACE_MIME,
- wxT("Test '%s' for mime type '%s' succeeded."),
- command.c_str(), params.GetMimeType().c_str());
- break;
- }
- else {
- wxLogTrace(TRACE_MIME,
- wxT("Test '%s' for mime type '%s' failed."),
- command.c_str(), params.GetMimeType().c_str());
- }
-
- entry = entry->GetNext();
- }
+ mimeTypes.Clear();
+ size_t nCount = m_index.GetCount();
+ for (size_t i = 0; i < nCount; i++)
+ mimeTypes.Add(m_manager->m_aTypes[m_index[i]]);
- return entry;
+ return true;
}
-bool wxFileTypeImpl::GetIcon(wxIcon *icon) const
+size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
+ wxArrayString *commands,
+ const wxFileType::MessageParameters& params) const
{
- wxArrayString mimetypes;
- GetMimeTypes(mimetypes);
+ wxString vrb, cmd, sTmp;
+ size_t count = 0;
+ wxMimeTypeCommands * sPairs;
- ArrayIconHandlers& handlers = m_manager->GetIconHandlers();
- size_t count = handlers.GetCount();
- size_t counttypes = mimetypes.GetCount();
- for ( size_t n = 0; n < count; n++ )
+ // verbs and commands have been cleared already in mimecmn.cpp...
+ // if we find no entries in the exact match, try the inexact match
+ for (size_t n = 0; ((count == 0) && (n < m_index.GetCount())); n++)
{
- for ( size_t n2 = 0; n2 < counttypes; n2++ )
+ // list of verb = command pairs for this mimetype
+ sPairs = m_manager->m_aEntries [m_index[n]];
+ size_t i;
+ for ( i = 0; i < sPairs->GetCount(); i++ )
{
- if ( handlers[n]->GetIcon(mimetypes[n2], icon) )
- return TRUE;
+ vrb = sPairs->GetVerb(i);
+ // some gnome entries have "." inside
+ vrb = vrb.AfterLast(wxT('.'));
+ cmd = sPairs->GetCmd(i);
+ if (! cmd.empty() )
+ {
+ cmd = wxFileType::ExpandCommand(cmd, params);
+ count++;
+ if ( vrb.IsSameAs(wxT("open")))
+ {
+ if ( verbs )
+ verbs->Insert(vrb, 0u);
+ if ( commands )
+ commands ->Insert(cmd, 0u);
+ }
+ else
+ {
+ if ( verbs )
+ verbs->Add(vrb);
+ if ( commands )
+ commands->Add(cmd);
+ }
+ }
}
}
- return FALSE;
-}
-
-
-bool
-wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
-{
- mimeTypes.Clear();
- for (size_t i = 0; i < m_index.GetCount(); i++)
- mimeTypes.Add(m_manager->m_aTypes[m_index[i]]);
- return TRUE;
-}
-
-
-bool
-wxFileTypeImpl::GetExpandedCommand(wxString *expandedCmd,
- const wxFileType::MessageParameters& params,
- bool open) const
-{
- MailCapEntry *entry = GetEntry(params);
- if ( entry == NULL ) {
- // all tests failed...
- return FALSE;
- }
-
- wxString cmd = open ? entry->GetOpenCmd() : entry->GetPrintCmd();
- if ( cmd.IsEmpty() ) {
- // may happen, especially for "print"
- return FALSE;
- }
-
- *expandedCmd = wxFileType::ExpandCommand(cmd, params);
- return TRUE;
+ return count;
}
bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
{
- wxString strExtensions = m_manager->GetExtension(m_index[0]);
+ const wxString strExtensions = m_manager->GetExtension(m_index[0]);
extensions.Empty();
- // one extension in the space or comma delimitid list
+ // one extension in the space or comma-delimited list
wxString strExt;
- for ( const wxChar *p = strExtensions; ; p++ ) {
- if ( *p == wxT(' ') || *p == wxT(',') || *p == wxT('\0') ) {
- if ( !strExt.IsEmpty() ) {
+ wxString::const_iterator end = strExtensions.end();
+ for ( wxString::const_iterator p = strExtensions.begin(); /* nothing */; ++p )
+ {
+ if ( p == end || *p == wxT(' ') || *p == wxT(',') )
+ {
+ if ( !strExt.empty() )
+ {
extensions.Add(strExt);
strExt.Empty();
}
- //else: repeated spaces (shouldn't happen, but it's not that
- // important if it does happen)
+ //else: repeated spaces
+ // (shouldn't happen, but it's not that important if it does happen)
- if ( *p == wxT('\0') )
+ if ( p == end )
break;
}
- else if ( *p == wxT('.') ) {
+ else if ( *p == wxT('.') )
+ {
// remove the dot from extension (but only if it's the first char)
- if ( !strExt.IsEmpty() ) {
+ if ( !strExt.empty() )
+ {
strExt += wxT('.');
}
//else: no, don't append it
}
- else {
+ else
+ {
strExt += *p;
}
}
- return TRUE;
+ return true;
}
-// ----------------------------------------------------------------------------
-// wxMimeTypesManagerImpl (Unix)
-// ----------------------------------------------------------------------------
-
-/* static */
-ArrayIconHandlers& wxMimeTypesManagerImpl::GetIconHandlers()
+// set an arbitrary command:
+// could adjust the code to ask confirmation if it already exists and
+// overwriteprompt is true, but this is currently ignored as *Associate* has
+// no overwrite prompt
+bool
+wxFileTypeImpl::SetCommand(const wxString& cmd,
+ const wxString& verb,
+ bool WXUNUSED(overwriteprompt))
{
- if ( ms_iconHandlers.GetCount() == 0 )
+ wxArrayString strExtensions;
+ wxString strDesc, strIcon;
+
+ wxArrayString strTypes;
+ GetMimeTypes(strTypes);
+ if ( strTypes.IsEmpty() )
+ return false;
+
+ wxMimeTypeCommands *entry = new wxMimeTypeCommands();
+ entry->Add(verb + wxT("=") + cmd + wxT(" %s "));
+
+ bool ok = false;
+ size_t nCount = strTypes.GetCount();
+ for ( size_t i = 0; i < nCount; i++ )
{
- ms_iconHandlers.Add(&gs_iconHandlerGNOME);
- ms_iconHandlers.Add(&gs_iconHandlerKDE);
+ if ( m_manager->DoAssociation
+ (
+ strTypes[i],
+ strIcon,
+ entry,
+ strExtensions,
+ strDesc
+ ) )
+ {
+ // DoAssociation() took ownership of entry, don't delete it below
+ ok = true;
+ }
}
- return ms_iconHandlers;
-}
+ if ( !ok )
+ delete entry;
-wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
-{
- m_initialized = FALSE;
+ return ok;
}
-// read system and user mailcaps and other files
-void wxMimeTypesManagerImpl::Initialize()
+// ignore index on the grounds that we only have one icon in a Unix file
+bool wxFileTypeImpl::SetDefaultIcon(const wxString& strIcon, int WXUNUSED(index))
{
- // directories where we look for mailcap and mime.types by default
- // (taken from metamail(1) sources)
- //
- // although RFC 1524 specifies the search path of
- // /etc/:/usr/etc:/usr/local/etc only, it doesn't hurt to search in more
- // places - OTOH, the RFC also says that this path can be changed with
- // MAILCAPS environment variable (containing the colon separated full
- // filenames to try) which is not done yet (TODO?)
- static const wxChar *aStandardLocations[] =
- {
- wxT("/etc"),
- wxT("/usr/etc"),
- wxT("/usr/local/etc"),
- wxT("/etc/mail"),
- wxT("/usr/public/lib")
- };
-
- // first read the system wide file(s)
- size_t n;
- for ( n = 0; n < WXSIZEOF(aStandardLocations); n++ ) {
- wxString dir = aStandardLocations[n];
-
- wxString file = dir + wxT("/mailcap");
- if ( wxFile::Exists(file) ) {
- ReadMailcap(file);
- }
+ if (strIcon.empty())
+ return false;
- file = dir + wxT("/mime.types");
- if ( wxFile::Exists(file) ) {
- ReadMimeTypes(file);
- }
- }
+ wxArrayString strExtensions;
+ wxString strDesc;
- wxString strHome = wxGetenv(wxT("HOME"));
+ wxArrayString strTypes;
+ GetMimeTypes(strTypes);
+ if ( strTypes.IsEmpty() )
+ return false;
- // and now the users mailcap
- wxString strUserMailcap = strHome + wxT("/.mailcap");
- if ( wxFile::Exists(strUserMailcap) ) {
- ReadMailcap(strUserMailcap);
+ wxMimeTypeCommands *entry = new wxMimeTypeCommands();
+ bool ok = false;
+ size_t nCount = strTypes.GetCount();
+ for ( size_t i = 0; i < nCount; i++ )
+ {
+ if ( m_manager->DoAssociation
+ (
+ strTypes[i],
+ strIcon,
+ entry,
+ strExtensions,
+ strDesc
+ ) )
+ {
+ // we don't need to free entry now, DoAssociation() took ownership
+ // of it
+ ok = true;
+ }
}
- // read the users mime.types
- wxString strUserMimeTypes = strHome + wxT("/.mime.types");
- if ( wxFile::Exists(strUserMimeTypes) ) {
- ReadMimeTypes(strUserMimeTypes);
- }
+ if ( !ok )
+ delete entry;
- // read KDE/GNOME tables
- ArrayIconHandlers& handlers = GetIconHandlers();
- size_t count = handlers.GetCount();
- for ( size_t hn = 0; hn < count; hn++ )
- handlers[hn]->GetMimeInfoRecords(this);
+ return ok;
}
+// ----------------------------------------------------------------------------
+// wxMimeTypesManagerImpl (Unix)
+// ----------------------------------------------------------------------------
-wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
+wxMimeTypesManagerImpl::wxMimeTypesManagerImpl()
{
- size_t cnt = m_aEntries.GetCount();
- for (size_t i = 0; i < cnt; i++)
- delete m_aEntries[i];
+ m_initialized = false;
}
-wxFileType *
-wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
+void wxMimeTypesManagerImpl::InitIfNeeded()
{
- wxFAIL_MSG( _T("unimplemented") ); // TODO
+ if ( !m_initialized )
+ {
+ // set the flag first to prevent recursion
+ m_initialized = true;
- return NULL;
+ int mailcapStyles = wxMAILCAP_ALL;
+ if ( wxAppTraits * const traits = wxApp::GetTraitsIfExists() )
+ {
+ wxString wm = traits->GetDesktopEnvironment();
+
+ if ( wm == "KDE" )
+ mailcapStyles = wxMAILCAP_KDE;
+ else if ( wm == "GNOME" )
+ mailcapStyles = wxMAILCAP_GNOME;
+ //else: unknown, use the default
+ }
+
+ Initialize(mailcapStyles);
+ }
}
-wxFileType *
-wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
+
+
+// read system and user mailcaps and other files
+void wxMimeTypesManagerImpl::Initialize(int mailcapStyles,
+ const wxString& sExtraDir)
{
- InitIfNeeded();
+#ifdef __VMS
+ // XDG tables are never installed on OpenVMS
+ return;
+#else
- wxFileType *fileType = NULL;
- size_t count = m_aExtensions.GetCount();
- for ( size_t n = 0; n < count; n++ ) {
- wxString extensions = m_aExtensions[n];
- while ( !extensions.IsEmpty() ) {
- wxString field = extensions.BeforeFirst(wxT(' '));
- extensions = extensions.AfterFirst(wxT(' '));
+ // Read MIME type - extension associations
+ LoadXDGGlobs( "/usr/share/mime/globs" );
+ LoadXDGGlobs( "/usr/local/share/mime/globs" );
- // consider extensions as not being case-sensitive
- if ( field.IsSameAs(ext, FALSE /* no case */) ) {
- // found
- if (fileType == NULL) fileType = new wxFileType;
- fileType->m_impl->Init(this, n);
- // adds this mime type to _list_ of mime types with this extension
+ // Load desktop files for XDG, and then override them with the defaults.
+ // We will override them one desktop file at a time, rather
+ // than one mime type at a time, but it should be a reasonable
+ // heuristic.
+ {
+ wxString xdgDataHome = wxGetenv("XDG_DATA_HOME");
+ if ( xdgDataHome.empty() )
+ xdgDataHome = wxGetHomeDir() + "/.local/share";
+ wxString xdgDataDirs = wxGetenv("XDG_DATA_DIRS");
+ if ( xdgDataDirs.empty() )
+ {
+ xdgDataDirs = "/usr/local/share:/usr/share";
+ if (mailcapStyles & wxMAILCAP_GNOME)
+ xdgDataDirs += ":/usr/share/gnome:/opt/gnome/share";
+ if (mailcapStyles & wxMAILCAP_KDE)
+ xdgDataDirs += ":/usr/share/kde3:/opt/kde3/share";
+ }
+ if ( !sExtraDir.empty() )
+ {
+ xdgDataDirs += ':';
+ xdgDataDirs += sExtraDir;
+ }
+
+ wxArrayString dirs;
+ wxStringTokenizer tokenizer(xdgDataDirs, ":");
+ while ( tokenizer.HasMoreTokens() )
+ {
+ wxString p = tokenizer.GetNextToken();
+ dirs.Add(p);
+ }
+ dirs.insert(dirs.begin(), xdgDataHome);
+
+ wxString defaultsList;
+ size_t i;
+ for (i = 0; i < dirs.GetCount(); i++)
+ {
+ wxString f = dirs[i];
+ if (f.Last() != '/') f += '/';
+ f += "applications/defaults.list";
+ if (wxFileExists(f))
+ {
+ defaultsList = f;
+ break;
}
}
- }
- return fileType;
-}
+ // Load application files and associate them to corresponding mime types.
+ size_t nDirs = dirs.GetCount();
+ for (size_t nDir = 0; nDir < nDirs; nDir++)
+ {
+ wxString dirStr = dirs[nDir];
+ if (dirStr.Last() != '/') dirStr += '/';
+ dirStr += "applications";
+ LoadXDGAppsFilesFromDir(dirStr);
+ }
-wxFileType *
-wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
-{
- InitIfNeeded();
+ if (!defaultsList.IsEmpty())
+ {
+ wxArrayString deskTopFilesSeen;
- // mime types are not case-sensitive
- wxString mimetype(mimeType);
- mimetype.MakeLower();
+ wxMimeTextFile textfile(defaultsList);
+ if ( textfile.Open() )
+ {
+ int nIndex = textfile.pIndexOf( wxT("[Default Applications]") );
+ if (nIndex != wxNOT_FOUND)
+ {
+ for (i = nIndex+1; i < textfile.GetLineCount(); i++)
+ {
+ if (textfile.GetLine(i).Find(wxT("=")) != wxNOT_FOUND)
+ {
+ wxString desktopFile = textfile.GetCmd(i);
- // first look for an exact match
- int index = m_aTypes.Index(mimetype);
- if ( index == wxNOT_FOUND ) {
- // then try to find "text/*" as match for "text/plain" (for example)
- // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
- // the whole string - ok.
- wxString strCategory = mimetype.BeforeFirst(wxT('/'));
-
- size_t nCount = m_aTypes.Count();
- for ( size_t n = 0; n < nCount; n++ ) {
- if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
- m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") ) {
- index = n;
- break;
+ if (deskTopFilesSeen.Index(desktopFile) == wxNOT_FOUND)
+ {
+ deskTopFilesSeen.Add(desktopFile);
+ size_t j;
+ for (j = 0; j < dirs.GetCount(); j++)
+ {
+ wxString desktopPath = dirs[j];
+ if (desktopPath.Last() != '/') desktopPath += '/';
+ desktopPath += "applications/";
+ desktopPath += desktopFile;
+
+ if (wxFileExists(desktopPath))
+ LoadXDGApp(desktopPath);
+ }
+ }
+ }
+ }
+ }
}
}
}
+#endif
+}
- if ( index != wxNOT_FOUND ) {
- wxFileType *fileType = new wxFileType;
- fileType->m_impl->Init(this, index);
+// clear data so you can read another group of WM files
+void wxMimeTypesManagerImpl::ClearData()
+{
+ m_aTypes.Clear();
+ m_aIcons.Clear();
+ m_aExtensions.Clear();
+ m_aDescriptions.Clear();
- return fileType;
- }
- else {
- // not found...
- return NULL;
- }
+ WX_CLEAR_ARRAY(m_aEntries);
+ m_aEntries.Empty();
}
-void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
+wxMimeTypesManagerImpl::~wxMimeTypesManagerImpl()
+{
+ ClearData();
+}
+
+wxFileType * wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
{
InitIfNeeded();
- wxString extensions;
- const wxArrayString& exts = filetype.GetExtensions();
- size_t nExts = exts.GetCount();
- for ( size_t nExt = 0; nExt < nExts; nExt++ ) {
- if ( nExt > 0 ) {
- extensions += wxT(' ');
- }
- extensions += exts[nExt];
- }
+ wxString strType = ftInfo.GetMimeType();
+ wxString strDesc = ftInfo.GetDescription();
+ wxString strIcon = ftInfo.GetIconFile();
- AddMimeTypeInfo(filetype.GetMimeType(),
- extensions,
- filetype.GetDescription());
+ wxMimeTypeCommands *entry = new wxMimeTypeCommands();
- AddMailcapInfo(filetype.GetMimeType(),
- filetype.GetOpenCommand(),
- filetype.GetPrintCommand(),
- wxT(""),
- filetype.GetDescription());
-}
+ if ( ! ftInfo.GetOpenCommand().empty())
+ entry->Add(wxT("open=") + ftInfo.GetOpenCommand() + wxT(" %s "));
+ if ( ! ftInfo.GetPrintCommand().empty())
+ entry->Add(wxT("print=") + ftInfo.GetPrintCommand() + wxT(" %s "));
-void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
- const wxString& strExtensions,
- const wxString& strDesc)
-{
- InitIfNeeded();
+ // now find where these extensions are in the data store and remove them
+ wxArrayString sA_Exts = ftInfo.GetExtensions();
+ wxString sExt, sExtStore;
+ size_t i, nIndex;
+ size_t nExtCount = sA_Exts.GetCount();
+ for (i=0; i < nExtCount; i++)
+ {
+ sExt = sA_Exts.Item(i);
- int index = m_aTypes.Index(strMimeType);
- if ( index == wxNOT_FOUND ) {
- // add a new entry
- m_aTypes.Add(strMimeType);
- m_aEntries.Add(NULL);
- m_aExtensions.Add(strExtensions);
- m_aDescriptions.Add(strDesc);
- }
- else {
- // modify an existing one
- if ( !strDesc.IsEmpty() ) {
- m_aDescriptions[index] = strDesc; // replace old value
+ // clean up to just a space before and after
+ sExt.Trim().Trim(false);
+ sExt = wxT(' ') + sExt + wxT(' ');
+ size_t nCount = m_aExtensions.GetCount();
+ for (nIndex = 0; nIndex < nCount; nIndex++)
+ {
+ sExtStore = m_aExtensions.Item(nIndex);
+ if (sExtStore.Replace(sExt, wxT(" ") ) > 0)
+ m_aExtensions.Item(nIndex) = sExtStore;
}
- m_aExtensions[index] += ' ' + strExtensions;
}
+
+ if ( !DoAssociation(strType, strIcon, entry, sA_Exts, strDesc) )
+ return NULL;
+
+ return GetFileTypeFromMimeType(strType);
}
-void wxMimeTypesManagerImpl::AddMailcapInfo(const wxString& strType,
- const wxString& strOpenCmd,
- const wxString& strPrintCmd,
- const wxString& strTest,
- const wxString& strDesc)
+bool wxMimeTypesManagerImpl::DoAssociation(const wxString& strType,
+ const wxString& strIcon,
+ wxMimeTypeCommands *entry,
+ const wxArrayString& strExtensions,
+ const wxString& strDesc)
{
- InitIfNeeded();
-
- MailCapEntry *entry = new MailCapEntry(strOpenCmd, strPrintCmd, strTest);
+ int nIndex = AddToMimeData(strType, strIcon, entry, strExtensions, strDesc, true);
- int nIndex = m_aTypes.Index(strType);
- if ( nIndex == wxNOT_FOUND ) {
- // new file type
- m_aTypes.Add(strType);
+ if ( nIndex == wxNOT_FOUND )
+ return false;
- m_aEntries.Add(entry);
- m_aExtensions.Add(wxT(""));
- m_aDescriptions.Add(strDesc);
- }
- else {
- // always append the entry in the tail of the list - info added with
- // this function can only come from AddFallbacks()
- MailCapEntry *entryOld = m_aEntries[nIndex];
- if ( entryOld )
- entry->Append(entryOld);
- else
- m_aEntries[nIndex] = entry;
- }
+ return true;
}
-bool wxMimeTypesManagerImpl::ReadMimeTypes(const wxString& strFileName)
+int wxMimeTypesManagerImpl::AddToMimeData(const wxString& strType,
+ const wxString& strIcon,
+ wxMimeTypeCommands *entry,
+ const wxArrayString& strExtensions,
+ const wxString& strDesc,
+ bool replaceExisting)
{
- wxLogTrace(TRACE_MIME, wxT("--- Parsing mime.types file '%s' ---"),
- strFileName.c_str());
+ InitIfNeeded();
- wxTextFile file(strFileName);
- if ( !file.Open() )
- return FALSE;
+ // ensure mimetype is always lower case
+ wxString mimeType = strType.Lower();
+
+ // is this a known MIME type?
+ int nIndex = m_aTypes.Index(mimeType);
+ if ( nIndex == wxNOT_FOUND )
+ {
+ // We put MIME types containing "application" at the end, so that
+ // if the MIME type for the extension "htm" is searched for, it will
+ // rather find "text/html" than "application/x-mozilla-bookmarks".
+ if (mimeType.Find( "application" ) == 0)
+ {
+ // new file type
+ m_aTypes.Add(mimeType);
+ m_aIcons.Add(strIcon);
+ m_aEntries.Add(entry ? entry : new wxMimeTypeCommands);
- // the information we extract
- wxString strMimeType, strDesc, strExtensions;
+ // change nIndex so we can use it below to add the extensions
+ m_aExtensions.Add(wxEmptyString);
+ nIndex = m_aExtensions.size() - 1;
- size_t nLineCount = file.GetLineCount();
- const wxChar *pc = NULL;
- for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
- if ( pc == NULL ) {
- // now we're at the start of the line
- pc = file[nLine].c_str();
- }
- else {
- // we didn't finish with the previous line yet
- nLine--;
+ m_aDescriptions.Add(strDesc);
}
+ else
+ {
+ // new file type
+ m_aTypes.Insert(mimeType,0);
+ m_aIcons.Insert(strIcon,0);
+ m_aEntries.Insert(entry ? entry : new wxMimeTypeCommands,0);
- // skip whitespace
- while ( wxIsspace(*pc) )
- pc++;
+ // change nIndex so we can use it below to add the extensions
+ m_aExtensions.Insert(wxEmptyString,0);
+ nIndex = 0;
- // comment or blank line?
- if ( *pc == wxT('#') || !*pc ) {
- // skip the whole line
- pc = NULL;
- continue;
+ m_aDescriptions.Insert(strDesc,0);
}
+ }
+ else // yes, we already have it
+ {
+ if ( replaceExisting )
+ {
+ // if new description change it
+ if ( !strDesc.empty())
+ m_aDescriptions[nIndex] = strDesc;
- // detect file format
- const wxChar *pEqualSign = wxStrchr(pc, wxT('='));
- if ( pEqualSign == NULL ) {
- // brief format
- // ------------
+ // if new icon change it
+ if ( !strIcon.empty())
+ m_aIcons[nIndex] = strIcon;
- // first field is mime type
- for ( strMimeType.Empty(); !wxIsspace(*pc) && *pc != wxT('\0'); pc++ ) {
- strMimeType += *pc;
+ if ( entry )
+ {
+ delete m_aEntries[nIndex];
+ m_aEntries[nIndex] = entry;
}
+ }
+ else // add data we don't already have ...
+ {
+ // if new description add only if none
+ if ( m_aDescriptions[nIndex].empty() )
+ m_aDescriptions[nIndex] = strDesc;
- // skip whitespace
- while ( wxIsspace(*pc) )
- pc++;
+ // if new icon and no existing icon
+ if ( m_aIcons[nIndex].empty() )
+ m_aIcons[nIndex] = strIcon;
- // take all the rest of the string
- strExtensions = pc;
+ // add any new entries...
+ if ( entry )
+ {
+ wxMimeTypeCommands *entryOld = m_aEntries[nIndex];
- // no description...
- strDesc.Empty();
- }
- else {
- // expanded format
- // ---------------
-
- // the string on the left of '=' is the field name
- wxString strLHS(pc, pEqualSign - pc);
-
- // eat whitespace
- for ( pc = pEqualSign + 1; wxIsspace(*pc); pc++ )
- ;
-
- const wxChar *pEnd;
- if ( *pc == wxT('"') ) {
- // the string is quoted and ends at the matching quote
- pEnd = wxStrchr(++pc, wxT('"'));
- if ( pEnd == NULL ) {
- wxLogWarning(_("Mime.types file %s, line %d: unterminated "
- "quoted string."),
- strFileName.c_str(), nLine + 1);
+ size_t count = entry->GetCount();
+ for ( size_t i = 0; i < count; i++ )
+ {
+ const wxString& verb = entry->GetVerb(i);
+ if ( !entryOld->HasVerb(verb) )
+ {
+ entryOld->AddOrReplaceVerb(verb, entry->GetCmd(i));
+ }
}
- }
- else {
- // unquoted string ends at the first space or at the end of
- // line
- for ( pEnd = pc; *pEnd && !wxIsspace(*pEnd); pEnd++ )
- ;
- }
-
- // now we have the RHS (field value)
- wxString strRHS(pc, pEnd - pc);
- // check what follows this entry
- if ( *pEnd == wxT('"') ) {
- // skip this quote
- pEnd++;
+ // as we don't store it anywhere, it won't be deleted later as
+ // usual -- do it immediately instead
+ delete entry;
}
+ }
+ }
- for ( pc = pEnd; wxIsspace(*pc); pc++ )
- ;
+ // always add the extensions to this mimetype
+ wxString& exts = m_aExtensions[nIndex];
- // if there is something left, it may be either a '\\' to continue
- // the line or the next field of the same entry
- bool entryEnded = *pc == wxT('\0'),
- nextFieldOnSameLine = FALSE;
- if ( !entryEnded ) {
- nextFieldOnSameLine = ((*pc != wxT('\\')) || (pc[1] != wxT('\0')));
- }
+ // add all extensions we don't have yet
+ wxString ext;
+ size_t count = strExtensions.GetCount();
+ for ( size_t i = 0; i < count; i++ )
+ {
+ ext = strExtensions[i];
+ ext += wxT(' ');
- // now see what we got
- if ( strLHS == wxT("type") ) {
- strMimeType = strRHS;
- }
- else if ( strLHS == wxT("desc") ) {
- strDesc = strRHS;
- }
- else if ( strLHS == wxT("exts") ) {
- strExtensions = strRHS;
- }
- else {
- wxLogWarning(_("Unknown field in file %s, line %d: '%s'."),
- strFileName.c_str(), nLine + 1, strLHS.c_str());
- }
+ if ( exts.Find(ext) == wxNOT_FOUND )
+ {
+ exts += ext;
+ }
+ }
- if ( !entryEnded ) {
- if ( !nextFieldOnSameLine )
- pc = NULL;
- //else: don't reset it
+ // check data integrity
+ wxASSERT( m_aTypes.GetCount() == m_aEntries.GetCount() &&
+ m_aTypes.GetCount() == m_aExtensions.GetCount() &&
+ m_aTypes.GetCount() == m_aIcons.GetCount() &&
+ m_aTypes.GetCount() == m_aDescriptions.GetCount() );
- // as we don't reset strMimeType, the next field in this entry
- // will be interpreted correctly.
+ return nIndex;
+}
- continue;
- }
- }
+wxFileType * wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
+{
+ if (ext.empty() )
+ return NULL;
- // depending on the format (Mosaic or Netscape) either space or comma
- // is used to separate the extensions
- strExtensions.Replace(wxT(","), wxT(" "));
+ InitIfNeeded();
- // also deal with the leading dot
- if ( !strExtensions.IsEmpty() && strExtensions[0u] == wxT('.') )
- {
- strExtensions.erase(0, 1);
- }
+ size_t count = m_aExtensions.GetCount();
+ for ( size_t n = 0; n < count; n++ )
+ {
+ wxStringTokenizer tk(m_aExtensions[n], wxT(' '));
- AddMimeTypeInfo(strMimeType, strExtensions, strDesc);
+ while ( tk.HasMoreTokens() )
+ {
+ // consider extensions as not being case-sensitive
+ if ( tk.GetNextToken().IsSameAs(ext, false /* no case */) )
+ {
+ // found
+ wxFileType *fileType = new wxFileType;
+ fileType->m_impl->Init(this, n);
- // finished with this line
- pc = NULL;
+ return fileType;
+ }
+ }
}
- // check our data integriry
- wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
- m_aTypes.Count() == m_aExtensions.Count() &&
- m_aTypes.Count() == m_aDescriptions.Count() );
-
- return TRUE;
+ return NULL;
}
-bool wxMimeTypesManagerImpl::ReadMailcap(const wxString& strFileName,
- bool fallback)
+wxFileType * wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
{
- wxLogTrace(TRACE_MIME, wxT("--- Parsing mailcap file '%s' ---"),
- strFileName.c_str());
-
- wxTextFile file(strFileName);
- if ( !file.Open() )
- return FALSE;
-
- // see the comments near the end of function for the reason we need these
- // variables (search for the next occurence of them)
- // indices of MIME types (in m_aTypes) we already found in this file
- wxArrayInt aEntryIndices;
- // aLastIndices[n] is the index of last element in
- // m_aEntries[aEntryIndices[n]] from this file
- wxArrayInt aLastIndices;
-
- size_t nLineCount = file.GetLineCount();
- for ( size_t nLine = 0; nLine < nLineCount; nLine++ ) {
- // now we're at the start of the line
- const wxChar *pc = file[nLine].c_str();
-
- // skip whitespace
- while ( wxIsspace(*pc) )
- pc++;
-
- // comment or empty string?
- if ( *pc == wxT('#') || *pc == wxT('\0') )
- continue;
-
- // no, do parse
-
- // what field are we currently in? The first 2 are fixed and there may
- // be an arbitrary number of other fields -- currently, we are not
- // interested in any of them, but we should parse them as well...
- enum
- {
- Field_Type,
- Field_OpenCmd,
- Field_Other
- } currentToken = Field_Type;
-
- // the flags and field values on the current line
- bool needsterminal = FALSE,
- copiousoutput = FALSE;
- wxString strType,
- strOpenCmd,
- strPrintCmd,
- strTest,
- strDesc,
- curField; // accumulator
- for ( bool cont = TRUE; cont; pc++ ) {
- switch ( *pc ) {
- case wxT('\\'):
- // interpret the next character literally (notice that
- // backslash can be used for line continuation)
- if ( *++pc == wxT('\0') ) {
- // fetch the next line.
-
- // pc currently points to nowhere, but after the next
- // pc++ in the for line it will point to the beginning
- // of the next line in the file
- pc = file[++nLine].c_str() - 1;
- }
- else {
- // just a normal character
- curField += *pc;
- }
- break;
-
- case wxT('\0'):
- cont = FALSE; // end of line reached, exit the loop
+ InitIfNeeded();
- // fall through
+ wxFileType * fileType = NULL;
+ // mime types are not case-sensitive
+ wxString mimetype(mimeType);
+ mimetype.MakeLower();
- case wxT(';'):
- // store this field and start looking for the next one
+ // first look for an exact match
+ int index = m_aTypes.Index(mimetype);
- // trim whitespaces from both sides
- curField.Trim(TRUE).Trim(FALSE);
+ if ( index != wxNOT_FOUND )
+ {
+ fileType = new wxFileType;
+ fileType->m_impl->Init(this, index);
+ }
- switch ( currentToken ) {
- case Field_Type:
- strType = curField;
- if ( strType.Find(wxT('/')) == wxNOT_FOUND ) {
- // we interpret "type" as "type/*"
- strType += wxT("/*");
- }
+ // then try to find "text/*" as match for "text/plain" (for example)
+ // NB: if mimeType doesn't contain '/' at all, BeforeFirst() will return
+ // the whole string - ok.
- currentToken = Field_OpenCmd;
- break;
+ index = wxNOT_FOUND;
+ wxString strCategory = mimetype.BeforeFirst(wxT('/'));
- case Field_OpenCmd:
- strOpenCmd = curField;
+ size_t nCount = m_aTypes.GetCount();
+ for ( size_t n = 0; n < nCount; n++ )
+ {
+ if ( (m_aTypes[n].BeforeFirst(wxT('/')) == strCategory ) &&
+ m_aTypes[n].AfterFirst(wxT('/')) == wxT("*") )
+ {
+ index = n;
+ break;
+ }
+ }
- currentToken = Field_Other;
- break;
+ if ( index != wxNOT_FOUND )
+ {
+ // don't throw away fileType that was already found
+ if (!fileType)
+ fileType = new wxFileType;
+ fileType->m_impl->Init(this, index);
+ }
- case Field_Other:
- {
- // "good" mailcap entry?
- bool ok = TRUE;
-
- // is this something of the form foo=bar?
- const wxChar *pEq = wxStrchr(curField, wxT('='));
- if ( pEq != NULL ) {
- wxString lhs = curField.BeforeFirst(wxT('=')),
- rhs = curField.AfterFirst(wxT('='));
-
- lhs.Trim(TRUE); // from right
- rhs.Trim(FALSE); // from left
-
- if ( lhs == wxT("print") )
- strPrintCmd = rhs;
- else if ( lhs == wxT("test") )
- strTest = rhs;
- else if ( lhs == wxT("description") ) {
- // it might be quoted
- if ( rhs[0u] == wxT('"') &&
- rhs.Last() == wxT('"') ) {
- strDesc = wxString(rhs.c_str() + 1,
- rhs.Len() - 2);
- }
- else {
- strDesc = rhs;
- }
- }
- else if ( lhs == wxT("compose") ||
- lhs == wxT("composetyped") ||
- lhs == wxT("notes") ||
- lhs == wxT("edit") )
- ; // ignore
- else
- ok = FALSE;
+ return fileType;
+}
- }
- else {
- // no, it's a simple flag
- if ( curField == wxT("needsterminal") )
- needsterminal = TRUE;
- else if ( curField == wxT("copiousoutput")) {
- // copiousoutput impies that the
- // viewer is a console program
- needsterminal =
- copiousoutput = TRUE;
- }
- else {
- // unknown flag
- ok = FALSE;
- }
- }
+wxString wxMimeTypesManagerImpl::GetCommand(const wxString & verb, size_t nIndex) const
+{
+ wxString command, testcmd, sV, sTmp;
+ sV = verb + wxT("=");
- if ( !ok )
- {
- if ( !IsKnownUnimportantField(curField) )
- {
- // don't flood the user with error
- // messages if we don't understand
- // something in his mailcap, but give
- // them in debug mode because this might
- // be useful for the programmer
- wxLogDebug
- (
- wxT("Mailcap file %s, line %d: "
- "unknown field '%s' for the "
- "MIME type '%s' ignored."),
- strFileName.c_str(),
- nLine + 1,
- curField.c_str(),
- strType.c_str()
- );
- }
- }
- }
+ // list of verb = command pairs for this mimetype
+ wxMimeTypeCommands * sPairs = m_aEntries [nIndex];
- // it already has this value
- //currentToken = Field_Other;
- break;
+ size_t i;
+ size_t nCount = sPairs->GetCount();
+ for ( i = 0; i < nCount; i++ )
+ {
+ sTmp = sPairs->GetVerbCmd (i);
+ if ( sTmp.Contains(sV) )
+ command = sTmp.AfterFirst(wxT('='));
+ }
- default:
- wxFAIL_MSG(wxT("unknown field type in mailcap"));
- }
+ return command;
+}
- // next token starts immediately after ';'
- curField.Empty();
- break;
+void wxMimeTypesManagerImpl::AddFallback(const wxFileTypeInfo& filetype)
+{
+ InitIfNeeded();
- default:
- curField += *pc;
- }
- }
+ wxString extensions;
+ const wxArrayString& exts = filetype.GetExtensions();
+ size_t nExts = exts.GetCount();
+ for ( size_t nExt = 0; nExt < nExts; nExt++ )
+ {
+ if ( nExt > 0 )
+ extensions += wxT(' ');
- // check that we really read something reasonable
- if ( currentToken == Field_Type || currentToken == Field_OpenCmd ) {
- wxLogWarning(_("Mailcap file %s, line %d: incomplete entry "
- "ignored."),
- strFileName.c_str(), nLine + 1);
- }
- else {
- // support for flags:
- // 1. create an xterm for 'needsterminal'
- // 2. append "| $PAGER" for 'copiousoutput'
- //
- // Note that the RFC says that having both needsterminal and
- // copiousoutput is probably a mistake, so it seems that running
- // programs with copiousoutput inside an xterm as it is done now
- // is a bad idea (FIXME)
- if ( copiousoutput ) {
- const wxChar *p = wxGetenv(_T("PAGER"));
- strOpenCmd << _T(" | ") << (p ? p : _T("more"));
- }
+ extensions += exts[nExt];
+ }
- if ( needsterminal ) {
- strOpenCmd.Printf(_T("xterm -e sh -c '%s'"),
- strOpenCmd.c_str());
- }
+ AddMimeTypeInfo(filetype.GetMimeType(),
+ extensions,
+ filetype.GetDescription());
+}
- MailCapEntry *entry = new MailCapEntry(strOpenCmd,
- strPrintCmd,
- strTest);
-
- // NB: because of complications below (we must get entries priority
- // right), we can't use AddMailcapInfo() here, unfortunately.
- strType.MakeLower();
- int nIndex = m_aTypes.Index(strType);
- if ( nIndex == wxNOT_FOUND ) {
- // new file type
- m_aTypes.Add(strType);
-
- m_aEntries.Add(entry);
- m_aExtensions.Add(wxT(""));
- m_aDescriptions.Add(strDesc);
- }
- else {
- // modify the existing entry: the entries in one and the same
- // file are read in top-to-bottom order, i.e. the entries read
- // first should be tried before the entries below. However,
- // the files read later should override the settings in the
- // files read before (except if fallback is TRUE), thus we
- // Insert() the new entry to the list if it has already
- // occured in _this_ file, but Prepend() it if it occured in
- // some of the previous ones and Append() to it in the
- // fallback case
-
- if ( fallback ) {
- // 'fallback' parameter prevents the entries from this
- // file from overriding the other ones - always append
- MailCapEntry *entryOld = m_aEntries[nIndex];
- if ( entryOld )
- entry->Append(entryOld);
- else
- m_aEntries[nIndex] = entry;
- }
- else {
- int entryIndex = aEntryIndices.Index(nIndex);
- if ( entryIndex == wxNOT_FOUND ) {
- // first time in this file
- aEntryIndices.Add(nIndex);
- aLastIndices.Add(0);
-
- entry->Prepend(m_aEntries[nIndex]);
- m_aEntries[nIndex] = entry;
- }
- else {
- // not the first time in _this_ file
- size_t nEntryIndex = (size_t)entryIndex;
- MailCapEntry *entryOld = m_aEntries[nIndex];
- if ( entryOld )
- entry->Insert(entryOld, aLastIndices[nEntryIndex]);
- else
- m_aEntries[nIndex] = entry;
-
- // the indices were shifted by 1
- aLastIndices[nEntryIndex]++;
- }
- }
+void wxMimeTypesManagerImpl::AddMimeTypeInfo(const wxString& strMimeType,
+ const wxString& strExtensions,
+ const wxString& strDesc)
+{
+ // reading mailcap may find image/* , while
+ // reading mime.types finds image/gif and no match is made
+ // this means all the get functions don't work fix this
+ wxString strIcon;
+ wxString sTmp = strExtensions;
- if ( !strDesc.IsEmpty() ) {
- // replace the old one - what else can we do??
- m_aDescriptions[nIndex] = strDesc;
- }
- }
- }
+ wxArrayString sExts;
+ sTmp.Trim().Trim(false);
- // check our data integriry
- wxASSERT( m_aTypes.Count() == m_aEntries.Count() &&
- m_aTypes.Count() == m_aExtensions.Count() &&
- m_aTypes.Count() == m_aDescriptions.Count() );
+ while (!sTmp.empty())
+ {
+ sExts.Add(sTmp.AfterLast(wxT(' ')));
+ sTmp = sTmp.BeforeLast(wxT(' '));
}
- return TRUE;
+ AddToMimeData(strMimeType, strIcon, NULL, sExts, strDesc, true);
}
size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
mimetypes.Empty();
- wxString type;
size_t count = m_aTypes.GetCount();
for ( size_t n = 0; n < count; n++ )
{
// don't return template types from here (i.e. anything containg '*')
- type = m_aTypes[n];
- if ( type.Find(_T('*')) == wxNOT_FOUND )
+ const wxString &type = m_aTypes[n];
+ if ( type.Find(wxT('*')) == wxNOT_FOUND )
{
mimetypes.Add(type);
}
// writing to MIME type files
// ----------------------------------------------------------------------------
-bool wxFileTypeImpl::Unassociate()
+bool wxMimeTypesManagerImpl::Unassociate(wxFileType *ft)
{
- wxFAIL_MSG( _T("unimplemented") ); // TODO
-
- return FALSE;
-}
-
-// ----------------------------------------------------------------------------
-// private functions
-// ----------------------------------------------------------------------------
+ InitIfNeeded();
-static bool IsKnownUnimportantField(const wxString& fieldAll)
-{
- static const wxChar *knownFields[] =
- {
- _T("x-mozilla-flags"),
- _T("nametemplate"),
- _T("textualnewlines"),
- };
+ wxArrayString sMimeTypes;
+ ft->GetMimeTypes(sMimeTypes);
- wxString field = fieldAll.BeforeFirst(_T('='));
- for ( size_t n = 0; n < WXSIZEOF(knownFields); n++ )
+ size_t i;
+ size_t nCount = sMimeTypes.GetCount();
+ for (i = 0; i < nCount; i ++)
{
- if ( field.CmpNoCase(knownFields[n]) == 0 )
- return TRUE;
+ const wxString &sMime = sMimeTypes.Item(i);
+ int nIndex = m_aTypes.Index(sMime);
+ if ( nIndex == wxNOT_FOUND)
+ {
+ // error if we get here ??
+ return false;
+ }
+ else
+ {
+ m_aTypes.RemoveAt(nIndex);
+ m_aEntries.RemoveAt(nIndex);
+ m_aExtensions.RemoveAt(nIndex);
+ m_aDescriptions.RemoveAt(nIndex);
+ m_aIcons.RemoveAt(nIndex);
+ }
}
+ // check data integrity
+ wxASSERT( m_aTypes.GetCount() == m_aEntries.GetCount() &&
+ m_aTypes.GetCount() == m_aExtensions.GetCount() &&
+ m_aTypes.GetCount() == m_aIcons.GetCount() &&
+ m_aTypes.GetCount() == m_aDescriptions.GetCount() );
- return FALSE;
+ return true;
}
#endif
- // wxUSE_FILE && wxUSE_TEXTFILE
-
+ // wxUSE_MIMETYPE && wxUSE_FILE