]>
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 licence (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "mimetype.h"
16 // for compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
25 // Doesn't compile in WIN16 mode
29 #include "wx/string.h"
32 #include "wx/msgdlg.h"
39 #include "wx/dynarray.h"
40 #include "wx/confbase.h"
43 #include "wx/msw/registry.h"
44 #include "wx/msw/private.h"
47 #include "wx/msw/mimetype.h"
49 // other standard headers
52 // in case we're compiling in non-GUI mode
53 class WXDLLEXPORT wxIcon
;
55 // These classes use Windows registry to retrieve the required information.
57 // Keys used (not all of them are documented, so it might actually stop working
58 // in future versions of Windows...):
59 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
60 // types, each key has a string value "Extension" which gives (dot preceded)
61 // extension for the files of this MIME type.
63 // 2. "HKCR\.ext" contains
64 // a) unnamed value containing the "filetype"
65 // b) value "Content Type" containing the MIME type
67 // 3. "HKCR\filetype" contains
68 // a) unnamed value containing the description
69 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
71 // c) shell\open\command and shell\open\print subkeys containing the commands
72 // to open/print the file (the positional parameters are introduced by %1,
73 // %2, ... in these strings, we change them to %s ourselves)
75 // although I don't know of any official documentation which mentions this
76 // location, uses it, so it isn't likely to change
77 static const wxChar
*MIME_DATABASE_KEY
= wxT("MIME\\Database\\Content Type\\");
79 void wxFileTypeImpl::Init(const wxString
& strFileType
, const wxString
& ext
)
81 // VZ: does it? (FIXME)
82 wxCHECK_RET( !ext
.IsEmpty(), _T("needs an extension") );
84 if ( ext
[0u] != wxT('.') ) {
89 m_strFileType
= strFileType
;
91 m_strFileType
= m_ext
.AfterFirst('.') + _T("_auto_file");
95 wxString
wxFileTypeImpl::GetVerbPath(const wxString
& verb
) const
98 path
<< m_strFileType
<< _T("\\shell\\") << verb
<< _T("\\command");
102 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
103 wxArrayString
*commands
,
104 const wxFileType::MessageParameters
& params
) const
106 wxCHECK_MSG( !m_ext
.IsEmpty(), 0, _T("GetAllCommands() needs an extension") );
108 if ( m_strFileType
.IsEmpty() )
110 // get it from the registry
111 wxFileTypeImpl
*self
= wxConstCast(this, wxFileTypeImpl
);
112 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
113 if ( !rkey
.Exists() || !rkey
.QueryValue(_T(""), self
->m_strFileType
) )
115 wxLogDebug(_T("Can't get the filetype for extension '%s'."),
122 // enum all subkeys of HKCR\filetype\shell
124 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell"));
127 bool ok
= rkey
.GetFirstKey(verb
, dummy
);
130 wxString command
= wxFileType::ExpandCommand(GetCommand(verb
), params
);
132 // we want the open bverb to eb always the first
134 if ( verb
.CmpNoCase(_T("open")) == 0 )
137 verbs
->Insert(verb
, 0);
139 commands
->Insert(command
, 0);
141 else // anything else than "open"
146 commands
->Add(command
);
151 ok
= rkey
.GetNextKey(verb
, dummy
);
157 // ----------------------------------------------------------------------------
158 // modify the registry database
159 // ----------------------------------------------------------------------------
161 bool wxFileTypeImpl::EnsureExtKeyExists()
163 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
164 if ( !rkey
.Exists() )
166 if ( !rkey
.Create() || !rkey
.SetValue(_T(""), m_strFileType
) )
168 wxLogError(_("Failed to create registry entry for '%s' files."),
177 // ----------------------------------------------------------------------------
178 // get the command to use
179 // ----------------------------------------------------------------------------
181 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
183 // suppress possible error messages
187 if ( wxRegKey(wxRegKey::HKCR
, m_ext
+ _T("\\shell")).Exists() )
189 if ( wxRegKey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell")).Exists() )
190 strKey
= m_strFileType
;
195 return wxEmptyString
;
198 strKey
<< wxT("\\shell\\") << verb
;
199 wxRegKey
key(wxRegKey::HKCR
, strKey
+ _T("\\command"));
202 // it's the default value of the key
203 if ( key
.QueryValue(wxT(""), command
) ) {
204 // transform it from '%1' to '%s' style format string (now also
205 // test for %L - apparently MS started using it as well for the
208 // NB: we don't make any attempt to verify that the string is valid,
209 // i.e. doesn't contain %2, or second %1 or .... But we do make
210 // sure that we return a string with _exactly_ one '%s'!
211 bool foundFilename
= FALSE
;
212 size_t len
= command
.Len();
213 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ ) {
214 if ( command
[n
] == wxT('%') &&
216 (command
[n
+ 1] == wxT('1') ||
217 command
[n
+ 1] == wxT('L')) ) {
218 // replace it with '%s'
219 command
[n
+ 1] = wxT('s');
221 foundFilename
= TRUE
;
226 // look whether we must issue some DDE requests to the application
227 // (and not just launch it)
228 strKey
+= _T("\\DDEExec");
229 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
230 if ( keyDDE
.Open() ) {
231 wxString ddeCommand
, ddeServer
, ddeTopic
;
232 keyDDE
.QueryValue(_T(""), ddeCommand
);
233 ddeCommand
.Replace(_T("%1"), _T("%s"));
235 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Application")).
236 QueryValue(_T(""), ddeServer
);
237 wxRegKey(wxRegKey::HKCR
, strKey
+ _T("\\Topic")).
238 QueryValue(_T(""), ddeTopic
);
240 if (ddeTopic
.IsEmpty())
241 ddeTopic
= wxT("System");
243 // HACK: we use a special feature of wxExecute which exists
244 // just because we need it here: it will establish DDE
245 // conversation with the program it just launched
246 command
.Prepend(_T("WX_DDE#"));
247 command
<< _T('#') << ddeServer
248 << _T('#') << ddeTopic
249 << _T('#') << ddeCommand
;
253 if ( !foundFilename
) {
254 // we didn't find any '%1' - the application doesn't know which
255 // file to open (note that we only do it if there is no DDEExec
258 // HACK: append the filename at the end, hope that it will do
259 command
<< wxT(" %s");
263 //else: no such file type or no value, will return empty string
269 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
270 const wxFileType::MessageParameters
& params
)
273 wxString cmd
= GetCommand(wxT("open"));
275 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
277 return !openCmd
->IsEmpty();
281 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
282 const wxFileType::MessageParameters
& params
)
285 wxString cmd
= GetCommand(wxT("print"));
287 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
289 return !printCmd
->IsEmpty();
292 // ----------------------------------------------------------------------------
293 // getting other stuff
294 // ----------------------------------------------------------------------------
296 // TODO this function is half implemented
297 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
299 if ( m_ext
.IsEmpty() ) {
300 // the only way to get the list of extensions from the file type is to
301 // scan through all extensions in the registry - too slow...
306 extensions
.Add(m_ext
);
308 // it's a lie too, we don't return _all_ extensions...
313 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
315 // suppress possible error messages
317 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
319 return key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
);
322 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
326 if ( !GetMimeType(&s
) )
337 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
,
339 int *iconIndex
) const
343 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
345 // suppress possible error messages
347 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
351 // it's the default value of the key
352 if ( key
.QueryValue(wxT(""), strIcon
) ) {
353 // the format is the following: <full path to file>, <icon index>
354 // NB: icon index may be negative as well as positive and the full
355 // path may contain the environment variables inside '%'
356 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
357 strIndex
= strIcon
.AfterLast(wxT(','));
359 // index may be omitted, in which case BeforeLast(',') is empty and
360 // AfterLast(',') is the whole string
361 if ( strFullPath
.IsEmpty() ) {
362 strFullPath
= strIndex
;
366 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
367 // here we need C based counting!
368 int nIndex
= wxAtoi(strIndex
);
369 #ifdef __DIGITALMARS__
370 //FIXME __DIGITALMARS__ April 2003 CE
371 // why no ExtractIcon in library
372 wxLogTrace(_T("wxFileTypeImpl::GetIcon"),
373 _T("Returning false from wxFileTypeImpl::GetIcon because of DigitalMars compiler bug"));
377 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
379 switch ( (int)hIcon
) {
380 case 0: // means no icons were found
381 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
382 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
383 key
.GetName().c_str());
387 icon
->SetHICON((WXHICON
)hIcon
);
388 wxSize size
= wxGetHiconSize(hIcon
);
393 *iconFile
= strFullPath
;
399 // no such file type or no value or incorrect icon entry
405 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
407 // suppress possible error messages
409 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
412 // it's the default value of the key
413 if ( key
.QueryValue(wxT(""), *desc
) ) {
423 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
425 wxFileType
*fileType
= new wxFileType
;
426 fileType
->m_impl
->Init(filetype
, ext
);
430 // extension -> file type
432 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
434 // add the leading point if necessary
436 if ( ext
[0u] != wxT('.') ) {
441 // suppress possible error messages
444 bool knownExtension
= FALSE
;
446 wxString strFileType
;
447 wxRegKey
key(wxRegKey::HKCR
, str
);
449 // it's the default value of the key
450 if ( key
.QueryValue(wxT(""), strFileType
) ) {
451 // create the new wxFileType object
452 return CreateFileType(strFileType
, ext
);
455 // this extension doesn't have a filetype, but it's known to the
456 // system and may be has some other useful keys (open command or
457 // content-type), so still return a file type object for it
458 knownExtension
= TRUE
;
462 if ( !knownExtension
)
468 return CreateFileType(wxEmptyString
, ext
);
473 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
475 wxFileType *fileType = GetFileTypeFromExtension(ext);
478 fileType = CreateFileType(wxEmptyString, ext);
485 // MIME type -> extension -> file type
487 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
489 wxString strKey
= MIME_DATABASE_KEY
;
492 // suppress possible error messages
496 wxRegKey
key(wxRegKey::HKCR
, strKey
);
498 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
499 return GetFileTypeFromExtension(ext
);
507 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
509 // enumerate all keys under MIME_DATABASE_KEY
510 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
514 bool cont
= key
.GetFirstKey(type
, cookie
);
519 cont
= key
.GetNextKey(type
, cookie
);
522 return mimetypes
.GetCount();
525 // ----------------------------------------------------------------------------
526 // create a new association
527 // ----------------------------------------------------------------------------
529 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
531 wxCHECK_MSG( !ftInfo
.GetExtensions().IsEmpty(), NULL
,
532 _T("Associate() needs extension") );
539 wxString ext
= ftInfo
.GetExtensions()[iExtCount
];
541 wxCHECK_MSG( !ext
.empty(), NULL
,
542 _T("Associate() needs non empty extension") );
544 if ( ext
[0u] != _T('.') )
545 extWithDot
= _T('.');
548 // start by setting the HKCR\\.ext entries
549 // default is filetype; content type is mimetype
550 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
552 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
555 // create the mapping from the extension to the filetype
560 if ( filetypeOrig
.empty() )
562 // make it up from the extension
563 filetype
<< extWithDot
.c_str() + 1 << _T("_file");
567 // just use the provided one
568 filetype
= filetypeOrig
;
571 ok
= key
.SetValue(_T(""), filetype
);
576 // key already exists, maybe we want to change it ??
577 if (!filetypeOrig
.empty())
579 filetype
= filetypeOrig
;
580 ok
= key
.SetValue(_T(""), filetype
);
584 ok
= key
.QueryValue(_T(""), filetype
);
587 // now set a mimetypeif we have it, but ignore it if none
588 const wxString
& mimetype
= ftInfo
.GetMimeType();
589 if ( !mimetype
.empty() )
592 ok
= key
.SetValue(_T("Content Type"), mimetype
);
596 // create the MIME key
597 wxString strKey
= MIME_DATABASE_KEY
;
599 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
600 ok
= keyMIME
.Create();
604 // and provide a back link to the extension
605 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
611 // now make other extensions have the same filetype
613 for (iExtCount
=1; iExtCount
< ftInfo
.GetExtensionsCount(); iExtCount
++ )
615 ext
= ftInfo
.GetExtensions()[iExtCount
];
616 if ( ext
[0u] != _T('.') )
617 extWithDot
= _T('.');
620 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
621 if ( !key
.Exists() ) ok
= key
.Create();
622 ok
= key
.SetValue(_T(""), filetype
);
624 // now set any mimetypes we may have, but ignore it if none
625 const wxString
& mimetype
= ftInfo
.GetMimeType();
626 if ( !mimetype
.empty() )
629 ok
= key
.SetValue(_T("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 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
648 } // end of for loop; all extensions now point to HKCR\.ext\Default
650 // create the filetype key itself (it will be empty for now, but
651 // SetCommand(), SetDefaultIcon() &c will use it later)
652 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
655 wxFileType
*ft
= NULL
;
656 ft
= CreateFileType(filetype
, extWithDot
);
660 if (! ftInfo
.GetOpenCommand ().IsEmpty() ) ft
->SetCommand (ftInfo
.GetOpenCommand (), wxT("open" ) );
661 if (! ftInfo
.GetPrintCommand().IsEmpty() ) ft
->SetCommand (ftInfo
.GetPrintCommand(), wxT("print" ) );
662 // chris: I don't like the ->m_impl-> here FIX this ??
663 if (! ftInfo
.GetDescription ().IsEmpty() ) ft
->m_impl
->SetDescription (ftInfo
.GetDescription ()) ;
664 if (! ftInfo
.GetIconFile().IsEmpty() ) ft
->SetDefaultIcon (ftInfo
.GetIconFile(), ftInfo
.GetIconIndex() );
670 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
671 const wxString
& verb
,
672 bool WXUNUSED(overwriteprompt
))
674 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
675 _T("SetCommand() needs an extension and a verb") );
677 if ( !EnsureExtKeyExists() )
680 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
682 if ( rkey
.Exists() && overwriteprompt
)
686 rkey
.QueryValue(wxT(""), old
);
690 _("Do you want to overwrite the command used to %s "
691 "files with extension \"%s\" ?\nCurrent value is \n%s, "
692 "\nNew value is \n%s %1"), // bug here FIX need %1 ??
697 _("Confirm registry update"),
698 wxYES_NO
| wxICON_QUESTION
708 // 1. translate '%s' to '%1' instead of always adding it
709 // 2. create DDEExec value if needed (undo GetCommand)
710 return rkey
.Create() && rkey
.SetValue(_T(""), cmd
+ _T(" \"%1\"") );
714 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
716 wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("SetMimeType() needs extension") );
718 if ( !EnsureExtKeyExists() )
721 // VZ: is this really useful? (FIXME)
725 // make up a default value for it
727 wxSplitPath(GetCommand(_T("open")), NULL, &cmd, NULL);
728 mimeType << _T("application/x-") << cmd;
732 mimeType = mimeTypeOrig;
735 wxRegKey rkey(wxRegKey::HKCR, m_ext);
736 return rkey.Create() && rkey.SetValue(_T("Content Type"), mimeType);
740 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
742 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetDefaultIcon() needs extension") );
743 wxCHECK_MSG( !m_strFileType
.IsEmpty(), FALSE
, _T("File key not found") );
744 // the next line fails on a SMBshare, I think because it is case mangled
745 // wxCHECK_MSG( !wxFileExists(cmd), FALSE, _T("Icon file not found.") );
747 if ( !EnsureExtKeyExists() )
750 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
752 return rkey
.Create() &&
753 rkey
.SetValue(_T(""),
754 wxString::Format(_T("%s,%d"), cmd
.c_str(), index
));
757 bool wxFileTypeImpl::SetDescription (const wxString
& desc
)
759 wxCHECK_MSG( !m_strFileType
.IsEmpty(), FALSE
, _T("File key not found") );
760 wxCHECK_MSG( !desc
.IsEmpty(), FALSE
, _T("No file description supplied") );
762 if ( !EnsureExtKeyExists() )
765 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
);
767 return rkey
.Create() &&
768 rkey
.SetValue(_T(""), desc
);
771 // ----------------------------------------------------------------------------
772 // remove file association
773 // ----------------------------------------------------------------------------
775 bool wxFileTypeImpl::Unassociate()
778 if ( !RemoveOpenCommand() )
780 if ( !RemoveDefaultIcon() )
782 if ( !RemoveMimeType() )
784 if ( !RemoveDescription() )
788 //this might hold other keys, eg some have CSLID keys
791 // delete the root key
792 wxRegKey key(wxRegKey::HKCR, m_ext);
794 result = key.DeleteSelf();
800 bool wxFileTypeImpl::RemoveOpenCommand()
802 return RemoveCommand(_T("open"));
805 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
807 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
808 _T("RemoveCommand() needs an extension and a verb") );
810 wxString sKey
= m_strFileType
;
811 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
813 // if the key already doesn't exist, it's a success
814 return !rkey
.Exists() || rkey
.DeleteSelf();
817 bool wxFileTypeImpl::RemoveMimeType()
819 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("RemoveMimeType() needs extension") );
821 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
822 return !rkey
.Exists() || rkey
.DeleteSelf();
825 bool wxFileTypeImpl::RemoveDefaultIcon()
827 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
828 _T("RemoveDefaultIcon() needs extension") );
830 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
831 return !rkey
.Exists() || rkey
.DeleteSelf();
834 bool wxFileTypeImpl::RemoveDescription()
836 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
837 _T("RemoveDescription() needs extension") );
839 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
);
840 return !rkey
.Exists() || rkey
.DeleteSelf();
846 #endif // wxUSE_MIMETYPE