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