]> git.saurik.com Git - wxWidgets.git/blob - src/msw/ole/automtn.cpp
wxIsNumeric for values < 0
[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 case VT_EMPTY:
684 {
685 break; // Ignore Empty Variant, used only during destruction of objects
686 }
687 default:
688 {
689 wxLogError("wxAutomationObject::ConvertOleToVariant: Unknown variant value type");
690 return FALSE;
691 }
692 }
693 return TRUE;
694 }
695
696 static BSTR ConvertStringToOle(const wxString& str)
697 {
698 /*
699 unsigned int len = strlen((const char*) str);
700 unsigned short* s = new unsigned short[len*2+2];
701 unsigned int i;
702 memset(s, 0, len*2+2);
703 for (i=0; i < len; i++)
704 s[i*2] = str[i];
705 */
706 BasicString bstr((const char*) str);
707 return bstr.Get();
708 }
709
710 static wxString ConvertStringFromOle(BSTR bStr)
711 {
712 int len = SysStringLen(bStr) + 1;
713 char *buf = new char[len];
714 int i = wcstombs( buf, bStr, len);
715
716 wxString str(buf);
717 delete[] buf;
718 return str;
719 }
720
721 // ----------------------------------------------------------------------------
722 // BasicString
723 // ----------------------------------------------------------------------------
724
725 // ctor takes an ANSI string and transforms it to Unicode
726 BasicString::BasicString(const char *sz)
727 {
728 // get the size of required buffer
729 UINT lenAnsi = strlen(sz);
730 UINT lenWide = mbstowcs(NULL, sz, lenAnsi);
731
732 if ( lenWide > 0 ) {
733 m_wzBuf = new OLECHAR[lenWide + 1];
734 mbstowcs(m_wzBuf, sz, lenAnsi);
735 m_wzBuf[lenWide] = L'\0';
736 }
737 else {
738 m_wzBuf = NULL;
739 }
740 }
741
742 // dtor frees memory
743 BasicString::~BasicString()
744 {
745 delete [] m_wzBuf;
746 }
747
748 /////////////////////////////////////////////////////////////////////////////
749 // COleDateTime class HELPERS - implementation
750
751 BOOL OleDateFromTm(WORD wYear, WORD wMonth, WORD wDay,
752 WORD wHour, WORD wMinute, WORD wSecond, DATE& dtDest)
753 {
754 // Validate year and month (ignore day of week and milliseconds)
755 if (wYear > 9999 || wMonth < 1 || wMonth > 12)
756 return FALSE;
757
758 // Check for leap year and set the number of days in the month
759 BOOL bLeapYear = ((wYear & 3) == 0) &&
760 ((wYear % 100) != 0 || (wYear % 400) == 0);
761
762 int nDaysInMonth =
763 rgMonthDays[wMonth] - rgMonthDays[wMonth-1] +
764 ((bLeapYear && wDay == 29 && wMonth == 2) ? 1 : 0);
765
766 // Finish validating the date
767 if (wDay < 1 || wDay > nDaysInMonth ||
768 wHour > 23 || wMinute > 59 ||
769 wSecond > 59)
770 {
771 return FALSE;
772 }
773
774 // Cache the date in days and time in fractional days
775 long nDate;
776 double dblTime;
777
778 //It is a valid date; make Jan 1, 1AD be 1
779 nDate = wYear*365L + wYear/4 - wYear/100 + wYear/400 +
780 rgMonthDays[wMonth-1] + wDay;
781
782 // If leap year and it's before March, subtract 1:
783 if (wMonth <= 2 && bLeapYear)
784 --nDate;
785
786 // Offset so that 12/30/1899 is 0
787 nDate -= 693959L;
788
789 dblTime = (((long)wHour * 3600L) + // hrs in seconds
790 ((long)wMinute * 60L) + // mins in seconds
791 ((long)wSecond)) / 86400.;
792
793 dtDest = (double) nDate + ((nDate >= 0) ? dblTime : -dblTime);
794
795 return TRUE;
796 }
797
798 BOOL TmFromOleDate(DATE dtSrc, struct tm& tmDest)
799 {
800 // The legal range does not actually span year 0 to 9999.
801 if (dtSrc > MAX_DATE || dtSrc < MIN_DATE) // about year 100 to about 9999
802 return FALSE;
803
804 long nDays; // Number of days since Dec. 30, 1899
805 long nDaysAbsolute; // Number of days since 1/1/0
806 long nSecsInDay; // Time in seconds since midnight
807 long nMinutesInDay; // Minutes in day
808
809 long n400Years; // Number of 400 year increments since 1/1/0
810 long n400Century; // Century within 400 year block (0,1,2 or 3)
811 long n4Years; // Number of 4 year increments since 1/1/0
812 long n4Day; // Day within 4 year block
813 // (0 is 1/1/yr1, 1460 is 12/31/yr4)
814 long n4Yr; // Year within 4 year block (0,1,2 or 3)
815 BOOL bLeap4 = TRUE; // TRUE if 4 year block includes leap year
816
817 double dblDate = dtSrc; // tempory serial date
818
819 // If a valid date, then this conversion should not overflow
820 nDays = (long)dblDate;
821
822 // Round to the second
823 dblDate += ((dtSrc > 0.0) ? HALF_SECOND : -HALF_SECOND);
824
825 nDaysAbsolute = (long)dblDate + 693959L; // Add days from 1/1/0 to 12/30/1899
826
827 dblDate = fabs(dblDate);
828 nSecsInDay = (long)((dblDate - floor(dblDate)) * 86400.);
829
830 // Calculate the day of week (sun=1, mon=2...)
831 // -1 because 1/1/0 is Sat. +1 because we want 1-based
832 tmDest.tm_wday = (int)((nDaysAbsolute - 1) % 7L) + 1;
833
834 // Leap years every 4 yrs except centuries not multiples of 400.
835 n400Years = (long)(nDaysAbsolute / 146097L);
836
837 // Set nDaysAbsolute to day within 400-year block
838 nDaysAbsolute %= 146097L;
839
840 // -1 because first century has extra day
841 n400Century = (long)((nDaysAbsolute - 1) / 36524L);
842
843 // Non-leap century
844 if (n400Century != 0)
845 {
846 // Set nDaysAbsolute to day within century
847 nDaysAbsolute = (nDaysAbsolute - 1) % 36524L;
848
849 // +1 because 1st 4 year increment has 1460 days
850 n4Years = (long)((nDaysAbsolute + 1) / 1461L);
851
852 if (n4Years != 0)
853 n4Day = (long)((nDaysAbsolute + 1) % 1461L);
854 else
855 {
856 bLeap4 = FALSE;
857 n4Day = (long)nDaysAbsolute;
858 }
859 }
860 else
861 {
862 // Leap century - not special case!
863 n4Years = (long)(nDaysAbsolute / 1461L);
864 n4Day = (long)(nDaysAbsolute % 1461L);
865 }
866
867 if (bLeap4)
868 {
869 // -1 because first year has 366 days
870 n4Yr = (n4Day - 1) / 365;
871
872 if (n4Yr != 0)
873 n4Day = (n4Day - 1) % 365;
874 }
875 else
876 {
877 n4Yr = n4Day / 365;
878 n4Day %= 365;
879 }
880
881 // n4Day is now 0-based day of year. Save 1-based day of year, year number
882 tmDest.tm_yday = (int)n4Day + 1;
883 tmDest.tm_year = n400Years * 400 + n400Century * 100 + n4Years * 4 + n4Yr;
884
885 // Handle leap year: before, on, and after Feb. 29.
886 if (n4Yr == 0 && bLeap4)
887 {
888 // Leap Year
889 if (n4Day == 59)
890 {
891 /* Feb. 29 */
892 tmDest.tm_mon = 2;
893 tmDest.tm_mday = 29;
894 goto DoTime;
895 }
896
897 // Pretend it's not a leap year for month/day comp.
898 if (n4Day >= 60)
899 --n4Day;
900 }
901
902 // Make n4DaY a 1-based day of non-leap year and compute
903 // month/day for everything but Feb. 29.
904 ++n4Day;
905
906 // Month number always >= n/32, so save some loop time */
907 for (tmDest.tm_mon = (n4Day >> 5) + 1;
908 n4Day > rgMonthDays[tmDest.tm_mon]; tmDest.tm_mon++);
909
910 tmDest.tm_mday = (int)(n4Day - rgMonthDays[tmDest.tm_mon-1]);
911
912 DoTime:
913 if (nSecsInDay == 0)
914 tmDest.tm_hour = tmDest.tm_min = tmDest.tm_sec = 0;
915 else
916 {
917 tmDest.tm_sec = (int)nSecsInDay % 60L;
918 nMinutesInDay = nSecsInDay / 60L;
919 tmDest.tm_min = (int)nMinutesInDay % 60;
920 tmDest.tm_hour = (int)nMinutesInDay / 60;
921 }
922
923 return TRUE;
924 }
925
926 void TmConvertToStandardFormat(struct tm& tmSrc)
927 {
928 // Convert afx internal tm to format expected by runtimes (_tcsftime, etc)
929 tmSrc.tm_year -= 1900; // year is based on 1900
930 tmSrc.tm_mon -= 1; // month of year is 0-based
931 tmSrc.tm_wday -= 1; // day of week is 0-based
932 tmSrc.tm_yday -= 1; // day of year is 0-based
933 }
934
935 double DoubleFromDate(DATE dt)
936 {
937 // No problem if positive
938 if (dt >= 0)
939 return dt;
940
941 // If negative, must convert since negative dates not continuous
942 // (examples: -1.25 to -.75, -1.50 to -.50, -1.75 to -.25)
943 double temp = ceil(dt);
944 return temp - (dt - temp);
945 }
946
947 DATE DateFromDouble(double dbl)
948 {
949 // No problem if positive
950 if (dbl >= 0)
951 return dbl;
952
953 // If negative, must convert since negative dates not continuous
954 // (examples: -.75 to -1.25, -.50 to -1.50, -.25 to -1.75)
955 double temp = floor(dbl); // dbl is now whole part
956 return temp + (temp - dbl);
957 }
958
959 /*
960 * ClearVariant
961 *
962 * Zeros a variant structure without regard to current contents
963 */
964 static void ClearVariant(VARIANTARG *pvarg)
965 {
966 pvarg->vt = VT_EMPTY;
967 pvarg->wReserved1 = 0;
968 pvarg->wReserved2 = 0;
969 pvarg->wReserved3 = 0;
970 pvarg->lVal = 0;
971 }
972
973 /*
974 * ReleaseVariant
975 *
976 * Clears a particular variant structure and releases any external objects
977 * or memory contained in the variant. Supports the data types listed above.
978 */
979 static void ReleaseVariant(VARIANTARG *pvarg)
980 {
981 VARTYPE vt;
982 VARIANTARG _huge *pvargArray;
983 long lLBound, lUBound, l;
984
985 vt = pvarg->vt & 0xfff; // mask off flags
986
987 // check if an array. If so, free its contents, then the array itself.
988 if (V_ISARRAY(pvarg))
989 {
990 // variant arrays are all this routine currently knows about. Since a
991 // variant can contain anything (even other arrays), call ourselves
992 // recursively.
993 if (vt == VT_VARIANT)
994 {
995 SafeArrayGetLBound(pvarg->parray, 1, &lLBound);
996 SafeArrayGetUBound(pvarg->parray, 1, &lUBound);
997
998 if (lUBound > lLBound)
999 {
1000 lUBound -= lLBound;
1001
1002 SafeArrayAccessData(pvarg->parray, (void**)&pvargArray);
1003
1004 for (l = 0; l < lUBound; l++)
1005 {
1006 ReleaseVariant(pvargArray);
1007 pvargArray++;
1008 }
1009
1010 SafeArrayUnaccessData(pvarg->parray);
1011 }
1012 }
1013 else
1014 {
1015 wxLogWarning("ReleaseVariant: Array contains non-variant type");
1016 }
1017
1018 // Free the array itself.
1019 SafeArrayDestroy(pvarg->parray);
1020 }
1021 else
1022 {
1023 switch (vt)
1024 {
1025 case VT_DISPATCH:
1026 if (pvarg->pdispVal)
1027 pvarg->pdispVal->Release();
1028 break;
1029
1030 case VT_BSTR:
1031 SysFreeString(pvarg->bstrVal);
1032 break;
1033
1034 case VT_I2:
1035 case VT_BOOL:
1036 case VT_R8:
1037 case VT_ERROR: // to avoid erroring on an error return from Excel
1038 // no work for these types
1039 break;
1040
1041 default:
1042 wxLogWarning("ReleaseVariant: Unknown type");
1043 break;
1044 }
1045 }
1046
1047 ClearVariant(pvarg);
1048 }
1049
1050 #if 0
1051
1052 void ShowException(LPOLESTR szMember, HRESULT hr, EXCEPINFO *pexcep, unsigned int uiArgErr)
1053 {
1054 TCHAR szBuf[512];
1055
1056 switch (GetScode(hr))
1057 {
1058 case DISP_E_UNKNOWNNAME:
1059 wsprintf(szBuf, L"%s: Unknown name or named argument.", szMember);
1060 break;
1061
1062 case DISP_E_BADPARAMCOUNT:
1063 wsprintf(szBuf, L"%s: Incorrect number of arguments.", szMember);
1064 break;
1065
1066 case DISP_E_EXCEPTION:
1067 wsprintf(szBuf, L"%s: Error %d: ", szMember, pexcep->wCode);
1068 if (pexcep->bstrDescription != NULL)
1069 lstrcat(szBuf, pexcep->bstrDescription);
1070 else
1071 lstrcat(szBuf, L"<<No Description>>");
1072 break;
1073
1074 case DISP_E_MEMBERNOTFOUND:
1075 wsprintf(szBuf, L"%s: method or property not found.", szMember);
1076 break;
1077
1078 case DISP_E_OVERFLOW:
1079 wsprintf(szBuf, L"%s: Overflow while coercing argument values.", szMember);
1080 break;
1081
1082 case DISP_E_NONAMEDARGS:
1083 wsprintf(szBuf, L"%s: Object implementation does not support named arguments.",
1084 szMember);
1085 break;
1086
1087 case DISP_E_UNKNOWNLCID:
1088 wsprintf(szBuf, L"%s: The locale ID is unknown.", szMember);
1089 break;
1090
1091 case DISP_E_PARAMNOTOPTIONAL:
1092 wsprintf(szBuf, L"%s: Missing a required parameter.", szMember);
1093 break;
1094
1095 case DISP_E_PARAMNOTFOUND:
1096 wsprintf(szBuf, L"%s: Argument not found, argument %d.", szMember, uiArgErr);
1097 break;
1098
1099 case DISP_E_TYPEMISMATCH:
1100 wsprintf(szBuf, L"%s: Type mismatch, argument %d.", szMember, uiArgErr);
1101 break;
1102
1103 default:
1104 wsprintf(szBuf, L"%s: Unknown error occured.", szMember);
1105 break;
1106 }
1107
1108 wxLogWarning(szBuf);
1109 }
1110
1111 #endif
1112