1
/////////////////////////////////////////////////////////////////////////////
2
// Name: src/msw/mimetype.cpp
3
// Purpose: classes and functions to manage MIME types
4
// Author: Vadim Zeitlin
7
// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
8
// Licence: wxWindows licence (part of wxExtra library)
9
/////////////////////////////////////////////////////////////////////////////
11
// for compilers that support precompilation, includes "wx.h".
12
#include "wx/wxprec.h"
20
#include "wx/msw/mimetype.h"
23
#include "wx/dynarray.h"
24
#include "wx/string.h"
30
#include "wx/msgdlg.h"
35
#include "wx/iconloc.h"
36
#include "wx/confbase.h"
39
#include "wx/msw/registry.h"
40
#include "wx/msw/private.h"
43
// other standard headers
46
// in case we're compiling in non-GUI mode
47
class WXDLLIMPEXP_FWD_CORE wxIcon;
49
// These classes use Windows registry to retrieve the required information.
51
// Keys used (not all of them are documented, so it might actually stop working
52
// in future versions of Windows...):
53
// 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
54
// types, each key has a string value "Extension" which gives (dot preceded)
55
// extension for the files of this MIME type.
57
// 2. "HKCR\.ext" contains
58
// a) unnamed value containing the "filetype"
59
// b) value "Content Type" containing the MIME type
61
// 3. "HKCR\filetype" contains
62
// a) unnamed value containing the description
63
// b) subkey "DefaultIcon" with single unnamed value giving the icon index in
65
// c) shell\open\command and shell\open\print subkeys containing the commands
66
// to open/print the file (the positional parameters are introduced by %1,
67
// %2, ... in these strings, we change them to %s ourselves)
69
// although I don't know of any official documentation which mentions this
70
// location, uses it, so it isn't likely to change
71
static const wxChar *MIME_DATABASE_KEY = wxT("MIME\\Database\\Content Type\\");
73
// this function replaces Microsoft %1 with Unix-like %s
74
static bool CanonicalizeParams(wxString& command)
76
// transform it from '%1' to '%s' style format string (now also test for %L
77
// as apparently MS started using it as well for the same purpose)
79
// NB: we don't make any attempt to verify that the string is valid, i.e.
80
// doesn't contain %2, or second %1 or .... But we do make sure that we
81
// return a string with _exactly_ one '%s'!
82
bool foundFilename = false;
83
size_t len = command.length();
84
for ( size_t n = 0; (n < len) && !foundFilename; n++ )
86
if ( command[n] == wxT('%') &&
88
(command[n + 1] == wxT('1') || command[n + 1] == wxT('L')) )
90
// replace it with '%s'
91
command[n + 1] = wxT('s');
99
// Some values also contain an addition %* expansion string which is
100
// presumably supposed to be replaced with the names of the other files
101
// accepted by the command. As we don't support more than one file
102
// anyhow, simply ignore it.
103
command.Replace(" %*", "");
106
return foundFilename;
109
void wxFileTypeImpl::Init(const wxString& strFileType, const wxString& ext)
111
// VZ: does it? (FIXME)
112
wxCHECK_RET( !ext.empty(), wxT("needs an extension") );
114
if ( ext[0u] != wxT('.') ) {
119
m_strFileType = strFileType;
120
if ( !strFileType ) {
121
m_strFileType = m_ext.AfterFirst('.') + wxT("_auto_file");
125
wxString wxFileTypeImpl::GetVerbPath(const wxString& verb) const
128
path << m_strFileType << wxT("\\shell\\") << verb << wxT("\\command");
132
size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
133
wxArrayString *commands,
134
const wxFileType::MessageParameters& params) const
136
wxCHECK_MSG( !m_ext.empty(), 0, wxT("GetAllCommands() needs an extension") );
138
if ( m_strFileType.empty() )
140
// get it from the registry
141
wxFileTypeImpl *self = wxConstCast(this, wxFileTypeImpl);
142
wxRegKey rkey(wxRegKey::HKCR, m_ext);
143
if ( !rkey.Exists() || !rkey.QueryValue(wxEmptyString, self->m_strFileType) )
145
wxLogDebug(wxT("Can't get the filetype for extension '%s'."),
152
// enum all subkeys of HKCR\filetype\shell
154
wxRegKey rkey(wxRegKey::HKCR, m_strFileType + wxT("\\shell"));
157
bool ok = rkey.GetFirstKey(verb, dummy);
160
wxString command = wxFileType::ExpandCommand(GetCommand(verb), params);
162
// we want the open bverb to eb always the first
164
if ( verb.CmpNoCase(wxT("open")) == 0 )
167
verbs->Insert(verb, 0);
169
commands->Insert(command, 0);
171
else // anything else than "open"
176
commands->Add(command);
181
ok = rkey.GetNextKey(verb, dummy);
187
// ----------------------------------------------------------------------------
188
// modify the registry database
189
// ----------------------------------------------------------------------------
191
bool wxFileTypeImpl::EnsureExtKeyExists()
193
wxRegKey rkey(wxRegKey::HKCR, m_ext);
194
if ( !rkey.Exists() )
196
if ( !rkey.Create() || !rkey.SetValue(wxEmptyString, m_strFileType) )
198
wxLogError(_("Failed to create registry entry for '%s' files."),
207
// ----------------------------------------------------------------------------
208
// get the command to use
209
// ----------------------------------------------------------------------------
211
static wxString wxFileTypeImplGetCurVer(const wxString& progId)
213
wxRegKey key(wxRegKey::HKCR, progId + wxT("\\CurVer"));
217
if (key.QueryValue(wxEmptyString, value))
223
wxString wxFileTypeImpl::GetCommand(const wxString& verb) const
225
// suppress possible error messages
229
// Since Windows Vista the association used by Explorer is different from
230
// the association information stored in the traditional part of the
231
// registry. Unfortunately the new schema doesn't seem to be documented
232
// anywhere so using it involves a bit of guesswork:
234
// The information is stored under Explorer-specific key whose path is
235
// below. The interesting part is UserChoice subkey which is the only one
236
// we use so far but there is also OpenWithProgids subkey which can exist
237
// even if UserChoice doesn't. However in practice there doesn't seem to be
238
// any cases when OpenWithProgids values for the given extension are
239
// different from those found directly under HKCR\.ext, so for now we don't
240
// bother to use this, apparently the programs registering their file type
241
// associations do it in both places. We do use UserChoice because when the
242
// association is manually changed by the user it's only recorded there and
243
// so must override whatever value was created under HKCR by the setup
250
wxT("Software\\Microsoft\\Windows\\CurrentVersion\\")
251
wxT("Explorer\\FileExts\\") +
255
if ( explorerKey.Open(wxRegKey::Read) &&
256
explorerKey.QueryValue(wxT("Progid"), strKey) )
258
strKey = wxFileTypeImplGetCurVer(strKey);
262
if (!strKey && wxRegKey(wxRegKey::HKCR, m_ext + wxT("\\shell")).Exists())
265
if ( !strKey && !m_strFileType.empty())
267
wxString fileType = wxFileTypeImplGetCurVer(m_strFileType);
268
if (wxRegKey(wxRegKey::HKCR, fileType + wxT("\\shell")).Exists())
275
return wxEmptyString;
278
strKey << wxT("\\shell\\") << verb;
279
wxRegKey key(wxRegKey::HKCR, strKey + wxT("\\command"));
281
if ( key.Open(wxRegKey::Read) ) {
282
// it's the default value of the key
283
if ( key.QueryValue(wxEmptyString, command) ) {
284
bool foundFilename = CanonicalizeParams(command);
287
// look whether we must issue some DDE requests to the application
288
// (and not just launch it)
289
strKey += wxT("\\DDEExec");
290
wxRegKey keyDDE(wxRegKey::HKCR, strKey);
291
if ( keyDDE.Open(wxRegKey::Read) ) {
292
wxString ddeCommand, ddeServer, ddeTopic;
293
keyDDE.QueryValue(wxEmptyString, ddeCommand);
295
// in some cases "DDEExec" subkey exists but has no value, we
296
// shouldn't use DDE in this case
297
if ( !ddeCommand.empty() ) {
298
ddeCommand.Replace(wxT("%1"), wxT("%s"));
300
wxRegKey keyServer(wxRegKey::HKCR, strKey + wxT("\\Application"));
301
keyServer.QueryValue(wxEmptyString, ddeServer);
302
wxRegKey keyTopic(wxRegKey::HKCR, strKey + wxT("\\Topic"));
303
keyTopic.QueryValue(wxEmptyString, ddeTopic);
305
if (ddeTopic.empty())
306
ddeTopic = wxT("System");
308
// HACK: we use a special feature of wxExecute which exists
309
// just because we need it here: it will establish DDE
310
// conversation with the program it just launched
311
command.Prepend(wxT("WX_DDE#"));
312
command << wxT('#') << ddeServer
313
<< wxT('#') << ddeTopic
314
<< wxT('#') << ddeCommand;
319
if ( !foundFilename )
321
// we didn't find any '%1' - the application doesn't know which
322
// file to open (note that we only do it if there is no DDEExec
325
// HACK: append the filename at the end, hope that it will do
326
command << wxT(" %s");
330
//else: no such file type or no value, will return empty string
336
wxFileTypeImpl::GetOpenCommand(wxString *openCmd,
337
const wxFileType::MessageParameters& params)
340
wxString cmd = GetCommand(wxT("open"));
342
*openCmd = wxFileType::ExpandCommand(cmd, params);
344
return !openCmd->empty();
348
wxFileTypeImpl::GetPrintCommand(wxString *printCmd,
349
const wxFileType::MessageParameters& params)
352
wxString cmd = GetCommand(wxT("print"));
354
*printCmd = wxFileType::ExpandCommand(cmd, params);
356
return !printCmd->empty();
359
// ----------------------------------------------------------------------------
360
// getting other stuff
361
// ----------------------------------------------------------------------------
363
// TODO this function is half implemented
364
bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
366
if ( m_ext.empty() ) {
367
// the only way to get the list of extensions from the file type is to
368
// scan through all extensions in the registry - too slow...
373
extensions.Add(m_ext);
375
// it's a lie too, we don't return _all_ extensions...
380
bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
382
// suppress possible error messages
384
wxRegKey key(wxRegKey::HKCR, m_ext);
386
return key.Open(wxRegKey::Read) &&
387
key.QueryValue(wxT("Content Type"), *mimeType);
390
bool wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
394
if ( !GetMimeType(&s) )
405
bool wxFileTypeImpl::GetIcon(wxIconLocation *iconLoc) const
408
strIconKey << m_strFileType << wxT("\\DefaultIcon");
410
// suppress possible error messages
412
wxRegKey key(wxRegKey::HKCR, strIconKey);
414
if ( key.Open(wxRegKey::Read) ) {
416
// it's the default value of the key
417
if ( key.QueryValue(wxEmptyString, strIcon) ) {
418
// the format is the following: <full path to file>, <icon index>
419
// NB: icon index may be negative as well as positive and the full
420
// path may contain the environment variables inside '%'
421
wxString strFullPath = strIcon.BeforeLast(wxT(',')),
422
strIndex = strIcon.AfterLast(wxT(','));
424
// index may be omitted, in which case BeforeLast(',') is empty and
425
// AfterLast(',') is the whole string
426
if ( strFullPath.empty() ) {
427
strFullPath = strIndex;
433
iconLoc->SetFileName(wxExpandEnvVars(strFullPath));
435
iconLoc->SetIndex(wxAtoi(strIndex));
442
// no such file type or no value or incorrect icon entry
446
bool wxFileTypeImpl::GetDescription(wxString *desc) const
448
// suppress possible error messages
450
wxRegKey key(wxRegKey::HKCR, m_strFileType);
452
if ( key.Open(wxRegKey::Read) ) {
453
// it's the default value of the key
454
if ( key.QueryValue(wxEmptyString, *desc) ) {
464
wxMimeTypesManagerImpl::CreateFileType(const wxString& filetype, const wxString& ext)
466
wxFileType *fileType = new wxFileType;
467
fileType->m_impl->Init(filetype, ext);
471
// extension -> file type
473
wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
475
// add the leading point if necessary
477
if ( ext[0u] != wxT('.') ) {
482
// suppress possible error messages
485
bool knownExtension = false;
487
wxString strFileType;
488
wxRegKey key(wxRegKey::HKCR, str);
489
if ( key.Open(wxRegKey::Read) ) {
490
// it's the default value of the key
491
if ( key.QueryValue(wxEmptyString, strFileType) ) {
492
// create the new wxFileType object
493
return CreateFileType(strFileType, ext);
496
// this extension doesn't have a filetype, but it's known to the
497
// system and may be has some other useful keys (open command or
498
// content-type), so still return a file type object for it
499
knownExtension = true;
503
if ( !knownExtension )
509
return CreateFileType(wxEmptyString, ext);
514
wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
516
wxFileType *fileType = GetFileTypeFromExtension(ext);
519
fileType = CreateFileType(wxEmptyString, ext);
526
// MIME type -> extension -> file type
528
wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
530
wxString strKey = MIME_DATABASE_KEY;
533
// suppress possible error messages
537
wxRegKey key(wxRegKey::HKCR, strKey);
538
if ( key.Open(wxRegKey::Read) ) {
539
if ( key.QueryValue(wxT("Extension"), ext) ) {
540
return GetFileTypeFromExtension(ext);
548
size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
550
// enumerate all keys under MIME_DATABASE_KEY
551
wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
555
bool cont = key.GetFirstKey(type, cookie);
560
cont = key.GetNextKey(type, cookie);
563
return mimetypes.GetCount();
566
// ----------------------------------------------------------------------------
567
// create a new association
568
// ----------------------------------------------------------------------------
570
wxFileType *wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
572
wxCHECK_MSG( !ftInfo.GetExtensions().empty(), NULL,
573
wxT("Associate() needs extension") );
576
size_t iExtCount = 0;
580
wxString ext = ftInfo.GetExtensions()[iExtCount];
582
wxCHECK_MSG( !ext.empty(), NULL,
583
wxT("Associate() needs non empty extension") );
585
if ( ext[0u] != wxT('.') )
586
extWithDot = wxT('.');
589
// start by setting the HKCR\\.ext entries
590
// default is filetype; content type is mimetype
591
const wxString& filetypeOrig = ftInfo.GetShortDesc();
593
wxRegKey key(wxRegKey::HKCR, extWithDot);
596
// create the mapping from the extension to the filetype
601
if ( filetypeOrig.empty() )
603
// make it up from the extension
604
filetype << extWithDot.c_str() + 1 << wxT("_file");
608
// just use the provided one
609
filetype = filetypeOrig;
612
key.SetValue(wxEmptyString, filetype);
617
// key already exists, maybe we want to change it ??
618
if (!filetypeOrig.empty())
620
filetype = filetypeOrig;
621
key.SetValue(wxEmptyString, filetype);
625
key.QueryValue(wxEmptyString, filetype);
629
// now set a mimetypeif we have it, but ignore it if none
630
const wxString& mimetype = ftInfo.GetMimeType();
631
if ( !mimetype.empty() )
634
ok = key.SetValue(wxT("Content Type"), mimetype);
638
// create the MIME key
639
wxString strKey = MIME_DATABASE_KEY;
641
wxRegKey keyMIME(wxRegKey::HKCR, strKey);
642
ok = keyMIME.Create();
646
// and provide a back link to the extension
647
keyMIME.SetValue(wxT("Extension"), extWithDot);
653
// now make other extensions have the same filetype
655
for (iExtCount=1; iExtCount < ftInfo.GetExtensionsCount(); iExtCount++ )
657
ext = ftInfo.GetExtensions()[iExtCount];
658
if ( ext[0u] != wxT('.') )
659
extWithDot = wxT('.');
662
wxRegKey key2(wxRegKey::HKCR, extWithDot);
663
if ( !key2.Exists() )
665
key2.SetValue(wxEmptyString, filetype);
667
// now set any mimetypes we may have, but ignore it if none
668
const wxString& mimetype2 = ftInfo.GetMimeType();
669
if ( !mimetype2.empty() )
672
ok = key2.SetValue(wxT("Content Type"), mimetype2);
676
// create the MIME key
677
wxString strKey = MIME_DATABASE_KEY;
679
wxRegKey keyMIME(wxRegKey::HKCR, strKey);
680
ok = keyMIME.Create();
684
// and provide a back link to the extension
685
keyMIME.SetValue(wxT("Extension"), extWithDot);
690
} // end of for loop; all extensions now point to HKCR\.ext\Default
692
// create the filetype key itself (it will be empty for now, but
693
// SetCommand(), SetDefaultIcon() &c will use it later)
694
wxRegKey keyFT(wxRegKey::HKCR, filetype);
697
wxFileType *ft = CreateFileType(filetype, extWithDot);
701
if (! ftInfo.GetOpenCommand ().empty() ) ft->SetCommand (ftInfo.GetOpenCommand (), wxT("open" ) );
702
if (! ftInfo.GetPrintCommand().empty() ) ft->SetCommand (ftInfo.GetPrintCommand(), wxT("print" ) );
703
// chris: I don't like the ->m_impl-> here FIX this ??
704
if (! ftInfo.GetDescription ().empty() ) ft->m_impl->SetDescription (ftInfo.GetDescription ()) ;
705
if (! ftInfo.GetIconFile().empty() ) ft->SetDefaultIcon (ftInfo.GetIconFile(), ftInfo.GetIconIndex() );
712
bool wxFileTypeImpl::SetCommand(const wxString& cmd,
713
const wxString& verb,
714
bool WXUNUSED(overwriteprompt))
716
wxCHECK_MSG( !m_ext.empty() && !verb.empty(), false,
717
wxT("SetCommand() needs an extension and a verb") );
719
if ( !EnsureExtKeyExists() )
722
wxRegKey rkey(wxRegKey::HKCR, GetVerbPath(verb));
724
if ( rkey.Exists() && overwriteprompt )
728
rkey.QueryValue(wxEmptyString, old);
732
_("Do you want to overwrite the command used to %s "
733
"files with extension \"%s\" ?\nCurrent value is \n%s, "
734
"\nNew value is \n%s %1"), // bug here FIX need %1 ??
739
_("Confirm registry update"),
740
wxYES_NO | wxICON_QUESTION
750
// 1. translate '%s' to '%1' instead of always adding it
751
// 2. create DDEExec value if needed (undo GetCommand)
752
return rkey.Create() && rkey.SetValue(wxEmptyString, cmd + wxT(" \"%1\"") );
756
bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
758
wxCHECK_MSG( !m_ext.empty(), false, wxT("SetMimeType() needs extension") );
760
if ( !EnsureExtKeyExists() )
763
// VZ: is this really useful? (FIXME)
767
// make up a default value for it
769
wxFileName::SplitPath(GetCommand(wxT("open")), NULL, &cmd, NULL);
770
mimeType << wxT("application/x-") << cmd;
774
mimeType = mimeTypeOrig;
777
wxRegKey rkey(wxRegKey::HKCR, m_ext);
778
return rkey.Create() && rkey.SetValue(wxT("Content Type"), mimeType);
782
bool wxFileTypeImpl::SetDefaultIcon(const wxString& cmd, int index)
784
wxCHECK_MSG( !m_ext.empty(), false, wxT("SetDefaultIcon() needs extension") );
785
wxCHECK_MSG( !m_strFileType.empty(), false, wxT("File key not found") );
786
// the next line fails on a SMBshare, I think because it is case mangled
787
// wxCHECK_MSG( !wxFileExists(cmd), false, wxT("Icon file not found.") );
789
if ( !EnsureExtKeyExists() )
792
wxRegKey rkey(wxRegKey::HKCR, m_strFileType + wxT("\\DefaultIcon"));
794
return rkey.Create() &&
795
rkey.SetValue(wxEmptyString,
796
wxString::Format(wxT("%s,%d"), cmd.c_str(), index));
799
bool wxFileTypeImpl::SetDescription (const wxString& desc)
801
wxCHECK_MSG( !m_strFileType.empty(), false, wxT("File key not found") );
802
wxCHECK_MSG( !desc.empty(), false, wxT("No file description supplied") );
804
if ( !EnsureExtKeyExists() )
807
wxRegKey rkey(wxRegKey::HKCR, m_strFileType );
809
return rkey.Create() &&
810
rkey.SetValue(wxEmptyString, desc);
813
// ----------------------------------------------------------------------------
814
// remove file association
815
// ----------------------------------------------------------------------------
817
bool wxFileTypeImpl::Unassociate()
820
if ( !RemoveOpenCommand() )
822
if ( !RemoveDefaultIcon() )
824
if ( !RemoveMimeType() )
826
if ( !RemoveDescription() )
830
//this might hold other keys, eg some have CSLID keys
833
// delete the root key
834
wxRegKey key(wxRegKey::HKCR, m_ext);
836
result = key.DeleteSelf();
842
bool wxFileTypeImpl::RemoveOpenCommand()
844
return RemoveCommand(wxT("open"));
847
bool wxFileTypeImpl::RemoveCommand(const wxString& verb)
849
wxCHECK_MSG( !m_ext.empty() && !verb.empty(), false,
850
wxT("RemoveCommand() needs an extension and a verb") );
852
wxRegKey rkey(wxRegKey::HKCR, GetVerbPath(verb));
854
// if the key already doesn't exist, it's a success
855
return !rkey.Exists() || rkey.DeleteSelf();
858
bool wxFileTypeImpl::RemoveMimeType()
860
wxCHECK_MSG( !m_ext.empty(), false, wxT("RemoveMimeType() needs extension") );
862
wxRegKey rkey(wxRegKey::HKCR, m_ext);
863
return !rkey.Exists() || rkey.DeleteSelf();
866
bool wxFileTypeImpl::RemoveDefaultIcon()
868
wxCHECK_MSG( !m_ext.empty(), false,
869
wxT("RemoveDefaultIcon() needs extension") );
871
wxRegKey rkey (wxRegKey::HKCR, m_strFileType + wxT("\\DefaultIcon"));
872
return !rkey.Exists() || rkey.DeleteSelf();
875
bool wxFileTypeImpl::RemoveDescription()
877
wxCHECK_MSG( !m_ext.empty(), false,
878
wxT("RemoveDescription() needs extension") );
880
wxRegKey rkey (wxRegKey::HKCR, m_strFileType );
881
return !rkey.Exists() || rkey.DeleteSelf();
884
#endif // wxUSE_MIMETYPE