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