1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
12 // for compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
21 #include "wx/msw/mimetype.h"
24 #include "wx/dynarray.h"
25 #include "wx/string.h"
31 #include "wx/msgdlg.h"
36 #include "wx/iconloc.h"
37 #include "wx/confbase.h"
40 #include "wx/msw/registry.h"
41 #include "wx/msw/private.h"
44 // other standard headers
47 // in case we're compiling in non-GUI mode
48 class WXDLLIMPEXP_FWD_CORE wxIcon
;
50 // These classes use Windows registry to retrieve the required information.
52 // Keys used (not all of them are documented, so it might actually stop working
53 // in future versions of Windows...):
54 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
55 // types, each key has a string value "Extension" which gives (dot preceded)
56 // extension for the files of this MIME type.
58 // 2. "HKCR\.ext" contains
59 // a) unnamed value containing the "filetype"
60 // b) value "Content Type" containing the MIME type
62 // 3. "HKCR\filetype" contains
63 // a) unnamed value containing the description
64 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
66 // c) shell\open\command and shell\open\print subkeys containing the commands
67 // to open/print the file (the positional parameters are introduced by %1,
68 // %2, ... in these strings, we change them to %s ourselves)
70 // although I don't know of any official documentation which mentions this
71 // location, uses it, so it isn't likely to change
72 static const wxChar
*MIME_DATABASE_KEY
= wxT("MIME\\Database\\Content Type\\");
74 // this function replaces Microsoft %1 with Unix-like %s
75 static bool CanonicalizeParams(wxString
& command
)
77 // transform it from '%1' to '%s' style format string (now also test for %L
78 // as apparently MS started using it as well for the same purpose)
80 // NB: we don't make any attempt to verify that the string is valid, i.e.
81 // doesn't contain %2, or second %1 or .... But we do make sure that we
82 // return a string with _exactly_ one '%s'!
83 bool foundFilename
= false;
84 size_t len
= command
.length();
85 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ )
87 if ( command
[n
] == wxT('%') &&
89 (command
[n
+ 1] == wxT('1') || command
[n
+ 1] == wxT('L')) )
91 // replace it with '%s'
92 command
[n
+ 1] = wxT('s');
100 // Some values also contain an addition %* expansion string which is
101 // presumably supposed to be replaced with the names of the other files
102 // accepted by the command. As we don't support more than one file
103 // anyhow, simply ignore it.
104 command
.Replace(" %*", "");
107 return foundFilename
;
110 void wxFileTypeImpl::Init(const wxString
& strFileType
, const wxString
& ext
)
112 // VZ: does it? (FIXME)
113 wxCHECK_RET( !ext
.empty(), wxT("needs an extension") );
115 if ( ext
[0u] != wxT('.') ) {
120 m_strFileType
= strFileType
;
121 if ( !strFileType
) {
122 m_strFileType
= m_ext
.AfterFirst('.') + wxT("_auto_file");
126 wxString
wxFileTypeImpl::GetVerbPath(const wxString
& verb
) const
129 path
<< m_strFileType
<< wxT("\\shell\\") << verb
<< wxT("\\command");
133 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
134 wxArrayString
*commands
,
135 const wxFileType::MessageParameters
& params
) const
137 wxCHECK_MSG( !m_ext
.empty(), 0, wxT("GetAllCommands() needs an extension") );
139 if ( m_strFileType
.empty() )
141 // get it from the registry
142 wxFileTypeImpl
*self
= wxConstCast(this, wxFileTypeImpl
);
143 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
144 if ( !rkey
.Exists() || !rkey
.QueryValue(wxEmptyString
, self
->m_strFileType
) )
146 wxLogDebug(wxT("Can't get the filetype for extension '%s'."),
153 // enum all subkeys of HKCR\filetype\shell
155 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ wxT("\\shell"));
158 bool ok
= rkey
.GetFirstKey(verb
, dummy
);
161 wxString command
= wxFileType::ExpandCommand(GetCommand(verb
), params
);
163 // we want the open bverb to eb always the first
165 if ( verb
.CmpNoCase(wxT("open")) == 0 )
168 verbs
->Insert(verb
, 0);
170 commands
->Insert(command
, 0);
172 else // anything else than "open"
177 commands
->Add(command
);
182 ok
= rkey
.GetNextKey(verb
, dummy
);
188 // ----------------------------------------------------------------------------
189 // modify the registry database
190 // ----------------------------------------------------------------------------
192 bool wxFileTypeImpl::EnsureExtKeyExists()
194 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
195 if ( !rkey
.Exists() )
197 if ( !rkey
.Create() || !rkey
.SetValue(wxEmptyString
, m_strFileType
) )
199 wxLogError(_("Failed to create registry entry for '%s' files."),
208 // ----------------------------------------------------------------------------
209 // get the command to use
210 // ----------------------------------------------------------------------------
212 static wxString
wxFileTypeImplGetCurVer(const wxString
& progId
)
214 wxRegKey
key(wxRegKey::HKCR
, progId
+ wxT("\\CurVer"));
218 if (key
.QueryValue(wxEmptyString
, value
))
224 wxString
wxFileTypeImpl::GetCommand(const wxString
& verb
) const
226 // suppress possible error messages
230 // Since Windows Vista the association used by Explorer is different from
231 // the association information stored in the traditional part of the
232 // registry. Unfortunately the new schema doesn't seem to be documented
233 // anywhere so using it involves a bit of guesswork:
235 // The information is stored under Explorer-specific key whose path is
236 // below. The interesting part is UserChoice subkey which is the only one
237 // we use so far but there is also OpenWithProgids subkey which can exist
238 // even if UserChoice doesn't. However in practice there doesn't seem to be
239 // any cases when OpenWithProgids values for the given extension are
240 // different from those found directly under HKCR\.ext, so for now we don't
241 // bother to use this, apparently the programs registering their file type
242 // associations do it in both places. We do use UserChoice because when the
243 // association is manually changed by the user it's only recorded there and
244 // so must override whatever value was created under HKCR by the setup
251 wxT("Software\\Microsoft\\Windows\\CurrentVersion\\")
252 wxT("Explorer\\FileExts\\") +
256 if ( explorerKey
.Open(wxRegKey::Read
) &&
257 explorerKey
.QueryValue(wxT("Progid"), strKey
) )
259 strKey
= wxFileTypeImplGetCurVer(strKey
);
263 if (!strKey
&& wxRegKey(wxRegKey::HKCR
, m_ext
+ wxT("\\shell")).Exists())
266 if ( !strKey
&& !m_strFileType
.empty())
268 wxString fileType
= wxFileTypeImplGetCurVer(m_strFileType
);
269 if (wxRegKey(wxRegKey::HKCR
, fileType
+ wxT("\\shell")).Exists())
276 return wxEmptyString
;
279 strKey
<< wxT("\\shell\\") << verb
;
280 wxRegKey
key(wxRegKey::HKCR
, strKey
+ wxT("\\command"));
282 if ( key
.Open(wxRegKey::Read
) ) {
283 // it's the default value of the key
284 if ( key
.QueryValue(wxEmptyString
, command
) ) {
285 bool foundFilename
= CanonicalizeParams(command
);
288 // look whether we must issue some DDE requests to the application
289 // (and not just launch it)
290 strKey
+= wxT("\\DDEExec");
291 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
292 if ( keyDDE
.Open(wxRegKey::Read
) ) {
293 wxString ddeCommand
, ddeServer
, ddeTopic
;
294 keyDDE
.QueryValue(wxEmptyString
, ddeCommand
);
295 ddeCommand
.Replace(wxT("%1"), wxT("%s"));
297 wxRegKey
keyServer(wxRegKey::HKCR
, strKey
+ wxT("\\Application"));
298 keyServer
.QueryValue(wxEmptyString
, ddeServer
);
299 wxRegKey
keyTopic(wxRegKey::HKCR
, strKey
+ wxT("\\Topic"));
300 keyTopic
.QueryValue(wxEmptyString
, ddeTopic
);
302 if (ddeTopic
.empty())
303 ddeTopic
= wxT("System");
305 // HACK: we use a special feature of wxExecute which exists
306 // just because we need it here: it will establish DDE
307 // conversation with the program it just launched
308 command
.Prepend(wxT("WX_DDE#"));
309 command
<< wxT('#') << ddeServer
310 << wxT('#') << ddeTopic
311 << wxT('#') << ddeCommand
;
315 if ( !foundFilename
)
317 // we didn't find any '%1' - the application doesn't know which
318 // file to open (note that we only do it if there is no DDEExec
321 // HACK: append the filename at the end, hope that it will do
322 command
<< wxT(" %s");
326 //else: no such file type or no value, will return empty string
332 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
333 const wxFileType::MessageParameters
& params
)
336 wxString cmd
= GetCommand(wxT("open"));
338 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
340 return !openCmd
->empty();
344 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
345 const wxFileType::MessageParameters
& params
)
348 wxString cmd
= GetCommand(wxT("print"));
350 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
352 return !printCmd
->empty();
355 // ----------------------------------------------------------------------------
356 // getting other stuff
357 // ----------------------------------------------------------------------------
359 // TODO this function is half implemented
360 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
362 if ( m_ext
.empty() ) {
363 // the only way to get the list of extensions from the file type is to
364 // scan through all extensions in the registry - too slow...
369 extensions
.Add(m_ext
);
371 // it's a lie too, we don't return _all_ extensions...
376 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
378 // suppress possible error messages
380 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
382 return key
.Open(wxRegKey::Read
) &&
383 key
.QueryValue(wxT("Content Type"), *mimeType
);
386 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
390 if ( !GetMimeType(&s
) )
401 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
404 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
406 // suppress possible error messages
408 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
410 if ( key
.Open(wxRegKey::Read
) ) {
412 // it's the default value of the key
413 if ( key
.QueryValue(wxEmptyString
, strIcon
) ) {
414 // the format is the following: <full path to file>, <icon index>
415 // NB: icon index may be negative as well as positive and the full
416 // path may contain the environment variables inside '%'
417 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
418 strIndex
= strIcon
.AfterLast(wxT(','));
420 // index may be omitted, in which case BeforeLast(',') is empty and
421 // AfterLast(',') is the whole string
422 if ( strFullPath
.empty() ) {
423 strFullPath
= strIndex
;
429 iconLoc
->SetFileName(wxExpandEnvVars(strFullPath
));
431 iconLoc
->SetIndex(wxAtoi(strIndex
));
438 // no such file type or no value or incorrect icon entry
442 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
444 // suppress possible error messages
446 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
448 if ( key
.Open(wxRegKey::Read
) ) {
449 // it's the default value of the key
450 if ( key
.QueryValue(wxEmptyString
, *desc
) ) {
460 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
462 wxFileType
*fileType
= new wxFileType
;
463 fileType
->m_impl
->Init(filetype
, ext
);
467 // extension -> file type
469 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
471 // add the leading point if necessary
473 if ( ext
[0u] != wxT('.') ) {
478 // suppress possible error messages
481 bool knownExtension
= false;
483 wxString strFileType
;
484 wxRegKey
key(wxRegKey::HKCR
, str
);
485 if ( key
.Open(wxRegKey::Read
) ) {
486 // it's the default value of the key
487 if ( key
.QueryValue(wxEmptyString
, strFileType
) ) {
488 // create the new wxFileType object
489 return CreateFileType(strFileType
, ext
);
492 // this extension doesn't have a filetype, but it's known to the
493 // system and may be has some other useful keys (open command or
494 // content-type), so still return a file type object for it
495 knownExtension
= true;
499 if ( !knownExtension
)
505 return CreateFileType(wxEmptyString
, ext
);
510 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
512 wxFileType *fileType = GetFileTypeFromExtension(ext);
515 fileType = CreateFileType(wxEmptyString, ext);
522 // MIME type -> extension -> file type
524 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
526 wxString strKey
= MIME_DATABASE_KEY
;
529 // suppress possible error messages
533 wxRegKey
key(wxRegKey::HKCR
, strKey
);
534 if ( key
.Open(wxRegKey::Read
) ) {
535 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
536 return GetFileTypeFromExtension(ext
);
544 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
546 // enumerate all keys under MIME_DATABASE_KEY
547 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
551 bool cont
= key
.GetFirstKey(type
, cookie
);
556 cont
= key
.GetNextKey(type
, cookie
);
559 return mimetypes
.GetCount();
562 // ----------------------------------------------------------------------------
563 // create a new association
564 // ----------------------------------------------------------------------------
566 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
568 wxCHECK_MSG( !ftInfo
.GetExtensions().empty(), NULL
,
569 wxT("Associate() needs extension") );
572 size_t iExtCount
= 0;
576 wxString ext
= ftInfo
.GetExtensions()[iExtCount
];
578 wxCHECK_MSG( !ext
.empty(), NULL
,
579 wxT("Associate() needs non empty extension") );
581 if ( ext
[0u] != wxT('.') )
582 extWithDot
= wxT('.');
585 // start by setting the HKCR\\.ext entries
586 // default is filetype; content type is mimetype
587 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
589 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
592 // create the mapping from the extension to the filetype
597 if ( filetypeOrig
.empty() )
599 // make it up from the extension
600 filetype
<< extWithDot
.c_str() + 1 << wxT("_file");
604 // just use the provided one
605 filetype
= filetypeOrig
;
608 key
.SetValue(wxEmptyString
, filetype
);
613 // key already exists, maybe we want to change it ??
614 if (!filetypeOrig
.empty())
616 filetype
= filetypeOrig
;
617 key
.SetValue(wxEmptyString
, filetype
);
621 key
.QueryValue(wxEmptyString
, filetype
);
625 // now set a mimetypeif we have it, but ignore it if none
626 const wxString
& mimetype
= ftInfo
.GetMimeType();
627 if ( !mimetype
.empty() )
630 ok
= key
.SetValue(wxT("Content Type"), mimetype
);
634 // create the MIME key
635 wxString strKey
= MIME_DATABASE_KEY
;
637 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
638 ok
= keyMIME
.Create();
642 // and provide a back link to the extension
643 keyMIME
.SetValue(wxT("Extension"), extWithDot
);
649 // now make other extensions have the same filetype
651 for (iExtCount
=1; iExtCount
< ftInfo
.GetExtensionsCount(); iExtCount
++ )
653 ext
= ftInfo
.GetExtensions()[iExtCount
];
654 if ( ext
[0u] != wxT('.') )
655 extWithDot
= wxT('.');
658 wxRegKey
key2(wxRegKey::HKCR
, extWithDot
);
659 if ( !key2
.Exists() )
661 key2
.SetValue(wxEmptyString
, filetype
);
663 // now set any mimetypes we may have, but ignore it if none
664 const wxString
& mimetype2
= ftInfo
.GetMimeType();
665 if ( !mimetype2
.empty() )
668 ok
= key2
.SetValue(wxT("Content Type"), mimetype2
);
672 // create the MIME key
673 wxString strKey
= MIME_DATABASE_KEY
;
675 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
676 ok
= keyMIME
.Create();
680 // and provide a back link to the extension
681 keyMIME
.SetValue(wxT("Extension"), extWithDot
);
686 } // end of for loop; all extensions now point to HKCR\.ext\Default
688 // create the filetype key itself (it will be empty for now, but
689 // SetCommand(), SetDefaultIcon() &c will use it later)
690 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
693 wxFileType
*ft
= CreateFileType(filetype
, extWithDot
);
697 if (! ftInfo
.GetOpenCommand ().empty() ) ft
->SetCommand (ftInfo
.GetOpenCommand (), wxT("open" ) );
698 if (! ftInfo
.GetPrintCommand().empty() ) ft
->SetCommand (ftInfo
.GetPrintCommand(), wxT("print" ) );
699 // chris: I don't like the ->m_impl-> here FIX this ??
700 if (! ftInfo
.GetDescription ().empty() ) ft
->m_impl
->SetDescription (ftInfo
.GetDescription ()) ;
701 if (! ftInfo
.GetIconFile().empty() ) ft
->SetDefaultIcon (ftInfo
.GetIconFile(), ftInfo
.GetIconIndex() );
708 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
709 const wxString
& verb
,
710 bool WXUNUSED(overwriteprompt
))
712 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
713 wxT("SetCommand() needs an extension and a verb") );
715 if ( !EnsureExtKeyExists() )
718 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
720 if ( rkey
.Exists() && overwriteprompt
)
724 rkey
.QueryValue(wxEmptyString
, old
);
728 _("Do you want to overwrite the command used to %s "
729 "files with extension \"%s\" ?\nCurrent value is \n%s, "
730 "\nNew value is \n%s %1"), // bug here FIX need %1 ??
735 _("Confirm registry update"),
736 wxYES_NO
| wxICON_QUESTION
746 // 1. translate '%s' to '%1' instead of always adding it
747 // 2. create DDEExec value if needed (undo GetCommand)
748 return rkey
.Create() && rkey
.SetValue(wxEmptyString
, cmd
+ wxT(" \"%1\"") );
752 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
754 wxCHECK_MSG( !m_ext.empty(), false, wxT("SetMimeType() needs extension") );
756 if ( !EnsureExtKeyExists() )
759 // VZ: is this really useful? (FIXME)
763 // make up a default value for it
765 wxFileName::SplitPath(GetCommand(wxT("open")), NULL, &cmd, NULL);
766 mimeType << wxT("application/x-") << cmd;
770 mimeType = mimeTypeOrig;
773 wxRegKey rkey(wxRegKey::HKCR, m_ext);
774 return rkey.Create() && rkey.SetValue(wxT("Content Type"), mimeType);
778 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
780 wxCHECK_MSG( !m_ext
.empty(), false, wxT("SetDefaultIcon() needs extension") );
781 wxCHECK_MSG( !m_strFileType
.empty(), false, wxT("File key not found") );
782 // the next line fails on a SMBshare, I think because it is case mangled
783 // wxCHECK_MSG( !wxFileExists(cmd), false, wxT("Icon file not found.") );
785 if ( !EnsureExtKeyExists() )
788 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ wxT("\\DefaultIcon"));
790 return rkey
.Create() &&
791 rkey
.SetValue(wxEmptyString
,
792 wxString::Format(wxT("%s,%d"), cmd
.c_str(), index
));
795 bool wxFileTypeImpl::SetDescription (const wxString
& desc
)
797 wxCHECK_MSG( !m_strFileType
.empty(), false, wxT("File key not found") );
798 wxCHECK_MSG( !desc
.empty(), false, wxT("No file description supplied") );
800 if ( !EnsureExtKeyExists() )
803 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
);
805 return rkey
.Create() &&
806 rkey
.SetValue(wxEmptyString
, desc
);
809 // ----------------------------------------------------------------------------
810 // remove file association
811 // ----------------------------------------------------------------------------
813 bool wxFileTypeImpl::Unassociate()
816 if ( !RemoveOpenCommand() )
818 if ( !RemoveDefaultIcon() )
820 if ( !RemoveMimeType() )
822 if ( !RemoveDescription() )
826 //this might hold other keys, eg some have CSLID keys
829 // delete the root key
830 wxRegKey key(wxRegKey::HKCR, m_ext);
832 result = key.DeleteSelf();
838 bool wxFileTypeImpl::RemoveOpenCommand()
840 return RemoveCommand(wxT("open"));
843 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
845 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
846 wxT("RemoveCommand() needs an extension and a verb") );
848 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
850 // if the key already doesn't exist, it's a success
851 return !rkey
.Exists() || rkey
.DeleteSelf();
854 bool wxFileTypeImpl::RemoveMimeType()
856 wxCHECK_MSG( !m_ext
.empty(), false, wxT("RemoveMimeType() needs extension") );
858 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
859 return !rkey
.Exists() || rkey
.DeleteSelf();
862 bool wxFileTypeImpl::RemoveDefaultIcon()
864 wxCHECK_MSG( !m_ext
.empty(), false,
865 wxT("RemoveDefaultIcon() needs extension") );
867 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ wxT("\\DefaultIcon"));
868 return !rkey
.Exists() || rkey
.DeleteSelf();
871 bool wxFileTypeImpl::RemoveDescription()
873 wxCHECK_MSG( !m_ext
.empty(), false,
874 wxT("RemoveDescription() needs extension") );
876 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
);
877 return !rkey
.Exists() || rkey
.DeleteSelf();
880 #endif // wxUSE_MIMETYPE