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