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