]>
git.saurik.com Git - wxWidgets.git/blob - src/msw/mimetype.cpp
64ac0c17d959f1327fc60deae55ee9e63df949ea
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 // Doesn't compile in WIN16 mode
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
);
147 ok
= rkey
.GetNextKey(verb
, dummy
);
153 // ----------------------------------------------------------------------------
154 // modify the registry database
155 // ----------------------------------------------------------------------------
157 bool wxFileTypeImpl::EnsureExtKeyExists()
159 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
160 if ( !rkey
.Exists() )
162 if ( !rkey
.Create() || !rkey
.SetValue(_T(""), m_strFileType
) )
164 wxLogError(_("Failed to create registry entry for '%s' files."),
173 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
174 const wxString
& verb
,
175 bool overwriteprompt
)
177 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
178 _T("SetCommand() needs an extension and a verb") );
180 if ( !EnsureExtKeyExists() )
183 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
185 if ( rkey
.Exists() && overwriteprompt
)
189 rkey
.QueryValue(wxT(""), old
);
193 _("Do you want to overwrite the command used to %s "
194 "files with extension \"%s\" (current value is '%s', "
195 "new value is '%s')?"),
200 _("Confirm registry update"),
201 wxYES_NO
| wxICON_QUESTION
211 // 1. translate '%s' to '%1' instead of always adding it
212 // 2. create DDEExec value if needed (undo GetCommand)
213 return rkey
.Create() && rkey
.SetValue(_T(""), cmd
+ _T(" \"%1\"") );
216 bool wxFileTypeImpl::SetMimeType(const wxString
& mimeTypeOrig
)
218 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetMimeType() needs extension") );
220 if ( !EnsureExtKeyExists() )
223 // VZ: is this really useful? (FIXME)
227 // make up a default value for it
229 wxSplitPath(GetCommand(_T("open")), NULL
, &cmd
, NULL
);
230 mimeType
<< _T("application/x-") << cmd
;
234 mimeType
= mimeTypeOrig
;
237 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
238 return rkey
.Create() && rkey
.SetValue(_T("Content Type"), mimeType
);
241 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
243 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetMimeType() needs extension") );
244 wxCHECK_MSG( wxFileExists(cmd
), FALSE
, _T("Icon file not found.") );
246 if ( !EnsureExtKeyExists() )
249 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
251 return rkey
.Create() &&
252 rkey
.SetValue(_T(""),
253 wxString::Format(_T("%s,%d"), cmd
.c_str(), index
));
256 // ----------------------------------------------------------------------------
257 // remove file association
258 // ----------------------------------------------------------------------------
260 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
262 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
263 _T("RemoveCommand() needs an extension and a verb") );
265 wxString sKey
= m_strFileType
;
266 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
268 // if the key already doesn't exist, it's a success
269 return !rkey
.Exists() || rkey
.DeleteSelf();
272 bool wxFileTypeImpl::RemoveMimeType()
274 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("RemoveMimeType() needs extension") );
276 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
277 return !rkey
.Exists() || rkey
.DeleteSelf();
280 bool wxFileTypeImpl::RemoveDefaultIcon()
282 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
283 _T("RemoveDefaultIcon() needs extension") );
285 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
286 return !rkey
.Exists() || rkey
.DeleteSelf();
289 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
291 // suppress possible error messages
295 if ( wxRegKey(wxRegKey::HKCR
, m_ext
+ _T("\\shell")).Exists() )
297 if ( wxRegKey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell")).Exists() )
298 strKey
= m_strFileType
;
303 return wxEmptyString
;
306 strKey
<< wxT("\\shell\\") << verb
;
307 wxRegKey
key(wxRegKey::HKCR
, strKey
+ _T("\\command"));
310 // it's the default value of the key
311 if ( key
.QueryValue(wxT(""), command
) ) {
312 // transform it from '%1' to '%s' style format string (now also
313 // test for %L - apparently MS started using it as well for the
316 // NB: we don't make any attempt to verify that the string is valid,
317 // i.e. doesn't contain %2, or second %1 or .... But we do make
318 // sure that we return a string with _exactly_ one '%s'!
319 bool foundFilename
= FALSE
;
320 size_t len
= command
.Len();
321 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
322 if ( command
[n
] == wxT('%') &&
324 (command
[n
+ 1] == wxT('1') ||
325 command
[n
+ 1] == wxT('L')) ) {
326 // replace it with '%s'
327 command
[n
+ 1] = wxT('s');
329 foundFilename
= TRUE
;
334 // look whether we must issue some DDE requests to the application
335 // (and not just launch it)
336 strKey
+= _T("\\DDEExec");
337 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
338 if ( keyDDE
.Open() ) {
339 wxString ddeCommand
, ddeServer
, ddeTopic
;
340 keyDDE
.QueryValue(_T(""), ddeCommand
);
341 ddeCommand
.Replace(_T("%1"), _T("%s"));
343 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Application")).
344 QueryValue(_T(""), ddeServer
);
345 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Topic")).
346 QueryValue(_T(""), ddeTopic
);
348 // HACK: we use a special feature of wxExecute which exists
349 // just because we need it here: it will establish DDE
350 // conversation with the program it just launched
351 command
.Prepend(_T("WX_DDE#"));
352 command
<< _T('#') << ddeServer
353 << _T('#') << ddeTopic
354 << _T('#') << ddeCommand
;
358 if ( !foundFilename
) {
359 // we didn't find any '%1' - the application doesn't know which
360 // file to open (note that we only do it if there is no DDEExec
363 // HACK: append the filename at the end, hope that it will do
364 command
<< wxT(" %s");
368 //else: no such file type or no value, will return empty string
374 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
375 const wxFileType::MessageParameters
& params
)
380 cmd
= m_info
->GetOpenCommand();
383 cmd
= GetCommand(wxT("open"));
386 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
388 return !openCmd
->IsEmpty();
392 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
393 const wxFileType::MessageParameters
& params
)
398 cmd
= m_info
->GetPrintCommand();
401 cmd
= GetCommand(wxT("print"));
404 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
406 return !printCmd
->IsEmpty();
409 // TODO this function is half implemented
410 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
413 extensions
= m_info
->GetExtensions();
417 else if ( m_ext
.IsEmpty() ) {
418 // the only way to get the list of extensions from the file type is to
419 // scan through all extensions in the registry - too slow...
424 extensions
.Add(m_ext
);
426 // it's a lie too, we don't return _all_ extensions...
431 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
434 // we already have it
435 *mimeType
= m_info
->GetMimeType();
440 // suppress possible error messages
442 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
444 return key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
);
447 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
451 if ( !GetMimeType(&s
) )
462 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
,
464 int *iconIndex
) const
468 // we don't have icons in the fallback resources
473 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
475 // suppress possible error messages
477 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
481 // it's the default value of the key
482 if ( key
.QueryValue(wxT(""), strIcon
) ) {
483 // the format is the following: <full path to file>, <icon index>
484 // NB: icon index may be negative as well as positive and the full
485 // path may contain the environment variables inside '%'
486 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
487 strIndex
= strIcon
.AfterLast(wxT(','));
489 // index may be omitted, in which case BeforeLast(',') is empty and
490 // AfterLast(',') is the whole string
491 if ( strFullPath
.IsEmpty() ) {
492 strFullPath
= strIndex
;
496 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
497 int nIndex
= wxAtoi(strIndex
) - 1 ; //bug here we need C based counting!!
499 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
500 switch ( (int)hIcon
) {
501 case 0: // means no icons were found
502 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
503 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
504 key
.GetName().c_str());
508 icon
->SetHICON((WXHICON
)hIcon
);
512 *iconFile
= strFullPath
;
518 // no such file type or no value or incorrect icon entry
524 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
527 // we already have it
528 *desc
= m_info
->GetDescription();
533 // suppress possible error messages
535 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
538 // it's the default value of the key
539 if ( key
.QueryValue(wxT(""), *desc
) ) {
549 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
551 wxFileType
*fileType
= new wxFileType
;
552 fileType
->m_impl
->Init(filetype
, ext
);
556 // extension -> file type
558 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
560 // add the leading point if necessary
562 if ( ext
[0u] != wxT('.') ) {
567 // suppress possible error messages
570 bool knownExtension
= FALSE
;
572 wxString strFileType
;
573 wxRegKey
key(wxRegKey::HKCR
, str
);
575 // it's the default value of the key
576 if ( key
.QueryValue(wxT(""), strFileType
) ) {
577 // create the new wxFileType object
578 return CreateFileType(strFileType
, ext
);
581 // this extension doesn't have a filetype, but it's known to the
582 // system and may be has some other useful keys (open command or
583 // content-type), so still return a file type object for it
584 knownExtension
= TRUE
;
588 // check the fallbacks
589 // TODO linear search is potentially slow, perhaps we should use a sorted
591 size_t count
= m_fallbacks
.GetCount();
592 for ( size_t n
= 0; n
< count
; n
++ ) {
593 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
594 wxFileType
*fileType
= new wxFileType
;
595 fileType
->m_impl
->Init(m_fallbacks
[n
]);
601 if ( !knownExtension
)
607 return CreateFileType(wxEmptyString
, ext
);
611 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString
& ext
)
613 wxFileType
*fileType
= GetFileTypeFromExtension(ext
);
616 fileType
= CreateFileType(wxEmptyString
, ext
);
623 // MIME type -> extension -> file type
625 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
627 wxString strKey
= MIME_DATABASE_KEY
;
630 // suppress possible error messages
634 wxRegKey
key(wxRegKey::HKCR
, strKey
);
636 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
637 return GetFileTypeFromExtension(ext
);
641 // check the fallbacks
642 // TODO linear search is potentially slow, perhaps we should use a sorted
644 size_t count
= m_fallbacks
.GetCount();
645 for ( size_t n
= 0; n
< count
; n
++ ) {
646 if ( wxMimeTypesManager::IsOfType(mimeType
,
647 m_fallbacks
[n
].GetMimeType()) ) {
648 wxFileType
*fileType
= new wxFileType
;
649 fileType
->m_impl
->Init(m_fallbacks
[n
]);
659 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
661 // enumerate all keys under MIME_DATABASE_KEY
662 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
666 bool cont
= key
.GetFirstKey(type
, cookie
);
671 cont
= key
.GetNextKey(type
, cookie
);
674 return mimetypes
.GetCount();
677 // ----------------------------------------------------------------------------
678 // create a new association
679 // ----------------------------------------------------------------------------
681 wxFileType
*wxMimeTypesManager::Associate(const wxString
& ext
,
682 const wxString
& mimetype
,
683 const wxString
& filetypeOrig
,
684 const wxString
& WXUNUSED(desc
))
686 wxCHECK_MSG( !ext
.empty(), NULL
, _T("Associate() needs extension") );
689 if ( ext
[0u] != _T('.') )
690 extWithDot
= _T('.');
693 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
694 wxFileType
*ft
= NULL
;
699 // create the mapping from the extension to the filetype
700 bool ok
= key
.Create();
703 if ( filetypeOrig
.empty() )
705 // make it up from the extension
706 filetype
<< extWithDot
.c_str() + 1 << _T("_auto_file");
710 // just use the provided one
711 filetype
= filetypeOrig
;
714 ok
= key
.SetValue(_T(""), filetype
);
717 if ( ok
&& !mimetype
.empty() )
720 ok
= key
.SetValue(_T("Content Type"), mimetype
);
724 // create the MIME key
725 wxString strKey
= MIME_DATABASE_KEY
;
727 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
728 ok
= keyMIME
.Create();
732 // and provide a back link to the extension
733 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
740 // create the filetype key itself (it will be empty for now, but
741 // SetCommand(), SetDefaultIcon() &c will use it later)
742 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
748 // ok, we've created everything correctly
749 ft
= m_impl
->CreateFileType(filetype
, extWithDot
);
753 // one of the registry operations failed
754 wxLogError(_("Failed to register extension '%s'."), ext
.c_str());
757 else // key already exists
759 // FIXME we probably should return an existing file type then?