01: /*
02: * This is free software, licensed under the Gnu Public License (GPL)
03: * get a copy from <http://www.gnu.org/licenses/gpl.html>
04: * $Id: ProgressWriter.java,v 1.2 2005/03/25 15:39:44 hzeller Exp $
05: * author: Henner Zeller <H.Zeller@acm.org>
06: */
07: package henplus.view.util;
08:
09: import henplus.OutputDevice;
10: import henplus.commands.TimeRenderer;
11:
12: /**
13: * A utility class that can write the progress of an operation
14: * to the screen.
15: */
16: public class ProgressWriter {
17: private final static int DEFAULT_SCREEN_WIDTH = 65;
18:
19: /** min time before presenting an eta */
20: private final static long MIN_ETA_RUNNING_TIME = 30 * 1000L;
21: /** min time between two eta updates */
22: private final static long MIN_ETA_DIFF_TIME = 1 * 1000L;
23:
24: private final long _expectedTargetValue;
25: private final OutputDevice _out;
26: private final long _startTime;
27: private final CancelWriter _etaWriter;
28:
29: private long _lastEtaUpdate;
30:
31: private int _progressDots;
32: private int _screenWidth;
33:
34: public ProgressWriter(long expectedTargetValue, OutputDevice out) {
35: _expectedTargetValue = expectedTargetValue;
36: _out = out;
37: _progressDots = 0;
38: _startTime = System.currentTimeMillis();
39: _lastEtaUpdate = -1;
40: _etaWriter = new CancelWriter(_out);
41: setScreenWidth(DEFAULT_SCREEN_WIDTH);
42: }
43:
44: public void setScreenWidth(int screenWidth) {
45: _screenWidth = screenWidth;
46: }
47:
48: public int getScreenWidth() {
49: return _screenWidth;
50: }
51:
52: public void update(long value) {
53: if (_expectedTargetValue > 0 && value <= _expectedTargetValue) {
54: long newDots = (_screenWidth * value)
55: / _expectedTargetValue;
56: if (newDots > _progressDots) {
57: _etaWriter.cancel(false);
58: while (_progressDots < newDots) {
59: _out.print(".");
60: ++_progressDots;
61: }
62: _out.flush();
63: }
64: writeEta(value);
65: }
66: }
67:
68: public void finish() {
69: _etaWriter.cancel();
70: }
71:
72: private void writeEta(long value) {
73: if (!_etaWriter.isPrinting())
74: return;
75: final long now = System.currentTimeMillis();
76: final long runningTime = now - _startTime;
77: if (runningTime < MIN_ETA_RUNNING_TIME)
78: return;
79: final long lastUpdateDiff = now - _lastEtaUpdate;
80: if (!_etaWriter.hasCancellableOutput()
81: || lastUpdateDiff > MIN_ETA_DIFF_TIME) {
82: long etaTime = _expectedTargetValue * runningTime / value;
83: long rest = etaTime - runningTime;
84: _etaWriter.print("ETA: " + TimeRenderer.renderTime(rest));
85: _lastEtaUpdate = now;
86: }
87: }
88: }
|