]>
git.saurik.com Git - wxWidgets.git/blob - src/msw/mimetype.cpp
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
);
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 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
176 const wxString
& verb
,
177 bool overwriteprompt
)
179 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
180 _T("SetCommand() needs an extension and a verb") );
182 if ( !EnsureExtKeyExists() )
185 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
187 if ( rkey
.Exists() && overwriteprompt
)
191 rkey
.QueryValue(wxT(""), old
);
195 _("Do you want to overwrite the command used to %s "
196 "files with extension \"%s\" (current value is '%s', "
197 "new value is '%s')?"),
202 _("Confirm registry update"),
203 wxYES_NO
| wxICON_QUESTION
213 // 1. translate '%s' to '%1' instead of always adding it
214 // 2. create DDEExec value if needed (undo GetCommand)
215 return rkey
.Create() && rkey
.SetValue(_T(""), cmd
+ _T(" \"%1\"") );
218 bool wxFileTypeImpl::SetMimeType(const wxString
& mimeTypeOrig
)
220 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetMimeType() needs extension") );
222 if ( !EnsureExtKeyExists() )
225 // VZ: is this really useful? (FIXME)
229 // make up a default value for it
231 wxSplitPath(GetCommand(_T("open")), NULL
, &cmd
, NULL
);
232 mimeType
<< _T("application/x-") << cmd
;
236 mimeType
= mimeTypeOrig
;
239 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
240 return rkey
.Create() && rkey
.SetValue(_T("Content Type"), mimeType
);
243 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
245 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetMimeType() needs extension") );
246 wxCHECK_MSG( wxFileExists(cmd
), FALSE
, _T("Icon file not found.") );
248 if ( !EnsureExtKeyExists() )
251 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
253 return rkey
.Create() &&
254 rkey
.SetValue(_T(""),
255 wxString::Format(_T("%s,%d"), cmd
.c_str(), index
));
258 // ----------------------------------------------------------------------------
259 // remove file association
260 // ----------------------------------------------------------------------------
262 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
264 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
265 _T("RemoveCommand() needs an extension and a verb") );
267 wxString sKey
= m_strFileType
;
268 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
270 // if the key already doesn't exist, it's a success
271 return !rkey
.Exists() || rkey
.DeleteSelf();
274 bool wxFileTypeImpl::RemoveMimeType()
276 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("RemoveMimeType() needs extension") );
278 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
279 return !rkey
.Exists() || rkey
.DeleteSelf();
282 bool wxFileTypeImpl::RemoveDefaultIcon()
284 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
285 _T("RemoveDefaultIcon() needs extension") );
287 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
288 return !rkey
.Exists() || rkey
.DeleteSelf();
291 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
293 // suppress possible error messages
297 if ( wxRegKey(wxRegKey::HKCR
, m_ext
+ _T("\\shell")).Exists() )
299 if ( wxRegKey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell")).Exists() )
300 strKey
= m_strFileType
;
305 return wxEmptyString
;
308 strKey
<< wxT("\\shell\\") << verb
;
309 wxRegKey
key(wxRegKey::HKCR
, strKey
+ _T("\\command"));
312 // it's the default value of the key
313 if ( key
.QueryValue(wxT(""), command
) ) {
314 // transform it from '%1' to '%s' style format string (now also
315 // test for %L - apparently MS started using it as well for the
318 // NB: we don't make any attempt to verify that the string is valid,
319 // i.e. doesn't contain %2, or second %1 or .... But we do make
320 // sure that we return a string with _exactly_ one '%s'!
321 bool foundFilename
= FALSE
;
322 size_t len
= command
.Len();
323 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
324 if ( command
[n
] == wxT('%') &&
326 (command
[n
+ 1] == wxT('1') ||
327 command
[n
+ 1] == wxT('L')) ) {
328 // replace it with '%s'
329 command
[n
+ 1] = wxT('s');
331 foundFilename
= TRUE
;
336 // look whether we must issue some DDE requests to the application
337 // (and not just launch it)
338 strKey
+= _T("\\DDEExec");
339 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
340 if ( keyDDE
.Open() ) {
341 wxString ddeCommand
, ddeServer
, ddeTopic
;
342 keyDDE
.QueryValue(_T(""), ddeCommand
);
343 ddeCommand
.Replace(_T("%1"), _T("%s"));
345 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Application")).
346 QueryValue(_T(""), ddeServer
);
347 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Topic")).
348 QueryValue(_T(""), ddeTopic
);
350 // HACK: we use a special feature of wxExecute which exists
351 // just because we need it here: it will establish DDE
352 // conversation with the program it just launched
353 command
.Prepend(_T("WX_DDE#"));
354 command
<< _T('#') << ddeServer
355 << _T('#') << ddeTopic
356 << _T('#') << ddeCommand
;
360 if ( !foundFilename
) {
361 // we didn't find any '%1' - the application doesn't know which
362 // file to open (note that we only do it if there is no DDEExec
365 // HACK: append the filename at the end, hope that it will do
366 command
<< wxT(" %s");
370 //else: no such file type or no value, will return empty string
376 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
377 const wxFileType::MessageParameters
& params
)
382 cmd
= m_info
->GetOpenCommand();
385 cmd
= GetCommand(wxT("open"));
388 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
390 return !openCmd
->IsEmpty();
394 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
395 const wxFileType::MessageParameters
& params
)
400 cmd
= m_info
->GetPrintCommand();
403 cmd
= GetCommand(wxT("print"));
406 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
408 return !printCmd
->IsEmpty();
411 // TODO this function is half implemented
412 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
415 extensions
= m_info
->GetExtensions();
419 else if ( m_ext
.IsEmpty() ) {
420 // the only way to get the list of extensions from the file type is to
421 // scan through all extensions in the registry - too slow...
426 extensions
.Add(m_ext
);
428 // it's a lie too, we don't return _all_ extensions...
433 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
436 // we already have it
437 *mimeType
= m_info
->GetMimeType();
442 // suppress possible error messages
444 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
446 return key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
);
449 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
453 if ( !GetMimeType(&s
) )
464 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
,
466 int *iconIndex
) const
470 // we don't have icons in the fallback resources
475 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
477 // suppress possible error messages
479 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
483 // it's the default value of the key
484 if ( key
.QueryValue(wxT(""), strIcon
) ) {
485 // the format is the following: <full path to file>, <icon index>
486 // NB: icon index may be negative as well as positive and the full
487 // path may contain the environment variables inside '%'
488 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
489 strIndex
= strIcon
.AfterLast(wxT(','));
491 // index may be omitted, in which case BeforeLast(',') is empty and
492 // AfterLast(',') is the whole string
493 if ( strFullPath
.IsEmpty() ) {
494 strFullPath
= strIndex
;
498 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
499 int nIndex
= wxAtoi(strIndex
) - 1 ; //bug here we need C based counting!!
501 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
502 switch ( (int)hIcon
) {
503 case 0: // means no icons were found
504 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
505 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
506 key
.GetName().c_str());
510 icon
->SetHICON((WXHICON
)hIcon
);
514 *iconFile
= strFullPath
;
520 // no such file type or no value or incorrect icon entry
526 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
529 // we already have it
530 *desc
= m_info
->GetDescription();
535 // suppress possible error messages
537 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
540 // it's the default value of the key
541 if ( key
.QueryValue(wxT(""), *desc
) ) {
551 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
553 wxFileType
*fileType
= new wxFileType
;
554 fileType
->m_impl
->Init(filetype
, ext
);
558 // extension -> file type
560 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
562 // add the leading point if necessary
564 if ( ext
[0u] != wxT('.') ) {
569 // suppress possible error messages
572 bool knownExtension
= FALSE
;
574 wxString strFileType
;
575 wxRegKey
key(wxRegKey::HKCR
, str
);
577 // it's the default value of the key
578 if ( key
.QueryValue(wxT(""), strFileType
) ) {
579 // create the new wxFileType object
580 return CreateFileType(strFileType
, ext
);
583 // this extension doesn't have a filetype, but it's known to the
584 // system and may be has some other useful keys (open command or
585 // content-type), so still return a file type object for it
586 knownExtension
= TRUE
;
590 // check the fallbacks
591 // TODO linear search is potentially slow, perhaps we should use a sorted
593 size_t count
= m_fallbacks
.GetCount();
594 for ( size_t n
= 0; n
< count
; n
++ ) {
595 if ( m_fallbacks
[n
].GetExtensions().Index(ext
) != wxNOT_FOUND
) {
596 wxFileType
*fileType
= new wxFileType
;
597 fileType
->m_impl
->Init(m_fallbacks
[n
]);
603 if ( !knownExtension
)
609 return CreateFileType(wxEmptyString
, ext
);
613 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString
& ext
)
615 wxFileType
*fileType
= GetFileTypeFromExtension(ext
);
618 fileType
= CreateFileType(wxEmptyString
, ext
);
625 // MIME type -> extension -> file type
627 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
629 wxString strKey
= MIME_DATABASE_KEY
;
632 // suppress possible error messages
636 wxRegKey
key(wxRegKey::HKCR
, strKey
);
638 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
639 return GetFileTypeFromExtension(ext
);
643 // check the fallbacks
644 // TODO linear search is potentially slow, perhaps we should use a sorted
646 size_t count
= m_fallbacks
.GetCount();
647 for ( size_t n
= 0; n
< count
; n
++ ) {
648 if ( wxMimeTypesManager::IsOfType(mimeType
,
649 m_fallbacks
[n
].GetMimeType()) ) {
650 wxFileType
*fileType
= new wxFileType
;
651 fileType
->m_impl
->Init(m_fallbacks
[n
]);
661 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
663 // enumerate all keys under MIME_DATABASE_KEY
664 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
668 bool cont
= key
.GetFirstKey(type
, cookie
);
673 cont
= key
.GetNextKey(type
, cookie
);
676 return mimetypes
.GetCount();
679 // ----------------------------------------------------------------------------
680 // create a new association
681 // ----------------------------------------------------------------------------
683 wxFileType
*wxMimeTypesManager::Associate(const wxString
& ext
,
684 const wxString
& mimetype
,
685 const wxString
& filetypeOrig
,
686 const wxString
& WXUNUSED(desc
))
688 wxCHECK_MSG( !ext
.empty(), NULL
, _T("Associate() needs extension") );
691 if ( ext
[0u] != _T('.') )
692 extWithDot
= _T('.');
695 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
696 wxFileType
*ft
= NULL
;
701 // create the mapping from the extension to the filetype
702 bool ok
= key
.Create();
705 if ( filetypeOrig
.empty() )
707 // make it up from the extension
708 filetype
<< extWithDot
.c_str() + 1 << _T("_auto_file");
712 // just use the provided one
713 filetype
= filetypeOrig
;
716 ok
= key
.SetValue(_T(""), filetype
);
719 if ( ok
&& !mimetype
.empty() )
722 ok
= key
.SetValue(_T("Content Type"), mimetype
);
726 // create the MIME key
727 wxString strKey
= MIME_DATABASE_KEY
;
729 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
730 ok
= keyMIME
.Create();
734 // and provide a back link to the extension
735 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
742 // create the filetype key itself (it will be empty for now, but
743 // SetCommand(), SetDefaultIcon() &c will use it later)
744 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
750 // ok, we've created everything correctly
751 ft
= m_impl
->CreateFileType(filetype
, extWithDot
);
755 // one of the registry operations failed
756 wxLogError(_("Failed to register extension '%s'."), ext
.c_str());
759 else // key already exists
761 // FIXME we probably should return an existing file type then?