]>
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 /////////////////////////////////////////////////////////////////////////////
12 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
13 #pragma implementation "mimetype.h"
16 // for compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
26 #include "wx/string.h"
29 #include "wx/msgdlg.h"
35 #include "wx/iconloc.h"
37 #include "wx/dynarray.h"
38 #include "wx/confbase.h"
41 #include "wx/msw/registry.h"
42 #include "wx/msw/private.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 // this function replaces Microsoft %1 with Unix-like %s
78 static bool CanonicalizeParams(wxString
& command
)
80 // transform it from '%1' to '%s' style format string (now also test for %L
81 // as apparently MS started using it as well for the same purpose)
83 // NB: we don't make any attempt to verify that the string is valid, i.e.
84 // doesn't contain %2, or second %1 or .... But we do make sure that we
85 // return a string with _exactly_ one '%s'!
86 bool foundFilename
= false;
87 size_t len
= command
.length();
88 for ( size_t n
= 0; (n
< len
) && !foundFilename
; n
++ )
90 if ( command
[n
] == wxT('%') &&
92 (command
[n
+ 1] == wxT('1') || command
[n
+ 1] == wxT('L')) )
94 // replace it with '%s'
95 command
[n
+ 1] = wxT('s');
101 return foundFilename
;
104 void wxFileTypeImpl::Init(const wxString
& strFileType
, const wxString
& ext
)
106 // VZ: does it? (FIXME)
107 wxCHECK_RET( !ext
.empty(), _T("needs an extension") );
109 if ( ext
[0u] != wxT('.') ) {
114 m_strFileType
= strFileType
;
115 if ( !strFileType
) {
116 m_strFileType
= m_ext
.AfterFirst('.') + _T("_auto_file");
120 wxString
wxFileTypeImpl::GetVerbPath(const wxString
& verb
) const
123 path
<< m_strFileType
<< _T("\\shell\\") << verb
<< _T("\\command");
127 size_t wxFileTypeImpl::GetAllCommands(wxArrayString
*verbs
,
128 wxArrayString
*commands
,
129 const wxFileType::MessageParameters
& params
) const
131 wxCHECK_MSG( !m_ext
.empty(), 0, _T("GetAllCommands() needs an extension") );
133 if ( m_strFileType
.empty() )
135 // get it from the registry
136 wxFileTypeImpl
*self
= wxConstCast(this, wxFileTypeImpl
);
137 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
138 if ( !rkey
.Exists() || !rkey
.QueryValue(wxEmptyString
, self
->m_strFileType
) )
140 wxLogDebug(_T("Can't get the filetype for extension '%s'."),
147 // enum all subkeys of HKCR\filetype\shell
149 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell"));
152 bool ok
= rkey
.GetFirstKey(verb
, dummy
);
155 wxString command
= wxFileType::ExpandCommand(GetCommand(verb
), params
);
157 // we want the open bverb to eb always the first
159 if ( verb
.CmpNoCase(_T("open")) == 0 )
162 verbs
->Insert(verb
, 0);
164 commands
->Insert(command
, 0);
166 else // anything else than "open"
171 commands
->Add(command
);
176 ok
= rkey
.GetNextKey(verb
, dummy
);
182 // ----------------------------------------------------------------------------
183 // modify the registry database
184 // ----------------------------------------------------------------------------
186 bool wxFileTypeImpl::EnsureExtKeyExists()
188 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
189 if ( !rkey
.Exists() )
191 if ( !rkey
.Create() || !rkey
.SetValue(wxEmptyString
, m_strFileType
) )
193 wxLogError(_("Failed to create registry entry for '%s' files."),
202 // ----------------------------------------------------------------------------
203 // get the command to use
204 // ----------------------------------------------------------------------------
206 wxString
wxFileTypeImpl::GetCommand(const wxChar
*verb
) const
208 // suppress possible error messages
212 if ( wxRegKey(wxRegKey::HKCR
, m_ext
+ _T("\\shell")).Exists() )
214 if ( wxRegKey(wxRegKey::HKCR
, m_strFileType
+ _T("\\shell")).Exists() )
215 strKey
= m_strFileType
;
220 return wxEmptyString
;
223 strKey
<< wxT("\\shell\\") << verb
;
224 wxRegKey
key(wxRegKey::HKCR
, strKey
+ _T("\\command"));
226 if ( key
.Open(wxRegKey::Read
) ) {
227 // it's the default value of the key
228 if ( key
.QueryValue(wxEmptyString
, command
) ) {
229 bool foundFilename
= CanonicalizeParams(command
);
232 // look whether we must issue some DDE requests to the application
233 // (and not just launch it)
234 strKey
+= _T("\\DDEExec");
235 wxRegKey
keyDDE(wxRegKey::HKCR
, strKey
);
236 if ( keyDDE
.Open(wxRegKey::Read
) ) {
237 wxString ddeCommand
, ddeServer
, ddeTopic
;
238 keyDDE
.QueryValue(wxEmptyString
, ddeCommand
);
239 ddeCommand
.Replace(_T("%1"), _T("%s"));
241 wxRegKey
keyServer(wxRegKey::HKCR
, strKey
+ _T("\\Application"));
242 keyServer
.QueryValue(wxEmptyString
, ddeServer
);
243 wxRegKey
keyTopic(wxRegKey::HKCR
, strKey
+ _T("\\Topic"));
244 keyTopic
.QueryValue(wxEmptyString
, ddeTopic
);
246 if (ddeTopic
.empty())
247 ddeTopic
= wxT("System");
249 // HACK: we use a special feature of wxExecute which exists
250 // just because we need it here: it will establish DDE
251 // conversation with the program it just launched
252 command
.Prepend(_T("WX_DDE#"));
253 command
<< _T('#') << ddeServer
254 << _T('#') << ddeTopic
255 << _T('#') << ddeCommand
;
259 if ( !foundFilename
)
261 // we didn't find any '%1' - the application doesn't know which
262 // file to open (note that we only do it if there is no DDEExec
265 // HACK: append the filename at the end, hope that it will do
266 command
<< wxT(" %s");
270 //else: no such file type or no value, will return empty string
276 wxFileTypeImpl::GetOpenCommand(wxString
*openCmd
,
277 const wxFileType::MessageParameters
& params
)
280 wxString cmd
= GetCommand(wxT("open"));
282 *openCmd
= wxFileType::ExpandCommand(cmd
, params
);
284 return !openCmd
->empty();
288 wxFileTypeImpl::GetPrintCommand(wxString
*printCmd
,
289 const wxFileType::MessageParameters
& params
)
292 wxString cmd
= GetCommand(wxT("print"));
294 *printCmd
= wxFileType::ExpandCommand(cmd
, params
);
296 return !printCmd
->empty();
299 // ----------------------------------------------------------------------------
300 // getting other stuff
301 // ----------------------------------------------------------------------------
303 // TODO this function is half implemented
304 bool wxFileTypeImpl::GetExtensions(wxArrayString
& extensions
)
306 if ( m_ext
.empty() ) {
307 // the only way to get the list of extensions from the file type is to
308 // scan through all extensions in the registry - too slow...
313 extensions
.Add(m_ext
);
315 // it's a lie too, we don't return _all_ extensions...
320 bool wxFileTypeImpl::GetMimeType(wxString
*mimeType
) const
322 // suppress possible error messages
324 wxRegKey
key(wxRegKey::HKCR
, m_ext
);
326 return key
.Open(wxRegKey::Read
) &&
327 key
.QueryValue(wxT("Content Type"), *mimeType
);
330 bool wxFileTypeImpl::GetMimeTypes(wxArrayString
& mimeTypes
) const
334 if ( !GetMimeType(&s
) )
345 bool wxFileTypeImpl::GetIcon(wxIconLocation
*iconLoc
) const
348 strIconKey
<< m_strFileType
<< wxT("\\DefaultIcon");
350 // suppress possible error messages
352 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
354 if ( key
.Open(wxRegKey::Read
) ) {
356 // it's the default value of the key
357 if ( key
.QueryValue(wxEmptyString
, strIcon
) ) {
358 // the format is the following: <full path to file>, <icon index>
359 // NB: icon index may be negative as well as positive and the full
360 // path may contain the environment variables inside '%'
361 wxString strFullPath
= strIcon
.BeforeLast(wxT(',')),
362 strIndex
= strIcon
.AfterLast(wxT(','));
364 // index may be omitted, in which case BeforeLast(',') is empty and
365 // AfterLast(',') is the whole string
366 if ( strFullPath
.empty() ) {
367 strFullPath
= strIndex
;
373 iconLoc
->SetFileName(wxExpandEnvVars(strFullPath
));
375 iconLoc
->SetIndex(wxAtoi(strIndex
));
382 // no such file type or no value or incorrect icon entry
386 bool wxFileTypeImpl::GetDescription(wxString
*desc
) const
388 // suppress possible error messages
390 wxRegKey
key(wxRegKey::HKCR
, m_strFileType
);
392 if ( key
.Open(wxRegKey::Read
) ) {
393 // it's the default value of the key
394 if ( key
.QueryValue(wxEmptyString
, *desc
) ) {
404 wxMimeTypesManagerImpl::CreateFileType(const wxString
& filetype
, const wxString
& ext
)
406 wxFileType
*fileType
= new wxFileType
;
407 fileType
->m_impl
->Init(filetype
, ext
);
411 // extension -> file type
413 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString
& ext
)
415 // add the leading point if necessary
417 if ( ext
[0u] != wxT('.') ) {
422 // suppress possible error messages
425 bool knownExtension
= false;
427 wxString strFileType
;
428 wxRegKey
key(wxRegKey::HKCR
, str
);
429 if ( key
.Open(wxRegKey::Read
) ) {
430 // it's the default value of the key
431 if ( key
.QueryValue(wxEmptyString
, strFileType
) ) {
432 // create the new wxFileType object
433 return CreateFileType(strFileType
, ext
);
436 // this extension doesn't have a filetype, but it's known to the
437 // system and may be has some other useful keys (open command or
438 // content-type), so still return a file type object for it
439 knownExtension
= true;
443 if ( !knownExtension
)
449 return CreateFileType(wxEmptyString
, ext
);
454 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
456 wxFileType *fileType = GetFileTypeFromExtension(ext);
459 fileType = CreateFileType(wxEmptyString, ext);
466 // MIME type -> extension -> file type
468 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString
& mimeType
)
470 wxString strKey
= MIME_DATABASE_KEY
;
473 // suppress possible error messages
477 wxRegKey
key(wxRegKey::HKCR
, strKey
);
478 if ( key
.Open(wxRegKey::Read
) ) {
479 if ( key
.QueryValue(wxT("Extension"), ext
) ) {
480 return GetFileTypeFromExtension(ext
);
488 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString
& mimetypes
)
490 // enumerate all keys under MIME_DATABASE_KEY
491 wxRegKey
key(wxRegKey::HKCR
, MIME_DATABASE_KEY
);
495 bool cont
= key
.GetFirstKey(type
, cookie
);
500 cont
= key
.GetNextKey(type
, cookie
);
503 return mimetypes
.GetCount();
506 // ----------------------------------------------------------------------------
507 // create a new association
508 // ----------------------------------------------------------------------------
510 wxFileType
*wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo
& ftInfo
)
512 wxCHECK_MSG( !ftInfo
.GetExtensions().empty(), NULL
,
513 _T("Associate() needs extension") );
520 wxString ext
= ftInfo
.GetExtensions()[iExtCount
];
522 wxCHECK_MSG( !ext
.empty(), NULL
,
523 _T("Associate() needs non empty extension") );
525 if ( ext
[0u] != _T('.') )
526 extWithDot
= _T('.');
529 // start by setting the HKCR\\.ext entries
530 // default is filetype; content type is mimetype
531 const wxString
& filetypeOrig
= ftInfo
.GetShortDesc();
533 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
536 // create the mapping from the extension to the filetype
541 if ( filetypeOrig
.empty() )
543 // make it up from the extension
544 filetype
<< extWithDot
.c_str() + 1 << _T("_file");
548 // just use the provided one
549 filetype
= filetypeOrig
;
552 key
.SetValue(wxEmptyString
, filetype
);
557 // key already exists, maybe we want to change it ??
558 if (!filetypeOrig
.empty())
560 filetype
= filetypeOrig
;
561 key
.SetValue(wxEmptyString
, filetype
);
565 key
.QueryValue(wxEmptyString
, filetype
);
569 // now set a mimetypeif we have it, but ignore it if none
570 const wxString
& mimetype
= ftInfo
.GetMimeType();
571 if ( !mimetype
.empty() )
574 ok
= key
.SetValue(_T("Content Type"), mimetype
);
578 // create the MIME key
579 wxString strKey
= MIME_DATABASE_KEY
;
581 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
582 ok
= keyMIME
.Create();
586 // and provide a back link to the extension
587 keyMIME
.SetValue(_T("Extension"), extWithDot
);
593 // now make other extensions have the same filetype
595 for (iExtCount
=1; iExtCount
< ftInfo
.GetExtensionsCount(); iExtCount
++ )
597 ext
= ftInfo
.GetExtensions()[iExtCount
];
598 if ( ext
[0u] != _T('.') )
599 extWithDot
= _T('.');
602 wxRegKey
key(wxRegKey::HKCR
, extWithDot
);
603 if ( !key
.Exists() ) key
.Create();
604 key
.SetValue(wxEmptyString
, filetype
);
606 // now set any mimetypes we may have, but ignore it if none
607 const wxString
& mimetype
= ftInfo
.GetMimeType();
608 if ( !mimetype
.empty() )
611 ok
= key
.SetValue(_T("Content Type"), mimetype
);
615 // create the MIME key
616 wxString strKey
= MIME_DATABASE_KEY
;
618 wxRegKey
keyMIME(wxRegKey::HKCR
, strKey
);
619 ok
= keyMIME
.Create();
623 // and provide a back link to the extension
624 keyMIME
.SetValue(_T("Extension"), extWithDot
);
629 } // end of for loop; all extensions now point to HKCR\.ext\Default
631 // create the filetype key itself (it will be empty for now, but
632 // SetCommand(), SetDefaultIcon() &c will use it later)
633 wxRegKey
keyFT(wxRegKey::HKCR
, filetype
);
636 wxFileType
*ft
= CreateFileType(filetype
, extWithDot
);
640 if (! ftInfo
.GetOpenCommand ().empty() ) ft
->SetCommand (ftInfo
.GetOpenCommand (), wxT("open" ) );
641 if (! ftInfo
.GetPrintCommand().empty() ) ft
->SetCommand (ftInfo
.GetPrintCommand(), wxT("print" ) );
642 // chris: I don't like the ->m_impl-> here FIX this ??
643 if (! ftInfo
.GetDescription ().empty() ) ft
->m_impl
->SetDescription (ftInfo
.GetDescription ()) ;
644 if (! ftInfo
.GetIconFile().empty() ) ft
->SetDefaultIcon (ftInfo
.GetIconFile(), ftInfo
.GetIconIndex() );
651 bool wxFileTypeImpl::SetCommand(const wxString
& cmd
,
652 const wxString
& verb
,
653 bool WXUNUSED(overwriteprompt
))
655 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
656 _T("SetCommand() needs an extension and a verb") );
658 if ( !EnsureExtKeyExists() )
661 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
663 if ( rkey
.Exists() && overwriteprompt
)
667 rkey
.QueryValue(wxEmptyString
, old
);
671 _("Do you want to overwrite the command used to %s "
672 "files with extension \"%s\" ?\nCurrent value is \n%s, "
673 "\nNew value is \n%s %1"), // bug here FIX need %1 ??
678 _("Confirm registry update"),
679 wxYES_NO
| wxICON_QUESTION
689 // 1. translate '%s' to '%1' instead of always adding it
690 // 2. create DDEExec value if needed (undo GetCommand)
691 return rkey
.Create() && rkey
.SetValue(wxEmptyString
, cmd
+ _T(" \"%1\"") );
695 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
697 wxCHECK_MSG( !m_ext.empty(), false, _T("SetMimeType() needs extension") );
699 if ( !EnsureExtKeyExists() )
702 // VZ: is this really useful? (FIXME)
706 // make up a default value for it
708 wxSplitPath(GetCommand(_T("open")), NULL, &cmd, NULL);
709 mimeType << _T("application/x-") << cmd;
713 mimeType = mimeTypeOrig;
716 wxRegKey rkey(wxRegKey::HKCR, m_ext);
717 return rkey.Create() && rkey.SetValue(_T("Content Type"), mimeType);
721 bool wxFileTypeImpl::SetDefaultIcon(const wxString
& cmd
, int index
)
723 wxCHECK_MSG( !m_ext
.empty(), false, _T("SetDefaultIcon() needs extension") );
724 wxCHECK_MSG( !m_strFileType
.empty(), false, _T("File key not found") );
725 // the next line fails on a SMBshare, I think because it is case mangled
726 // wxCHECK_MSG( !wxFileExists(cmd), false, _T("Icon file not found.") );
728 if ( !EnsureExtKeyExists() )
731 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
733 return rkey
.Create() &&
734 rkey
.SetValue(wxEmptyString
,
735 wxString::Format(_T("%s,%d"), cmd
.c_str(), index
));
738 bool wxFileTypeImpl::SetDescription (const wxString
& desc
)
740 wxCHECK_MSG( !m_strFileType
.empty(), false, _T("File key not found") );
741 wxCHECK_MSG( !desc
.empty(), false, _T("No file description supplied") );
743 if ( !EnsureExtKeyExists() )
746 wxRegKey
rkey(wxRegKey::HKCR
, m_strFileType
);
748 return rkey
.Create() &&
749 rkey
.SetValue(wxEmptyString
, desc
);
752 // ----------------------------------------------------------------------------
753 // remove file association
754 // ----------------------------------------------------------------------------
756 bool wxFileTypeImpl::Unassociate()
759 if ( !RemoveOpenCommand() )
761 if ( !RemoveDefaultIcon() )
763 if ( !RemoveMimeType() )
765 if ( !RemoveDescription() )
769 //this might hold other keys, eg some have CSLID keys
772 // delete the root key
773 wxRegKey key(wxRegKey::HKCR, m_ext);
775 result = key.DeleteSelf();
781 bool wxFileTypeImpl::RemoveOpenCommand()
783 return RemoveCommand(_T("open"));
786 bool wxFileTypeImpl::RemoveCommand(const wxString
& verb
)
788 wxCHECK_MSG( !m_ext
.empty() && !verb
.empty(), false,
789 _T("RemoveCommand() needs an extension and a verb") );
791 wxRegKey
rkey(wxRegKey::HKCR
, GetVerbPath(verb
));
793 // if the key already doesn't exist, it's a success
794 return !rkey
.Exists() || rkey
.DeleteSelf();
797 bool wxFileTypeImpl::RemoveMimeType()
799 wxCHECK_MSG( !m_ext
.empty(), false, _T("RemoveMimeType() needs extension") );
801 wxRegKey
rkey(wxRegKey::HKCR
, m_ext
);
802 return !rkey
.Exists() || rkey
.DeleteSelf();
805 bool wxFileTypeImpl::RemoveDefaultIcon()
807 wxCHECK_MSG( !m_ext
.empty(), false,
808 _T("RemoveDefaultIcon() needs extension") );
810 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
+ _T("\\DefaultIcon"));
811 return !rkey
.Exists() || rkey
.DeleteSelf();
814 bool wxFileTypeImpl::RemoveDescription()
816 wxCHECK_MSG( !m_ext
.empty(), false,
817 _T("RemoveDescription() needs extension") );
819 wxRegKey
rkey (wxRegKey::HKCR
, m_strFileType
);
820 return !rkey
.Exists() || rkey
.DeleteSelf();
823 #endif // wxUSE_MIMETYPE