Numerous bug fixes and updates
[debian/openrocket] / src / net / sf / openrocket / util / ProgressOutputStream.java
1 package net.sf.openrocket.util;
2
3 import java.io.FilterOutputStream;
4 import java.io.IOException;
5 import java.io.InterruptedIOException;
6 import java.io.OutputStream;
7
8 import javax.swing.SwingWorker;
9
10
11 public abstract class ProgressOutputStream extends FilterOutputStream {
12
13         private final int totalBytes;
14         private final SwingWorker<?,?> worker;
15         private int writtenBytes = 0;
16         private int progress = -1;
17         
18         public ProgressOutputStream(OutputStream out, int estimate, SwingWorker<?,?> worker) {
19                 super(out);
20                 this.totalBytes = estimate;
21                 this.worker = worker;
22         }
23
24         @Override
25         public void write(byte[] b, int off, int len) throws IOException {
26                 out.write(b, off, len);
27                 writtenBytes += len;
28                 setProgress();
29                 if (worker.isCancelled()) {
30                         throw new InterruptedIOException("SaveFileWorker was cancelled");
31                 }
32         }
33
34         @Override
35         public void write(byte[] b) throws IOException {
36                 out.write(b);
37                 writtenBytes += b.length;
38                 setProgress();
39                 if (worker.isCancelled()) {
40                         throw new InterruptedIOException("SaveFileWorker was cancelled");
41                 }
42         }
43
44         @Override
45         public void write(int b) throws IOException {
46                 out.write(b);
47                 writtenBytes++;
48                 setProgress();
49                 if (worker.isCancelled()) {
50                         throw new InterruptedIOException("SaveFileWorker was cancelled");
51                 }
52         }
53         
54         
55         private void setProgress() {
56                 int p = MathUtil.clamp(writtenBytes * 100 / totalBytes, 0, 100);
57                 if (progress != p) {
58                         progress = p;
59                         setProgress(progress);
60                 }
61         }
62         
63         /**
64          * Set the current progress.  The value of <code>progress</code> is guaranteed
65          * to be between 0 and 100, inclusive.
66          * 
67          * @param progress      the current progress in the range 0-100.
68          */
69         protected abstract void setProgress(int progress);
70
71 }