1 | package org.openstreetmap.josm.io;
|
---|
2 |
|
---|
3 | import java.io.IOException;
|
---|
4 | import java.io.InputStream;
|
---|
5 | import java.net.URLConnection;
|
---|
6 |
|
---|
7 | import javax.swing.BoundedRangeModel;
|
---|
8 | import javax.swing.JLabel;
|
---|
9 |
|
---|
10 | /**
|
---|
11 | * Read from an other reader and increment an progress counter while on the way.
|
---|
12 | * @author Imi
|
---|
13 | */
|
---|
14 | public class ProgressReader extends InputStream {
|
---|
15 |
|
---|
16 | private final InputStream in;
|
---|
17 | private final BoundedRangeModel progress;
|
---|
18 | private final JLabel currentAction;
|
---|
19 | private int readSoFar = 0;
|
---|
20 | private int lastDialogUpdate = 0;
|
---|
21 | private final URLConnection connection;
|
---|
22 |
|
---|
23 | public ProgressReader(URLConnection con, BoundedRangeModel progress, JLabel currentAction) throws IOException {
|
---|
24 | this.connection = con;
|
---|
25 | this.in = con.getInputStream();
|
---|
26 | this.progress = progress;
|
---|
27 | this.currentAction = currentAction;
|
---|
28 | int contentLength = con.getContentLength();
|
---|
29 | if (contentLength > 0)
|
---|
30 | progress.setMaximum(contentLength);
|
---|
31 | else
|
---|
32 | progress.setMaximum(0);
|
---|
33 | progress.setValue(0);
|
---|
34 | }
|
---|
35 |
|
---|
36 | @Override public void close() throws IOException {
|
---|
37 | in.close();
|
---|
38 | }
|
---|
39 |
|
---|
40 | @Override public int read(byte[] b, int off, int len) throws IOException {
|
---|
41 | int read = in.read(b, off, len);
|
---|
42 | if (read != -1)
|
---|
43 | advanceTicker(read);
|
---|
44 | return read;
|
---|
45 | }
|
---|
46 |
|
---|
47 | @Override public int read() throws IOException {
|
---|
48 | int read = in.read();
|
---|
49 | if (read != -1)
|
---|
50 | advanceTicker(1);
|
---|
51 | return read;
|
---|
52 | }
|
---|
53 |
|
---|
54 | /**
|
---|
55 | * Increase ticker (progress counter and displayed text) by the given amount.
|
---|
56 | * @param amount
|
---|
57 | */
|
---|
58 | private void advanceTicker(int amount) {
|
---|
59 | if (progress.getMaximum() == 0 && connection.getContentLength() != -1)
|
---|
60 | progress.setMaximum(connection.getContentLength());
|
---|
61 |
|
---|
62 | readSoFar += amount;
|
---|
63 |
|
---|
64 | if (readSoFar / 1024 != lastDialogUpdate) {
|
---|
65 | lastDialogUpdate++;
|
---|
66 | String progStr = " "+readSoFar/1024+"/";
|
---|
67 | progStr += (progress.getMaximum()==0) ? "??? KB" : (progress.getMaximum()/1024)+" KB";
|
---|
68 | progress.setValue(readSoFar);
|
---|
69 |
|
---|
70 | String cur = currentAction.getText();
|
---|
71 | int i = cur.indexOf(' ');
|
---|
72 | if (i != -1)
|
---|
73 | cur = cur.substring(0, i) + progStr;
|
---|
74 | else
|
---|
75 | cur += progStr;
|
---|
76 | currentAction.setText(cur);
|
---|
77 | }
|
---|
78 | }
|
---|
79 | }
|
---|