Compare commits

..

1 Commits

Author SHA1 Message Date
Bryan Petty
b9cf0ce54e This commit was manufactured by cvs2svn to create tag
'MIMECODE_WITHOUT_KDE_GNOME'.

git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/tags/MIMECODE_WITHOUT_KDE_GNOME@9626 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
2001-04-01 20:42:05 +00:00
7 changed files with 3726 additions and 80 deletions

View File

@@ -1,80 +0,0 @@
dnl
dnl AM_PATH_CPPUNIT(MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]])
dnl
AC_DEFUN(AM_PATH_CPPUNIT,
[
AC_ARG_WITH(cppunit-prefix,[ --with-cppunit-prefix=PFX Prefix where CppUnit is installed (optional)],
cppunit_config_prefix="$withval", cppunit_config_prefix="")
AC_ARG_WITH(cppunit-exec-prefix,[ --with-cppunit-exec-prefix=PFX Exec prefix where CppUnit is installed (optional)],
cppunit_config_exec_prefix="$withval", cppunit_config_exec_prefix="")
if test x$cppunit_config_exec_prefix != x ; then
cppunit_config_args="$cppunit_config_args --exec-prefix=$cppunit_config_exec_prefix"
if test x${CPPUNIT_CONFIG+set} != xset ; then
CPPUNIT_CONFIG=$cppunit_config_exec_prefix/bin/cppunit-config
fi
fi
if test x$cppunit_config_prefix != x ; then
cppunit_config_args="$cppunit_config_args --prefix=$cppunit_config_prefix"
if test x${CPPUNIT_CONFIG+set} != xset ; then
CPPUNIT_CONFIG=$cppunit_config_prefix/bin/cppunit-config
fi
fi
AC_PATH_PROG(CPPUNIT_CONFIG, cppunit-config, no)
cppunit_version_min=$1
AC_MSG_CHECKING(for Cppunit - version >= $cppunit_version_min)
no_cppunit=""
if test "$CPPUNIT_CONFIG" = "no" ; then
no_cppunit=yes
else
CPPUNIT_CFLAGS=`$CPPUNIT_CONFIG --cflags`
CPPUNIT_LIBS=`$CPPUNIT_CONFIG --libs`
cppunit_version=`$CPPUNIT_CONFIG --version`
cppunit_major_version=`echo $cppunit_version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
cppunit_minor_version=`echo $cppunit_version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
cppunit_micro_version=`echo $cppunit_version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
cppunit_major_min=`echo $cppunit_version_min | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
cppunit_minor_min=`echo $cppunit_version_min | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
cppunit_micro_min=`echo $cppunit_version_min | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
cppunit_version_proper=`expr \
$cppunit_major_version \> $cppunit_major_min \| \
$cppunit_major_version \= $cppunit_major_min \& \
$cppunit_minor_version \> $cppunit_minor_min \| \
$cppunit_major_version \= $cppunit_major_min \& \
$cppunit_minor_version \= $cppunit_minor_min \& \
$cppunit_micro_version \>= $cppunit_micro_min `
if test "$cppunit_version_proper" = "1" ; then
AC_MSG_RESULT([$cppunit_major_version.$cppunit_minor_version.$cppunit_micro_version])
else
AC_MSG_RESULT(no)
no_cppunit=yes
fi
fi
if test "x$no_cppunit" = x ; then
ifelse([$2], , :, [$2])
else
CPPUNIT_CFLAGS=""
CPPUNIT_LIBS=""
ifelse([$3], , :, [$3])
fi
AC_SUBST(CPPUNIT_CFLAGS)
AC_SUBST(CPPUNIT_LIBS)
])

346
include/wx/mimetype.h Normal file
View File

