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