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