VirtualBox

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

Last change on this file since 29900 was 29881, checked in by vboxsync, 15 years ago

ProgressImpl.cpp: Log cancelation.

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