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