-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathPSurfaceAWT.java
More file actions
1393 lines (1161 loc) · 46.4 KB
/
PSurfaceAWT.java
File metadata and controls
1393 lines (1161 loc) · 46.4 KB
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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2014-23 The Processing Foundation
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, version 2.1.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.awt;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PSurfaceNone;
import processing.event.Event;
import processing.event.KeyEvent;
import processing.event.MouseEvent;
public class PSurfaceAWT extends PSurfaceNone {
GraphicsDevice displayDevice;
// used for canvas to determine whether resizable or not
// boolean resizable; // default is false
// Internally, we know it's always a JFrame (not just a Frame)
// JFrame frame;
// Trying Frame again with a11 to see if this avoids some Swing nastiness.
// In the past, AWT Frames caused some problems on Windows and Linux,
// but those may not be a problem for our reworked PSurfaceAWT class.
JFrame frame;
// Note that x and y may not be zero, depending on the display configuration
Rectangle screenRect;
// Used for resizing, at least on Windows insets size changes when
// frame.setResizable() is called, and in resize listener we need
// to know what size the window was before.
Insets currentInsets = new Insets(0, 0, 0, 0);
// 3.0a5 didn't use strategy, and active was shut off during init() w/ retina
// boolean useStrategy = true;
Canvas canvas;
// Component canvas;
// PGraphics graphics; // moved to PSurfaceNone
int sketchWidth;
int sketchHeight;
// int windowScaleFactor;
final int windowScaleFactor = 1;
public PSurfaceAWT(PGraphics graphics) {
//this.graphics = graphics;
super(graphics);
/*
if (checkRetina()) {
// System.out.println("retina in use");
// The active-mode rendering seems to be 2x slower, so disable it
// with retina. On a non-retina machine, however, useActive seems
// the only (or best) way to handle the rendering.
// useActive = false;
// canvas = new JPanel(true) {
// @Override
// public void paint(Graphics screen) {
//// if (!sketch.insideDraw) {
// screen.drawImage(PSurfaceAWT.this.graphics.image, 0, 0, sketchWidth, sketchHeight, null);
//// }
// }
// };
// Under 1.8 and the current 3.0a6 threading regime, active mode w/o
// strategy is far faster, but perhaps only because it's blitting with
// flicker--pushing pixels out before the screen has finished rendering.
// useStrategy = false;
}
*/
canvas = new SmoothCanvas();
// if (useStrategy) {
//canvas.setIgnoreRepaint(true);
// }
// Pass tab key to the sketch, rather than moving between components
canvas.setFocusTraversalKeysEnabled(false);
canvas.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
if (!sketch.isLooping()) {
// make sure this is a real resize event, not just initial setup
// https://github.com/processing/processing/issues/3310
Dimension canvasSize = canvas.getSize();
if (canvasSize.width != sketch.sketchWidth() ||
canvasSize.height != sketch.sketchHeight()) {
sketch.redraw();
}
}
}
});
addListeners();
}
// /**
// * Handle grabbing the focus on startup. Other renderers can override this
// * if handling needs to be different. For the AWT, the request is invoked
// * later on the EDT. Other implementations may not require that, so the
// * invokeLater() happens in here rather than requiring the caller to wrap it.
// */
// @Override
// void requestFocus() {
//// System.out.println("requesFocus() outer " + EventQueue.isDispatchThread());
// // for 2.0a6, moving this request to the EDT
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// // Call the request focus event once the image is sure to be on
// // screen and the component is valid. The OpenGL renderer will
// // request focus for its canvas inside beginDraw().
// // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
// // Disabling for 0185, because it causes an assertion failure on OS X
// // https://github.com/processing/processing/issues/297
// // requestFocus();
//
// // Changing to this version for 0187
// // https://github.com/processing/processing/issues/318
// //requestFocusInWindow();
//
// // For 3.0, just call this directly on the Canvas object
// if (canvas != null) {
// //System.out.println("requesting focus " + EventQueue.isDispatchThread());
// //System.out.println("requesting focus " + frame.isVisible());
// //canvas.requestFocusInWindow();
// canvas.requestFocus();
// }
// }
// });
// }
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
public class SmoothCanvas extends Canvas {
private Dimension oldSize = new Dimension(0, 0);
// Turns out getParent() returns a JPanel on a JFrame. Yech.
public Frame getFrame() {
return frame;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(sketchWidth, sketchHeight);
}
@Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
@Override
public Dimension getMaximumSize() {
//return resizable ? super.getMaximumSize() : getPreferredSize();
return frame.isResizable() ? super.getMaximumSize() : getPreferredSize();
}
@Override
public void validate() {
super.validate();
Dimension newSize = getSize();
if (!oldSize.equals(newSize)) {
oldSize = newSize;
sketch.setSize(newSize.width / windowScaleFactor, newSize.height / windowScaleFactor);
render();
}
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public void paint(Graphics screen) {
render();
}
}
protected void render() {
if (canvas.isDisplayable() &&
graphics.image != null) {
if (canvas.getBufferStrategy() == null) {
canvas.createBufferStrategy(2);
}
BufferStrategy strategy = canvas.getBufferStrategy();
if (strategy != null) {
// Render single frame
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
Graphics2D draw = (Graphics2D) strategy.getDrawGraphics();
// draw to width/height, since this may be a 2x image
draw.drawImage(graphics.image, 0, 0, sketchWidth, sketchHeight, null);
draw.dispose();
} while (strategy.contentsRestored());
// Display the buffer
strategy.show();
// Repeat the rendering if the drawing buffer was lost
} while (strategy.contentsLost());
}
}
}
@Override
public void selectInput(String prompt, String callback,
File file, Object callbackObject) {
ShimAWT.selectInput(prompt, callback, file, callbackObject);
}
@Override
public void selectOutput(String prompt, String callback,
File file, Object callbackObject) {
ShimAWT.selectOutput(prompt, callback, file, callbackObject);
}
@Override
public void selectFolder(String prompt, String callback,
File file, Object callbackObject) {
ShimAWT.selectFolder(prompt, callback, file, callbackObject);
}
// what needs to happen here?
@Override
public void initOffscreen(PApplet sketch) {
this.sketch = sketch;
}
@Override
public void initFrame(final PApplet sketch) {/*, int backgroundColor,
int deviceIndex, boolean fullScreen, boolean spanDisplays) {*/
this.sketch = sketch;
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultDevice =
environment.getDefaultScreenDevice();
int displayNum = sketch.sketchDisplay();
// System.out.println("display from sketch is " + displayNum);
if (displayNum > 0) { // if -1, use the default device
GraphicsDevice[] devices = environment.getScreenDevices();
if (displayNum <= devices.length) {
displayDevice = devices[displayNum - 1];
} else {
System.err.format("Display %d does not exist, " +
"using the default display instead.%n", displayNum);
if (devices.length > 1) {
System.err.println("Available displays:");
// The code below is cribbed from the version in PreferencesFrame,
// though it uses \u00d7 and removes the space between because
// it's printing in a monospace font to the console.
for (int i = 0; i < devices.length; i++) {
DisplayMode mode = devices[i].getDisplayMode();
// \u00d7 supported more widely than \u2715 (and a better size)
String title = String.format("%d (%d\u00d7%d)",
i + 1, mode.getWidth(), mode.getHeight());
if (devices[i] == defaultDevice) {
title += " default";
}
System.err.println(title);
}
}
}
}
if (displayDevice == null) {
displayDevice = defaultDevice;
}
// Need to save the window bounds at full screen,
// because pack() will cause the bounds to go to zero.
// https://download.processing.org/bugzilla/923.html
boolean spanDisplays = sketch.sketchDisplay() == PConstants.SPAN;
screenRect = spanDisplays ? getDisplaySpan() :
displayDevice.getDefaultConfiguration().getBounds();
// DisplayMode doesn't work here, because we can't get the upper-left
// corner of the display, which is important for multi-display setups.
// Set the displayWidth/Height variables inside PApplet, so that they're
// usable and can even be returned by the sketchWidth()/Height() methods.
sketch.displayWidth = screenRect.width;
sketch.displayHeight = screenRect.height;
// windowScaleFactor = PApplet.platform == PConstants.MACOS ?
// 1 : sketch.pixelDensity;
sketchWidth = sketch.sketchWidth() * windowScaleFactor;
sketchHeight = sketch.sketchHeight() * windowScaleFactor;
boolean fullScreen = sketch.sketchFullScreen();
// Removing the section below because sometimes people want to do the
// full screen size in a window, and it also breaks insideSettings().
// With 3.x, fullScreen() is so easy, that it's just better that way.
// https://github.com/processing/processing/issues/3545
/*
// Sketch has already requested to be the same as the screen's
// width and height, so let's roll with full screen mode.
if (screenRect.width == sketchWidth &&
screenRect.height == sketchHeight) {
fullScreen = true;
sketch.fullScreen(); // won't change the renderer
}
*/
if (fullScreen || spanDisplays) {
sketchWidth = screenRect.width;
sketchHeight = screenRect.height;
}
// Using a JFrame fixes a Windows problem with Present mode. This might
// be our error, but usually this is the sort of crap we usually get from
// OS X. It's time for a turnaround: Redmond is thinking different too!
// https://github.com/processing/processing/issues/1955
frame = new JFrame(displayDevice.getDefaultConfiguration());
// frame = new Frame(displayDevice.getDefaultConfiguration());
// // Default Processing gray, which will be replaced below if another
// // color is specified on the command line (i.e. in the prefs).
// ((JFrame) frame).getContentPane().setBackground(WINDOW_BGCOLOR);
// // Cannot call setResizable(false) until later due to OS X (issue #467)
// // Removed code above, also removed from what's now in the placeXxxx()
// // methods. Not sure why it was being double-set; hopefully anachronistic.
// if (backgroundColor == 0) {
// backgroundColor = WINDOW_BGCOLOR;
// }
final Color windowColor = new Color(sketch.sketchWindowColor(), false);
frame.getContentPane().setBackground(windowColor);
// Put the p5 logo in the Frame's corner to override the Java coffee cup.
setProcessingIcon(frame);
// For 0149, moving this code (up to the pack() method) before init().
// For OpenGL (and perhaps other renderers in the future), a peer is
// needed before a GLDrawable can be created. So pack() needs to be
// called on the Frame before init(), which itself calls size(),
// and launches the Thread that will kick off setup().
// https://download.processing.org/bugzilla/891.html
// https://download.processing.org/bugzilla/908.html
frame.add(canvas);
setSize(sketchWidth / windowScaleFactor, sketchHeight / windowScaleFactor);
/*
if (fullScreen) {
// Called here because the graphics device is needed before we can
// determine whether the sketch wants size(displayWidth, displayHeight),
// and getting the graphics device will be PSurface-specific.
PApplet.hideMenuBar();
// Tried to use this to fix the 'present' mode issue.
// Did not help, and the screenRect setup seems to work fine.
//frame.setExtendedState(Frame.MAXIMIZED_BOTH);
// https://github.com/processing/processing/pull/3162
frame.dispose(); // release native resources, allows setUndecorated()
frame.setUndecorated(true);
// another duplicate?
// if (backgroundColor != null) {
// frame.getContentPane().setBackground(backgroundColor);
// }
// this may be the bounds of all screens
frame.setBounds(screenRect);
// will be set visible in placeWindow() [3.0a10]
//frame.setVisible(true); // re-add native resources
}
*/
frame.setLayout(null);
// Need to pass back our new sketchWidth/Height here, because it may have
// been overridden by numbers we calculated above if fullScreen and/or
// spanScreens was in use.
// pg = sketch.makePrimaryGraphics(sketchWidth, sketchHeight);
// pg = sketch.makePrimaryGraphics();
// resize sketch to sketchWidth/sketchHeight here
if (fullScreen) {
frame.invalidate();
// } else {
// frame.pack();
}
// insufficient, places the 100x100 sketches offset strangely
//frame.validate();
// disabling resize has to happen after pack() to avoid apparent Apple bug
// https://github.com/processing/processing/issues/506
frame.setResizable(false);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
sketch.exit(); // don't quit, need to just shut everything down (0133)
}
});
// sketch.setFrame(frame);
}
@Override
public Object getNative() {
return canvas;
}
// public Toolkit getToolkit() {
// return canvas.getToolkit();
// }
/** Set the window (and dock, or whatever necessary) title. */
@Override
public void setTitle(String title) {
frame.setTitle(title);
// Workaround for apparent Java bug on OS X?
// https://github.com/processing/processing/issues/3472
if (cursorVisible &&
(PApplet.platform == PConstants.MACOS) &&
(cursorType != PConstants.ARROW)) {
hideCursor();
showCursor();
}
}
/** Set true if we want to resize things (default is not resizable) */
@Override
public void setResizable(boolean resizable) {
//this.resizable = resizable; // really only used for canvas
if (frame != null) {
frame.setResizable(resizable);
}
}
@Override
public void setIcon(PImage image) {
Image awtImage = (Image) image.getNative();
if (PApplet.platform != PConstants.MACOS) {
frame.setIconImage(awtImage);
} else {
try {
final String td = "processing.core.ThinkDifferent";
Class<?> thinkDifferent =
Thread.currentThread().getContextClassLoader().loadClass(td);
Method method =
thinkDifferent.getMethod("setIconImage", Image.class);
method.invoke(null, awtImage);
} catch (Exception e) {
e.printStackTrace(); // That's unfortunate
}
}
}
@Override
public void setAlwaysOnTop(boolean always) {
frame.setAlwaysOnTop(always);
}
@Override
public void setLocation(int x, int y) {
frame.setLocation(x, y);
}
List<Image> iconImages;
protected void setProcessingIcon(Frame frame) {
// On OS X, this only affects what shows up in the dock when minimized.
// So replacing it is actually a step backwards. Brilliant.
if (PApplet.platform != PConstants.MACOS) {
//Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
//frame.setIconImage(image);
try {
if (iconImages == null) {
iconImages = new ArrayList<>();
final int[] sizes = { 16, 32, 48, 64, 128, 256, 512 };
for (int sz : sizes) {
URL url = PApplet.class.getResource("/icon/icon-" + sz + ".png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
iconImages.add(image);
}
}
frame.setIconImages(iconImages);
} catch (Exception ignored) { } // harmless; keep this to ourselves
} else { // handle OS X differently
if (!dockIconSpecified()) { // don't override existing -Xdock param
// On OS X, set this for AWT surfaces, which handles the dock image
// as well as the cmd-tab image that's shown. Just one size, I guess.
URL url = PApplet.class.getResource("/icon/icon-512.png");
// Seems dangerous to have this in code instead of using reflection, no?
//ThinkDifferent.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
try {
final String td = "processing.core.ThinkDifferent";
Class<?> thinkDifferent =
Thread.currentThread().getContextClassLoader().loadClass(td);
Method method =
thinkDifferent.getMethod("setIconImage", Image.class);
method.invoke(null, Toolkit.getDefaultToolkit().getImage(url));
} catch (Exception e) {
e.printStackTrace(); // That's unfortunate
}
}
}
}
/**
* @return true if -Xdock:icon was specified on the command line
*/
private boolean dockIconSpecified() {
// TODO This is incomplete... Haven't yet found a way to figure out if
// the app has an icns file specified already. Help?
List<String> jvmArgs =
ManagementFactory.getRuntimeMXBean().getInputArguments();
for (String arg : jvmArgs) {
if (arg.startsWith("-Xdock:icon")) {
return true; // dock image already set
}
}
return false;
}
@Override
public void setVisible(boolean visible) {
frame.setVisible(visible);
// Generally useful whenever setting the frame visible
if (canvas != null) {
//canvas.requestFocusInWindow();
canvas.requestFocus();
}
// removing per https://github.com/processing/processing/pull/3162
// can remove the code below once 3.0a6 is tested and behaving
/*
if (visible && PApplet.platform == PConstants.LINUX) {
// Linux doesn't deal with insets the same way. We get fake insets
// earlier, and then the window manager will slap its own insets
// onto things once the frame is realized on the screen. Awzm.
if (PApplet.platform == PConstants.LINUX) {
Insets insets = frame.getInsets();
frame.setSize(Math.max(sketchWidth, MIN_WINDOW_WIDTH) +
insets.left + insets.right,
Math.max(sketchHeight, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom);
}
}
*/
}
//public void placeFullScreen(boolean hideStop) {
@Override
public void placePresent(int stopColor) {
setFullFrame();
// After the pack(), the screen bounds are gonna be 0s
// frame.setBounds(screenRect); // already called in setFullFrame()
canvas.setBounds((screenRect.width - sketchWidth) / 2,
(screenRect.height - sketchHeight) / 2,
sketchWidth, sketchHeight);
// if (PApplet.platform == PConstants.MACOSX) {
// macosxFullScreenEnable(frame);
// macosxFullScreenToggle(frame);
// }
if (stopColor != 0) {
Label label = new Label("stop");
label.setForeground(new Color(stopColor, false));
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
sketch.exit();
}
});
frame.add(label);
Dimension labelSize = label.getPreferredSize();
// sometimes shows up truncated on mac
//System.out.println("label width is " + labelSize.width);
labelSize = new Dimension(100, labelSize.height);
label.setSize(labelSize);
label.setLocation(20, screenRect.height - labelSize.height - 20);
}
}
private void setCanvasSize() {
int contentW = Math.max(sketchWidth, MIN_WINDOW_WIDTH);
int contentH = Math.max(sketchHeight, MIN_WINDOW_HEIGHT);
canvas.setBounds((contentW - sketchWidth)/2,
(contentH - sketchHeight)/2,
sketchWidth, sketchHeight);
}
/** Resize frame for these sketch (canvas) dimensions. */
private Dimension setFrameSize() { //int sketchWidth, int sketchHeight) {
// https://github.com/processing/processing/pull/3162
frame.addNotify(); // using instead of show() to add the peer [fry]
// System.out.format("setting frame size %d %d %n", sketchWidth, sketchHeight);
// new Exception().printStackTrace(System.out);
currentInsets = frame.getInsets();
int windowW = Math.max(sketchWidth, MIN_WINDOW_WIDTH) +
currentInsets.left + currentInsets.right;
int windowH = Math.max(sketchHeight, MIN_WINDOW_HEIGHT) +
currentInsets.top + currentInsets.bottom;
frame.setSize(windowW, windowH);
return new Dimension(windowW, windowH);
}
private void setFrameCentered() {
// Can't use frame.setLocationRelativeTo(null) because it sends the
// frame to the main display, which undermines the --display setting.
frame.setLocation(screenRect.x + (screenRect.width - sketchWidth) / 2,
screenRect.y + (screenRect.height - sketchHeight) / 2);
}
/** Hide the menu bar, make the Frame undecorated, set it to screenRect. */
private void setFullFrame() {
// Called here because the graphics device is needed before we can
// determine whether the sketch wants size(displayWidth, displayHeight),
// and getting the graphics device will be PSurface-specific.
PApplet.hideMenuBar();
// Tried to use this to fix the 'present' mode issue.
// Did not help, and the screenRect setup seems to work fine.
//frame.setExtendedState(Frame.MAXIMIZED_BOTH);
// https://github.com/processing/processing/pull/3162
//frame.dispose(); // release native resources, allows setUndecorated()
frame.removeNotify();
frame.setUndecorated(true);
frame.addNotify();
// this may be the bounds of all screens
frame.setBounds(screenRect);
// will be set visible in placeWindow() [3.0a10]
//frame.setVisible(true); // re-add native resources
}
@Override
public void placeWindow(int[] location, int[] editorLocation) {
//Dimension window = setFrameSize(sketchWidth, sketchHeight);
Dimension window = setFrameSize(); //sketchWidth, sketchHeight);
int contentW = Math.max(sketchWidth, MIN_WINDOW_WIDTH);
int contentH = Math.max(sketchHeight, MIN_WINDOW_HEIGHT);
if (sketch.sketchFullScreen()) {
setFullFrame();
}
// Ignore placement of previous window and editor when full screen
if (!sketch.sketchFullScreen()) {
if (location != null) {
// a specific location was received from the Runner
// (sketch has been run more than once, user placed window)
frame.setLocation(location[0], location[1]);
} else if (editorLocation != null) {
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - window.width > 10) {
// if it fits to the left of the window
frame.setLocation(locationX - window.width, locationY);
} else { // doesn't fit
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
//locationX = editorLocation[0] + 66;
//locationY = editorLocation[1] + 66;
locationX = (sketch.displayWidth - window.width) / 2;
locationY = (sketch.displayHeight - window.height) / 2;
/*
if ((locationX + window.width > sketch.displayWidth - 33) ||
(locationY + window.height > sketch.displayHeight - 33)) {
// otherwise center on screen
locationX = (sketch.displayWidth - window.width) / 2;
locationY = (sketch.displayHeight - window.height) / 2;
}
*/
frame.setLocation(locationX, locationY);
}
} else { // just center on screen
setFrameCentered();
}
Point frameLoc = frame.getLocation();
if (frameLoc.y < 0) {
// Windows actually allows you to place frames where they can't be
// closed. Awesome. https://download.processing.org/bugzilla/1508.html
frame.setLocation(frameLoc.x, 30);
}
// make sure that windowX and windowY are set on startup
sketch.postWindowMoved(frame.getX(), frame.getY());
}
canvas.setBounds((contentW - sketchWidth)/2,
(contentH - sketchHeight)/2,
sketchWidth, sketchHeight);
// handle frame resizing events
setupFrameResizeListener();
/*
// If displayable() is false, then PSurfaceNone should be used, but...
if (sketch.getGraphics().displayable()) {
frame.setVisible(true);
// System.out.println("setting visible on EDT? " + EventQueue.isDispatchThread());
//requestFocus();
// if (canvas != null) {
// //canvas.requestFocusInWindow();
// canvas.requestFocus();
// }
}
*/
// if (sketch.getGraphics().displayable()) {
// setVisible(true);
// }
}
// needs to resize the frame, which will resize the canvas, and so on...
@Override
public void setSize(int wide, int high) {
// When the surface is set to resizable via surface.setResizable(true),
// a crash may occur if the user sets the window to size zero.
// https://github.com/processing/processing/issues/5052
if (high <= 0) {
high = 1;
}
if (wide <= 0) {
wide = 1;
}
// if (PApplet.DEBUG) {
// //System.out.format("frame visible %b, setSize(%d, %d) %n", frame.isVisible(), wide, high);
// new Exception(String.format("setSize(%d, %d)", wide, high)).printStackTrace(System.out);
// }
//if (wide == sketchWidth && high == sketchHeight) { // doesn't work on launch
if (wide == sketch.width && high == sketch.height &&
(frame == null || currentInsets.equals(frame.getInsets()))) {
// if (PApplet.DEBUG) {
// new Exception("w/h unchanged " + wide + " " + high).printStackTrace(System.out);
// }
return; // unchanged, don't rebuild everything
}
sketchWidth = wide * windowScaleFactor;
sketchHeight = high * windowScaleFactor;
// canvas.setSize(wide, high);
// frame.setSize(wide, high);
if (frame != null) { // skip if just a canvas
setFrameSize(); //wide, high);
}
setCanvasSize();
// if (frame != null) {
// frame.setLocationRelativeTo(null);
// }
//initImage(graphics, wide, high);
//throw new RuntimeException("implement me, see readme.md");
sketch.setSize(wide, high);
// sketch.width = wide;
// sketch.height = high;
// set PGraphics variables for width/height/pixelWidth/pixelHeight
graphics.setSize(wide, high);
// System.out.println("out of setSize()");
}
//public void initImage(PGraphics gr, int wide, int high) {
/*
@Override
public void initImage(PGraphics graphics) {
GraphicsConfiguration gc = canvas.getGraphicsConfiguration();
// If not realized (off-screen, i.e the Color Selector Tool), gc will be null.
if (gc == null) {
System.err.println("GraphicsConfiguration null in initImage()");
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
}
// Formerly this was broken into separate versions based on offscreen or
// not, but we may as well create a compatible image; it won't hurt, right?
int wide = graphics.width * graphics.pixelFactor;
int high = graphics.height * graphics.pixelFactor;
graphics.image = gc.createCompatibleImage(wide, high);
}
*/
// @Override
// public Component getComponent() {
// return canvas;
// }
// @Override
// public void setSmooth(int level) {
// }
/*
private boolean checkRetina() {
if (PApplet.platform == PConstants.MACOSX) {
// This should probably be reset each time there's a display change.
// A 5-minute search didn't turn up any such event in the Java 7 API.
// Also, should we use the Toolkit associated with the editor window?
final String javaVendor = System.getProperty("java.vendor");
if (javaVendor.contains("Oracle")) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = env.getDefaultScreenDevice();
try {
Field field = device.getClass().getDeclaredField("scale");
if (field != null) {
field.setAccessible(true);
Object scale = field.get(device);
if (scale instanceof Integer && ((Integer)scale).intValue() == 2) {
return true;
}
}
} catch (Exception ignore) { }
}
}
return false;
}
*/
/** Get the bounds rectangle for all displays. */
static Rectangle getDisplaySpan() {
Rectangle bounds = new Rectangle();
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
for (GraphicsDevice device : environment.getScreenDevices()) {
for (GraphicsConfiguration config : device.getConfigurations()) {
Rectangle2D.union(bounds, config.getBounds(), bounds);
}
}
return bounds;
}
/*
private void checkDisplaySize() {
if (canvas.getGraphicsConfiguration() != null) {
GraphicsDevice displayDevice = getGraphicsConfiguration().getDevice();
if (displayDevice != null) {
Rectangle screenRect =
displayDevice.getDefaultConfiguration().getBounds();
displayWidth = screenRect.width;
displayHeight = screenRect.height;
}
}
}
*/
// /**
// * Set this sketch to communicate its state back to the PDE.
// * <p/>
// * This uses the stderr stream to write positions of the window
// * (so that it will be saved by the PDE for the next run) and
// * notify on quit. See more notes in the Worker class.
// */
// @Override
// public void setupExternalMessages() {
// frame.addComponentListener(new ComponentAdapter() {
// @Override
// public void componentMoved(ComponentEvent e) {
// Point where = ((Frame) e.getSource()).getLocation();
// //sketch.frameMoved(where.x, where.y);
// sketch.queueWindowPosition(where.x, where.y);
// }
// });
// }
/**
* Set up a listener that will fire proper component resize events
* in cases where frame.setResizable(true) is called.
*/
private void setupFrameResizeListener() {
// Detect when the frame is resized to handle a macOS bug:
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8036935
frame.addWindowStateListener(e -> {
// This seems to be firing when dragging the window on OS X
// https://github.com/processing/processing/issues/3092
if (Frame.MAXIMIZED_BOTH == e.getNewState()) {
// Supposedly, sending the frame to back and then front is a
// workaround for this bug:
// http://stackoverflow.com/a/23897602
// but is not working for me...
//frame.toBack();
//frame.toFront();
// Packing the frame works, but that causes the window to collapse
// on OS X when the window is dragged. Changing to addNotify() for
// https://github.com/processing/processing/issues/3092
//frame.pack();
frame.addNotify();
}
});
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Ignore bad resize events fired during setup to fix
// https://download.processing.org/bugzilla/341.html
// This should also fix the blank screen on Linux bug
// https://download.processing.org/bugzilla/282.html
if (frame.isResizable()) {
// might be multiple resize calls before visible (i.e. first
// when pack() is called, then when it's resized for use).
// ignore them because it's not the user resizing things.