@@ -0,0 +1,346 @@
/////////////////////////////////////////////////////////////////////////////
// Name: wx/mimetype.h
// Purpose: classes and functions to manage MIME types
// Author: Vadim Zeitlin
// Modified by:
// Chris Elliott (biol75@york.ac.uk) 5 Dec 00: write support for Win32
// Created: 23.09.98
// RCS-ID: $Id$
// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows license (part of wxExtra library)
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_MIMETYPE_H_
#define _WX_MIMETYPE_H_
#ifdef __GNUG__
#pragma interface "mimetypebase.h"
#endif // __GNUG__
// ----------------------------------------------------------------------------
// headers and such
// ----------------------------------------------------------------------------
#include "wx/defs.h"
// the things we really need
#include "wx/string.h"
#include "wx/dynarray.h"
// fwd decls
class WXDLLEXPORT wxIcon;
class WXDLLEXPORT wxFileTypeImpl;
class WXDLLEXPORT wxMimeTypesManagerImpl;
/*
TODO: would it be more convenient to have this class?
class WXDLLEXPORT wxMimeType : public wxString
{
public:
// all string ctors here
wxString GetType() const { return BeforeFirst(_T('/')); }
wxString GetSubType() const { return AfterFirst(_T('/')); }
void SetSubType(const wxString& subtype)
{
*this = GetType() + _T('/') + subtype;
}
bool Matches(const wxMimeType& wildcard)
{
// implement using wxMimeTypesManager::IsOfType()
}
};
*/
// ----------------------------------------------------------------------------
// wxFileTypeInfo: static container of information accessed via wxFileType.
//
// This class is used with wxMimeTypesManager::AddFallbacks() and Associate()
// ----------------------------------------------------------------------------
class WXDLLEXPORT wxFileTypeInfo
{
public:
// ctors
// a normal item
wxFileTypeInfo(const char *mimeType,
const char *openCmd,
const char *printCmd,
const char *desc,
// the other parameters form a NULL terminated list of
// extensions
...);
// invalid item - use this to terminate the array passed to
// wxMimeTypesManager::AddFallbacks
wxFileTypeInfo() { }
// test if this object can be used
bool IsValid() const { return !m_mimeType.IsEmpty(); }
// setters
// set the icon info
void SetIcon(const wxString& iconFile, int iconIndex = 0)
{
m_iconFile = iconFile;
m_iconIndex = iconIndex;
}
// set the short desc
void SetShortDesc(const wxString& shortDesc) { m_shortDesc = shortDesc; }
// accessors
// get the MIME type
const wxString& GetMimeType() const { return m_mimeType; }
// get the open command
const wxString& GetOpenCommand() const { return m_openCmd; }
// get the print command
const wxString& GetPrintCommand() const { return m_printCmd; }
// get the short description (only used under Win32 so far)
const wxString& GetShortDesc() const { return m_shortDesc; }
// get the long, user visible description
const wxString& GetDescription() const { return m_desc; }
// get the array of all extensions
const wxArrayString& GetExtensions() const { return m_exts; }
// get the icon info
const wxString& GetIconFile() const { return m_iconFile; }
int GetIconIndex() const { return m_iconIndex; }
private:
wxString m_mimeType, // the MIME type in "type/subtype" form
m_openCmd, // command to use for opening the file (%s allowed)
m_printCmd, // command to use for printing the file (%s allowed)
m_shortDesc, // a short string used in the registry
m_desc; // a free form description of this file type
// icon stuff
wxString m_iconFile; // the file containing the icon
int m_iconIndex; // icon index in this file
wxArrayString m_exts; // the extensions which are mapped on this filetype
#if 0 // TODO
// the additional (except "open" and "print") command names and values
wxArrayString m_commandNames,
m_commandValues;
#endif // 0
};
WX_DECLARE_EXPORTED_OBJARRAY(wxFileTypeInfo, wxArrayFileTypeInfo);
// ----------------------------------------------------------------------------
// wxFileType: gives access to all information about the files of given type.
//
// This class holds information about a given "file type". File type is the
// same as MIME type under Unix, but under Windows it corresponds more to an
// extension than to MIME type (in fact, several extensions may correspond to a
// file type). This object may be created in many different ways and depending
// on how it was created some fields may be unknown so the return value of all
// the accessors *must* be checked!
// ----------------------------------------------------------------------------
class WXDLLEXPORT wxFileType
{
friend class WXDLLEXPORT wxMimeTypesManagerImpl; // it has access to m_impl
public:
// An object of this class must be passed to Get{Open|Print}Command. The
// default implementation is trivial and doesn't know anything at all about
// parameters, only filename and MIME type are used (so it's probably ok for
// Windows where %{param} is not used anyhow)
class MessageParameters
{
public:
// ctors
MessageParameters() { }
MessageParameters(const wxString& filename, const wxString& mimetype)
: m_filename(filename), m_mimetype(mimetype) { }
// accessors (called by GetOpenCommand)
// filename
const wxString& GetFileName() const { return m_filename; }
// mime type
const wxString& GetMimeType() const { return m_mimetype; }
// override this function in derived class
virtual wxString GetParamValue(const wxString& WXUNUSED(name)) const
{ return wxEmptyString; }
// virtual dtor as in any base class
virtual ~MessageParameters() { }
protected:
wxString m_filename, m_mimetype;
};
// ctor from static data
wxFileType(const wxFileTypeInfo& ftInfo);
// accessors: all of them return true if the corresponding information
// could be retrieved/found, false otherwise (and in this case all [out]
// parameters are unchanged)
// return the MIME type for this file type
bool GetMimeType(wxString *mimeType) const;
bool GetMimeTypes(wxArrayString& mimeTypes) const;
// fill passed in array with all extensions associated with this file
// type
bool GetExtensions(wxArrayString& extensions);
// get the icon corresponding to this file type, the name of the file
// where the icon resides is return in iconfile if !NULL and its index
// in this file (Win-only) is in iconIndex
bool GetIcon(wxIcon *icon,
wxString *iconFile = NULL,
int *iconIndex = NULL) const;
// get a brief file type description ("*.txt" => "text document")
bool GetDescription(wxString *desc) const;
// get the command to be used to open/print the given file.
// get the command to execute the file of given type
bool GetOpenCommand(wxString *openCmd,
const MessageParameters& params) const;
// get the command to print the file of given type
bool GetPrintCommand(wxString *printCmd,
const MessageParameters& params) const;
// return the number of commands defined for this file type, 0 if none
size_t GetAllCommands(wxArrayString *verbs, wxArrayString *commands,
const wxFileType::MessageParameters& params) const;
// remove the association for this filetype from the system MIME database:
// notice that it will only work if the association is defined in the user
// file/registry part, we will never modify the system-wide settings
bool Unassociate();
// operations
// expand a string in the format of GetOpenCommand (which may contain
// '%s' and '%t' format specificators for the file name and mime type
// and %{param} constructions).
static wxString ExpandCommand(const wxString& command,
const MessageParameters& params);
// dtor (not virtual, shouldn't be derived from)
~wxFileType();
private:
// default ctor is private because the user code never creates us
wxFileType();
// no copy ctor/assignment operator
wxFileType(const wxFileType&);
wxFileType& operator=(const wxFileType&);
// the static container of wxFileType data: if it's not NULL, it means that
// this object is used as fallback only
const wxFileTypeInfo *m_info;
// the object which implements the real stuff like reading and writing
// to/from system MIME database
wxFileTypeImpl *m_impl;
};
// ----------------------------------------------------------------------------
// wxMimeTypesManager: interface to system MIME database.
//
// This class accesses the information about all known MIME types and allows
// the application to retrieve information (including how to handle data of
// given type) about them.
// ----------------------------------------------------------------------------
class WXDLLEXPORT wxMimeTypesManager
{
public:
// static helper functions
// -----------------------
// check if the given MIME type is the same as the other one: the
// second argument may contain wildcards ('*'), but not the first. If
// the types are equal or if the mimeType matches wildcard the function
// returns TRUE, otherwise it returns FALSE
static bool IsOfType(const wxString& mimeType, const wxString& wildcard);
// ctor
wxMimeTypesManager();
// Database lookup: all functions return a pointer to wxFileType object
// whose methods may be used to query it for the information you're
// interested in. If the return value is !NULL, caller is responsible for
// deleting it.
// get file type from file extension
wxFileType *GetFileTypeFromExtension(const wxString& ext);
// get file type from MIME type (in format <category>/<format>)
wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
// other operations: return TRUE if there were no errors or FALSE if there
// were some unreckognized entries (the good entries are always read anyhow)
// read in additional file (the standard ones are read automatically)
// in mailcap format (see mimetype.cpp for description)
//
// 'fallback' parameter may be set to TRUE to avoid overriding the
// settings from other, previously parsed, files by this one: normally,
// the files read most recently would override the older files, but with
// fallback == TRUE this won't happen
bool ReadMailcap(const wxString& filename, bool fallback = FALSE);
// read in additional file in mime.types format
bool ReadMimeTypes(const wxString& filename);
// enumerate all known MIME types
//
// returns the number of retrieved file types
size_t EnumAllFileTypes(wxArrayString& mimetypes);
// these functions can be used to provide default values for some of the
// MIME types inside the program itself (you may also use
// ReadMailcap(filenameWithDefaultTypes, TRUE /* use as fallback */) to
// achieve the same goal, but this requires having this info in a file).
//
// The filetypes array should be terminated by either NULL entry or an
// invalid wxFileTypeInfo (i.e. the one created with default ctor)
void AddFallbacks(const wxFileTypeInfo *filetypes);
void AddFallback(const wxFileTypeInfo& ft) { m_fallbacks.Add(ft); }
// create or remove associations
// create a new association using the fields of wxFileTypeInfo (at least
// the MIME type and the extension should be set)
wxFileType *Associate(const wxFileTypeInfo& ftInfo);
// undo Associate()
bool Unassociate(wxFileType *ft) { return ft->Unassociate(); }
// dtor (not virtual, shouldn't be derived from)
~wxMimeTypesManager();
private:
// no copy ctor/assignment operator
wxMimeTypesManager(const wxMimeTypesManager&);
wxMimeTypesManager& operator=(const wxMimeTypesManager&);
// the fallback info which is used if the information is not found in the
// real system database
wxArrayFileTypeInfo m_fallbacks;
// the object working with the system MIME database
wxMimeTypesManagerImpl *m_impl;
// if m_impl is NULL, create one
void EnsureImpl();
friend class wxMimeTypeCmnModule;
};
// ----------------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------------
// the default mime manager for wxWindows programs
WXDLLEXPORT_DATA(extern wxMimeTypesManager *) wxTheMimeTypesManager;
#endif
//_WX_MIMETYPE_H_
/* vi: set cin tw=80 ts=4 sw=4: */

