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