1 /* vi:set ts=8 sts=4 sw=4: 2 * 3 * VIM - Vi IMproved by Bram Moolenaar 4 * 5 * Do ":help uganda" in Vim to read copying and usage conditions. 6 * Do ":help credits" in Vim to see a list of people who contributed. 7 */ 8 9 #if defined(FEAT_OLE) && defined(FEAT_GUI_W32) 10 /* 11 * OLE server implementation. 12 * 13 * See os_mswin.c for the client side. 14 */ 15 16 /* 17 * We have some trouble with order of includes here. For Borland it needs to 18 * be different from MSVC... 19 */ 20 #ifndef __BORLANDC__ 21 extern "C" { 22 # include "vim.h" 23 } 24 #endif 25 26 #include <windows.h> 27 #include <oleauto.h> 28 29 extern "C" { 30 #ifdef __BORLANDC__ 31 # include "vim.h" 32 #endif 33 extern HWND s_hwnd; 34 extern HWND vim_parent_hwnd; 35 } 36 37 #if _MSC_VER < 1300 38 /* Work around old versions of basetsd.h which wrongly declares 39 * UINT_PTR as unsigned long */ 40 # define UINT_PTR UINT 41 #endif 42 43 #include "if_ole.h" // Interface definitions 44 #include "iid_ole.c" // UUID definitions (compile here) 45 46 /* Supply function prototype to work around bug in Mingw oleauto.h header */ 47 #ifdef __MINGW32__ 48 WINOLEAUTAPI UnRegisterTypeLib(REFGUID libID, WORD wVerMajor, 49 WORD wVerMinor, LCID lcid, SYSKIND syskind); 50 #endif 51 52 /***************************************************************************** 53 1. Internal definitions for this file 54 *****************************************************************************/ 55 56 class CVim; 57 class CVimCF; 58 59 /* Internal data */ 60 // The identifier of the registered class factory 61 static unsigned long cf_id = 0; 62 63 // The identifier of the running application object 64 static unsigned long app_id = 0; 65 66 // The single global instance of the class factory 67 static CVimCF *cf = 0; 68 69 // The single global instance of the application object 70 static CVim *app = 0; 71 72 /* GUIDs, versions and type library information */ 73 #define MYCLSID CLSID_Vim 74 #define MYLIBID LIBID_Vim 75 #define MYIID IID_IVim 76 77 #define MAJORVER 1 78 #define MINORVER 0 79 #define LOCALE 0x0409 80 81 #define MYNAME "Vim" 82 #define MYPROGID "Vim.Application.1" 83 #define MYVIPROGID "Vim.Application" 84 85 #define MAX_CLSID_LEN 100 86 87 /***************************************************************************** 88 2. The application object 89 *****************************************************************************/ 90 91 /* Definition 92 * ---------- 93 */ 94 95 class CVim : public IVim 96 { 97 public: 98 ~CVim(); 99 static CVim *Create(int *pbDoRestart); 100 101 // IUnknown members 102 STDMETHOD(QueryInterface)(REFIID riid, void ** ppv); 103 STDMETHOD_(unsigned long, AddRef)(void); 104 STDMETHOD_(unsigned long, Release)(void); 105 106 // IDispatch members 107 STDMETHOD(GetTypeInfoCount)(UINT *pCount); 108 STDMETHOD(GetTypeInfo)(UINT iTypeInfo, LCID, ITypeInfo **ppITypeInfo); 109 STDMETHOD(GetIDsOfNames)(const IID &iid, OLECHAR **names, UINT n, LCID, DISPID *dispids); 110 STDMETHOD(Invoke)(DISPID member, const IID &iid, LCID, WORD flags, DISPPARAMS *dispparams, VARIANT *result, EXCEPINFO *excepinfo, UINT *argerr); 111 112 // IVim members 113 STDMETHOD(SendKeys)(BSTR keys); 114 STDMETHOD(Eval)(BSTR expr, BSTR *result); 115 STDMETHOD(SetForeground)(void); 116 STDMETHOD(GetHwnd)(UINT_PTR *result); 117 118 private: 119 // Constructor is private - create using CVim::Create() 120 CVim() : ref(0), typeinfo(0) {}; 121 122 // Reference count 123 unsigned long ref; 124 125 // The object's TypeInfo 126 ITypeInfo *typeinfo; 127 }; 128 129 /* Implementation 130 * -------------- 131 */ 132 133 CVim *CVim::Create(int *pbDoRestart) 134 { 135 HRESULT hr; 136 CVim *me = 0; 137 ITypeLib *typelib = 0; 138 ITypeInfo *typeinfo = 0; 139 140 *pbDoRestart = FALSE; 141 142 // Create the object 143 me = new CVim(); 144 if (me == NULL) 145 { 146 MessageBox(0, "Cannot create application object", "Vim Initialisation", 0); 147 return NULL; 148 } 149 150 // Load the type library from the registry 151 hr = LoadRegTypeLib(MYLIBID, 1, 0, 0x00, &typelib); 152 if (FAILED(hr)) 153 { 154 HKEY hKey; 155 156 // Check we can write to the registry. 157 // RegCreateKeyEx succeeds even if key exists. W.Briscoe W2K 20021011 158 if (RegCreateKeyEx(HKEY_CLASSES_ROOT, MYVIPROGID, 0, NULL, 159 REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL)) 160 { 161 delete me; 162 return NULL; // Unable to write to registry. Quietly fail. 163 } 164 RegCloseKey(hKey); 165 166 if (MessageBox(0, "Cannot load registered type library.\nDo you want to register Vim now?", 167 "Vim Initialisation", MB_YESNO | MB_ICONQUESTION) != IDYES) 168 { 169 delete me; 170 return NULL; 171 } 172 173 RegisterMe(FALSE); 174 175 // Load the type library from the registry 176 hr = LoadRegTypeLib(MYLIBID, 1, 0, 0x00, &typelib); 177 if (FAILED(hr)) 178 { 179 MessageBox(0, "You must restart Vim in order for the registration to take effect.", 180 "Vim Initialisation", 0); 181 *pbDoRestart = TRUE; 182 delete me; 183 return NULL; 184 } 185 } 186 187 // Get the type info of the vtable interface 188 hr = typelib->GetTypeInfoOfGuid(MYIID, &typeinfo); 189 typelib->Release(); 190 191 if (FAILED(hr)) 192 { 193 MessageBox(0, "Cannot get interface type information", 194 "Vim Initialisation", 0); 195 delete me; 196 return NULL; 197 } 198 199 // Save the type information 200 me->typeinfo = typeinfo; 201 return me; 202 } 203 204 CVim::~CVim() 205 { 206 if (typeinfo && vim_parent_hwnd == NULL) 207 typeinfo->Release(); 208 typeinfo = 0; 209 } 210 211 STDMETHODIMP 212 CVim::QueryInterface(REFIID riid, void **ppv) 213 { 214 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDispatch) || IsEqualIID(riid, MYIID)) 215 { 216 AddRef(); 217 *ppv = this; 218 return S_OK; 219 } 220 221 *ppv = 0; 222 return E_NOINTERFACE; 223 } 224 225 STDMETHODIMP_(ULONG) 226 CVim::AddRef() 227 { 228 return ++ref; 229 } 230 231 STDMETHODIMP_(ULONG) 232 CVim::Release() 233 { 234 // Don't delete the object when the reference count reaches zero, as there 235 // is only a single application object, and its lifetime is controlled by 236 // the running instance, not by its reference count. 237 if (ref > 0) 238 --ref; 239 return ref; 240 } 241 242 STDMETHODIMP 243 CVim::GetTypeInfoCount(UINT *pCount) 244 { 245 *pCount = 1; 246 return S_OK; 247 } 248 249 STDMETHODIMP 250 CVim::GetTypeInfo(UINT iTypeInfo, LCID, ITypeInfo **ppITypeInfo) 251 { 252 *ppITypeInfo = 0; 253 254 if (iTypeInfo != 0) 255 return DISP_E_BADINDEX; 256 257 typeinfo->AddRef(); 258 *ppITypeInfo = typeinfo; 259 return S_OK; 260 } 261 262 STDMETHODIMP 263 CVim::GetIDsOfNames( 264 const IID &iid, 265 OLECHAR **names, 266 UINT n, 267 LCID, 268 DISPID *dispids) 269 { 270 if (iid != IID_NULL) 271 return DISP_E_UNKNOWNINTERFACE; 272 273 return typeinfo->GetIDsOfNames(names, n, dispids); 274 } 275 276 STDMETHODIMP 277 CVim::Invoke( 278 DISPID member, 279 const IID &iid, 280 LCID, 281 WORD flags, 282 DISPPARAMS *dispparams, 283 VARIANT *result, 284 EXCEPINFO *excepinfo, 285 UINT *argerr) 286 { 287 if (iid != IID_NULL) 288 return DISP_E_UNKNOWNINTERFACE; 289 290 ::SetErrorInfo(0, NULL); 291 return typeinfo->Invoke(static_cast<IDispatch*>(this), 292 member, flags, dispparams, 293 result, excepinfo, argerr); 294 } 295 296 STDMETHODIMP 297 CVim::GetHwnd(UINT_PTR *result) 298 { 299 *result = (UINT_PTR)s_hwnd; 300 return S_OK; 301 } 302 303 STDMETHODIMP 304 CVim::SetForeground(void) 305 { 306 /* Make the Vim window come to the foreground */ 307 gui_mch_set_foreground(); 308 return S_OK; 309 } 310 311 STDMETHODIMP 312 CVim::SendKeys(BSTR keys) 313 { 314 int len; 315 char *buffer; 316 char_u *str; 317 char_u *ptr; 318 319 /* Get a suitable buffer */ 320 len = WideCharToMultiByte(CP_ACP, 0, keys, -1, 0, 0, 0, 0); 321 buffer = (char *)alloc(len+1); 322 323 if (buffer == NULL) 324 return E_OUTOFMEMORY; 325 326 len = WideCharToMultiByte(CP_ACP, 0, keys, -1, buffer, len, 0, 0); 327 328 if (len == 0) 329 { 330 vim_free(buffer); 331 return E_INVALIDARG; 332 } 333 334 /* Translate key codes like <Esc> */ 335 str = replace_termcodes((char_u *)buffer, &ptr, FALSE, TRUE, FALSE); 336 337 /* If ptr was set, then a new buffer was allocated, 338 * so we can free the old one. 339 */ 340 if (ptr) 341 vim_free((char_u *)(buffer)); 342 343 /* Reject strings too long to fit in the input buffer. Allow 10 bytes 344 * space to cover for the (remote) possibility that characters may enter 345 * the input buffer between now and when the WM_OLE message is actually 346 * processed. If more that 10 characters enter the input buffer in that 347 * time, the WM_OLE processing will simply fail to insert the characters. 348 */ 349 if ((int)(STRLEN(str)) > (vim_free_in_input_buf() - 10)) 350 { 351 vim_free(str); 352 return E_INVALIDARG; 353 } 354 355 /* Pass the string to the main input loop. The memory will be freed when 356 * the message is processed. 357 */ 358 PostMessage(NULL, WM_OLE, 0, (LPARAM)str); 359 360 return S_OK; 361 } 362 363 STDMETHODIMP 364 CVim::Eval(BSTR expr, BSTR *result) 365 { 366 #ifdef FEAT_EVAL 367 int len; 368 char *buffer; 369 char *str; 370 wchar_t *w_buffer; 371 372 /* Get a suitable buffer */ 373 len = WideCharToMultiByte(CP_ACP, 0, expr, -1, 0, 0, 0, 0); 374 if (len == 0) 375 return E_INVALIDARG; 376 377 buffer = (char *)alloc((unsigned)len); 378 379 if (buffer == NULL) 380 return E_OUTOFMEMORY; 381 382 /* Convert the (wide character) expression to an ASCII string */ 383 len = WideCharToMultiByte(CP_ACP, 0, expr, -1, buffer, len, 0, 0); 384 if (len == 0) 385 return E_INVALIDARG; 386 387 /* Evaluate the expression */ 388 ++emsg_skip; 389 str = (char *)eval_to_string((char_u *)buffer, NULL, TRUE); 390 --emsg_skip; 391 vim_free(buffer); 392 if (str == NULL) 393 return E_FAIL; 394 395 /* Convert the result to wide characters */ 396 MultiByteToWideChar_alloc(CP_ACP, 0, str, -1, &w_buffer, &len); 397 vim_free(str); 398 if (w_buffer == NULL) 399 return E_OUTOFMEMORY; 400 401 if (len == 0) 402 { 403 vim_free(w_buffer); 404 return E_FAIL; 405 } 406 407 /* Store the result */ 408 *result = SysAllocString(w_buffer); 409 vim_free(w_buffer); 410 411 return S_OK; 412 #else 413 return E_NOTIMPL; 414 #endif 415 } 416 417 /***************************************************************************** 418 3. The class factory 419 *****************************************************************************/ 420 421 /* Definition 422 * ---------- 423 */ 424 425 class CVimCF : public IClassFactory 426 { 427 public: 428 static CVimCF *Create(); 429 430 STDMETHOD(QueryInterface)(REFIID riid, void ** ppv); 431 STDMETHOD_(unsigned long, AddRef)(void); 432 STDMETHOD_(unsigned long, Release)(void); 433 STDMETHOD(CreateInstance)(IUnknown *punkOuter, REFIID riid, void ** ppv); 434 STDMETHOD(LockServer)(BOOL lock); 435 436 private: 437 // Constructor is private - create via Create() 438 CVimCF() : ref(0) {}; 439 440 // Reference count 441 unsigned long ref; 442 }; 443 444 /* Implementation 445 * -------------- 446 */ 447 448 CVimCF *CVimCF::Create() 449 { 450 CVimCF *me = new CVimCF(); 451 452 if (me == NULL) 453 MessageBox(0, "Cannot create class factory", "Vim Initialisation", 0); 454 455 return me; 456 } 457 458 STDMETHODIMP 459 CVimCF::QueryInterface(REFIID riid, void **ppv) 460 { 461 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory)) 462 { 463 AddRef(); 464 *ppv = this; 465 return S_OK; 466 } 467 468 *ppv = 0; 469 return E_NOINTERFACE; 470 } 471 472 STDMETHODIMP_(ULONG) 473 CVimCF::AddRef() 474 { 475 return ++ref; 476 } 477 478 STDMETHODIMP_(ULONG) 479 CVimCF::Release() 480 { 481 // Don't delete the object when the reference count reaches zero, as there 482 // is only a single application object, and its lifetime is controlled by 483 // the running instance, not by its reference count. 484 if (ref > 0) 485 --ref; 486 return ref; 487 } 488 489 /*ARGSUSED*/ 490 STDMETHODIMP 491 CVimCF::CreateInstance(IUnknown *punkOuter, REFIID riid, void **ppv) 492 { 493 return app->QueryInterface(riid, ppv); 494 } 495 496 /*ARGSUSED*/ 497 STDMETHODIMP 498 CVimCF::LockServer(BOOL lock) 499 { 500 return S_OK; 501 } 502 503 /***************************************************************************** 504 4. Registry manipulation code 505 *****************************************************************************/ 506 507 // Internal use only 508 static void SetKeyAndValue(const char *path, const char *subkey, const char *value); 509 static void GUIDtochar(const GUID &guid, char *GUID, int length); 510 static void RecursiveDeleteKey(HKEY hKeyParent, const char *child); 511 static const int GUID_STRING_SIZE = 39; 512 513 // Register the component in the registry 514 // When "silent" is TRUE don't give any messages. 515 516 extern "C" void RegisterMe(int silent) 517 { 518 BOOL ok = TRUE; 519 520 // Get the application startup command 521 char module[MAX_PATH]; 522 523 ::GetModuleFileName(NULL, module, MAX_PATH); 524 525 // Unregister first (quietly) 526 UnregisterMe(FALSE); 527 528 // Convert the CLSID into a char 529 char clsid[GUID_STRING_SIZE]; 530 GUIDtochar(MYCLSID, clsid, sizeof(clsid)); 531 532 // Convert the LIBID into a char 533 char libid[GUID_STRING_SIZE]; 534 GUIDtochar(MYLIBID, libid, sizeof(libid)); 535 536 // Build the key CLSID\\{...} 537 char Key[MAX_CLSID_LEN]; 538 strcpy(Key, "CLSID\\"); 539 strcat(Key, clsid); 540 541 // Add the CLSID to the registry 542 SetKeyAndValue(Key, NULL, MYNAME); 543 SetKeyAndValue(Key, "LocalServer32", module); 544 SetKeyAndValue(Key, "ProgID", MYPROGID); 545 SetKeyAndValue(Key, "VersionIndependentProgID", MYVIPROGID); 546 SetKeyAndValue(Key, "TypeLib", libid); 547 548 // Add the version-independent ProgID subkey under HKEY_CLASSES_ROOT 549 SetKeyAndValue(MYVIPROGID, NULL, MYNAME); 550 SetKeyAndValue(MYVIPROGID, "CLSID", clsid); 551 SetKeyAndValue(MYVIPROGID, "CurVer", MYPROGID); 552 553 // Add the versioned ProgID subkey under HKEY_CLASSES_ROOT 554 SetKeyAndValue(MYPROGID, NULL, MYNAME); 555 SetKeyAndValue(MYPROGID, "CLSID", clsid); 556 557 wchar_t w_module[MAX_PATH]; 558 MultiByteToWideChar(CP_ACP, 0, module, -1, w_module, MAX_PATH); 559 560 ITypeLib *typelib = NULL; 561 if (LoadTypeLib(w_module, &typelib) != S_OK) 562 { 563 if (!silent) 564 MessageBox(0, "Cannot load type library to register", 565 "Vim Registration", 0); 566 ok = FALSE; 567 } 568 else 569 { 570 if (RegisterTypeLib(typelib, w_module, NULL) != S_OK) 571 { 572 if (!silent) 573 MessageBox(0, "Cannot register type library", 574 "Vim Registration", 0); 575 ok = FALSE; 576 } 577 typelib->Release(); 578 } 579 580 if (ok && !silent) 581 MessageBox(0, "Registered successfully", "Vim", 0); 582 } 583 584 // Remove the component from the registry 585 // 586 // Note: There is little error checking in this code, to allow incomplete 587 // or failed registrations to be undone. 588 extern "C" void UnregisterMe(int bNotifyUser) 589 { 590 // Unregister the type library 591 ITypeLib *typelib; 592 if (SUCCEEDED(LoadRegTypeLib(MYLIBID, MAJORVER, MINORVER, LOCALE, &typelib))) 593 { 594 TLIBATTR *tla; 595 if (SUCCEEDED(typelib->GetLibAttr(&tla))) 596 { 597 UnRegisterTypeLib(tla->guid, tla->wMajorVerNum, tla->wMinorVerNum, 598 tla->lcid, tla->syskind); 599 typelib->ReleaseTLibAttr(tla); 600 } 601 typelib->Release(); 602 } 603 604 // Convert the CLSID into a char 605 char clsid[GUID_STRING_SIZE]; 606 GUIDtochar(MYCLSID, clsid, sizeof(clsid)); 607 608 // Build the key CLSID\\{...} 609 char Key[MAX_CLSID_LEN]; 610 strcpy(Key, "CLSID\\"); 611 strcat(Key, clsid); 612 613 // Delete the CLSID Key - CLSID\{...} 614 RecursiveDeleteKey(HKEY_CLASSES_ROOT, Key); 615 616 // Delete the version-independent ProgID Key 617 RecursiveDeleteKey(HKEY_CLASSES_ROOT, MYVIPROGID); 618 619 // Delete the ProgID key 620 RecursiveDeleteKey(HKEY_CLASSES_ROOT, MYPROGID); 621 622 if (bNotifyUser) 623 MessageBox(0, "Unregistered successfully", "Vim", 0); 624 } 625 626 /****************************************************************************/ 627 628 // Convert a GUID to a char string 629 static void GUIDtochar(const GUID &guid, char *GUID, int length) 630 { 631 // Get wide string version 632 LPOLESTR wGUID = NULL; 633 StringFromCLSID(guid, &wGUID); 634 635 // Covert from wide characters to non-wide 636 wcstombs(GUID, wGUID, length); 637 638 // Free memory 639 CoTaskMemFree(wGUID); 640 } 641 642 // Delete a key and all of its descendents 643 static void RecursiveDeleteKey(HKEY hKeyParent, const char *child) 644 { 645 // Open the child 646 HKEY hKeyChild; 647 LONG result = RegOpenKeyEx(hKeyParent, child, 0, KEY_ALL_ACCESS, &hKeyChild); 648 if (result != ERROR_SUCCESS) 649 return; 650 651 // Enumerate all of the decendents of this child 652 FILETIME time; 653 char buffer[1024]; 654 DWORD size = 1024; 655 656 while (RegEnumKeyEx(hKeyChild, 0, buffer, &size, NULL, 657 NULL, NULL, &time) == S_OK) 658 { 659 // Delete the decendents of this child 660 RecursiveDeleteKey(hKeyChild, buffer); 661 size = 256; 662 } 663 664 // Close the child 665 RegCloseKey(hKeyChild); 666 667 // Delete this child 668 RegDeleteKey(hKeyParent, child); 669 } 670 671 // Create a key and set its value 672 static void SetKeyAndValue(const char *key, const char *subkey, const char *value) 673 { 674 HKEY hKey; 675 char buffer[1024]; 676 677 strcpy(buffer, key); 678 679 // Add subkey name to buffer. 680 if (subkey) 681 { 682 strcat(buffer, "\\"); 683 strcat(buffer, subkey); 684 } 685 686 // Create and open key and subkey. 687 long result = RegCreateKeyEx(HKEY_CLASSES_ROOT, 688 buffer, 689 0, NULL, REG_OPTION_NON_VOLATILE, 690 KEY_ALL_ACCESS, NULL, 691 &hKey, NULL); 692 if (result != ERROR_SUCCESS) 693 return; 694 695 // Set the value 696 if (value) 697 RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE *)value, 698 (DWORD)STRLEN(value)+1); 699 700 RegCloseKey(hKey); 701 } 702 703 /***************************************************************************** 704 5. OLE Initialisation and shutdown processing 705 *****************************************************************************/ 706 extern "C" void InitOLE(int *pbDoRestart) 707 { 708 HRESULT hr; 709 710 *pbDoRestart = FALSE; 711 712 // Initialize the OLE libraries 713 hr = OleInitialize(NULL); 714 if (FAILED(hr)) 715 { 716 MessageBox(0, "Cannot initialise OLE", "Vim Initialisation", 0); 717 goto error0; 718 } 719 720 // Create the application object 721 app = CVim::Create(pbDoRestart); 722 if (app == NULL) 723 goto error1; 724 725 // Create the class factory 726 cf = CVimCF::Create(); 727 if (cf == NULL) 728 goto error1; 729 730 // Register the class factory 731 hr = CoRegisterClassObject( 732 MYCLSID, 733 cf, 734 CLSCTX_LOCAL_SERVER, 735 REGCLS_MULTIPLEUSE, 736 &cf_id); 737 738 if (FAILED(hr)) 739 { 740 MessageBox(0, "Cannot register class factory", "Vim Initialisation", 0); 741 goto error1; 742 } 743 744 // Register the application object as active 745 hr = RegisterActiveObject( 746 app, 747 MYCLSID, 748 NULL, 749 &app_id); 750 751 if (FAILED(hr)) 752 { 753 MessageBox(0, "Cannot register application object", "Vim Initialisation", 0); 754 goto error1; 755 } 756 757 return; 758 759 // Errors: tidy up as much as needed and return 760 error1: 761 UninitOLE(); 762 error0: 763 return; 764 } 765 766 extern "C" void UninitOLE() 767 { 768 // Unregister the application object 769 if (app_id) 770 { 771 RevokeActiveObject(app_id, NULL); 772 app_id = 0; 773 } 774 775 // Unregister the class factory 776 if (cf_id) 777 { 778 CoRevokeClassObject(cf_id); 779 cf_id = 0; 780 } 781 782 // Shut down the OLE libraries 783 OleUninitialize(); 784 785 // Delete the application object 786 if (app) 787 { 788 delete app; 789 app = NULL; 790 } 791 792 // Delete the class factory 793 if (cf) 794 { 795 delete cf; 796 cf = NULL; 797 } 798 } 799 #endif /* FEAT_OLE */ 800