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