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