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
231 wxRegKey
explorerKey(wxRegKey::HKCU
, wxT("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\") + m_ext
);
232 if (explorerKey
.Exists())
234 if (explorerKey
.Open(wxRegKey::Read
))
236 if (explorerKey
.QueryValue(wxT("Progid"), strKey
))
238 strKey
= wxFileTypeImplGetCurVer(strKey
);
244 if (!strKey
&& wxRegKey(wxRegKey::HKCR
, m_ext
+ wxT("\\shell")).Exists())
247 if ( !strKey
&& !m_strFileType
.empty())
249 wxString fileType
= wxFileTypeImplGetCurVer(m_strFileType
);
250 if (wxRegKey(wxRegKey::HKCR
, fileType
+ wxT("\\shell")).Exists())
257 return wxEmptyString
;
260 strKey
<< wxT("\\shell\\") << verb
;
261 wxRegKey
key(wxRegKey::HKCR
, strKey
+ wxT("\\command"));
263 if ( key
.Open(wxRegKey::Read
) ) {
264 // it's the default value of the key
265 if ( key
.QueryValue(wxEmptyString
, command
) ) {
266 bool foundFilename
= CanonicalizeParams(command
);
269 // look whether we must issue some DDE requests to the application
270 // (and not just launch it)
271 strKey
+= wxT("\\DDEExec");
272 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
273 if ( keyDDE
.Open(wxRegKey::Read
) ) {
274 wxString ddeCommand
, ddeServer
, ddeTopic
;
275 keyDDE
.QueryValue(wxEmptyString
, ddeCommand
);
276 ddeCommand
.Replace(wxT("%1"), wxT("%s"));
278 wxRegKey
keyServer(wxRegKey::HKCR
, strKey
+ wxT("\\Application"));
279 keyServer
.QueryValue(wxEmptyString
, ddeServer
);
280 wxRegKey
keyTopic(wxRegKey::HKCR
, strKey
+ wxT("\\Topic"));
281 keyTopic
.QueryValue(wxEmptyString
, ddeTopic
);
283 if (ddeTopic
.empty())
284 ddeTopic
= wxT("System");
286 // HACK: we use a special feature of wxExecute which exists
287 // just because we need it here: it will establish DDE
288 // conversation with the program it just launched
289 command
.Prepend(wxT("WX_DDE#"));
290 command
<< wxT('#') << ddeServer
291 << wxT('#') << ddeTopic
292 << wxT('#') << ddeCommand
;
296 if ( !foundFilename
)
298 // we didn't find any '%1' - the application doesn't know which
299 // file to open (note that we only do it if there is no DDEExec
302 // HACK: append the filename at the end, hope that it will do
303 command
<< wxT(" %s");
307 //else: no such file type or no value, will return empty string
313 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
314 const wxFileType::MessageParameters
& params
)
317 wxString cmd
= GetCommand(wxT("open"));
319 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
321 return !openCmd
->empty();
325 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
326 const wxFileType::MessageParameters
& params
)
329 wxString cmd
= GetCommand(wxT("print"));
331 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
333 return !printCmd
->empty();
336 // ----------------------------------------------------------------------------
337 // getting other stuff
338 // ----------------------------------------------------------------------------
340 // TODO this function is half implemented
341 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
343 if ( m_ext
.empty() ) {
344 // the only way to get the list of extensions from the file type is to
345 // scan through all extensions in the registry - too slow...
350 extensions
.Add(m_ext
);
352 // it's a lie too, we don't return _all_ extensions...
357 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
359 // suppress possible error messages
361 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
363 return key
.Open(wxRegKey::Read
) &&
364 key
.QueryValue(wxT("Content Type"), *mimeType
);
367 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
371 if ( !GetMimeType(&s
) )
382 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
385 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
387 // suppress possible error messages
389 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
391 if ( key
.Open(wxRegKey::Read
) ) {
393 // it's the default value of the key
394 if ( key
.QueryValue(wxEmptyString
, strIcon
) ) {
395 // the format is the following: <full path to file>, <icon index>
396 // NB: icon index may be negative as well as positive and the full
397 // path may contain the environment variables inside '%'
398 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
399 strIndex
= strIcon
.AfterLast(wxT(','));
401 // index may be omitted, in which case BeforeLast(',') is empty and
402 // AfterLast(',') is the whole string
403 if ( strFullPath
.empty() ) {
404 strFullPath
= strIndex
;
410 iconLoc
->SetFileName(wxExpandEnvVars(strFullPath
));
412 iconLoc
->SetIndex(wxAtoi(strIndex
));
419 // no such file type or no value or incorrect icon entry
423 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
425 // suppress possible error messages
427 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
429 if ( key
.Open(wxRegKey::Read
) ) {
430 // it's the default value of the key
431 if ( key
.QueryValue(wxEmptyString
, *desc
) ) {
441 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
443 wxFileType
*fileType
= new wxFileType
;
444 fileType
->m_impl
->Init(filetype
, ext
);
448 // extension -> file type
450 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
452 // add the leading point if necessary
454 if ( ext
[0u] != wxT('.') ) {
459 // suppress possible error messages
462 bool knownExtension
= false;
464 wxString strFileType
;
465 wxRegKey
key(wxRegKey::HKCR
, str
);
466 if ( key
.Open(wxRegKey::Read
) ) {
467 // it's the default value of the key
468 if ( key
.QueryValue(wxEmptyString
, strFileType
) ) {
469 // create the new wxFileType object
470 return CreateFileType(strFileType
, ext
);
473 // this extension doesn't have a filetype, but it's known to the
474 // system and may be has some other useful keys (open command or
475 // content-type), so still return a file type object for it
476 knownExtension
= true;
480 if ( !knownExtension
)
486 return CreateFileType(wxEmptyString
, ext
);
491 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
493 wxFileType *fileType = GetFileTypeFromExtension(ext);
496 fileType = CreateFileType(wxEmptyString, ext);
503 // MIME type -> extension -> file type
505 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
507 wxString strKey
= MIME_DATABASE_KEY
;
510 // suppress possible error messages
514 wxRegKey
key(wxRegKey::HKCR
, strKey
);
515 if ( key
.Open(wxRegKey::Read
) ) {
516 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
517 return GetFileTypeFromExtension(ext
);
525 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
527 // enumerate all keys under MIME_DATABASE_KEY
528 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
532 bool cont
= key
.GetFirstKey(type
, cookie
);
537 cont
= key
.GetNextKey(type
, cookie
);
540 return mimetypes
.GetCount();
543 // ----------------------------------------------------------------------------
544 // create a new association
545 // ----------------------------------------------------------------------------
547 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
549 wxCHECK_MSG( !ftInfo
.GetExtensions().empty(), NULL
,
550 wxT("Associate() needs extension") );
553 size_t iExtCount
= 0;
557 wxString ext
= ftInfo
.GetExtensions()[iExtCount
];
559 wxCHECK_MSG( !ext
.empty(), NULL
,
560 wxT("Associate() needs non empty extension") );
562 if ( ext
[0u] != wxT('.') )
563 extWithDot
= wxT('.');
566 // start by setting the HKCR\\.ext entries
567 // default is filetype; content type is mimetype
568 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
570 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
573 // create the mapping from the extension to the filetype
578 if ( filetypeOrig
.empty() )
580 // make it up from the extension
581 filetype
<< extWithDot
.c_str() + 1 << wxT("_file");
585 // just use the provided one
586 filetype
= filetypeOrig
;
589 key
.SetValue(wxEmptyString
, filetype
);
594 // key already exists, maybe we want to change it ??
595 if (!filetypeOrig
.empty())
597 filetype
= filetypeOrig
;
598 key
.SetValue(wxEmptyString
, filetype
);
602 key
.QueryValue(wxEmptyString
, filetype
);
606 // now set a mimetypeif we have it, but ignore it if none
607 const wxString
& mimetype
= ftInfo
.GetMimeType();
608 if ( !mimetype
.empty() )
611 ok
= key
.SetValue(wxT("Content Type"), mimetype
);
615 // create the MIME key
616 wxString strKey
= MIME_DATABASE_KEY
;
618 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
619 ok
= keyMIME
.Create();
623 // and provide a back link to the extension
624 keyMIME
.SetValue(wxT("Extension"), extWithDot
);
630 // now make other extensions have the same filetype
632 for (iExtCount
=1; iExtCount
< ftInfo
.GetExtensionsCount(); iExtCount
++ )
634 ext
= ftInfo
.GetExtensions()[iExtCount
];
635 if ( ext
[0u] != wxT('.') )
636 extWithDot
= wxT('.');
639 wxRegKey
key2(wxRegKey::HKCR
, extWithDot
);
640 if ( !key2
.Exists() )
642 key2
.SetValue(wxEmptyString
, filetype
);
644 // now set any mimetypes we may have, but ignore it if none
645 const wxString
& mimetype2
= ftInfo
.GetMimeType();
646 if ( !mimetype2
.empty() )
649 ok
= key2
.SetValue(wxT("Content Type"), mimetype2
);
653 // create the MIME key
654 wxString strKey
= MIME_DATABASE_KEY
;
656 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
657 ok
= keyMIME
.Create();
661 // and provide a back link to the extension
662 keyMIME
.SetValue(wxT("Extension"), extWithDot
);
667 } // end of for loop; all extensions now point to HKCR\.ext\Default
669 // create the filetype key itself (it will be empty for now, but
670 // SetCommand(), SetDefaultIcon() &c will use it later)
671 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
674 wxFileType
*ft
= CreateFileType(filetype
, extWithDot
);
678 if (! ftInfo
.GetOpenCommand ().empty() ) ft
->SetCommand (ftInfo
.GetOpenCommand (), wxT("open" ) );
679 if (! ftInfo
.GetPrintCommand().empty() ) ft
->SetCommand (ftInfo
.GetPrintCommand(), wxT("print" ) );
680 // chris: I don't like the ->m_impl-> here FIX this ??
681 if (! ftInfo
.GetDescription ().empty() ) ft
->m_impl
->SetDescription (ftInfo
.GetDescription ()) ;
682 if (! ftInfo
.GetIconFile().empty() ) ft
->SetDefaultIcon (ftInfo
.GetIconFile(), ftInfo
.GetIconIndex() );
689 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
690 const wxString
& verb
,
691 bool WXUNUSED(overwriteprompt
))
693 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
694 wxT("SetCommand() needs an extension and a verb") );
696 if ( !EnsureExtKeyExists() )
699 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
701 if ( rkey
.Exists() && overwriteprompt
)
705 rkey
.QueryValue(wxEmptyString
, old
);
709 _("Do you want to overwrite the command used to %s "
710 "files with extension \"%s\" ?\nCurrent value is \n%s, "
711 "\nNew value is \n%s %1"), // bug here FIX need %1 ??
716 _("Confirm registry update"),
717 wxYES_NO
| wxICON_QUESTION
727 // 1. translate '%s' to '%1' instead of always adding it
728 // 2. create DDEExec value if needed (undo GetCommand)
729 return rkey
.Create() && rkey
.SetValue(wxEmptyString
, cmd
+ wxT(" \"%1\"") );
733 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
735 wxCHECK_MSG( !m_ext.empty(), false, wxT("SetMimeType() needs extension") );
737 if ( !EnsureExtKeyExists() )
740 // VZ: is this really useful? (FIXME)
744 // make up a default value for it
746 wxFileName::SplitPath(GetCommand(wxT("open")), NULL, &cmd, NULL);
747 mimeType << wxT("application/x-") << cmd;
751 mimeType = mimeTypeOrig;
754 wxRegKey rkey(wxRegKey::HKCR, m_ext);
755 return rkey.Create() && rkey.SetValue(wxT("Content Type"), mimeType);
759 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
761 wxCHECK_MSG( !m_ext
.empty(), false, wxT("SetDefaultIcon() needs extension") );
762 wxCHECK_MSG( !m_strFileType
.empty(), false, wxT("File key not found") );
763 // the next line fails on a SMBshare, I think because it is case mangled
764 // wxCHECK_MSG( !wxFileExists(cmd), false, wxT("Icon file not found.") );
766 if ( !EnsureExtKeyExists() )
769 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ wxT("\\DefaultIcon"));
771 return rkey
.Create() &&
772 rkey
.SetValue(wxEmptyString
,
773 wxString::Format(wxT("%s,%d"), cmd
.c_str(), index
));
776 bool wxFileTypeImpl::SetDescription (const wxString
& desc
)
778 wxCHECK_MSG( !m_strFileType
.empty(), false, wxT("File key not found") );
779 wxCHECK_MSG( !desc
.empty(), false, wxT("No file description supplied") );
781 if ( !EnsureExtKeyExists() )
784 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
);
786 return rkey
.Create() &&
787 rkey
.SetValue(wxEmptyString
, desc
);
790 // ----------------------------------------------------------------------------
791 // remove file association
792 // ----------------------------------------------------------------------------
794 bool wxFileTypeImpl::Unassociate()
797 if ( !RemoveOpenCommand() )
799 if ( !RemoveDefaultIcon() )
801 if ( !RemoveMimeType() )
803 if ( !RemoveDescription() )
807 //this might hold other keys, eg some have CSLID keys
810 // delete the root key
811 wxRegKey key(wxRegKey::HKCR, m_ext);
813 result = key.DeleteSelf();
819 bool wxFileTypeImpl::RemoveOpenCommand()
821 return RemoveCommand(wxT("open"));
824 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
826 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
827 wxT("RemoveCommand() needs an extension and a verb") );
829 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
831 // if the key already doesn't exist, it's a success
832 return !rkey
.Exists() || rkey
.DeleteSelf();
835 bool wxFileTypeImpl::RemoveMimeType()
837 wxCHECK_MSG( !m_ext
.empty(), false, wxT("RemoveMimeType() needs extension") );
839 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
840 return !rkey
.Exists() || rkey
.DeleteSelf();
843 bool wxFileTypeImpl::RemoveDefaultIcon()
845 wxCHECK_MSG( !m_ext
.empty(), false,
846 wxT("RemoveDefaultIcon() needs extension") );
848 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ wxT("\\DefaultIcon"));
849 return !rkey
.Exists() || rkey
.DeleteSelf();
852 bool wxFileTypeImpl::RemoveDescription()
854 wxCHECK_MSG( !m_ext
.empty(), false,
855 wxT("RemoveDescription() needs extension") );
857 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
);
858 return !rkey
.Exists() || rkey
.DeleteSelf();
861 #endif // wxUSE_MIMETYPE