VirtualBox

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

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

Main: lock validator, first batch: implement per-thread stack to trace locking (disabled by default, use VBOX_WITH_LOCK_VALIDATOR, but that WILL FAIL presently)

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

© 2023 Oracle
ContactPrivacy policyTerms of Use