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