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
);
294 ddeCommand
.Replace(wxT("%1"), wxT("%s"));
296 wxRegKey
keyServer(wxRegKey::HKCR
, strKey
+ wxT("\\Application"));
297 keyServer
.QueryValue(wxEmptyString
, ddeServer
);
298 wxRegKey
keyTopic(wxRegKey::HKCR
, strKey
+ wxT("\\Topic"));
299 keyTopic
.QueryValue(wxEmptyString
, ddeTopic
);
301 if (ddeTopic
.empty())
302 ddeTopic
= wxT("System");
304 // HACK: we use a special feature of wxExecute which exists
305 // just because we need it here: it will establish DDE
306 // conversation with the program it just launched
307 command
.Prepend(wxT("WX_DDE#"));
308 command
<< wxT('#') << ddeServer
309 << wxT('#') << ddeTopic
310 << wxT('#') << ddeCommand
;
314 if ( !foundFilename
)
316 // we didn't find any '%1' - the application doesn't know which
317 // file to open (note that we only do it if there is no DDEExec
320 // HACK: append the filename at the end, hope that it will do
321 command
<< wxT(" %s");
325 //else: no such file type or no value, will return empty string
331 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
332 const wxFileType::MessageParameters
& params
)
335 wxString cmd
= GetCommand(wxT("open"));
337 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
339 return !openCmd
->empty();
343 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
344 const wxFileType::MessageParameters
& params
)
347 wxString cmd
= GetCommand(wxT("print"));
349 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
351 return !printCmd
->empty();
354 // ----------------------------------------------------------------------------
355 // getting other stuff
356 // ----------------------------------------------------------------------------
358 // TODO this function is half implemented
359 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
361 if ( m_ext
.empty() ) {
362 // the only way to get the list of extensions from the file type is to
363 // scan through all extensions in the registry - too slow...
368 extensions
.Add(m_ext
);
370 // it's a lie too, we don't return _all_ extensions...
375 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
377 // suppress possible error messages
379 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
381 return key
.Open(wxRegKey::Read
) &&
382 key
.QueryValue(wxT("Content Type"), *mimeType
);
385 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
389 if ( !GetMimeType(&s
) )
400 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
403 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
405 // suppress possible error messages
407 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
409 if ( key
.Open(wxRegKey::Read
) ) {
411 // it's the default value of the key
412 if ( key
.QueryValue(wxEmptyString
, strIcon
) ) {
413 // the format is the following: <full path to file>, <icon index>
414 // NB: icon index may be negative as well as positive and the full
415 // path may contain the environment variables inside '%'
416 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
417 strIndex
= strIcon
.AfterLast(wxT(','));
419 // index may be omitted, in which case BeforeLast(',') is empty and
420 // AfterLast(',') is the whole string
421 if ( strFullPath
.empty() ) {
422 strFullPath
= strIndex
;
428 iconLoc
->SetFileName(wxExpandEnvVars(strFullPath
));
430 iconLoc
->SetIndex(wxAtoi(strIndex
));
437 // no such file type or no value or incorrect icon entry
441 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
443 // suppress possible error messages
445 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
447 if ( key
.Open(wxRegKey::Read
) ) {
448 // it's the default value of the key
449 if ( key
.QueryValue(wxEmptyString
, *desc
) ) {
459 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
461 wxFileType
*fileType
= new wxFileType
;
462 fileType
->m_impl
->Init(filetype
, ext
);
466 // extension -> file type
468 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
470 // add the leading point if necessary
472 if ( ext
[0u] != wxT('.') ) {
477 // suppress possible error messages
480 bool knownExtension
= false;
482 wxString strFileType
;
483 wxRegKey
key(wxRegKey::HKCR
, str
);
484 if ( key
.Open(wxRegKey::Read
) ) {
485 // it's the default value of the key
486 if ( key
.QueryValue(wxEmptyString
, strFileType
) ) {
487 // create the new wxFileType object
488 return CreateFileType(strFileType
, ext
);
491 // this extension doesn't have a filetype, but it's known to the
492 // system and may be has some other useful keys (open command or
493 // content-type), so still return a file type object for it
494 knownExtension
= true;
498 if ( !knownExtension
)
504 return CreateFileType(wxEmptyString
, ext
);
509 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
511 wxFileType *fileType = GetFileTypeFromExtension(ext);
514 fileType = CreateFileType(wxEmptyString, ext);
521 // MIME type -> extension -> file type
523 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
525 wxString strKey
= MIME_DATABASE_KEY
;
528 // suppress possible error messages
532 wxRegKey
key(wxRegKey::HKCR
, strKey
);
533 if ( key
.Open(wxRegKey::Read
) ) {
534 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
535 return GetFileTypeFromExtension(ext
);
543 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
545 // enumerate all keys under MIME_DATABASE_KEY
546 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
550 bool cont
= key
.GetFirstKey(type
, cookie
);
555 cont
= key
.GetNextKey(type
, cookie
);
558 return mimetypes
.GetCount();
561 // ----------------------------------------------------------------------------
562 // create a new association
563 // ----------------------------------------------------------------------------
565 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
567 wxCHECK_MSG( !ftInfo
.GetExtensions().empty(), NULL
,
568 wxT("Associate() needs extension") );
571 size_t iExtCount
= 0;
575 wxString ext
= ftInfo
.GetExtensions()[iExtCount
];
577 wxCHECK_MSG( !ext
.empty(), NULL
,
578 wxT("Associate() needs non empty extension") );
580 if ( ext
[0u] != wxT('.') )
581 extWithDot
= wxT('.');
584 // start by setting the HKCR\\.ext entries
585 // default is filetype; content type is mimetype
586 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
588 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
591 // create the mapping from the extension to the filetype
596 if ( filetypeOrig
.empty() )
598 // make it up from the extension
599 filetype
<< extWithDot
.c_str() + 1 << wxT("_file");
603 // just use the provided one
604 filetype
= filetypeOrig
;
607 key
.SetValue(wxEmptyString
, filetype
);
612 // key already exists, maybe we want to change it ??
613 if (!filetypeOrig
.empty())
615 filetype
= filetypeOrig
;
616 key
.SetValue(wxEmptyString
, filetype
);
620 key
.QueryValue(wxEmptyString
, filetype
);
624 // now set a mimetypeif we have it, but ignore it if none
625 const wxString
& mimetype
= ftInfo
.GetMimeType();
626 if ( !mimetype
.empty() )
629 ok
= key
.SetValue(wxT("Content Type"), mimetype
);
633 // create the MIME key
634 wxString strKey
= MIME_DATABASE_KEY
;
636 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
637 ok
= keyMIME
.Create();
641 // and provide a back link to the extension
642 keyMIME
.SetValue(wxT("Extension"), extWithDot
);
648 // now make other extensions have the same filetype
650 for (iExtCount
=1; iExtCount
< ftInfo
.GetExtensionsCount(); iExtCount
++ )
652 ext
= ftInfo
.GetExtensions()[iExtCount
];
653 if ( ext
[0u] != wxT('.') )
654 extWithDot
= wxT('.');
657 wxRegKey
key2(wxRegKey::HKCR
, extWithDot
);
658 if ( !key2
.Exists() )
660 key2
.SetValue(wxEmptyString
, filetype
);
662 // now set any mimetypes we may have, but ignore it if none
663 const wxString
& mimetype2
= ftInfo
.GetMimeType();
664 if ( !mimetype2
.empty() )
667 ok
= key2
.SetValue(wxT("Content Type"), mimetype2
);
671 // create the MIME key
672 wxString strKey
= MIME_DATABASE_KEY
;
674 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
675 ok
= keyMIME
.Create();
679 // and provide a back link to the extension
680 keyMIME
.SetValue(wxT("Extension"), extWithDot
);
685 } // end of for loop; all extensions now point to HKCR\.ext\Default
687 // create the filetype key itself (it will be empty for now, but
688 // SetCommand(), SetDefaultIcon() &c will use it later)
689 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
692 wxFileType
*ft
= CreateFileType(filetype
, extWithDot
);
696 if (! ftInfo
.GetOpenCommand ().empty() ) ft
->SetCommand (ftInfo
.GetOpenCommand (), wxT("open" ) );
697 if (! ftInfo
.GetPrintCommand().empty() ) ft
->SetCommand (ftInfo
.GetPrintCommand(), wxT("print" ) );
698 // chris: I don't like the ->m_impl-> here FIX this ??
699 if (! ftInfo
.GetDescription ().empty() ) ft
->m_impl
->SetDescription (ftInfo
.GetDescription ()) ;
700 if (! ftInfo
.GetIconFile().empty() ) ft
->SetDefaultIcon (ftInfo
.GetIconFile(), ftInfo
.GetIconIndex() );
707 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
708 const wxString
& verb
,
709 bool WXUNUSED(overwriteprompt
))
711 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
712 wxT("SetCommand() needs an extension and a verb") );
714 if ( !EnsureExtKeyExists() )
717 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
719 if ( rkey
.Exists() && overwriteprompt
)
723 rkey
.QueryValue(wxEmptyString
, old
);
727 _("Do you want to overwrite the command used to %s "
728 "files with extension \"%s\" ?\nCurrent value is \n%s, "
729 "\nNew value is \n%s %1"), // bug here FIX need %1 ??
734 _("Confirm registry update"),
735 wxYES_NO
| wxICON_QUESTION
745 // 1. translate '%s' to '%1' instead of always adding it
746 // 2. create DDEExec value if needed (undo GetCommand)
747 return rkey
.Create() && rkey
.SetValue(wxEmptyString
, cmd
+ wxT(" \"%1\"") );
751 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
753 wxCHECK_MSG( !m_ext.empty(), false, wxT("SetMimeType() needs extension") );
755 if ( !EnsureExtKeyExists() )
758 // VZ: is this really useful? (FIXME)
762 // make up a default value for it
764 wxFileName::SplitPath(GetCommand(wxT("open")), NULL, &cmd, NULL);
765 mimeType << wxT("application/x-") << cmd;
769 mimeType = mimeTypeOrig;
772 wxRegKey rkey(wxRegKey::HKCR, m_ext);
773 return rkey.Create() && rkey.SetValue(wxT("Content Type"), mimeType);
777 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
779 wxCHECK_MSG( !m_ext
.empty(), false, wxT("SetDefaultIcon() needs extension") );
780 wxCHECK_MSG( !m_strFileType
.empty(), false, wxT("File key not found") );
781 // the next line fails on a SMBshare, I think because it is case mangled
782 // wxCHECK_MSG( !wxFileExists(cmd), false, wxT("Icon file not found.") );
784 if ( !EnsureExtKeyExists() )
787 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ wxT("\\DefaultIcon"));
789 return rkey
.Create() &&
790 rkey
.SetValue(wxEmptyString
,
791 wxString::Format(wxT("%s,%d"), cmd
.c_str(), index
));
794 bool wxFileTypeImpl::SetDescription (const wxString
& desc
)
796 wxCHECK_MSG( !m_strFileType
.empty(), false, wxT("File key not found") );
797 wxCHECK_MSG( !desc
.empty(), false, wxT("No file description supplied") );
799 if ( !EnsureExtKeyExists() )
802 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
);
804 return rkey
.Create() &&
805 rkey
.SetValue(wxEmptyString
, desc
);
808 // ----------------------------------------------------------------------------
809 // remove file association
810 // ----------------------------------------------------------------------------
812 bool wxFileTypeImpl::Unassociate()
815 if ( !RemoveOpenCommand() )
817 if ( !RemoveDefaultIcon() )
819 if ( !RemoveMimeType() )
821 if ( !RemoveDescription() )
825 //this might hold other keys, eg some have CSLID keys
828 // delete the root key
829 wxRegKey key(wxRegKey::HKCR, m_ext);
831 result = key.DeleteSelf();
837 bool wxFileTypeImpl::RemoveOpenCommand()
839 return RemoveCommand(wxT("open"));
842 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
844 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
845 wxT("RemoveCommand() needs an extension and a verb") );
847 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
849 // if the key already doesn't exist, it's a success
850 return !rkey
.Exists() || rkey
.DeleteSelf();
853 bool wxFileTypeImpl::RemoveMimeType()
855 wxCHECK_MSG( !m_ext
.empty(), false, wxT("RemoveMimeType() needs extension") );
857 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
858 return !rkey
.Exists() || rkey
.DeleteSelf();
861 bool wxFileTypeImpl::RemoveDefaultIcon()
863 wxCHECK_MSG( !m_ext
.empty(), false,
864 wxT("RemoveDefaultIcon() needs extension") );
866 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ wxT("\\DefaultIcon"));
867 return !rkey
.Exists() || rkey
.DeleteSelf();
870 bool wxFileTypeImpl::RemoveDescription()
872 wxCHECK_MSG( !m_ext
.empty(), false,
873 wxT("RemoveDescription() needs extension") );
875 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
);
876 return !rkey
.Exists() || rkey
.DeleteSelf();
879 #endif // wxUSE_MIMETYPE