-
Notifications
You must be signed in to change notification settings - Fork 0
/
DrawingPanel.java
3085 lines (2690 loc) · 116 KB
/
DrawingPanel.java
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
992
993
994
995
996
997
998
999
1000
/**
The DrawingPanel class provides a simple interface for drawing persistent
images using a Graphics object. An internal BufferedImage object is used
to keep track of what has been drawn. A client of the class simply
constructs a DrawingPanel of a particular size and then draws on it with
the Graphics object, setting the background color if they so choose.
<p>
To ensure that the image is always displayed, a timer calls repaint at
regular intervals.
<p>
This version of DrawingPanel also saves animated GIFs, though this is kind
of hit-and-miss because animated GIFs are pretty sucky (256 color limit, large
file size, etc).
<p>
Recent features:
- save zoomed images (2011/10/25)
- window no longer moves when zoom changes (2011/10/25)
- grid lines (2011/10/11)
@author Marty Stepp
@version October 21, 2011
*/
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.Exception;
import java.lang.Integer;
import java.lang.InterruptedException;
import java.lang.Math;
import java.lang.Object;
import java.lang.OutOfMemoryError;
import java.lang.SecurityException;
import java.lang.String;
import java.lang.System;
import java.lang.Thread;
import java.net.URL;
import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MouseInputListener;
import javax.swing.filechooser.FileFilter;
public final class DrawingPanel extends FileFilter
implements ActionListener, MouseMotionListener, Runnable, WindowListener {
// inner class to represent one frame of an animated GIF
private static class ImageFrame {
public Image image;
public int delay;
public ImageFrame(Image image, int delay) {
this.image = image;
this.delay = delay / 10; // strangely, gif stores delay as sec/100
}
}
// class constants
public static final String ANIMATED_PROPERTY = "drawingpanel.animated";
public static final String AUTO_ENABLE_ANIMATION_ON_SLEEP_PROPERTY = "drawingpanel.animateonsleep";
public static final String DIFF_PROPERTY = "drawingpanel.diff";
public static final String HEADLESS_PROPERTY = "drawingpanel.headless";
public static final String MULTIPLE_PROPERTY = "drawingpanel.multiple";
public static final String SAVE_PROPERTY = "drawingpanel.save";
public static final String ANIMATION_FILE_NAME = "_drawingpanel_animation_save.txt";
private static final String TITLE = "Drawing Panel";
private static final String COURSE_WEB_SITE = "http://www.cs.washington.edu/education/courses/cse142/12sp/drawingpanel.txt";
private static final Color GRID_LINE_COLOR = new Color(64, 64, 64, 128);
private static final int GRID_SIZE = 10; // 10px between grid lines
private static final int DELAY = 100; // delay between repaints in millis
private static final int MAX_FRAMES = 100; // max animation frames
private static final int MAX_SIZE = 10000; // max width/height
private static final boolean DEBUG = false;
private static final boolean SAVE_SCALED_IMAGES = true; // if true, when panel is zoomed, saves images at that zoom factor
private static int instances = 0;
private static Thread shutdownThread = null;
private static void checkAnimationSettings() {
try {
File settingsFile = new File(ANIMATION_FILE_NAME);
if (settingsFile.exists()) {
Scanner input = new Scanner(settingsFile);
String animationSaveFileName = input.nextLine();
input.close();
// *** TODO: delete the file
System.out.println("***");
System.out.println("*** DrawingPanel saving animated GIF: " +
new File(animationSaveFileName).getName());
System.out.println("***");
settingsFile.delete();
System.setProperty(ANIMATED_PROPERTY, "1");
System.setProperty(SAVE_PROPERTY, animationSaveFileName);
}
} catch (Exception e) {
if (DEBUG) {
System.out.println("error checking animation settings: " + e);
}
}
}
private static boolean hasProperty(String name) {
try {
return System.getProperty(name) != null;
} catch (SecurityException e) {
if (DEBUG) System.out.println("Security exception when trying to read " + name);
return false;
}
}
private static boolean propertyIsTrue(String name) {
try {
String prop = System.getProperty(name);
return prop != null && (prop.equalsIgnoreCase("true") || prop.equalsIgnoreCase("yes") || prop.equalsIgnoreCase("1"));
} catch (SecurityException e) {
if (DEBUG) System.out.println("Security exception when trying to read " + name);
return false;
}
}
/*
private static boolean propertyIsFalse(String name) {
try {
String prop = System.getProperty(name);
return prop != null && (prop.equalsIgnoreCase("false") || prop.equalsIgnoreCase("no") || prop.equalsIgnoreCase("0"));
} catch (SecurityException e) {
if (DEBUG) System.out.println("Security exception when trying to read " + name);
return false;
}
}
*/
// Returns whether the 'main' thread is still running.
private static boolean mainIsActive() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
int activeCount = group.activeCount();
// look for the main thread in the current thread group
Thread[] threads = new Thread[activeCount];
group.enumerate(threads);
for (int i = 0; i < threads.length; i++) {
Thread thread = threads[i];
String name = ("" + thread.getName()).toLowerCase();
if (name.indexOf("main") >= 0 ||
name.indexOf("testrunner-assignmentrunner") >= 0) {
// found main thread!
// (TestRunnerApplet's main runner also counts as "main" thread)
return thread.isAlive();
}
}
// didn't find a running main thread; guess that main is done running
return false;
}
private static boolean usingDrJava() {
try {
return System.getProperty("drjava.debug.port") != null ||
System.getProperty("java.class.path").toLowerCase().indexOf("drjava") >= 0;
} catch (SecurityException e) {
// running as an applet, or something
return false;
}
}
private class ImagePanel extends JPanel {
private static final long serialVersionUID = 0;
private Image image;
public ImagePanel(Image image) {
setImage(image);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(image.getWidth(this), image.getHeight(this)));
setAlignmentX(0.0f);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (currentZoom != 1) {
g2.scale(currentZoom, currentZoom);
}
g2.drawImage(image, 0, 0, this);
// possibly draw grid lines for debugging
if (gridLines) {
g2.setPaint(GRID_LINE_COLOR);
for (int row = 1; row <= getHeight() / GRID_SIZE; row++) {
g2.drawLine(0, row * GRID_SIZE, getWidth(), row * GRID_SIZE);
}
for (int col = 1; col <= getWidth() / GRID_SIZE; col++) {
g2.drawLine(col * GRID_SIZE, 0, col * GRID_SIZE, getHeight());
}
}
}
public void setImage(Image image) {
this.image = image;
repaint();
}
}
// fields
private int width, height; // dimensions of window frame
private JFrame frame; // overall window frame
private JPanel panel; // overall drawing surface
private ImagePanel imagePanel; // real drawing surface
private BufferedImage image; // remembers drawing commands
private Graphics2D g2; // graphics context for painting
private JLabel statusBar; // status bar showing mouse position
private JFileChooser chooser; // file chooser to save files
private long createTime; // time at which DrawingPanel was constructed
private Timer timer; // animation timer
private ArrayList<ImageFrame> frames; // stores frames of animation to save
private Gif89Encoder encoder;
// private FileOutputStream stream;
private Color backgroundColor = Color.WHITE;
private String callingClassName; // name of class that constructed this panel
private boolean animated = false; // changes to true if sleep() is called
private boolean PRETTY = true; // true to anti-alias
private boolean gridLines = false;
private int instanceNumber;
private int currentZoom = 1;
private int initialPixel; // initial value in each pixel, for clear()
// construct a drawing panel of given width and height enclosed in a window
public DrawingPanel(int width, int height) {
if (width < 0 || width > MAX_SIZE || height < 0 || height > MAX_SIZE) {
throw new IllegalArgumentException("Illegal width/height: " + width + " x " + height);
}
checkAnimationSettings();
synchronized (getClass()) {
instances++;
instanceNumber = instances; // each DrawingPanel stores its own int number
if (shutdownThread == null && !usingDrJava()) {
shutdownThread = new Thread(new Runnable() {
// Runnable implementation; used for shutdown thread.
public void run() {
try {
while (true) {
// maybe shut down the program, if no more DrawingPanels are onscreen
// and main has finished executing
if ((instances == 0 || shouldSave()) && !mainIsActive()) {
try {
System.exit(0);
} catch (SecurityException sex) {}
}
Thread.sleep(250);
}
} catch (Exception e) {}
}
});
shutdownThread.setPriority(Thread.MIN_PRIORITY);
shutdownThread.start();
}
}
this.width = width;
this.height = height;
if (DEBUG) System.out.println("w=" + width + ",h=" + height + ",anim=" + isAnimated() + ",graph=" + isGraphical() + ",save=" + shouldSave());
if (isAnimated() && shouldSave()) {
// image must be no more than 256 colors
image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
// image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
PRETTY = false; // turn off anti-aliasing to save palette colors
// initially fill the entire frame with the background color,
// because it won't show through via transparency like with a full ARGB image
Graphics g = image.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, width + 1, height + 1);
} else {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
initialPixel = image.getRGB(0, 0);
g2 = (Graphics2D) image.getGraphics();
g2.setColor(Color.BLACK);
if (PRETTY) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
if (isAnimated()) {
initializeAnimation();
}
if (isGraphical()) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {}
statusBar = new JLabel(" ");
statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.setBackground(backgroundColor);
panel.setPreferredSize(new Dimension(width, height));
imagePanel = new ImagePanel(image);
imagePanel.setBackground(backgroundColor);
panel.add(imagePanel);
// listen to mouse movement
panel.addMouseMotionListener(this);
// main window frame
frame = new JFrame(TITLE);
// frame.setResizable(false);
frame.addWindowListener(this);
// JPanel center = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
JScrollPane center = new JScrollPane(panel);
// center.add(panel);
frame.getContentPane().add(center);
frame.getContentPane().add(statusBar, "South");
frame.setBackground(Color.DARK_GRAY);
// menu bar
setupMenuBar();
frame.pack();
center(frame);
frame.setVisible(true);
if (!shouldSave()) {
toFront(frame);
}
// repaint timer so that the screen will update
createTime = System.currentTimeMillis();
timer = new Timer(DELAY, this);
timer.start();
} else if (shouldSave()) {
// headless mode; just set a hook on shutdown to save the image
callingClassName = getCallingClassName();
try {
Runtime.getRuntime().addShutdownHook(new Thread(this));
} catch (Exception e) {
if (DEBUG) System.out.println("unable to add shutdown hook: " + e);
}
}
//System.out.println("DrawingPanel constructor, image panel = " + imagePanel);
}
// method of FileFilter interface
public boolean accept(File file) {
return file.isDirectory() ||
(file.getName().toLowerCase().endsWith(".png") ||
file.getName().toLowerCase().endsWith(".gif"));
}
// used for an internal timer that keeps repainting
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Timer) {
// redraw the screen at regular intervals to catch all paint operations
panel.repaint();
if (shouldDiff() &&
System.currentTimeMillis() > createTime + 4 * DELAY) {
String expected = System.getProperty(DIFF_PROPERTY);
try {
String actual = saveToTempFile();
DiffImage diff = new DiffImage(expected, actual);
diff.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} catch (IOException ioe) {
System.err.println("Error diffing image: " + ioe);
}
timer.stop();
} else if (shouldSave() && readyToClose()) {
// auto-save-and-close if desired
try {
if (isAnimated()) {
saveAnimated(System.getProperty(SAVE_PROPERTY));
} else {
save(System.getProperty(SAVE_PROPERTY));
}
} catch (IOException ioe) {
System.err.println("Error saving image: " + ioe);
}
exit();
}
} else if (e.getActionCommand().equals("Exit")) {
exit();
} else if (e.getActionCommand().equals("Compare to File...")) {
compareToFile();
} else if (e.getActionCommand().equals("Compare to Web File...")) {
new Thread(new Runnable() {
public void run() {
compareToURL();
}
}).start();
} else if (e.getActionCommand().equals("Save As...")) {
saveAs();
} else if (e.getActionCommand().equals("Save Animated GIF...")) {
saveAsAnimated();
} else if (e.getActionCommand().equals("Zoom In")) {
zoom(currentZoom + 1);
} else if (e.getActionCommand().equals("Zoom Out")) {
zoom(currentZoom - 1);
} else if (e.getActionCommand().equals("Zoom Normal (100%)")) {
zoom(1);
} else if (e.getActionCommand().equals("Grid Lines")) {
setGridLines(((JCheckBoxMenuItem) e.getSource()).isSelected());
} else if (e.getActionCommand().equals("About...")) {
JOptionPane.showMessageDialog(frame,
"DrawingPanel\n" +
"Graphical library class to support Building Java Programs textbook\n" +
"written by Marty Stepp and Stuart Reges\n" +
"University of Washington\n\n" +
"please visit our web site at:\n" +
"http://www.buildingjavaprograms.com/",
"About DrawingPanel",
JOptionPane.INFORMATION_MESSAGE);
}
}
public void addMouseListener(MouseInputListener listener) {
panel.addMouseListener(listener);
if (listener instanceof MouseMotionListener) {
panel.addMouseMotionListener((MouseMotionListener) listener);
}
}
// erases all drawn shapes/lines/colors from the panel
public void clear() {
int[] pixels = new int[width * height];
for (int i = 0; i < pixels.length; i++) {
pixels[i] = initialPixel;
}
image.setRGB(0, 0, width, height, pixels, 0, 1);
}
// method of FileFilter interface
public String getDescription() {
return "Image files (*.png; *.gif)";
}
// obtain the Graphics object to draw on the panel
public Graphics2D getGraphics() {
return g2;
}
// returns the drawing panel's width in pixels
public int getHeight() {
return height;
}
// returns the drawing panel's pixel size (width, height) as a Dimension object
public Dimension getSize() {
return new Dimension(width, height);
}
// returns the drawing panel's width in pixels
public int getWidth() {
return width;
}
// returns panel's current zoom factor
public int getZoom() {
return currentZoom;
}
// listens to mouse dragging
public void mouseDragged(MouseEvent e) {}
// listens to mouse movement
public void mouseMoved(MouseEvent e) {
int x = e.getX() / currentZoom;
int y = e.getY() / currentZoom;
setStatusBarText("(" + x + ", " + y + ")");
}
// run on shutdown to save the image
public void run() {
if (DEBUG) System.out.println("Running shutdown hook");
try {
String filename = System.getProperty(SAVE_PROPERTY);
if (filename == null) {
filename = callingClassName + ".png";
}
if (isAnimated()) {
saveAnimated(filename);
} else {
save(filename);
}
} catch (SecurityException e) {
} catch (IOException e) {
System.err.println("Error saving image: " + e);
}
}
// take the current contents of the panel and write them to a file
public void save(String filename) throws IOException {
BufferedImage image2 = getImage();
// if zoomed, scale image before saving it
if (SAVE_SCALED_IMAGES && currentZoom != 1) {
BufferedImage zoomedImage = new BufferedImage(width * currentZoom, height * currentZoom, image.getType());
Graphics2D g = (Graphics2D) zoomedImage.getGraphics();
g.setColor(Color.BLACK);
if (PRETTY) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
g.scale(currentZoom, currentZoom);
g.drawImage(image2, 0, 0, imagePanel);
image2 = zoomedImage;
}
// if saving multiple panels, append number
// (e.g. output_*.png becomes output_1.png, output_2.png, etc.)
if (isMultiple()) {
filename = filename.replaceAll("\\*", String.valueOf(instanceNumber));
}
int lastDot = filename.lastIndexOf(".");
String extension = filename.substring(lastDot + 1);
// write file
// TODO: doesn't save background color I don't think
ImageIO.write(image2, extension, new File(filename));
}
// take the current contents of the panel and write them to a file
public void saveAnimated(String filename) throws IOException {
// add one more final frame
if (DEBUG) System.out.println("saveAnimated(" + filename + ")");
frames.add(new ImageFrame(getImage(), 5000));
// encoder.continueEncoding(stream, getImage(), 5000);
// Gif89Encoder gifenc = new Gif89Encoder();
// add each frame of animation to the encoder
try {
for (int i = 0; i < frames.size(); i++) {
ImageFrame imageFrame = frames.get(i);
encoder.addFrame(imageFrame.image);
encoder.getFrameAt(i).setDelay(imageFrame.delay);
imageFrame.image.flush();
frames.set(i, null);
}
} catch (OutOfMemoryError e) {
System.out.println("Out of memory when saving");
}
// gifenc.setComments(annotation);
// gifenc.setUniformDelay((int) Math.round(100 / frames_per_second));
// gifenc.setUniformDelay(DELAY);
// encoder.setBackground(backgroundColor);
encoder.setLoopCount(0);
encoder.encode(new FileOutputStream(filename));
}
// set the background color of the drawing panel
public void setBackground(Color c) {
Color oldBackgroundColor = backgroundColor;
backgroundColor = c;
if (isGraphical()) {
panel.setBackground(c);
imagePanel.setBackground(c);
}
// with animated images, need to palette-swap the old bg color for the new
// because there's no notion of transparency in a palettized 8-bit image
if (isAnimated()) {
replaceColor(image, oldBackgroundColor, c);
}
}
// Enables or disables the drawing of grid lines on top of the image to help
// with debugging sizes and coordinates.
public void setGridLines(boolean gridLines) {
this.gridLines = gridLines;
imagePanel.repaint();
}
// sets the drawing panel's height in pixels to the given value
// After calling this method, the client must call getGraphics() again
// to get the new graphics context of the newly enlarged image buffer.
public void setHeight(int height) {
setSize(getWidth(), height);
}
// sets the drawing panel's pixel size (width, height) to the given values
// After calling this method, the client must call getGraphics() again
// to get the new graphics context of the newly enlarged image buffer.
public void setSize(int width, int height) {
// replace the image buffer for drawing
BufferedImage newImage = new BufferedImage(width, height, image.getType());
this.width = width;
this.height = height;
image = newImage;
g2 = (Graphics2D) newImage.getGraphics();
g2.setColor(Color.BLACK);
if (PRETTY) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
if (isGraphical()) {
imagePanel.setImage(newImage);
newImage.getGraphics().drawImage(image, 0, 0, imagePanel);
zoom(currentZoom);
frame.pack();
} else {
zoom(currentZoom);
}
}
// show or hide the drawing panel on the screen
public void setVisible(boolean visible) {
if (isGraphical()) {
frame.setVisible(visible);
}
}
// sets the drawing panel's width in pixels to the given value
// After calling this method, the client must call getGraphics() again
// to get the new graphics context of the newly enlarged image buffer.
public void setWidth(int width) {
setSize(width, getHeight());
}
// makes the program pause for the given amount of time,
// allowing for animation
public void sleep(int millis) {
if (isGraphical() && frame.isVisible()) {
// if not even displaying, we don't actually need to sleep
if (millis > 0) {
try {
Thread.sleep(millis);
panel.repaint();
toFront(frame);
} catch (Exception e) {}
}
}
// manually enable animation if necessary
if (!isAnimated() && !isMultiple() && autoEnableAnimationOnSleep()) {
animated = true;
initializeAnimation();
}
// capture a frame of animation
if (isAnimated() && shouldSave() && !isMultiple()) {
try {
if (frames.size() < MAX_FRAMES) {
frames.add(new ImageFrame(getImage(), millis));
}
// reset creation timer so that we won't save/close just yet
createTime = System.currentTimeMillis();
} catch (OutOfMemoryError e) {
System.out.println("Out of memory after capturing " + frames.size() + " frames");
}
}
}
// moves window on top of other windows
public void toFront() {
toFront(frame);
}
// called when DrawingPanel closes, to potentially exit the program
public void windowClosing(WindowEvent event) {
frame.setVisible(false);
synchronized (getClass()) {
instances--;
}
frame.dispose();
}
// methods required by WindowListener interface
public void windowActivated(WindowEvent event) {}
public void windowClosed(WindowEvent event) {}
public void windowDeactivated(WindowEvent event) {}
public void windowDeiconified(WindowEvent event) {}
public void windowIconified(WindowEvent event) {}
public void windowOpened(WindowEvent event) {}
// zooms the drawing panel in/out to the given factor
// factor should be >= 1
public void zoom(int zoomFactor) {
currentZoom = Math.max(1, zoomFactor);
if (isGraphical()) {
Dimension size = new Dimension(width * currentZoom, height * currentZoom);
imagePanel.setPreferredSize(size);
panel.setPreferredSize(size);
imagePanel.validate();
imagePanel.revalidate();
panel.validate();
panel.revalidate();
// imagePanel.setSize(size);
frame.getContentPane().validate();
imagePanel.repaint();
setStatusBarText(" ");
// resize frame if any more space for it exists or it's the wrong size
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
if (size.width <= screen.width || size.height <= screen.height) {
frame.pack();
}
// if (size.width <= screen.width && size.height <= screen.height) {
// frame.pack();
// center(frame);
// }
}
}
// moves given jframe to center of screen
private void center(Window frame) {
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screen = tk.getScreenSize();
int x = Math.max(0, (screen.width - frame.getWidth()) / 2);
int y = Math.max(0, (screen.height - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
// constructs and initializes JFileChooser object if necessary
private void checkChooser() {
if (chooser == null) {
// TODO: fix security on applet mode
chooser = new JFileChooser(System.getProperty("user.dir"));
chooser.setMultiSelectionEnabled(false);
chooser.setFileFilter(this);
}
}
// compares current DrawingPanel image to an image file on disk
private void compareToFile() {
// save current image to a temp file
try {
String tempFile = saveToTempFile();
// use file chooser dialog to find image to compare against
checkChooser();
if (chooser.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION) {
return;
}
// user chose a file; let's diff it
new DiffImage(chooser.getSelectedFile().toString(), tempFile);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(frame,
"Unable to compare images: \n" + ioe);
}
}
// compares current DrawingPanel image to an image file on the web
private void compareToURL() {
// save current image to a temp file
try {
String tempFile = saveToTempFile();
// get list of images to compare against from web site
URL url = new URL(COURSE_WEB_SITE);
Scanner input = new Scanner(url.openStream());
List<String> lines = new ArrayList<String>();
List<String> filenames = new ArrayList<String>();
while (input.hasNextLine()) {
String line = input.nextLine().trim();
if (line.length() == 0) { continue; }
if (line.startsWith("#")) {
// a comment
if (line.endsWith(":")) {
// category label
lines.add(line);
line = line.replaceAll("#\\s*", "");
filenames.add(line);
}
} else {
lines.add(line);
// get filename
int lastSlash = line.lastIndexOf('/');
if (lastSlash >= 0) {
line = line.substring(lastSlash + 1);
}
// remove extension
int dot = line.lastIndexOf('.');
if (dot >= 0) {
line = line.substring(0, dot);
}
filenames.add(line);
}
}
if (filenames.isEmpty()) {
JOptionPane.showMessageDialog(frame,
"No valid web files found to compare against.",
"Error: no web files found",
JOptionPane.ERROR_MESSAGE);
return;
} else {
String fileURL = null;
if (filenames.size() == 1) {
// only one choice; take it
fileURL = lines.get(0);
} else {
// user chooses file to compare against
int choice = showOptionDialog(frame, "File to compare against?",
"Choose File", filenames.toArray(new String[0]));
if (choice < 0) {
return;
}
// user chose a file; let's diff it
fileURL = lines.get(choice);
}
if (DEBUG) System.out.println(fileURL);
new DiffImage(fileURL, tempFile);
}
} catch (NoRouteToHostException nrthe) {
JOptionPane.showMessageDialog(frame, "You do not appear to have a working internet connection.\nPlease check your internet settings and try again.\n\n" + nrthe);
} catch (UnknownHostException uhe) {
JOptionPane.showMessageDialog(frame, "Internet connection error: \n" + uhe);
} catch (SocketException se) {
JOptionPane.showMessageDialog(frame, "Internet connection error: \n" + se);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(frame, "Unable to compare images: \n" + ioe);
}
}
// closes the frame and exits the program
private void exit() {
if (isGraphical()) {
frame.setVisible(false);
frame.dispose();
}
try {
System.exit(0);
} catch (SecurityException e) {
// if we're running in an applet or something, can't do System.exit
}
}
// returns a best guess about the name of the class that constructed this panel
private String getCallingClassName() {
StackTraceElement[] stack = new RuntimeException().getStackTrace();
String className = this.getClass().getName();
for (StackTraceElement element : stack) {
String cl = element.getClassName();
if (!className.equals(cl)) {
className = cl;
break;
}
}
return className;
}
private BufferedImage getImage() {
// create second image so we get the background color
BufferedImage image2;
if (isAnimated()) {
image2 = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
} else {
image2 = new BufferedImage(width, height, image.getType());
}
Graphics g = image2.getGraphics();
if (DEBUG) System.out.println("getImage setting background to " + backgroundColor);
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);
g.drawImage(image, 0, 0, panel);
return image2;
}
private void initializeAnimation() {
frames = new ArrayList<ImageFrame>();
encoder = new Gif89Encoder();
/*
try {
if (hasProperty(SAVE_PROPERTY)) {
stream = new FileOutputStream(System.getProperty(SAVE_PROPERTY));
}
// encoder.startEncoding(stream);
} catch (IOException e) {
System.out.println(e);
}
*/
}
private boolean autoEnableAnimationOnSleep() {
return propertyIsTrue(AUTO_ENABLE_ANIMATION_ON_SLEEP_PROPERTY);
}
private boolean isAnimated() {
return animated || propertyIsTrue(ANIMATED_PROPERTY);
}
private boolean isGraphical() {
return !hasProperty(SAVE_PROPERTY) && !hasProperty(HEADLESS_PROPERTY);
}
private boolean isMultiple() {
return propertyIsTrue(MULTIPLE_PROPERTY);
}
private boolean readyToClose() {
/*
if (isAnimated()) {
// wait a little longer, in case animation is sleeping
return System.currentTimeMillis() > createTime + 5 * DELAY;
} else {
return System.currentTimeMillis() > createTime + 4 * DELAY;
}
*/
return (instances == 0 || shouldSave()) && !mainIsActive();
}
private void replaceColor(BufferedImage image, Color oldColor, Color newColor) {
int oldRGB = oldColor.getRGB();
int newRGB = newColor.getRGB();
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
if (image.getRGB(x, y) == oldRGB) {
image.setRGB(x, y, newRGB);
}
}
}
}
// called when user presses "Save As" menu item
private void saveAs() {
String filename = saveAsHelper("png");
if (filename != null) {
try {
save(filename); // save the file
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, "Unable to save image:\n" + ex);
}
}
}