VirtualBox

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

Last change on this file since 29960 was 29924, checked in by vboxsync, 14 years ago

Progress.cpp: Don't assert in SetNextOperation if the object is canceled already since it is an external factor that we cannot control.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 53.3 KB
Line 
1/* $Id: ProgressImpl.cpp 29924 2010-05-31 18:30:29Z 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 int vrc = VINF_SUCCESS;
838 bool fForever = aTimeout < 0;
839 int64_t timeLeft = aTimeout;
840 int64_t lastTime = RTTimeMilliTS();
841
842 while (!mCompleted && (fForever || timeLeft > 0))
843 {
844 mWaitersCount++;
845 alock.leave();
846 vrc = RTSemEventMultiWait(mCompletedSem,
847 fForever ? RT_INDEFINITE_WAIT : (RTMSINTERVAL)timeLeft);
848 alock.enter();
849 mWaitersCount--;
850
851 /* the last waiter resets the semaphore */
852 if (mWaitersCount == 0)
853 RTSemEventMultiReset(mCompletedSem);
854
855 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
856 break;
857
858 if (!fForever)
859 {
860 int64_t now = RTTimeMilliTS();
861 timeLeft -= now - lastTime;
862 lastTime = now;
863 }
864 }
865
866 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
867 return setError(VBOX_E_IPRT_ERROR,
868 tr("Failed to wait for the task completion (%Rrc)"),
869 vrc);
870 }
871
872 LogFlowThisFuncLeave();
873
874 return S_OK;
875}
876
877/**
878 * @note XPCOM: when this method is not called on the main XPCOM thread, it
879 * simply blocks the thread until mCompletedSem is signalled. If the
880 * thread has its own event queue (hmm, what for?) that it must run, then
881 * calling this method will definitely freeze event processing.
882 */
883STDMETHODIMP Progress::WaitForOperationCompletion(ULONG aOperation, LONG aTimeout)
884{
885 LogFlowThisFuncEnter();
886 LogFlowThisFunc(("aOperation=%d, aTimeout=%d\n", aOperation, aTimeout));
887
888 AutoCaller autoCaller(this);
889 if (FAILED(autoCaller.rc())) return autoCaller.rc();
890
891 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
892
893 CheckComArgExpr(aOperation, aOperation < m_cOperations);
894
895 /* if we're already completed or if the given operation is already done,
896 * then take a shortcut */
897 if ( !mCompleted
898 && aOperation >= m_ulCurrentOperation)
899 {
900 int vrc = VINF_SUCCESS;
901 bool fForever = aTimeout < 0;
902 int64_t timeLeft = aTimeout;
903 int64_t lastTime = RTTimeMilliTS();
904
905 while ( !mCompleted && aOperation >= m_ulCurrentOperation
906 && (fForever || timeLeft > 0))
907 {
908 mWaitersCount ++;
909 alock.leave();
910 vrc = RTSemEventMultiWait(mCompletedSem,
911 fForever ? RT_INDEFINITE_WAIT : (unsigned) timeLeft);
912 alock.enter();
913 mWaitersCount--;
914
915 /* the last waiter resets the semaphore */
916 if (mWaitersCount == 0)
917 RTSemEventMultiReset(mCompletedSem);
918
919 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
920 break;
921
922 if (!fForever)
923 {
924 int64_t now = RTTimeMilliTS();
925 timeLeft -= now - lastTime;
926 lastTime = now;
927 }
928 }
929
930 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
931 return setError(E_FAIL,
932 tr("Failed to wait for the operation completion (%Rrc)"),
933 vrc);
934 }
935
936 LogFlowThisFuncLeave();
937
938 return S_OK;
939}
940
941STDMETHODIMP Progress::Cancel()
942{
943 AutoCaller autoCaller(this);
944 if (FAILED(autoCaller.rc())) return autoCaller.rc();
945
946 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
947
948 if (!mCancelable)
949 return setError(VBOX_E_INVALID_OBJECT_STATE,
950 tr("Operation cannot be canceled"));
951
952 if (!mCanceled)
953 {
954 LogThisFunc(("Canceling\n"));
955 mCanceled = TRUE;
956 if (m_pfnCancelCallback)
957 m_pfnCancelCallback(m_pvCancelUserArg);
958
959 }
960 else
961 LogThisFunc(("Already canceled\n"));
962
963 return S_OK;
964}
965
966/**
967 * Updates the percentage value of the current operation.
968 *
969 * @param aPercent New percentage value of the operation in progress
970 * (in range [0, 100]).
971 */
972STDMETHODIMP Progress::SetCurrentOperationProgress(ULONG aPercent)
973{
974 AutoCaller autoCaller(this);
975 AssertComRCReturnRC(autoCaller.rc());
976
977 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
978
979 AssertReturn(aPercent <= 100, E_INVALIDARG);
980
981 checkForAutomaticTimeout();
982 if (mCancelable && mCanceled)
983 {
984 Assert(!mCompleted);
985 return E_FAIL;
986 }
987 AssertReturn(!mCompleted && !mCanceled, E_FAIL);
988
989 m_ulOperationPercent = aPercent;
990
991 return S_OK;
992}
993
994/**
995 * Signals that the current operation is successfully completed and advances to
996 * the next operation. The operation percentage is reset to 0.
997 *
998 * @param aOperationDescription Description of the next operation.
999 *
1000 * @note The current operation must not be the last one.
1001 */
1002STDMETHODIMP Progress::SetNextOperation(IN_BSTR bstrNextOperationDescription, ULONG ulNextOperationsWeight)
1003{
1004 AssertReturn(bstrNextOperationDescription, E_INVALIDARG);
1005
1006 AutoCaller autoCaller(this);
1007 AssertComRCReturnRC(autoCaller.rc());
1008
1009 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1010
1011 if (mCanceled)
1012 return E_FAIL;
1013 AssertReturn(!mCompleted, E_FAIL);
1014 AssertReturn(m_ulCurrentOperation + 1 < m_cOperations, E_FAIL);
1015
1016 ++m_ulCurrentOperation;
1017 m_ulOperationsCompletedWeight += m_ulCurrentOperationWeight;
1018
1019 m_bstrOperationDescription = bstrNextOperationDescription;
1020 m_ulCurrentOperationWeight = ulNextOperationsWeight;
1021 m_ulOperationPercent = 0;
1022
1023 Log(("Progress::setNextOperation(%ls): ulNextOperationsWeight = %d; m_ulCurrentOperation is now %d, m_ulOperationsCompletedWeight is now %d\n",
1024 m_bstrOperationDescription.raw(), ulNextOperationsWeight, m_ulCurrentOperation, m_ulOperationsCompletedWeight));
1025
1026 /* wake up all waiting threads */
1027 if (mWaitersCount > 0)
1028 RTSemEventMultiSignal(mCompletedSem);
1029
1030 return S_OK;
1031}
1032
1033// public methods only for internal purposes
1034/////////////////////////////////////////////////////////////////////////////
1035
1036/**
1037 * Sets the internal result code and attempts to retrieve additional error
1038 * info from the current thread. Gets called from Progress::notifyComplete(),
1039 * but can be called again to override a previous result set with
1040 * notifyComplete().
1041 *
1042 * @param aResultCode
1043 */
1044HRESULT Progress::setResultCode(HRESULT aResultCode)
1045{
1046 AutoCaller autoCaller(this);
1047 AssertComRCReturnRC(autoCaller.rc());
1048
1049 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1050
1051 mResultCode = aResultCode;
1052
1053 HRESULT rc = S_OK;
1054
1055 if (FAILED(aResultCode))
1056 {
1057 /* try to import error info from the current thread */
1058
1059#if !defined (VBOX_WITH_XPCOM)
1060
1061 ComPtr<IErrorInfo> err;
1062 rc = ::GetErrorInfo(0, err.asOutParam());
1063 if (rc == S_OK && err)
1064 {
1065 rc = err.queryInterfaceTo(mErrorInfo.asOutParam());
1066 if (SUCCEEDED(rc) && !mErrorInfo)
1067 rc = E_FAIL;
1068 }
1069
1070#else /* !defined (VBOX_WITH_XPCOM) */
1071
1072 nsCOMPtr<nsIExceptionService> es;
1073 es = do_GetService(NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
1074 if (NS_SUCCEEDED(rc))
1075 {
1076 nsCOMPtr <nsIExceptionManager> em;
1077 rc = es->GetCurrentExceptionManager(getter_AddRefs(em));
1078 if (NS_SUCCEEDED(rc))
1079 {
1080 ComPtr<nsIException> ex;
1081 rc = em->GetCurrentException(ex.asOutParam());
1082 if (NS_SUCCEEDED(rc) && ex)
1083 {
1084 rc = ex.queryInterfaceTo(mErrorInfo.asOutParam());
1085 if (NS_SUCCEEDED(rc) && !mErrorInfo)
1086 rc = E_FAIL;
1087 }
1088 }
1089 }
1090#endif /* !defined (VBOX_WITH_XPCOM) */
1091
1092 AssertMsg (rc == S_OK, ("Couldn't get error info (rc=%08X) while trying "
1093 "to set a failed result (%08X)!\n", rc, aResultCode));
1094 }
1095
1096 return rc;
1097}
1098
1099/**
1100 * Marks the whole task as complete and sets the result code.
1101 *
1102 * If the result code indicates a failure (|FAILED(@a aResultCode)|) then this
1103 * method will import the error info from the current thread and assign it to
1104 * the errorInfo attribute (it will return an error if no info is available in
1105 * such case).
1106 *
1107 * If the result code indicates a success (|SUCCEEDED(@a aResultCode)|) then
1108 * the current operation is set to the last.
1109 *
1110 * Note that this method may be called only once for the given Progress object.
1111 * Subsequent calls will assert.
1112 *
1113 * @param aResultCode Operation result code.
1114 */
1115HRESULT Progress::notifyComplete(HRESULT aResultCode)
1116{
1117 AutoCaller autoCaller(this);
1118 AssertComRCReturnRC(autoCaller.rc());
1119
1120 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1121
1122 AssertReturn(mCompleted == FALSE, E_FAIL);
1123
1124 if (mCanceled && SUCCEEDED(aResultCode))
1125 aResultCode = E_FAIL;
1126
1127 HRESULT rc = setResultCode(aResultCode);
1128
1129 mCompleted = TRUE;
1130
1131 if (!FAILED(aResultCode))
1132 {
1133 m_ulCurrentOperation = m_cOperations - 1; /* last operation */
1134 m_ulOperationPercent = 100;
1135 }
1136
1137#if !defined VBOX_COM_INPROC
1138 /* remove from the global collection of pending progress operations */
1139 if (mParent)
1140 mParent->removeProgress (mId);
1141#endif
1142
1143 /* wake up all waiting threads */
1144 if (mWaitersCount > 0)
1145 RTSemEventMultiSignal (mCompletedSem);
1146
1147 return rc;
1148}
1149
1150/**
1151 * Wrapper around Progress:notifyCompleteV.
1152 */
1153HRESULT Progress::notifyComplete(HRESULT aResultCode,
1154 const GUID &aIID,
1155 const Bstr &aComponent,
1156 const char *aText,
1157 ...)
1158{
1159 va_list va;
1160 va_start(va, aText);
1161 HRESULT hrc = notifyCompleteV(aResultCode, aIID, aComponent, aText, va);
1162 va_end(va);
1163 return hrc;
1164}
1165
1166/**
1167 * Marks the operation as complete and attaches full error info.
1168 *
1169 * See com::SupportErrorInfoImpl::setError(HRESULT, const GUID &, const wchar_t
1170 * *, const char *, ...) for more info.
1171 *
1172 * @param aResultCode Operation result (error) code, must not be S_OK.
1173 * @param aIID IID of the interface that defines the error.
1174 * @param aComponent Name of the component that generates the error.
1175 * @param aText Error message (must not be null), an RTStrPrintf-like
1176 * format string in UTF-8 encoding.
1177 * @param va List of arguments for the format string.
1178 */
1179HRESULT Progress::notifyCompleteV(HRESULT aResultCode,
1180 const GUID &aIID,
1181 const Bstr &aComponent,
1182 const char *aText,
1183 va_list va)
1184{
1185 Utf8Str text = Utf8StrFmtVA(aText, va);
1186
1187 AutoCaller autoCaller(this);
1188 AssertComRCReturnRC(autoCaller.rc());
1189
1190 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1191
1192 AssertReturn(mCompleted == FALSE, E_FAIL);
1193
1194 if (mCanceled && SUCCEEDED(aResultCode))
1195 aResultCode = E_FAIL;
1196
1197 mCompleted = TRUE;
1198 mResultCode = aResultCode;
1199
1200 AssertReturn(FAILED(aResultCode), E_FAIL);
1201
1202 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
1203 HRESULT rc = errorInfo.createObject();
1204 AssertComRC (rc);
1205 if (SUCCEEDED(rc))
1206 {
1207 errorInfo->init(aResultCode, aIID, aComponent, Bstr(text));
1208 errorInfo.queryInterfaceTo(mErrorInfo.asOutParam());
1209 }
1210
1211#if !defined VBOX_COM_INPROC
1212 /* remove from the global collection of pending progress operations */
1213 if (mParent)
1214 mParent->removeProgress (mId);
1215#endif
1216
1217 /* wake up all waiting threads */
1218 if (mWaitersCount > 0)
1219 RTSemEventMultiSignal(mCompletedSem);
1220
1221 return rc;
1222}
1223
1224/**
1225 * Notify the progress object that we're almost at the point of no return.
1226 *
1227 * This atomically checks for and disables cancelation. Calls to
1228 * IProgress::Cancel() made after a successfull call to this method will fail
1229 * and the user can be told. While this isn't entirely clean behavior, it
1230 * prevents issues with an irreversible actually operation succeeding while the
1231 * user belive it was rolled back.
1232 *
1233 * @returns Success indicator.
1234 * @retval true on success.
1235 * @retval false if the progress object has already been canceled or is in an
1236 * invalid state
1237 */
1238bool Progress::notifyPointOfNoReturn(void)
1239{
1240 AutoCaller autoCaller(this);
1241 AssertComRCReturn(autoCaller.rc(), false);
1242
1243 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1244
1245 if (mCanceled)
1246 {
1247 LogThisFunc(("returns false\n"));
1248 return false;
1249 }
1250
1251 mCancelable = FALSE;
1252 LogThisFunc(("returns true\n"));
1253 return true;
1254}
1255
1256////////////////////////////////////////////////////////////////////////////////
1257// CombinedProgress class
1258////////////////////////////////////////////////////////////////////////////////
1259
1260HRESULT CombinedProgress::FinalConstruct()
1261{
1262 HRESULT rc = ProgressBase::FinalConstruct();
1263 if (FAILED(rc)) return rc;
1264
1265 mProgress = 0;
1266 mCompletedOperations = 0;
1267
1268 return S_OK;
1269}
1270
1271void CombinedProgress::FinalRelease()
1272{
1273 uninit();
1274}
1275
1276// public initializer/uninitializer for internal purposes only
1277////////////////////////////////////////////////////////////////////////////////
1278
1279/**
1280 * Initializes this object based on individual combined progresses.
1281 * Must be called only from #init()!
1282 *
1283 * @param aAutoInitSpan AutoInitSpan object instantiated by a subclass.
1284 * @param aParent See ProgressBase::init().
1285 * @param aInitiator See ProgressBase::init().
1286 * @param aDescription See ProgressBase::init().
1287 * @param aId See ProgressBase::init().
1288 */
1289HRESULT CombinedProgress::protectedInit (AutoInitSpan &aAutoInitSpan,
1290#if !defined (VBOX_COM_INPROC)
1291 VirtualBox *aParent,
1292#endif
1293 IUnknown *aInitiator,
1294 CBSTR aDescription, OUT_GUID aId)
1295{
1296 LogFlowThisFunc(("aDescription={%ls} mProgresses.size()=%d\n",
1297 aDescription, mProgresses.size()));
1298
1299 HRESULT rc = S_OK;
1300
1301 rc = ProgressBase::protectedInit (aAutoInitSpan,
1302#if !defined (VBOX_COM_INPROC)
1303 aParent,
1304#endif
1305 aInitiator, aDescription, aId);
1306 if (FAILED(rc)) return rc;
1307
1308 mProgress = 0; /* the first object */
1309 mCompletedOperations = 0;
1310
1311 mCompleted = FALSE;
1312 mCancelable = TRUE; /* until any progress returns FALSE */
1313 mCanceled = FALSE;
1314
1315 m_cOperations = 0; /* will be calculated later */
1316
1317 m_ulCurrentOperation = 0;
1318 rc = mProgresses[0]->COMGETTER(OperationDescription)(m_bstrOperationDescription.asOutParam());
1319 if (FAILED(rc)) return rc;
1320
1321 for (size_t i = 0; i < mProgresses.size(); i ++)
1322 {
1323 if (mCancelable)
1324 {
1325 BOOL cancelable = FALSE;
1326 rc = mProgresses[i]->COMGETTER(Cancelable)(&cancelable);
1327 if (FAILED(rc)) return rc;
1328
1329 if (!cancelable)
1330 mCancelable = FALSE;
1331 }
1332
1333 {
1334 ULONG opCount = 0;
1335 rc = mProgresses[i]->COMGETTER(OperationCount)(&opCount);
1336 if (FAILED(rc)) return rc;
1337
1338 m_cOperations += opCount;
1339 }
1340 }
1341
1342 rc = checkProgress();
1343 if (FAILED(rc)) return rc;
1344
1345 return rc;
1346}
1347
1348/**
1349 * Initializes the combined progress object given two normal progress
1350 * objects.
1351 *
1352 * @param aParent See ProgressBase::init().
1353 * @param aInitiator See ProgressBase::init().
1354 * @param aDescription See ProgressBase::init().
1355 * @param aProgress1 First normal progress object.
1356 * @param aProgress2 Second normal progress object.
1357 * @param aId See ProgressBase::init().
1358 */
1359HRESULT CombinedProgress::init(
1360#if !defined (VBOX_COM_INPROC)
1361 VirtualBox *aParent,
1362#endif
1363 IUnknown *aInitiator,
1364 CBSTR aDescription,
1365 IProgress *aProgress1,
1366 IProgress *aProgress2,
1367 OUT_GUID aId /* = NULL */)
1368{
1369 /* Enclose the state transition NotReady->InInit->Ready */
1370 AutoInitSpan autoInitSpan(this);
1371 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1372
1373 mProgresses.resize(2);
1374 mProgresses[0] = aProgress1;
1375 mProgresses[1] = aProgress2;
1376
1377 HRESULT rc = protectedInit(autoInitSpan,
1378#if !defined (VBOX_COM_INPROC)
1379 aParent,
1380#endif
1381 aInitiator,
1382 aDescription,
1383 aId);
1384
1385 /* Confirm a successful initialization when it's the case */
1386 if (SUCCEEDED(rc))
1387 autoInitSpan.setSucceeded();
1388
1389 return rc;
1390}
1391
1392/**
1393 * Uninitializes the instance and sets the ready flag to FALSE.
1394 *
1395 * Called either from FinalRelease() or by the parent when it gets destroyed.
1396 */
1397void CombinedProgress::uninit()
1398{
1399 LogFlowThisFunc(("\n"));
1400
1401 /* Enclose the state transition Ready->InUninit->NotReady */
1402 AutoUninitSpan autoUninitSpan(this);
1403 if (autoUninitSpan.uninitDone())
1404 return;
1405
1406 mProgress = 0;
1407 mProgresses.clear();
1408
1409 ProgressBase::protectedUninit (autoUninitSpan);
1410}
1411
1412// IProgress properties
1413////////////////////////////////////////////////////////////////////////////////
1414
1415STDMETHODIMP CombinedProgress::COMGETTER(Percent)(ULONG *aPercent)
1416{
1417 CheckComArgOutPointerValid(aPercent);
1418
1419 AutoCaller autoCaller(this);
1420 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1421
1422 /* checkProgress needs a write lock */
1423 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1424
1425 if (mCompleted && SUCCEEDED(mResultCode))
1426 *aPercent = 100;
1427 else
1428 {
1429 HRESULT rc = checkProgress();
1430 if (FAILED(rc)) return rc;
1431
1432 /* global percent =
1433 * (100 / m_cOperations) * mOperation +
1434 * ((100 / m_cOperations) / 100) * m_ulOperationPercent */
1435 *aPercent = (100 * m_ulCurrentOperation + m_ulOperationPercent) / m_cOperations;
1436 }
1437
1438 return S_OK;
1439}
1440
1441STDMETHODIMP CombinedProgress::COMGETTER(Completed) (BOOL *aCompleted)
1442{
1443 CheckComArgOutPointerValid(aCompleted);
1444
1445 AutoCaller autoCaller(this);
1446 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1447
1448 /* checkProgress needs a write lock */
1449 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1450
1451 HRESULT rc = checkProgress();
1452 if (FAILED(rc)) return rc;
1453
1454 return ProgressBase::COMGETTER(Completed) (aCompleted);
1455}
1456
1457STDMETHODIMP CombinedProgress::COMGETTER(Canceled) (BOOL *aCanceled)
1458{
1459 CheckComArgOutPointerValid(aCanceled);
1460
1461 AutoCaller autoCaller(this);
1462 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1463
1464 /* checkProgress needs a write lock */
1465 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1466
1467 HRESULT rc = checkProgress();
1468 if (FAILED(rc)) return rc;
1469
1470 return ProgressBase::COMGETTER(Canceled) (aCanceled);
1471}
1472
1473STDMETHODIMP CombinedProgress::COMGETTER(ResultCode) (LONG *aResultCode)
1474{
1475 CheckComArgOutPointerValid(aResultCode);
1476
1477 AutoCaller autoCaller(this);
1478 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1479
1480 /* checkProgress needs a write lock */
1481 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1482
1483 HRESULT rc = checkProgress();
1484 if (FAILED(rc)) return rc;
1485
1486 return ProgressBase::COMGETTER(ResultCode) (aResultCode);
1487}
1488
1489STDMETHODIMP CombinedProgress::COMGETTER(ErrorInfo) (IVirtualBoxErrorInfo **aErrorInfo)
1490{
1491 CheckComArgOutPointerValid(aErrorInfo);
1492
1493 AutoCaller autoCaller(this);
1494 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1495
1496 /* checkProgress needs a write lock */
1497 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1498
1499 HRESULT rc = checkProgress();
1500 if (FAILED(rc)) return rc;
1501
1502 return ProgressBase::COMGETTER(ErrorInfo) (aErrorInfo);
1503}
1504
1505STDMETHODIMP CombinedProgress::COMGETTER(Operation) (ULONG *aOperation)
1506{
1507 CheckComArgOutPointerValid(aOperation);
1508
1509 AutoCaller autoCaller(this);
1510 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1511
1512 /* checkProgress needs a write lock */
1513 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1514
1515 HRESULT rc = checkProgress();
1516 if (FAILED(rc)) return rc;
1517
1518 return ProgressBase::COMGETTER(Operation) (aOperation);
1519}
1520
1521STDMETHODIMP CombinedProgress::COMGETTER(OperationDescription) (BSTR *aOperationDescription)
1522{
1523 CheckComArgOutPointerValid(aOperationDescription);
1524
1525 AutoCaller autoCaller(this);
1526 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1527
1528 /* checkProgress needs a write lock */
1529 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1530
1531 HRESULT rc = checkProgress();
1532 if (FAILED(rc)) return rc;
1533
1534 return ProgressBase::COMGETTER(OperationDescription) (aOperationDescription);
1535}
1536
1537STDMETHODIMP CombinedProgress::COMGETTER(OperationPercent)(ULONG *aOperationPercent)
1538{
1539 CheckComArgOutPointerValid(aOperationPercent);
1540
1541 AutoCaller autoCaller(this);
1542 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1543
1544 /* checkProgress needs a write lock */
1545 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1546
1547 HRESULT rc = checkProgress();
1548 if (FAILED(rc)) return rc;
1549
1550 return ProgressBase::COMGETTER(OperationPercent) (aOperationPercent);
1551}
1552
1553STDMETHODIMP CombinedProgress::COMSETTER(Timeout)(ULONG aTimeout)
1554{
1555 NOREF(aTimeout);
1556 AssertFailed();
1557 return E_NOTIMPL;
1558}
1559
1560STDMETHODIMP CombinedProgress::COMGETTER(Timeout)(ULONG *aTimeout)
1561{
1562 CheckComArgOutPointerValid(aTimeout);
1563
1564 AssertFailed();
1565 return E_NOTIMPL;
1566}
1567
1568// IProgress methods
1569/////////////////////////////////////////////////////////////////////////////
1570
1571/**
1572 * @note XPCOM: when this method is called not on the main XPCOM thread, it
1573 * simply blocks the thread until mCompletedSem is signalled. If the
1574 * thread has its own event queue (hmm, what for?) that it must run, then
1575 * calling this method will definitely freeze event processing.
1576 */
1577STDMETHODIMP CombinedProgress::WaitForCompletion (LONG aTimeout)
1578{
1579 LogFlowThisFuncEnter();
1580 LogFlowThisFunc(("aTtimeout=%d\n", aTimeout));
1581
1582 AutoCaller autoCaller(this);
1583 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1584
1585 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1586
1587 /* if we're already completed, take a shortcut */
1588 if (!mCompleted)
1589 {
1590 HRESULT rc = S_OK;
1591 bool forever = aTimeout < 0;
1592 int64_t timeLeft = aTimeout;
1593 int64_t lastTime = RTTimeMilliTS();
1594
1595 while (!mCompleted && (forever || timeLeft > 0))
1596 {
1597 alock.leave();
1598 rc = mProgresses.back()->WaitForCompletion(forever ? -1 : (LONG) timeLeft);
1599 alock.enter();
1600
1601 if (SUCCEEDED(rc))
1602 rc = checkProgress();
1603
1604 if (FAILED(rc)) break;
1605
1606 if (!forever)
1607 {
1608 int64_t now = RTTimeMilliTS();
1609 timeLeft -= now - lastTime;
1610 lastTime = now;
1611 }
1612 }
1613
1614 if (FAILED(rc)) return rc;
1615 }
1616
1617 LogFlowThisFuncLeave();
1618
1619 return S_OK;
1620}
1621
1622/**
1623 * @note XPCOM: when this method is called not on the main XPCOM thread, it
1624 * simply blocks the thread until mCompletedSem is signalled. If the
1625 * thread has its own event queue (hmm, what for?) that it must run, then
1626 * calling this method will definitely freeze event processing.
1627 */
1628STDMETHODIMP CombinedProgress::WaitForOperationCompletion (ULONG aOperation, LONG aTimeout)
1629{
1630 LogFlowThisFuncEnter();
1631 LogFlowThisFunc(("aOperation=%d, aTimeout=%d\n", aOperation, aTimeout));
1632
1633 AutoCaller autoCaller(this);
1634 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1635
1636 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1637
1638 if (aOperation >= m_cOperations)
1639 return setError(E_FAIL,
1640 tr("Operation number must be in range [0, %d]"), m_ulCurrentOperation - 1);
1641
1642 /* if we're already completed or if the given operation is already done,
1643 * then take a shortcut */
1644 if (!mCompleted && aOperation >= m_ulCurrentOperation)
1645 {
1646 HRESULT rc = S_OK;
1647
1648 /* find the right progress object to wait for */
1649 size_t progress = mProgress;
1650 ULONG operation = 0, completedOps = mCompletedOperations;
1651 do
1652 {
1653 ULONG opCount = 0;
1654 rc = mProgresses[progress]->COMGETTER(OperationCount)(&opCount);
1655 if (FAILED(rc))
1656 return rc;
1657
1658 if (completedOps + opCount > aOperation)
1659 {
1660 /* found the right progress object */
1661 operation = aOperation - completedOps;
1662 break;
1663 }
1664
1665 completedOps += opCount;
1666 progress ++;
1667 ComAssertRet(progress < mProgresses.size(), E_FAIL);
1668 }
1669 while (1);
1670
1671 LogFlowThisFunc(("will wait for mProgresses [%d] (%d)\n",
1672 progress, operation));
1673
1674 bool forever = aTimeout < 0;
1675 int64_t timeLeft = aTimeout;
1676 int64_t lastTime = RTTimeMilliTS();
1677
1678 while (!mCompleted && aOperation >= m_ulCurrentOperation &&
1679 (forever || timeLeft > 0))
1680 {
1681 alock.leave();
1682 /* wait for the appropriate progress operation completion */
1683 rc = mProgresses[progress]-> WaitForOperationCompletion(operation,
1684 forever ? -1 : (LONG) timeLeft);
1685 alock.enter();
1686
1687 if (SUCCEEDED(rc))
1688 rc = checkProgress();
1689
1690 if (FAILED(rc)) break;
1691
1692 if (!forever)
1693 {
1694 int64_t now = RTTimeMilliTS();
1695 timeLeft -= now - lastTime;
1696 lastTime = now;
1697 }
1698 }
1699
1700 if (FAILED(rc)) return rc;
1701 }
1702
1703 LogFlowThisFuncLeave();
1704
1705 return S_OK;
1706}
1707
1708STDMETHODIMP CombinedProgress::Cancel()
1709{
1710 AutoCaller autoCaller(this);
1711 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1712
1713 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1714
1715 if (!mCancelable)
1716 return setError(E_FAIL, tr("Operation cannot be canceled"));
1717
1718 if (!mCanceled)
1719 {
1720 LogThisFunc(("Canceling\n"));
1721 mCanceled = TRUE;
1722/** @todo Teleportation: Shouldn't this be propagated to mProgresses? If
1723 * powerUp creates passes a combined progress object to the client, I
1724 * won't get called back since I'm only getting the powerupProgress ...
1725 * Or what? */
1726 if (m_pfnCancelCallback)
1727 m_pfnCancelCallback(m_pvCancelUserArg);
1728
1729 }
1730 else
1731 LogThisFunc(("Already canceled\n"));
1732
1733 return S_OK;
1734}
1735
1736// private methods
1737////////////////////////////////////////////////////////////////////////////////
1738
1739/**
1740 * Fetches the properties of the current progress object and, if it is
1741 * successfully completed, advances to the next uncompleted or unsuccessfully
1742 * completed object in the vector of combined progress objects.
1743 *
1744 * @note Must be called from under this object's write lock!
1745 */
1746HRESULT CombinedProgress::checkProgress()
1747{
1748 /* do nothing if we're already marked ourselves as completed */
1749 if (mCompleted)
1750 return S_OK;
1751
1752 AssertReturn(mProgress < mProgresses.size(), E_FAIL);
1753
1754 ComPtr<IProgress> progress = mProgresses[mProgress];
1755 ComAssertRet(!progress.isNull(), E_FAIL);
1756
1757 HRESULT rc = S_OK;
1758 BOOL fCompleted = FALSE;
1759
1760 do
1761 {
1762 rc = progress->COMGETTER(Completed)(&fCompleted);
1763 if (FAILED(rc))
1764 return rc;
1765
1766 if (fCompleted)
1767 {
1768 rc = progress->COMGETTER(Canceled)(&mCanceled);
1769 if (FAILED(rc))
1770 return rc;
1771
1772 LONG iRc;
1773 rc = progress->COMGETTER(ResultCode)(&iRc);
1774 if (FAILED(rc))
1775 return rc;
1776 mResultCode = iRc;
1777
1778 if (FAILED(mResultCode))
1779 {
1780 rc = progress->COMGETTER(ErrorInfo) (mErrorInfo.asOutParam());
1781 if (FAILED(rc))
1782 return rc;
1783 }
1784
1785 if (FAILED(mResultCode) || mCanceled)
1786 {
1787 mCompleted = TRUE;
1788 }
1789 else
1790 {
1791 ULONG opCount = 0;
1792 rc = progress->COMGETTER(OperationCount) (&opCount);
1793 if (FAILED(rc))
1794 return rc;
1795
1796 mCompletedOperations += opCount;
1797 mProgress ++;
1798
1799 if (mProgress < mProgresses.size())
1800 progress = mProgresses[mProgress];
1801 else
1802 mCompleted = TRUE;
1803 }
1804 }
1805 }
1806 while (fCompleted && !mCompleted);
1807
1808 rc = progress->COMGETTER(OperationPercent) (&m_ulOperationPercent);
1809 if (SUCCEEDED(rc))
1810 {
1811 ULONG operation = 0;
1812 rc = progress->COMGETTER(Operation) (&operation);
1813 if (SUCCEEDED(rc) && mCompletedOperations + operation > m_ulCurrentOperation)
1814 {
1815 m_ulCurrentOperation = mCompletedOperations + operation;
1816 rc = progress->COMGETTER(OperationDescription) (
1817 m_bstrOperationDescription.asOutParam());
1818 }
1819 }
1820
1821 return rc;
1822}
1823/* 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