summaryrefslogtreecommitdiff
path: root/demos/java/gsviewer/src/com/artifex/gsviewer/ViewerController.java
blob: 92e7d725e5a1b6a95fd99e50cf93f2e3eaac35ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package com.artifex.gsviewer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.JFileChooser;
import com.artifex.gsviewer.gui.ViewerGUIListener;
import com.artifex.gsviewer.gui.ViewerWindow;

/**
 * The ViewerController is an implementation of a <code>ViewerGUIListener</code>
 * used to control the main logic of the viewer such as determining what pages
 * should be loaded.
 *
 * @author Ethan Vrhel
 *
 */
public class ViewerController implements ViewerGUIListener {

	private static final Lock lock = new ReentrantLock();
	private static final Condition cv = lock.newCondition();

	private ViewerWindow source;
	private Document currentDocument;
	private SmartLoader smartLoader;

	public void open(final File file) {
		if (currentDocument != null)
			close();
		Document.loadDocumentAsync(file, (final Document doc, final Exception exception) -> {
			source.loadDocumentToViewer(doc);
			source.setLoadProgress(0);
			if (exception != null) {
				source.showErrorDialog("Failed to load", exception.toString());
			} else {
				this.currentDocument = doc;
				dispatchSmartLoader();
			}
			source.revalidate();
		}, (int progress) -> {
			source.setLoadProgress(progress);
		}, Document.OPERATION_RETURN);
	}

	public void close() {
		if (smartLoader != null) {
			smartLoader.stop();
			smartLoader = null;
		}

		if (currentDocument != null) {
			source.loadDocumentToViewer(null);
			currentDocument.unload();
			currentDocument = null;
		}
	}

	public Document getCurrentDocument() {
		return currentDocument;
	}

	@Override
	public void onViewerAdd(ViewerWindow source) {
		this.source = source;
		Thread.setDefaultUncaughtExceptionHandler(new UnhandledExceptionHandler());
	}

	@Override
	public void onPageChange(int oldPage, int newPage) {
		lock.lock();
		try {
			cv.signalAll();
		} catch (IllegalMonitorStateException e) {
			System.err.println("Exception on signaling: " + e);
		} finally {
			lock.unlock();
		}
	}

	@Override
	public void onZoomChange(double oldZoom, double newZoom) {
		if (newZoom > 1.0) {
			int currentPage = source.getCurrentPage();
			Runnable r = () -> {
					//source.showWarningDialog("Error", "An operation is already in progress");
					//return;

				try {
					currentDocument.zoomArea(Document.OPERATION_THROW, currentPage, newZoom);
				} catch (Document.OperationInProgressException e) {
					source.showWarningDialog("Error", "An operation is already in progress");
				}
			};
			Thread t = new Thread(r);
			t.setName("Zoom-Thread");
			t.start();
		}
	}

	@Override
	public void onScrollChange(int newScroll) {
		lock.lock();
		try {
			cv.signalAll();
		} catch (IllegalMonitorStateException e) {
			System.err.println("Exception on signaling: " + e);
		} finally {
			lock.unlock();
		}
	}

	@Override
	public void onOpenFile() {
		JFileChooser chooser = new JFileChooser();
		chooser.setFileFilter(GSFileFilter.INSTANCE);
		chooser.setCurrentDirectory(new File("").getAbsoluteFile());
		int status = chooser.showOpenDialog(source);
		if (status == JFileChooser.APPROVE_OPTION)
			open(chooser.getSelectedFile());
	}

	@Override
	public void onCloseFile() {
		close();
	}

	@Override
	public void onClosing() {
		source.dispose();
		System.exit(0);
	}

	@Override
	public void onSettingsOpen() { }

	private void dispatchSmartLoader() {
		if (smartLoader != null)
			smartLoader.stop();
		smartLoader = new SmartLoader(currentDocument);
		smartLoader.start();
	}

	private class UnhandledExceptionHandler implements Thread.UncaughtExceptionHandler {

		@Override
		public void uncaughtException(Thread t, Throwable e) {
			e.printStackTrace(System.err);
			if (source != null) {
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				PrintStream out = new PrintStream(os);
				e.printStackTrace(out);
				String errorMessage = new String(os.toByteArray());
				source.showErrorDialog("Unhandled Exception", errorMessage);
			}
			DefaultUnhandledExceptionHandler.INSTANCE.uncaughtException(t, e);

		}

	}

	private class SmartLoader implements Runnable {

		private volatile boolean[] loaded;
		private volatile boolean shouldRun;
		private Thread thread;

		private SmartLoader(Document doc) {
			loaded = new boolean[doc.size()];
			shouldRun = true;
		}

		private void start() {
			if (thread != null)
				stop();
			shouldRun = true;
			thread = new Thread(this);
			thread.setDaemon(true);
			thread.setName("Document-Smart-Loader-Thread");
			thread.start();
		}

		private void stop() {
			shouldRun = false;
			lock.lock();
			cv.signalAll();
			lock.unlock();
			try {
				thread.join();
			} catch (InterruptedException e) {
				throw new RuntimeException("Thread join interrupted", e);
			}
			thread = null;
		}

		@Override
		public void run() {
			System.out.println("Smart loader dispatched.");
			while (shouldRun) {
				int currentPage = source.getCurrentPage();
				int[] toLoad =  new int[] {
						currentPage, currentPage - 1, currentPage + 1,
						currentPage - 2, currentPage + 2 };

				if (loaded.length != currentDocument.size())
					throw new IllegalStateException("Array is size " + loaded.length + " while doc size is " + currentDocument.size());

				int ind = 0;
				for (int page : toLoad) {
					if (page >= 1 && page <= currentDocument.size()) {
						if (!loaded[page - 1]) {
							currentDocument.loadHighRes(Document.OPERATION_WAIT, page);
							loaded[page - 1] = true;
						}
					}
					ind++;
					source.setLoadProgress((int)(((double)ind / toLoad.length) * 100));
				}
				source.setLoadProgress(0);

				lock.lock();
				try {
					cv.await();
				} catch (InterruptedException e) {
					System.err.println("Interrupted in smart loader: " + e);
				} finally {
					lock.unlock();
				}
			}
		}
	}
}