]> git.saurik.com Git - wxWidgets.git/blame - src/msw/ole/automtn.cpp
Deprecated wxSizer::Remove( wxWindow* ), s/Remove/Detach/ in most places.
[wxWidgets.git] / src / msw / ole / automtn.cpp
CommitLineData
d980b3e1
JS
1/////////////////////////////////////////////////////////////////////////////
2// Name: 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#ifdef __GNUG__
13#pragma implementation "automtn.h"
14#endif
15
16// For compilers that support precompilation, includes "wx.h".
17#include "wx/wxprec.h"
18
19#if defined(__BORLANDC__)
20#pragma hdrstop
21#endif
22
f6bcfd97 23#include "wx/defs.h"
d980b3e1 24
457e6c54 25// Watcom C++ gives a linker error if this is compiled in.
f6bcfd97 26// With Borland C++, all samples crash if this is compiled in.
3bce6687 27#if wxUSE_OLE &&!defined(__WATCOMC__) && !(defined(__BORLANDC__) && (__BORLANDC__ < 0x520)) && !defined(__CYGWIN10__) && !defined(__WXWINE__)
457e6c54 28
f6bcfd97 29#include "wx/log.h"
42e69d6b 30#include "wx/msw/ole/automtn.h"
42e69d6b
VZ
31#include "wx/msw/private.h"
32
f6bcfd97
BP
33#include <math.h>
34#include <time.h>
35
7dee726c
RS
36#include <wtypes.h>
37#include <unknwn.h>
38#include <ole2.h>
39#define _huge
42e69d6b
VZ
40#include <ole2ver.h>
41#include <oleauto.h>
17b74d79
JS
42
43// wrapper around BSTR type (by Vadim Zeitlin)
44
45class WXDLLEXPORT BasicString
46{
47public:
48 // ctors & dtor
49 BasicString(const char *sz);
50 ~BasicString();
51
52 // accessors
53 // just get the string
54 operator BSTR() const { return m_wzBuf; }
55 // retrieve a copy of our string - caller must SysFreeString() it later!
56 BSTR Get() const { return SysAllocString(m_wzBuf); }
57
58private:
59 // @@@ not implemented (but should be)
60 BasicString(const BasicString&);
61 BasicString& operator=(const BasicString&);
62
63 OLECHAR *m_wzBuf; // actual string
64};
65
66// Convert variants
67static bool ConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant) ;
68static bool ConvertOleToVariant(const VARIANTARG& oleVariant, wxVariant& variant) ;
69
d980b3e1
JS
70// Convert string to Unicode
71static BSTR ConvertStringToOle(const wxString& str);
72
73// Convert string from BSTR to wxString
74static wxString ConvertStringFromOle(BSTR bStr);
75
76// Verifies will fail if the needed buffer size is too large
77#define MAX_TIME_BUFFER_SIZE 128 // matches that in timecore.cpp
78#define MIN_DATE (-657434L) // about year 100
79#define MAX_DATE 2958465L // about year 9999
80
81// Half a second, expressed in days
82#define HALF_SECOND (1.0/172800.0)
83
84// One-based array of days in year at month start
85static int rgMonthDays[13] =
86 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
87
e421922f 88#if wxUSE_TIMEDATE
d980b3e1
JS
89static BOOL OleDateFromTm(WORD wYear, WORD wMonth, WORD wDay,
90 WORD wHour, WORD wMinute, WORD wSecond, DATE& dtDest);
91static BOOL TmFromOleDate(DATE dtSrc, struct tm& tmDest);
e421922f 92#endif // wxUSE_TIMEDATE
d980b3e1
JS
93
94static void ClearVariant(VARIANTARG *pvarg) ;
95static void ReleaseVariant(VARIANTARG *pvarg) ;
96// static void ShowException(LPOLESTR szMember, HRESULT hr, EXCEPINFO *pexcep, unsigned int uiArgErr);
97
98/*
99 * wxAutomationObject
100 */
101
102wxAutomationObject::wxAutomationObject(WXIDISPATCH* dispatchPtr)
103{
104 m_dispatchPtr = dispatchPtr;
105}
106
107wxAutomationObject::~wxAutomationObject()
108{
109 if (m_dispatchPtr)
110 {
111 ((IDispatch*)m_dispatchPtr)->Release();
112 m_dispatchPtr = NULL;
113 }
114}
115
116#define INVOKEARG(i) (args ? args[i] : *(ptrArgs[i]))
117
118// For Put/Get, no named arguments are allowed.
119bool wxAutomationObject::Invoke(const wxString& member, int action,
120 wxVariant& retValue, int noArgs, wxVariant args[], const wxVariant* ptrArgs[]) const
121{
122 if (!m_dispatchPtr)
123 return FALSE;
124
125 // nonConstMember is necessary because the wxString class doesn't have enough consts...
126 wxString nonConstMember(member);
127
128 int ch = nonConstMember.Find('.');
129 if (ch != -1)
130 {
131 // Use dot notation to get the next object
132 wxString member2(nonConstMember.Left((size_t) ch));
133 wxString rest(nonConstMember.Right(nonConstMember.Length() - ch - 1));
134 wxAutomationObject obj;
135 if (!GetObject(obj, member2))
136 return FALSE;
137 return obj.Invoke(rest, action, retValue, noArgs, args, ptrArgs);
138 }
139
140 VARIANTARG vReturn;
141 ClearVariant(& vReturn);
142
143 VARIANTARG* vReturnPtr = & vReturn;
144
145 // Find number of names args
146 int namedArgCount = 0;
147 int i;
148 for (i = 0; i < noArgs; i++)
149 if (!INVOKEARG(i).GetName().IsNull())
150 {
151 namedArgCount ++;
152 }
153
154 int namedArgStringCount = namedArgCount + 1;
155 BSTR* argNames = new BSTR[namedArgStringCount];
156 argNames[0] = ConvertStringToOle(member);
157
158 // Note that arguments are specified in reverse order
159 // (all totally logical; hey, we're dealing with OLE here.)
160
161 int j = 0;
162 for (i = 0; i < namedArgCount; i++)
163 {
164 if (!INVOKEARG(i).GetName().IsNull())
165 {
166 argNames[(namedArgCount-j)] = ConvertStringToOle(INVOKEARG(i).GetName());
167 j ++;
168 }
169 }
170
171 // + 1 for the member name, + 1 again in case we're a 'put'
172 DISPID* dispIds = new DISPID[namedArgCount + 2];
173
174 HRESULT hr;
175 DISPPARAMS dispparams;
176 unsigned int uiArgErr;
177 EXCEPINFO excep;
178
179 // Get the IDs for the member and its arguments. GetIDsOfNames expects the
180 // member name as the first name, followed by argument names (if any).
181 hr = ((IDispatch*)m_dispatchPtr)->GetIDsOfNames(IID_NULL, argNames,
182 1 + namedArgCount, LOCALE_SYSTEM_DEFAULT, dispIds);
183 if (FAILED(hr))
184 {
185// ShowException(szMember, hr, NULL, 0);
12335fa6
JS
186 delete[] argNames;
187 delete[] dispIds;
d980b3e1
JS
188 return FALSE;
189 }
190
191 // if doing a property put(ref), we need to adjust the first argument to have a
192 // named arg of DISPID_PROPERTYPUT.
193 if (action & (DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF))
194 {
195 namedArgCount = 1;
196 dispIds[1] = DISPID_PROPERTYPUT;
197 vReturnPtr = (VARIANTARG*) NULL;
198 }
199
200 // Convert the wxVariants to VARIANTARGs
201 VARIANTARG* oleArgs = new VARIANTARG[noArgs];
202 for (i = 0; i < noArgs; i++)
203 {
204 // Again, reverse args
7be1f0d9 205 if (!ConvertVariantToOle(INVOKEARG((noArgs-1) - i), oleArgs[i]))
12335fa6
JS
206 {
207 delete[] argNames;
208 delete[] dispIds;
209 delete[] oleArgs;
210 return FALSE;
211 }
d980b3e1
JS
212 }
213
214 dispparams.rgdispidNamedArgs = dispIds + 1;
215 dispparams.rgvarg = oleArgs;
216 dispparams.cArgs = noArgs;
217 dispparams.cNamedArgs = namedArgCount;
218
219 excep.pfnDeferredFillIn = NULL;
220
221 hr = ((IDispatch*)m_dispatchPtr)->Invoke(dispIds[0], IID_NULL, LOCALE_SYSTEM_DEFAULT,
222 action, &dispparams, vReturnPtr, &excep, &uiArgErr);
223
224 for (i = 0; i < namedArgStringCount; i++)
225 {
226 SysFreeString(argNames[i]);
227 }
228 delete[] argNames;
229 delete[] dispIds;
230
231 for (i = 0; i < noArgs; i++)
232 ReleaseVariant(& oleArgs[i]) ;
233 delete[] oleArgs;
234
235 if (FAILED(hr))
236 {
237 // display the exception information if appropriate:
238// ShowException((const char*) member, hr, &excep, uiArgErr);
239
240 // free exception structure information
241 SysFreeString(excep.bstrSource);
242 SysFreeString(excep.bstrDescription);
243 SysFreeString(excep.bstrHelpFile);
244
245 if (vReturnPtr)
246 ReleaseVariant(vReturnPtr);
247 return FALSE;
248 }
249 else
250 {
251 if (vReturnPtr)
252 {
253 // Convert result to wxVariant form
254 ConvertOleToVariant(vReturn, retValue);
255 // Mustn't release the dispatch pointer
256 if (vReturn.vt == VT_DISPATCH)
257 {
258 vReturn.pdispVal = (IDispatch*) NULL;
259 }
260 ReleaseVariant(& vReturn);
261 }
262 }
263 return TRUE;
264}
265
266// Invoke a member function
267wxVariant wxAutomationObject::CallMethod(const wxString& member, int noArgs, wxVariant args[])
268{
269 wxVariant retVariant;
270 if (!Invoke(member, DISPATCH_METHOD, retVariant, noArgs, args))
271 {
272 retVariant.MakeNull();
273 }
274 return retVariant;
275}
276
24f4ad95
JS
277wxVariant wxAutomationObject::CallMethodArray(const wxString& member, int noArgs, const wxVariant **args)
278{
279 wxVariant retVariant;
280 if (!Invoke(member, DISPATCH_METHOD, retVariant, noArgs, NULL, args))
281 {
282 retVariant.MakeNull();
283 }
284 return retVariant;
285}
286
d980b3e1
JS
287wxVariant wxAutomationObject::CallMethod(const wxString& member,
288 const wxVariant& arg1, const wxVariant& arg2,
289 const wxVariant& arg3, const wxVariant& arg4,
290 const wxVariant& arg5, const wxVariant& arg6)
291{
292 const wxVariant** args = new const wxVariant*[6];
293 int i = 0;
294 if (!arg1.IsNull())
295 {
296 args[i] = & arg1;
297 i ++;
298 }
299 if (!arg2.IsNull())
300 {
301 args[i] = & arg2;
302 i ++;
303 }
304 if (!arg3.IsNull())
305 {
306 args[i] = & arg3;
307 i ++;
308 }
309 if (!arg4.IsNull())
310 {
311 args[i] = & arg4;
312 i ++;
313 }
314 if (!arg5.IsNull())
315 {
316 args[i] = & arg5;
317 i ++;
318 }
319 if (!arg6.IsNull())
320 {
321 args[i] = & arg6;
322 i ++;
323 }
324 wxVariant retVariant;
325 if (!Invoke(member, DISPATCH_METHOD, retVariant, i, NULL, args))
326 {
327 retVariant.MakeNull();
328 }
329 delete[] args;
330 return retVariant;
331}
332
333// Get/Set property
24f4ad95
JS
334wxVariant wxAutomationObject::GetPropertyArray(const wxString& property, int noArgs, const wxVariant **args) const
335{
336 wxVariant retVariant;
337 if (!Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, NULL, args))
338 {
339 retVariant.MakeNull();
340 }
341 return retVariant;
342}
d980b3e1
JS
343wxVariant wxAutomationObject::GetProperty(const wxString& property, int noArgs, wxVariant args[]) const
344{
345 wxVariant retVariant;
346 if (!Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, args))
347 {
348 retVariant.MakeNull();
349 }
350 return retVariant;
351}
352
353wxVariant wxAutomationObject::GetProperty(const wxString& property,
354 const wxVariant& arg1, const wxVariant& arg2,
355 const wxVariant& arg3, const wxVariant& arg4,
356 const wxVariant& arg5, const wxVariant& arg6)
357{
358 const wxVariant** args = new const wxVariant*[6];
359 int i = 0;
360 if (!arg1.IsNull())
361 {
362 args[i] = & arg1;
363 i ++;
364 }
365 if (!arg2.IsNull())
366 {
367 args[i] = & arg2;
368 i ++;
369 }
370 if (!arg3.IsNull())
371 {
372 args[i] = & arg3;
373 i ++;
374 }
375 if (!arg4.IsNull())
376 {
377 args[i] = & arg4;
378 i ++;
379 }
380 if (!arg5.IsNull())
381 {
382 args[i] = & arg5;
383 i ++;
384 }
385 if (!arg6.IsNull())
386 {
387 args[i] = & arg6;
388 i ++;
389 }
390 wxVariant retVariant;
391 if (!Invoke(property, DISPATCH_PROPERTYGET, retVariant, i, NULL, args))
392 {
393 retVariant.MakeNull();
394 }
395 delete[] args;
396 return retVariant;
397}
398
399bool wxAutomationObject::PutProperty(const wxString& property, int noArgs, wxVariant args[])
400{
401 wxVariant retVariant;
402 if (!Invoke(property, DISPATCH_PROPERTYPUT, retVariant, noArgs, args))
403 {
404 return FALSE;
405 }
406 return TRUE;
407}
408
24f4ad95
JS
409bool wxAutomationObject::PutPropertyArray(const wxString& property, int noArgs, const wxVariant **args)
410{
411 wxVariant retVariant;
412 if (!Invoke(property, DISPATCH_PROPERTYPUT, retVariant, noArgs, NULL, args))
413 {
414 return FALSE;
415 }
416 return TRUE;
417}
418
d980b3e1
JS
419bool wxAutomationObject::PutProperty(const wxString& property,
420 const wxVariant& arg1, const wxVariant& arg2,
421 const wxVariant& arg3, const wxVariant& arg4,
422 const wxVariant& arg5, const wxVariant& arg6)
423{
424 const wxVariant** args = new const wxVariant*[6];
425 int i = 0;
426 if (!arg1.IsNull())
427 {
428 args[i] = & arg1;
429 i ++;
430 }
431 if (!arg2.IsNull())
432 {
433 args[i] = & arg2;
434 i ++;
435 }
436 if (!arg3.IsNull())
437 {
438 args[i] = & arg3;
439 i ++;
440 }
441 if (!arg4.IsNull())
442 {
443 args[i] = & arg4;
444 i ++;
445 }
446 if (!arg5.IsNull())
447 {
448 args[i] = & arg5;
449 i ++;
450 }
451 if (!arg6.IsNull())
452 {
453 args[i] = & arg6;
454 i ++;
455 }
456 wxVariant retVariant;
457 bool ret = Invoke(property, DISPATCH_PROPERTYPUT, retVariant, i, NULL, args);
458 delete[] args;
459 return ret;
460}
461
462
463// Uses DISPATCH_PROPERTYGET
464// and returns a dispatch pointer. The calling code should call Release
465// on the pointer, though this could be implicit by constructing an wxAutomationObject
466// with it and letting the destructor call Release.
467WXIDISPATCH* wxAutomationObject::GetDispatchProperty(const wxString& property, int noArgs, wxVariant args[]) const
468{
469 wxVariant retVariant;
470 if (Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, args))
471 {
223d09f6 472 if (retVariant.GetType() == wxT("void*"))
d980b3e1
JS
473 {
474 return (WXIDISPATCH*) retVariant.GetVoidPtr();
475 }
d980b3e1 476 }
3ca6a5f0
BP
477
478 return (WXIDISPATCH*) NULL;
d980b3e1
JS
479}
480
24f4ad95
JS
481// Uses DISPATCH_PROPERTYGET
482// and returns a dispatch pointer. The calling code should call Release
483// on the pointer, though this could be implicit by constructing an wxAutomationObject
484// with it and letting the destructor call Release.
485WXIDISPATCH* wxAutomationObject::GetDispatchProperty(const wxString& property, int noArgs, const wxVariant **args) const
486{
487 wxVariant retVariant;
488 if (Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, NULL, args))
489 {
490 if (retVariant.GetType() == wxT("void*"))
491 {
492 return (WXIDISPATCH*) retVariant.GetVoidPtr();
493 }
494 }
495
496 return (WXIDISPATCH*) NULL;
497}
498
499
d980b3e1
JS
500// A way of initialising another wxAutomationObject with a dispatch object
501bool wxAutomationObject::GetObject(wxAutomationObject& obj, const wxString& property, int noArgs, wxVariant args[]) const
502{
503 WXIDISPATCH* dispatch = GetDispatchProperty(property, noArgs, args);
504 if (dispatch)
505 {
506 obj.SetDispatchPtr(dispatch);
507 return TRUE;
508 }
509 else
510 return FALSE;
511}
512
24f4ad95
JS
513// A way of initialising another wxAutomationObject with a dispatch object
514bool wxAutomationObject::GetObject(wxAutomationObject& obj, const wxString& property, int noArgs, const wxVariant **args) const
515{
516 WXIDISPATCH* dispatch = GetDispatchProperty(property, noArgs, args);
517 if (dispatch)
518 {
519 obj.SetDispatchPtr(dispatch);
520 return TRUE;
521 }
522 else
523 return FALSE;
524}
525
d980b3e1
JS
526// Get a dispatch pointer from the current object associated
527// with a class id
528bool wxAutomationObject::GetInstance(const wxString& classId) const
529{
530 if (m_dispatchPtr)
531 return FALSE;
532
533 CLSID clsId;
534 IUnknown * pUnk = NULL;
535
b6caf397 536 BasicString unicodeName(classId.mb_str());
d980b3e1
JS
537
538 if (FAILED(CLSIDFromProgID((BSTR) unicodeName, &clsId)))
539 {
223d09f6 540 wxLogWarning(wxT("Cannot obtain CLSID from ProgID"));
d980b3e1
JS
541 return FALSE;
542 }
543
544 if (FAILED(GetActiveObject(clsId, NULL, &pUnk)))
545 {
223d09f6 546 wxLogWarning(wxT("Cannot find an active object"));
d980b3e1
JS
547 return FALSE;
548 }
549
550 if (pUnk->QueryInterface(IID_IDispatch, (LPVOID*) &m_dispatchPtr) != S_OK)
551 {
223d09f6 552 wxLogWarning(wxT("Cannot find IDispatch interface"));
d980b3e1
JS
553 return FALSE;
554 }
555
556 return TRUE;
557}
558
559// Get a dispatch pointer from a new object associated
560// with the given class id
561bool wxAutomationObject::CreateInstance(const wxString& classId) const
562{
563 if (m_dispatchPtr)
564 return FALSE;
565
566 CLSID clsId;
d980b3e1 567
b6caf397 568 BasicString unicodeName(classId.mb_str());
d980b3e1
JS
569
570 if (FAILED(CLSIDFromProgID((BSTR) unicodeName, &clsId)))
571 {
223d09f6 572 wxLogWarning(wxT("Cannot obtain CLSID from ProgID"));
d980b3e1
JS
573 return FALSE;
574 }
575
576 // start a new copy of Excel, grab the IDispatch interface
577 if (FAILED(CoCreateInstance(clsId, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void**)&m_dispatchPtr)))
578 {
223d09f6 579 wxLogWarning(wxT("Cannot start an instance of this class."));
d980b3e1
JS
580 return FALSE;
581 }
582
583 return TRUE;
584}
585
586
17b74d79 587bool ConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant)
d980b3e1
JS
588{
589 ClearVariant(&oleVariant);
590 if (variant.IsNull())
591 {
592 oleVariant.vt = VT_NULL;
593 return TRUE;
594 }
595
596 wxString type(variant.GetType());
597
6b978929
JS
598
599 if (type == wxT("long"))
d980b3e1
JS
600 {
601 oleVariant.vt = VT_I4;
602 oleVariant.lVal = variant.GetLong() ;
603 }
6b978929
JS
604 // cVal not always present
605#ifndef __GNUWIN32__
606 else if (type == wxT("char"))
607 {
608 oleVariant.vt=VT_I1; // Signed Char
609 oleVariant.cVal=variant.GetChar();
610 }
611#endif
223d09f6 612 else if (type == wxT("double"))
d980b3e1
JS
613 {
614 oleVariant.vt = VT_R8;
615 oleVariant.dblVal = variant.GetDouble();
616 }
223d09f6 617 else if (type == wxT("bool"))
d980b3e1
JS
618 {
619 oleVariant.vt = VT_BOOL;
7c5dc04f 620 // 'bool' required for VC++ 4 apparently
aeab10d0 621#if defined(__WATCOMC__) || (defined(__VISUALC__) && (__VISUALC__ <= 1000))
7be1f0d9
JS
622 oleVariant.bool = variant.GetBool();
623#else
d980b3e1 624 oleVariant.boolVal = variant.GetBool();
7be1f0d9 625#endif
d980b3e1 626 }
223d09f6 627 else if (type == wxT("string"))
d980b3e1
JS
628 {
629 wxString str( variant.GetString() );
630 oleVariant.vt = VT_BSTR;
631 oleVariant.bstrVal = ConvertStringToOle(str);
632 }
457e6c54
JS
633// For some reason, Watcom C++ can't link variant.cpp with time/date classes compiled
634#if wxUSE_TIMEDATE && !defined(__WATCOMC__)
223d09f6 635 else if (type == wxT("date"))
d980b3e1
JS
636 {
637 wxDate date( variant.GetDate() );
638 oleVariant.vt = VT_DATE;
639
640 if (!OleDateFromTm(date.GetYear(), date.GetMonth(), date.GetDay(),
641 0, 0, 0, oleVariant.date))
642 return FALSE;
643 }
223d09f6 644 else if (type == wxT("time"))
d980b3e1
JS
645 {
646 wxTime time( variant.GetTime() );
647 oleVariant.vt = VT_DATE;
648
649 if (!OleDateFromTm(time.GetYear(), time.GetMonth(), time.GetDay(),
650 time.GetHour(), time.GetMinute(), time.GetSecond(), oleVariant.date))
651 return FALSE;
652 }
457e6c54 653#endif
223d09f6 654 else if (type == wxT("void*"))
d980b3e1
JS
655 {
656 oleVariant.vt = VT_DISPATCH;
657 oleVariant.pdispVal = (IDispatch*) variant.GetVoidPtr();
658 }
223d09f6 659 else if (type == wxT("list") || type == wxT("stringlist"))
d980b3e1
JS
660 {
661 oleVariant.vt = VT_VARIANT | VT_ARRAY;
662
663 SAFEARRAY *psa;
664 SAFEARRAYBOUND saBound;
665 VARIANTARG *pvargBase;
666 VARIANTARG *pvarg;
667 int i, j;
668
669 int iCount = variant.GetCount();
670
671 saBound.lLbound = 0;
672 saBound.cElements = iCount;
673
674 psa = SafeArrayCreate(VT_VARIANT, 1, &saBound);
675 if (psa == NULL)
676 return FALSE;
677
678 SafeArrayAccessData(psa, (void**)&pvargBase);
679
680 pvarg = pvargBase;
681 for (i = 0; i < iCount; i++)
682 {
683 // copy each string in the list of strings
684 wxVariant eachVariant(variant[i]);
685 if (!ConvertVariantToOle(eachVariant, * pvarg))
686 {
687 // memory failure: back out and free strings alloc'ed up to
688 // now, and then the array itself.
689 pvarg = pvargBase;
690 for (j = 0; j < i; j++)
691 {
692 SysFreeString(pvarg->bstrVal);
693 pvarg++;
694 }
695 SafeArrayDestroy(psa);
696 return FALSE;
697 }
698 pvarg++;
699 }
700
701 SafeArrayUnaccessData(psa);
702
703 oleVariant.parray = psa;
704 }
705 else
706 {
707 oleVariant.vt = VT_NULL;
708 return FALSE;
709 }
710 return TRUE;
711}
712
713#ifndef VT_TYPEMASK
714#define VT_TYPEMASK 0xfff
715#endif
716
17b74d79 717bool ConvertOleToVariant(const VARIANTARG& oleVariant, wxVariant& variant)
d980b3e1
JS
718{
719 switch (oleVariant.vt & VT_TYPEMASK)
720 {
721 case VT_BSTR:
722 {
723 wxString str(ConvertStringFromOle(oleVariant.bstrVal));
724 variant = str;
725 break;
726 }
727 case VT_DATE:
728 {
f6bcfd97
BP
729#if wxUSE_TIMEDATE
730 struct tm tmTemp;
d980b3e1
JS
731 if (!TmFromOleDate(oleVariant.date, tmTemp))
732 return FALSE;
733
734 wxDate date(tmTemp.tm_yday, tmTemp.tm_mon, tmTemp.tm_year);
735 wxTime time(date, tmTemp.tm_hour, tmTemp.tm_min, tmTemp.tm_sec);
736
737 variant = time;
f6bcfd97
BP
738#endif
739
740 break;
d980b3e1
JS
741 }
742 case VT_I4:
743 {
744 variant = (long) oleVariant.lVal;
745 break;
746 }
747 case VT_I2:
748 {
749 variant = (long) oleVariant.iVal;
750 break;
751 }
752
753 case VT_BOOL:
754 {
585ae8cb 755#if defined(__WATCOMC__) || (defined(_MSC_VER) && (_MSC_VER <= 1000) && !defined(__MWERKS__) ) //GC
25889d3c
JS
756#ifndef HAVE_BOOL // Can't use bool operator if no native bool type
757 variant = (long) (oleVariant.bool != 0);
758#else
7be1f0d9 759 variant = (bool) (oleVariant.bool != 0);
25889d3c 760#endif
f6bcfd97
BP
761#else
762#ifndef HAVE_BOOL // Can't use bool operator if no native bool type
763 variant = (long) (oleVariant.boolVal != 0);
7be1f0d9 764#else
d980b3e1 765 variant = (bool) (oleVariant.boolVal != 0);
f6bcfd97 766#endif
7be1f0d9 767#endif
d980b3e1
JS
768 break;
769 }
770 case VT_R8:
771 {
772 variant = oleVariant.dblVal;
773 break;
774 }
775 case VT_ARRAY:
776 {
777 variant.ClearList();
778
779 int cDims, cElements, i;
780 VARIANTARG* pvdata;
781
782 // Iterate the dimensions: number of elements is x*y*z
783 for (cDims = 0, cElements = 1;
784 cDims < oleVariant.parray->cDims; cDims ++)
785 cElements *= oleVariant.parray->rgsabound[cDims].cElements;
786
787 // Get a pointer to the data
788 HRESULT hr = SafeArrayAccessData(oleVariant.parray, (void HUGEP* FAR*) & pvdata);
789 if (hr != NOERROR)
790 return FALSE;
791 // Iterate the data.
792 for (i = 0; i < cElements; i++)
793 {
794 VARIANTARG& oleElement = pvdata[i];
795 wxVariant vElement;
796 if (!ConvertOleToVariant(oleElement, vElement))
797 return FALSE;
798
799 variant.Append(vElement);
800 }
801 SafeArrayUnaccessData(oleVariant.parray);
802 break;
803 }
804 case VT_DISPATCH:
805 {
806 variant = (void*) oleVariant.pdispVal;
807 break;
808 }
809 case VT_NULL:
810 {
811 variant.MakeNull();
812 break;
813 }
5dcf05ae
JS
814 case VT_EMPTY:
815 {
816 break; // Ignore Empty Variant, used only during destruction of objects
817 }
d980b3e1
JS
818 default:
819 {
223d09f6 820 wxLogError(wxT("wxAutomationObject::ConvertOleToVariant: Unknown variant value type"));
d980b3e1
JS
821 return FALSE;
822 }
823 }
824 return TRUE;
825}
826
827static BSTR ConvertStringToOle(const wxString& str)
828{
829/*
830 unsigned int len = strlen((const char*) str);
831 unsigned short* s = new unsigned short[len*2+2];
832 unsigned int i;
833 memset(s, 0, len*2+2);
834 for (i=0; i < len; i++)
835 s[i*2] = str[i];
836*/
b6caf397 837 BasicString bstr(str.mb_str());
d980b3e1
JS
838 return bstr.Get();
839}
840
841static wxString ConvertStringFromOle(BSTR bStr)
842{
2b5f62a0
VZ
843#if wxUSE_UNICODE
844 wxString str(bStr);
845#else
d980b3e1
JS
846 int len = SysStringLen(bStr) + 1;
847 char *buf = new char[len];
b21624e7 848 (void)wcstombs( buf, bStr, len);
2b5f62a0 849 wxString str(buf);
d980b3e1 850 delete[] buf;
2b5f62a0 851#endif
d980b3e1
JS
852 return str;
853}
854
855// ----------------------------------------------------------------------------
856// BasicString
857// ----------------------------------------------------------------------------
858
859// ctor takes an ANSI string and transforms it to Unicode
860BasicString::BasicString(const char *sz)
861{
862 // get the size of required buffer
863 UINT lenAnsi = strlen(sz);
b2cce0c4
SC
864 #ifdef __MWERKS__
865 UINT lenWide = lenAnsi * 2 ;
866 #else
d980b3e1 867 UINT lenWide = mbstowcs(NULL, sz, lenAnsi);
b2cce0c4 868 #endif
d980b3e1
JS
869
870 if ( lenWide > 0 ) {
871 m_wzBuf = new OLECHAR[lenWide + 1];
872 mbstowcs(m_wzBuf, sz, lenAnsi);
873 m_wzBuf[lenWide] = L'\0';
874 }
875 else {
876 m_wzBuf = NULL;
877 }
878}
879
880// dtor frees memory
881BasicString::~BasicString()
882{
883 delete [] m_wzBuf;
884}
885
886/////////////////////////////////////////////////////////////////////////////
887// COleDateTime class HELPERS - implementation
888
889BOOL OleDateFromTm(WORD wYear, WORD wMonth, WORD wDay,
890 WORD wHour, WORD wMinute, WORD wSecond, DATE& dtDest)
891{
892 // Validate year and month (ignore day of week and milliseconds)
893 if (wYear > 9999 || wMonth < 1 || wMonth > 12)
894 return FALSE;
895
896 // Check for leap year and set the number of days in the month
897 BOOL bLeapYear = ((wYear & 3) == 0) &&
898 ((wYear % 100) != 0 || (wYear % 400) == 0);
899
900 int nDaysInMonth =
901 rgMonthDays[wMonth] - rgMonthDays[wMonth-1] +
902 ((bLeapYear && wDay == 29 && wMonth == 2) ? 1 : 0);
903
904 // Finish validating the date
905 if (wDay < 1 || wDay > nDaysInMonth ||
906 wHour > 23 || wMinute > 59 ||
907 wSecond > 59)
908 {
909 return FALSE;
910 }
911
912 // Cache the date in days and time in fractional days
913 long nDate;
914 double dblTime;
915
916 //It is a valid date; make Jan 1, 1AD be 1
917 nDate = wYear*365L + wYear/4 - wYear/100 + wYear/400 +
918 rgMonthDays[wMonth-1] + wDay;
919
920 // If leap year and it's before March, subtract 1:
921 if (wMonth <= 2 && bLeapYear)
922 --nDate;
923
924 // Offset so that 12/30/1899 is 0
925 nDate -= 693959L;
926
927 dblTime = (((long)wHour * 3600L) + // hrs in seconds
928 ((long)wMinute * 60L) + // mins in seconds
929 ((long)wSecond)) / 86400.;
930
931 dtDest = (double) nDate + ((nDate >= 0) ? dblTime : -dblTime);
932
933 return TRUE;
934}
935
936BOOL TmFromOleDate(DATE dtSrc, struct tm& tmDest)
937{
938 // The legal range does not actually span year 0 to 9999.
939 if (dtSrc > MAX_DATE || dtSrc < MIN_DATE) // about year 100 to about 9999
940 return FALSE;
941
942 long nDays; // Number of days since Dec. 30, 1899
943 long nDaysAbsolute; // Number of days since 1/1/0
944 long nSecsInDay; // Time in seconds since midnight
945 long nMinutesInDay; // Minutes in day
946
947 long n400Years; // Number of 400 year increments since 1/1/0
948 long n400Century; // Century within 400 year block (0,1,2 or 3)
949 long n4Years; // Number of 4 year increments since 1/1/0
950 long n4Day; // Day within 4 year block
951 // (0 is 1/1/yr1, 1460 is 12/31/yr4)
952 long n4Yr; // Year within 4 year block (0,1,2 or 3)
953 BOOL bLeap4 = TRUE; // TRUE if 4 year block includes leap year
954
955 double dblDate = dtSrc; // tempory serial date
956
957 // If a valid date, then this conversion should not overflow
958 nDays = (long)dblDate;
959
960 // Round to the second
961 dblDate += ((dtSrc > 0.0) ? HALF_SECOND : -HALF_SECOND);
962
963 nDaysAbsolute = (long)dblDate + 693959L; // Add days from 1/1/0 to 12/30/1899
964
965 dblDate = fabs(dblDate);
966 nSecsInDay = (long)((dblDate - floor(dblDate)) * 86400.);
967
968 // Calculate the day of week (sun=1, mon=2...)
969 // -1 because 1/1/0 is Sat. +1 because we want 1-based
970 tmDest.tm_wday = (int)((nDaysAbsolute - 1) % 7L) + 1;
971
972 // Leap years every 4 yrs except centuries not multiples of 400.
973 n400Years = (long)(nDaysAbsolute / 146097L);
974
975 // Set nDaysAbsolute to day within 400-year block
976 nDaysAbsolute %= 146097L;
977
978 // -1 because first century has extra day
979 n400Century = (long)((nDaysAbsolute - 1) / 36524L);
980
981 // Non-leap century
982 if (n400Century != 0)
983 {
984 // Set nDaysAbsolute to day within century
985 nDaysAbsolute = (nDaysAbsolute - 1) % 36524L;
986
987 // +1 because 1st 4 year increment has 1460 days
988 n4Years = (long)((nDaysAbsolute + 1) / 1461L);
989
990 if (n4Years != 0)
991 n4Day = (long)((nDaysAbsolute + 1) % 1461L);
992 else
993 {
994 bLeap4 = FALSE;
995 n4Day = (long)nDaysAbsolute;
996 }
997 }
998 else
999 {
1000 // Leap century - not special case!
1001 n4Years = (long)(nDaysAbsolute / 1461L);
1002 n4Day = (long)(nDaysAbsolute % 1461L);
1003 }
1004
1005 if (bLeap4)
1006 {
1007 // -1 because first year has 366 days
1008 n4Yr = (n4Day - 1) / 365;
1009
1010 if (n4Yr != 0)
1011 n4Day = (n4Day - 1) % 365;
1012 }
1013 else
1014 {
1015 n4Yr = n4Day / 365;
1016 n4Day %= 365;
1017 }
1018
1019 // n4Day is now 0-based day of year. Save 1-based day of year, year number
1020 tmDest.tm_yday = (int)n4Day + 1;
1021 tmDest.tm_year = n400Years * 400 + n400Century * 100 + n4Years * 4 + n4Yr;
1022
1023 // Handle leap year: before, on, and after Feb. 29.
1024 if (n4Yr == 0 && bLeap4)
1025 {
1026 // Leap Year
1027 if (n4Day == 59)
1028 {
1029 /* Feb. 29 */
1030 tmDest.tm_mon = 2;
1031 tmDest.tm_mday = 29;
1032 goto DoTime;
1033 }
1034
1035 // Pretend it's not a leap year for month/day comp.
1036 if (n4Day >= 60)
1037 --n4Day;
1038 }
1039
1040 // Make n4DaY a 1-based day of non-leap year and compute
1041 // month/day for everything but Feb. 29.
1042 ++n4Day;
1043
1044 // Month number always >= n/32, so save some loop time */
1045 for (tmDest.tm_mon = (n4Day >> 5) + 1;
1046 n4Day > rgMonthDays[tmDest.tm_mon]; tmDest.tm_mon++);
1047
1048 tmDest.tm_mday = (int)(n4Day - rgMonthDays[tmDest.tm_mon-1]);
1049
1050DoTime:
1051 if (nSecsInDay == 0)
1052 tmDest.tm_hour = tmDest.tm_min = tmDest.tm_sec = 0;
1053 else
1054 {
1055 tmDest.tm_sec = (int)nSecsInDay % 60L;
1056 nMinutesInDay = nSecsInDay / 60L;
1057 tmDest.tm_min = (int)nMinutesInDay % 60;
1058 tmDest.tm_hour = (int)nMinutesInDay / 60;
1059 }
1060
1061 return TRUE;
1062}
1063
b21624e7
VZ
1064// this function is not used
1065#if 0
d980b3e1
JS
1066void TmConvertToStandardFormat(struct tm& tmSrc)
1067{
1068 // Convert afx internal tm to format expected by runtimes (_tcsftime, etc)
1069 tmSrc.tm_year -= 1900; // year is based on 1900
1070 tmSrc.tm_mon -= 1; // month of year is 0-based
1071 tmSrc.tm_wday -= 1; // day of week is 0-based
1072 tmSrc.tm_yday -= 1; // day of year is 0-based
1073}
1074
1075double DoubleFromDate(DATE dt)
1076{
1077 // No problem if positive
1078 if (dt >= 0)
1079 return dt;
1080
1081 // If negative, must convert since negative dates not continuous
1082 // (examples: -1.25 to -.75, -1.50 to -.50, -1.75 to -.25)
1083 double temp = ceil(dt);
1084 return temp - (dt - temp);
1085}
1086
1087DATE DateFromDouble(double dbl)
1088{
1089 // No problem if positive
1090 if (dbl >= 0)
1091 return dbl;
1092
1093 // If negative, must convert since negative dates not continuous
1094 // (examples: -.75 to -1.25, -.50 to -1.50, -.25 to -1.75)
1095 double temp = floor(dbl); // dbl is now whole part
1096 return temp + (temp - dbl);
1097}
b21624e7 1098#endif // 0
d980b3e1
JS
1099
1100/*
1101 * ClearVariant
1102 *
1103 * Zeros a variant structure without regard to current contents
1104 */
1105static void ClearVariant(VARIANTARG *pvarg)
1106{
1107 pvarg->vt = VT_EMPTY;
1108 pvarg->wReserved1 = 0;
1109 pvarg->wReserved2 = 0;
1110 pvarg->wReserved3 = 0;
1111 pvarg->lVal = 0;
1112}
1113
1114/*
1115 * ReleaseVariant
1116 *
1117 * Clears a particular variant structure and releases any external objects
1118 * or memory contained in the variant. Supports the data types listed above.
1119 */
1120static void ReleaseVariant(VARIANTARG *pvarg)
1121{
1122 VARTYPE vt;
1123 VARIANTARG _huge *pvargArray;
1124 long lLBound, lUBound, l;
1125
1126 vt = pvarg->vt & 0xfff; // mask off flags
1127
1128 // check if an array. If so, free its contents, then the array itself.
1129 if (V_ISARRAY(pvarg))
1130 {
1131 // variant arrays are all this routine currently knows about. Since a
1132 // variant can contain anything (even other arrays), call ourselves
1133 // recursively.
1134 if (vt == VT_VARIANT)
1135 {
1136 SafeArrayGetLBound(pvarg->parray, 1, &lLBound);
1137 SafeArrayGetUBound(pvarg->parray, 1, &lUBound);
1138
1139 if (lUBound > lLBound)
1140 {
1141 lUBound -= lLBound;
1142
1143 SafeArrayAccessData(pvarg->parray, (void**)&pvargArray);
1144
1145 for (l = 0; l < lUBound; l++)
1146 {
1147 ReleaseVariant(pvargArray);
1148 pvargArray++;
1149 }
1150
1151 SafeArrayUnaccessData(pvarg->parray);
1152 }
1153 }
1154 else
1155 {
223d09f6 1156 wxLogWarning(wxT("ReleaseVariant: Array contains non-variant type"));
d980b3e1
JS
1157 }
1158
1159 // Free the array itself.
1160 SafeArrayDestroy(pvarg->parray);
1161 }
1162 else
1163 {
1164 switch (vt)
1165 {
1166 case VT_DISPATCH:
1167 if (pvarg->pdispVal)
1168 pvarg->pdispVal->Release();
1169 break;
1170
1171 case VT_BSTR:
1172 SysFreeString(pvarg->bstrVal);
1173 break;
1174
1175 case VT_I2:
1176 case VT_BOOL:
1177 case VT_R8:
1178 case VT_ERROR: // to avoid erroring on an error return from Excel
1179 // no work for these types
1180 break;
1181
1182 default:
223d09f6 1183 wxLogWarning(wxT("ReleaseVariant: Unknown type"));
d980b3e1
JS
1184 break;
1185 }
1186 }
1187
1188 ClearVariant(pvarg);
1189}
1190
1191#if 0
1192
1193void ShowException(LPOLESTR szMember, HRESULT hr, EXCEPINFO *pexcep, unsigned int uiArgErr)
1194{
1195 TCHAR szBuf[512];
1196
1197 switch (GetScode(hr))
1198 {
1199 case DISP_E_UNKNOWNNAME:
1200 wsprintf(szBuf, L"%s: Unknown name or named argument.", szMember);
1201 break;
1202
1203 case DISP_E_BADPARAMCOUNT:
1204 wsprintf(szBuf, L"%s: Incorrect number of arguments.", szMember);
1205 break;
1206
1207 case DISP_E_EXCEPTION:
1208 wsprintf(szBuf, L"%s: Error %d: ", szMember, pexcep->wCode);
1209 if (pexcep->bstrDescription != NULL)
1210 lstrcat(szBuf, pexcep->bstrDescription);
1211 else
1212 lstrcat(szBuf, L"<<No Description>>");
1213 break;
1214
1215 case DISP_E_MEMBERNOTFOUND:
1216 wsprintf(szBuf, L"%s: method or property not found.", szMember);
1217 break;
1218
1219 case DISP_E_OVERFLOW:
1220 wsprintf(szBuf, L"%s: Overflow while coercing argument values.", szMember);
1221 break;
1222
1223 case DISP_E_NONAMEDARGS:
1224 wsprintf(szBuf, L"%s: Object implementation does not support named arguments.",
1225 szMember);
1226 break;
1227
1228 case DISP_E_UNKNOWNLCID:
1229 wsprintf(szBuf, L"%s: The locale ID is unknown.", szMember);
1230 break;
1231
1232 case DISP_E_PARAMNOTOPTIONAL:
1233 wsprintf(szBuf, L"%s: Missing a required parameter.", szMember);
1234 break;
1235
1236 case DISP_E_PARAMNOTFOUND:
1237 wsprintf(szBuf, L"%s: Argument not found, argument %d.", szMember, uiArgErr);
1238 break;
1239
1240 case DISP_E_TYPEMISMATCH:
1241 wsprintf(szBuf, L"%s: Type mismatch, argument %d.", szMember, uiArgErr);
1242 break;
1243
1244 default:
1245 wsprintf(szBuf, L"%s: Unknown error occured.", szMember);
1246 break;
1247 }
1248
1249 wxLogWarning(szBuf);
1250}
1251
1252#endif
1253
457e6c54
JS
1254#endif // __WATCOMC__
1255