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