116
include/wx/msw/mimetype.h Normal file
View File

@@ -0,0 +1,116 @@
/////////////////////////////////////////////////////////////////////////////
// Name: wx/msw/mimetype.h
// 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)
/////////////////////////////////////////////////////////////////////////////
#ifndef _MIMETYPE_IMPL_H
#define _MIMETYPE_IMPL_H
#ifdef __GNUG__
#pragma interface "mimetype.h"
#endif
#include "wx/defs.h"
#include "wx/mimetype.h"
// ----------------------------------------------------------------------------
// wxFileTypeImpl is the MSW version of wxFileType, this is a private class
// and is never used directly by the application
// ----------------------------------------------------------------------------
class WXDLLEXPORT wxFileTypeImpl
{
public:
// ctor
wxFileTypeImpl() { }
// one of these Init() function must be called (ctor can't take any
// arguments because it's common)
// initialize us with our file type name and extension - in this case
// we will read all other data from the registry
void Init(const wxString& strFileType, const wxString& ext);
// implement accessor functions
bool GetExtensions(wxArrayString& extensions);
bool GetMimeType(wxString *mimeType) const;
bool GetMimeTypes(wxArrayString& mimeTypes) const;
bool GetIcon(wxIcon *icon, wxString *sCommand = NULL, int *iIndex = NULL) const;
bool GetDescription(wxString *desc) const;
bool GetOpenCommand(wxString *openCmd,
const wxFileType::MessageParameters& params) const;
bool GetPrintCommand(wxString *printCmd,
const wxFileType::MessageParameters& params) const;
size_t GetAllCommands(wxArrayString * verbs, wxArrayString * commands,
const wxFileType::MessageParameters& params) const;
bool Unassociate();
// these methods are not publicly accessible (as wxMimeTypesManager
// doesn't know about them), and generally not very useful - they could be
// removed in the (near) future
bool SetCommand(const wxString& cmd, const wxString& verb,
bool overwriteprompt = true);
bool SetMimeType(const wxString& mimeType);
bool SetDefaultIcon(const wxString& cmd = wxEmptyString, int index = 0);
bool RemoveOpenCommand();
bool RemoveCommand(const wxString& verb);
bool RemoveMimeType();
bool RemoveDefaultIcon();
private:
// helper function: reads the command corresponding to the specified verb
// from the registry (returns an empty string if not found)
wxString GetCommand(const wxChar *verb) const;
// get the registry path for the given verb
wxString GetVerbPath(const wxString& verb) const;
// check that the registry key for our extension exists, create it if it
// doesn't, return FALSE if this failed
bool EnsureExtKeyExists();
wxString m_strFileType, // may be empty
m_ext;
};
class WXDLLEXPORT wxMimeTypesManagerImpl
{
public:
// nothing to do here, we don't load any data but just go and fetch it from
// the registry when asked for
wxMimeTypesManagerImpl() { }
// implement containing class functions
wxFileType *GetFileTypeFromExtension(const wxString& ext);
wxFileType *GetOrAllocateFileTypeFromExtension(const wxString& ext) ;
wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
size_t EnumAllFileTypes(wxArrayString& mimetypes);
// this are NOPs under Windows
bool ReadMailcap(const wxString& filename, bool fallback = TRUE)
{ return TRUE; }
bool ReadMimeTypes(const wxString& filename)
{ return TRUE; }
// create a new filetype association
wxFileType *Associate(const wxFileTypeInfo& ftInfo);
// create a new filetype with the given name and extension
wxFileType *CreateFileType(const wxString& filetype, const wxString& ext);
};
#endif
//_MIMETYPE_IMPL_H

149
include/wx/unix/mimetype.h Normal file
View File

@@ -0,0 +1,149 @@
/////////////////////////////////////////////////////////////////////////////
// Name: unix/mimetype.h
// 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)
/////////////////////////////////////////////////////////////////////////////
#ifndef _MIMETYPE_IMPL_H
#define _MIMETYPE_IMPL_H
#ifdef __GNUG__
#pragma interface "mimetype.h"
#endif
#include "wx/mimetype.h"
#if (wxUSE_FILE && wxUSE_TEXTFILE)
class MailCapEntry;
class wxMimeTypeIconHandler;
WX_DEFINE_ARRAY(wxMimeTypeIconHandler *, ArrayIconHandlers);
WX_DEFINE_ARRAY(MailCapEntry *, ArrayTypeEntries);
// this is the real wxMimeTypesManager for Unix
class WXDLLEXPORT wxMimeTypesManagerImpl
{
public:
// ctor and dtor
wxMimeTypesManagerImpl();
~wxMimeTypesManagerImpl();
// load all data into memory - done when it is needed for the first time
void Initialize();
// implement containing class functions
wxFileType *GetFileTypeFromExtension(const wxString& ext);
wxFileType *GetFileTypeFromMimeType(const wxString& mimeType);
size_t EnumAllFileTypes(wxArrayString& mimetypes);
bool ReadMailcap(const wxString& filename, bool fallback = FALSE);
bool ReadMimeTypes(const wxString& filename);
void AddFallback(const wxFileTypeInfo& filetype);
// add information about the given mimetype
void AddMimeTypeInfo(const wxString& mimetype,
const wxString& extensions,
const wxString& description);
void AddMailcapInfo(const wxString& strType,
const wxString& strOpenCmd,
const wxString& strPrintCmd,
const wxString& strTest,
const wxString& strDesc);
// add a new record to the user .mailcap/.mime.types files
wxFileType *Associate(const wxFileTypeInfo& ftInfo);
// accessors
// get the string containing space separated extensions for the given
// file type
wxString GetExtension(size_t index) { return m_aExtensions[index]; }
// get the array of icon handlers
static ArrayIconHandlers& GetIconHandlers();
private:
void InitIfNeeded()
{
if ( !m_initialized ) {
// set the flag first to prevent recursion
m_initialized = TRUE;
Initialize();
}
}
wxArrayString m_aTypes, // MIME types
m_aDescriptions, // descriptions (just some text)
m_aExtensions; // space separated list of extensions
ArrayTypeEntries m_aEntries; // commands and tests for this file type
// are we initialized?
bool m_initialized;
// head of the linked list of the icon handlers
static ArrayIconHandlers ms_iconHandlers;
// give it access to m_aXXX variables
friend class WXDLLEXPORT wxFileTypeImpl;
};
class WXDLLEXPORT wxFileTypeImpl
{
public:
// initialization functions
void Init(wxMimeTypesManagerImpl *manager, size_t index)
{ m_manager = manager; m_index.Add(index); }
// accessors
bool GetExtensions(wxArrayString& extensions);
bool GetMimeType(wxString *mimeType) const
{ *mimeType = m_manager->m_aTypes[m_index[0]]; return TRUE; }
bool GetMimeTypes(wxArrayString& mimeTypes) const;
bool GetIcon(wxIcon *icon) const;
bool GetDescription(wxString *desc) const
{ *desc = m_manager->m_aDescriptions[m_index[0]]; return TRUE; }
bool GetOpenCommand(wxString *openCmd,
const wxFileType::MessageParameters& params) const
{
return GetExpandedCommand(openCmd, params, TRUE);
}
bool GetPrintCommand(wxString *printCmd,
const wxFileType::MessageParameters& params) const
{
return GetExpandedCommand(printCmd, params, FALSE);
}
// remove the record for this file type
bool Unassociate();
private:
// get the entry which passes the test (may return NULL)
MailCapEntry *GetEntry(const wxFileType::MessageParameters& params) const;
// choose the correct entry to use and expand the command
bool GetExpandedCommand(wxString *expandedCmd,
const wxFileType::MessageParameters& params,
bool open) const;
wxMimeTypesManagerImpl *m_manager;
wxArrayInt m_index; // in the wxMimeTypesManagerImpl arrays
};
#endif
// wxUSE_FILE
#endif
//_MIMETYPE_IMPL_H

