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