]>
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 // 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
);
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
);
458 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
460 wxFileType *fileType = GetFileTypeFromExtension(ext);
463 fileType = CreateFileType(wxEmptyString, ext);
470 // MIME type -> extension -> file type
472 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
474 wxString strKey
= MIME_DATABASE_KEY
;
477 // suppress possible error messages
481 wxRegKey
key(wxRegKey::HKCR
, strKey
);
483 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
484 return GetFileTypeFromExtension(ext
);
492 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
494 // enumerate all keys under MIME_DATABASE_KEY
495 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
499 bool cont
= key
.GetFirstKey(type
, cookie
);
504 cont
= key
.GetNextKey(type
, cookie
);
507 return mimetypes
.GetCount();
510 // ----------------------------------------------------------------------------
511 // create a new association
512 // ----------------------------------------------------------------------------
514 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
516 wxCHECK_MSG( !ftInfo
.GetExtensions().IsEmpty(), NULL
,
517 _T("Associate() needs extension") );
524 wxString ext
= ftInfo
.GetExtensions()[iExtCount
];
526 wxCHECK_MSG( !ext
.empty(), NULL
,
527 _T("Associate() needs non empty extension") );
529 if ( ext
[0u] != _T('.') )
530 extWithDot
= _T('.');
533 // start by setting the HKCR\\.ext entries
534 // default is filetype; content type is mimetype
535 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
537 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
540 // create the mapping from the extension to the filetype
545 if ( filetypeOrig
.empty() )
547 // make it up from the extension
548 filetype
<< extWithDot
.c_str() + 1 << _T("_file");
552 // just use the provided one
553 filetype
= filetypeOrig
;
556 ok
= key
.SetValue(_T(""), filetype
);
561 // key already exists, maybe we want to change it ??
562 if (!filetypeOrig
.empty())
564 filetype
= filetypeOrig
;
565 ok
= key
.SetValue(_T(""), filetype
);
569 ok
= key
.QueryValue(_T(""), filetype
);
572 // now set a mimetypeif we have it, but ignore it if none
573 const wxString
& mimetype
= ftInfo
.GetMimeType();
574 if ( !mimetype
.empty() )
577 ok
= key
.SetValue(_T("Content Type"), mimetype
);
581 // create the MIME key
582 wxString strKey
= MIME_DATABASE_KEY
;
584 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
585 ok
= keyMIME
.Create();
589 // and provide a back link to the extension
590 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
596 // now make other extensions have the same filetype
598 for (iExtCount
=1; iExtCount
< ftInfo
.GetExtensionsCount(); iExtCount
++ )
600 ext
= ftInfo
.GetExtensions()[iExtCount
];
601 if ( ext
[0u] != _T('.') )
602 extWithDot
= _T('.');
605 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
606 if ( !key
.Exists() ) ok
= key
.Create();
607 ok
= key
.SetValue(_T(""), filetype
);
609 // now set any mimetypes we may have, but ignore it if none
610 const wxString
& mimetype
= ftInfo
.GetMimeType();
611 if ( !mimetype
.empty() )
614 ok
= key
.SetValue(_T("Content Type"), mimetype
);
618 // create the MIME key
619 wxString strKey
= MIME_DATABASE_KEY
;
621 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
622 ok
= keyMIME
.Create();
626 // and provide a back link to the extension
627 ok
= keyMIME
.SetValue(_T("Extension"), extWithDot
);
633 } // end of for loop; all extensions now point to HKCR\.ext\Default
635 // create the filetype key itself (it will be empty for now, but
636 // SetCommand(), SetDefaultIcon() &c will use it later)
637 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
640 wxFileType
*ft
= NULL
;
641 ft
= CreateFileType(filetype
, extWithDot
);
645 if (! ftInfo
.GetOpenCommand ().IsEmpty() ) ft
->SetCommand (ftInfo
.GetOpenCommand (), wxT("open" ) );
646 if (! ftInfo
.GetPrintCommand().IsEmpty() ) ft
->SetCommand (ftInfo
.GetPrintCommand(), wxT("print" ) );
647 // chris: I don't like the ->m_impl-> here FIX this ??
648 if (! ftInfo
.GetDescription ().IsEmpty() ) ft
->m_impl
->SetDescription (ftInfo
.GetDescription ()) ;
649 if (! ftInfo
.GetIconFile().IsEmpty() ) ft
->SetDefaultIcon (ftInfo
.GetIconFile(), ftInfo
.GetIconIndex() );
655 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
656 const wxString
& verb
,
657 bool WXUNUSED(overwriteprompt
))
659 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
660 _T("SetCommand() needs an extension and a verb") );
662 if ( !EnsureExtKeyExists() )
665 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
667 if ( rkey
.Exists() && overwriteprompt
)
671 rkey
.QueryValue(wxT(""), old
);
675 _("Do you want to overwrite the command used to %s "
676 "files with extension \"%s\" ?\nCurrent value is \n%s, "
677 "\nNew value is \n%s %1"), // bug here FIX need %1 ??
682 _("Confirm registry update"),
683 wxYES_NO
| wxICON_QUESTION
693 // 1. translate '%s' to '%1' instead of always adding it
694 // 2. create DDEExec value if needed (undo GetCommand)
695 return rkey
.Create() && rkey
.SetValue(_T(""), cmd
+ _T(" \"%1\"") );
699 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
701 wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("SetMimeType() needs extension") );
703 if ( !EnsureExtKeyExists() )
706 // VZ: is this really useful? (FIXME)
710 // make up a default value for it
712 wxSplitPath(GetCommand(_T("open")), NULL, &cmd, NULL);
713 mimeType << _T("application/x-") << cmd;
717 mimeType = mimeTypeOrig;
720 wxRegKey rkey(wxRegKey::HKCR, m_ext);
721 return rkey.Create() && rkey.SetValue(_T("Content Type"), mimeType);
725 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
727 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("SetDefaultIcon() needs extension") );
728 wxCHECK_MSG( !m_strFileType
.IsEmpty(), FALSE
, _T("File key not found") );
729 // the next line fails on a SMBshare, I think because it is case mangled
730 // wxCHECK_MSG( !wxFileExists(cmd), FALSE, _T("Icon file not found.") );
732 if ( !EnsureExtKeyExists() )
735 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
737 return rkey
.Create() &&
738 rkey
.SetValue(_T(""),
739 wxString::Format(_T("%s,%d"), cmd
.c_str(), index
));
742 bool wxFileTypeImpl::SetDescription (const wxString
& desc
)
744 wxCHECK_MSG( !m_strFileType
.IsEmpty(), FALSE
, _T("File key not found") );
745 wxCHECK_MSG( !desc
.IsEmpty(), FALSE
, _T("No file description supplied") );
747 if ( !EnsureExtKeyExists() )
750 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
);
752 return rkey
.Create() &&
753 rkey
.SetValue(_T(""), desc
);
756 // ----------------------------------------------------------------------------
757 // remove file association
758 // ----------------------------------------------------------------------------
760 bool wxFileTypeImpl::Unassociate()
763 if ( !RemoveOpenCommand() )
765 if ( !RemoveDefaultIcon() )
767 if ( !RemoveMimeType() )
769 if ( !RemoveDescription() )
773 //this might hold other keys, eg some have CSLID keys
776 // delete the root key
777 wxRegKey key(wxRegKey::HKCR, m_ext);
779 result = key.DeleteSelf();
785 bool wxFileTypeImpl::RemoveOpenCommand()
787 return RemoveCommand(_T("open"));
790 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
792 wxCHECK_MSG( !m_ext
.IsEmpty() && !verb
.IsEmpty(), FALSE
,
793 _T("RemoveCommand() needs an extension and a verb") );
795 wxString sKey
= m_strFileType
;
796 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
798 // if the key already doesn't exist, it's a success
799 return !rkey
.Exists() || rkey
.DeleteSelf();
802 bool wxFileTypeImpl::RemoveMimeType()
804 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
, _T("RemoveMimeType() needs extension") );
806 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
807 return !rkey
.Exists() || rkey
.DeleteSelf();
810 bool wxFileTypeImpl::RemoveDefaultIcon()
812 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
813 _T("RemoveDefaultIcon() needs extension") );
815 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
816 return !rkey
.Exists() || rkey
.DeleteSelf();
819 bool wxFileTypeImpl::RemoveDescription()
821 wxCHECK_MSG( !m_ext
.IsEmpty(), FALSE
,
822 _T("RemoveDescription() needs extension") );
824 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
);
825 return !rkey
.Exists() || rkey
.DeleteSelf();