]>
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"
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('.') + "_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 // HACK: we use a special feature of wxExecute which exists
241 // just because we need it here: it will establish DDE
242 // conversation with the program it just launched
243 command
.Prepend(_T("WX_DDE#"));
244 command
<< _T('#') << ddeServer
245 << _T('#') << ddeTopic
246 << _T('#') << ddeCommand
;
250 if ( !foundFilename
) {
251 // we didn't find any '%1' - the application doesn't know which
252 // file to open (note that we only do it if there is no DDEExec
255 // HACK: append the filename at the end, hope that it will do
256 command
<< wxT(" %s");
260 //else: no such file type or no value, will return empty string
266 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
267 const wxFileType::MessageParameters
& params
)
270 wxString cmd
= GetCommand(wxT("open"));
272 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
274 return !openCmd
->IsEmpty();
278 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
279 const wxFileType::MessageParameters
& params
)
282 wxString cmd
= GetCommand(wxT("print"));
284 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
286 return !printCmd
->IsEmpty();
289 // ----------------------------------------------------------------------------
290 // getting other stuff
291 // ----------------------------------------------------------------------------
293 // TODO this function is half implemented
294 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
296 if ( m_ext
.IsEmpty() ) {
297 // the only way to get the list of extensions from the file type is to
298 // scan through all extensions in the registry - too slow...
303 extensions
.Add(m_ext
);
305 // it's a lie too, we don't return _all_ extensions...
310 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
312 // suppress possible error messages
314 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
316 return key
.Open() && key
.QueryValue(wxT("Content Type"), *mimeType
);
319 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
323 if ( !GetMimeType(&s
) )
334 bool wxFileTypeImpl::GetIcon(wxIcon
*icon
,
336 int *iconIndex
) const
340 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
342 // suppress possible error messages
344 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
348 // it's the default value of the key
349 if ( key
.QueryValue(wxT(""), strIcon
) ) {
350 // the format is the following: <full path to file>, <icon index>
351 // NB: icon index may be negative as well as positive and the full
352 // path may contain the environment variables inside '%'
353 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
354 strIndex
= strIcon
.AfterLast(wxT(','));
356 // index may be omitted, in which case BeforeLast(',') is empty and
357 // AfterLast(',') is the whole string
358 if ( strFullPath
.IsEmpty() ) {
359 strFullPath
= strIndex
;
363 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
364 // here we need C based counting!
365 int nIndex
= wxAtoi(strIndex
);
367 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
368 switch ( (int)hIcon
) {
369 case 0: // means no icons were found
370 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
371 wxLogDebug(wxT("incorrect registry entry '%s': no such icon."),
372 key
.GetName().c_str());
376 icon
->SetHICON((WXHICON
)hIcon
);
377 wxSize size
= wxGetHiconSize(hIcon
);
382 *iconFile
= strFullPath
;
388 // no such file type or no value or incorrect icon entry
394 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
396 // suppress possible error messages
398 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
401 // it's the default value of the key
402 if ( key
.QueryValue(wxT(""), *desc
) ) {
412 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
414 wxFileType
*fileType
= new wxFileType
;
415 fileType
->m_impl
->Init(filetype
, ext
);
419 // extension -> file type
421 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
423 // add the leading point if necessary
425 if ( ext
[0u] != wxT('.') ) {
430 // suppress possible error messages
433 bool knownExtension
= FALSE
;
435 wxString strFileType
;
436 wxRegKey
key(wxRegKey::HKCR
, str
);
438 // it's the default value of the key
439 if ( key
.QueryValue(wxT(""), strFileType
) ) {
440 // create the new wxFileType object
441 return CreateFileType(strFileType
, ext
);
444 // this extension doesn't have a filetype, but it's known to the
445 // system and may be has some other useful keys (open command or
446 // content-type), so still return a file type object for it
447 knownExtension
= TRUE
;
451 if ( !knownExtension
)
457 return CreateFileType(wxEmptyString
, ext
);
462 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
464 wxFileType *fileType = GetFileTypeFromExtension(ext);
467 fileType = CreateFileType(wxEmptyString, ext);
474 // MIME type -> extension -> file type
476 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
478 wxString strKey
= MIME_DATABASE_KEY
;
481 // suppress possible error messages
485 wxRegKey
key(wxRegKey::HKCR
, strKey
);
487 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
488 return GetFileTypeFromExtension(ext
);
496 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
498 // enumerate all keys under MIME_DATABASE_KEY
499 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
503 bool cont
= key
.GetFirstKey(type
, cookie
);
508 cont
= key
.GetNextKey(type
, cookie
);
511 return mimetypes
.GetCount();
514 // ----------------------------------------------------------------------------
515 // create a new association
516 // ----------------------------------------------------------------------------
518 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
520 wxCHECK_MSG( !ftInfo
.GetExtensions().IsEmpty(), NULL
,
521 _T("Associate() needs extension") );
528 wxString ext
= ftInfo
.GetExtensions()[iExtCount
];
530 wxCHECK_MSG( !ext
.empty(), NULL
,
531 _T("Associate() needs non empty extension") );
533 if ( ext
[0u] != _T('.') )
534 extWithDot
= _T('.');
537 // start by setting the HKCR\\.ext entries
538 // default is filetype; content type is mimetype
539 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
541 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
544 // create the mapping from the extension to the filetype
549 if ( filetypeOrig
.empty() )
551 // make it up from the extension
552 filetype
<< extWithDot
.c_str() + 1 << _T("_file");
556 // just use the provided one
557 filetype
= filetypeOrig
;
560 ok
= key
.SetValue(_T(""), filetype
);
565 // key already exists, maybe we want to change it ??
566 if (!filetypeOrig
.empty())
568 filetype
= filetypeOrig
;
569 ok
= key
.SetValue(_T(""), filetype
);
573 ok
= key
.QueryValue(_T(""), filetype
);
576 // now set a mimetypeif we have it, but ignore it if none
577 const wxString
& mimetype
= ftInfo
.GetMimeType();
578 if ( !mimetype
.empty() )
581 ok
= key
.SetValue(_T("Content Type"), mimetype
);
585 // create the MIME key
586 wxString strKey
= MIME_DATABASE_KEY
;
588 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
589 ok
= keyMIME
.Create();
593 // and provide a back link to the extension
594 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
600 // now make other extensions have the same filetype
602 for (iExtCount
=1; iExtCount
< ftInfo
.GetExtensionsCount(); iExtCount
++ )
604 ext
= ftInfo
.GetExtensions()[iExtCount
];
605 if ( ext
[0u] != _T('.') )
606 extWithDot
= _T('.');
609 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
610 if ( !key
.Exists() ) ok
= key
.Create();
611 ok
= key
.SetValue(_T(""), filetype
);
613 // now set any mimetypes we may have, but ignore it if none
614 const wxString
& mimetype
= ftInfo
.GetMimeType();
615 if ( !mimetype
.empty() )
618 ok
= key
.SetValue(_T("Content Type"), mimetype
);
622 // create the MIME key
623 wxString strKey
= MIME_DATABASE_KEY
;
625 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
626 ok
= keyMIME
.Create();
630 // and provide a back link to the extension
631 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
637 } // end of for loop; all extensions now point to HKCR\.ext\Default
639 // create the filetype key itself (it will be empty for now, but
640 // SetCommand(), SetDefaultIcon() &c will use it later)
641 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
644 wxFileType
*ft
= NULL
;
645 ft
= CreateFileType(filetype
, extWithDot
);
649 if (! ftInfo
.GetOpenCommand ().IsEmpty() ) ft
->SetCommand (ftInfo
.GetOpenCommand (), wxT("open" ) );
650 if (! ftInfo
.GetPrintCommand().IsEmpty() ) ft
->SetCommand (ftInfo
.GetPrintCommand(), wxT("print" ) );
651 // chris: I don't like the ->m_impl-> here FIX this ??
652 if (! ftInfo
.GetDescription ().IsEmpty() ) ft
->m_impl
->SetDescription (ftInfo
.GetDescription ()) ;
653 if (! ftInfo
.GetIconFile().IsEmpty() ) ft
->SetDefaultIcon (ftInfo
.GetIconFile(), ftInfo
.GetIconIndex() );
659 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
660 const wxString
& verb
,
661 bool WXUNUSED(overwriteprompt
))
663 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
664 _T("SetCommand() needs an extension and a verb") );
666 if ( !EnsureExtKeyExists() )
669 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
671 if ( rkey
.Exists() && overwriteprompt
)
675 rkey
.QueryValue(wxT(""), old
);
679 _("Do you want to overwrite the command used to %s "
680 "files with extension \"%s\" ?\nCurrent value is \n%s, "
681 "\nNew value is \n%s %1"), // bug here FIX need %1 ??
686 _("Confirm registry update"),
687 wxYES_NO
| wxICON_QUESTION
697 // 1. translate '%s' to '%1' instead of always adding it
698 // 2. create DDEExec value if needed (undo GetCommand)
699 return rkey
.Create() && rkey
.SetValue(_T(""), cmd
+ _T(" \"%1\"") );
703 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
705 wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("SetMimeType() needs extension") );
707 if ( !EnsureExtKeyExists() )
710 // VZ: is this really useful? (FIXME)
714 // make up a default value for it
716 wxSplitPath(GetCommand(_T("open")), NULL, &cmd, NULL);
717 mimeType << _T("application/x-") << cmd;
721 mimeType = mimeTypeOrig;
724 wxRegKey rkey(wxRegKey::HKCR, m_ext);
725 return rkey.Create() && rkey.SetValue(_T("Content Type"), mimeType);
729 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
731 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetDefaultIcon() needs extension") );
732 wxCHECK_MSG( !m_strFileType
.IsEmpty(), FALSE
, _T("File key not found") );
733 // the next line fails on a SMBshare, I think because it is case mangled
734 // wxCHECK_MSG( !wxFileExists(cmd), FALSE, _T("Icon file not found.") );
736 if ( !EnsureExtKeyExists() )
739 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
741 return rkey
.Create() &&
742 rkey
.SetValue(_T(""),
743 wxString::Format(_T("%s,%d"), cmd
.c_str(), index
));
746 bool wxFileTypeImpl::SetDescription (const wxString
& desc
)
748 wxCHECK_MSG( !m_strFileType
.IsEmpty(), FALSE
, _T("File key not found") );
749 wxCHECK_MSG( !desc
.IsEmpty(), FALSE
, _T("No file description supplied") );
751 if ( !EnsureExtKeyExists() )
754 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
);
756 return rkey
.Create() &&
757 rkey
.SetValue(_T(""), desc
);
760 // ----------------------------------------------------------------------------
761 // remove file association
762 // ----------------------------------------------------------------------------
764 bool wxFileTypeImpl::Unassociate()
767 if ( !RemoveOpenCommand() )
769 if ( !RemoveDefaultIcon() )
771 if ( !RemoveMimeType() )
773 if ( !RemoveDescription() )
777 //this might hold other keys, eg some have CSLID keys
780 // delete the root key
781 wxRegKey key(wxRegKey::HKCR, m_ext);
783 result = key.DeleteSelf();
789 bool wxFileTypeImpl::RemoveOpenCommand()
791 return RemoveCommand(_T("open"));
794 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
796 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
797 _T("RemoveCommand() needs an extension and a verb") );
799 wxString sKey
= m_strFileType
;
800 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
802 // if the key already doesn't exist, it's a success
803 return !rkey
.Exists() || rkey
.DeleteSelf();
806 bool wxFileTypeImpl::RemoveMimeType()
808 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("RemoveMimeType() needs extension") );
810 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
811 return !rkey
.Exists() || rkey
.DeleteSelf();
814 bool wxFileTypeImpl::RemoveDefaultIcon()
816 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
817 _T("RemoveDefaultIcon() needs extension") );
819 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
820 return !rkey
.Exists() || rkey
.DeleteSelf();
823 bool wxFileTypeImpl::RemoveDescription()
825 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
826 _T("RemoveDescription() needs extension") );
828 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
);
829 return !rkey
.Exists() || rkey
.DeleteSelf();
835 #endif // wxUSE_MIMETYPE