VirtualBox

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

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

Main: missing Progress changes.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 53.5 KB
Line 
1/* $Id: ProgressImpl.cpp 29863 2010-05-28 13:33:59Z 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 mCanceled = TRUE;
961 if (m_pfnCancelCallback)
962 m_pfnCancelCallback(m_pvCancelUserArg);
963
964 }
965 return S_OK;
966}
967
968/**
969 * Updates the percentage value of the current operation.
970 *
971 * @param aPercent New percentage value of the operation in progress
972 * (in range [0, 100]).
973 */
974STDMETHODIMP Progress::SetCurrentOperationProgress(ULONG aPercent)
975{
976 AutoCaller autoCaller(this);
977 AssertComRCReturnRC(autoCaller.rc());
978
979 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
980
981 AssertReturn(aPercent <= 100, E_INVALIDARG);
982
983 checkForAutomaticTimeout();
984 if (mCancelable && mCanceled)
985 {
986 Assert(!mCompleted);
987 return E_FAIL;
988 }
989 AssertReturn(!mCompleted && !mCanceled, E_FAIL);
990
991 m_ulOperationPercent = aPercent;
992
993 return S_OK;
994}
995
996/**
997 * Signals that the current operation is successfully completed and advances to
998 * the next operation. The operation percentage is reset to 0.
999 *
1000 * @param aOperationDescription Description of the next operation.
1001 *
1002 * @note The current operation must not be the last one.
1003 */
1004STDMETHODIMP Progress::SetNextOperation(IN_BSTR bstrNextOperationDescription, ULONG ulNextOperationsWeight)
1005{
1006 AssertReturn(bstrNextOperationDescription, E_INVALIDARG);
1007
1008 AutoCaller autoCaller(this);
1009 AssertComRCReturnRC(autoCaller.rc());
1010
1011 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1012
1013 AssertReturn(!mCompleted && !mCanceled, 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 return false;
1247
1248 mCancelable = FALSE;
1249 return true;
1250}
1251
1252////////////////////////////////////////////////////////////////////////////////
1253// CombinedProgress class
1254////////////////////////////////////////////////////////////////////////////////
1255
1256HRESULT CombinedProgress::FinalConstruct()
1257{
1258 HRESULT rc = ProgressBase::FinalConstruct();
1259 if (FAILED(rc)) return rc;
1260
1261 mProgress = 0;
1262 mCompletedOperations = 0;
1263
1264 return S_OK;
1265}
1266
1267void CombinedProgress::FinalRelease()
1268{
1269 uninit();
1270}
1271
1272// public initializer/uninitializer for internal purposes only
1273////////////////////////////////////////////////////////////////////////////////
1274
1275/**
1276 * Initializes this object based on individual combined progresses.
1277 * Must be called only from #init()!
1278 *
1279 * @param aAutoInitSpan AutoInitSpan object instantiated by a subclass.
1280 * @param aParent See ProgressBase::init().
1281 * @param aInitiator See ProgressBase::init().
1282 * @param aDescription See ProgressBase::init().
1283 * @param aId See ProgressBase::init().
1284 */
1285HRESULT CombinedProgress::protectedInit (AutoInitSpan &aAutoInitSpan,
1286#if !defined (VBOX_COM_INPROC)
1287 VirtualBox *aParent,
1288#endif
1289 IUnknown *aInitiator,
1290 CBSTR aDescription, OUT_GUID aId)
1291{
1292 LogFlowThisFunc(("aDescription={%ls} mProgresses.size()=%d\n",
1293 aDescription, mProgresses.size()));
1294
1295 HRESULT rc = S_OK;
1296
1297 rc = ProgressBase::protectedInit (aAutoInitSpan,
1298#if !defined (VBOX_COM_INPROC)
1299 aParent,
1300#endif
1301 aInitiator, aDescription, aId);
1302 if (FAILED(rc)) return rc;
1303
1304 mProgress = 0; /* the first object */
1305 mCompletedOperations = 0;
1306
1307 mCompleted = FALSE;
1308 mCancelable = TRUE; /* until any progress returns FALSE */
1309 mCanceled = FALSE;
1310
1311 m_cOperations = 0; /* will be calculated later */
1312
1313 m_ulCurrentOperation = 0;
1314 rc = mProgresses[0]->COMGETTER(OperationDescription)(m_bstrOperationDescription.asOutParam());
1315 if (FAILED(rc)) return rc;
1316
1317 for (size_t i = 0; i < mProgresses.size(); i ++)
1318 {
1319 if (mCancelable)
1320 {
1321 BOOL cancelable = FALSE;
1322 rc = mProgresses[i]->COMGETTER(Cancelable)(&cancelable);
1323 if (FAILED(rc)) return rc;
1324
1325 if (!cancelable)
1326 mCancelable = FALSE;
1327 }
1328
1329 {
1330 ULONG opCount = 0;
1331 rc = mProgresses[i]->COMGETTER(OperationCount)(&opCount);
1332 if (FAILED(rc)) return rc;
1333
1334 m_cOperations += opCount;
1335 }
1336 }
1337
1338 rc = checkProgress();
1339 if (FAILED(rc)) return rc;
1340
1341 return rc;
1342}
1343
1344/**
1345 * Initializes the combined progress object given two normal progress
1346 * objects.
1347 *
1348 * @param aParent See ProgressBase::init().
1349 * @param aInitiator See ProgressBase::init().
1350 * @param aDescription See ProgressBase::init().
1351 * @param aProgress1 First normal progress object.
1352 * @param aProgress2 Second normal progress object.
1353 * @param aId See ProgressBase::init().
1354 */
1355HRESULT CombinedProgress::init(
1356#if !defined (VBOX_COM_INPROC)
1357 VirtualBox *aParent,
1358#endif
1359 IUnknown *aInitiator,
1360 CBSTR aDescription,
1361 IProgress *aProgress1,
1362 IProgress *aProgress2,
1363 OUT_GUID aId /* = NULL */)
1364{
1365 /* Enclose the state transition NotReady->InInit->Ready */
1366 AutoInitSpan autoInitSpan(this);
1367 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1368
1369 mProgresses.resize(2);
1370 mProgresses[0] = aProgress1;
1371 mProgresses[1] = aProgress2;
1372
1373 HRESULT rc = protectedInit(autoInitSpan,
1374#if !defined (VBOX_COM_INPROC)
1375 aParent,
1376#endif
1377 aInitiator,
1378 aDescription,
1379 aId);
1380
1381 /* Confirm a successful initialization when it's the case */
1382 if (SUCCEEDED(rc))
1383 autoInitSpan.setSucceeded();
1384
1385 return rc;
1386}
1387
1388/**
1389 * Uninitializes the instance and sets the ready flag to FALSE.
1390 *
1391 * Called either from FinalRelease() or by the parent when it gets destroyed.
1392 */
1393void CombinedProgress::uninit()
1394{
1395 LogFlowThisFunc(("\n"));
1396
1397 /* Enclose the state transition Ready->InUninit->NotReady */
1398 AutoUninitSpan autoUninitSpan(this);
1399 if (autoUninitSpan.uninitDone())
1400 return;
1401
1402 mProgress = 0;
1403 mProgresses.clear();
1404
1405 ProgressBase::protectedUninit (autoUninitSpan);
1406}
1407
1408// IProgress properties
1409////////////////////////////////////////////////////////////////////////////////
1410
1411STDMETHODIMP CombinedProgress::COMGETTER(Percent)(ULONG *aPercent)
1412{
1413 CheckComArgOutPointerValid(aPercent);
1414
1415 AutoCaller autoCaller(this);
1416 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1417
1418 /* checkProgress needs a write lock */
1419 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1420
1421 if (mCompleted && SUCCEEDED(mResultCode))
1422 *aPercent = 100;
1423 else
1424 {
1425 HRESULT rc = checkProgress();
1426 if (FAILED(rc)) return rc;
1427
1428 /* global percent =
1429 * (100 / m_cOperations) * mOperation +
1430 * ((100 / m_cOperations) / 100) * m_ulOperationPercent */
1431 *aPercent = (100 * m_ulCurrentOperation + m_ulOperationPercent) / m_cOperations;
1432 }
1433
1434 return S_OK;
1435}
1436
1437STDMETHODIMP CombinedProgress::COMGETTER(Completed) (BOOL *aCompleted)
1438{
1439 CheckComArgOutPointerValid(aCompleted);
1440
1441 AutoCaller autoCaller(this);
1442 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1443
1444 /* checkProgress needs a write lock */
1445 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1446
1447 HRESULT rc = checkProgress();
1448 if (FAILED(rc)) return rc;
1449
1450 return ProgressBase::COMGETTER(Completed) (aCompleted);
1451}
1452
1453STDMETHODIMP CombinedProgress::COMGETTER(Canceled) (BOOL *aCanceled)
1454{
1455 CheckComArgOutPointerValid(aCanceled);
1456
1457 AutoCaller autoCaller(this);
1458 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1459
1460 /* checkProgress needs a write lock */
1461 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1462
1463 HRESULT rc = checkProgress();
1464 if (FAILED(rc)) return rc;
1465
1466 return ProgressBase::COMGETTER(Canceled) (aCanceled);
1467}
1468
1469STDMETHODIMP CombinedProgress::COMGETTER(ResultCode) (LONG *aResultCode)
1470{
1471 CheckComArgOutPointerValid(aResultCode);
1472
1473 AutoCaller autoCaller(this);
1474 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1475
1476 /* checkProgress needs a write lock */
1477 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1478
1479 HRESULT rc = checkProgress();
1480 if (FAILED(rc)) return rc;
1481
1482 return ProgressBase::COMGETTER(ResultCode) (aResultCode);
1483}
1484
1485STDMETHODIMP CombinedProgress::COMGETTER(ErrorInfo) (IVirtualBoxErrorInfo **aErrorInfo)
1486{
1487 CheckComArgOutPointerValid(aErrorInfo);
1488
1489 AutoCaller autoCaller(this);
1490 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1491
1492 /* checkProgress needs a write lock */
1493 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1494
1495 HRESULT rc = checkProgress();
1496 if (FAILED(rc)) return rc;
1497
1498 return ProgressBase::COMGETTER(ErrorInfo) (aErrorInfo);
1499}
1500
1501STDMETHODIMP CombinedProgress::COMGETTER(Operation) (ULONG *aOperation)
1502{
1503 CheckComArgOutPointerValid(aOperation);
1504
1505 AutoCaller autoCaller(this);
1506 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1507
1508 /* checkProgress needs a write lock */
1509 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1510
1511 HRESULT rc = checkProgress();
1512 if (FAILED(rc)) return rc;
1513
1514 return ProgressBase::COMGETTER(Operation) (aOperation);
1515}
1516
1517STDMETHODIMP CombinedProgress::COMGETTER(OperationDescription) (BSTR *aOperationDescription)
1518{
1519 CheckComArgOutPointerValid(aOperationDescription);
1520
1521 AutoCaller autoCaller(this);
1522 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1523
1524 /* checkProgress needs a write lock */
1525 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1526
1527 HRESULT rc = checkProgress();
1528 if (FAILED(rc)) return rc;
1529
1530 return ProgressBase::COMGETTER(OperationDescription) (aOperationDescription);
1531}
1532
1533STDMETHODIMP CombinedProgress::COMGETTER(OperationPercent)(ULONG *aOperationPercent)
1534{
1535 CheckComArgOutPointerValid(aOperationPercent);
1536
1537 AutoCaller autoCaller(this);
1538 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1539
1540 /* checkProgress needs a write lock */
1541 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1542
1543 HRESULT rc = checkProgress();
1544 if (FAILED(rc)) return rc;
1545
1546 return ProgressBase::COMGETTER(OperationPercent) (aOperationPercent);
1547}
1548
1549STDMETHODIMP CombinedProgress::COMSETTER(Timeout)(ULONG aTimeout)
1550{
1551 NOREF(aTimeout);
1552 AssertFailed();
1553 return E_NOTIMPL;
1554}
1555
1556STDMETHODIMP CombinedProgress::COMGETTER(Timeout)(ULONG *aTimeout)
1557{
1558 CheckComArgOutPointerValid(aTimeout);
1559
1560 AssertFailed();
1561 return E_NOTIMPL;
1562}
1563
1564// IProgress methods
1565/////////////////////////////////////////////////////////////////////////////
1566
1567/**
1568 * @note XPCOM: when this method is called not on the main XPCOM thread, it
1569 * simply blocks the thread until mCompletedSem is signalled. If the
1570 * thread has its own event queue (hmm, what for?) that it must run, then
1571 * calling this method will definitely freeze event processing.
1572 */
1573STDMETHODIMP CombinedProgress::WaitForCompletion (LONG aTimeout)
1574{
1575 LogFlowThisFuncEnter();
1576 LogFlowThisFunc(("aTtimeout=%d\n", aTimeout));
1577
1578 AutoCaller autoCaller(this);
1579 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1580
1581 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1582
1583 /* if we're already completed, take a shortcut */
1584 if (!mCompleted)
1585 {
1586 RTTIMESPEC time;
1587 RTTimeNow(&time);
1588
1589 HRESULT rc = S_OK;
1590 bool forever = aTimeout < 0;
1591 int64_t timeLeft = aTimeout;
1592 int64_t lastTime = RTTimeSpecGetMilli(&time);
1593
1594 while (!mCompleted && (forever || timeLeft > 0))
1595 {
1596 alock.leave();
1597 rc = mProgresses.back()->WaitForCompletion(forever ? -1 : (LONG) timeLeft);
1598 alock.enter();
1599
1600 if (SUCCEEDED(rc))
1601 rc = checkProgress();
1602
1603 if (FAILED(rc)) break;
1604
1605 if (!forever)
1606 {
1607 RTTimeNow(&time);
1608 timeLeft -= RTTimeSpecGetMilli(&time) - lastTime;
1609 lastTime = RTTimeSpecGetMilli(&time);
1610 }
1611 }
1612
1613 if (FAILED(rc)) return rc;
1614 }
1615
1616 LogFlowThisFuncLeave();
1617
1618 return S_OK;
1619}
1620
1621/**
1622 * @note XPCOM: when this method is called not on the main XPCOM thread, it
1623 * simply blocks the thread until mCompletedSem is signalled. If the
1624 * thread has its own event queue (hmm, what for?) that it must run, then
1625 * calling this method will definitely freeze event processing.
1626 */
1627STDMETHODIMP CombinedProgress::WaitForOperationCompletion (ULONG aOperation, LONG aTimeout)
1628{
1629 LogFlowThisFuncEnter();
1630 LogFlowThisFunc(("aOperation=%d, aTimeout=%d\n", aOperation, aTimeout));
1631
1632 AutoCaller autoCaller(this);
1633 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1634
1635 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1636
1637 if (aOperation >= m_cOperations)
1638 return setError(E_FAIL,
1639 tr("Operation number must be in range [0, %d]"), m_ulCurrentOperation - 1);
1640
1641 /* if we're already completed or if the given operation is already done,
1642 * then take a shortcut */
1643 if (!mCompleted && aOperation >= m_ulCurrentOperation)
1644 {
1645 HRESULT rc = S_OK;
1646
1647 /* find the right progress object to wait for */
1648 size_t progress = mProgress;
1649 ULONG operation = 0, completedOps = mCompletedOperations;
1650 do
1651 {
1652 ULONG opCount = 0;
1653 rc = mProgresses[progress]->COMGETTER(OperationCount)(&opCount);
1654 if (FAILED(rc))
1655 return rc;
1656
1657 if (completedOps + opCount > aOperation)
1658 {
1659 /* found the right progress object */
1660 operation = aOperation - completedOps;
1661 break;
1662 }
1663
1664 completedOps += opCount;
1665 progress ++;
1666 ComAssertRet(progress < mProgresses.size(), E_FAIL);
1667 }
1668 while (1);
1669
1670 LogFlowThisFunc(("will wait for mProgresses [%d] (%d)\n",
1671 progress, operation));
1672
1673 RTTIMESPEC time;
1674 RTTimeNow (&time);
1675
1676 bool forever = aTimeout < 0;
1677 int64_t timeLeft = aTimeout;
1678 int64_t lastTime = RTTimeSpecGetMilli (&time);
1679
1680 while (!mCompleted && aOperation >= m_ulCurrentOperation &&
1681 (forever || timeLeft > 0))
1682 {
1683 alock.leave();
1684 /* wait for the appropriate progress operation completion */
1685 rc = mProgresses[progress]-> WaitForOperationCompletion(operation,
1686 forever ? -1 : (LONG) timeLeft);
1687 alock.enter();
1688
1689 if (SUCCEEDED(rc))
1690 rc = checkProgress();
1691
1692 if (FAILED(rc)) break;
1693
1694 if (!forever)
1695 {
1696 RTTimeNow(&time);
1697 timeLeft -= RTTimeSpecGetMilli(&time) - lastTime;
1698 lastTime = RTTimeSpecGetMilli(&time);
1699 }
1700 }
1701
1702 if (FAILED(rc)) return rc;
1703 }
1704
1705 LogFlowThisFuncLeave();
1706
1707 return S_OK;
1708}
1709
1710STDMETHODIMP CombinedProgress::Cancel()
1711{
1712 AutoCaller autoCaller(this);
1713 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1714
1715 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1716
1717 if (!mCancelable)
1718 return setError(E_FAIL, tr("Operation cannot be canceled"));
1719
1720 if (!mCanceled)
1721 {
1722 mCanceled = TRUE;
1723/** @todo Teleportation: Shouldn't this be propagated to mProgresses? If
1724 * powerUp creates passes a combined progress object to the client, I
1725 * won't get called back since I'm only getting the powerupProgress ...
1726 * Or what? */
1727 if (m_pfnCancelCallback)
1728 m_pfnCancelCallback(m_pvCancelUserArg);
1729
1730 }
1731 return S_OK;
1732}
1733
1734// private methods
1735////////////////////////////////////////////////////////////////////////////////
1736
1737/**
1738 * Fetches the properties of the current progress object and, if it is
1739 * successfully completed, advances to the next uncompleted or unsuccessfully
1740 * completed object in the vector of combined progress objects.
1741 *
1742 * @note Must be called from under this object's write lock!
1743 */
1744HRESULT CombinedProgress::checkProgress()
1745{
1746 /* do nothing if we're already marked ourselves as completed */
1747 if (mCompleted)
1748 return S_OK;
1749
1750 AssertReturn(mProgress < mProgresses.size(), E_FAIL);
1751
1752 ComPtr<IProgress> progress = mProgresses[mProgress];
1753 ComAssertRet(!progress.isNull(), E_FAIL);
1754
1755 HRESULT rc = S_OK;
1756 BOOL fCompleted = FALSE;
1757
1758 do
1759 {
1760 rc = progress->COMGETTER(Completed)(&fCompleted);
1761 if (FAILED(rc))
1762 return rc;
1763
1764 if (fCompleted)
1765 {
1766 rc = progress->COMGETTER(Canceled)(&mCanceled);
1767 if (FAILED(rc))
1768 return rc;
1769
1770 LONG iRc;
1771 rc = progress->COMGETTER(ResultCode)(&iRc);
1772 if (FAILED(rc))
1773 return rc;
1774 mResultCode = iRc;
1775
1776 if (FAILED(mResultCode))
1777 {
1778 rc = progress->COMGETTER(ErrorInfo) (mErrorInfo.asOutParam());
1779 if (FAILED(rc))
1780 return rc;
1781 }
1782
1783 if (FAILED(mResultCode) || mCanceled)
1784 {
1785 mCompleted = TRUE;
1786 }
1787 else
1788 {
1789 ULONG opCount = 0;
1790 rc = progress->COMGETTER(OperationCount) (&opCount);
1791 if (FAILED(rc))
1792 return rc;
1793
1794 mCompletedOperations += opCount;
1795 mProgress ++;
1796
1797 if (mProgress < mProgresses.size())
1798 progress = mProgresses[mProgress];
1799 else
1800 mCompleted = TRUE;
1801 }
1802 }
1803 }
1804 while (fCompleted && !mCompleted);
1805
1806 rc = progress->COMGETTER(OperationPercent) (&m_ulOperationPercent);
1807 if (SUCCEEDED(rc))
1808 {
1809 ULONG operation = 0;
1810 rc = progress->COMGETTER(Operation) (&operation);
1811 if (SUCCEEDED(rc) && mCompletedOperations + operation > m_ulCurrentOperation)
1812 {
1813 m_ulCurrentOperation = mCompletedOperations + operation;
1814 rc = progress->COMGETTER(OperationDescription) (
1815 m_bstrOperationDescription.asOutParam());
1816 }
1817 }
1818
1819 return rc;
1820}
1821/* 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