]> git.saurik.com Git - wxWidgets.git/blob - src/msw/ole/automtn.cpp
Fixed centering/right alignment of last line
[wxWidgets.git] / src / msw / ole / automtn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/ole/automtn.cpp
3 // Purpose: OLE automation utilities
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 11/6/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998, Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
14
15 #if defined(__BORLANDC__)
16 #pragma hdrstop
17 #endif
18
19 // With Borland C++, all samples crash if this is compiled in.
20 #if (defined(__BORLANDC__) && (__BORLANDC__ < 0x520)) || defined(__CYGWIN10__)
21 #undef wxUSE_OLE_AUTOMATION
22 #define wxUSE_OLE_AUTOMATION 0
23 #endif
24
25 #ifndef WX_PRECOMP
26 #include "wx/log.h"
27 #include "wx/math.h"
28 #endif
29
30 #define _FORCENAMELESSUNION
31 #include "wx/msw/private.h"
32 #include "wx/msw/ole/oleutils.h"
33 #include "wx/msw/ole/automtn.h"
34
35 #ifdef __WXWINCE__
36 #include "wx/msw/wince/time.h"
37 #else
38 #include <time.h>
39 #endif
40
41 #include <wtypes.h>
42 #include <unknwn.h>
43
44 #include <ole2.h>
45 #define _huge
46
47 #ifndef __WXWINCE__
48 #include <ole2ver.h>
49 #endif
50
51 #include <oleauto.h>
52
53 #if wxUSE_DATETIME
54 #include "wx/datetime.h"
55 #endif // wxUSE_DATETIME
56
57 #if wxUSE_OLE_AUTOMATION
58
59 #include <wx/vector.h>
60
61 // Report an OLE error when calling the specified method to the user via wxLog.
62 static void
63 ShowException(const wxString& member,
64 HRESULT hr,
65 EXCEPINFO *pexcep = NULL,
66 unsigned int uiArgErr = 0);
67
68 // wxAutomationObject
69
70 wxAutomationObject::wxAutomationObject(WXIDISPATCH* dispatchPtr)
71 {
72 m_dispatchPtr = dispatchPtr;
73 m_lcid = LOCALE_SYSTEM_DEFAULT;
74 }
75
76 wxAutomationObject::~wxAutomationObject()
77 {
78 if (m_dispatchPtr)
79 {
80 ((IDispatch*)m_dispatchPtr)->Release();
81 m_dispatchPtr = NULL;
82 }
83 }
84
85 namespace
86 {
87
88 // A simple helper that ensures that VARIANT is destroyed on scope exit.
89 struct wxOleVariantArg : VARIANTARG
90 {
91 wxOleVariantArg() { VariantInit(this); }
92 ~wxOleVariantArg() { VariantClear(this); }
93 };
94
95 } // anonymous namespace
96
97
98 #define INVOKEARG(i) (args ? args[i] : *(ptrArgs[i]))
99
100 // For Put/Get, no named arguments are allowed.
101 // WARNING: if args contain IDispatches, their reference count will be decreased
102 // by one after Invoke() returns!
103 bool wxAutomationObject::Invoke(const wxString& member, int action,
104 wxVariant& retValue, int noArgs, wxVariant args[], const wxVariant* ptrArgs[]) const
105 {
106 if (!m_dispatchPtr)
107 return false;
108
109 int ch = member.Find('.');
110 if (ch != -1)
111 {
112 // Use dot notation to get the next object
113 wxString member2(member.Left((size_t) ch));
114 wxString rest(member.Right(member.length() - ch - 1));
115 wxAutomationObject obj;
116 if (!GetObject(obj, member2))
117 return false;
118 return obj.Invoke(rest, action, retValue, noArgs, args, ptrArgs);
119 }
120
121 wxOleVariantArg vReturn;
122 wxOleVariantArg* vReturnPtr = & vReturn;
123
124 // Find number of names args
125 int namedArgCount = 0;
126 int i;
127 for (i = 0; i < noArgs; i++)
128 {
129 if ( !INVOKEARG(i).GetName().empty() )
130 {
131 namedArgCount ++;
132 }
133 }
134
135 int namedArgStringCount = namedArgCount + 1;
136 wxVector<wxBasicString> argNames(namedArgStringCount, wxString());
137 argNames[0] = member;
138
139 // Note that arguments are specified in reverse order
140 // (all totally logical; hey, we're dealing with OLE here.)
141
142 int j = 0;
143 for (i = 0; i < namedArgCount; i++)
144 {
145 if ( !INVOKEARG(i).GetName().empty() )
146 {
147 argNames[(namedArgCount-j)] = INVOKEARG(i).GetName();
148 j ++;
149 }
150 }
151
152 // + 1 for the member name, + 1 again in case we're a 'put'
153 wxVector<DISPID> dispIds(namedArgCount + 2);
154
155 HRESULT hr;
156 DISPPARAMS dispparams;
157 unsigned int uiArgErr;
158
159 // Get the IDs for the member and its arguments. GetIDsOfNames expects the
160 // member name as the first name, followed by argument names (if any).
161 hr = ((IDispatch*)m_dispatchPtr)->GetIDsOfNames(IID_NULL,
162 // We rely on the fact that wxBasicString is
163 // just BSTR with some methods here.
164 reinterpret_cast<BSTR *>(&argNames[0]),
165 1 + namedArgCount, m_lcid, &dispIds[0]);
166 if (FAILED(hr))
167 {
168 ShowException(member, hr);
169 return false;
170 }
171
172 // if doing a property put(ref), we need to adjust the first argument to have a
173 // named arg of DISPID_PROPERTYPUT.
174 if (action & (DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF))
175 {
176 namedArgCount = 1;
177 dispIds[1] = DISPID_PROPERTYPUT;
178 vReturnPtr = NULL;
179 }
180
181 // Convert the wxVariants to VARIANTARGs
182 wxVector<wxOleVariantArg> oleArgs(noArgs);
183 for (i = 0; i < noArgs; i++)
184 {
185 // Again, reverse args
186 if (!wxConvertVariantToOle(INVOKEARG((noArgs-1) - i), oleArgs[i]))
187 return false;
188 }
189
190 dispparams.rgdispidNamedArgs = &dispIds[0] + 1;
191 dispparams.rgvarg = oleArgs.empty() ? NULL : &oleArgs[0];
192 dispparams.cArgs = noArgs;
193 dispparams.cNamedArgs = namedArgCount;
194
195 EXCEPINFO excep;
196 wxZeroMemory(excep);
197
198 hr = ((IDispatch*)m_dispatchPtr)->Invoke(dispIds[0], IID_NULL, m_lcid,
199 (WORD)action, &dispparams, vReturnPtr, &excep, &uiArgErr);
200
201 if (FAILED(hr))
202 {
203 // display the exception information if appropriate:
204 ShowException(member, hr, &excep, uiArgErr);
205
206 // free exception structure information
207 SysFreeString(excep.bstrSource);
208 SysFreeString(excep.bstrDescription);
209 SysFreeString(excep.bstrHelpFile);
210
211 return false;
212 }
213 else
214 {
215 if (vReturnPtr)
216 {
217 // Convert result to wxVariant form
218 if (!wxConvertOleToVariant(vReturn, retValue))
219 return false;
220 // Mustn't release the dispatch pointer
221 if (vReturn.vt == VT_DISPATCH)
222 {
223 vReturn.pdispVal = NULL;
224 }
225 // Mustn't free the SAFEARRAY if it is contained in the retValue
226 if ((vReturn.vt & VT_ARRAY) &&
227 retValue.GetType() == wxS("safearray"))
228 {
229 vReturn.parray = NULL;
230 }
231 }
232 }
233 return true;
234 }
235
236 // Invoke a member function
237 wxVariant wxAutomationObject::CallMethod(const wxString& member, int noArgs, wxVariant args[])
238 {
239 wxVariant retVariant;
240 if (!Invoke(member, DISPATCH_METHOD, retVariant, noArgs, args))
241 {
242 retVariant.MakeNull();
243 }
244 return retVariant;
245 }
246
247 wxVariant wxAutomationObject::CallMethodArray(const wxString& member, int noArgs, const wxVariant **args)
248 {
249 wxVariant retVariant;
250 if (!Invoke(member, DISPATCH_METHOD, retVariant, noArgs, NULL, args))
251 {
252 retVariant.MakeNull();
253 }
254 return retVariant;
255 }
256
257 wxVariant wxAutomationObject::CallMethod(const wxString& member,
258 const wxVariant& arg1, const wxVariant& arg2,
259 const wxVariant& arg3, const wxVariant& arg4,
260 const wxVariant& arg5, const wxVariant& arg6)
261 {
262 const wxVariant** args = new const wxVariant*[6];
263 int i = 0;
264 if (!arg1.IsNull())
265 {
266 args[i] = & arg1;
267 i ++;
268 }
269 if (!arg2.IsNull())
270 {
271 args[i] = & arg2;
272 i ++;
273 }
274 if (!arg3.IsNull())
275 {
276 args[i] = & arg3;
277 i ++;
278 }
279 if (!arg4.IsNull())
280 {
281 args[i] = & arg4;
282 i ++;
283 }
284 if (!arg5.IsNull())
285 {
286 args[i] = & arg5;
287 i ++;
288 }
289 if (!arg6.IsNull())
290 {
291 args[i] = & arg6;
292 i ++;
293 }
294 wxVariant retVariant;
295 if (!Invoke(member, DISPATCH_METHOD, retVariant, i, NULL, args))
296 {
297 retVariant.MakeNull();
298 }
299 delete[] args;
300 return retVariant;
301 }
302
303 // Get/Set property
304 wxVariant wxAutomationObject::GetPropertyArray(const wxString& property, int noArgs, const wxVariant **args) const
305 {
306 wxVariant retVariant;
307 if (!Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, NULL, args))
308 {
309 retVariant.MakeNull();
310 }
311 return retVariant;
312 }
313 wxVariant wxAutomationObject::GetProperty(const wxString& property, int noArgs, wxVariant args[]) const
314 {
315 wxVariant retVariant;
316 if (!Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, args))
317 {
318 retVariant.MakeNull();
319 }
320 return retVariant;
321 }
322
323 wxVariant wxAutomationObject::GetProperty(const wxString& property,
324 const wxVariant& arg1, const wxVariant& arg2,
325 const wxVariant& arg3, const wxVariant& arg4,
326 const wxVariant& arg5, const wxVariant& arg6)
327 {
328 const wxVariant** args = new const wxVariant*[6];
329 int i = 0;
330 if (!arg1.IsNull())
331 {
332 args[i] = & arg1;
333 i ++;
334 }
335 if (!arg2.IsNull())
336 {
337 args[i] = & arg2;
338 i ++;
339 }
340 if (!arg3.IsNull())
341 {
342 args[i] = & arg3;
343 i ++;
344 }
345 if (!arg4.IsNull())
346 {
347 args[i] = & arg4;
348 i ++;
349 }
350 if (!arg5.IsNull())
351 {
352 args[i] = & arg5;
353 i ++;
354 }
355 if (!arg6.IsNull())
356 {
357 args[i] = & arg6;
358 i ++;
359 }
360 wxVariant retVariant;
361 if (!Invoke(property, DISPATCH_PROPERTYGET, retVariant, i, NULL, args))
362 {
363 retVariant.MakeNull();
364 }
365 delete[] args;
366 return retVariant;
367 }
368
369 bool wxAutomationObject::PutProperty(const wxString& property, int noArgs, wxVariant args[])
370 {
371 wxVariant retVariant;
372 if (!Invoke(property, DISPATCH_PROPERTYPUT, retVariant, noArgs, args))
373 {
374 return false;
375 }
376 return true;
377 }
378
379 bool wxAutomationObject::PutPropertyArray(const wxString& property, int noArgs, const wxVariant **args)
380 {
381 wxVariant retVariant;
382 if (!Invoke(property, DISPATCH_PROPERTYPUT, retVariant, noArgs, NULL, args))
383 {
384 return false;
385 }
386 return true;
387 }
388
389 bool wxAutomationObject::PutProperty(const wxString& property,
390 const wxVariant& arg1, const wxVariant& arg2,
391 const wxVariant& arg3, const wxVariant& arg4,
392 const wxVariant& arg5, const wxVariant& arg6)
393 {
394 const wxVariant** args = new const wxVariant*[6];
395 int i = 0;
396 if (!arg1.IsNull())
397 {
398 args[i] = & arg1;
399 i ++;
400 }
401 if (!arg2.IsNull())
402 {
403 args[i] = & arg2;
404 i ++;
405 }
406 if (!arg3.IsNull())
407 {
408 args[i] = & arg3;
409 i ++;
410 }
411 if (!arg4.IsNull())
412 {
413 args[i] = & arg4;
414 i ++;
415 }
416 if (!arg5.IsNull())
417 {
418 args[i] = & arg5;
419 i ++;
420 }
421 if (!arg6.IsNull())
422 {
423 args[i] = & arg6;
424 i ++;
425 }
426 wxVariant retVariant;
427 bool ret = Invoke(property, DISPATCH_PROPERTYPUT, retVariant, i, NULL, args);
428 delete[] args;
429 return ret;
430 }
431
432
433 // Uses DISPATCH_PROPERTYGET
434 // and returns a dispatch pointer. The calling code should call Release
435 // on the pointer, though this could be implicit by constructing an wxAutomationObject
436 // with it and letting the destructor call Release.
437 WXIDISPATCH* wxAutomationObject::GetDispatchProperty(const wxString& property, int noArgs, wxVariant args[]) const
438 {
439 wxVariant retVariant;
440 if (Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, args))
441 {
442 if (retVariant.GetType() == wxT("void*"))
443 {
444 return (WXIDISPATCH*) retVariant.GetVoidPtr();
445 }
446 }
447
448 return NULL;
449 }
450
451 // Uses DISPATCH_PROPERTYGET
452 // and returns a dispatch pointer. The calling code should call Release
453 // on the pointer, though this could be implicit by constructing an wxAutomationObject
454 // with it and letting the destructor call Release.
455 WXIDISPATCH* wxAutomationObject::GetDispatchProperty(const wxString& property, int noArgs, const wxVariant **args) const
456 {
457 wxVariant retVariant;
458 if (Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, NULL, args))
459 {
460 if (retVariant.GetType() == wxT("void*"))
461 {
462 return (WXIDISPATCH*) retVariant.GetVoidPtr();
463 }
464 }
465
466 return NULL;
467 }
468
469
470 // A way of initialising another wxAutomationObject with a dispatch object
471 bool wxAutomationObject::GetObject(wxAutomationObject& obj, const wxString& property, int noArgs, wxVariant args[]) const
472 {
473 WXIDISPATCH* dispatch = GetDispatchProperty(property, noArgs, args);
474 if (dispatch)
475 {
476 obj.SetDispatchPtr(dispatch);
477 obj.SetLCID(GetLCID());
478 return true;
479 }
480 else
481 return false;
482 }
483
484 // A way of initialising another wxAutomationObject with a dispatch object
485 bool wxAutomationObject::GetObject(wxAutomationObject& obj, const wxString& property, int noArgs, const wxVariant **args) const
486 {
487 WXIDISPATCH* dispatch = GetDispatchProperty(property, noArgs, args);
488 if (dispatch)
489 {
490 obj.SetDispatchPtr(dispatch);
491 obj.SetLCID(GetLCID());
492 return true;
493 }
494 else
495 return false;
496 }
497
498 namespace
499 {
500
501 HRESULT wxCLSIDFromProgID(const wxString& progId, CLSID& clsId)
502 {
503 HRESULT hr = CLSIDFromProgID(wxBasicString(progId), &clsId);
504 if ( FAILED(hr) )
505 {
506 wxLogSysError(hr, _("Failed to find CLSID of \"%s\""), progId);
507 }
508 return hr;
509 }
510
511 void *DoCreateInstance(const wxString& progId, const CLSID& clsId)
512 {
513 // get the server IDispatch interface
514 //
515 // NB: using CLSCTX_INPROC_HANDLER results in failure when getting
516 // Automation interface for Microsoft Office applications so don't use
517 // CLSCTX_ALL which includes it
518 void *pDispatch = NULL;
519 HRESULT hr = CoCreateInstance(clsId, NULL, CLSCTX_SERVER,
520 IID_IDispatch, &pDispatch);
521 if (FAILED(hr))
522 {
523 wxLogSysError(hr, _("Failed to create an instance of \"%s\""), progId);
524 return NULL;
525 }
526
527 return pDispatch;
528 }
529
530 } // anonymous namespace
531
532 // Get a dispatch pointer from the current object associated
533 // with a ProgID
534 bool wxAutomationObject::GetInstance(const wxString& progId, int flags) const
535 {
536 if (m_dispatchPtr)
537 return false;
538
539 CLSID clsId;
540 HRESULT hr = wxCLSIDFromProgID(progId, clsId);
541 if (FAILED(hr))
542 return false;
543
544 IUnknown *pUnk = NULL;
545 hr = GetActiveObject(clsId, NULL, &pUnk);
546 if (FAILED(hr))
547 {
548 if ( flags & wxAutomationInstance_CreateIfNeeded )
549 {
550 const_cast<wxAutomationObject *>(this)->
551 m_dispatchPtr = DoCreateInstance(progId, clsId);
552 if ( m_dispatchPtr )
553 return true;
554 }
555 else
556 {
557 // Log an error except if we're supposed to fail silently when the
558 // error is that no current instance exists.
559 if ( hr != MK_E_UNAVAILABLE ||
560 !(flags & wxAutomationInstance_SilentIfNone) )
561 {
562 wxLogSysError(hr,
563 _("Cannot get an active instance of \"%s\""),
564 progId);
565 }
566 }
567
568 return false;
569 }
570
571 hr = pUnk->QueryInterface(IID_IDispatch, (LPVOID*) &m_dispatchPtr);
572 if (FAILED(hr))
573 {
574 wxLogSysError(hr,
575 _("Failed to get OLE automation interface for \"%s\""),
576 progId);
577 return false;
578 }
579
580 return true;
581 }
582
583 // Get a dispatch pointer from a new object associated
584 // with the given ProgID
585 bool wxAutomationObject::CreateInstance(const wxString& progId) const
586 {
587 if (m_dispatchPtr)
588 return false;
589
590 CLSID clsId;
591 HRESULT hr = wxCLSIDFromProgID(progId, clsId);
592 if (FAILED(hr))
593 return false;
594
595 const_cast<wxAutomationObject *>(this)->
596 m_dispatchPtr = DoCreateInstance(progId, clsId);
597
598 return m_dispatchPtr != NULL;
599 }
600
601 LCID wxAutomationObject::GetLCID() const
602 {
603 return m_lcid;
604 }
605
606 void wxAutomationObject::SetLCID(LCID lcid)
607 {
608 m_lcid = lcid;
609 }
610
611 static void
612 ShowException(const wxString& member,
613 HRESULT hr,
614 EXCEPINFO *pexcep,
615 unsigned int uiArgErr)
616 {
617 wxString message;
618 switch (GetScode(hr))
619 {
620 case DISP_E_UNKNOWNNAME:
621 message = _("Unknown name or named argument.");
622 break;
623
624 case DISP_E_BADPARAMCOUNT:
625 message = _("Incorrect number of arguments.");
626 break;
627
628 case DISP_E_EXCEPTION:
629 if ( pexcep )
630 {
631 if ( pexcep->bstrDescription )
632 message << pexcep->bstrDescription << wxS(" ");
633 message += wxString::Format(wxS("error code %u"), pexcep->wCode);
634 }
635 else
636 {
637 message = _("Unknown exception");
638 }
639 break;
640
641 case DISP_E_MEMBERNOTFOUND:
642 message = _("Method or property not found.");
643 break;
644
645 case DISP_E_OVERFLOW:
646 message = _("Overflow while coercing argument values.");
647 break;
648
649 case DISP_E_NONAMEDARGS:
650 message = _("Object implementation does not support named arguments.");
651 break;
652
653 case DISP_E_UNKNOWNLCID:
654 message = _("The locale ID is unknown.");
655 break;
656
657 case DISP_E_PARAMNOTOPTIONAL:
658 message = _("Missing a required parameter.");
659 break;
660
661 case DISP_E_PARAMNOTFOUND:
662 message.Printf(_("Argument %u not found."), uiArgErr);
663 break;
664
665 case DISP_E_TYPEMISMATCH:
666 message.Printf(_("Type mismatch in argument %u."), uiArgErr);
667 break;
668
669 case ERROR_FILE_NOT_FOUND:
670 message = _("The system cannot find the file specified.");
671 break;
672
673 case REGDB_E_CLASSNOTREG:
674 message = _("Class not registered.");
675 break;
676
677 default:
678 message.Printf(_("Unknown error %08x"), hr);
679 break;
680 }
681
682 wxLogError(_("OLE Automation error in %s: %s"), member, message);
683 }
684
685 #endif // wxUSE_OLE_AUTOMATION