1
2
3
4
5
6
7
8
9
10
11 package org.eclipse.jgit.transport;
12
13 import static java.nio.charset.StandardCharsets.UTF_8;
14
15 import java.io.IOException;
16 import java.io.OutputStream;
17 import java.util.concurrent.TimeUnit;
18
19
20
21
22
23
24
25
26
27
28
29 public class ProgressSpinner {
30 private static final long MIN_REFRESH_MILLIS = 500;
31 private static final char[] STATES = new char[] { '-', '\\', '|', '/' };
32
33 private final OutputStream out;
34 private String msg;
35 private int state;
36 private boolean write;
37 private boolean shown;
38 private long nextUpdateMillis;
39
40
41
42
43
44
45
46 public ProgressSpinner(OutputStream out) {
47 this.out = out;
48 this.write = true;
49 }
50
51
52
53
54
55
56
57
58
59
60
61 public void beginTask(String title, long delay, TimeUnit delayUnits) {
62 msg = title;
63 state = 0;
64 shown = false;
65
66 long now = System.currentTimeMillis();
67 if (delay > 0) {
68 nextUpdateMillis = now + delayUnits.toMillis(delay);
69 } else {
70 send(now);
71 }
72 }
73
74
75
76
77 public void update() {
78 long now = System.currentTimeMillis();
79 if (now >= nextUpdateMillis) {
80 send(now);
81 state = (state + 1) % STATES.length;
82 }
83 }
84
85 private void send(long now) {
86 StringBuilder buf = new StringBuilder(msg.length() + 16);
87 buf.append('\r').append(msg).append("... (");
88 buf.append(STATES[state]);
89 buf.append(") ");
90 shown = true;
91 write(buf.toString());
92 nextUpdateMillis = now + MIN_REFRESH_MILLIS;
93 }
94
95
96
97
98
99
100
101
102 public void endTask(String result) {
103 if (shown) {
104 write('\r' + msg + "... " + result + "\n");
105 }
106 }
107
108 private void write(String s) {
109 if (write) {
110 try {
111 out.write(s.getBytes(UTF_8));
112 out.flush();
113 } catch (IOException e) {
114 write = false;
115 }
116 }
117 }
118 }