549
src/common/mimecmn.cpp Normal file
View File

@@ -0,0 +1,549 @@
/////////////////////////////////////////////////////////////////////////////
// Name: common/mimecmn.cpp
// Purpose: classes and functions to manage MIME types
// Author: Vadim Zeitlin
// Modified by:
// Chris Elliott (biol75@york.ac.uk) 5 Dec 00: write support for Win32
// Created: 23.09.98
// RCS-ID: $Id$
// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows license (part of wxExtra library)
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#ifdef __GNUG__
#pragma implementation "mimetypebase.h"
#endif
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#include "wx/module.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/defs.h"
#endif
#ifndef WX_PRECOMP
#include "wx/string.h"
#if wxUSE_GUI
#include "wx/icon.h"
#endif
#endif //WX_PRECOMP
#include "wx/log.h"
#include "wx/file.h"
#include "wx/intl.h"
#include "wx/dynarray.h"
#include "wx/confbase.h"
#include "wx/mimetype.h"
// other standard headers
#include <ctype.h>
// implementation classes:
#if defined(__WXMSW__)
#include "wx/msw/mimetype.h"
#elif defined(__WXMAC__)
#include "wx/mac/mimetype.h"
#elif defined(__WXPM__)
#include "wx/os2/mimetype.h"
#else // Unix
#include "wx/unix/mimetype.h"
#endif
// ============================================================================
// common classes
// ============================================================================
// ----------------------------------------------------------------------------
// wxFileTypeInfo
// ----------------------------------------------------------------------------
wxFileTypeInfo::wxFileTypeInfo(const char *mimeType,
const char *openCmd,
const char *printCmd,
const char *desc,
...)
: m_mimeType(mimeType),
m_openCmd(openCmd),
m_printCmd(printCmd),
m_desc(desc)
{
va_list argptr;
va_start(argptr, desc);
for ( ;; )
{
const char *ext = va_arg(argptr, const char *);
if ( !ext )
{
// NULL terminates the list
break;
}
m_exts.Add(ext);
}
va_end(argptr);
}
#include "wx/arrimpl.cpp"
WX_DEFINE_OBJARRAY(wxArrayFileTypeInfo);
// ============================================================================
// implementation of the wrapper classes
// ============================================================================
// ----------------------------------------------------------------------------
// wxFileType
// ----------------------------------------------------------------------------
/* static */
wxString wxFileType::ExpandCommand(const wxString& command,
const wxFileType::MessageParameters& params)
{
bool hasFilename = FALSE;
wxString str;
for ( const wxChar *pc = command.c_str(); *pc != wxT('\0'); pc++ ) {
if ( *pc == wxT('%') ) {
switch ( *++pc ) {
case wxT('s'):
// '%s' expands into file name (quoted because it might
// contain spaces) - except if there are already quotes
// there because otherwise some programs may get confused
// by double double quotes
#if 0
if ( *(pc - 2) == wxT('"') )
str << params.GetFileName();
else
str << wxT('"') << params.GetFileName() << wxT('"');
#endif
str << params.GetFileName();
hasFilename = TRUE;
break;
case wxT('t'):
// '%t' expands into MIME type (quote it too just to be
// consistent)
str << wxT('\'') << params.GetMimeType() << wxT('\'');
break;
case wxT('{'):
{
const wxChar *pEnd = wxStrchr(pc, wxT('}'));
if ( pEnd == NULL ) {
wxString mimetype;
wxLogWarning(_("Unmatched '{' in an entry for mime type %s."),
params.GetMimeType().c_str());
str << wxT("%{");
}
else {
wxString param(pc + 1, pEnd - pc - 1);
str << wxT('\'') << params.GetParamValue(param) << wxT('\'');
pc = pEnd;
}
}
break;
case wxT('n'):
case wxT('F'):
// TODO %n is the number of parts, %F is an array containing
// the names of temp files these parts were written to
// and their mime types.
break;
default:
wxLogDebug(wxT("Unknown field %%%c in command '%s'."),
*pc, command.c_str());
str << *pc;
}
}
else {
str << *pc;
}
}
// metamail(1) man page states that if the mailcap entry doesn't have '%s'
// the program will accept the data on stdin so normally we should append
// "< %s" to the end of the command in such case, but not all commands
// behave like this, in particular a common test is 'test -n "$DISPLAY"'
// and appending "< %s" to this command makes the test fail... I don't
// know of the correct solution, try to guess what we have to do.
if ( !hasFilename && !str.IsEmpty()
#ifdef __UNIX__
&& !str.StartsWith(_T("test "))
#endif // Unix
) {
str << wxT(" < '") << params.GetFileName() << wxT('\'');
}
return str;
}
wxFileType::wxFileType(const wxFileTypeInfo& info)
{
m_info = &info;
m_impl = NULL;
}
wxFileType::wxFileType()
{
m_info = NULL;
m_impl = new wxFileTypeImpl;
}
wxFileType::~wxFileType()
{
if ( m_impl )
delete m_impl;
}
bool wxFileType::GetExtensions(wxArrayString& extensions)
{
if ( m_info )
{
extensions = m_info->GetExtensions();
return TRUE;
}
return m_impl->GetExtensions(extensions);
}
bool wxFileType::GetMimeType(wxString *mimeType) const
{
wxCHECK_MSG( mimeType, FALSE, _T("invalid parameter in GetMimeType") );
if ( m_info )
{
*mimeType = m_info->GetMimeType();
return TRUE;
}
return m_impl->GetMimeType(mimeType);
}
bool wxFileType::GetMimeTypes(wxArrayString& mimeTypes) const
{
if ( m_info )
{
mimeTypes.Clear();
mimeTypes.Add(m_info->GetMimeType());
return TRUE;
}
return m_impl->GetMimeTypes(mimeTypes);
}
bool wxFileType::GetIcon(wxIcon *icon,
wxString *iconFile,
int *iconIndex) const
{
if ( m_info )
{
if ( iconFile )
*iconFile = m_info->GetIconFile();
if ( iconIndex )
*iconIndex = m_info->GetIconIndex();
#if wxUSE_GUI
if ( icon && !m_info->GetIconFile().empty() )
{
// FIXME: what about the index?
icon->LoadFile(m_info->GetIconFile());
}
#endif // wxUSE_GUI
return TRUE;
}
#ifdef __WXMSW__
return m_impl->GetIcon(icon, iconFile, iconIndex);
#else
return m_impl->GetIcon(icon);
#endif
}
bool wxFileType::GetDescription(wxString *desc) const
{
wxCHECK_MSG( desc, FALSE, _T("invalid parameter in GetDescription") );
if ( m_info )
{
*desc = m_info->GetDescription();
return TRUE;
}
return m_impl->GetDescription(desc);
}
bool
wxFileType::GetOpenCommand(wxString *openCmd,
const wxFileType::MessageParameters& params) const
{
wxCHECK_MSG( openCmd, FALSE, _T("invalid parameter in GetOpenCommand") );
if ( m_info )
{
*openCmd = ExpandCommand(m_info->GetOpenCommand(), params);
return TRUE;
}
return m_impl->GetOpenCommand(openCmd, params);
}
bool
wxFileType::GetPrintCommand(wxString *printCmd,
const wxFileType::MessageParameters& params) const
{
wxCHECK_MSG( printCmd, FALSE, _T("invalid parameter in GetPrintCommand") );
if ( m_info )
{
*printCmd = ExpandCommand(m_info->GetPrintCommand(), params);
return TRUE;
}
return m_impl->GetPrintCommand(printCmd, params);
}
size_t wxFileType::GetAllCommands(wxArrayString *verbs,
wxArrayString *commands,
const wxFileType::MessageParameters& params) const
{
if ( verbs )
verbs->Clear();
if ( commands )
commands->Clear();
#ifdef __WXMSW__
return m_impl->GetAllCommands(verbs, commands, params);
#else // !__WXMSW__
// we don't know how to retrieve all commands, so just try the 2 we know
// about
size_t count = 0;
wxString cmd;
if ( GetOpenCommand(&cmd, params) )
{
if ( verbs )
verbs->Add(_T("Open"));
if ( commands )
commands->Add(cmd);
count++;
}
if ( GetPrintCommand(&cmd, params) )
{
if ( verbs )
verbs->Add(_T("Print"));
if ( commands )
commands->Add(cmd);
count++;
}
return count;
#endif // __WXMSW__/!__WXMSW__
}
bool wxFileType::Unassociate()
{
#if defined(__WXMSW__) || defined(__UNIX__)
return m_impl->Unassociate();
#else
wxFAIL_MSG( _T("not implemented") ); // TODO
return FALSE;
#endif
}
// ----------------------------------------------------------------------------
// wxMimeTypesManager
// ----------------------------------------------------------------------------
void wxMimeTypesManager::EnsureImpl()
{
if ( !m_impl )
m_impl = new wxMimeTypesManagerImpl;
}
bool wxMimeTypesManager::IsOfType(const wxString& mimeType,
const wxString& wildcard)
{
wxASSERT_MSG( mimeType.Find(wxT('*')) == wxNOT_FOUND,
wxT("first MIME type can't contain wildcards") );
// all comparaisons are case insensitive (2nd arg of IsSameAs() is FALSE)
if ( wildcard.BeforeFirst(wxT('/')).
IsSameAs(mimeType.BeforeFirst(wxT('/')), FALSE) )
{
wxString strSubtype = wildcard.AfterFirst(wxT('/'));
if ( strSubtype == wxT("*") ||
strSubtype.IsSameAs(mimeType.AfterFirst(wxT('/')), FALSE) )
{
// matches (either exactly or it's a wildcard)
return TRUE;
}
}
return FALSE;
}
wxMimeTypesManager::wxMimeTypesManager()
{
m_impl = NULL;
}
wxMimeTypesManager::~wxMimeTypesManager()
{
if ( m_impl )
delete m_impl;
}
wxFileType *
wxMimeTypesManager::Associate(const wxFileTypeInfo& ftInfo)
{
EnsureImpl();
#if defined(__WXMSW__) || defined(__UNIX__)
return m_impl->Associate(ftInfo);
#else // other platforms
wxFAIL_MSG( _T("not implemented") ); // TODO
return NULL;
#endif // platforms
}
wxFileType *
wxMimeTypesManager::GetFileTypeFromExtension(const wxString& ext)
{
EnsureImpl();
wxFileType *ft = m_impl->GetFileTypeFromExtension(ext);
if ( !ft ) {
// check the fallbacks
//
// TODO linear search is potentially slow, perhaps we should use a
// sorted array?
size_t count = m_fallbacks.GetCount();
for ( size_t n = 0; n < count; n++ ) {
if ( m_fallbacks[n].GetExtensions().Index(ext) != wxNOT_FOUND ) {
ft = new wxFileType(m_fallbacks[n]);
break;
}
}
}
return ft;
}
wxFileType *
wxMimeTypesManager::GetFileTypeFromMimeType(const wxString& mimeType)
{
EnsureImpl();
wxFileType *ft = m_impl->GetFileTypeFromMimeType(mimeType);
if ( ft ) {
// check the fallbacks
//
// TODO linear search is potentially slow, perhaps we should use a sorted
// array?
size_t count = m_fallbacks.GetCount();
for ( size_t n = 0; n < count; n++ ) {
if ( wxMimeTypesManager::IsOfType(mimeType,
m_fallbacks[n].GetMimeType()) ) {
ft = new wxFileType(m_fallbacks[n]);
break;
}
}
}
return ft;
}
bool wxMimeTypesManager::ReadMailcap(const wxString& filename, bool fallback)
{
EnsureImpl();
return m_impl->ReadMailcap(filename, fallback);
}
bool wxMimeTypesManager::ReadMimeTypes(const wxString& filename)
{
EnsureImpl();
return m_impl->ReadMimeTypes(filename);
}
void wxMimeTypesManager::AddFallbacks(const wxFileTypeInfo *filetypes)
{
EnsureImpl();
for ( const wxFileTypeInfo *ft = filetypes; ft && ft->IsValid(); ft++ ) {
AddFallback(*ft);
}
}
size_t wxMimeTypesManager::EnumAllFileTypes(wxArrayString& mimetypes)
{
EnsureImpl();
size_t countAll = m_impl->EnumAllFileTypes(mimetypes);
// add the fallback filetypes
size_t count = m_fallbacks.GetCount();
for ( size_t n = 0; n < count; n++ ) {
if ( mimetypes.Index(m_fallbacks[n].GetMimeType()) == wxNOT_FOUND ) {
mimetypes.Add(m_fallbacks[n].GetMimeType());
countAll++;
}
}
return countAll;
}
// ----------------------------------------------------------------------------
// global data and wxMimeTypeCmnModule
// ----------------------------------------------------------------------------
// private object
static wxMimeTypesManager gs_mimeTypesManager;
// and public pointer
wxMimeTypesManager *wxTheMimeTypesManager = &gs_mimeTypesManager;
class wxMimeTypeCmnModule: public wxModule
{
public:
wxMimeTypeCmnModule() : wxModule() { }
virtual bool OnInit() { return TRUE; }
virtual void OnExit()
{
// this avoids false memory leak allerts:
if ( gs_mimeTypesManager.m_impl != NULL )
{
delete gs_mimeTypesManager.m_impl;
gs_mimeTypesManager.m_impl = NULL;
}
}
DECLARE_DYNAMIC_CLASS(wxMimeTypeCmnModule)
};
IMPLEMENT_DYNAMIC_CLASS(wxMimeTypeCmnModule, wxModule)

