JAL-3130 adapted getdown src. attempt 2. first attempt failed due to cp'ed .git files
[jalview.git] / getdown / src / getdown / core / src / main / java / com / threerings / getdown / util / ProgressAggregator.java
1 //
2 // Getdown - application installer, patcher and launcher
3 // Copyright (C) 2004-2018 Getdown authors
4 // https://github.com/threerings/getdown/blob/master/LICENSE
5
6 package com.threerings.getdown.util;
7
8 /**
9  * Accumulates the progress from a number of (potentially parallel) elements into a single smoothly
10  * progressing progress.
11  */
12 public class ProgressAggregator
13 {
14     public ProgressAggregator (ProgressObserver target, long[] sizes) {
15         _target = target;
16         _sizes = sizes;
17         _progress = new int[sizes.length];
18     }
19
20     public ProgressObserver startElement (final int index) {
21         return new ProgressObserver() {
22             public void progress (int percent) {
23                 _progress[index] = percent;
24                 updateAggProgress();
25             }
26         };
27     }
28
29     protected void updateAggProgress () {
30         long totalSize = 0L, currentSize = 0L;
31         synchronized (this) {
32             for (int ii = 0, ll = _sizes.length; ii < ll; ii++) {
33                 long size = _sizes[ii];
34                 totalSize += size;
35                 currentSize += (int)((size * _progress[ii])/100.0);
36             }
37         }
38         _target.progress((int)(100.0*currentSize / totalSize));
39     }
40
41     protected static long sum (long[] sizes) {
42         long totalSize = 0L;
43         for (long size : sizes) totalSize += size;
44         return totalSize;
45     }
46
47     protected ProgressObserver _target;
48     protected long[] _sizes;
49     protected int[] _progress;
50 }