]>
git.saurik.com Git - wxWidgets.git/blob - src/msw/mimetype.cpp
869c78dac052f09c971abee98972dc71223f527d
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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 license (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "mimetype.h"
16 // for compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
23 // this is Win32 only code
27 #include "wx/string.h"
30 #include "wx/msgdlg.h"
37 #include "wx/dynarray.h"
38 #include "wx/confbase.h"
41 #include "wx/msw/registry.h"
45 #include "wx/msw/mimetype.h"
47 // other standard headers
50 // in case we're compiling in non-GUI mode
51 class WXDLLEXPORT wxIcon
;
53 // These classes use Windows registry to retrieve the required information.
55 // Keys used (not all of them are documented, so it might actually stop working
56 // in future versions of Windows...):
57 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
58 // types, each key has a string value "Extension" which gives (dot preceded)
59 // extension for the files of this MIME type.
61 // 2. "HKCR\.ext" contains
62 // a) unnamed value containing the "filetype"
63 // b) value "Content Type" containing the MIME type
65 // 3. "HKCR\filetype" contains
66 // a) unnamed value containing the description
67 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
69 // c) shell\open\command and shell\open\print subkeys containing the commands
70 // to open/print the file (the positional parameters are introduced by %1,
71 // %2, ... in these strings, we change them to %s ourselves)
73 // although I don't know of any official documentation which mentions this
74 // location, uses it, so it isn't likely to change
75 static const wxChar
*MIME_DATABASE_KEY
= wxT("MIME\\Database\\Content Type\\");
77 void wxFileTypeImpl::Init(const wxString
& strFileType
, const wxString
& ext
)
79 // VZ: does it? (FIXME)
80 wxCHECK_RET( !ext
.IsEmpty(), _T("needs an extension") );
82 if ( ext
[0u] != wxT('.') ) {
87 m_strFileType
= strFileType
;
89 m_strFileType
= m_ext
.AfterFirst('.') + "_auto_file";
93 wxString
wxFileTypeImpl::GetVerbPath(const wxString
& verb
) const
96 path
<< m_strFileType
<< _T("\\shell\\") << verb
<< _T("\\command");
100 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
101 wxArrayString
*commands
,
102 const wxFileType::MessageParameters
& params
) const
104 wxCHECK_MSG( !m_ext
.IsEmpty(), 0, _T("GetAllCommands() needs an extension") );
106 if ( m_strFileType
.IsEmpty() )
108 // get it from the registry
109 wxFileTypeImpl
*self
= wxConstCast(this, wxFileTypeImpl
);
110 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
111 if ( !rkey
.Exists() || !rkey
.QueryValue(_T(""), self
->m_strFileType
) )
113 wxLogDebug(_T("Can't get the filetype for extension '%s'."),
120 // enum all subkeys of HKCR\filetype\shell
122 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell"));
125 bool ok
= rkey
.GetFirstKey(verb
, dummy
);
128 wxString command
= wxFileType::ExpandCommand(GetCommand(verb
), params
);
130 // we want the open bverb to eb always the first
132 if ( verb
.CmpNoCase(_T("open")) == 0 )
135 verbs
->Insert(verb
, 0);
137 commands
->Insert(command
, 0);
139 else // anything else than "open"
144 commands
->Add(command
);
149 ok
= rkey
.GetNextKey(verb
, dummy
);
155 // ----------------------------------------------------------------------------
156 // modify the registry database
157 // ----------------------------------------------------------------------------
159 bool wxFileTypeImpl::EnsureExtKeyExists()
161 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
162 if ( !rkey
.Exists() )
164 if ( !rkey
.Create() || !rkey
.SetValue(_T(""), m_strFileType
) )
166 wxLogError(_("Failed to create registry entry for '%s' files."),
175 // ----------------------------------------------------------------------------
176 // get the command to use
177 // ----------------------------------------------------------------------------
179 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
181 // suppress possible error messages
185 if ( wxRegKey(wxRegKey::HKCR
, m_ext
+ _T("\\shell")).Exists() )
187 if ( wxRegKey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell")).Exists() )
188 strKey
= m_strFileType
;
193 return wxEmptyString
;
196 strKey
<< wxT("\\shell\\") << verb
;
197 wxRegKey
key(wxRegKey::HKCR
, strKey
+ _T("\\command"));
200 // it's the default value of the key
201 if ( key
.QueryValue(wxT(""), command
) ) {
202 // transform it from '%1' to '%s' style format string (now also
203 // test for %L - apparently MS started using it as well for the
206 // NB: we don't make any attempt to verify that the string is valid,
207 // i.e. doesn't contain %2, or second %1 or .... But we do make
208 // sure that we return a string with _exactly_ one '%s'!
209 bool foundFilename
= FALSE
;
210 size_t len
= command
.Len();
211 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
212 if ( command
[n
] == wxT('%') &&
214 (command
[n
+ 1] == wxT('1') ||
215 command
[n
+ 1] == wxT('L')) ) {
216 // replace it with '%s'
217 command
[n
+ 1] = wxT('s');
219 foundFilename
= TRUE
;
224 // look whether we must issue some DDE requests to the application
225 // (and not just launch it)
226 strKey
+= _T("\\DDEExec");
227 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
228 if ( keyDDE
.Open() ) {
229 wxString ddeCommand
, ddeServer
, ddeTopic
;
230 keyDDE
.QueryValue(_T(""), ddeCommand
);
231 ddeCommand
.Replace(_T("%1"), _T("%s"));
233 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Application")).
234 QueryValue(_T(""), ddeServer
);
235 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Topic")).
236 QueryValue(_T(""), ddeTopic
);
238 // HACK: we use a special feature of wxExecute which exists
239 // just because we need it here: it will establish DDE
240 // conversation with the program it just launched
241 command
.Prepend(_T("WX_DDE#"));
242 command
<< _T('#') << ddeServer
243 << _T('#') << ddeTopic
244 << _T('#') << ddeCommand
;
248 if ( !foundFilename
) {
249 // we didn't find any '%1' - the application doesn't know which
250 // file to open (note that we only do it if there is no DDEExec
253 // HACK: append the filename at the end, hope that it will do
254 command
<< wxT(" %s");
258 //else: no such file type or no value, will return empty string
264 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
265 const wxFileType::MessageParameters
& params
)
268 wxString cmd
= GetCommand(wxT("open"));
270 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
272 return !openCmd
->IsEmpty();
276 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
277 const wxFileType::MessageParameters
& params
)
280 wxString cmd
= GetCommand(wxT("print"));
282 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
284 return !printCmd
->IsEmpty();
287 // ----------------------------------------------------------------------------
288 // getting other stuff
289 // ----------------------------------------------------------------------------
291 // TODO this function is half implemented
292 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
294 if ( m_ext
.IsEmpty() ) {
295 // the only way to get the list of extensions from the file type is to
296 // scan through all extensions in the registry - too slow...
301 extensions
.Add(m_ext
);
303 // it's a lie too, we don't return _all_ extensions...
308 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
310 // suppress possible error messages
312 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
314 return key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
);
317 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
321 if ( !GetMimeType(&s
) )
332 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
,
334 int *iconIndex
) const
338 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
340 // suppress possible error messages
342 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
346 // it's the default value of the key
347 if ( key
.QueryValue(wxT(""), strIcon
) ) {
348 // the format is the following: <full path to file>, <icon index>
349 // NB: icon index may be negative as well as positive and the full
350 // path may contain the environment variables inside '%'
351 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
352 strIndex
= strIcon
.AfterLast(wxT(','));
354 // index may be omitted, in which case BeforeLast(',') is empty and
355 // AfterLast(',') is the whole string
356 if ( strFullPath
.IsEmpty() ) {
357 strFullPath
= strIndex
;
361 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
362 // here we need C based counting!
363 int nIndex
= wxAtoi(strIndex
) - 1 ;
365 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
366 switch ( (int)hIcon
) {
367 case 0: // means no icons were found
368 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
369 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
370 key
.GetName().c_str());
374 icon
->SetHICON((WXHICON
)hIcon
);
378 *iconFile
= strFullPath
;
384 // no such file type or no value or incorrect icon entry
390 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
392 // suppress possible error messages
394 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
397 // it's the default value of the key
398 if ( key
.QueryValue(wxT(""), *desc
) ) {
408 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
410 wxFileType
*fileType
= new wxFileType
;
411 fileType
->m_impl
->Init(filetype
, ext
);
415 // extension -> file type
417 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
419 // add the leading point if necessary
421 if ( ext
[0u] != wxT('.') ) {
426 // suppress possible error messages
429 bool knownExtension
= FALSE
;
431 wxString strFileType
;
432 wxRegKey
key(wxRegKey::HKCR
, str
);
434 // it's the default value of the key
435 if ( key
.QueryValue(wxT(""), strFileType
) ) {
436 // create the new wxFileType object
437 return CreateFileType(strFileType
, ext
);
440 // this extension doesn't have a filetype, but it's known to the
441 // system and may be has some other useful keys (open command or
442 // content-type), so still return a file type object for it
443 knownExtension
= TRUE
;
447 if ( !knownExtension
)
453 return CreateFileType(wxEmptyString
, ext
);
457 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString
& ext
)
459 wxFileType
*fileType
= GetFileTypeFromExtension(ext
);
462 fileType
= CreateFileType(wxEmptyString
, ext
);
469 // MIME type -> extension -> file type
471 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
473 wxString strKey
= MIME_DATABASE_KEY
;
476 // suppress possible error messages
480 wxRegKey
key(wxRegKey::HKCR
, strKey
);
482 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
483 return GetFileTypeFromExtension(ext
);
491 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
493 // enumerate all keys under MIME_DATABASE_KEY
494 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
498 bool cont
= key
.GetFirstKey(type
, cookie
);
503 cont
= key
.GetNextKey(type
, cookie
);
506 return mimetypes
.GetCount();
509 // ----------------------------------------------------------------------------
510 // create a new association
511 // ----------------------------------------------------------------------------
513 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
515 wxCHECK_MSG( !ftInfo
.GetExtensions().IsEmpty(), NULL
,
516 _T("Associate() needs extension") );
518 const wxString
& ext
= ftInfo
.GetExtensions()[0u];
520 wxCHECK_MSG( !ext
.empty(), NULL
,
521 _T("Associate() needs non empty extension") );
524 if ( ext
[0u] != _T('.') )
525 extWithDot
= _T('.');
528 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
529 wxFileType
*ft
= NULL
;
534 // create the mapping from the extension to the filetype
535 bool ok
= key
.Create();
538 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
539 if ( filetypeOrig
.empty() )
541 // make it up from the extension
542 filetype
<< extWithDot
.c_str() + 1 << _T("_auto_file");
546 // just use the provided one
547 filetype
= filetypeOrig
;
550 ok
= key
.SetValue(_T(""), filetype
);
553 const wxString
& mimetype
= ftInfo
.GetMimeType();
554 if ( ok
&& !mimetype
.empty() )
557 ok
= key
.SetValue(_T("Content Type"), mimetype
);
561 // create the MIME key
562 wxString strKey
= MIME_DATABASE_KEY
;
564 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
565 ok
= keyMIME
.Create();
569 // and provide a back link to the extension
570 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
577 // create the filetype key itself (it will be empty for now, but
578 // SetCommand(), SetDefaultIcon() &c will use it later)
579 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
585 // ok, we've created everything correctly
586 ft
= CreateFileType(filetype
, extWithDot
);
590 // one of the registry operations failed
591 wxLogError(_("Failed to register extension '%s'."), ext
.c_str());
594 else // key already exists
596 // FIXME we probably should return an existing file type then?
602 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
603 const wxString
& verb
,
604 bool overwriteprompt
)
606 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
607 _T("SetCommand() needs an extension and a verb") );
609 if ( !EnsureExtKeyExists() )
612 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
614 if ( rkey
.Exists() && overwriteprompt
)
618 rkey
.QueryValue(wxT(""), old
);
622 _("Do you want to overwrite the command used to %s "
623 "files with extension \"%s\" (current value is '%s', "
624 "new value is '%s')?"),
629 _("Confirm registry update"),
630 wxYES_NO
| wxICON_QUESTION
640 // 1. translate '%s' to '%1' instead of always adding it
641 // 2. create DDEExec value if needed (undo GetCommand)
642 return rkey
.Create() && rkey
.SetValue(_T(""), cmd
+ _T(" \"%1\"") );
645 bool wxFileTypeImpl::SetMimeType(const wxString
& mimeTypeOrig
)
647 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetMimeType() needs extension") );
649 if ( !EnsureExtKeyExists() )
652 // VZ: is this really useful? (FIXME)
656 // make up a default value for it
658 wxSplitPath(GetCommand(_T("open")), NULL
, &cmd
, NULL
);
659 mimeType
<< _T("application/x-") << cmd
;
663 mimeType
= mimeTypeOrig
;
666 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
667 return rkey
.Create() && rkey
.SetValue(_T("Content Type"), mimeType
);
670 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
672 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetMimeType() needs extension") );
673 wxCHECK_MSG( wxFileExists(cmd
), FALSE
, _T("Icon file not found.") );
675 if ( !EnsureExtKeyExists() )
678 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
680 return rkey
.Create() &&
681 rkey
.SetValue(_T(""),
682 wxString::Format(_T("%s,%d"), cmd
.c_str(), index
));
685 // ----------------------------------------------------------------------------
686 // remove file association
687 // ----------------------------------------------------------------------------
689 bool wxFileTypeImpl::Unassociate()
692 if ( !RemoveOpenCommand() )
694 if ( !RemoveDefaultIcon() )
696 if ( !RemoveMimeType() )
701 // delete the root key
702 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
704 result
= key
.DeleteSelf();
710 bool wxFileTypeImpl::RemoveOpenCommand()
712 return RemoveCommand(_T("open"));
715 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
717 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
718 _T("RemoveCommand() needs an extension and a verb") );
720 wxString sKey
= m_strFileType
;
721 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
723 // if the key already doesn't exist, it's a success
724 return !rkey
.Exists() || rkey
.DeleteSelf();
727 bool wxFileTypeImpl::RemoveMimeType()
729 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("RemoveMimeType() needs extension") );
731 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
732 return !rkey
.Exists() || rkey
.DeleteSelf();
735 bool wxFileTypeImpl::RemoveDefaultIcon()
737 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
738 _T("RemoveDefaultIcon() needs extension") );
740 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
741 return !rkey
.Exists() || rkey
.DeleteSelf();