VirtualBox

source: vbox/trunk/src/VBox/Main/ProgressImpl.cpp@ 24968

Last change on this file since 24968 was 24961, checked in by vboxsync, 15 years ago

Main: Added a timeout property to IProgress that can be used to automatically time out an operation. This is to make life simpler on the client side.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 51.4 KB
Line 
1/* $Id: ProgressImpl.cpp 24961 2009-11-25 16:02:32Z vboxsync $ */
2/** @file
3 *
4 * VirtualBox Progress COM class implementation
5 */
6
7/*
8 * Copyright (C) 2006-2009 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23#include <iprt/types.h>
24
25#if defined (VBOX_WITH_XPCOM)
26#include <nsIServiceManager.h>
27#include <nsIExceptionService.h>
28#include <nsCOMPtr.h>
29#endif /* defined (VBOX_WITH_XPCOM) */
30
31#include "ProgressImpl.h"
32
33#include "VirtualBoxImpl.h"
34#include "VirtualBoxErrorInfoImpl.h"
35
36#include "Logging.h"
37
38#include <iprt/time.h>
39#include <iprt/semaphore.h>
40
41#include <VBox/err.h>
42
43////////////////////////////////////////////////////////////////////////////////
44// ProgressBase class
45////////////////////////////////////////////////////////////////////////////////
46
47// constructor / destructor
48////////////////////////////////////////////////////////////////////////////////
49
50DEFINE_EMPTY_CTOR_DTOR (ProgressBase)
51
52/**
53 * Subclasses must call this method from their FinalConstruct() implementations.
54 */
55HRESULT ProgressBase::FinalConstruct()
56{
57 mCancelable = FALSE;
58 mCompleted = FALSE;
59 mCanceled = FALSE;
60 mResultCode = S_OK;
61
62 m_cOperations
63 = m_ulTotalOperationsWeight
64 = m_ulOperationsCompletedWeight
65 = m_ulCurrentOperation
66 = m_ulCurrentOperationWeight
67 = m_ulOperationPercent
68 = m_cMsTimeout
69 = 0;
70
71 // get creation timestamp
72 m_ullTimestamp = RTTimeMilliTS();
73
74 m_pfnCancelCallback = NULL;
75 m_pvCancelUserArg = NULL;
76
77 return S_OK;
78}
79
80// protected initializer/uninitializer for internal purposes only
81////////////////////////////////////////////////////////////////////////////////
82
83/**
84 * Initializes the progress base object.
85 *
86 * Subclasses should call this or any other #protectedInit() method from their
87 * init() implementations.
88 *
89 * @param aAutoInitSpan AutoInitSpan object instantiated by a subclass.
90 * @param aParent Parent object (only for server-side Progress objects).
91 * @param aInitiator Initiator of the task (for server-side objects. Can be
92 * NULL which means initiator = parent, otherwise must not
93 * be NULL).
94 * @param aDescription Task description.
95 * @param aID Address of result GUID structure (optional).
96 *
97 * @return COM result indicator.
98 */
99HRESULT ProgressBase::protectedInit (AutoInitSpan &aAutoInitSpan,
100#if !defined (VBOX_COM_INPROC)
101 VirtualBox *aParent,
102#endif
103 IUnknown *aInitiator,
104 CBSTR aDescription, OUT_GUID aId /* = NULL */)
105{
106 /* Guarantees subclasses call this method at the proper time */
107 NOREF (aAutoInitSpan);
108
109 AutoCaller autoCaller(this);
110 AssertReturn(autoCaller.state() == InInit, E_FAIL);
111
112#if !defined (VBOX_COM_INPROC)
113 AssertReturn(aParent, E_INVALIDARG);
114#else
115 AssertReturn(aInitiator, E_INVALIDARG);
116#endif
117
118 AssertReturn(aDescription, E_INVALIDARG);
119
120#if !defined (VBOX_COM_INPROC)
121 /* share parent weakly */
122 unconst(mParent) = aParent;
123
124 /* register with parent early, since uninit() will unconditionally
125 * unregister on failure */
126 mParent->addDependentChild (this);
127#endif
128
129#if !defined (VBOX_COM_INPROC)
130 /* assign (and therefore addref) initiator only if it is not VirtualBox
131 * (to avoid cycling); otherwise mInitiator will remain null which means
132 * that it is the same as the parent */
133 if (aInitiator && !mParent.equalsTo (aInitiator))
134 unconst(mInitiator) = aInitiator;
135#else
136 unconst(mInitiator) = aInitiator;
137#endif
138
139 unconst(mId).create();
140 if (aId)
141 mId.cloneTo(aId);
142
143#if !defined (VBOX_COM_INPROC)
144 /* add to the global collection of progress operations (note: after
145 * creating mId) */
146 mParent->addProgress (this);
147#endif
148
149 unconst(mDescription) = aDescription;
150
151 return S_OK;
152}
153
154/**
155 * Initializes the progress base object.
156 *
157 * This is a special initializer that doesn't initialize any field. Used by one
158 * of the Progress::init() forms to create sub-progress operations combined
159 * together using a CombinedProgress instance, so it doesn't require the parent,
160 * initiator, description and doesn't create an ID.
161 *
162 * Subclasses should call this or any other #protectedInit() method from their
163 * init() implementations.
164 *
165 * @param aAutoInitSpan AutoInitSpan object instantiated by a subclass.
166 */
167HRESULT ProgressBase::protectedInit (AutoInitSpan &aAutoInitSpan)
168{
169 /* Guarantees subclasses call this method at the proper time */
170 NOREF (aAutoInitSpan);
171
172 return S_OK;
173}
174
175/**
176 * Uninitializes the instance.
177 *
178 * Subclasses should call this from their uninit() implementations.
179 *
180 * @param aAutoUninitSpan AutoUninitSpan object instantiated by a subclass.
181 *
182 * @note Using the mParent member after this method returns is forbidden.
183 */
184void ProgressBase::protectedUninit (AutoUninitSpan &aAutoUninitSpan)
185{
186 /* release initiator (effective only if mInitiator has been assigned in
187 * init()) */
188 unconst(mInitiator).setNull();
189
190#if !defined (VBOX_COM_INPROC)
191 if (mParent)
192 {
193 /* remove the added progress on failure to complete the initialization */
194 if (aAutoUninitSpan.initFailed() && !mId.isEmpty())
195 mParent->removeProgress (mId);
196
197 mParent->removeDependentChild (this);
198
199 unconst(mParent).setNull();
200 }
201#endif
202}
203
204// IProgress properties
205/////////////////////////////////////////////////////////////////////////////
206
207STDMETHODIMP ProgressBase::COMGETTER(Id) (BSTR *aId)
208{
209 CheckComArgOutPointerValid(aId);
210
211 AutoCaller autoCaller(this);
212 CheckComRCReturnRC(autoCaller.rc());
213
214 /* mId is constant during life time, no need to lock */
215 mId.toUtf16().cloneTo(aId);
216
217 return S_OK;
218}
219
220STDMETHODIMP ProgressBase::COMGETTER(Description) (BSTR *aDescription)
221{
222 CheckComArgOutPointerValid(aDescription);
223
224 AutoCaller autoCaller(this);
225 CheckComRCReturnRC(autoCaller.rc());
226
227 /* mDescription is constant during life time, no need to lock */
228 mDescription.cloneTo(aDescription);
229
230 return S_OK;
231}
232
233STDMETHODIMP ProgressBase::COMGETTER(Initiator) (IUnknown **aInitiator)
234{
235 CheckComArgOutPointerValid(aInitiator);
236
237 AutoCaller autoCaller(this);
238 CheckComRCReturnRC(autoCaller.rc());
239
240 /* mInitiator/mParent are constant during life time, no need to lock */
241
242#if !defined (VBOX_COM_INPROC)
243 if (mInitiator)
244 mInitiator.queryInterfaceTo(aInitiator);
245 else
246 mParent.queryInterfaceTo(aInitiator);
247#else
248 mInitiator.queryInterfaceTo(aInitiator);
249#endif
250
251 return S_OK;
252}
253
254STDMETHODIMP ProgressBase::COMGETTER(Cancelable) (BOOL *aCancelable)
255{
256 CheckComArgOutPointerValid(aCancelable);
257
258 AutoCaller autoCaller(this);
259 CheckComRCReturnRC(autoCaller.rc());
260
261 AutoReadLock alock(this);
262
263 *aCancelable = mCancelable;
264
265 return S_OK;
266}
267
268/**
269 * Internal helper to compute the total percent value based on the member values and
270 * returns it as a "double". This is used both by GetPercent (which returns it as a
271 * rounded ULONG) and GetTimeRemaining().
272 *
273 * Requires locking by the caller!
274 *
275 * @return fractional percentage as a double value.
276 */
277double ProgressBase::calcTotalPercent()
278{
279 // avoid division by zero
280 if (m_ulTotalOperationsWeight == 0)
281 return 0;
282
283 double dPercent = ( (double)m_ulOperationsCompletedWeight // weight of operations that have been completed
284 + ((double)m_ulOperationPercent * (double)m_ulCurrentOperationWeight / (double)100) // plus partial weight of the current operation
285 ) * (double)100 / (double)m_ulTotalOperationsWeight;
286
287 return dPercent;
288}
289
290STDMETHODIMP ProgressBase::COMGETTER(TimeRemaining)(LONG *aTimeRemaining)
291{
292 CheckComArgOutPointerValid(aTimeRemaining);
293
294 AutoCaller autoCaller(this);
295 CheckComRCReturnRC(autoCaller.rc());
296
297 AutoReadLock alock(this);
298
299 if (mCompleted)
300 *aTimeRemaining = 0;
301 else
302 {
303 double dPercentDone = calcTotalPercent();
304 if (dPercentDone < 1)
305 *aTimeRemaining = -1; // unreliable, or avoid division by 0 below
306 else
307 {
308 uint64_t ullTimeNow = RTTimeMilliTS();
309 uint64_t ullTimeElapsed = ullTimeNow - m_ullTimestamp;
310 uint64_t ullTimeTotal = (uint64_t)(ullTimeElapsed / dPercentDone * 100);
311 uint64_t ullTimeRemaining = ullTimeTotal - ullTimeElapsed;
312
313// Log(("ProgressBase::GetTimeRemaining: dPercentDone %RI32, ullTimeNow = %RI64, ullTimeElapsed = %RI64, ullTimeTotal = %RI64, ullTimeRemaining = %RI64\n",
314// (uint32_t)dPercentDone, ullTimeNow, ullTimeElapsed, ullTimeTotal, ullTimeRemaining));
315
316 *aTimeRemaining = (LONG)(ullTimeRemaining / 1000);
317 }
318 }
319
320 return S_OK;
321}
322
323STDMETHODIMP ProgressBase::COMGETTER(Percent)(ULONG *aPercent)
324{
325 CheckComArgOutPointerValid(aPercent);
326
327 AutoCaller autoCaller(this);
328 CheckComRCReturnRC(autoCaller.rc());
329
330 AutoReadLock alock(this);
331
332 if (mCompleted && SUCCEEDED(mResultCode))
333 *aPercent = 100;
334 else
335 {
336 ULONG ulPercent = (ULONG)calcTotalPercent();
337 // do not report 100% until we're really really done with everything as the Qt GUI dismisses progress dialogs in that case
338 if ( ulPercent == 100
339 && ( m_ulOperationPercent < 100
340 || (m_ulCurrentOperation < m_cOperations -1)
341 )
342 )
343 *aPercent = 99;
344 else
345 *aPercent = ulPercent;
346 }
347
348 return S_OK;
349}
350
351STDMETHODIMP ProgressBase::COMGETTER(Completed) (BOOL *aCompleted)
352{
353 CheckComArgOutPointerValid(aCompleted);
354
355 AutoCaller autoCaller(this);
356 CheckComRCReturnRC(autoCaller.rc());
357
358 AutoReadLock alock(this);
359
360 *aCompleted = mCompleted;
361
362 return S_OK;
363}
364
365STDMETHODIMP ProgressBase::COMGETTER(Canceled) (BOOL *aCanceled)
366{
367 CheckComArgOutPointerValid(aCanceled);
368
369 AutoCaller autoCaller(this);
370 CheckComRCReturnRC(autoCaller.rc());
371
372 AutoReadLock alock(this);
373
374 *aCanceled = mCanceled;
375
376 return S_OK;
377}
378
379STDMETHODIMP ProgressBase::COMGETTER(ResultCode) (LONG *aResultCode)
380{
381 CheckComArgOutPointerValid(aResultCode);
382
383 AutoCaller autoCaller(this);
384 CheckComRCReturnRC(autoCaller.rc());
385
386 AutoReadLock alock(this);
387
388 if (!mCompleted)
389 return setError (E_FAIL,
390 tr ("Result code is not available, operation is still in progress"));
391
392 *aResultCode = mResultCode;
393
394 return S_OK;
395}
396
397STDMETHODIMP ProgressBase::COMGETTER(ErrorInfo) (IVirtualBoxErrorInfo **aErrorInfo)
398{
399 CheckComArgOutPointerValid(aErrorInfo);
400
401 AutoCaller autoCaller(this);
402 CheckComRCReturnRC(autoCaller.rc());
403
404 AutoReadLock alock(this);
405
406 if (!mCompleted)
407 return setError (E_FAIL,
408 tr ("Error info is not available, operation is still in progress"));
409
410 mErrorInfo.queryInterfaceTo(aErrorInfo);
411
412 return S_OK;
413}
414
415STDMETHODIMP ProgressBase::COMGETTER(OperationCount) (ULONG *aOperationCount)
416{
417 CheckComArgOutPointerValid(aOperationCount);
418
419 AutoCaller autoCaller(this);
420 CheckComRCReturnRC(autoCaller.rc());
421
422 AutoReadLock alock(this);
423
424 *aOperationCount = m_cOperations;
425
426 return S_OK;
427}
428
429STDMETHODIMP ProgressBase::COMGETTER(Operation) (ULONG *aOperation)
430{
431 CheckComArgOutPointerValid(aOperation);
432
433 AutoCaller autoCaller(this);
434 CheckComRCReturnRC(autoCaller.rc());
435
436 AutoReadLock alock(this);
437
438 *aOperation = m_ulCurrentOperation;
439
440 return S_OK;
441}
442
443STDMETHODIMP ProgressBase::COMGETTER(OperationDescription) (BSTR *aOperationDescription)
444{
445 CheckComArgOutPointerValid(aOperationDescription);
446
447 AutoCaller autoCaller(this);
448 CheckComRCReturnRC(autoCaller.rc());
449
450 AutoReadLock alock(this);
451
452 m_bstrOperationDescription.cloneTo(aOperationDescription);
453
454 return S_OK;
455}
456
457STDMETHODIMP ProgressBase::COMGETTER(OperationPercent)(ULONG *aOperationPercent)
458{
459 CheckComArgOutPointerValid(aOperationPercent);
460
461 AutoCaller autoCaller(this);
462 CheckComRCReturnRC(autoCaller.rc());
463
464 AutoReadLock alock(this);
465
466 if (mCompleted && SUCCEEDED(mResultCode))
467 *aOperationPercent = 100;
468 else
469 *aOperationPercent = m_ulOperationPercent;
470
471 return S_OK;
472}
473
474STDMETHODIMP ProgressBase::COMSETTER(Timeout)(ULONG aTimeout)
475{
476 AutoCaller autoCaller(this);
477 CheckComRCReturnRC(autoCaller.rc());
478
479 AutoWriteLock alock(this);
480
481 if (!mCancelable)
482 return setError(VBOX_E_INVALID_OBJECT_STATE,
483 tr("Operation cannot be canceled"));
484
485 LogThisFunc(("%#x => %#x\n", m_cMsTimeout, aTimeout));
486 m_cMsTimeout = aTimeout;
487 return S_OK;
488}
489
490STDMETHODIMP ProgressBase::COMGETTER(Timeout)(ULONG *aTimeout)
491{
492 CheckComArgOutPointerValid(aTimeout);
493
494 AutoCaller autoCaller(this);
495 CheckComRCReturnRC(autoCaller.rc());
496
497 AutoReadLock alock(this);
498
499 *aTimeout = m_cMsTimeout;
500 return S_OK;
501}
502
503// public methods only for internal purposes
504////////////////////////////////////////////////////////////////////////////////
505
506/**
507 * Sets the error info stored in the given progress object as the error info on
508 * the current thread.
509 *
510 * This method is useful if some other COM method uses IProgress to wait for
511 * something and then wants to return a failed result of the operation it was
512 * waiting for as its own result retaining the extended error info.
513 *
514 * If the operation tracked by this progress object is completed successfully
515 * and returned S_OK, this method does nothing but returns S_OK. Otherwise, the
516 * failed warning or error result code specified at progress completion is
517 * returned and the extended error info object (if any) is set on the current
518 * thread.
519 *
520 * Note that the given progress object must be completed, otherwise this method
521 * will assert and fail.
522 */
523/* static */
524HRESULT ProgressBase::setErrorInfoOnThread (IProgress *aProgress)
525{
526 AssertReturn(aProgress != NULL, E_INVALIDARG);
527
528 LONG iRc;
529 HRESULT rc = aProgress->COMGETTER(ResultCode) (&iRc);
530 AssertComRCReturnRC(rc);
531 HRESULT resultCode = iRc;
532
533 if (resultCode == S_OK)
534 return resultCode;
535
536 ComPtr<IVirtualBoxErrorInfo> errorInfo;
537 rc = aProgress->COMGETTER(ErrorInfo) (errorInfo.asOutParam());
538 AssertComRCReturnRC(rc);
539
540 if (!errorInfo.isNull())
541 setErrorInfo (errorInfo);
542
543 return resultCode;
544}
545
546/**
547 * Sets the cancelation callback, checking for cancelation first.
548 *
549 * @returns Success indicator.
550 * @retval true on success.
551 * @retval false if the progress object has already been canceled or is in an
552 * invalid state
553 *
554 * @param pfnCallback The function to be called upon cancelation.
555 * @param pvUser The callback argument.
556 */
557bool ProgressBase::setCancelCallback(void (*pfnCallback)(void *), void *pvUser)
558{
559 AutoCaller autoCaller(this);
560 AssertComRCReturn(autoCaller.rc(), false);
561
562 AutoWriteLock alock(this);
563
564 if (mCanceled)
565 return false;
566
567 m_pvCancelUserArg = pvUser;
568 m_pfnCancelCallback = pfnCallback;
569 return true;
570}
571
572////////////////////////////////////////////////////////////////////////////////
573// Progress class
574////////////////////////////////////////////////////////////////////////////////
575
576HRESULT Progress::FinalConstruct()
577{
578 HRESULT rc = ProgressBase::FinalConstruct();
579 CheckComRCReturnRC(rc);
580
581 mCompletedSem = NIL_RTSEMEVENTMULTI;
582 mWaitersCount = 0;
583
584 return S_OK;
585}
586
587void Progress::FinalRelease()
588{
589 uninit();
590}
591
592// public initializer/uninitializer for internal purposes only
593////////////////////////////////////////////////////////////////////////////////
594
595/**
596 * Initializes the normal progress object. With this variant, one can have
597 * an arbitrary number of sub-operation which IProgress can analyze to
598 * have a weighted progress computed.
599 *
600 * For example, say that one IProgress is supposed to track the cloning
601 * of two hard disk images, which are 100 MB and 1000 MB in size, respectively,
602 * and each of these hard disks should be one sub-operation of the IProgress.
603 *
604 * Obviously the progress would be misleading if the progress displayed 50%
605 * after the smaller image was cloned and would then take much longer for
606 * the second half.
607 *
608 * With weighted progress, one can invoke the following calls:
609 *
610 * 1) create progress object with cOperations = 2 and ulTotalOperationsWeight =
611 * 1100 (100 MB plus 1100, but really the weights can be any ULONG); pass
612 * in ulFirstOperationWeight = 100 for the first sub-operation
613 *
614 * 2) Then keep calling setCurrentOperationProgress() with a percentage
615 * for the first image; the total progress will increase up to a value
616 * of 9% (100MB / 1100MB * 100%).
617 *
618 * 3) Then call setNextOperation with the second weight (1000 for the megabytes
619 * of the second disk).
620 *
621 * 4) Then keep calling setCurrentOperationProgress() with a percentage for
622 * the second image, where 100% of the operation will then yield a 100%
623 * progress of the entire task.
624 *
625 * Weighting is optional; you can simply assign a weight of 1 to each operation
626 * and pass ulTotalOperationsWeight == cOperations to this constructor (but
627 * for that variant and for backwards-compatibility a simpler constructor exists
628 * in ProgressImpl.h as well).
629 *
630 * Even simpler, if you need no sub-operations at all, pass in cOperations =
631 * ulTotalOperationsWeight = ulFirstOperationWeight = 1.
632 *
633 * @param aParent See ProgressBase::init().
634 * @param aInitiator See ProgressBase::init().
635 * @param aDescription See ProgressBase::init().
636 * @param aCancelable Flag whether the task maybe canceled.
637 * @param cOperations Number of operations within this task (at least 1).
638 * @param ulTotalOperationsWeight Total weight of operations; must be the sum of ulFirstOperationWeight and
639 * what is later passed with each subsequent setNextOperation() call.
640 * @param bstrFirstOperationDescription Description of the first operation.
641 * @param ulFirstOperationWeight Weight of first sub-operation.
642 * @param aId See ProgressBase::init().
643 */
644HRESULT Progress::init (
645#if !defined (VBOX_COM_INPROC)
646 VirtualBox *aParent,
647#endif
648 IUnknown *aInitiator,
649 CBSTR aDescription,
650 BOOL aCancelable,
651 ULONG cOperations,
652 ULONG ulTotalOperationsWeight,
653 CBSTR bstrFirstOperationDescription,
654 ULONG ulFirstOperationWeight,
655 OUT_GUID aId /* = NULL */)
656{
657 LogFlowThisFunc(("aDescription=\"%ls\", cOperations=%d, ulTotalOperationsWeight=%d, bstrFirstOperationDescription=\"%ls\", ulFirstOperationWeight=%d\n",
658 aDescription,
659 cOperations,
660 ulTotalOperationsWeight,
661 bstrFirstOperationDescription,
662 ulFirstOperationWeight));
663
664 AssertReturn(bstrFirstOperationDescription, E_INVALIDARG);
665 AssertReturn(ulTotalOperationsWeight >= 1, E_INVALIDARG);
666
667 /* Enclose the state transition NotReady->InInit->Ready */
668 AutoInitSpan autoInitSpan(this);
669 AssertReturn(autoInitSpan.isOk(), E_FAIL);
670
671 HRESULT rc = S_OK;
672
673 rc = ProgressBase::protectedInit (autoInitSpan,
674#if !defined (VBOX_COM_INPROC)
675 aParent,
676#endif
677 aInitiator, aDescription, aId);
678 CheckComRCReturnRC(rc);
679
680 mCancelable = aCancelable;
681
682 m_cOperations = cOperations;
683 m_ulTotalOperationsWeight = ulTotalOperationsWeight;
684 m_ulOperationsCompletedWeight = 0;
685 m_ulCurrentOperation = 0;
686 m_bstrOperationDescription = bstrFirstOperationDescription;
687 m_ulCurrentOperationWeight = ulFirstOperationWeight;
688 m_ulOperationPercent = 0;
689
690 int vrc = RTSemEventMultiCreate (&mCompletedSem);
691 ComAssertRCRet (vrc, E_FAIL);
692
693 RTSemEventMultiReset (mCompletedSem);
694
695 /* Confirm a successful initialization when it's the case */
696 if (SUCCEEDED(rc))
697 autoInitSpan.setSucceeded();
698
699 return rc;
700}
701
702/**
703 * Initializes the sub-progress object that represents a specific operation of
704 * the whole task.
705 *
706 * Objects initialized with this method are then combined together into the
707 * single task using a CombinedProgress instance, so it doesn't require the
708 * parent, initiator, description and doesn't create an ID. Note that calling
709 * respective getter methods on an object initialized with this method is
710 * useless. Such objects are used only to provide a separate wait semaphore and
711 * store individual operation descriptions.
712 *
713 * @param aCancelable Flag whether the task maybe canceled.
714 * @param aOperationCount Number of sub-operations within this task (at least 1).
715 * @param aOperationDescription Description of the individual operation.
716 */
717HRESULT Progress::init(BOOL aCancelable,
718 ULONG aOperationCount,
719 CBSTR aOperationDescription)
720{
721 LogFlowThisFunc(("aOperationDescription=\"%ls\"\n", aOperationDescription));
722
723 /* Enclose the state transition NotReady->InInit->Ready */
724 AutoInitSpan autoInitSpan(this);
725 AssertReturn(autoInitSpan.isOk(), E_FAIL);
726
727 HRESULT rc = S_OK;
728
729 rc = ProgressBase::protectedInit (autoInitSpan);
730 CheckComRCReturnRC(rc);
731
732 mCancelable = aCancelable;
733
734 // for this variant we assume for now that all operations are weighed "1"
735 // and equal total weight = operation count
736 m_cOperations = aOperationCount;
737 m_ulTotalOperationsWeight = aOperationCount;
738 m_ulOperationsCompletedWeight = 0;
739 m_ulCurrentOperation = 0;
740 m_bstrOperationDescription = aOperationDescription;
741 m_ulCurrentOperationWeight = 1;
742 m_ulOperationPercent = 0;
743
744 int vrc = RTSemEventMultiCreate (&mCompletedSem);
745 ComAssertRCRet (vrc, E_FAIL);
746
747 RTSemEventMultiReset (mCompletedSem);
748
749 /* Confirm a successful initialization when it's the case */
750 if (SUCCEEDED(rc))
751 autoInitSpan.setSucceeded();
752
753 return rc;
754}
755
756/**
757 * Uninitializes the instance and sets the ready flag to FALSE.
758 *
759 * Called either from FinalRelease() or by the parent when it gets destroyed.
760 */
761void Progress::uninit()
762{
763 LogFlowThisFunc(("\n"));
764
765 /* Enclose the state transition Ready->InUninit->NotReady */
766 AutoUninitSpan autoUninitSpan(this);
767 if (autoUninitSpan.uninitDone())
768 return;
769
770 /* wake up all threads still waiting on occasion */
771 if (mWaitersCount > 0)
772 {
773 LogFlow (("WARNING: There are still %d threads waiting for '%ls' completion!\n",
774 mWaitersCount, mDescription.raw()));
775 RTSemEventMultiSignal (mCompletedSem);
776 }
777
778 RTSemEventMultiDestroy (mCompletedSem);
779
780 ProgressBase::protectedUninit (autoUninitSpan);
781}
782
783// IProgress properties
784/////////////////////////////////////////////////////////////////////////////
785
786// IProgress methods
787/////////////////////////////////////////////////////////////////////////////
788
789/**
790 * @note XPCOM: when this method is not called on the main XPCOM thread, it
791 * simply blocks the thread until mCompletedSem is signalled. If the
792 * thread has its own event queue (hmm, what for?) that it must run, then
793 * calling this method will definitely freeze event processing.
794 */
795STDMETHODIMP Progress::WaitForCompletion (LONG aTimeout)
796{
797 LogFlowThisFuncEnter();
798 LogFlowThisFunc(("aTimeout=%d\n", aTimeout));
799
800 AutoCaller autoCaller(this);
801 CheckComRCReturnRC(autoCaller.rc());
802
803 AutoWriteLock alock(this);
804
805 /* if we're already completed, take a shortcut */
806 if (!mCompleted)
807 {
808 RTTIMESPEC time;
809 RTTimeNow (&time); /** @todo r=bird: Use monotonic time (RTTimeMilliTS()) here because of daylight saving and things like that. */
810
811 int vrc = VINF_SUCCESS;
812 bool fForever = aTimeout < 0;
813 int64_t timeLeft = aTimeout;
814 int64_t lastTime = RTTimeSpecGetMilli (&time);
815
816 while (!mCompleted && (fForever || timeLeft > 0))
817 {
818 mWaitersCount++;
819 alock.leave();
820 int vrc = RTSemEventMultiWait(mCompletedSem,
821 fForever ? RT_INDEFINITE_WAIT : (unsigned)timeLeft);
822 alock.enter();
823 mWaitersCount--;
824
825 /* the last waiter resets the semaphore */
826 if (mWaitersCount == 0)
827 RTSemEventMultiReset(mCompletedSem);
828
829 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
830 break;
831
832 if (!fForever)
833 {
834 RTTimeNow (&time);
835 timeLeft -= RTTimeSpecGetMilli(&time) - lastTime;
836 lastTime = RTTimeSpecGetMilli(&time);
837 }
838 }
839
840 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
841 return setError(VBOX_E_IPRT_ERROR,
842 tr("Failed to wait for the task completion (%Rrc)"),
843 vrc);
844 }
845
846 LogFlowThisFuncLeave();
847
848 return S_OK;
849}
850
851/**
852 * @note XPCOM: when this method is not called on the main XPCOM thread, it
853 * simply blocks the thread until mCompletedSem is signalled. If the
854 * thread has its own event queue (hmm, what for?) that it must run, then
855 * calling this method will definitely freeze event processing.
856 */
857STDMETHODIMP Progress::WaitForOperationCompletion(ULONG aOperation, LONG aTimeout)
858{
859 LogFlowThisFuncEnter();
860 LogFlowThisFunc(("aOperation=%d, aTimeout=%d\n", aOperation, aTimeout));
861
862 AutoCaller autoCaller(this);
863 CheckComRCReturnRC(autoCaller.rc());
864
865 AutoWriteLock alock(this);
866
867 CheckComArgExpr(aOperation, aOperation < m_cOperations);
868
869 /* if we're already completed or if the given operation is already done,
870 * then take a shortcut */
871 if ( !mCompleted
872 && aOperation >= m_ulCurrentOperation)
873 {
874 RTTIMESPEC time;
875 RTTimeNow (&time);
876
877 int vrc = VINF_SUCCESS;
878 bool fForever = aTimeout < 0;
879 int64_t timeLeft = aTimeout;
880 int64_t lastTime = RTTimeSpecGetMilli (&time);
881
882 while ( !mCompleted && aOperation >= m_ulCurrentOperation
883 && (fForever || timeLeft > 0))
884 {
885 mWaitersCount ++;
886 alock.leave();
887 int vrc = RTSemEventMultiWait(mCompletedSem,
888 fForever ? RT_INDEFINITE_WAIT : (unsigned) timeLeft);
889 alock.enter();
890 mWaitersCount--;
891
892 /* the last waiter resets the semaphore */
893 if (mWaitersCount == 0)
894 RTSemEventMultiReset(mCompletedSem);
895
896 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
897 break;
898
899 if (!fForever)
900 {
901 RTTimeNow(&time);
902 timeLeft -= RTTimeSpecGetMilli(&time) - lastTime;
903 lastTime = RTTimeSpecGetMilli(&time);
904 }
905 }
906
907 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
908 return setError(E_FAIL,
909 tr("Failed to wait for the operation completion (%Rrc)"),
910 vrc);
911 }
912
913 LogFlowThisFuncLeave();
914
915 return S_OK;
916}
917
918STDMETHODIMP Progress::Cancel()
919{
920 AutoCaller autoCaller(this);
921 CheckComRCReturnRC(autoCaller.rc());
922
923 AutoWriteLock alock(this);
924
925 if (!mCancelable)
926 return setError(VBOX_E_INVALID_OBJECT_STATE,
927 tr("Operation cannot be canceled"));
928
929 if (!mCanceled)
930 {
931 mCanceled = TRUE;
932 if (m_pfnCancelCallback)
933 m_pfnCancelCallback(m_pvCancelUserArg);
934
935 }
936 return S_OK;
937}
938
939/**
940 * Updates the percentage value of the current operation.
941 *
942 * @param aPercent New percentage value of the operation in progress
943 * (in range [0, 100]).
944 */
945STDMETHODIMP Progress::SetCurrentOperationProgress(ULONG aPercent)
946{
947 AutoCaller autoCaller(this);
948 AssertComRCReturnRC(autoCaller.rc());
949
950 AutoWriteLock alock(this);
951
952 AssertReturn(aPercent <= 100, E_INVALIDARG);
953
954 if (mCancelable && mCanceled)
955 {
956 Assert(!mCompleted);
957 return E_FAIL;
958 }
959 else
960 AssertReturn(!mCompleted && !mCanceled, E_FAIL);
961
962 m_ulOperationPercent = aPercent;
963
964 return S_OK;
965}
966
967/**
968 * Signals that the current operation is successfully completed and advances to
969 * the next operation. The operation percentage is reset to 0.
970 *
971 * @param aOperationDescription Description of the next operation.
972 *
973 * @note The current operation must not be the last one.
974 */
975STDMETHODIMP Progress::SetNextOperation(IN_BSTR bstrNextOperationDescription, ULONG ulNextOperationsWeight)
976{
977 AssertReturn(bstrNextOperationDescription, E_INVALIDARG);
978
979 AutoCaller autoCaller(this);
980 AssertComRCReturnRC(autoCaller.rc());
981
982 AutoWriteLock alock(this);
983
984 AssertReturn(!mCompleted && !mCanceled, E_FAIL);
985 AssertReturn(m_ulCurrentOperation + 1 < m_cOperations, E_FAIL);
986
987 ++m_ulCurrentOperation;
988 m_ulOperationsCompletedWeight += m_ulCurrentOperationWeight;
989
990 m_bstrOperationDescription = bstrNextOperationDescription;
991 m_ulCurrentOperationWeight = ulNextOperationsWeight;
992 m_ulOperationPercent = 0;
993
994 Log(("Progress::setNextOperation(%ls): ulNextOperationsWeight = %d; m_ulCurrentOperation is now %d, m_ulOperationsCompletedWeight is now %d\n",
995 m_bstrOperationDescription.raw(), ulNextOperationsWeight, m_ulCurrentOperation, m_ulOperationsCompletedWeight));
996
997 /* wake up all waiting threads */
998 if (mWaitersCount > 0)
999 RTSemEventMultiSignal(mCompletedSem);
1000
1001 return S_OK;
1002}
1003
1004// public methods only for internal purposes
1005/////////////////////////////////////////////////////////////////////////////
1006
1007/**
1008 * Sets the internal result code and attempts to retrieve additional error
1009 * info from the current thread. Gets called from Progress::notifyComplete(),
1010 * but can be called again to override a previous result set with
1011 * notifyComplete().
1012 *
1013 * @param aResultCode
1014 */
1015HRESULT Progress::setResultCode(HRESULT aResultCode)
1016{
1017 AutoCaller autoCaller(this);
1018 AssertComRCReturnRC(autoCaller.rc());
1019
1020 AutoWriteLock alock(this);
1021
1022 mResultCode = aResultCode;
1023
1024 HRESULT rc = S_OK;
1025
1026 if (FAILED(aResultCode))
1027 {
1028 /* try to import error info from the current thread */
1029
1030#if !defined (VBOX_WITH_XPCOM)
1031
1032 ComPtr<IErrorInfo> err;
1033 rc = ::GetErrorInfo(0, err.asOutParam());
1034 if (rc == S_OK && err)
1035 {
1036 rc = err.queryInterfaceTo(mErrorInfo.asOutParam());
1037 if (SUCCEEDED(rc) && !mErrorInfo)
1038 rc = E_FAIL;
1039 }
1040
1041#else /* !defined (VBOX_WITH_XPCOM) */
1042
1043 nsCOMPtr<nsIExceptionService> es;
1044 es = do_GetService(NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
1045 if (NS_SUCCEEDED(rc))
1046 {
1047 nsCOMPtr <nsIExceptionManager> em;
1048 rc = es->GetCurrentExceptionManager(getter_AddRefs(em));
1049 if (NS_SUCCEEDED(rc))
1050 {
1051 ComPtr<nsIException> ex;
1052 rc = em->GetCurrentException(ex.asOutParam());
1053 if (NS_SUCCEEDED(rc) && ex)
1054 {
1055 rc = ex.queryInterfaceTo(mErrorInfo.asOutParam());
1056 if (NS_SUCCEEDED(rc) && !mErrorInfo)
1057 rc = E_FAIL;
1058 }
1059 }
1060 }
1061#endif /* !defined (VBOX_WITH_XPCOM) */
1062
1063 AssertMsg (rc == S_OK, ("Couldn't get error info (rc=%08X) while trying "
1064 "to set a failed result (%08X)!\n", rc, aResultCode));
1065 }
1066
1067 return rc;
1068}
1069
1070/**
1071 * Marks the whole task as complete and sets the result code.
1072 *
1073 * If the result code indicates a failure (|FAILED (@a aResultCode)|) then this
1074 * method will import the error info from the current thread and assign it to
1075 * the errorInfo attribute (it will return an error if no info is available in
1076 * such case).
1077 *
1078 * If the result code indicates a success (|SUCCEEDED(@a aResultCode)|) then
1079 * the current operation is set to the last.
1080 *
1081 * Note that this method may be called only once for the given Progress object.
1082 * Subsequent calls will assert.
1083 *
1084 * @param aResultCode Operation result code.
1085 */
1086HRESULT Progress::notifyComplete(HRESULT aResultCode)
1087{
1088 AutoCaller autoCaller(this);
1089 AssertComRCReturnRC(autoCaller.rc());
1090
1091 AutoWriteLock alock(this);
1092
1093 AssertReturn(mCompleted == FALSE, E_FAIL);
1094
1095 if (mCanceled && SUCCEEDED(aResultCode))
1096 aResultCode = E_FAIL;
1097
1098 HRESULT rc = setResultCode(aResultCode);
1099
1100 mCompleted = TRUE;
1101
1102 if (!FAILED(aResultCode))
1103 {
1104 m_ulCurrentOperation = m_cOperations - 1; /* last operation */
1105 m_ulOperationPercent = 100;
1106 }
1107
1108#if !defined VBOX_COM_INPROC
1109 /* remove from the global collection of pending progress operations */
1110 if (mParent)
1111 mParent->removeProgress (mId);
1112#endif
1113
1114 /* wake up all waiting threads */
1115 if (mWaitersCount > 0)
1116 RTSemEventMultiSignal (mCompletedSem);
1117
1118 return rc;
1119}
1120
1121/**
1122 * Marks the operation as complete and attaches full error info.
1123 *
1124 * See com::SupportErrorInfoImpl::setError(HRESULT, const GUID &, const wchar_t
1125 * *, const char *, ...) for more info.
1126 *
1127 * @param aResultCode Operation result (error) code, must not be S_OK.
1128 * @param aIID IID of the interface that defines the error.
1129 * @param aComponent Name of the component that generates the error.
1130 * @param aText Error message (must not be null), an RTStrPrintf-like
1131 * format string in UTF-8 encoding.
1132 * @param ... List of arguments for the format string.
1133 */
1134HRESULT Progress::notifyComplete(HRESULT aResultCode,
1135 const GUID &aIID,
1136 const Bstr &aComponent,
1137 const char *aText,
1138 ...)
1139{
1140 va_list args;
1141 va_start(args, aText);
1142 Utf8Str text = Utf8StrFmtVA(aText, args);
1143 va_end (args);
1144
1145 AutoCaller autoCaller(this);
1146 AssertComRCReturnRC(autoCaller.rc());
1147
1148 AutoWriteLock alock(this);
1149
1150 AssertReturn(mCompleted == FALSE, E_FAIL);
1151
1152 if (mCanceled && SUCCEEDED(aResultCode))
1153 aResultCode = E_FAIL;
1154
1155 mCompleted = TRUE;
1156 mResultCode = aResultCode;
1157
1158 AssertReturn(FAILED (aResultCode), E_FAIL);
1159
1160 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
1161 HRESULT rc = errorInfo.createObject();
1162 AssertComRC (rc);
1163 if (SUCCEEDED(rc))
1164 {
1165 errorInfo->init(aResultCode, aIID, aComponent, Bstr(text));
1166 errorInfo.queryInterfaceTo(mErrorInfo.asOutParam());
1167 }
1168
1169#if !defined VBOX_COM_INPROC
1170 /* remove from the global collection of pending progress operations */
1171 if (mParent)
1172 mParent->removeProgress (mId);
1173#endif
1174
1175 /* wake up all waiting threads */
1176 if (mWaitersCount > 0)
1177 RTSemEventMultiSignal(mCompletedSem);
1178
1179 return rc;
1180}
1181
1182/**
1183 * Notify the progress object that we're almost at the point of no return.
1184 *
1185 * This atomically checks for and disables cancelation. Calls to
1186 * IProgress::Cancel() made after a successfull call to this method will fail
1187 * and the user can be told. While this isn't entirely clean behavior, it
1188 * prevents issues with an irreversible actually operation succeeding while the
1189 * user belive it was rolled back.
1190 *
1191 * @returns Success indicator.
1192 * @retval true on success.
1193 * @retval false if the progress object has already been canceled or is in an
1194 * invalid state
1195 */
1196bool Progress::notifyPointOfNoReturn(void)
1197{
1198 AutoCaller autoCaller(this);
1199 AssertComRCReturn(autoCaller.rc(), false);
1200
1201 AutoWriteLock alock(this);
1202
1203 if (mCanceled)
1204 return false;
1205
1206 mCancelable = FALSE;
1207 return true;
1208}
1209
1210////////////////////////////////////////////////////////////////////////////////
1211// CombinedProgress class
1212////////////////////////////////////////////////////////////////////////////////
1213
1214HRESULT CombinedProgress::FinalConstruct()
1215{
1216 HRESULT rc = ProgressBase::FinalConstruct();
1217 CheckComRCReturnRC(rc);
1218
1219 mProgress = 0;
1220 mCompletedOperations = 0;
1221
1222 return S_OK;
1223}
1224
1225void CombinedProgress::FinalRelease()
1226{
1227 uninit();
1228}
1229
1230// public initializer/uninitializer for internal purposes only
1231////////////////////////////////////////////////////////////////////////////////
1232
1233/**
1234 * Initializes this object based on individual combined progresses.
1235 * Must be called only from #init()!
1236 *
1237 * @param aAutoInitSpan AutoInitSpan object instantiated by a subclass.
1238 * @param aParent See ProgressBase::init().
1239 * @param aInitiator See ProgressBase::init().
1240 * @param aDescription See ProgressBase::init().
1241 * @param aId See ProgressBase::init().
1242 */
1243HRESULT CombinedProgress::protectedInit (AutoInitSpan &aAutoInitSpan,
1244#if !defined (VBOX_COM_INPROC)
1245 VirtualBox *aParent,
1246#endif
1247 IUnknown *aInitiator,
1248 CBSTR aDescription, OUT_GUID aId)
1249{
1250 LogFlowThisFunc(("aDescription={%ls} mProgresses.size()=%d\n",
1251 aDescription, mProgresses.size()));
1252
1253 HRESULT rc = S_OK;
1254
1255 rc = ProgressBase::protectedInit (aAutoInitSpan,
1256#if !defined (VBOX_COM_INPROC)
1257 aParent,
1258#endif
1259 aInitiator, aDescription, aId);
1260 CheckComRCReturnRC(rc);
1261
1262 mProgress = 0; /* the first object */
1263 mCompletedOperations = 0;
1264
1265 mCompleted = FALSE;
1266 mCancelable = TRUE; /* until any progress returns FALSE */
1267 mCanceled = FALSE;
1268
1269 m_cOperations = 0; /* will be calculated later */
1270
1271 m_ulCurrentOperation = 0;
1272 rc = mProgresses [0]->COMGETTER(OperationDescription) (
1273 m_bstrOperationDescription.asOutParam());
1274 CheckComRCReturnRC(rc);
1275
1276 for (size_t i = 0; i < mProgresses.size(); i ++)
1277 {
1278 if (mCancelable)
1279 {
1280 BOOL cancelable = FALSE;
1281 rc = mProgresses [i]->COMGETTER(Cancelable) (&cancelable);
1282 CheckComRCReturnRC(rc);
1283
1284 if (!cancelable)
1285 mCancelable = FALSE;
1286 }
1287
1288 {
1289 ULONG opCount = 0;
1290 rc = mProgresses [i]->COMGETTER(OperationCount) (&opCount);
1291 CheckComRCReturnRC(rc);
1292
1293 m_cOperations += opCount;
1294 }
1295 }
1296
1297 rc = checkProgress();
1298 CheckComRCReturnRC(rc);
1299
1300 return rc;
1301}
1302
1303/**
1304 * Initializes the combined progress object given two normal progress
1305 * objects.
1306 *
1307 * @param aParent See ProgressBase::init().
1308 * @param aInitiator See ProgressBase::init().
1309 * @param aDescription See ProgressBase::init().
1310 * @param aProgress1 First normal progress object.
1311 * @param aProgress2 Second normal progress object.
1312 * @param aId See ProgressBase::init().
1313 */
1314HRESULT CombinedProgress::init (
1315#if !defined (VBOX_COM_INPROC)
1316 VirtualBox *aParent,
1317#endif
1318 IUnknown *aInitiator,
1319 CBSTR aDescription,
1320 IProgress *aProgress1, IProgress *aProgress2,
1321 OUT_GUID aId /* = NULL */)
1322{
1323 /* Enclose the state transition NotReady->InInit->Ready */
1324 AutoInitSpan autoInitSpan(this);
1325 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1326
1327 mProgresses.resize (2);
1328 mProgresses [0] = aProgress1;
1329 mProgresses [1] = aProgress2;
1330
1331 HRESULT rc = protectedInit (autoInitSpan,
1332#if !defined (VBOX_COM_INPROC)
1333 aParent,
1334#endif
1335 aInitiator, aDescription, aId);
1336
1337 /* Confirm a successful initialization when it's the case */
1338 if (SUCCEEDED(rc))
1339 autoInitSpan.setSucceeded();
1340
1341 return rc;
1342}
1343
1344/**
1345 * Uninitializes the instance and sets the ready flag to FALSE.
1346 *
1347 * Called either from FinalRelease() or by the parent when it gets destroyed.
1348 */
1349void CombinedProgress::uninit()
1350{
1351 LogFlowThisFunc(("\n"));
1352
1353 /* Enclose the state transition Ready->InUninit->NotReady */
1354 AutoUninitSpan autoUninitSpan(this);
1355 if (autoUninitSpan.uninitDone())
1356 return;
1357
1358 mProgress = 0;
1359 mProgresses.clear();
1360
1361 ProgressBase::protectedUninit (autoUninitSpan);
1362}
1363
1364// IProgress properties
1365////////////////////////////////////////////////////////////////////////////////
1366
1367STDMETHODIMP CombinedProgress::COMGETTER(Percent)(ULONG *aPercent)
1368{
1369 CheckComArgOutPointerValid(aPercent);
1370
1371 AutoCaller autoCaller(this);
1372 CheckComRCReturnRC(autoCaller.rc());
1373
1374 /* checkProgress needs a write lock */
1375 AutoWriteLock alock(this);
1376
1377 if (mCompleted && SUCCEEDED(mResultCode))
1378 *aPercent = 100;
1379 else
1380 {
1381 HRESULT rc = checkProgress();
1382 CheckComRCReturnRC(rc);
1383
1384 /* global percent =
1385 * (100 / m_cOperations) * mOperation +
1386 * ((100 / m_cOperations) / 100) * m_ulOperationPercent */
1387 *aPercent = (100 * m_ulCurrentOperation + m_ulOperationPercent) / m_cOperations;
1388 }
1389
1390 return S_OK;
1391}
1392
1393STDMETHODIMP CombinedProgress::COMGETTER(Completed) (BOOL *aCompleted)
1394{
1395 CheckComArgOutPointerValid(aCompleted);
1396
1397 AutoCaller autoCaller(this);
1398 CheckComRCReturnRC(autoCaller.rc());
1399
1400 /* checkProgress needs a write lock */
1401 AutoWriteLock alock(this);
1402
1403 HRESULT rc = checkProgress();
1404 CheckComRCReturnRC(rc);
1405
1406 return ProgressBase::COMGETTER(Completed) (aCompleted);
1407}
1408
1409STDMETHODIMP CombinedProgress::COMGETTER(Canceled) (BOOL *aCanceled)
1410{
1411 CheckComArgOutPointerValid(aCanceled);
1412
1413 AutoCaller autoCaller(this);
1414 CheckComRCReturnRC(autoCaller.rc());
1415
1416 /* checkProgress needs a write lock */
1417 AutoWriteLock alock(this);
1418
1419 HRESULT rc = checkProgress();
1420 CheckComRCReturnRC(rc);
1421
1422 return ProgressBase::COMGETTER(Canceled) (aCanceled);
1423}
1424
1425STDMETHODIMP CombinedProgress::COMGETTER(ResultCode) (LONG *aResultCode)
1426{
1427 CheckComArgOutPointerValid(aResultCode);
1428
1429 AutoCaller autoCaller(this);
1430 CheckComRCReturnRC(autoCaller.rc());
1431
1432 /* checkProgress needs a write lock */
1433 AutoWriteLock alock(this);
1434
1435 HRESULT rc = checkProgress();
1436 CheckComRCReturnRC(rc);
1437
1438 return ProgressBase::COMGETTER(ResultCode) (aResultCode);
1439}
1440
1441STDMETHODIMP CombinedProgress::COMGETTER(ErrorInfo) (IVirtualBoxErrorInfo **aErrorInfo)
1442{
1443 CheckComArgOutPointerValid(aErrorInfo);
1444
1445 AutoCaller autoCaller(this);
1446 CheckComRCReturnRC(autoCaller.rc());
1447
1448 /* checkProgress needs a write lock */
1449 AutoWriteLock alock(this);
1450
1451 HRESULT rc = checkProgress();
1452 CheckComRCReturnRC(rc);
1453
1454 return ProgressBase::COMGETTER(ErrorInfo) (aErrorInfo);
1455}
1456
1457STDMETHODIMP CombinedProgress::COMGETTER(Operation) (ULONG *aOperation)
1458{
1459 CheckComArgOutPointerValid(aOperation);
1460
1461 AutoCaller autoCaller(this);
1462 CheckComRCReturnRC(autoCaller.rc());
1463
1464 /* checkProgress needs a write lock */
1465 AutoWriteLock alock(this);
1466
1467 HRESULT rc = checkProgress();
1468 CheckComRCReturnRC(rc);
1469
1470 return ProgressBase::COMGETTER(Operation) (aOperation);
1471}
1472
1473STDMETHODIMP CombinedProgress::COMGETTER(OperationDescription) (BSTR *aOperationDescription)
1474{
1475 CheckComArgOutPointerValid(aOperationDescription);
1476
1477 AutoCaller autoCaller(this);
1478 CheckComRCReturnRC(autoCaller.rc());
1479
1480 /* checkProgress needs a write lock */
1481 AutoWriteLock alock(this);
1482
1483 HRESULT rc = checkProgress();
1484 CheckComRCReturnRC(rc);
1485
1486 return ProgressBase::COMGETTER(OperationDescription) (aOperationDescription);
1487}
1488
1489STDMETHODIMP CombinedProgress::COMGETTER(OperationPercent)(ULONG *aOperationPercent)
1490{
1491 CheckComArgOutPointerValid(aOperationPercent);
1492
1493 AutoCaller autoCaller(this);
1494 CheckComRCReturnRC(autoCaller.rc());
1495
1496 /* checkProgress needs a write lock */
1497 AutoWriteLock alock(this);
1498
1499 HRESULT rc = checkProgress();
1500 CheckComRCReturnRC(rc);
1501
1502 return ProgressBase::COMGETTER(OperationPercent) (aOperationPercent);
1503}
1504
1505STDMETHODIMP CombinedProgress::COMSETTER(Timeout)(ULONG aTimeout)
1506{
1507 NOREF(aTimeout);
1508 AssertFailed();
1509 return E_NOTIMPL;
1510}
1511
1512STDMETHODIMP CombinedProgress::COMGETTER(Timeout)(ULONG *aTimeout)
1513{
1514 CheckComArgOutPointerValid(aTimeout);
1515
1516 AssertFailed();
1517 return E_NOTIMPL;
1518}
1519
1520// IProgress methods
1521/////////////////////////////////////////////////////////////////////////////
1522
1523/**
1524 * @note XPCOM: when this method is called not on the main XPCOM thread, it
1525 * simply blocks the thread until mCompletedSem is signalled. If the
1526 * thread has its own event queue (hmm, what for?) that it must run, then
1527 * calling this method will definitely freeze event processing.
1528 */
1529STDMETHODIMP CombinedProgress::WaitForCompletion (LONG aTimeout)
1530{
1531 LogFlowThisFuncEnter();
1532 LogFlowThisFunc(("aTtimeout=%d\n", aTimeout));
1533
1534 AutoCaller autoCaller(this);
1535 CheckComRCReturnRC(autoCaller.rc());
1536
1537 AutoWriteLock alock(this);
1538
1539 /* if we're already completed, take a shortcut */
1540 if (!mCompleted)
1541 {
1542 RTTIMESPEC time;
1543 RTTimeNow (&time);
1544
1545 HRESULT rc = S_OK;
1546 bool forever = aTimeout < 0;
1547 int64_t timeLeft = aTimeout;
1548 int64_t lastTime = RTTimeSpecGetMilli (&time);
1549
1550 while (!mCompleted && (forever || timeLeft > 0))
1551 {
1552 alock.leave();
1553 rc = mProgresses.back()->WaitForCompletion (
1554 forever ? -1 : (LONG) timeLeft);
1555 alock.enter();
1556
1557 if (SUCCEEDED(rc))
1558 rc = checkProgress();
1559
1560 CheckComRCBreakRC (rc);
1561
1562 if (!forever)
1563 {
1564 RTTimeNow (&time);
1565 timeLeft -= RTTimeSpecGetMilli (&time) - lastTime;
1566 lastTime = RTTimeSpecGetMilli (&time);
1567 }
1568 }
1569
1570 CheckComRCReturnRC(rc);
1571 }
1572
1573 LogFlowThisFuncLeave();
1574
1575 return S_OK;
1576}
1577
1578/**
1579 * @note XPCOM: when this method is called not on the main XPCOM thread, it
1580 * simply blocks the thread until mCompletedSem is signalled. If the
1581 * thread has its own event queue (hmm, what for?) that it must run, then
1582 * calling this method will definitely freeze event processing.
1583 */
1584STDMETHODIMP CombinedProgress::WaitForOperationCompletion (ULONG aOperation, LONG aTimeout)
1585{
1586 LogFlowThisFuncEnter();
1587 LogFlowThisFunc(("aOperation=%d, aTimeout=%d\n", aOperation, aTimeout));
1588
1589 AutoCaller autoCaller(this);
1590 CheckComRCReturnRC(autoCaller.rc());
1591
1592 AutoWriteLock alock(this);
1593
1594 if (aOperation >= m_cOperations)
1595 return setError (E_FAIL,
1596 tr ("Operation number must be in range [0, %d]"), m_ulCurrentOperation - 1);
1597
1598 /* if we're already completed or if the given operation is already done,
1599 * then take a shortcut */
1600 if (!mCompleted && aOperation >= m_ulCurrentOperation)
1601 {
1602 HRESULT rc = S_OK;
1603
1604 /* find the right progress object to wait for */
1605 size_t progress = mProgress;
1606 ULONG operation = 0, completedOps = mCompletedOperations;
1607 do
1608 {
1609 ULONG opCount = 0;
1610 rc = mProgresses [progress]->COMGETTER(OperationCount) (&opCount);
1611 if (FAILED (rc))
1612 return rc;
1613
1614 if (completedOps + opCount > aOperation)
1615 {
1616 /* found the right progress object */
1617 operation = aOperation - completedOps;
1618 break;
1619 }
1620
1621 completedOps += opCount;
1622 progress ++;
1623 ComAssertRet (progress < mProgresses.size(), E_FAIL);
1624 }
1625 while (1);
1626
1627 LogFlowThisFunc(("will wait for mProgresses [%d] (%d)\n",
1628 progress, operation));
1629
1630 RTTIMESPEC time;
1631 RTTimeNow (&time);
1632
1633 bool forever = aTimeout < 0;
1634 int64_t timeLeft = aTimeout;
1635 int64_t lastTime = RTTimeSpecGetMilli (&time);
1636
1637 while (!mCompleted && aOperation >= m_ulCurrentOperation &&
1638 (forever || timeLeft > 0))
1639 {
1640 alock.leave();
1641 /* wait for the appropriate progress operation completion */
1642 rc = mProgresses [progress]-> WaitForOperationCompletion (
1643 operation, forever ? -1 : (LONG) timeLeft);
1644 alock.enter();
1645
1646 if (SUCCEEDED(rc))
1647 rc = checkProgress();
1648
1649 CheckComRCBreakRC (rc);
1650
1651 if (!forever)
1652 {
1653 RTTimeNow (&time);
1654 timeLeft -= RTTimeSpecGetMilli (&time) - lastTime;
1655 lastTime = RTTimeSpecGetMilli (&time);
1656 }
1657 }
1658
1659 CheckComRCReturnRC(rc);
1660 }
1661
1662 LogFlowThisFuncLeave();
1663
1664 return S_OK;
1665}
1666
1667STDMETHODIMP CombinedProgress::Cancel()
1668{
1669 AutoCaller autoCaller(this);
1670 CheckComRCReturnRC(autoCaller.rc());
1671
1672 AutoWriteLock alock(this);
1673
1674 if (!mCancelable)
1675 return setError (E_FAIL, tr ("Operation cannot be canceled"));
1676
1677 if (!mCanceled)
1678 {
1679 mCanceled = TRUE;
1680/** @todo Teleportation: Shouldn't this be propagated to mProgresses? If
1681 * powerUp creates passes a combined progress object to the client, I
1682 * won't get called back since I'm only getting the powerupProgress ...
1683 * Or what? */
1684 if (m_pfnCancelCallback)
1685 m_pfnCancelCallback(m_pvCancelUserArg);
1686
1687 }
1688 return S_OK;
1689}
1690
1691// private methods
1692////////////////////////////////////////////////////////////////////////////////
1693
1694/**
1695 * Fetches the properties of the current progress object and, if it is
1696 * successfully completed, advances to the next uncompleted or unsuccessfully
1697 * completed object in the vector of combined progress objects.
1698 *
1699 * @note Must be called from under this object's write lock!
1700 */
1701HRESULT CombinedProgress::checkProgress()
1702{
1703 /* do nothing if we're already marked ourselves as completed */
1704 if (mCompleted)
1705 return S_OK;
1706
1707 AssertReturn(mProgress < mProgresses.size(), E_FAIL);
1708
1709 ComPtr<IProgress> progress = mProgresses [mProgress];
1710 ComAssertRet (!progress.isNull(), E_FAIL);
1711
1712 HRESULT rc = S_OK;
1713 BOOL completed = FALSE;
1714
1715 do
1716 {
1717 rc = progress->COMGETTER(Completed) (&completed);
1718 if (FAILED (rc))
1719 return rc;
1720
1721 if (completed)
1722 {
1723 rc = progress->COMGETTER(Canceled) (&mCanceled);
1724 if (FAILED (rc))
1725 return rc;
1726
1727 LONG iRc;
1728 rc = progress->COMGETTER(ResultCode) (&iRc);
1729 if (FAILED (rc))
1730 return rc;
1731 mResultCode = iRc;
1732
1733 if (FAILED (mResultCode))
1734 {
1735 rc = progress->COMGETTER(ErrorInfo) (mErrorInfo.asOutParam());
1736 if (FAILED (rc))
1737 return rc;
1738 }
1739
1740 if (FAILED (mResultCode) || mCanceled)
1741 {
1742 mCompleted = TRUE;
1743 }
1744 else
1745 {
1746 ULONG opCount = 0;
1747 rc = progress->COMGETTER(OperationCount) (&opCount);
1748 if (FAILED (rc))
1749 return rc;
1750
1751 mCompletedOperations += opCount;
1752 mProgress ++;
1753
1754 if (mProgress < mProgresses.size())
1755 progress = mProgresses [mProgress];
1756 else
1757 mCompleted = TRUE;
1758 }
1759 }
1760 }
1761 while (completed && !mCompleted);
1762
1763 rc = progress->COMGETTER(OperationPercent) (&m_ulOperationPercent);
1764 if (SUCCEEDED(rc))
1765 {
1766 ULONG operation = 0;
1767 rc = progress->COMGETTER(Operation) (&operation);
1768 if (SUCCEEDED(rc) && mCompletedOperations + operation > m_ulCurrentOperation)
1769 {
1770 m_ulCurrentOperation = mCompletedOperations + operation;
1771 rc = progress->COMGETTER(OperationDescription) (
1772 m_bstrOperationDescription.asOutParam());
1773 }
1774 }
1775
1776 return rc;
1777}
1778/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette