]> git.saurik.com Git - wxWidgets.git/blob - src/msw/mimetype.cpp
corrections for Mac OS X
[wxWidgets.git] / src / msw / mimetype.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/mimetype.cpp
3 // Purpose: classes and functions to manage MIME types
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 23.09.98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license (part of wxExtra library)
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "mimetype.h"
14 #endif
15
16 // for compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 // this is Win32 only code
24 #ifndef __WIN16__
25
26 #ifndef WX_PRECOMP
27 #include "wx/string.h"
28 #if wxUSE_GUI
29 #include "wx/icon.h"
30 #include "wx/msgdlg.h"
31 #endif
32 #endif //WX_PRECOMP
33
34 #include "wx/log.h"
35 #include "wx/file.h"
36 #include "wx/intl.h"
37 #include "wx/dynarray.h"
38 #include "wx/confbase.h"
39
40 #ifdef __WXMSW__
41 #include "wx/msw/registry.h"
42 #include "windows.h"
43 #endif // OS
44
45 #include "wx/msw/mimetype.h"
46
47 // other standard headers
48 #include <ctype.h>
49
50 // in case we're compiling in non-GUI mode
51 class WXDLLEXPORT wxIcon;
52
53 // These classes use Windows registry to retrieve the required information.
54 //
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.
60 //
61 // 2. "HKCR\.ext" contains
62 // a) unnamed value containing the "filetype"
63 // b) value "Content Type" containing the MIME type
64 //
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
68 // an icon file
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)
72
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\\");
76
77 void wxFileTypeImpl::Init(const wxString& strFileType, const wxString& ext)
78 {
79 // VZ: does it? (FIXME)
80 wxCHECK_RET( !ext.IsEmpty(), _T("needs an extension") );
81
82 if ( ext[0u] != wxT('.') ) {
83 m_ext = wxT('.');
84 }
85 m_ext << ext;
86
87 m_strFileType = strFileType;
88 if ( !strFileType ) {
89 m_strFileType = m_ext.AfterFirst('.') + "_auto_file";
90 }
91 }
92
93 wxString wxFileTypeImpl::GetVerbPath(const wxString& verb) const
94 {
95 wxString path;
96 path << m_strFileType << _T("\\shell\\") << verb << _T("\\command");
97 return path;
98 }
99
100 size_t wxFileTypeImpl::GetAllCommands(wxArrayString *verbs,
101 wxArrayString *commands,
102 const wxFileType::MessageParameters& params) const
103 {
104 wxCHECK_MSG( !m_ext.IsEmpty(), 0, _T("GetAllCommands() needs an extension") );
105
106 if ( m_strFileType.IsEmpty() )
107 {
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) )
112 {
113 wxLogDebug(_T("Can't get the filetype for extension '%s'."),
114 m_ext.c_str());
115
116 return 0;
117 }
118 }
119
120 // enum all subkeys of HKCR\filetype\shell
121 size_t count = 0;
122 wxRegKey rkey(wxRegKey::HKCR, m_strFileType + _T("\\shell"));
123 long dummy;
124 wxString verb;
125 bool ok = rkey.GetFirstKey(verb, dummy);
126 while ( ok )
127 {
128 wxString command = wxFileType::ExpandCommand(GetCommand(verb), params);
129
130 // we want the open bverb to eb always the first
131
132 if ( verb.CmpNoCase(_T("open")) == 0 )
133 {
134 if ( verbs )
135 verbs->Insert(verb, 0);
136 if ( commands )
137 commands->Insert(command, 0);
138 }
139 else // anything else than "open"
140 {
141 if ( verbs )
142 verbs->Add(verb);
143 if ( commands )
144 commands->Add(command);
145 }
146
147 count++;
148
149 ok = rkey.GetNextKey(verb, dummy);
150 }
151
152 return count;
153 }
154
155 // ----------------------------------------------------------------------------
156 // modify the registry database
157 // ----------------------------------------------------------------------------
158
159 bool wxFileTypeImpl::EnsureExtKeyExists()
160 {
161 wxRegKey rkey(wxRegKey::HKCR, m_ext);
162 if ( !rkey.Exists() )
163 {
164 if ( !rkey.Create() || !rkey.SetValue(_T(""), m_strFileType) )
165 {
166 wxLogError(_("Failed to create registry entry for '%s' files."),
167 m_ext.c_str());
168 return FALSE;
169 }
170 }
171
172 return TRUE;
173 }
174
175 // ----------------------------------------------------------------------------
176 // get the command to use
177 // ----------------------------------------------------------------------------
178
179 wxString wxFileTypeImpl::GetCommand(const wxChar *verb) const
180 {
181 // suppress possible error messages
182 wxLogNull nolog;
183 wxString strKey;
184
185 if ( wxRegKey(wxRegKey::HKCR, m_ext + _T("\\shell")).Exists() )
186 strKey = m_ext;
187 if ( wxRegKey(wxRegKey::HKCR, m_strFileType + _T("\\shell")).Exists() )
188 strKey = m_strFileType;
189
190 if ( !strKey )
191 {
192 // no info
193 return wxEmptyString;
194 }
195
196 strKey << wxT("\\shell\\") << verb;
197 wxRegKey key(wxRegKey::HKCR, strKey + _T("\\command"));
198 wxString command;
199 if ( key.Open() ) {
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
204 // same purpose)
205
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('%') &&
213 (n + 1 < len) &&
214 (command[n + 1] == wxT('1') ||
215 command[n + 1] == wxT('L')) ) {
216 // replace it with '%s'
217 command[n + 1] = wxT('s');
218
219 foundFilename = TRUE;
220 }
221 }
222
223 #if wxUSE_IPC
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"));
232
233 wxRegKey(wxRegKey::HKCR, strKey + _T("\\Application")).
234 QueryValue(_T(""), ddeServer);
235 wxRegKey(wxRegKey::HKCR, strKey + _T("\\Topic")).
236 QueryValue(_T(""), ddeTopic);
237
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;
245 }
246 else
247 #endif // wxUSE_IPC
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
251 // subkey)
252 //
253 // HACK: append the filename at the end, hope that it will do
254 command << wxT(" %s");
255 }
256 }
257 }
258 //else: no such file type or no value, will return empty string
259
260 return command;
261 }
262
263 bool
264 wxFileTypeImpl::GetOpenCommand(wxString *openCmd,
265 const wxFileType::MessageParameters& params)
266 const
267 {
268 wxString cmd = GetCommand(wxT("open"));
269
270 *openCmd = wxFileType::ExpandCommand(cmd, params);
271
272 return !openCmd->IsEmpty();
273 }
274
275 bool
276 wxFileTypeImpl::GetPrintCommand(wxString *printCmd,
277 const wxFileType::MessageParameters& params)
278 const
279 {
280 wxString cmd = GetCommand(wxT("print"));
281
282 *printCmd = wxFileType::ExpandCommand(cmd, params);
283
284 return !printCmd->IsEmpty();
285 }
286
287 // ----------------------------------------------------------------------------
288 // getting other stuff
289 // ----------------------------------------------------------------------------
290
291 // TODO this function is half implemented
292 bool wxFileTypeImpl::GetExtensions(wxArrayString& extensions)
293 {
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...
297 return FALSE;
298 }
299 else {
300 extensions.Empty();
301 extensions.Add(m_ext);
302
303 // it's a lie too, we don't return _all_ extensions...
304 return TRUE;
305 }
306 }
307
308 bool wxFileTypeImpl::GetMimeType(wxString *mimeType) const
309 {
310 // suppress possible error messages
311 wxLogNull nolog;
312 wxRegKey key(wxRegKey::HKCR, m_ext);
313
314 return key.Open() && key.QueryValue(wxT("Content Type"), *mimeType);
315 }
316
317 bool wxFileTypeImpl::GetMimeTypes(wxArrayString& mimeTypes) const
318 {
319 wxString s;
320
321 if ( !GetMimeType(&s) )
322 {
323 return FALSE;
324 }
325
326 mimeTypes.Clear();
327 mimeTypes.Add(s);
328 return TRUE;
329 }
330
331
332 bool wxFileTypeImpl::GetIcon(wxIcon *icon,
333 wxString *iconFile,
334 int *iconIndex) const
335 {
336 #if wxUSE_GUI
337 wxString strIconKey;
338 strIconKey << m_strFileType << wxT("\\DefaultIcon");
339
340 // suppress possible error messages
341 wxLogNull nolog;
342 wxRegKey key(wxRegKey::HKCR, strIconKey);
343
344 if ( key.Open() ) {
345 wxString strIcon;
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(','));
353
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;
358 strIndex = wxT("0");
359 }
360
361 wxString strExpPath = wxExpandEnvVars(strFullPath);
362 // here we need C based counting!
363 int nIndex = wxAtoi(strIndex) - 1 ;
364
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());
371 break;
372
373 default:
374 icon->SetHICON((WXHICON)hIcon);
375 if ( iconIndex )
376 *iconIndex = nIndex;
377 if ( iconFile )
378 *iconFile = strFullPath;
379 return TRUE;
380 }
381 }
382 }
383
384 // no such file type or no value or incorrect icon entry
385 #endif // wxUSE_GUI
386
387 return FALSE;
388 }
389
390 bool wxFileTypeImpl::GetDescription(wxString *desc) const
391 {
392 // suppress possible error messages
393 wxLogNull nolog;
394 wxRegKey key(wxRegKey::HKCR, m_strFileType);
395
396 if ( key.Open() ) {
397 // it's the default value of the key
398 if ( key.QueryValue(wxT(""), *desc) ) {
399 return TRUE;
400 }
401 }
402
403 return FALSE;
404 }
405
406 // helper function
407 wxFileType *
408 wxMimeTypesManagerImpl::CreateFileType(const wxString& filetype, const wxString& ext)
409 {
410 wxFileType *fileType = new wxFileType;
411 fileType->m_impl->Init(filetype, ext);
412 return fileType;
413 }
414
415 // extension -> file type
416 wxFileType *
417 wxMimeTypesManagerImpl::GetFileTypeFromExtension(const wxString& ext)
418 {
419 // add the leading point if necessary
420 wxString str;
421 if ( ext[0u] != wxT('.') ) {
422 str = wxT('.');
423 }
424 str << ext;
425
426 // suppress possible error messages
427 wxLogNull nolog;
428
429 bool knownExtension = FALSE;
430
431 wxString strFileType;
432 wxRegKey key(wxRegKey::HKCR, str);
433 if ( key.Open() ) {
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);
438 }
439 else {
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;
444 }
445 }
446
447 if ( !knownExtension )
448 {
449 // unknown extension
450 return NULL;
451 }
452
453 return CreateFileType(wxEmptyString, ext);
454 }
455
456 wxFileType *
457 wxMimeTypesManagerImpl::GetOrAllocateFileTypeFromExtension(const wxString& ext)
458 {
459 wxFileType *fileType = GetFileTypeFromExtension(ext);
460 if ( !fileType )
461 {
462 fileType = CreateFileType(wxEmptyString, ext);
463 }
464
465 return fileType;
466 }
467
468
469 // MIME type -> extension -> file type
470 wxFileType *
471 wxMimeTypesManagerImpl::GetFileTypeFromMimeType(const wxString& mimeType)
472 {
473 wxString strKey = MIME_DATABASE_KEY;
474 strKey << mimeType;
475
476 // suppress possible error messages
477 wxLogNull nolog;
478
479 wxString ext;
480 wxRegKey key(wxRegKey::HKCR, strKey);
481 if ( key.Open() ) {
482 if ( key.QueryValue(wxT("Extension"), ext) ) {
483 return GetFileTypeFromExtension(ext);
484 }
485 }
486
487 // unknown MIME type
488 return NULL;
489 }
490
491 size_t wxMimeTypesManagerImpl::EnumAllFileTypes(wxArrayString& mimetypes)
492 {
493 // enumerate all keys under MIME_DATABASE_KEY
494 wxRegKey key(wxRegKey::HKCR, MIME_DATABASE_KEY);
495
496 wxString type;
497 long cookie;
498 bool cont = key.GetFirstKey(type, cookie);
499 while ( cont )
500 {
501 mimetypes.Add(type);
502
503 cont = key.GetNextKey(type, cookie);
504 }
505
506 return mimetypes.GetCount();
507 }
508
509 // ----------------------------------------------------------------------------
510 // create a new association
511 // ----------------------------------------------------------------------------
512
513 wxFileType *wxMimeTypesManagerImpl::Associate(const wxFileTypeInfo& ftInfo)
514 {
515 wxCHECK_MSG( !ftInfo.GetExtensions().IsEmpty(), NULL,
516 _T("Associate() needs extension") );
517
518 const wxString& ext = ftInfo.GetExtensions()[0u];
519
520 wxCHECK_MSG( !ext.empty(), NULL,
521 _T("Associate() needs non empty extension") );
522
523 wxString extWithDot;
524 if ( ext[0u] != _T('.') )
525 extWithDot = _T('.');
526 extWithDot += ext;
527
528 wxRegKey key(wxRegKey::HKCR, extWithDot);
529 wxFileType *ft = NULL;
530 if ( !key.Exists() )
531 {
532 wxString filetype;
533
534 // create the mapping from the extension to the filetype
535 bool ok = key.Create();
536 if ( ok )
537 {
538 const wxString& filetypeOrig = ftInfo.GetShortDesc();
539 if ( filetypeOrig.empty() )
540 {
541 // make it up from the extension
542 filetype << extWithDot.c_str() + 1 << _T("_auto_file");
543 }
544 else
545 {
546 // just use the provided one
547 filetype = filetypeOrig;
548 }
549
550 ok = key.SetValue(_T(""), filetype);
551 }
552
553 const wxString& mimetype = ftInfo.GetMimeType();
554 if ( ok && !mimetype.empty() )
555 {
556 // set the MIME type
557 ok = key.SetValue(_T("Content Type"), mimetype);
558
559 if ( ok )
560 {
561 // create the MIME key
562 wxString strKey = MIME_DATABASE_KEY;
563 strKey << mimetype;
564 wxRegKey keyMIME(wxRegKey::HKCR, strKey);
565 ok = keyMIME.Create();
566
567 if ( ok )
568 {
569 // and provide a back link to the extension
570 ok = keyMIME.SetValue(_T("Extension"), extWithDot);
571 }
572 }
573 }
574
575 if ( ok )
576 {
577 // create the filetype key itself (it will be empty for now, but
578 // SetCommand(), SetDefaultIcon() &c will use it later)
579 wxRegKey keyFT(wxRegKey::HKCR, filetype);
580 ok = keyFT.Create();
581 }
582
583 if ( ok )
584 {
585 // ok, we've created everything correctly
586 ft = CreateFileType(filetype, extWithDot);
587 }
588 else
589 {
590 // one of the registry operations failed
591 wxLogError(_("Failed to register extension '%s'."), ext.c_str());
592 }
593 }
594 else // key already exists
595 {
596 // FIXME we probably should return an existing file type then?
597 }
598
599 return ft;
600 }
601
602 bool wxFileTypeImpl::SetCommand(const wxString& cmd,
603 const wxString& verb,
604 bool overwriteprompt)
605 {
606 wxCHECK_MSG( !m_ext.IsEmpty() && !verb.IsEmpty(), FALSE,
607 _T("SetCommand() needs an extension and a verb") );
608
609 if ( !EnsureExtKeyExists() )
610 return FALSE;
611
612 wxRegKey rkey(wxRegKey::HKCR, GetVerbPath(verb));
613
614 if ( rkey.Exists() && overwriteprompt )
615 {
616 #if wxUSE_GUI
617 wxString old;
618 rkey.QueryValue(wxT(""), old);
619 if ( wxMessageBox
620 (
621 wxString::Format(
622 _("Do you want to overwrite the command used to %s "
623 "files with extension \"%s\" (current value is '%s', "
624 "new value is '%s')?"),
625 verb.c_str(),
626 m_ext.c_str(),
627 old.c_str(),
628 cmd.c_str()),
629 _("Confirm registry update"),
630 wxYES_NO | wxICON_QUESTION
631 ) != wxYES )
632 #endif // wxUSE_GUI
633 {
634 // cancelled by user
635 return FALSE;
636 }
637 }
638
639 // TODO:
640 // 1. translate '%s' to '%1' instead of always adding it
641 // 2. create DDEExec value if needed (undo GetCommand)
642 return rkey.Create() && rkey.SetValue(_T(""), cmd + _T(" \"%1\"") );
643 }
644
645 bool wxFileTypeImpl::SetMimeType(const wxString& mimeTypeOrig)
646 {
647 wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("SetMimeType() needs extension") );
648
649 if ( !EnsureExtKeyExists() )
650 return FALSE;
651
652 // VZ: is this really useful? (FIXME)
653 wxString mimeType;
654 if ( !mimeTypeOrig )
655 {
656 // make up a default value for it
657 wxString cmd;
658 wxSplitPath(GetCommand(_T("open")), NULL, &cmd, NULL);
659 mimeType << _T("application/x-") << cmd;
660 }
661 else
662 {
663 mimeType = mimeTypeOrig;
664 }
665
666 wxRegKey rkey(wxRegKey::HKCR, m_ext);
667 return rkey.Create() && rkey.SetValue(_T("Content Type"), mimeType);
668 }
669
670 bool wxFileTypeImpl::SetDefaultIcon(const wxString& cmd, int index)
671 {
672 wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("SetMimeType() needs extension") );
673 wxCHECK_MSG( wxFileExists(cmd), FALSE, _T("Icon file not found.") );
674
675 if ( !EnsureExtKeyExists() )
676 return FALSE;
677
678 wxRegKey rkey(wxRegKey::HKCR, m_strFileType + _T("\\DefaultIcon"));
679
680 return rkey.Create() &&
681 rkey.SetValue(_T(""),
682 wxString::Format(_T("%s,%d"), cmd.c_str(), index));
683 }
684
685 // ----------------------------------------------------------------------------
686 // remove file association
687 // ----------------------------------------------------------------------------
688
689 bool wxFileTypeImpl::Unassociate()
690 {
691 bool result = TRUE;
692 if ( !RemoveOpenCommand() )
693 result = FALSE;
694 if ( !RemoveDefaultIcon() )
695 result = FALSE;
696 if ( !RemoveMimeType() )
697 result = FALSE;
698
699 if ( result )
700 {
701 // delete the root key
702 wxRegKey key(wxRegKey::HKCR, m_ext);
703 if ( key.Exists() )
704 result = key.DeleteSelf();
705 }
706
707 return result;
708 }
709
710 bool wxFileTypeImpl::RemoveOpenCommand()
711 {
712 return RemoveCommand(_T("open"));
713 }
714
715 bool wxFileTypeImpl::RemoveCommand(const wxString& verb)
716 {
717 wxCHECK_MSG( !m_ext.IsEmpty() && !verb.IsEmpty(), FALSE,
718 _T("RemoveCommand() needs an extension and a verb") );
719
720 wxString sKey = m_strFileType;
721 wxRegKey rkey(wxRegKey::HKCR, GetVerbPath(verb));
722
723 // if the key already doesn't exist, it's a success
724 return !rkey.Exists() || rkey.DeleteSelf();
725 }
726
727 bool wxFileTypeImpl::RemoveMimeType()
728 {
729 wxCHECK_MSG( !m_ext.IsEmpty(), FALSE, _T("RemoveMimeType() needs extension") );
730
731 wxRegKey rkey(wxRegKey::HKCR, m_ext);
732 return !rkey.Exists() || rkey.DeleteSelf();
733 }
734
735 bool wxFileTypeImpl::RemoveDefaultIcon()
736 {
737 wxCHECK_MSG( !m_ext.IsEmpty(), FALSE,
738 _T("RemoveDefaultIcon() needs extension") );
739
740 wxRegKey rkey (wxRegKey::HKCR, m_strFileType + _T("\\DefaultIcon"));
741 return !rkey.Exists() || rkey.DeleteSelf();
742 }
743
744 #endif
745 // __WIN16__