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