summaryrefslogtreecommitdiff
path: root/demos/java/gsviewer/src/com/artifex/gsviewer/Document.java
blob: 80e14333b267513f602d61e905e758c2b19a62c6 (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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
package com.artifex.gsviewer;

import static com.artifex.gsjava.GSAPI.*;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import com.artifex.gsjava.GSInstance;
import com.artifex.gsjava.callbacks.DisplayCallback;
import com.artifex.gsjava.util.BytePointer;
import com.artifex.gsviewer.ImageUtil.ImageParams;

/**
 * <p>A Document stores an ordered list of Pages. This class implements
 * <code>java.util.List</code>, so it inherits all of a list's capabilities,
 * such as the ability to iterate over the document.</p>
 *
 * <p>The Document class also handles loading of pages through Ghostcript
 * and ensuring that two Ghostscript operations are not running at the
 * same time.</p>
 *
 * @author Ethan Vrhel
 *
 */
public class Document implements List<Page> {

	private static final DocumentLoader documentLoader = new DocumentLoader(); // The document loader
	private static final int format = GS_COLORS_RGB | GS_DISPLAY_DEPTH_8 | GS_DISPLAY_BIGENDIAN; // Format

	private static final ReentrantLock operationLock = new ReentrantLock(); // The operation lock
	private static final Condition operationCv = operationLock.newCondition(); // The operation condition variable
	private static volatile boolean operationInProgress = false; // Whether an operation is in progress

	/**
	 * Asynchronous execution dispatch returns.
	 */
	public static final int ASYNC_DISPATCH_OK = 0, ASYNC_DISPATCH_OPERATION_IN_PROGRESS = 1;

	/**
	 * Operation mode indicating the method should wait until a running operation has finished.
	 */
	public static final int OPERATION_WAIT = 0;

	/**
	 * Operation mode indicating the method should immediately return if an operation is already
	 * running.
	 */
	public static final int OPERATION_RETURN = 1;

	/**
	 * Operation mode indicating the method should throw an <code>OperationInProgressException</code>
	 * if an operation is already running.
	 */
	public static final int OPERATION_THROW = 2;

	/**
	 * Loads a document on a separate thread.
	 *
	 * @param file The file to load.
	 * @param cb The callback when loading the document has finished.
	 * @param dlb The callback signifying when progress has occurred while loading.
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return <code>ASYNC_DISPATCH_OPERATION_IN_PROGRESS</code>, or
	 * <code>OPERATION_THROW</code> meaning the loader should throw an
	 * <code>OperationInProgressException</code>.
	 *
	 * @return The state of the thread dispatching. This is either <code>ASYNC_DISPATCH_OK</code>
	 * or <code>ASYNC_DISPATCH_OPERATION_IN_PROGRESS</code> which is also dependent on
	 * <code>operationMode</code>.
	 *
	 * @throws NullPointerException When <code>cb</code> is <code>null</code>.
	 * @throws RuntimeException When the current thread fails to wait until a thread has finished
	 * completing an operation.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>OPERTAION_WAIT</coded>, <code>OPERATION_RETURN</code>, or <code>OPERATION_THROW</code>.
	 * @throws OperationInProgressException When an operation is in progress and
	 * <code>operationMode</codeE> is <code>OPERATION_THROW</code>.
	 */
	public static int loadDocumentAsync(final File file, final DocAsyncLoadCallback cb,
			final DocLoadProgressCallback dlb, final int operationMode)
			throws NullPointerException, RuntimeException, IllegalArgumentException,
			OperationInProgressException {
		if (!handleOperationMode(operationMode))
			return ASYNC_DISPATCH_OPERATION_IN_PROGRESS;

		Objects.requireNonNull(cb, "DocAsyncLoadCallback");
		final Thread t = new Thread(() -> {
			Document doc = null;
			Exception exception = null;
			try {
				doc = new Document(file, dlb, operationMode);
			} catch (FileNotFoundException | IllegalStateException | NullPointerException e) {
				exception = e;
			}
			cb.onDocumentLoad(doc, exception);
		});
		t.setName("Document-Loader-Thread");
		t.setDaemon(true);
		t.start();
		return ASYNC_DISPATCH_OK;
	}

	/**
	 * Loads a document on a separate thread.
	 *
	 * @param file The file to load.
	 * @param cb The callback when loading the document has finished.
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return <code>ASYNC_DISPATCH_OPERATION_IN_PROGRESS</code>, or
	 * <code>OPERATION_THROW</code> meaning the loader should throw an
	 * <code>OperationInProgressException</code>.
	 *
	 * @return The state of the thread dispatching. This is either <code>ASYNC_DISPATCH_OK</code>
	 * or <code>ASYNC_DISPATCH_OPERATION_IN_PROGRESS</code> which is also dependent on
	 * <code>operationMode</code>.
	 *
	 * @throws NullPointerException When <code>cb</code> is <code>null</code>.
	 * @throws RuntimeException When the current thread fails to wait until a thread has finished
	 * completing an operation.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>ASYNC_OPERTAION_WAIT</coded> or <code>ASYNC_OPERATION_RETURN</code>.
	 */
	public static int loadDocumentAsync(final File file, final DocAsyncLoadCallback cb,
			final int operationMode)
			throws NullPointerException, RuntimeException, IllegalArgumentException {
		return loadDocumentAsync(file, cb, null, operationMode);
	}

	/**
	 * Loads a document on a separate thread.
	 *
	 * @param filename The name of the file to load.
	 * @param cb The callback when loading the document has finished.
	 * @param dlb The callback signifying when progress has occurred while loading.
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return <code>ASYNC_DISPATCH_OPERATION_IN_PROGRESS</code>, or
	 * <code>OPERATION_THROW</code> meaning the loader should throw an
	 * <code>OperationInProgressException</code>.
	 *
	 * @return The state of the thread dispatching. This is either <code>ASYNC_DISPATCH_OK</code>
	 * or <code>ASYNC_DISPATCH_OPERATION_IN_PROGRESS</code> which is also dependent on
	 * <code>operationMode</code>.
	 *
	 * @throws NullPointerException When <code>cb</code> is <code>null</code>.
	 * @throws RuntimeException When the current thread fails to wait until a thread has finished
	 * completing an operation.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>ASYNC_OPERTAION_WAIT</coded> or <code>ASYNC_OPERATION_RETURN</code>.
	 */
	public static int loadDocumentAsync(final String filename, final DocAsyncLoadCallback cb,
			final DocLoadProgressCallback dlb, final int operationMode)
			throws NullPointerException, RuntimeException, IllegalArgumentException {
		return loadDocumentAsync(new File(filename), cb, dlb, operationMode);
	}

	/**
	 * Loads a document on a separate thread.
	 *
	 * @param filename The name of the file to load.
	 * @param cb The callback when loading the document has finished.
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return <code>ASYNC_DISPATCH_OPERATION_IN_PROGRESS</code>, or
	 * <code>OPERATION_THROW</code> meaning the loader should throw an
	 * <code>OperationInProgressException</code>.
	 *
	 * @return The state of the thread dispatching. This is either <code>ASYNC_DISPATCH_OK</code>
	 * or <code>ASYNC_DISPATCH_OPERATION_IN_PROGRESS</code> which is also dependent on
	 * <code>operationMode</code>.
	 *
	 * @throws NullPointerException When <code>cb</code> is <code>null</code>.
	 * @throws RuntimeException When the current thread fails to wait until a thread has finished
	 * completing an operation.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>ASYNC_OPERTAION_WAIT</coded> or <code>ASYNC_OPERATION_RETURN</code>.
	 */
	public static int loadDocumentAsync(final String filename, final DocAsyncLoadCallback cb,
			final int operationMode)
			throws NullPointerException, RuntimeException, IllegalArgumentException {
		return loadDocumentAsync(filename, cb, null, operationMode);
	}

	/**
	 * Call, internally, on the start of an operation.
	 */
	private static void startOperation() {
		operationInProgress = true;
	}

	/**
	 * Call, internally, on the start of an operation, before <code>startOperation()</code>.
	 *
	 * @param operationMode The operation mode.
	 * @return Whether the calling function should continue to its operation.
	 * @throws OperationInProgressException When an operation is in progress and <code>operationMode</code>
	 * is <code>OPERATION_THROW</code>. This should not be caught by the calling function, who should
	 * throw it instead.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not a valid operation mode.
	 */
	private static boolean handleOperationMode(final int operationMode)
			throws OperationInProgressException, IllegalArgumentException {
		if (operationInProgress && operationMode == OPERATION_RETURN)
			return false;
		else if (operationInProgress && operationMode == OPERATION_THROW) {
			StackTraceElement[] elems = new Exception().getStackTrace();
			throw new OperationInProgressException(elems[1].getClassName() + "." + elems[1].getMethodName());
		} else if (operationInProgress && operationMode == OPERATION_WAIT)
			waitForOperation();
		else if (operationInProgress)
			throw new IllegalArgumentException("Unknown operation mode: " + operationMode);
		return true;
	}

	/**
	 * Called internally by <code>handleOperationMode()</code>. Waits for an operation
	 * to finish.
	 */
	private static void waitForOperation() {
		operationLock.lock();
		try {
			operationCv.await();
		} catch (InterruptedException e) {
			throw new RuntimeException("Thread interrupted", e);
		} finally {
			operationLock.unlock();
		}
	}

	/**
	 * Call, internally, when an operation is done.
	 */
	private static void operationDone() {
		operationLock.lock();
		operationInProgress = false;
		try {
			operationCv.signal();
		} finally {
			operationLock.unlock();
		}
	}

	@FunctionalInterface
	public static interface DocAsyncLoadCallback {

		/**
		 * Called when a document has finished loading on a separate
		 * thread.
		 *
		 * @param doc The document which was loaded. <code>null</code> if the document
		 * failed to load.
		 * @param exception An exception that ocurred while loading, <code>null</code>
		 * if no exception was thrown.
		 */
		public void onDocumentLoad(Document doc, Exception exception);
	}

	@FunctionalInterface
	public static interface DocLoadProgressCallback {

		/**
		 * Called when the document has made progress while loading.
		 *
		 * @param progress The amount of progress (from 0 to 100).
		 */
		public void onDocumentProgress(int progress);
	}

	/**
	 * Exception indicating an operation is already in progress.
	 *
	 * @author Ethan Vrhel
	 *
	 */
	public static final class OperationInProgressException extends RuntimeException {

		private static final long serialVersionUID = 1L;

		public OperationInProgressException(String message) {
			super(message);
		}
	}

	/**
	 * Initializes an instance of Ghostcript.
	 *
	 * @param instanceRef A reference to the instance of Ghostscript.
	 * @throws IllegalStateException When any Ghostscript operation fails to execute.
	 */
//	private static void initDocInstance(LongReference instanceRef) throws IllegalStateException {
//		int code = gsapi_new_instance(instanceRef, GS_NULL);
//		if (code != GS_ERROR_OK) {
//			gsapi_delete_instance(instanceRef.value);
//			throw new IllegalStateException("Failed to set stdio with handle (code = " + code + ")");
//		}
//
//		code = gsapi_set_arg_encoding(instanceRef.value, 1);
//		if (code != GS_ERROR_OK) {
//			gsapi_delete_instance(instanceRef.value);
//			throw new IllegalArgumentException("Failed to set arg encoding (code = " + code + ")");
//		}
//
//		code = gsapi_set_display_callback(instanceRef.value, documentLoader.reset());
//		if (code != GS_ERROR_OK) {
//			gsapi_delete_instance(instanceRef.value);
//			throw new IllegalStateException("Failed to set display callback code=" + code);
//		}
//	}

	private static GSInstance initDocInstance() throws IllegalStateException {
		GSInstance instance = new GSInstance();

		int code;
		code = instance.set_arg_encoding(1);
		if (code != GS_ERROR_OK) {
			instance.delete_instance();
			throw new IllegalStateException("Failed to set arg encoding (code = " + code + ")");
		}

		code = instance.set_display_callback(documentLoader.reset());
		if (code != GS_ERROR_OK) {
			instance.delete_instance();
			throw new IllegalStateException("Failed to set display callback (code = " + code + ")");
		}

		return instance;
	}

	/**
	 * Class which handles loading a Document.
	 *
	 * @author Ethan Vrhel
	 *
	 */
	private static class DocumentLoader extends DisplayCallback {
		private int pageWidth, pageHeight, pageRaster;
		private BytePointer pimage;
		private List<BufferedImage> images;
		private int progress;
		private DocLoadProgressCallback callback;

		private DocumentLoader() {
			reset();
		}

		private DocumentLoader reset() {
			this.pageWidth = 0;
			this.pageHeight = 0;
			this.pageRaster = 0;
			this.pimage = null;
			this.images = new LinkedList<>();
			this.progress = 0;
			this.callback = null;
			return this;
		}

		@Override
		public int onDisplaySize(long handle, long device, int width, int height, int raster, int format,
				BytePointer pimage) {
			this.pageWidth = width;
			this.pageHeight = height;
			this.pageRaster = raster;
			this.pimage = pimage;
			return 0;
		}

		@Override
		public int onDisplayPage(long handle, long device, int copies, boolean flush) {
			byte[] data = (byte[]) pimage.toArrayNoConvert();
			images.add(ImageUtil.createImage(data, new ImageParams(pageWidth, pageHeight, pageRaster, BufferedImage.TYPE_3BYTE_BGR)));

			progress += (100 - progress) / 2;
			if (callback != null)
				callback.onDocumentProgress(progress);

			return 0;
		}
	}

	private File file;
	private List<Page> pages;

	/**
	 * Creates and loads a new document.
	 *
	 * @param file The file to load.
	 * @param loadCallback The callback to indicate when progress has occurred while loading.
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return, or <code>OPERATION_THROW</code> meaning the loader
	 * should throw an <code>OperationInProgressException</code>.
	 *
	 * @throws FileNotFoundException When <code>file</code> does not exist.
	 * @throws IllegalStateException When Ghostscript fails to initialize or load the document.
	 * @throws NullPointerException When <code>file</code> is <code>null</code>.
	 * @throws OperationInProgressException When an operation is already in progress
	 * and <code>operationMode</code> is <code>OPERATION_THROW</code>.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>OPERATION_WAIT</coded>, <code>OPERATION_RETURN</code>, or <code>OPERATION_THROW</code>.
	 */
	public Document(final File file, final DocLoadProgressCallback loadCallback, int operationMode)
			throws FileNotFoundException, IllegalStateException, NullPointerException,
			OperationInProgressException, IllegalArgumentException {
		this.file = Objects.requireNonNull(file, "file");
		if (!file.exists())
			throw new FileNotFoundException(file.getAbsolutePath());

		final String[] gargs = { "gs", "-dNOPAUSE", "-dSAFER", "-I%rom%Resource%/Init/", "-dBATCH", "-r" + Page.PAGE_LOW_DPI,
				"-sDEVICE=display", "-dDisplayFormat=" + format, "-f", file.getAbsolutePath() };

		if (!handleOperationMode(operationMode))
			return;

		startOperation();

		GSInstance instance = null;
		try {
			instance = initDocInstance();
		} catch (IllegalStateException e) {
			operationDone();
		}

		if (instance == null)
			throw new IllegalStateException("Failed to initialize Ghostscript");

		documentLoader.callback = loadCallback;

		int code = instance.init_with_args(gargs);
		instance.exit();
		instance.delete_instance();
		if (code != GS_ERROR_OK) {
			operationDone();
			throw new IllegalStateException("Failed to gsapi_init_with_args code=" + code);
		}

		this.pages = new ArrayList<>(documentLoader.images.size());
		for (BufferedImage img : documentLoader.images) {
			pages.add(new Page(img));
		}

		if (documentLoader.callback != null)
			documentLoader.callback.onDocumentProgress(100);

		operationDone();
	}

	/**
	 * Creates and loads a document from a filename.
	 *
	 * @param file The file to load.
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return, or <code>OPERATION_THROW</code> meaning the loader
	 * should throw an <code>OperationInProgressException</code>.
	 *
	 * @throws FileNotFoundException When <code>file</code> does not exist.
	 * @throws IllegalStateException When Ghostscript fails to initialize or load the document.
	 * @throws NullPointerException When <code>file</code> is <code>null</code>.
	 * @throws OperationInProgressException When an operation is already in progress
	 * and <code>operationMode</code> is <code>OPERATION_THROW</code>.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>OPERATION_WAIT</coded>, <code>OPERATION_RETURN</code>, or <code>OPERATION_THROW</code>.
	 */
	public Document(final File file, final int operationMode)
			throws FileNotFoundException, IllegalStateException, NullPointerException,
			OperationInProgressException {
		this(file, null, operationMode);
	}

	/**
	 * Creates and loads a document from a filename.
	 *
	 * @param filename The name of the file to load.
	 * @param loadCallback The callback to indicate when progress has occurred while loading.
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return, or <code>OPERATION_THROW</code> meaning the loader
	 * should throw an <code>OperationInProgressException</code>.
	 *
	 * @throws FileNotFoundException When <code>file</code> does not exist.
	 * @throws IllegalStateException When Ghostscript fails to initialize or load the document.
	 * @throws NullPointerException When <code>file</code> is <code>null</code>.
	 * @throws OperationInProgressException When an operation is already in progress
	 * and <code>operationMode</code> is <code>OPERATION_THROW</code>.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>OPERATION_WAIT</coded>, <code>OPERATION_RETURN</code>, or <code>OPERATION_THROW</code>.
	 */
	public Document(final String filename, final DocLoadProgressCallback loadCallback,
			final int operationMode)
			throws FileNotFoundException, IllegalStateException, NullPointerException,
			OperationInProgressException {
		this(new File(Objects.requireNonNull(filename, "filename")), loadCallback, operationMode);
	}

	/**
	 * Creates and loads a document from a filename.
	 *
	 * @param filename The name of the file to load.
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return, or <code>OPERATION_THROW</code> meaning the loader
	 * should throw an <code>OperationInProgressException</code>.
	 *
	 * @throws FileNotFoundException When <code>filename</code> does not exist.
	 * @throws IllegalStateException When Ghostscript fails to initialize or load the document.
	 * @throws NullPointerException When <code>filename</code> is <code>null</code>.
	 * @throws OperationInProgressException When an operation is already in progress
	 * and <code>operationMode</code> is <code>OPERATION_THROW</code>.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>OPERATION_WAIT</coded>, <code>OPERATION_RETURN</code>, or <code>OPERATION_THROW</code>.
	 */
	public Document(final String filename, final int operationMode)
			throws FileNotFoundException, IllegalStateException, NullPointerException,
			OperationInProgressException {
		this(filename, null, operationMode);
	}

	/**
	 * Loads the high resolution images in a range of images.
	 *
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return, or <code>OPERATION_THROW</code> meaning the loader
	 * should throw an <code>OperationInProgressException</code>.
	 * @param startPage The first page to load.
	 * @param endPage The end page to load.
	 *
	 * @throws IndexOutOfBoundsException When <code>firstPage</code> or <code>endPage</code>
	 * are not in the document or <code>endPage</code> is less than <code>firstPage</code>.
	 * @throws IllegalStateException When Ghostscript fails to initialize or load the document.
	 */
	public void loadHighRes(int operationMode, int startPage, int endPage)
			throws IndexOutOfBoundsException, IllegalStateException {
		checkBounds(startPage, endPage);

		if (!handleOperationMode(operationMode))
			return;

		startOperation();

		final String[] gargs = { "gs", "-dNOPAUSE", "-dSAFER", "-I%rom%Resource%/Init/",
				"-dBATCH", "-r" + Page.PAGE_HIGH_DPI, "-sDEVICE=display",
				"-dFirstPage=" + startPage, "-dLastPage=" + endPage, "-dDisplayFormat=" + format,
				"-dTextAlphaBits=4", "-dGraphicsAlphaBits=4",
				"-f", file.getAbsolutePath() };

		GSInstance instance = null;
		try {
			instance = initDocInstance();
		} catch (IllegalStateException e) {
			operationDone();
		}

		if (instance == null)
			throw new IllegalStateException("Failed to initialize Ghoscript");

		int code = instance.init_with_args(gargs);
		instance.exit();
		instance.delete_instance();
		if (code != GS_ERROR_OK) {
			operationDone();
			throw new IllegalStateException("Failed to gsapi_init_with_args code=" + code);
		}

		int ind = startPage - 1;
		for (final BufferedImage img : documentLoader.images) {
			this.pages.get(ind++).setHighRes(img);
		}

		operationDone();
	}

	/**
	 * Loads the high resolution image of a singular page.
	 *
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return, or <code>OPERATION_THROW</code> meaning the loader
	 * should throw an <code>OperationInProgressException</code>.
	 * @param page The page to load.
	 *
	 * @throws IndexOutOfBoundsException When <code>page</code> is not in the document.
	 * @throws IllegalStateException When Ghostscript fails to initialize or load the document.
	 * @throws OperationInProgressException When an operation is already in progress
	 * and <code>operationMode</code> is <code>OPERATION_THROW</code>.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>OPERATION_WAIT</coded>, <code>OPERATION_RETURN</code>, or <code>OPERATION_THROW</code>.
	 */
	public void loadHighRes(int operationMode, int page)
			throws IndexOutOfBoundsException, IllegalStateException, OperationInProgressException {
		loadHighRes(operationMode, page, page);
	}

	/**
	 * Loads the high resolution images of a list of pages.
	 *
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return, or <code>OPERATION_THROW</code> meaning the loader
	 * should throw an <code>OperationInProgressException</code>.
	 * @param pages The pages to load.
	 *
	 * @throws IndexOutOfBoundsException When any page is not a page in the document.
	 * @throws IllegalStateException When Ghostscript fails to initialize or load the document.
	 * @throws OperationInProgressException When an operation is already in progress
	 * and <code>operationMode</code> is <code>OPERATION_THROW</code>.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>OPERATION_WAIT</coded>, <code>OPERATION_RETURN</code>, or <code>OPERATION_THROW</code>.
	 */
	public void loadHighResList(int operationMode, final int[] pages)
			throws IndexOutOfBoundsException, IllegalStateException, OperationInProgressException {
		if (pages.length > 0) {
			if (!handleOperationMode(operationMode))
				return;

			try {
				startOperation();

				final StringBuilder builder = new StringBuilder();
				if (pages[0] < 1 || pages[0] > this.pages.size())
					throw new IndexOutOfBoundsException("page=" + pages[0]);
				builder.append(pages[0]);

				for (int i = 1; i < pages.length; i++) {
					if (pages[i] < 1 || pages[i] > this.pages.size())
						throw new IndexOutOfBoundsException("page=" + pages[i]);
					builder.append(',').append(pages[i]);
				}


				final String[] gargs = { "gs", "-dNOPAUSE", "-dSAFER", "-I%rom%Resource%/Init/", "-dBATCH", "-r" + Page.PAGE_HIGH_DPI,
						"-sDEVICE=display", "-sPageList=" + builder.toString(), "-dDisplayFormat=" + format,
						"-dTextAlphaBits=4", "-dGraphicsAlphaBits=4",
						"-f", file.getAbsolutePath() };

				GSInstance instance = null;
				try {
					instance = initDocInstance();
				} catch (IllegalStateException e) {
					operationDone();
				}

				if (instance == null)
					throw new IllegalStateException("Failed to initialize Ghoscript");

				int code = instance.init_with_args(gargs);
				instance.exit();
				instance.delete_instance();
				if (code != GS_ERROR_OK) {
					throw new IllegalStateException("Failed to gsapi_init_with_args code=" + code);
				}

				int ind = 0;
				for (final BufferedImage img : documentLoader.images) {
					this.pages.get(pages[ind] - 1).setHighRes(img);
				}
			} finally {
				operationDone();
			}
		}
	}

	/**
	 * Unloads the high resolution images in a range of pages.
	 *
	 * @param startPage The start page to unload the high resolution image from.
	 * @param endPage The end page to unload the high resolution image from.
	 *
	 * @throws IndexOutOfBoundsException When <code>startPage</code> and <code>endPage</code>
	 * are outside document or <code>endPage</code> is less than <code>startPage</code>.
	 */
	public void unloadHighRes(int startPage, int endPage) throws IndexOutOfBoundsException {
		checkBounds(startPage, endPage);
		for (int i = startPage - 1; i < endPage; i++) {
			pages.get(i).unloadHighRes();
		}
	}

	/**
	 * Unloads a high resolution image at the given page.
	 *
	 * @param page The page to unload the high resolution image.
	 *
	 * @throws IndexOutOfBoundsException When page is not a page in the document.
	 */
	public void unloadHighRes(int page) throws IndexOutOfBoundsException {
		unloadHighRes(page, page);
	}

	/**
	 * Unloads the zoomed images for a range of pages.
	 *
	 * @param startPage The start page to unload.
	 * @param endPage The end page to unload.
	 *
	 * @throws IndexOutOfBoundsException When <code>startPage</code> and <code>endPage</code>
	 * are outside document or <code>endPage</code> is less than <code>startPage</code>.
	 */
	public void unloadZoomed(int startPage, int endPage) throws IndexOutOfBoundsException {
		checkBounds(startPage, endPage);
		for (int i = startPage; i <= endPage; i++) {
			pages.get(i).unloadZoomed();
		}
	}

	/**
	 * Unloads a zoomed image for a page.
	 *
	 * @param page The page to unload.
	 *
	 * @throws IndexOutOfBoundsException When <code>page</code> is not in the document.
	 */
	public void unloadZoomed(int page) throws IndexOutOfBoundsException {
		unloadZoomed(page, page);
	}

	/**
	 * Unloads the document's resources. The document will be unusable after this
	 * call.
	 */
	public void unload() {
		for (Page p : pages) {
			p.unloadAll();
		}
		pages.clear();
	}

	/**
	 * Returns the name of the document loaded.
	 *
	 * @return The name.
	 */
	public String getName() {
		return file.getName();
	}

	/**
	 * Zooms the area around page <code>page</code>. The area around <code>page</code>
	 * is <code>page - 1</code> to <code>page + 1</code>. The method will automatically
	 * handle if <code>page - 1</code> or <code>page + 1</code> are out of range. However,
	 * it does not handle if <code>page</code> is not in the document.
	 *
	 * @param operationMode How the loader should behave if an operation is already in
	 * progress. Can be <code>OPERATION_WAIT</code>, meaning the loader should
	 * wait until a running operation has finished, <code>OPERATION_RETURN</code> meaning
	 * the loader should immediately return, or <code>OPERATION_THROW</code> meaning the loader
	 * should throw an <code>OperationInProgressException</code>.
	 * @param page The page to load around.
	 * @param zoom The zoom of the pages.
	 *
	 * @throws IndexOutOfBoundsException When <code>page</code> is not in the document.
	 * @throws IllegalStateException When Ghostscript fails to initialize or load the document.
	 * @throws OperationInProgressException When an operation is already in progress
	 * and <code>operationMode</code> is <code>OPERATION_THROW</code>.
	 * @throws IllegalArgumentException When <code>operationMode</code> is not
	 * <code>OPERATION_WAIT</coded>, <code>OPERATION_RETURN</code>, or <code>OPERATION_THROW</code>.
	 */
	public void zoomArea(final int operationMode, final int page, final double zoom)
		throws IndexOutOfBoundsException {
		checkBounds(page, page);

		if (!handleOperationMode(operationMode))
			return;

		try {
			startOperation();

			int start = page - 1;
			start = start < 1 ? page : start;
			int end = page + 1;
			end = end > pages.size() ? page : end;

			final String[] gargs = {
					"gs", "-dNOPAUSE", "-dSAFER", "-I%rom%Resource%/Init/",
					"-dBATCH", "-r" + (int)(Page.PAGE_HIGH_DPI * zoom),
					"-sDEVICE=display", "-dFirstPage=" + start, "-dLastPage=" + end,
					"-dDisplayFormat=" + format,
					"-dTextAlphaBits=4", "-dGraphicsAlphaBits=4",
					"-f", file.getAbsolutePath() };

			GSInstance instance = null;
			try {
				instance = initDocInstance();
			} catch (IllegalStateException e) {
				operationDone();
			}

			if (instance == null)
				throw new IllegalStateException("Failed to initialize Ghoscript");

			int code = instance.init_with_args(gargs);
			instance.exit();
			instance.delete_instance();
			if (code != GS_ERROR_OK) {
				operationDone();
				throw new IllegalStateException("Failed to gsapi_init_with_args code=" + code);
			}

			int ind = start - 1;
			for (final BufferedImage img : documentLoader.images) {
				this.pages.get(ind++).setZoomed(img);
			}
		} finally {
			operationDone();
		}
	}

	/**
	 * Checks to make sure the pages <code>start</code> through
	 * <code>end</code> are in the document, and throws an
	 * <code>IndexOutOfBoundsException</code> if they are not.
	 *
	 * @param start The start page.
	 * @param end The end page.
	 * @throws IndexOutOfBoundsException When <code>startPage</code> and <code>endPage</code>
	 * are outside document or <code>endPage</code> is less than <code>startPage</code>.
	 */
	private void checkBounds(int start, int end) throws IndexOutOfBoundsException {
		if (start < 1 || start > pages.size())
			throw new IndexOutOfBoundsException("start=" + start);
		if (end < 1 || end > pages.size())
			throw new IndexOutOfBoundsException("end=" + end);
		if (end < start)
			throw new IndexOutOfBoundsException("end < start");
	}

	// Implementations of inherited methods from java.util.List.

	@Override
	public int size() {
		return pages.size();
	}

	@Override
	public boolean isEmpty() {
		return pages.isEmpty();
	}

	@Override
	public boolean contains(Object o) {
		return pages.contains(o);
	}

	@Override
	public Iterator<Page> iterator() {
		return pages.iterator();
	}

	@Override
	public Object[] toArray() {
		return pages.toArray();
	}

	@Override
	public <T> T[] toArray(T[] a) {
		return pages.toArray(a);
	}

	@Override
	public boolean add(Page e) {
		return pages.add(e);
	}

	@Override
	public boolean remove(Object o) {
		return pages.remove(o);
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return pages.containsAll(c);
	}

	@Override
	public boolean addAll(Collection<? extends Page> c) {
		return pages.addAll(c);
	}

	@Override
	public boolean addAll(int index, Collection<? extends Page> c) {
		return pages.addAll(index, c);
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		return pages.removeAll(c);
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		return pages.retainAll(c);
	}

	@Override
	public void clear() {
		pages.clear();
	}

	@Override
	public Page get(int index) {
		return pages.get(index);
	}

	@Override
	public Page set(int index, Page element) {
		return pages.set(index, element);
	}

	@Override
	public void add(int index, Page element) {
		pages.add(index, element);
	}

	@Override
	public Page remove(int index) {
		return pages.remove(index);
	}

	@Override
	public int indexOf(Object o) {
		return pages.indexOf(o);
	}

	@Override
	public int lastIndexOf(Object o) {
		return pages.lastIndexOf(o);
	}

	@Override
	public ListIterator<Page> listIterator() {
		return pages.listIterator();
	}

	@Override
	public ListIterator<Page> listIterator(int index) {
		return pages.listIterator(index);
	}

	@Override
	public List<Page> subList(int fromIndex, int toIndex) {
		return pages.subList(fromIndex, toIndex);
	}

	@Override
	public String toString() {
		return "Document[numPages=" + size() + "]";
	}

	@Override
	public boolean equals(Object o) {
		if (o == this)
			return true;
		if (o instanceof Document) {
			return pages.equals(((Document)o).pages);
		}
		return false;
	}

	@Override
	public int hashCode() {
		return pages.hashCode();
	}

	@Override
	public void finalize() {
		unload();
	}
}