1 package net.sf.openrocket.util;
3 import java.io.BufferedInputStream;
5 import java.io.FileInputStream;
6 import java.io.FilterInputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InterruptedIOException;
11 import javax.swing.SwingWorker;
13 import net.sf.openrocket.document.OpenRocketDocument;
14 import net.sf.openrocket.file.GeneralRocketLoader;
15 import net.sf.openrocket.file.RocketLoader;
19 * A SwingWorker thread that opens a rocket design file.
21 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
23 public class OpenFileWorker extends SwingWorker<OpenRocketDocument, Void> {
25 private static final RocketLoader ROCKET_LOADER = new GeneralRocketLoader();
27 private final File file;
28 private final InputStream stream;
30 public OpenFileWorker(File file) {
36 public OpenFileWorker(InputStream stream) {
43 protected OpenRocketDocument doInBackground() throws Exception {
46 // Get the correct input stream
48 is = new FileInputStream(file);
53 // Buffer stream unless already buffered
54 if (!(is instanceof BufferedInputStream)) {
55 is = new BufferedInputStream(is);
58 // Encapsulate in a ProgressInputStream
59 is = new ProgressInputStream(is);
62 return ROCKET_LOADER.load(is);
66 } catch (Exception e) {
67 System.err.println("Error closing file: ");
76 private class ProgressInputStream extends FilterInputStream {
78 private final int size;
79 private int readBytes = 0;
80 private int progress = -1;
82 protected ProgressInputStream(InputStream in) {
87 } catch (IOException e) {
88 System.err.println("ERROR estimating available bytes!");
91 size = Math.max(s, 1);
97 public int read() throws IOException {
104 throw new InterruptedIOException("OpenFileWorker was cancelled");
110 public int read(byte[] b, int off, int len) throws IOException {
111 int n = in.read(b, off, len);
117 throw new InterruptedIOException("OpenFileWorker was cancelled");
123 public int read(byte[] b) throws IOException {
130 throw new InterruptedIOException("OpenFileWorker was cancelled");
136 public long skip(long n) throws IOException {
137 long nr = in.skip(n);
143 throw new InterruptedIOException("OpenFileWorker was cancelled");
149 public synchronized void reset() throws IOException {
151 readBytes = size - in.available();
154 throw new InterruptedIOException("OpenFileWorker was cancelled");
160 private void setProgress() {
161 int p = MathUtil.clamp(readBytes * 100 / size, 0, 100);
164 OpenFileWorker.this.setProgress(progress);