]> git.saurik.com Git - wxWidgets.git/blob - src/msw/ole/automtn.cpp
signed/unsigned comparison warning 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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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(__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(__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 #if wxUSE_DATETIME
615 else if (type == wxT("datetime"))
616 {
617 wxDateTime date( variant.GetDateTime() );
618 oleVariant.vt = VT_DATE;
619
620 if (!OleDateFromTm(date.GetYear(), date.GetMonth(), date.GetDay(),
621 date.GetHour(), date.GetMinute(), date.GetSecond(), oleVariant.date))
622 return false;
623 }
624 #endif
625 else if (type == wxT("void*"))
626 {
627 oleVariant.vt = VT_DISPATCH;
628 oleVariant.pdispVal = (IDispatch*) variant.GetVoidPtr();
629 }
630 else if (type == wxT("list") || type == wxT("stringlist"))
631 {
632 oleVariant.vt = VT_VARIANT | VT_ARRAY;
633
634 SAFEARRAY *psa;
635 SAFEARRAYBOUND saBound;
636 VARIANTARG *pvargBase;
637 VARIANTARG *pvarg;
638 int i, j;
639
640 int iCount = variant.GetCount();
641
642 saBound.lLbound = 0;
643 saBound.cElements = iCount;
644
645 psa = SafeArrayCreate(VT_VARIANT, 1, &saBound);
646 if (psa == NULL)
647 return false;
648
649 SafeArrayAccessData(psa, (void**)&pvargBase);
650
651 pvarg = pvargBase;
652 for (i = 0; i < iCount; i++)
653 {
654 // copy each string in the list of strings
655 wxVariant eachVariant(variant[i]);
656 if (!wxConvertVariantToOle(eachVariant, * pvarg))
657 {
658 // memory failure: back out and free strings alloc'ed up to
659 // now, and then the array itself.
660 pvarg = pvargBase;
661 for (j = 0; j < i; j++)
662 {
663 SysFreeString(pvarg->bstrVal);
664 pvarg++;
665 }
666 SafeArrayDestroy(psa);
667 return false;
668 }
669 pvarg++;
670 }
671
672 SafeArrayUnaccessData(psa);
673
674 oleVariant.parray = psa;
675 }
676 else
677 {
678 oleVariant.vt = VT_NULL;
679 return false;
680 }
681 return true;
682 }
683
684 #ifndef VT_TYPEMASK
685 #define VT_TYPEMASK 0xfff
686 #endif
687
688 bool wxConvertOleToVariant(const VARIANTARG& oleVariant, wxVariant& variant)
689 {
690 switch (oleVariant.vt & VT_TYPEMASK)
691 {
692 case VT_BSTR:
693 {
694 wxString str(wxConvertStringFromOle(oleVariant.bstrVal));
695 variant = str;
696 break;
697 }
698 case VT_DATE:
699 {
700 #if wxUSE_DATETIME
701 struct tm tmTemp;
702 if (!TmFromOleDate(oleVariant.date, tmTemp))
703 return false;
704
705 wxDateTime date(tmTemp.tm_yday, (wxDateTime::Month) tmTemp.tm_mon, tmTemp.tm_year, tmTemp.tm_hour, tmTemp.tm_min, tmTemp.tm_sec);
706
707 variant = date;
708 #endif
709
710 break;
711 }
712 case VT_I4:
713 {
714 variant = (long) oleVariant.lVal;
715 break;
716 }
717 case VT_I2:
718 {
719 variant = (long) oleVariant.iVal;
720 break;
721 }
722
723 case VT_BOOL:
724 {
725 #if (defined(_MSC_VER) && (_MSC_VER <= 1000) && !defined(__MWERKS__) ) //GC
726 #ifndef HAVE_BOOL // Can't use bool operator if no native bool type
727 variant = (long) (oleVariant.bool != 0);
728 #else
729 variant = (bool) (oleVariant.bool != 0);
730 #endif
731 #else
732 #ifndef HAVE_BOOL // Can't use bool operator if no native bool type
733 variant = (long) (oleVariant.boolVal != 0);
734 #else
735 variant = (bool) (oleVariant.boolVal != 0);
736 #endif
737 #endif
738 break;
739 }
740 case VT_R8:
741 {
742 variant = oleVariant.dblVal;
743 break;
744 }
745 case VT_ARRAY:
746 {
747 variant.ClearList();
748
749 int cDims, cElements, i;
750 VARIANTARG* pvdata;
751
752 // Iterate the dimensions: number of elements is x*y*z
753 for (cDims = 0, cElements = 1;
754 cDims < oleVariant.parray->cDims; cDims ++)
755 cElements *= oleVariant.parray->rgsabound[cDims].cElements;
756
757 // Get a pointer to the data
758 HRESULT hr = SafeArrayAccessData(oleVariant.parray, (void HUGEP* FAR*) & pvdata);
759 if (hr != NOERROR)
760 return false;
761 // Iterate the data.
762 for (i = 0; i < cElements; i++)
763 {
764 VARIANTARG& oleElement = pvdata[i];
765 wxVariant vElement;
766 if (!wxConvertOleToVariant(oleElement, vElement))
767 return false;
768
769 variant.Append(vElement);
770 }
771 SafeArrayUnaccessData(oleVariant.parray);
772 break;
773 }
774 case VT_DISPATCH:
775 {
776 variant = (void*) oleVariant.pdispVal;
777 break;
778 }
779 case VT_NULL:
780 {
781 variant.MakeNull();
782 break;
783 }
784 case VT_EMPTY:
785 {
786 break; // Ignore Empty Variant, used only during destruction of objects
787 }
788 default:
789 {
790 wxLogError(wxT("wxAutomationObject::ConvertOleToVariant: Unknown variant value type"));
791 return false;
792 }
793 }
794 return true;
795 }
796
797 BSTR wxConvertStringToOle(const wxString& str)
798 {
799 /*
800 unsigned int len = strlen((const char*) str);
801 unsigned short* s = new unsigned short[len*2+2];
802 unsigned int i;
803 memset(s, 0, len*2+2);
804 for (i=0; i < len; i++)
805 s[i*2] = str[i];
806 */
807 wxBasicString bstr(str.mb_str());
808 return bstr.Get();
809 }
810
811 wxString wxConvertStringFromOle(BSTR bStr)
812 {
813 #if wxUSE_UNICODE
814 wxString str(bStr);
815 #else
816 int len = SysStringLen(bStr) + 1;
817 char *buf = new char[len];
818 (void)wcstombs( buf, bStr, len);
819 wxString str(buf);
820 delete[] buf;
821 #endif
822 return str;
823 }
824
825 // ----------------------------------------------------------------------------
826 // wxBasicString
827 // ----------------------------------------------------------------------------
828
829 // ctor takes an ANSI string and transforms it to Unicode
830 wxBasicString::wxBasicString(const char *sz)
831 {
832 Init(sz);
833 }
834
835 // ctor takes an ANSI or Unicode string and transforms it to Unicode
836 wxBasicString::wxBasicString(const wxString& str)
837 {
838 #if wxUSE_UNICODE
839 m_wzBuf = new OLECHAR[str.Length() + 1];
840 memcpy(m_wzBuf, str.c_str(), str.Length()*2);
841 m_wzBuf[str.Length()] = L'\0';
842 #else
843 Init(str.c_str());
844 #endif
845 }
846
847 // Takes an ANSI string and transforms it to Unicode
848 void wxBasicString::Init(const char *sz)
849 {
850 // get the size of required buffer
851 UINT lenAnsi = strlen(sz);
852 #ifdef __MWERKS__
853 UINT lenWide = lenAnsi * 2 ;
854 #else
855 UINT lenWide = mbstowcs(NULL, sz, lenAnsi);
856 #endif
857
858 if ( lenWide > 0 ) {
859 m_wzBuf = new OLECHAR[lenWide + 1];
860 mbstowcs(m_wzBuf, sz, lenAnsi);
861 m_wzBuf[lenWide] = L'\0';
862 }
863 else {
864 m_wzBuf = NULL;
865 }
866 }
867
868 // dtor frees memory
869 wxBasicString::~wxBasicString()
870 {
871 delete [] m_wzBuf;
872 }
873
874 /////////////////////////////////////////////////////////////////////////////
875 // COleDateTime class HELPERS - implementation
876
877 BOOL OleDateFromTm(WORD wYear, WORD wMonth, WORD wDay,
878 WORD wHour, WORD wMinute, WORD wSecond, DATE& dtDest)
879 {
880 // Validate year and month (ignore day of week and milliseconds)
881 if (wYear > 9999 || wMonth < 1 || wMonth > 12)
882 return FALSE;
883
884 // Check for leap year and set the number of days in the month
885 BOOL bLeapYear = ((wYear & 3) == 0) &&
886 ((wYear % 100) != 0 || (wYear % 400) == 0);
887
888 int nDaysInMonth =
889 rgMonthDays[wMonth] - rgMonthDays[wMonth-1] +
890 ((bLeapYear && wDay == 29 && wMonth == 2) ? 1 : 0);
891
892 // Finish validating the date
893 if (wDay < 1 || wDay > nDaysInMonth ||
894 wHour > 23 || wMinute > 59 ||
895 wSecond > 59)
896 {
897 return FALSE;
898 }
899
900 // Cache the date in days and time in fractional days
901 long nDate;
902 double dblTime;
903
904 //It is a valid date; make Jan 1, 1AD be 1
905 nDate = wYear*365L + wYear/4 - wYear/100 + wYear/400 +
906 rgMonthDays[wMonth-1] + wDay;
907
908 // If leap year and it's before March, subtract 1:
909 if (wMonth <= 2 && bLeapYear)
910 --nDate;
911
912 // Offset so that 12/30/1899 is 0
913 nDate -= 693959L;
914
915 dblTime = (((long)wHour * 3600L) + // hrs in seconds
916 ((long)wMinute * 60L) + // mins in seconds
917 ((long)wSecond)) / 86400.;
918
919 dtDest = (double) nDate + ((nDate >= 0) ? dblTime : -dblTime);
920
921 return TRUE;
922 }
923
924 BOOL TmFromOleDate(DATE dtSrc, struct tm& tmDest)
925 {
926 // The legal range does not actually span year 0 to 9999.
927 if (dtSrc > MAX_DATE || dtSrc < MIN_DATE) // about year 100 to about 9999
928 return FALSE;
929
930 long nDaysAbsolute; // Number of days since 1/1/0
931 long nSecsInDay; // Time in seconds since midnight
932 long nMinutesInDay; // Minutes in day
933
934 long n400Years; // Number of 400 year increments since 1/1/0
935 long n400Century; // Century within 400 year block (0,1,2 or 3)
936 long n4Years; // Number of 4 year increments since 1/1/0
937 long n4Day; // Day within 4 year block
938 // (0 is 1/1/yr1, 1460 is 12/31/yr4)
939 long n4Yr; // Year within 4 year block (0,1,2 or 3)
940 BOOL bLeap4 = TRUE; // TRUE if 4 year block includes leap year
941
942 double dblDate = dtSrc; // tempory serial date
943
944 // Round to the second
945 dblDate += ((dtSrc > 0.0) ? HALF_SECOND : -HALF_SECOND);
946
947 nDaysAbsolute = (long)dblDate + 693959L; // Add days from 1/1/0 to 12/30/1899
948
949 dblDate = fabs(dblDate);
950 nSecsInDay = (long)((dblDate - floor(dblDate)) * 86400.);
951
952 // Calculate the day of week (sun=1, mon=2...)
953 // -1 because 1/1/0 is Sat. +1 because we want 1-based
954 tmDest.tm_wday = (int)((nDaysAbsolute - 1) % 7L) + 1;
955
956 // Leap years every 4 yrs except centuries not multiples of 400.
957 n400Years = (long)(nDaysAbsolute / 146097L);
958
959 // Set nDaysAbsolute to day within 400-year block
960 nDaysAbsolute %= 146097L;
961
962 // -1 because first century has extra day
963 n400Century = (long)((nDaysAbsolute - 1) / 36524L);
964
965 // Non-leap century
966 if (n400Century != 0)
967 {
968 // Set nDaysAbsolute to day within century
969 nDaysAbsolute = (nDaysAbsolute - 1) % 36524L;
970
971 // +1 because 1st 4 year increment has 1460 days
972 n4Years = (long)((nDaysAbsolute + 1) / 1461L);
973
974 if (n4Years != 0)
975 n4Day = (long)((nDaysAbsolute + 1) % 1461L);
976 else
977 {
978 bLeap4 = FALSE;
979 n4Day = (long)nDaysAbsolute;
980 }
981 }
982 else
983 {
984 // Leap century - not special case!
985 n4Years = (long)(nDaysAbsolute / 1461L);
986 n4Day = (long)(nDaysAbsolute % 1461L);
987 }
988
989 if (bLeap4)
990 {
991 // -1 because first year has 366 days
992 n4Yr = (n4Day - 1) / 365;
993
994 if (n4Yr != 0)
995 n4Day = (n4Day - 1) % 365;
996 }
997 else
998 {
999 n4Yr = n4Day / 365;
1000 n4Day %= 365;
1001 }
1002
1003 // n4Day is now 0-based day of year. Save 1-based day of year, year number
1004 tmDest.tm_yday = (int)n4Day + 1;
1005 tmDest.tm_year = n400Years * 400 + n400Century * 100 + n4Years * 4 + n4Yr;
1006
1007 // Handle leap year: before, on, and after Feb. 29.
1008 if (n4Yr == 0 && bLeap4)
1009 {
1010 // Leap Year
1011 if (n4Day == 59)
1012 {
1013 /* Feb. 29 */
1014 tmDest.tm_mon = 2;
1015 tmDest.tm_mday = 29;
1016 goto DoTime;
1017 }
1018
1019 // Pretend it's not a leap year for month/day comp.
1020 if (n4Day >= 60)
1021 --n4Day;
1022 }
1023
1024 // Make n4DaY a 1-based day of non-leap year and compute
1025 // month/day for everything but Feb. 29.
1026 ++n4Day;
1027
1028 // Month number always >= n/32, so save some loop time */
1029 for (tmDest.tm_mon = (n4Day >> 5) + 1;
1030 n4Day > rgMonthDays[tmDest.tm_mon]; tmDest.tm_mon++)
1031 ;
1032
1033 tmDest.tm_mday = (int)(n4Day - rgMonthDays[tmDest.tm_mon-1]);
1034
1035 DoTime:
1036 if (nSecsInDay == 0)
1037 tmDest.tm_hour = tmDest.tm_min = tmDest.tm_sec = 0;
1038 else
1039 {
1040 tmDest.tm_sec = (int)nSecsInDay % 60L;
1041 nMinutesInDay = nSecsInDay / 60L;
1042 tmDest.tm_min = (int)nMinutesInDay % 60;
1043 tmDest.tm_hour = (int)nMinutesInDay / 60;
1044 }
1045
1046 return TRUE;
1047 }
1048
1049 // this function is not used
1050 #if 0
1051 void TmConvertToStandardFormat(struct tm& tmSrc)
1052 {
1053 // Convert afx internal tm to format expected by runtimes (_tcsftime, etc)
1054 tmSrc.tm_year -= 1900; // year is based on 1900
1055 tmSrc.tm_mon -= 1; // month of year is 0-based
1056 tmSrc.tm_wday -= 1; // day of week is 0-based
1057 tmSrc.tm_yday -= 1; // day of year is 0-based
1058 }
1059
1060 double DoubleFromDate(DATE dt)
1061 {
1062 // No problem if positive
1063 if (dt >= 0)
1064 return dt;
1065
1066 // If negative, must convert since negative dates not continuous
1067 // (examples: -1.25 to -.75, -1.50 to -.50, -1.75 to -.25)
1068 double temp = ceil(dt);
1069 return temp - (dt - temp);
1070 }
1071
1072 DATE DateFromDouble(double dbl)
1073 {
1074 // No problem if positive
1075 if (dbl >= 0)
1076 return dbl;
1077
1078 // If negative, must convert since negative dates not continuous
1079 // (examples: -.75 to -1.25, -.50 to -1.50, -.25 to -1.75)
1080 double temp = floor(dbl); // dbl is now whole part
1081 return temp + (temp - dbl);
1082 }
1083 #endif // 0
1084
1085 /*
1086 * ClearVariant
1087 *
1088 * Zeros a variant structure without regard to current contents
1089 */
1090 static void ClearVariant(VARIANTARG *pvarg)
1091 {
1092 pvarg->vt = VT_EMPTY;
1093 pvarg->wReserved1 = 0;
1094 pvarg->wReserved2 = 0;
1095 pvarg->wReserved3 = 0;
1096 pvarg->lVal = 0;
1097 }
1098
1099 /*
1100 * ReleaseVariant
1101 *
1102 * Clears a particular variant structure and releases any external objects
1103 * or memory contained in the variant. Supports the data types listed above.
1104 */
1105 static void ReleaseVariant(VARIANTARG *pvarg)
1106 {
1107 VARTYPE vt;
1108 VARIANTARG _huge *pvargArray;
1109 long lLBound, lUBound, l;
1110
1111 vt = pvarg->vt & 0xfff; // mask off flags
1112
1113 // check if an array. If so, free its contents, then the array itself.
1114 if (V_ISARRAY(pvarg))
1115 {
1116 // variant arrays are all this routine currently knows about. Since a
1117 // variant can contain anything (even other arrays), call ourselves
1118 // recursively.
1119 if (vt == VT_VARIANT)
1120 {
1121 SafeArrayGetLBound(pvarg->parray, 1, &lLBound);
1122 SafeArrayGetUBound(pvarg->parray, 1, &lUBound);
1123
1124 if (lUBound > lLBound)
1125 {
1126 lUBound -= lLBound;
1127
1128 SafeArrayAccessData(pvarg->parray, (void**)&pvargArray);
1129
1130 for (l = 0; l < lUBound; l++)
1131 {
1132 ReleaseVariant(pvargArray);
1133 pvargArray++;
1134 }
1135
1136 SafeArrayUnaccessData(pvarg->parray);
1137 }
1138 }
1139 else
1140 {
1141 wxLogWarning(wxT("ReleaseVariant: Array contains non-variant type"));
1142 }
1143
1144 // Free the array itself.
1145 SafeArrayDestroy(pvarg->parray);
1146 }
1147 else
1148 {
1149 switch (vt)
1150 {
1151 case VT_DISPATCH:
1152 if (pvarg->pdispVal)
1153 pvarg->pdispVal->Release();
1154 break;
1155
1156 case VT_BSTR:
1157 SysFreeString(pvarg->bstrVal);
1158 break;
1159
1160 case VT_I2:
1161 case VT_BOOL:
1162 case VT_R8:
1163 case VT_ERROR: // to avoid erroring on an error return from Excel
1164 // no work for these types
1165 break;
1166
1167 default:
1168 wxLogWarning(wxT("ReleaseVariant: Unknown type"));
1169 break;
1170 }
1171 }
1172
1173 ClearVariant(pvarg);
1174 }
1175
1176 #if 0
1177
1178 void ShowException(LPOLESTR szMember, HRESULT hr, EXCEPINFO *pexcep, unsigned int uiArgErr)
1179 {
1180 TCHAR szBuf[512];
1181
1182 switch (GetScode(hr))
1183 {
1184 case DISP_E_UNKNOWNNAME:
1185 wsprintf(szBuf, L"%s: Unknown name or named argument.", szMember);
1186 break;
1187
1188 case DISP_E_BADPARAMCOUNT:
1189 wsprintf(szBuf, L"%s: Incorrect number of arguments.", szMember);
1190 break;
1191
1192 case DISP_E_EXCEPTION:
1193 wsprintf(szBuf, L"%s: Error %d: ", szMember, pexcep->wCode);
1194 if (pexcep->bstrDescription != NULL)
1195 lstrcat(szBuf, pexcep->bstrDescription);
1196 else
1197 lstrcat(szBuf, L"<<No Description>>");
1198 break;
1199
1200 case DISP_E_MEMBERNOTFOUND:
1201 wsprintf(szBuf, L"%s: method or property not found.", szMember);
1202 break;
1203
1204 case DISP_E_OVERFLOW:
1205 wsprintf(szBuf, L"%s: Overflow while coercing argument values.", szMember);
1206 break;
1207
1208 case DISP_E_NONAMEDARGS:
1209 wsprintf(szBuf, L"%s: Object implementation does not support named arguments.",
1210 szMember);
1211 break;
1212
1213 case DISP_E_UNKNOWNLCID:
1214 wsprintf(szBuf, L"%s: The locale ID is unknown.", szMember);
1215 break;
1216
1217 case DISP_E_PARAMNOTOPTIONAL:
1218 wsprintf(szBuf, L"%s: Missing a required parameter.", szMember);
1219 break;
1220
1221 case DISP_E_PARAMNOTFOUND:
1222 wsprintf(szBuf, L"%s: Argument not found, argument %d.", szMember, uiArgErr);
1223 break;
1224
1225 case DISP_E_TYPEMISMATCH:
1226 wsprintf(szBuf, L"%s: Type mismatch, argument %d.", szMember, uiArgErr);
1227 break;
1228
1229 default:
1230 wsprintf(szBuf, L"%s: Unknown error occured.", szMember);
1231 break;
1232 }
1233
1234 wxLogWarning(szBuf);
1235 }
1236
1237 #endif
1238
1239 #endif // wxUSE_OLE && !(defined(__BORLANDC__) && (__BORLANDC__ < 0x520)) && !defined(__CYGWIN10__)
1240