1 package net.sf.openrocket.gui.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.logging.LogHelper;
16 import net.sf.openrocket.startup.Application;
17 import net.sf.openrocket.util.MathUtil;
21 * A SwingWorker thread that opens a rocket design file.
23 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
25 public class OpenFileWorker extends SwingWorker<OpenRocketDocument, Void> {
26 private static final LogHelper log = Application.getLogger();
28 private final File file;
29 private final InputStream stream;
30 private final RocketLoader loader;
32 public OpenFileWorker(File file, RocketLoader loader) {
39 public OpenFileWorker(InputStream stream, RocketLoader loader) {
45 public RocketLoader getRocketLoader() {
50 protected OpenRocketDocument doInBackground() throws Exception {
53 // Get the correct input stream
55 is = new FileInputStream(file);
60 // Buffer stream unless already buffered
61 if (!(is instanceof BufferedInputStream)) {
62 is = new BufferedInputStream(is);
65 // Encapsulate in a ProgressInputStream
66 is = new ProgressInputStream(is);
69 return loader.load(is);
73 } catch (Exception e) {
74 Application.getExceptionHandler().handleErrorCondition("Error closing file", e);
82 private class ProgressInputStream extends FilterInputStream {
84 private final int size;
85 private int readBytes = 0;
86 private int progress = -1;
88 protected ProgressInputStream(InputStream in) {
93 } catch (IOException e) {
94 log.info("Exception while estimating available bytes!", e);
97 size = Math.max(s, 1);
103 public int read() throws IOException {
110 throw new InterruptedIOException("OpenFileWorker was cancelled");
116 public int read(byte[] b, int off, int len) throws IOException {
117 int n = in.read(b, off, len);
123 throw new InterruptedIOException("OpenFileWorker was cancelled");
129 public int read(byte[] b) throws IOException {
136 throw new InterruptedIOException("OpenFileWorker was cancelled");
142 public long skip(long n) throws IOException {
143 long nr = in.skip(n);
149 throw new InterruptedIOException("OpenFileWorker was cancelled");
155 public synchronized void reset() throws IOException {
157 readBytes = size - in.available();
160 throw new InterruptedIOException("OpenFileWorker was cancelled");
166 private void setProgress() {
167 int p = MathUtil.clamp(readBytes * 100 / size, 0, 100);
170 OpenFileWorker.this.setProgress(progress);