VirtualBox

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

Last change on this file since 26379 was 26235, checked in by vboxsync, 15 years ago

Main: coding style

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 53.0 KB
Line 
1/* $Id: ProgressImpl.cpp 26235 2010-02-04 13:55:00Z 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 "ProgressCombinedImpl.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)(m_bstrOperationDescription.asOutParam());
1289 if (FAILED(rc)) return rc;
1290
1291 for (size_t i = 0; i < mProgresses.size(); i ++)
1292 {
1293 if (mCancelable)
1294 {
1295 BOOL cancelable = FALSE;
1296 rc = mProgresses[i]->COMGETTER(Cancelable)(&cancelable);
1297 if (FAILED(rc)) return rc;
1298
1299 if (!cancelable)
1300 mCancelable = FALSE;
1301 }
1302
1303 {
1304 ULONG opCount = 0;
1305 rc = mProgresses[i]->COMGETTER(OperationCount)(&opCount);
1306 if (FAILED(rc)) return rc;
1307
1308 m_cOperations += opCount;
1309 }
1310 }
1311
1312 rc = checkProgress();
1313 if (FAILED(rc)) return rc;
1314
1315 return rc;
1316}
1317
1318/**
1319 * Initializes the combined progress object given two normal progress
1320 * objects.
1321 *
1322 * @param aParent See ProgressBase::init().
1323 * @param aInitiator See ProgressBase::init().
1324 * @param aDescription See ProgressBase::init().
1325 * @param aProgress1 First normal progress object.
1326 * @param aProgress2 Second normal progress object.
1327 * @param aId See ProgressBase::init().
1328 */
1329HRESULT CombinedProgress::init(
1330#if !defined (VBOX_COM_INPROC)
1331 VirtualBox *aParent,
1332#endif
1333 IUnknown *aInitiator,
1334 CBSTR aDescription,
1335 IProgress *aProgress1,
1336 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,
1352 aDescription,
1353 aId);
1354
1355 /* Confirm a successful initialization when it's the case */
1356 if (SUCCEEDED(rc))
1357 autoInitSpan.setSucceeded();
1358
1359 return rc;
1360}
1361
1362/**
1363 * Uninitializes the instance and sets the ready flag to FALSE.
1364 *
1365 * Called either from FinalRelease() or by the parent when it gets destroyed.
1366 */
1367void CombinedProgress::uninit()
1368{
1369 LogFlowThisFunc(("\n"));
1370
1371 /* Enclose the state transition Ready->InUninit->NotReady */
1372 AutoUninitSpan autoUninitSpan(this);
1373 if (autoUninitSpan.uninitDone())
1374 return;
1375
1376 mProgress = 0;
1377 mProgresses.clear();
1378
1379 ProgressBase::protectedUninit (autoUninitSpan);
1380}
1381
1382// IProgress properties
1383////////////////////////////////////////////////////////////////////////////////
1384
1385STDMETHODIMP CombinedProgress::COMGETTER(Percent)(ULONG *aPercent)
1386{
1387 CheckComArgOutPointerValid(aPercent);
1388
1389 AutoCaller autoCaller(this);
1390 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1391
1392 /* checkProgress needs a write lock */
1393 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1394
1395 if (mCompleted && SUCCEEDED(mResultCode))
1396 *aPercent = 100;
1397 else
1398 {
1399 HRESULT rc = checkProgress();
1400 if (FAILED(rc)) return rc;
1401
1402 /* global percent =
1403 * (100 / m_cOperations) * mOperation +
1404 * ((100 / m_cOperations) / 100) * m_ulOperationPercent */
1405 *aPercent = (100 * m_ulCurrentOperation + m_ulOperationPercent) / m_cOperations;
1406 }
1407
1408 return S_OK;
1409}
1410
1411STDMETHODIMP CombinedProgress::COMGETTER(Completed) (BOOL *aCompleted)
1412{
1413 CheckComArgOutPointerValid(aCompleted);
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 HRESULT rc = checkProgress();
1422 if (FAILED(rc)) return rc;
1423
1424 return ProgressBase::COMGETTER(Completed) (aCompleted);
1425}
1426
1427STDMETHODIMP CombinedProgress::COMGETTER(Canceled) (BOOL *aCanceled)
1428{
1429 CheckComArgOutPointerValid(aCanceled);
1430
1431 AutoCaller autoCaller(this);
1432 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1433
1434 /* checkProgress needs a write lock */
1435 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1436
1437 HRESULT rc = checkProgress();
1438 if (FAILED(rc)) return rc;
1439
1440 return ProgressBase::COMGETTER(Canceled) (aCanceled);
1441}
1442
1443STDMETHODIMP CombinedProgress::COMGETTER(ResultCode) (LONG *aResultCode)
1444{
1445 CheckComArgOutPointerValid(aResultCode);
1446
1447 AutoCaller autoCaller(this);
1448 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1449
1450 /* checkProgress needs a write lock */
1451 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1452
1453 HRESULT rc = checkProgress();
1454 if (FAILED(rc)) return rc;
1455
1456 return ProgressBase::COMGETTER(ResultCode) (aResultCode);
1457}
1458
1459STDMETHODIMP CombinedProgress::COMGETTER(ErrorInfo) (IVirtualBoxErrorInfo **aErrorInfo)
1460{
1461 CheckComArgOutPointerValid(aErrorInfo);
1462
1463 AutoCaller autoCaller(this);
1464 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1465
1466 /* checkProgress needs a write lock */
1467 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1468
1469 HRESULT rc = checkProgress();
1470 if (FAILED(rc)) return rc;
1471
1472 return ProgressBase::COMGETTER(ErrorInfo) (aErrorInfo);
1473}
1474
1475STDMETHODIMP CombinedProgress::COMGETTER(Operation) (ULONG *aOperation)
1476{
1477 CheckComArgOutPointerValid(aOperation);
1478
1479 AutoCaller autoCaller(this);
1480 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1481
1482 /* checkProgress needs a write lock */
1483 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1484
1485 HRESULT rc = checkProgress();
1486 if (FAILED(rc)) return rc;
1487
1488 return ProgressBase::COMGETTER(Operation) (aOperation);
1489}
1490
1491STDMETHODIMP CombinedProgress::COMGETTER(OperationDescription) (BSTR *aOperationDescription)
1492{
1493 CheckComArgOutPointerValid(aOperationDescription);
1494
1495 AutoCaller autoCaller(this);
1496 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1497
1498 /* checkProgress needs a write lock */
1499 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1500
1501 HRESULT rc = checkProgress();
1502 if (FAILED(rc)) return rc;
1503
1504 return ProgressBase::COMGETTER(OperationDescription) (aOperationDescription);
1505}
1506
1507STDMETHODIMP CombinedProgress::COMGETTER(OperationPercent)(ULONG *aOperationPercent)
1508{
1509 CheckComArgOutPointerValid(aOperationPercent);
1510
1511 AutoCaller autoCaller(this);
1512 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1513
1514 /* checkProgress needs a write lock */
1515 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1516
1517 HRESULT rc = checkProgress();
1518 if (FAILED(rc)) return rc;
1519
1520 return ProgressBase::COMGETTER(OperationPercent) (aOperationPercent);
1521}
1522
1523STDMETHODIMP CombinedProgress::COMSETTER(Timeout)(ULONG aTimeout)
1524{
1525 NOREF(aTimeout);
1526 AssertFailed();
1527 return E_NOTIMPL;
1528}
1529
1530STDMETHODIMP CombinedProgress::COMGETTER(Timeout)(ULONG *aTimeout)
1531{
1532 CheckComArgOutPointerValid(aTimeout);
1533
1534 AssertFailed();
1535 return E_NOTIMPL;
1536}
1537
1538// IProgress methods
1539/////////////////////////////////////////////////////////////////////////////
1540
1541/**
1542 * @note XPCOM: when this method is called not on the main XPCOM thread, it
1543 * simply blocks the thread until mCompletedSem is signalled. If the
1544 * thread has its own event queue (hmm, what for?) that it must run, then
1545 * calling this method will definitely freeze event processing.
1546 */
1547STDMETHODIMP CombinedProgress::WaitForCompletion (LONG aTimeout)
1548{
1549 LogFlowThisFuncEnter();
1550 LogFlowThisFunc(("aTtimeout=%d\n", aTimeout));
1551
1552 AutoCaller autoCaller(this);
1553 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1554
1555 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1556
1557 /* if we're already completed, take a shortcut */
1558 if (!mCompleted)
1559 {
1560 RTTIMESPEC time;
1561 RTTimeNow(&time);
1562
1563 HRESULT rc = S_OK;
1564 bool forever = aTimeout < 0;
1565 int64_t timeLeft = aTimeout;
1566 int64_t lastTime = RTTimeSpecGetMilli(&time);
1567
1568 while (!mCompleted && (forever || timeLeft > 0))
1569 {
1570 alock.leave();
1571 rc = mProgresses.back()->WaitForCompletion(forever ? -1 : (LONG) timeLeft);
1572 alock.enter();
1573
1574 if (SUCCEEDED(rc))
1575 rc = checkProgress();
1576
1577 if (FAILED(rc)) break;
1578
1579 if (!forever)
1580 {
1581 RTTimeNow(&time);
1582 timeLeft -= RTTimeSpecGetMilli(&time) - lastTime;
1583 lastTime = RTTimeSpecGetMilli(&time);
1584 }
1585 }
1586
1587 if (FAILED(rc)) return rc;
1588 }
1589
1590 LogFlowThisFuncLeave();
1591
1592 return S_OK;
1593}
1594
1595/**
1596 * @note XPCOM: when this method is called not on the main XPCOM thread, it
1597 * simply blocks the thread until mCompletedSem is signalled. If the
1598 * thread has its own event queue (hmm, what for?) that it must run, then
1599 * calling this method will definitely freeze event processing.
1600 */
1601STDMETHODIMP CombinedProgress::WaitForOperationCompletion (ULONG aOperation, LONG aTimeout)
1602{
1603 LogFlowThisFuncEnter();
1604 LogFlowThisFunc(("aOperation=%d, aTimeout=%d\n", aOperation, aTimeout));
1605
1606 AutoCaller autoCaller(this);
1607 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1608
1609 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1610
1611 if (aOperation >= m_cOperations)
1612 return setError(E_FAIL,
1613 tr("Operation number must be in range [0, %d]"), m_ulCurrentOperation - 1);
1614
1615 /* if we're already completed or if the given operation is already done,
1616 * then take a shortcut */
1617 if (!mCompleted && aOperation >= m_ulCurrentOperation)
1618 {
1619 HRESULT rc = S_OK;
1620
1621 /* find the right progress object to wait for */
1622 size_t progress = mProgress;
1623 ULONG operation = 0, completedOps = mCompletedOperations;
1624 do
1625 {
1626 ULONG opCount = 0;
1627 rc = mProgresses[progress]->COMGETTER(OperationCount)(&opCount);
1628 if (FAILED(rc))
1629 return rc;
1630
1631 if (completedOps + opCount > aOperation)
1632 {
1633 /* found the right progress object */
1634 operation = aOperation - completedOps;
1635 break;
1636 }
1637
1638 completedOps += opCount;
1639 progress ++;
1640 ComAssertRet(progress < mProgresses.size(), E_FAIL);
1641 }
1642 while (1);
1643
1644 LogFlowThisFunc(("will wait for mProgresses [%d] (%d)\n",
1645 progress, operation));
1646
1647 RTTIMESPEC time;
1648 RTTimeNow (&time);
1649
1650 bool forever = aTimeout < 0;
1651 int64_t timeLeft = aTimeout;
1652 int64_t lastTime = RTTimeSpecGetMilli (&time);
1653
1654 while (!mCompleted && aOperation >= m_ulCurrentOperation &&
1655 (forever || timeLeft > 0))
1656 {
1657 alock.leave();
1658 /* wait for the appropriate progress operation completion */
1659 rc = mProgresses[progress]-> WaitForOperationCompletion(operation,
1660 forever ? -1 : (LONG) timeLeft);
1661 alock.enter();
1662
1663 if (SUCCEEDED(rc))
1664 rc = checkProgress();
1665
1666 if (FAILED(rc)) break;
1667
1668 if (!forever)
1669 {
1670 RTTimeNow(&time);
1671 timeLeft -= RTTimeSpecGetMilli(&time) - lastTime;
1672 lastTime = RTTimeSpecGetMilli(&time);
1673 }
1674 }
1675
1676 if (FAILED(rc)) return rc;
1677 }
1678
1679 LogFlowThisFuncLeave();
1680
1681 return S_OK;
1682}
1683
1684STDMETHODIMP CombinedProgress::Cancel()
1685{
1686 AutoCaller autoCaller(this);
1687 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1688
1689 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1690
1691 if (!mCancelable)
1692 return setError(E_FAIL, tr("Operation cannot be canceled"));
1693
1694 if (!mCanceled)
1695 {
1696 mCanceled = TRUE;
1697/** @todo Teleportation: Shouldn't this be propagated to mProgresses? If
1698 * powerUp creates passes a combined progress object to the client, I
1699 * won't get called back since I'm only getting the powerupProgress ...
1700 * Or what? */
1701 if (m_pfnCancelCallback)
1702 m_pfnCancelCallback(m_pvCancelUserArg);
1703
1704 }
1705 return S_OK;
1706}
1707
1708// private methods
1709////////////////////////////////////////////////////////////////////////////////
1710
1711/**
1712 * Fetches the properties of the current progress object and, if it is
1713 * successfully completed, advances to the next uncompleted or unsuccessfully
1714 * completed object in the vector of combined progress objects.
1715 *
1716 * @note Must be called from under this object's write lock!
1717 */
1718HRESULT CombinedProgress::checkProgress()
1719{
1720 /* do nothing if we're already marked ourselves as completed */
1721 if (mCompleted)
1722 return S_OK;
1723
1724 AssertReturn(mProgress < mProgresses.size(), E_FAIL);
1725
1726 ComPtr<IProgress> progress = mProgresses[mProgress];
1727 ComAssertRet(!progress.isNull(), E_FAIL);
1728
1729 HRESULT rc = S_OK;
1730 BOOL fCompleted = FALSE;
1731
1732 do
1733 {
1734 rc = progress->COMGETTER(Completed)(&fCompleted);
1735 if (FAILED(rc))
1736 return rc;
1737
1738 if (fCompleted)
1739 {
1740 rc = progress->COMGETTER(Canceled)(&mCanceled);
1741 if (FAILED(rc))
1742 return rc;
1743
1744 LONG iRc;
1745 rc = progress->COMGETTER(ResultCode)(&iRc);
1746 if (FAILED(rc))
1747 return rc;
1748 mResultCode = iRc;
1749
1750 if (FAILED(mResultCode))
1751 {
1752 rc = progress->COMGETTER(ErrorInfo) (mErrorInfo.asOutParam());
1753 if (FAILED(rc))
1754 return rc;
1755 }
1756
1757 if (FAILED(mResultCode) || mCanceled)
1758 {
1759 mCompleted = TRUE;
1760 }
1761 else
1762 {
1763 ULONG opCount = 0;
1764 rc = progress->COMGETTER(OperationCount) (&opCount);
1765 if (FAILED(rc))
1766 return rc;
1767
1768 mCompletedOperations += opCount;
1769 mProgress ++;
1770
1771 if (mProgress < mProgresses.size())
1772 progress = mProgresses[mProgress];
1773 else
1774 mCompleted = TRUE;
1775 }
1776 }
1777 }
1778 while (fCompleted && !mCompleted);
1779
1780 rc = progress->COMGETTER(OperationPercent) (&m_ulOperationPercent);
1781 if (SUCCEEDED(rc))
1782 {
1783 ULONG operation = 0;
1784 rc = progress->COMGETTER(Operation) (&operation);
1785 if (SUCCEEDED(rc) && mCompletedOperations + operation > m_ulCurrentOperation)
1786 {
1787 m_ulCurrentOperation = mCompletedOperations + operation;
1788 rc = progress->COMGETTER(OperationDescription) (
1789 m_bstrOperationDescription.asOutParam());
1790 }
1791 }
1792
1793 return rc;
1794}
1795/* 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