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