]>
git.saurik.com Git - wxWidgets.git/blob - src/msw/mimetype.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/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 /////////////////////////////////////////////////////////////////////////////
12 // for compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
21 #include "wx/msw/mimetype.h"
24 #include "wx/dynarray.h"
25 #include "wx/string.h"
31 #include "wx/msgdlg.h"
36 #include "wx/iconloc.h"
37 #include "wx/confbase.h"
40 #include "wx/msw/registry.h"
41 #include "wx/msw/private.h"
44 // other standard headers
47 // in case we're compiling in non-GUI mode
48 class WXDLLEXPORT wxIcon
;
50 // These classes use Windows registry to retrieve the required information.
52 // Keys used (not all of them are documented, so it might actually stop working
53 // in future versions of Windows...):
54 // 1. "HKCR\MIME\Database\Content Type" contains subkeys for all known MIME
55 // types, each key has a string value "Extension" which gives (dot preceded)
56 // extension for the files of this MIME type.
58 // 2. "HKCR\.ext" contains
59 // a) unnamed value containing the "filetype"
60 // b) value "Content Type" containing the MIME type
62 // 3. "HKCR\filetype" contains
63 // a) unnamed value containing the description
64 // b) subkey "DefaultIcon" with single unnamed value giving the icon index in
66 // c) shell\open\command and shell\open\print subkeys containing the commands
67 // to open/print the file (the positional parameters are introduced by %1,
68 // %2, ... in these strings, we change them to %s ourselves)
70 // although I don't know of any official documentation which mentions this
71 // location, uses it, so it isn't likely to change
72 static const wxChar
*MIME_DATABASE_KEY
= wxT("MIME\\Database\\Content Type\\");
74 // this function replaces Microsoft %1 with Unix-like %s
75 static bool CanonicalizeParams(wxString
& command
)
77 // transform it from '%1' to '%s' style format string (now also test for %L
78 // as apparently MS started using it as well for the same purpose)
80 // NB: we don't make any attempt to verify that the string is valid, i.e.
81 // doesn't contain %2, or second %1 or .... But we do make sure that we
82 // return a string with _exactly_ one '%s'!
83 bool foundFilename
= false;
84 size_t len
= command
.length();
85 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ )
87 if ( command
[n
] == wxT('%') &&
89 (command
[n
+ 1] == wxT('1') || command
[n
+ 1] == wxT('L')) )
91 // replace it with '%s'
92 command
[n
+ 1] = wxT('s');
101 void wxFileTypeImpl::Init(const wxString
& strFileType
, const wxString
& ext
)
103 // VZ: does it? (FIXME)
104 wxCHECK_RET( !ext
.empty(), _T("needs an extension") );
106 if ( ext
[0u] != wxT('.') ) {
111 m_strFileType
= strFileType
;
112 if ( !strFileType
) {
113 m_strFileType
= m_ext
.AfterFirst('.') + _T("_auto_file");
117 wxString
wxFileTypeImpl::GetVerbPath(const wxString
& verb
) const
120 path
<< m_strFileType
<< _T("\\shell\\") << verb
<< _T("\\command");
124 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
125 wxArrayString
*commands
,
126 const wxFileType::MessageParameters
& params
) const
128 wxCHECK_MSG( !m_ext
.empty(), 0, _T("GetAllCommands() needs an extension") );
130 if ( m_strFileType
.empty() )
132 // get it from the registry
133 wxFileTypeImpl
*self
= wxConstCast(this, wxFileTypeImpl
);
134 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
135 if ( !rkey
.Exists() || !rkey
.QueryValue(wxEmptyString
, self
->m_strFileType
) )
137 wxLogDebug(_T("Can't get the filetype for extension '%s'."),
144 // enum all subkeys of HKCR\filetype\shell
146 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell"));
149 bool ok
= rkey
.GetFirstKey(verb
, dummy
);
152 wxString command
= wxFileType::ExpandCommand(GetCommand(verb
), params
);
154 // we want the open bverb to eb always the first
156 if ( verb
.CmpNoCase(_T("open")) == 0 )
159 verbs
->Insert(verb
, 0);
161 commands
->Insert(command
, 0);
163 else // anything else than "open"
168 commands
->Add(command
);
173 ok
= rkey
.GetNextKey(verb
, dummy
);
179 // ----------------------------------------------------------------------------
180 // modify the registry database
181 // ----------------------------------------------------------------------------
183 bool wxFileTypeImpl::EnsureExtKeyExists()
185 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
186 if ( !rkey
.Exists() )
188 if ( !rkey
.Create() || !rkey
.SetValue(wxEmptyString
, m_strFileType
) )
190 wxLogError(_("Failed to create registry entry for '%s' files."),
199 // ----------------------------------------------------------------------------
200 // get the command to use
201 // ----------------------------------------------------------------------------
203 wxString
wxFileTypeImpl::GetCommand(const wxString
& verb
) const
205 // suppress possible error messages
209 if ( wxRegKey(wxRegKey::HKCR
, m_ext
+ _T("\\shell")).Exists() )
211 if ( wxRegKey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell")).Exists() )
212 strKey
= m_strFileType
;
217 return wxEmptyString
;
220 strKey
<< wxT("\\shell\\") << verb
;
221 wxRegKey
key(wxRegKey::HKCR
, strKey
+ _T("\\command"));
223 if ( key
.Open(wxRegKey::Read
) ) {
224 // it's the default value of the key
225 if ( key
.QueryValue(wxEmptyString
, command
) ) {
226 bool foundFilename
= CanonicalizeParams(command
);
229 // look whether we must issue some DDE requests to the application
230 // (and not just launch it)
231 strKey
+= _T("\\DDEExec");
232 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
233 if ( keyDDE
.Open(wxRegKey::Read
) ) {
234 wxString ddeCommand
, ddeServer
, ddeTopic
;
235 keyDDE
.QueryValue(wxEmptyString
, ddeCommand
);
236 ddeCommand
.Replace(_T("%1"), _T("%s"));
238 wxRegKey
keyServer(wxRegKey::HKCR
, strKey
+ _T("\\Application"));
239 keyServer
.QueryValue(wxEmptyString
, ddeServer
);
240 wxRegKey
keyTopic(wxRegKey::HKCR
, strKey
+ _T("\\Topic"));
241 keyTopic
.QueryValue(wxEmptyString
, ddeTopic
);
243 if (ddeTopic
.empty())
244 ddeTopic
= wxT("System");
246 // HACK: we use a special feature of wxExecute which exists
247 // just because we need it here: it will establish DDE
248 // conversation with the program it just launched
249 command
.Prepend(_T("WX_DDE#"));
250 command
<< _T('#') << ddeServer
251 << _T('#') << ddeTopic
252 << _T('#') << ddeCommand
;
256 if ( !foundFilename
)
258 // we didn't find any '%1' - the application doesn't know which
259 // file to open (note that we only do it if there is no DDEExec
262 // HACK: append the filename at the end, hope that it will do
263 command
<< wxT(" %s");
267 //else: no such file type or no value, will return empty string
273 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
274 const wxFileType::MessageParameters
& params
)
277 wxString cmd
= GetCommand(wxT("open"));
279 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
281 return !openCmd
->empty();
285 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
286 const wxFileType::MessageParameters
& params
)
289 wxString cmd
= GetCommand(wxT("print"));
291 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
293 return !printCmd
->empty();
296 // ----------------------------------------------------------------------------
297 // getting other stuff
298 // ----------------------------------------------------------------------------
300 // TODO this function is half implemented
301 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
303 if ( m_ext
.empty() ) {
304 // the only way to get the list of extensions from the file type is to
305 // scan through all extensions in the registry - too slow...
310 extensions
.Add(m_ext
);
312 // it's a lie too, we don't return _all_ extensions...
317 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
319 // suppress possible error messages
321 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
323 return key
.Open(wxRegKey::Read
) &&
324 key
.QueryValue(wxT("Content Type"), *mimeType
);
327 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
331 if ( !GetMimeType(&s
) )
342 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
345 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
347 // suppress possible error messages
349 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
351 if ( key
.Open(wxRegKey::Read
) ) {
353 // it's the default value of the key
354 if ( key
.QueryValue(wxEmptyString
, strIcon
) ) {
355 // the format is the following: <full path to file>, <icon index>
356 // NB: icon index may be negative as well as positive and the full
357 // path may contain the environment variables inside '%'
358 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
359 strIndex
= strIcon
.AfterLast(wxT(','));
361 // index may be omitted, in which case BeforeLast(',') is empty and
362 // AfterLast(',') is the whole string
363 if ( strFullPath
.empty() ) {
364 strFullPath
= strIndex
;
370 iconLoc
->SetFileName(wxExpandEnvVars(strFullPath
));
372 iconLoc
->SetIndex(wxAtoi(strIndex
));
379 // no such file type or no value or incorrect icon entry
383 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
385 // suppress possible error messages
387 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
389 if ( key
.Open(wxRegKey::Read
) ) {
390 // it's the default value of the key
391 if ( key
.QueryValue(wxEmptyString
, *desc
) ) {
401 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
403 wxFileType
*fileType
= new wxFileType
;
404 fileType
->m_impl
->Init(filetype
, ext
);
408 // extension -> file type
410 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
412 // add the leading point if necessary
414 if ( ext
[0u] != wxT('.') ) {
419 // suppress possible error messages
422 bool knownExtension
= false;
424 wxString strFileType
;
425 wxRegKey
key(wxRegKey::HKCR
, str
);
426 if ( key
.Open(wxRegKey::Read
) ) {
427 // it's the default value of the key
428 if ( key
.QueryValue(wxEmptyString
, strFileType
) ) {
429 // create the new wxFileType object
430 return CreateFileType(strFileType
, ext
);
433 // this extension doesn't have a filetype, but it's known to the
434 // system and may be has some other useful keys (open command or
435 // content-type), so still return a file type object for it
436 knownExtension
= true;
440 if ( !knownExtension
)
446 return CreateFileType(wxEmptyString
, ext
);
451 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
453 wxFileType *fileType = GetFileTypeFromExtension(ext);
456 fileType = CreateFileType(wxEmptyString, ext);
463 // MIME type -> extension -> file type
465 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
467 wxString strKey
= MIME_DATABASE_KEY
;
470 // suppress possible error messages
474 wxRegKey
key(wxRegKey::HKCR
, strKey
);
475 if ( key
.Open(wxRegKey::Read
) ) {
476 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
477 return GetFileTypeFromExtension(ext
);
485 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
487 // enumerate all keys under MIME_DATABASE_KEY
488 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
492 bool cont
= key
.GetFirstKey(type
, cookie
);
497 cont
= key
.GetNextKey(type
, cookie
);
500 return mimetypes
.GetCount();
503 // ----------------------------------------------------------------------------
504 // create a new association
505 // ----------------------------------------------------------------------------
507 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
509 wxCHECK_MSG( !ftInfo
.GetExtensions().empty(), NULL
,
510 _T("Associate() needs extension") );
513 size_t iExtCount
= 0;
517 wxString ext
= ftInfo
.GetExtensions()[iExtCount
];
519 wxCHECK_MSG( !ext
.empty(), NULL
,
520 _T("Associate() needs non empty extension") );
522 if ( ext
[0u] != _T('.') )
523 extWithDot
= _T('.');
526 // start by setting the HKCR\\.ext entries
527 // default is filetype; content type is mimetype
528 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
530 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
533 // create the mapping from the extension to the filetype
538 if ( filetypeOrig
.empty() )
540 // make it up from the extension
541 filetype
<< extWithDot
.c_str() + 1 << _T("_file");
545 // just use the provided one
546 filetype
= filetypeOrig
;
549 key
.SetValue(wxEmptyString
, filetype
);
554 // key already exists, maybe we want to change it ??
555 if (!filetypeOrig
.empty())
557 filetype
= filetypeOrig
;
558 key
.SetValue(wxEmptyString
, filetype
);
562 key
.QueryValue(wxEmptyString
, filetype
);
566 // now set a mimetypeif we have it, but ignore it if none
567 const wxString
& mimetype
= ftInfo
.GetMimeType();
568 if ( !mimetype
.empty() )
571 ok
= key
.SetValue(_T("Content Type"), mimetype
);
575 // create the MIME key
576 wxString strKey
= MIME_DATABASE_KEY
;
578 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
579 ok
= keyMIME
.Create();
583 // and provide a back link to the extension
584 keyMIME
.SetValue(_T("Extension"), extWithDot
);
590 // now make other extensions have the same filetype
592 for (iExtCount
=1; iExtCount
< ftInfo
.GetExtensionsCount(); iExtCount
++ )
594 ext
= ftInfo
.GetExtensions()[iExtCount
];
595 if ( ext
[0u] != _T('.') )
596 extWithDot
= _T('.');
599 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
600 if ( !key
.Exists() ) key
.Create();
601 key
.SetValue(wxEmptyString
, filetype
);
603 // now set any mimetypes we may have, but ignore it if none
604 const wxString
& mimetype
= ftInfo
.GetMimeType();
605 if ( !mimetype
.empty() )
608 ok
= key
.SetValue(_T("Content Type"), mimetype
);
612 // create the MIME key
613 wxString strKey
= MIME_DATABASE_KEY
;
615 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
616 ok
= keyMIME
.Create();
620 // and provide a back link to the extension
621 keyMIME
.SetValue(_T("Extension"), extWithDot
);
626 } // end of for loop; all extensions now point to HKCR\.ext\Default
628 // create the filetype key itself (it will be empty for now, but
629 // SetCommand(), SetDefaultIcon() &c will use it later)
630 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
633 wxFileType
*ft
= CreateFileType(filetype
, extWithDot
);
637 if (! ftInfo
.GetOpenCommand ().empty() ) ft
->SetCommand (ftInfo
.GetOpenCommand (), wxT("open" ) );
638 if (! ftInfo
.GetPrintCommand().empty() ) ft
->SetCommand (ftInfo
.GetPrintCommand(), wxT("print" ) );
639 // chris: I don't like the ->m_impl-> here FIX this ??
640 if (! ftInfo
.GetDescription ().empty() ) ft
->m_impl
->SetDescription (ftInfo
.GetDescription ()) ;
641 if (! ftInfo
.GetIconFile().empty() ) ft
->SetDefaultIcon (ftInfo
.GetIconFile(), ftInfo
.GetIconIndex() );
648 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
649 const wxString
& verb
,
650 bool WXUNUSED(overwriteprompt
))
652 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
653 _T("SetCommand() needs an extension and a verb") );
655 if ( !EnsureExtKeyExists() )
658 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
660 if ( rkey
.Exists() && overwriteprompt
)
664 rkey
.QueryValue(wxEmptyString
, old
);
668 _("Do you want to overwrite the command used to %s "
669 "files with extension \"%s\" ?\nCurrent value is \n%s, "
670 "\nNew value is \n%s %1"), // bug here FIX need %1 ??
675 _("Confirm registry update"),
676 wxYES_NO
| wxICON_QUESTION
686 // 1. translate '%s' to '%1' instead of always adding it
687 // 2. create DDEExec value if needed (undo GetCommand)
688 return rkey
.Create() && rkey
.SetValue(wxEmptyString
, cmd
+ _T(" \"%1\"") );
692 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
694 wxCHECK_MSG( !m_ext.empty(), false, _T("SetMimeType() needs extension") );
696 if ( !EnsureExtKeyExists() )
699 // VZ: is this really useful? (FIXME)
703 // make up a default value for it
705 wxSplitPath(GetCommand(_T("open")), NULL, &cmd, NULL);
706 mimeType << _T("application/x-") << cmd;
710 mimeType = mimeTypeOrig;
713 wxRegKey rkey(wxRegKey::HKCR, m_ext);
714 return rkey.Create() && rkey.SetValue(_T("Content Type"), mimeType);
718 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
720 wxCHECK_MSG( !m_ext
.empty(), false, _T("SetDefaultIcon() needs extension") );
721 wxCHECK_MSG( !m_strFileType
.empty(), false, _T("File key not found") );
722 // the next line fails on a SMBshare, I think because it is case mangled
723 // wxCHECK_MSG( !wxFileExists(cmd), false, _T("Icon file not found.") );
725 if ( !EnsureExtKeyExists() )
728 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
730 return rkey
.Create() &&
731 rkey
.SetValue(wxEmptyString
,
732 wxString::Format(_T("%s,%d"), cmd
.c_str(), index
));
735 bool wxFileTypeImpl::SetDescription (const wxString
& desc
)
737 wxCHECK_MSG( !m_strFileType
.empty(), false, _T("File key not found") );
738 wxCHECK_MSG( !desc
.empty(), false, _T("No file description supplied") );
740 if ( !EnsureExtKeyExists() )
743 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
);
745 return rkey
.Create() &&
746 rkey
.SetValue(wxEmptyString
, desc
);
749 // ----------------------------------------------------------------------------
750 // remove file association
751 // ----------------------------------------------------------------------------
753 bool wxFileTypeImpl::Unassociate()
756 if ( !RemoveOpenCommand() )
758 if ( !RemoveDefaultIcon() )
760 if ( !RemoveMimeType() )
762 if ( !RemoveDescription() )
766 //this might hold other keys, eg some have CSLID keys
769 // delete the root key
770 wxRegKey key(wxRegKey::HKCR, m_ext);
772 result = key.DeleteSelf();
778 bool wxFileTypeImpl::RemoveOpenCommand()
780 return RemoveCommand(_T("open"));
783 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
785 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
786 _T("RemoveCommand() needs an extension and a verb") );
788 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
790 // if the key already doesn't exist, it's a success
791 return !rkey
.Exists() || rkey
.DeleteSelf();
794 bool wxFileTypeImpl::RemoveMimeType()
796 wxCHECK_MSG( !m_ext
.empty(), false, _T("RemoveMimeType() needs extension") );
798 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
799 return !rkey
.Exists() || rkey
.DeleteSelf();
802 bool wxFileTypeImpl::RemoveDefaultIcon()
804 wxCHECK_MSG( !m_ext
.empty(), false,
805 _T("RemoveDefaultIcon() needs extension") );
807 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
808 return !rkey
.Exists() || rkey
.DeleteSelf();
811 bool wxFileTypeImpl::RemoveDescription()
813 wxCHECK_MSG( !m_ext
.empty(), false,
814 _T("RemoveDescription() needs extension") );
816 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
);
817 return !rkey
.Exists() || rkey
.DeleteSelf();
820 #endif // wxUSE_MIMETYPE