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.RocketLoader;
15 import net.sf.openrocket.gui.main.ExceptionHandler;
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 final File file;
26 private final InputStream stream;
27 private final RocketLoader loader;
29 public OpenFileWorker(File file, RocketLoader loader) {
36 public OpenFileWorker(InputStream stream, RocketLoader loader) {
42 public RocketLoader getRocketLoader() {
47 protected OpenRocketDocument doInBackground() throws Exception {
50 // Get the correct input stream
52 is = new FileInputStream(file);
57 // Buffer stream unless already buffered
58 if (!(is instanceof BufferedInputStream)) {
59 is = new BufferedInputStream(is);
62 // Encapsulate in a ProgressInputStream
63 is = new ProgressInputStream(is);
66 return loader.load(is);
70 } catch (Exception e) {
71 ExceptionHandler.handleErrorCondition("Error closing file", e);
79 private class ProgressInputStream extends FilterInputStream {
81 private final int size;
82 private int readBytes = 0;
83 private int progress = -1;
85 protected ProgressInputStream(InputStream in) {
90 } catch (IOException e) {
91 System.err.println("ERROR estimating available bytes!");
94 size = Math.max(s, 1);
100 public int read() throws IOException {
107 throw new InterruptedIOException("OpenFileWorker was cancelled");
113 public int read(byte[] b, int off, int len) throws IOException {
114 int n = in.read(b, off, len);
120 throw new InterruptedIOException("OpenFileWorker was cancelled");
126 public int read(byte[] b) throws IOException {
133 throw new InterruptedIOException("OpenFileWorker was cancelled");
139 public long skip(long n) throws IOException {
140 long nr = in.skip(n);
146 throw new InterruptedIOException("OpenFileWorker was cancelled");
152 public synchronized void reset() throws IOException {
154 readBytes = size - in.available();
157 throw new InterruptedIOException("OpenFileWorker was cancelled");
163 private void setProgress() {
164 int p = MathUtil.clamp(readBytes * 100 / size, 0, 100);
167 OpenFileWorker.this.setProgress(progress);