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