]> git.saurik.com Git - wxWidgets.git/blob - src/msw/ole/automtn.cpp
support for incorrect entries in .mime.types added (world is not perfect, alas)
[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/log.h"
24 #include "wx/msw/ole/automtn.h"
25
26 #include <windows.h>
27 #include <ole2ver.h>
28 #include <oleauto.h>
29 #include <math.h>
30 #include <time.h>
31
32 #ifdef GetObject
33 #undef GetObject
34 #endif
35
36 // wrapper around BSTR type (by Vadim Zeitlin)
37
38 class WXDLLEXPORT BasicString
39 {
40 public:
41 // ctors & dtor
42 BasicString(const char *sz);
43 ~BasicString();
44
45 // accessors
46 // just get the string
47 operator BSTR() const { return m_wzBuf; }
48 // retrieve a copy of our string - caller must SysFreeString() it later!
49 BSTR Get() const { return SysAllocString(m_wzBuf); }
50
51 private:
52 // @@@ not implemented (but should be)
53 BasicString(const BasicString&);
54 BasicString& operator=(const BasicString&);
55
56 OLECHAR *m_wzBuf; // actual string
57 };
58
59 // Convert variants
60 static bool ConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant) ;
61 static bool ConvertOleToVariant(const VARIANTARG& oleVariant, wxVariant& variant) ;
62
63 // Convert string to Unicode
64 static BSTR ConvertStringToOle(const wxString& str);
65
66 // Convert string from BSTR to wxString
67 static wxString ConvertStringFromOle(BSTR bStr);
68
69 // Verifies will fail if the needed buffer size is too large
70 #define MAX_TIME_BUFFER_SIZE 128 // matches that in timecore.cpp
71 #define MIN_DATE (-657434L) // about year 100
72 #define MAX_DATE 2958465L // about year 9999
73
74 // Half a second, expressed in days
75 #define HALF_SECOND (1.0/172800.0)
76
77 // One-based array of days in year at month start
78 static int rgMonthDays[13] =
79 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
80
81 static BOOL OleDateFromTm(WORD wYear, WORD wMonth, WORD wDay,
82 WORD wHour, WORD wMinute, WORD wSecond, DATE& dtDest);
83 static BOOL TmFromOleDate(DATE dtSrc, struct tm& tmDest);
84 static void TmConvertToStandardFormat(struct tm& tmSrc);
85 static double DoubleFromDate(DATE dt);
86 static DATE DateFromDouble(double dbl);
87
88 static void ClearVariant(VARIANTARG *pvarg) ;
89 static void ReleaseVariant(VARIANTARG *pvarg) ;
90 // static void ShowException(LPOLESTR szMember, HRESULT hr, EXCEPINFO *pexcep, unsigned int uiArgErr);
91
92 /*
93 * wxAutomationObject
94 */
95
96 wxAutomationObject::wxAutomationObject(WXIDISPATCH* dispatchPtr)
97 {
98 m_dispatchPtr = dispatchPtr;
99 }
100
101 wxAutomationObject::~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.
113 bool 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
197 if (!ConvertVariantToOle(INVOKEARG((noArgs-1) - i), oleArgs[i]))
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
254 wxVariant 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
264 wxVariant 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
311 wxVariant 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
321 wxVariant 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
367 bool 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
377 bool 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.
425 WXIDISPATCH* wxAutomationObject::GetDispatchProperty(const wxString& property, int noArgs, wxVariant args[]) const
426 {
427 wxVariant retVariant;
428 if (Invoke(property, DISPATCH_PROPERTYGET, retVariant, noArgs, args))
429 {
430 if (retVariant.GetType() == "void*")
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
444 bool 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
458 bool wxAutomationObject::GetInstance(const wxString& classId) const
459 {
460 if (m_dispatchPtr)
461 return FALSE;
462
463 CLSID clsId;
464 IUnknown * pUnk = NULL;
465
466 BasicString unicodeName((const char*) classId);
467
468 if (FAILED(CLSIDFromProgID((BSTR) unicodeName, &clsId)))
469 {
470 wxLogWarning("Cannot obtain CLSID from ProgID");
471 return FALSE;
472 }
473
474 if (FAILED(GetActiveObject(clsId, NULL, &pUnk)))
475 {
476 wxLogWarning("Cannot find an active object");
477 return FALSE;
478 }
479
480 if (pUnk->QueryInterface(IID_IDispatch, (LPVOID*) &m_dispatchPtr) != S_OK)
481 {
482 wxLogWarning("Cannot find IDispatch interface");
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
491 bool wxAutomationObject::CreateInstance(const wxString& classId) const
492 {
493 if (m_dispatchPtr)
494 return FALSE;
495
496 CLSID clsId;
497 IUnknown * pUnk = NULL;
498
499 BasicString unicodeName((const char*) classId);
500
501 if (FAILED(CLSIDFromProgID((BSTR) unicodeName, &clsId)))
502 {
503 wxLogWarning("Cannot obtain CLSID from ProgID");
504 return FALSE;
505 }
506
507 // start a new copy of Excel, grab the IDispatch interface
508 if (FAILED(CoCreateInstance(clsId, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void**)&m_dispatchPtr)))
509 {
510 wxLogWarning("Cannot start an instance of this class.");
511 return FALSE;
512 }
513
514 return TRUE;
515 }
516
517
518 bool ConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant)
519 {
520 ClearVariant(&oleVariant);
521 if (variant.IsNull())
522 {
523 oleVariant.vt = VT_NULL;
524 return TRUE;
525 }
526
527 wxString type(variant.GetType());
528
529 if (type == "long")
530 {
531 oleVariant.vt = VT_I4;
532 oleVariant.lVal = variant.GetLong() ;
533 }
534 else if (type == "double")
535 {
536 oleVariant.vt = VT_R8;
537 oleVariant.dblVal = variant.GetDouble();
538 }
539 else if (type == "bool")
540 {
541 oleVariant.vt = VT_BOOL;
542 // 'bool' required for VC++ 4 apparently
543 #if defined(__WATCOMC__) || (defined(_MSC_VER) && (_MSC_VER <= 1000))
544 oleVariant.bool = variant.GetBool();
545 #else
546 oleVariant.boolVal = variant.GetBool();
547 #endif
548 }
549 else if (type == "string")
550 {
551 wxString str( variant.GetString() );
552 oleVariant.vt = VT_BSTR;
553 oleVariant.bstrVal = ConvertStringToOle(str);
554 }
555 else if (type == "date")
556 {
557 wxDate date( variant.GetDate() );
558 oleVariant.vt = VT_DATE;
559
560 if (!OleDateFromTm(date.GetYear(), date.GetMonth(), date.GetDay(),
561 0, 0, 0, oleVariant.date))
562 return FALSE;
563 }
564 else if (type == "time")
565 {
566 wxTime time( variant.GetTime() );
567 oleVariant.vt = VT_DATE;
568
569 if (!OleDateFromTm(time.GetYear(), time.GetMonth(), time.GetDay(),
570 time.GetHour(), time.GetMinute(), time.GetSecond(), oleVariant.date))
571 return FALSE;
572 }
573 else if (type == "void*")
574 {
575 oleVariant.vt = VT_DISPATCH;
576 oleVariant.pdispVal = (IDispatch*) variant.GetVoidPtr();
577 }
578 else if (type == "list" || type == "stringlist")
579 {
580 oleVariant.vt = VT_VARIANT | VT_ARRAY;
581
582 SAFEARRAY *psa;
583 SAFEARRAYBOUND saBound;
584 VARIANTARG *pvargBase;
585 VARIANTARG *pvarg;
586 int i, j;
587
588 int iCount = variant.GetCount();
589
590 saBound.lLbound = 0;
591 saBound.cElements = iCount;
592
593 psa = SafeArrayCreate(VT_VARIANT, 1, &saBound);
594 if (psa == NULL)
595 return FALSE;
596
597 SafeArrayAccessData(psa, (void**)&pvargBase);
598
599 pvarg = pvargBase;
600 for (i = 0; i < iCount; i++)
601 {
602 // copy each string in the list of strings
603 wxVariant eachVariant(variant[i]);
604 if (!ConvertVariantToOle(eachVariant, * pvarg))
605 {
606 // memory failure: back out and free strings alloc'ed up to
607 // now, and then the array itself.
608 pvarg = pvargBase;
609 for (j = 0; j < i; j++)
610 {
611 SysFreeString(pvarg->bstrVal);
612 pvarg++;
613 }
614 SafeArrayDestroy(psa);
615 return FALSE;
616 }
617 pvarg++;
618 }
619
620 SafeArrayUnaccessData(psa);
621
622 oleVariant.parray = psa;
623 }
624 else
625 {
626 oleVariant.vt = VT_NULL;
627 return FALSE;
628 }
629 return TRUE;
630 }
631
632 #ifndef VT_TYPEMASK
633 #define VT_TYPEMASK 0xfff
634 #endif
635
636 bool ConvertOleToVariant(const VARIANTARG& oleVariant, wxVariant& variant)
637 {
638 switch (oleVariant.vt & VT_TYPEMASK)
639 {
640 case VT_BSTR:
641 {
642 wxString str(ConvertStringFromOle(oleVariant.bstrVal));
643 variant = str;
644 break;
645 }
646 case VT_DATE:
647 {
648 struct tm tmTemp;
649 if (!TmFromOleDate(oleVariant.date, tmTemp))
650 return FALSE;
651
652 wxDate date(tmTemp.tm_yday, tmTemp.tm_mon, tmTemp.tm_year);
653 wxTime time(date, tmTemp.tm_hour, tmTemp.tm_min, tmTemp.tm_sec);
654
655 variant = time;
656 break;
657 }
658 case VT_I4:
659 {
660 variant = (long) oleVariant.lVal;
661 break;
662 }
663 case VT_I2:
664 {
665 variant = (long) oleVariant.iVal;
666 break;
667 }
668
669 case VT_BOOL:
670 {
671 #ifdef __WATCOMC__
672 variant = (bool) (oleVariant.bool != 0);
673 #else
674 variant = (bool) (oleVariant.boolVal != 0);
675 #endif
676 break;
677 }
678 case VT_R8:
679 {
680 variant = oleVariant.dblVal;
681 break;
682 }
683 case VT_ARRAY:
684 {
685 variant.ClearList();
686
687 int cDims, cElements, i;
688 VARIANTARG* pvdata;
689
690 // Iterate the dimensions: number of elements is x*y*z
691 for (cDims = 0, cElements = 1;
692 cDims < oleVariant.parray->cDims; cDims ++)
693 cElements *= oleVariant.parray->rgsabound[cDims].cElements;
694
695 // Get a pointer to the data
696 HRESULT hr = SafeArrayAccessData(oleVariant.parray, (void HUGEP* FAR*) & pvdata);
697 if (hr != NOERROR)
698 return FALSE;
699 // Iterate the data.
700 for (i = 0; i < cElements; i++)
701 {
702 VARIANTARG& oleElement = pvdata[i];
703 wxVariant vElement;
704 if (!ConvertOleToVariant(oleElement, vElement))
705 return FALSE;
706
707 variant.Append(vElement);
708 }
709 SafeArrayUnaccessData(oleVariant.parray);
710 break;
711 }
712 case VT_DISPATCH:
713 {
714 variant = (void*) oleVariant.pdispVal;
715 break;
716 }
717 case VT_NULL:
718 {
719 variant.MakeNull();
720 break;
721 }
722 case VT_EMPTY:
723 {
724 break; // Ignore Empty Variant, used only during destruction of objects
725 }
726 default:
727 {
728 wxLogError("wxAutomationObject::ConvertOleToVariant: Unknown variant value type");
729 return FALSE;
730 }
731 }
732 return TRUE;
733 }
734
735 static BSTR ConvertStringToOle(const wxString& str)
736 {
737 /*
738 unsigned int len = strlen((const char*) str);
739 unsigned short* s = new unsigned short[len*2+2];
740 unsigned int i;
741 memset(s, 0, len*2+2);
742 for (i=0; i < len; i++)
743 s[i*2] = str[i];
744 */
745 BasicString bstr((const char*) str);
746 return bstr.Get();
747 }
748
749 static wxString ConvertStringFromOle(BSTR bStr)
750 {
751 int len = SysStringLen(bStr) + 1;
752 char *buf = new char[len];
753 int i = wcstombs( buf, bStr, len);
754
755 wxString str(buf);
756 delete[] buf;
757 return str;
758 }
759
760 // ----------------------------------------------------------------------------
761 // BasicString
762 // ----------------------------------------------------------------------------
763
764 // ctor takes an ANSI string and transforms it to Unicode
765 BasicString::BasicString(const char *sz)
766 {
767 // get the size of required buffer
768 UINT lenAnsi = strlen(sz);
769 #ifdef __MWERKS__
770 UINT lenWide = lenAnsi * 2 ;
771 #else
772 UINT lenWide = mbstowcs(NULL, sz, lenAnsi);
773 #endif
774
775 if ( lenWide > 0 ) {
776 m_wzBuf = new OLECHAR[lenWide + 1];
777 mbstowcs(m_wzBuf, sz, lenAnsi);
778 m_wzBuf[lenWide] = L'\0';
779 }
780 else {
781 m_wzBuf = NULL;
782 }
783 }
784
785 // dtor frees memory
786 BasicString::~BasicString()
787 {
788 delete [] m_wzBuf;
789 }
790
791 /////////////////////////////////////////////////////////////////////////////
792 // COleDateTime class HELPERS - implementation
793
794 BOOL OleDateFromTm(WORD wYear, WORD wMonth, WORD wDay,
795 WORD wHour, WORD wMinute, WORD wSecond, DATE& dtDest)
796 {
797 // Validate year and month (ignore day of week and milliseconds)
798 if (wYear > 9999 || wMonth < 1 || wMonth > 12)
799 return FALSE;
800
801 // Check for leap year and set the number of days in the month
802 BOOL bLeapYear = ((wYear & 3) == 0) &&
803 ((wYear % 100) != 0 || (wYear % 400) == 0);
804
805 int nDaysInMonth =
806 rgMonthDays[wMonth] - rgMonthDays[wMonth-1] +
807 ((bLeapYear && wDay == 29 && wMonth == 2) ? 1 : 0);
808
809 // Finish validating the date
810 if (wDay < 1 || wDay > nDaysInMonth ||
811 wHour > 23 || wMinute > 59 ||
812 wSecond > 59)
813 {
814 return FALSE;
815 }
816
817 // Cache the date in days and time in fractional days
818 long nDate;
819 double dblTime;
820
821 //It is a valid date; make Jan 1, 1AD be 1
822 nDate = wYear*365L + wYear/4 - wYear/100 + wYear/400 +
823 rgMonthDays[wMonth-1] + wDay;
824
825 // If leap year and it's before March, subtract 1:
826 if (wMonth <= 2 && bLeapYear)
827 --nDate;
828
829 // Offset so that 12/30/1899 is 0
830 nDate -= 693959L;
831
832 dblTime = (((long)wHour * 3600L) + // hrs in seconds
833 ((long)wMinute * 60L) + // mins in seconds
834 ((long)wSecond)) / 86400.;
835
836 dtDest = (double) nDate + ((nDate >= 0) ? dblTime : -dblTime);
837
838 return TRUE;
839 }
840
841 BOOL TmFromOleDate(DATE dtSrc, struct tm& tmDest)
842 {
843 // The legal range does not actually span year 0 to 9999.
844 if (dtSrc > MAX_DATE || dtSrc < MIN_DATE) // about year 100 to about 9999
845 return FALSE;
846
847 long nDays; // Number of days since Dec. 30, 1899
848 long nDaysAbsolute; // Number of days since 1/1/0
849 long nSecsInDay; // Time in seconds since midnight
850 long nMinutesInDay; // Minutes in day
851
852 long n400Years; // Number of 400 year increments since 1/1/0
853 long n400Century; // Century within 400 year block (0,1,2 or 3)
854 long n4Years; // Number of 4 year increments since 1/1/0
855 long n4Day; // Day within 4 year block
856 // (0 is 1/1/yr1, 1460 is 12/31/yr4)
857 long n4Yr; // Year within 4 year block (0,1,2 or 3)
858 BOOL bLeap4 = TRUE; // TRUE if 4 year block includes leap year
859
860 double dblDate = dtSrc; // tempory serial date
861
862 // If a valid date, then this conversion should not overflow
863 nDays = (long)dblDate;
864
865 // Round to the second
866 dblDate += ((dtSrc > 0.0) ? HALF_SECOND : -HALF_SECOND);
867
868 nDaysAbsolute = (long)dblDate + 693959L; // Add days from 1/1/0 to 12/30/1899
869
870 dblDate = fabs(dblDate);
871 nSecsInDay = (long)((dblDate - floor(dblDate)) * 86400.);
872
873 // Calculate the day of week (sun=1, mon=2...)
874 // -1 because 1/1/0 is Sat. +1 because we want 1-based
875 tmDest.tm_wday = (int)((nDaysAbsolute - 1) % 7L) + 1;
876
877 // Leap years every 4 yrs except centuries not multiples of 400.
878 n400Years = (long)(nDaysAbsolute / 146097L);
879
880 // Set nDaysAbsolute to day within 400-year block
881 nDaysAbsolute %= 146097L;
882
883 // -1 because first century has extra day
884 n400Century = (long)((nDaysAbsolute - 1) / 36524L);
885
886 // Non-leap century
887 if (n400Century != 0)
888 {
889 // Set nDaysAbsolute to day within century
890 nDaysAbsolute = (nDaysAbsolute - 1) % 36524L;
891
892 // +1 because 1st 4 year increment has 1460 days
893 n4Years = (long)((nDaysAbsolute + 1) / 1461L);
894
895 if (n4Years != 0)
896 n4Day = (long)((nDaysAbsolute + 1) % 1461L);
897 else
898 {
899 bLeap4 = FALSE;
900 n4Day = (long)nDaysAbsolute;
901 }
902 }
903 else
904 {
905 // Leap century - not special case!
906 n4Years = (long)(nDaysAbsolute / 1461L);
907 n4Day = (long)(nDaysAbsolute % 1461L);
908 }
909
910 if (bLeap4)
911 {
912 // -1 because first year has 366 days
913 n4Yr = (n4Day - 1) / 365;
914
915 if (n4Yr != 0)
916 n4Day = (n4Day - 1) % 365;
917 }
918 else
919 {
920 n4Yr = n4Day / 365;
921 n4Day %= 365;
922 }
923
924 // n4Day is now 0-based day of year. Save 1-based day of year, year number
925 tmDest.tm_yday = (int)n4Day + 1;
926 tmDest.tm_year = n400Years * 400 + n400Century * 100 + n4Years * 4 + n4Yr;
927
928 // Handle leap year: before, on, and after Feb. 29.
929 if (n4Yr == 0 && bLeap4)
930 {
931 // Leap Year
932 if (n4Day == 59)
933 {
934 /* Feb. 29 */
935 tmDest.tm_mon = 2;
936 tmDest.tm_mday = 29;
937 goto DoTime;
938 }
939
940 // Pretend it's not a leap year for month/day comp.
941 if (n4Day >= 60)
942 --n4Day;
943 }
944
945 // Make n4DaY a 1-based day of non-leap year and compute
946 // month/day for everything but Feb. 29.
947 ++n4Day;
948
949 // Month number always >= n/32, so save some loop time */
950 for (tmDest.tm_mon = (n4Day >> 5) + 1;
951 n4Day > rgMonthDays[tmDest.tm_mon]; tmDest.tm_mon++);
952
953 tmDest.tm_mday = (int)(n4Day - rgMonthDays[tmDest.tm_mon-1]);
954
955 DoTime:
956 if (nSecsInDay == 0)
957 tmDest.tm_hour = tmDest.tm_min = tmDest.tm_sec = 0;
958 else
959 {
960 tmDest.tm_sec = (int)nSecsInDay % 60L;
961 nMinutesInDay = nSecsInDay / 60L;
962 tmDest.tm_min = (int)nMinutesInDay % 60;
963 tmDest.tm_hour = (int)nMinutesInDay / 60;
964 }
965
966 return TRUE;
967 }
968
969 void TmConvertToStandardFormat(struct tm& tmSrc)
970 {
971 // Convert afx internal tm to format expected by runtimes (_tcsftime, etc)
972 tmSrc.tm_year -= 1900; // year is based on 1900
973 tmSrc.tm_mon -= 1; // month of year is 0-based
974 tmSrc.tm_wday -= 1; // day of week is 0-based
975 tmSrc.tm_yday -= 1; // day of year is 0-based
976 }
977
978 double DoubleFromDate(DATE dt)
979 {
980 // No problem if positive
981 if (dt >= 0)
982 return dt;
983
984 // If negative, must convert since negative dates not continuous
985 // (examples: -1.25 to -.75, -1.50 to -.50, -1.75 to -.25)
986 double temp = ceil(dt);
987 return temp - (dt - temp);
988 }
989
990 DATE DateFromDouble(double dbl)
991 {
992 // No problem if positive
993 if (dbl >= 0)
994 return dbl;
995
996 // If negative, must convert since negative dates not continuous
997 // (examples: -.75 to -1.25, -.50 to -1.50, -.25 to -1.75)
998 double temp = floor(dbl); // dbl is now whole part
999 return temp + (temp - dbl);
1000 }
1001
1002 /*
1003 * ClearVariant
1004 *
1005 * Zeros a variant structure without regard to current contents
1006 */
1007 static void ClearVariant(VARIANTARG *pvarg)
1008 {
1009 pvarg->vt = VT_EMPTY;
1010 pvarg->wReserved1 = 0;
1011 pvarg->wReserved2 = 0;
1012 pvarg->wReserved3 = 0;
1013 pvarg->lVal = 0;
1014 }
1015
1016 /*
1017 * ReleaseVariant
1018 *
1019 * Clears a particular variant structure and releases any external objects
1020 * or memory contained in the variant. Supports the data types listed above.
1021 */
1022 static void ReleaseVariant(VARIANTARG *pvarg)
1023 {
1024 VARTYPE vt;
1025 VARIANTARG _huge *pvargArray;
1026 long lLBound, lUBound, l;
1027
1028 vt = pvarg->vt & 0xfff; // mask off flags
1029
1030 // check if an array. If so, free its contents, then the array itself.
1031 if (V_ISARRAY(pvarg))
1032 {
1033 // variant arrays are all this routine currently knows about. Since a
1034 // variant can contain anything (even other arrays), call ourselves
1035 // recursively.
1036 if (vt == VT_VARIANT)
1037 {
1038 SafeArrayGetLBound(pvarg->parray, 1, &lLBound);
1039 SafeArrayGetUBound(pvarg->parray, 1, &lUBound);
1040
1041 if (lUBound > lLBound)
1042 {
1043 lUBound -= lLBound;
1044
1045 SafeArrayAccessData(pvarg->parray, (void**)&pvargArray);
1046
1047 for (l = 0; l < lUBound; l++)
1048 {
1049 ReleaseVariant(pvargArray);
1050 pvargArray++;
1051 }
1052
1053 SafeArrayUnaccessData(pvarg->parray);
1054 }
1055 }
1056 else
1057 {
1058 wxLogWarning("ReleaseVariant: Array contains non-variant type");
1059 }
1060
1061 // Free the array itself.
1062 SafeArrayDestroy(pvarg->parray);
1063 }
1064 else
1065 {
1066 switch (vt)
1067 {
1068 case VT_DISPATCH:
1069 if (pvarg->pdispVal)
1070 pvarg->pdispVal->Release();
1071 break;
1072
1073 case VT_BSTR:
1074 SysFreeString(pvarg->bstrVal);
1075 break;
1076
1077 case VT_I2:
1078 case VT_BOOL:
1079 case VT_R8:
1080 case VT_ERROR: // to avoid erroring on an error return from Excel
1081 // no work for these types
1082 break;
1083
1084 default:
1085 wxLogWarning("ReleaseVariant: Unknown type");
1086 break;
1087 }
1088 }
1089
1090 ClearVariant(pvarg);
1091 }
1092
1093 #if 0
1094
1095 void ShowException(LPOLESTR szMember, HRESULT hr, EXCEPINFO *pexcep, unsigned int uiArgErr)
1096 {
1097 TCHAR szBuf[512];
1098
1099 switch (GetScode(hr))
1100 {
1101 case DISP_E_UNKNOWNNAME:
1102 wsprintf(szBuf, L"%s: Unknown name or named argument.", szMember);
1103 break;
1104
1105 case DISP_E_BADPARAMCOUNT:
1106 wsprintf(szBuf, L"%s: Incorrect number of arguments.", szMember);
1107 break;
1108
1109 case DISP_E_EXCEPTION:
1110 wsprintf(szBuf, L"%s: Error %d: ", szMember, pexcep->wCode);
1111 if (pexcep->bstrDescription != NULL)
1112 lstrcat(szBuf, pexcep->bstrDescription);
1113 else
1114 lstrcat(szBuf, L"<<No Description>>");
1115 break;
1116
1117 case DISP_E_MEMBERNOTFOUND:
1118 wsprintf(szBuf, L"%s: method or property not found.", szMember);
1119 break;
1120
1121 case DISP_E_OVERFLOW:
1122 wsprintf(szBuf, L"%s: Overflow while coercing argument values.", szMember);
1123 break;
1124
1125 case DISP_E_NONAMEDARGS:
1126 wsprintf(szBuf, L"%s: Object implementation does not support named arguments.",
1127 szMember);
1128 break;
1129
1130 case DISP_E_UNKNOWNLCID:
1131 wsprintf(szBuf, L"%s: The locale ID is unknown.", szMember);
1132 break;
1133
1134 case DISP_E_PARAMNOTOPTIONAL:
1135 wsprintf(szBuf, L"%s: Missing a required parameter.", szMember);
1136 break;
1137
1138 case DISP_E_PARAMNOTFOUND:
1139 wsprintf(szBuf, L"%s: Argument not found, argument %d.", szMember, uiArgErr);
1140 break;
1141
1142 case DISP_E_TYPEMISMATCH:
1143 wsprintf(szBuf, L"%s: Type mismatch, argument %d.", szMember, uiArgErr);
1144 break;
1145
1146 default:
1147 wsprintf(szBuf, L"%s: Unknown error occured.", szMember);
1148 break;
1149 }
1150
1151 wxLogWarning(szBuf);
1152 }
1153
1154 #endif
1155