745
src/msw/mimetype.cpp Normal file
View File

@@ -0,0 +1,745 @@
/////////////////////////////////////////////////////////////////////////////
// Name: msw/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)
/////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "mimetype.h"
#endif
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// this is Win32 only code
#ifndef __WIN16__
#ifndef WX_PRECOMP
#include "wx/string.h"
#if wxUSE_GUI
#include "wx/icon.h"
#include "wx/msgdlg.h"
#endif
#endif //WX_PRECOMP
#include "wx/log.h"
#include "wx/file.h"
#include "wx/intl.h"
#include "wx/dynarray.h"
#include "wx/confbase.h"
#ifdef __WXMSW__
#include "wx/msw/registry.h"
#include "windows.h"
#endif // OS
#include "wx/msw/mimetype.h"
// other standard headers
#include <ctype.h>
// in case we're compiling in non-GUI mode
class WXDLLEXPORT wxIcon;
// These classes use Windows registry to retrieve the required information.
//
// Keys used (not all of them are documented, so it might actually stop working
// in future versions of Windows...):
// 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
// types, each key has a string value "Extension" which gives (dot preceded)
// extension for the files of this MIME type.
//
// 2. "HKCR\.ext" contains
// a) unnamed value containing the "filetype"
// b) value "Content Type" containing the MIME type
//
// 3. "HKCR\filetype" contains
// a) unnamed value containing the description
// b) subkey "DefaultIcon" with single unnamed value giving the icon index in
// an icon file
// c) shell\open\command and shell\open\print subkeys containing the commands
// to open/print the file (the positional parameters are introduced by %1,
// %2, ... in these strings, we change them to %s ourselves)
// although I don't know of any official documentation which mentions this
// location, uses it, so it isn't likely to change
static const wxChar *MIME_DATABASE_KEY = wxT("MIME\\Database\\Content Type\\");
void wxFileTypeImpl::Init(const wxString& strFileType, const wxString& ext)
{
// VZ: does it? (FIXME)
wxCHECK_RET( !ext.IsEmpty(), _T("needs an extension") );
if ( ext[0u] != wxT('.') ) {
m_ext = wxT('.');
}
m_ext << ext;
m_strFileType = strFileType;
if ( !strFileType ) {
m_strFileType = m_ext.AfterFirst('.') + "_auto_file";
}
}
wxString wxFileTypeImpl::GetVerbPath(const wxString& verb) const
{
wxString path;
path << m_strFileType << _T("\\shell\\") << verb << _T("\\command");
return path;
}
size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
wxArrayString *commands,
const wxFileType::MessageParameters& params) const
{
wxCHECK_MSG( !m_ext.IsEmpty(), 0, _T("GetAllCommands() needs an extension") );
if ( m_strFileType.IsEmpty() )
{
// get it from the registry
wxFileTypeImpl *self = wxConstCast(this, wxFileTypeImpl);
wxRegKey rkey(wxRegKey::HKCR, m_ext);
if ( !rkey.Exists() || !rkey.QueryValue(_T(""), self->m_strFileType) )
{
wxLogDebug(_T("Can't get the filetype for extension '%s'."),
m_ext.c_str());
return 0;
}
}
// enum all subkeys of HKCR\filetype\shell
size_t count = 0;
wxRegKey rkey(wxRegKey::HKCR, m_strFileType + _T("\\shell"));
long dummy;
wxString verb;
bool ok = rkey.GetFirstKey(verb, dummy);
while ( ok )
{
wxString command = wxFileType::ExpandCommand(GetCommand(verb), params);
// we want the open bverb to eb always the first
if ( verb.CmpNoCase(_T("open")) == 0 )
{
if ( verbs )
verbs->Insert(verb, 0);
if ( commands )
commands->Insert(command, 0);
}
else // anything else than "open"
{
if ( verbs )
verbs->Add(verb);
if ( commands )
commands->Add(command);
}
count++;
ok = rkey.GetNextKey(verb, dummy);
}
return count;
}
// ----------------------------------------------------------------------------
// modify the registry database
// ----------------------------------------------------------------------------
bool wxFileTypeImpl::EnsureExtKeyExists()
{
wxRegKey rkey(wxRegKey::HKCR, m_ext);
if ( !rkey.Exists() )
{
if ( !rkey.Create() || !rkey.SetValue(_T(""), m_strFileType) )
{
wxLogError(_("Failed to create registry entry for '%s' files."),
m_ext.c_str());
return FALSE;
}
}
return TRUE;
}
// ----------------------------------------------------------------------------
// get the command to use
// ----------------------------------------------------------------------------
wxString wxFileTypeImpl::GetCommand(const wxChar *verb) const
{
// suppress possible error messages
wxLogNull nolog;
wxString strKey;
if ( wxRegKey(wxRegKey::HKCR, m_ext + _T("\\shell")).Exists() )
strKey = m_ext;
if ( wxRegKey(wxRegKey::HKCR, m_strFileType + _T("\\shell")).Exists() )
strKey = m_strFileType;
if ( !strKey )
{
// no info
return wxEmptyString;
}
strKey << wxT("\\shell\\") << verb;
wxRegKey key(wxRegKey::HKCR, strKey + _T("\\command"));
wxString command;
if ( key.Open() ) {
// it's the default value of the key
if ( key.QueryValue(wxT(""), command) ) {
// transform it from '%1' to '%s' style format string (now also
// test for %L - apparently MS started using it as well for the
// same purpose)
// NB: we don't make any attempt to verify that the string is valid,
// i.e. doesn't contain %2, or second %1 or .... But we do make
// sure that we return a string with _exactly_ one '%s'!
bool foundFilename = FALSE;
size_t len = command.Len();
for ( size_t n = 0; (n < len) && !foundFilename; n++ ) {
if ( command[n] == wxT('%') &&
(n + 1 < len) &&
(command[n + 1] == wxT('1') ||
command[n + 1] == wxT('L')) ) {
// replace it with '%s'
command[n + 1] = wxT('s');
foundFilename = TRUE;
}
}
#if wxUSE_IPC
// look whether we must issue some DDE requests to the application
// (and not just launch it)
strKey += _T("\\DDEExec");
wxRegKey keyDDE(wxRegKey::HKCR, strKey);
if ( keyDDE.Open() ) {
wxString ddeCommand, ddeServer, ddeTopic;
keyDDE.QueryValue(_T(""), ddeCommand);
ddeCommand.Replace(_T("%1"), _T("%s"));
wxRegKey(wxRegKey::HKCR, strKey + _T("\\Application")).
QueryValue(_T(""), ddeServer);
wxRegKey(wxRegKey::HKCR, strKey + _T("\\Topic")).
QueryValue(_T(""), ddeTopic);
// HACK: we use a special feature of wxExecute which exists
// just because we need it here: it will establish DDE
// conversation with the program it just launched
command.Prepend(_T("WX_DDE#"));
command << _T('#') << ddeServer
<< _T('#') << ddeTopic
<< _T('#') << ddeCommand;
}
else
#endif // wxUSE_IPC
if ( !foundFilename ) {
// we didn't find any '%1' - the application doesn't know which
// file to open (note that we only do it if there is no DDEExec
// subkey)
//
// HACK: append the filename at the end, hope that it will do
command << wxT(" %s");
}
}
}
//else: no such file type or no value, will return empty string
return command;
}
bool
wxFileTypeImpl::GetOpenCommand(wxString *openCmd,
const wxFileType::MessageParameters& params)
const
{
wxString cmd = GetCommand(wxT("open"));
*openCmd = wxFileType::ExpandCommand(cmd, params);
return !openCmd->IsEmpty();
}
bool
wxFileTypeImpl::GetPrintCommand(wxString *printCmd,
const wxFileType::MessageParameters& params)
const
{
wxString cmd = GetCommand(wxT("print"));
*printCmd = wxFileType::ExpandCommand(cmd, params);
return !printCmd->IsEmpty();
}
// ----------------------------------------------------------------------------
// getting other stuff
// ----------------------------------------------------------------------------
// TODO this function is half implemented
bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
{
if ( m_ext.IsEmpty() ) {
// the only way to get the list of extensions from the file type is to
// scan through all extensions in the registry - too slow...
return FALSE;
}
else {
extensions.Empty();
extensions.Add(m_ext);
// it's a lie too, we don't return _all_ extensions...
return TRUE;
}
}
bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
{
// suppress possible error messages
wxLogNull nolog;
wxRegKey key(wxRegKey::HKCR, m_ext);
return key.Open() && key.QueryValue(wxT("Content Type"), *mimeType);
}
bool wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
{
wxString s;
if ( !GetMimeType(&s) )
{
return FALSE;
}
mimeTypes.Clear();
mimeTypes.Add(s);
return TRUE;
}
bool wxFileTypeImpl::GetIcon(wxIcon *icon,
wxString *iconFile,
int *iconIndex) const
{
#if wxUSE_GUI
wxString strIconKey;
strIconKey << m_strFileType << wxT("\\DefaultIcon");
// suppress possible error messages
wxLogNull nolog;
wxRegKey key(wxRegKey::HKCR, strIconKey);
if ( key.Open() ) {
wxString strIcon;
// it's the default value of the key
if ( key.QueryValue(wxT(""), strIcon) ) {
// the format is the following: <full path to file>, <icon index>
// NB: icon index may be negative as well as positive and the full
// path may contain the environment variables inside '%'
wxString strFullPath = strIcon.BeforeLast(wxT(',')),
strIndex = strIcon.AfterLast(wxT(','));
// index may be omitted, in which case BeforeLast(',') is empty and
// AfterLast(',') is the whole string
if ( strFullPath.IsEmpty() ) {
strFullPath = strIndex;
strIndex = wxT("0");
}
wxString strExpPath = wxExpandEnvVars(strFullPath);
// here we need C based counting!
int nIndex = wxAtoi(strIndex) - 1 ;
HICON hIcon = ExtractIcon(GetModuleHandle(NULL), strExpPath, nIndex);
switch ( (int)hIcon ) {
case 0: // means no icons were found
case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
key.GetName().c_str());
break;
default:
icon->SetHICON((WXHICON)hIcon);
if ( iconIndex )
*iconIndex = nIndex;
if ( iconFile )
*iconFile = strFullPath;
return TRUE;
}
}
}
// no such file type or no value or incorrect icon entry
#endif // wxUSE_GUI
return FALSE;
}
bool wxFileTypeImpl::GetDescription(wxString *desc) const
{
// suppress possible error messages
wxLogNull nolog;
wxRegKey key(wxRegKey::HKCR, m_strFileType);
if ( key.Open() ) {
// it's the default value of the key
if ( key.QueryValue(wxT(""), *desc) ) {
return TRUE;
}
}
return FALSE;
}
// helper function
wxFileType *
wxMimeTypesManagerImpl::CreateFileType(const wxString& filetype, const wxString& ext)
{
wxFileType *fileType = new wxFileType;
fileType->m_impl->Init(filetype, ext);
return fileType;
}
// extension -> file type
wxFileType *
wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
{
// add the leading point if necessary
wxString str;
if ( ext[0u] != wxT('.') ) {
str = wxT('.');
}
str << ext;
// suppress possible error messages
wxLogNull nolog;
bool knownExtension = FALSE;
wxString strFileType;
wxRegKey key(wxRegKey::HKCR, str);
if ( key.Open() ) {
// it's the default value of the key
if ( key.QueryValue(wxT(""), strFileType) ) {
// create the new wxFileType object
return CreateFileType(strFileType, ext);
}
else {
// this extension doesn't have a filetype, but it's known to the
// system and may be has some other useful keys (open command or
// content-type), so still return a file type object for it
knownExtension = TRUE;
}
}
if ( !knownExtension )
{
// unknown extension
return NULL;
}
return CreateFileType(wxEmptyString, ext);
}
wxFileType *
wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
{
wxFileType *fileType = GetFileTypeFromExtension(ext);
if ( !fileType )
{
fileType = CreateFileType(wxEmptyString, ext);
}
return fileType;
}
// MIME type -> extension -> file type
wxFileType *
wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
{
wxString strKey = MIME_DATABASE_KEY;
strKey << mimeType;
// suppress possible error messages
wxLogNull nolog;
wxString ext;
wxRegKey key(wxRegKey::HKCR, strKey);
if ( key.Open() ) {
if ( key.QueryValue(wxT("Extension"), ext) ) {
return GetFileTypeFromExtension(ext);
}
}
// unknown MIME type
return NULL;
}
size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
{
// enumerate all keys under MIME_DATABASE_KEY
wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
wxString type;
long cookie;
bool cont = key.GetFirstKey(type, cookie);
while ( cont )
{
mimetypes.Add(type);
cont = key.GetNextKey(type, cookie);
}
return mimetypes.GetCount();
}
// ----------------------------------------------------------------------------
// create a new association
// ----------------------------------------------------------------------------
wxFileType *wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
{
wxCHECK_MSG( !ftInfo.GetExtensions().IsEmpty(), NULL,
_T("Associate() needs extension") );
const wxString& ext = ftInfo.GetExtensions()[0u];
wxCHECK_MSG( !ext.empty(), NULL,
_T("Associate() needs non empty extension") );
wxString extWithDot;
if ( ext[0u] != _T('.') )
extWithDot = _T('.');
extWithDot += ext;
wxRegKey key(wxRegKey::HKCR, extWithDot);
wxFileType *ft = NULL;
if ( !key.Exists() )
{
wxString filetype;
// create the mapping from the extension to the filetype
bool ok = key.Create();
if ( ok )
{
const wxString& filetypeOrig = ftInfo.GetShortDesc();
if ( filetypeOrig.empty() )
{
// make it up from the extension
filetype << extWithDot.c_str() + 1 << _T("_auto_file");
}
else
{
// just use the provided one
filetype = filetypeOrig;
}
ok = key.SetValue(_T(""), filetype);
}
const wxString& mimetype = ftInfo.GetMimeType();
if ( ok && !mimetype.empty() )
{
// set the MIME type
ok = key.SetValue(_T("Content Type"), mimetype);
if ( ok )
{
// create the MIME key
wxString strKey = MIME_DATABASE_KEY;
strKey << mimetype;
wxRegKey keyMIME(wxRegKey::HKCR, strKey);
ok = keyMIME.Create();
if ( ok )
{
// and provide a back link to the extension
ok = keyMIME.SetValue(_T("Extension"), extWithDot);
}
}
}
if ( ok )
{
// create the filetype key itself (it will be empty for now, but
// SetCommand(), SetDefaultIcon() &c will use it later)
wxRegKey keyFT(wxRegKey::HKCR, filetype);
ok = keyFT.Create();
}
if ( ok )
{
// ok, we've created everything correctly
ft = CreateFileType(filetype, extWithDot);
}
else
{
// one of the registry operations failed
wxLogError(_("Failed to register extension '%s'."), ext.c_str());
}
}
else // key already exists
{
// FIXME we probably should return an existing file type then?
}
return ft;
}
bool wxFileTypeImpl::SetCommand(const wxString& cmd,
const wxString& verb,
bool overwriteprompt)
{
wxCHECK_MSG( !m_ext.IsEmpty() && !verb.IsEmpty(), FALSE,
_T("SetCommand() needs an extension and a verb") );
if ( !EnsureExtKeyExists() )
return FALSE;
wxRegKey rkey(wxRegKey::HKCR, GetVerbPath(verb));
if ( rkey.Exists() && overwriteprompt )
{
#if wxUSE_GUI
wxString old;
rkey.QueryValue(wxT(""), old);
if ( wxMessageBox
(
wxString::Format(
_("Do you want to overwrite the command used to %s "
"files with extension \"%s\" (current value is '%s', "
"new value is '%s')?"),
verb.c_str(),
m_ext.c_str(),
old.c_str(),
cmd.c_str()),
_("Confirm registry update"),
wxYES_NO | wxICON_QUESTION
) != wxYES )
#endif // wxUSE_GUI
{
// cancelled by user
return FALSE;
}
}
// TODO:
// 1. translate '%s' to '%1' instead of always adding it
// 2. create DDEExec value if needed (undo GetCommand)
return rkey.Create() && rkey.SetValue(_T(""), cmd + _T(" \"%1\"") );
}
bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
{
wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("SetMimeType() needs extension") );
if ( !EnsureExtKeyExists() )
return FALSE;
// VZ: is this really useful? (FIXME)
wxString mimeType;
if ( !mimeTypeOrig )
{
// make up a default value for it
wxString cmd;
wxSplitPath(GetCommand(_T("open")), NULL, &cmd, NULL);
mimeType << _T("application/x-") << cmd;
}
else
{
mimeType = mimeTypeOrig;
}
wxRegKey rkey(wxRegKey::HKCR, m_ext);
return rkey.Create() && rkey.SetValue(_T("Content Type"), mimeType);
}
bool wxFileTypeImpl::SetDefaultIcon(const wxString& cmd, int index)
{
wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("SetMimeType() needs extension") );
wxCHECK_MSG( wxFileExists(cmd), FALSE, _T("Icon file not found.") );
if ( !EnsureExtKeyExists() )
return FALSE;
wxRegKey rkey(wxRegKey::HKCR, m_strFileType + _T("\\DefaultIcon"));
return rkey.Create() &&
rkey.SetValue(_T(""),
wxString::Format(_T("%s,%d"), cmd.c_str(), index));
}
// ----------------------------------------------------------------------------
// remove file association
// ----------------------------------------------------------------------------
bool wxFileTypeImpl::Unassociate()
{
bool result = TRUE;
if ( !RemoveOpenCommand() )
result = FALSE;
if ( !RemoveDefaultIcon() )
result = FALSE;
if ( !RemoveMimeType() )
result = FALSE;
if ( result )
{
// delete the root key
wxRegKey key(wxRegKey::HKCR, m_ext);
if ( key.Exists() )
result = key.DeleteSelf();
}
return result;
}
bool wxFileTypeImpl::RemoveOpenCommand()
{
return RemoveCommand(_T("open"));
}
bool wxFileTypeImpl::RemoveCommand(const wxString& verb)
{
wxCHECK_MSG( !m_ext.IsEmpty() && !verb.IsEmpty(), FALSE,
_T("RemoveCommand() needs an extension and a verb") );
wxString sKey = m_strFileType;
wxRegKey rkey(wxRegKey::HKCR, GetVerbPath(verb));
// if the key already doesn't exist, it's a success
return !rkey.Exists() || rkey.DeleteSelf();
}
bool wxFileTypeImpl::RemoveMimeType()
{
wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("RemoveMimeType() needs extension") );
wxRegKey rkey(wxRegKey::HKCR, m_ext);
return !rkey.Exists() || rkey.DeleteSelf();
}
bool wxFileTypeImpl::RemoveDefaultIcon()
{
wxCHECK_MSG( !m_ext.IsEmpty(), FALSE,
_T("RemoveDefaultIcon() needs extension") );
wxRegKey rkey (wxRegKey::HKCR, m_strFileType + _T("\\DefaultIcon"));
return !rkey.Exists() || rkey.DeleteSelf();
}
#endif
// __WIN16__

1821
src/unix/mimetype.cpp Normal file

File diff suppressed because it is too large Load Diff