/
WindowUtils.java
2092 lines (1957 loc) · 87.4 KB
/
WindowUtils.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
/* Copyright (c) 2007-2008 Timothy Wall, All Rights Reserved
* Copyright (c) 2007 Olivier Chafik
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna.platform;
import java.awt.AWTEvent;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.AWTEventListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ContainerEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Area;
import java.awt.geom.PathIterator;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.PopupFactory;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.platform.unix.X11;
import com.sun.jna.platform.unix.X11.Display;
import com.sun.jna.platform.unix.X11.GC;
import com.sun.jna.platform.unix.X11.Pixmap;
import com.sun.jna.platform.unix.X11.XVisualInfo;
import com.sun.jna.platform.unix.X11.Xext;
import com.sun.jna.platform.unix.X11.Xrender.XRenderPictFormat;
import com.sun.jna.platform.win32.GDI32;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.Psapi;
import com.sun.jna.platform.win32.PsapiUtil;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.Win32Exception;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinDef.DWORDByReference;
import com.sun.jna.platform.win32.WinDef.HBITMAP;
import com.sun.jna.platform.win32.WinDef.HDC;
import com.sun.jna.platform.win32.WinDef.HICON;
import com.sun.jna.platform.win32.WinDef.HRGN;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinDef.LPARAM;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.POINT;
import com.sun.jna.platform.win32.WinDef.RECT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinError;
import com.sun.jna.platform.win32.WinGDI;
import com.sun.jna.platform.win32.WinGDI.BITMAP;
import com.sun.jna.platform.win32.WinGDI.BITMAPINFO;
import com.sun.jna.platform.win32.WinGDI.BITMAPINFOHEADER;
import com.sun.jna.platform.win32.WinGDI.ICONINFO;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.platform.win32.WinUser.BLENDFUNCTION;
import com.sun.jna.platform.win32.WinUser.SIZE;
import com.sun.jna.platform.win32.WinUser.WNDENUMPROC;
import com.sun.jna.ptr.ByteByReference;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Provides additional features on a Java {@link Window}.
* <ul>
* <li>Non-rectangular shape (bitmap mask, no antialiasing)
* <li>Transparency (constant alpha applied to window contents or
* transparent background)
* <li>Fully transparent window (the transparency of all painted pixels is
* applied to the window).
* </ul>
* NOTE: since there is no explicit way to force PopupFactory to use a
* heavyweight popup, and anything but a heavyweight popup will be
* clipped by a window mask, an additional subwindow is added to all
* masked windows to implicitly force PopupFactory to use a heavyweight
* window and avoid clipping.
* <p>
* NOTE: Neither shaped windows nor transparency
* currently works with Java 1.4 under X11. This is at least partly due
* to 1.4 using multiple X11 windows for a single given Java window. It
* *might* be possible to remedy by applying the window
* region/transparency to all descendants, but I haven't tried it. In
* addition, windows must be both displayable <em>and</em> visible
* before the corresponding native Drawable may be obtained; in later
* Java versions, the window need only be displayable.
* <p>
* NOTE: If you use {@link #setWindowMask(Window,Shape)} and override {@link
* Window#paint(Graphics)} on OS X, you'll need to explicitly set the clip
* mask on the <code>Graphics</code> object with the window mask; only the
* content pane of the window and below have the window mask automatically
* applied.<p>
* NOTE: On OSX, the property
* <code>apple.awt.draggableWindowBackground</code> is set automatically when
* a window's background color has an alpha component. That property must be
* set to its final value <em>before</em> the heavyweight peer for the Window
* is created. Once {@link Component#addNotify} has been called on the
* component, causing creation of the heavyweight peer, changing this
* property has no effect.
* @see <a href="http://developer.apple.com/technotes/tn2007/tn2196.html#APPLE_AWT_DRAGGABLEWINDOWBACKGROUND">Apple Technote 2007</a>
*
* @author Andreas "PAX" Lück, onkelpax-git[at]yahoo.de
*/
// TODO: setWindowMask() should accept a threshold; some cases want a
// 50% threshold, some might want zero/non-zero
public class WindowUtils {
private static final Logger LOG = Logger.getLogger(WindowUtils.class.getName());
private static final String TRANSPARENT_OLD_BG = "transparent-old-bg";
private static final String TRANSPARENT_OLD_OPAQUE = "transparent-old-opaque";
private static final String TRANSPARENT_ALPHA = "transparent-alpha";
/** Use this to clear a window mask. */
public static final Shape MASK_NONE = null;
/**
* This class forces a heavyweight popup on the parent
* {@link Window}. See the implementation of {@link PopupFactory};
* a heavyweight is forced if there is an occluding subwindow on the
* target window.
* <p>
* Ideally we'd have more control over {@link PopupFactory} but this
* is a fairly simple, lightweight workaround. Note that, at least as of
* JDK 1.6, the following do not have the desired effect:<br>
* <pre><code>
* ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
* JPopupMenu.setDefaultLightWeightPopupEnabled(false);
* System.setProperty("JPopupMenu.defaultLWPopupEnabledKey", "false");
* </code></pre>
*/
private static class HeavyweightForcer extends Window {
private static final long serialVersionUID = 1L;
private final boolean packed;
public HeavyweightForcer(Window parent) {
super(parent);
pack();
packed = true;
}
@Override
public boolean isVisible() {
// Only want to be 'visible' once the peer is instantiated
// via pack; this tricks PopupFactory into using a heavyweight
// popup to avoid being obscured by this window
return packed;
}
@Override
public Rectangle getBounds() {
return getOwner().getBounds();
}
}
/**
* This can be installed over a {@link JLayeredPane} in order to
* listen for repaint requests. The content's repaint method will be
* invoked whenever any part of the ancestor window is repainted.
*/
protected static class RepaintTrigger extends JComponent {
private static final long serialVersionUID = 1L;
protected class Listener
extends WindowAdapter
implements ComponentListener, HierarchyListener, AWTEventListener {
@Override
public void windowOpened(WindowEvent e) {
repaint();
}
@Override
public void componentHidden(ComponentEvent e) {}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentResized(ComponentEvent e) {
setSize(getParent().getSize());
repaint();
}
@Override
public void componentShown(ComponentEvent e) {
repaint();
}
@Override
public void hierarchyChanged(HierarchyEvent e) {
repaint();
}
@Override
public void eventDispatched(AWTEvent e) {
if (e instanceof MouseEvent) {
Component src = ((MouseEvent)e).getComponent();
if (src != null
&& SwingUtilities.isDescendingFrom(src, content)) {
MouseEvent me = SwingUtilities.convertMouseEvent(src, (MouseEvent)e, content);
Component c = SwingUtilities.getDeepestComponentAt(content, me.getX(), me.getY());
if (c != null) {
setCursor(c.getCursor());
}
}
}
}
}
private final Listener listener = createListener();
private final JComponent content;
public RepaintTrigger(JComponent content) {
this.content = content;
}
@Override
public void addNotify() {
super.addNotify();
Window w = SwingUtilities.getWindowAncestor(this);
setSize(getParent().getSize());
w.addComponentListener(listener);
w.addWindowListener(listener);
Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.MOUSE_EVENT_MASK|AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
@Override
public void removeNotify() {
Toolkit.getDefaultToolkit().removeAWTEventListener(listener);
Window w = SwingUtilities.getWindowAncestor(this);
w.removeComponentListener(listener);
w.removeWindowListener(listener);
super.removeNotify();
}
private Rectangle dirty;
@Override
protected void paintComponent(Graphics g) {
Rectangle bounds = g.getClipBounds();
if (dirty == null || !dirty.contains(bounds)) {
if (dirty == null) {
dirty = bounds;
}
else {
dirty = dirty.union(bounds);
}
content.repaint(dirty);
}
else {
dirty = null;
}
}
protected Listener createListener() {
return new Listener();
}
};
/** Window utilities with differing native implementations. */
public static abstract class NativeWindowUtils {
protected abstract class TransparentContentPane
extends JPanel implements AWTEventListener {
private static final long serialVersionUID = 1L;
private boolean transparent;
public TransparentContentPane(Container oldContent) {
super(new BorderLayout());
add(oldContent, BorderLayout.CENTER);
setTransparent(true);
if (oldContent instanceof JPanel) {
((JComponent)oldContent).setOpaque(false);
}
}
@Override
public void addNotify() {
super.addNotify();
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.CONTAINER_EVENT_MASK);
}
@Override
public void removeNotify() {
Toolkit.getDefaultToolkit().removeAWTEventListener(this);
super.removeNotify();
}
public void setTransparent(boolean transparent) {
this.transparent = transparent;
setOpaque(!transparent);
setDoubleBuffered(!transparent);
repaint();
}
@Override
public void eventDispatched(AWTEvent e) {
if (e.getID() == ContainerEvent.COMPONENT_ADDED
&& SwingUtilities.isDescendingFrom(((ContainerEvent)e).getChild(), this)) {
Component child = ((ContainerEvent)e).getChild();
NativeWindowUtils.this.setDoubleBuffered(child, false);
}
}
@Override
public void paint(Graphics gr) {
if (transparent) {
Rectangle r = gr.getClipBounds();
final int w = r.width;
final int h = r.height;
if (getWidth() > 0 && getHeight() > 0) {
final BufferedImage buf =
new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D g = buf.createGraphics();
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, w, h);
g.dispose();
g = buf.createGraphics();
g.translate(-r.x, -r.y);
super.paint(g);
g.dispose();
paintDirect(buf, r);
}
}
else {
super.paint(gr);
}
}
/** Use the contents of the given BufferedImage to paint directly
* on this component's ancestor window.
*/
protected abstract void paintDirect(BufferedImage buf, Rectangle bounds);
}
protected Window getWindow(Component c) {
return c instanceof Window
? (Window)c : SwingUtilities.getWindowAncestor(c);
}
/**
* Execute the given action when the given window becomes
* displayable.
*/
protected void whenDisplayable(Component w, final Runnable action) {
if (w.isDisplayable() && (!Holder.requiresVisible || w.isVisible())) {
action.run();
}
else if (Holder.requiresVisible) {
getWindow(w).addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
e.getWindow().removeWindowListener(this);
action.run();
}
@Override
public void windowClosed(WindowEvent e) {
e.getWindow().removeWindowListener(this);
}
});
}
else {
// Hierarchy events are fired in direct response to
// displayability changes
w.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0
&& e.getComponent().isDisplayable()) {
e.getComponent().removeHierarchyListener(this);
action.run();
}
}
});
}
}
protected Raster toRaster(Shape mask) {
Raster raster = null;
if (mask != MASK_NONE) {
Rectangle bounds = mask.getBounds();
if (bounds.width > 0 && bounds.height > 0) {
BufferedImage clip =
new BufferedImage(bounds.x + bounds.width,
bounds.y + bounds.height,
BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g = clip.createGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, bounds.x + bounds.width, bounds.y + bounds.height);
g.setColor(Color.white);
g.fill(mask);
raster = clip.getRaster();
}
}
return raster;
}
protected Raster toRaster(Component c, Icon mask) {
Raster raster = null;
if (mask != null) {
Rectangle bounds = new Rectangle(0, 0, mask.getIconWidth(),
mask.getIconHeight());
BufferedImage clip = new BufferedImage(bounds.width,
bounds.height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = clip.createGraphics();
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, bounds.width, bounds.height);
g.setComposite(AlphaComposite.SrcOver);
mask.paintIcon(c, g, 0, 0);
raster = clip.getAlphaRaster();
}
return raster;
}
protected Shape toShape(Raster raster) {
final Area area = new Area(new Rectangle(0, 0, 0, 0));
RasterRangesUtils.outputOccupiedRanges(raster, new RasterRangesUtils.RangesOutput() {
@Override
public boolean outputRange(int x, int y, int w, int h) {
area.add(new Area(new Rectangle(x, y, w, h)));
return true;
}
});
return area;
}
/**
* Set the overall alpha transparency of the window. An alpha of
* 1.0 is fully opaque, 0.0 is fully transparent.
*/
public void setWindowAlpha(Window w, float alpha) {
// do nothing
}
/** Default: no support. */
public boolean isWindowAlphaSupported() {
return false;
}
/** Return the default graphics configuration. */
public GraphicsConfiguration getAlphaCompatibleGraphicsConfiguration() {
GraphicsEnvironment env = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice dev = env.getDefaultScreenDevice();
return dev.getDefaultConfiguration();
}
/**
* Set the window to be transparent. Only explicitly painted
* pixels will be non-transparent. All pixels will be composited
* with whatever is under the window using their alpha values.
*/
public void setWindowTransparent(Window w, boolean transparent) {
// do nothing
}
protected void setDoubleBuffered(Component root, boolean buffered) {
if (root instanceof JComponent) {
((JComponent)root).setDoubleBuffered(buffered);
}
if (root instanceof JRootPane && buffered) {
((JRootPane)root).setDoubleBuffered(true);
}
else if (root instanceof Container) {
Component[] kids = ((Container)root).getComponents();
for (int i=0;i < kids.length;i++) {
setDoubleBuffered(kids[i], buffered);
}
}
}
protected void setLayersTransparent(Window w, boolean transparent) {
Color bg = transparent ? new Color(0, 0, 0, 0) : null;
if (w instanceof RootPaneContainer) {
RootPaneContainer rpc = (RootPaneContainer)w;
JRootPane root = rpc.getRootPane();
JLayeredPane lp = root.getLayeredPane();
Container c = root.getContentPane();
JComponent content =
(c instanceof JComponent) ? (JComponent)c : null;
if (transparent) {
lp.putClientProperty(TRANSPARENT_OLD_OPAQUE, Boolean.valueOf(lp.isOpaque()));
lp.setOpaque(false);
root.putClientProperty(TRANSPARENT_OLD_OPAQUE, Boolean.valueOf(root.isOpaque()));
root.setOpaque(false);
if (content != null) {
content.putClientProperty(TRANSPARENT_OLD_OPAQUE, Boolean.valueOf(content.isOpaque()));
content.setOpaque(false);
}
root.putClientProperty(TRANSPARENT_OLD_BG,
root.getParent().getBackground());
}
else {
lp.setOpaque(Boolean.TRUE.equals(lp.getClientProperty(TRANSPARENT_OLD_OPAQUE)));
lp.putClientProperty(TRANSPARENT_OLD_OPAQUE, null);
root.setOpaque(Boolean.TRUE.equals(root.getClientProperty(TRANSPARENT_OLD_OPAQUE)));
root.putClientProperty(TRANSPARENT_OLD_OPAQUE, null);
if (content != null) {
content.setOpaque(Boolean.TRUE.equals(content.getClientProperty(TRANSPARENT_OLD_OPAQUE)));
content.putClientProperty(TRANSPARENT_OLD_OPAQUE, null);
}
bg = (Color)root.getClientProperty(TRANSPARENT_OLD_BG);
root.putClientProperty(TRANSPARENT_OLD_BG, null);
}
}
w.setBackground(bg);
}
/** Override this method to provide bitmap masking of the given
* heavyweight component.
*/
protected void setMask(Component c, Raster raster) {
throw new UnsupportedOperationException("Window masking is not available");
}
/**
* Set the window mask based on the given Raster, which should
* be treated as a bitmap (zero/nonzero values only). A value of
* <code>null</code> means to remove the mask.
*/
protected void setWindowMask(Component w, Raster raster) {
if (w.isLightweight())
throw new IllegalArgumentException("Component must be heavyweight: " + w);
setMask(w, raster);
}
/** Set the window mask based on a {@link Shape}. */
public void setWindowMask(Component w, Shape mask) {
setWindowMask(w, toRaster(mask));
}
/**
* Set the window mask based on an Icon. All non-transparent
* pixels will be included in the mask.
*/
public void setWindowMask(Component w, Icon mask) {
setWindowMask(w, toRaster(w, mask));
}
/**
* Use this method to ensure heavyweight popups are used in
* conjunction with a given window. This prevents the window's
* alpha setting or mask region from being applied to the popup.
*/
protected void setForceHeavyweightPopups(Window w, boolean force) {
if (!(w instanceof HeavyweightForcer)) {
Window[] owned = w.getOwnedWindows();
for (int i = 0; i < owned.length; i++) {
if (owned[i] instanceof HeavyweightForcer) {
if (force)
return;
owned[i].dispose();
}
}
Boolean b = Boolean.valueOf(System.getProperty("jna.force_hw_popups", "true"));
if (force && b.booleanValue()) {
new HeavyweightForcer(w);
}
}
}
/**
* Obtains the set icon for the window associated with the specified
* window handle.
*
* @param hwnd
* The concerning window handle.
* @return Either the window's icon or {@code null} if an error
* occurred.
*
* @throws UnsupportedOperationException
* Thrown if this method wasn't yet implemented for the
* current platform.
*/
protected BufferedImage getWindowIcon(final HWND hwnd) {
throw new UnsupportedOperationException("This platform is not supported, yet.");
}
/**
* Detects the size of an icon.
*
* @param hIcon
* The icon handle type.
* @return Either the requested icon's dimension or an {@link Dimension}
* instance of {@code (0, 0)}.
*
* @throws UnsupportedOperationException
* Thrown if this method wasn't yet implemented for the
* current platform.
*/
protected Dimension getIconSize(final HICON hIcon) {
throw new UnsupportedOperationException("This platform is not supported, yet.");
}
/**
* Requests a list of all currently available Desktop windows.
*
* @param onlyVisibleWindows
* Specifies whether only currently visible windows will be
* considered ({@code true}). That are windows which are not
* minimized. The {@code WS_VISIBLE} flag will be checked
* (see: <a href=
* "https://msdn.microsoft.com/de-de/library/windows/desktop/ms633530%28v=vs.85%29.aspx"
* >User32.IsWindowVisible(HWND)</a>).
*
* @return A list with all windows and some detailed information.
*
* @throws UnsupportedOperationException
* Thrown if this method wasn't yet implemented for the
* current platform.
*/
protected List<DesktopWindow> getAllWindows(final boolean onlyVisibleWindows) {
throw new UnsupportedOperationException("This platform is not supported, yet.");
}
/**
* Tries to obtain the Window's title which belongs to the specified
* window handle.
*
* @param hwnd
* The concerning window handle.
* @return Either the title or an empty string of no title was found or
* an error occurred.
*
* @throws UnsupportedOperationException
* Thrown if this method wasn't yet implemented for the
*/
protected String getWindowTitle(final HWND hwnd) {
throw new UnsupportedOperationException("This platform is not supported, yet.");
}
/**
* Detects the full file path of the process associated with the specified
* window handle.
*
* @param hwnd
* The concerning window handle for which the PE file path is
* required.
* @return The full file path of the PE file that is associated with the
* specified window handle.
*
* @throws UnsupportedOperationException
* Thrown if this method wasn't yet implemented for the
*/
protected String getProcessFilePath(final HWND hwnd){
throw new UnsupportedOperationException("This platform is not supported, yet.");
}
/**
* Requests the location and size of the window associated with the
* specified window handle.
*
* @param hwnd
* The concerning window handle.
* @return The location and size of the window.
*
* @throws UnsupportedOperationException
* Thrown if this method wasn't yet implemented for the
*/
protected Rectangle getWindowLocationAndSize(final HWND hwnd) {
throw new UnsupportedOperationException("This platform is not supported, yet.");
}
}
/** Canonical lazy loading of a singleton. */
private static class Holder {
/**
* Indicates whether a window must be visible before its native
* handle can be obtained. This wart is caused by the Java
* 1.4/X11 implementation.
*/
public static boolean requiresVisible;
public static final NativeWindowUtils INSTANCE;
static {
if (Platform.isWindows()) {
INSTANCE = new W32WindowUtils();
}
else if (Platform.isMac()) {
INSTANCE = new MacWindowUtils();
}
else if (Platform.isX11()) {
INSTANCE = new X11WindowUtils();
requiresVisible = System.getProperty("java.version")
.matches("^1\\.4\\..*");
}
else {
String os = System.getProperty("os.name");
throw new UnsupportedOperationException("No support for " + os);
}
}
}
private static NativeWindowUtils getInstance() {
return Holder.INSTANCE;
}
private static class W32WindowUtils extends NativeWindowUtils {
private HWND getHWnd(Component w) {
HWND hwnd = new HWND();
hwnd.setPointer(Native.getComponentPointer(w));
return hwnd;
}
/**
* W32 alpha will only work if <code>sun.java2d.noddraw</code>
* is set
*/
@Override
public boolean isWindowAlphaSupported() {
return Boolean.getBoolean("sun.java2d.noddraw");
}
/** Indicates whether UpdateLayeredWindow is in use. */
private boolean usingUpdateLayeredWindow(Window w) {
if (w instanceof RootPaneContainer) {
JRootPane root = ((RootPaneContainer)w).getRootPane();
return root.getClientProperty(TRANSPARENT_OLD_BG) != null;
}
return false;
}
/** Keep track of the alpha level, since we can't read it from
* the window itself.
*/
private void storeAlpha(Window w, byte alpha) {
if (w instanceof RootPaneContainer) {
JRootPane root = ((RootPaneContainer)w).getRootPane();
Byte b = alpha == (byte)0xFF ? null : Byte.valueOf(alpha);
root.putClientProperty(TRANSPARENT_ALPHA, b);
}
}
/** Return the last alpha level we set on the window. */
private byte getAlpha(Window w) {
if (w instanceof RootPaneContainer) {
JRootPane root = ((RootPaneContainer)w).getRootPane();
Byte b = (Byte)root.getClientProperty(TRANSPARENT_ALPHA);
if (b != null) {
return b.byteValue();
}
}
return (byte)0xFF;
}
@Override
public void setWindowAlpha(final Window w, final float alpha) {
if (!isWindowAlphaSupported()) {
throw new UnsupportedOperationException("Set sun.java2d.noddraw=true to enable transparent windows");
}
whenDisplayable(w, new Runnable() {
@Override
public void run() {
HWND hWnd = getHWnd(w);
User32 user = User32.INSTANCE;
int flags = user.GetWindowLong(hWnd, WinUser.GWL_EXSTYLE);
byte level = (byte)((int)(255 * alpha) & 0xFF);
if (usingUpdateLayeredWindow(w)) {
// If already using UpdateLayeredWindow, continue to
// do so
BLENDFUNCTION blend = new BLENDFUNCTION();
blend.SourceConstantAlpha = level;
blend.AlphaFormat = WinUser.AC_SRC_ALPHA;
user.UpdateLayeredWindow(hWnd, null, null, null, null,
null, 0, blend,
WinUser.ULW_ALPHA);
}
else if (alpha == 1f) {
flags &= ~WinUser.WS_EX_LAYERED;
user.SetWindowLong(hWnd, WinUser.GWL_EXSTYLE, flags);
}
else {
flags |= WinUser.WS_EX_LAYERED;
user.SetWindowLong(hWnd, WinUser.GWL_EXSTYLE, flags);
user.SetLayeredWindowAttributes(hWnd, 0, level,
WinUser.LWA_ALPHA);
}
setForceHeavyweightPopups(w, alpha != 1f);
storeAlpha(w, level);
}
});
}
/** W32 makes the client responsible for repainting the <em>entire</em>
* window on any change. It also does not paint window decorations
* when the window is transparent.
*/
private class W32TransparentContentPane extends TransparentContentPane {
private static final long serialVersionUID = 1L;
private HDC memDC;
private HBITMAP hBitmap;
private Pointer pbits;
private Dimension bitmapSize;
public W32TransparentContentPane(Container content) {
super(content);
}
private void disposeBackingStore() {
GDI32 gdi = GDI32.INSTANCE;
if (hBitmap != null) {
gdi.DeleteObject(hBitmap);
hBitmap = null;
}
if (memDC != null) {
gdi.DeleteDC(memDC);
memDC = null;
}
}
@Override
public void removeNotify() {
super.removeNotify();
disposeBackingStore();
}
@Override
public void setTransparent(boolean transparent) {
super.setTransparent(transparent);
if (!transparent) {
disposeBackingStore();
}
}
@Override
protected void paintDirect(BufferedImage buf, Rectangle bounds) {
// TODO: paint frame decoration if window is decorated
Window win = SwingUtilities.getWindowAncestor(this);
GDI32 gdi = GDI32.INSTANCE;
User32 user = User32.INSTANCE;
int x = bounds.x;
int y = bounds.y;
Point origin = SwingUtilities.convertPoint(this, x, y, win);
int w = bounds.width;
int h = bounds.height;
int ww = win.getWidth();
int wh = win.getHeight();
HDC screenDC = user.GetDC(null);
HANDLE oldBitmap = null;
try {
if (memDC == null) {
memDC = gdi.CreateCompatibleDC(screenDC);
}
if (hBitmap == null || !win.getSize().equals(bitmapSize)) {
if (hBitmap != null) {
gdi.DeleteObject(hBitmap);
hBitmap = null;
}
BITMAPINFO bmi = new BITMAPINFO();
bmi.bmiHeader.biWidth = ww;
bmi.bmiHeader.biHeight = wh;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = WinGDI.BI_RGB;
bmi.bmiHeader.biSizeImage = ww * wh * 4;
PointerByReference ppbits = new PointerByReference();
hBitmap = gdi.CreateDIBSection(memDC, bmi,
WinGDI.DIB_RGB_COLORS,
ppbits, null, 0);
pbits = ppbits.getValue();
bitmapSize = new Dimension(ww, wh);
}
oldBitmap = gdi.SelectObject(memDC, hBitmap);
Raster raster = buf.getData();
int[] pixel = new int[4];
int[] bits = new int[w];
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
raster.getPixel(col, row, pixel);
int alpha = (pixel[3] & 0xFF) << 24;
int red = (pixel[2] & 0xFF);
int green = (pixel[1] & 0xFF) << 8;
int blue = (pixel[0] & 0xFF) << 16;
bits[col] = alpha | red | green | blue;
}
int v = wh - (origin.y + row) - 1;
pbits.write((v*ww+origin.x)*4, bits, 0, bits.length);
}
SIZE winSize = new SIZE();
winSize.cx = win.getWidth();
winSize.cy = win.getHeight();
POINT winLoc = new POINT();
winLoc.x = win.getX();
winLoc.y = win.getY();
POINT srcLoc = new POINT();
BLENDFUNCTION blend = new BLENDFUNCTION();
HWND hWnd = getHWnd(win);
// extract current constant alpha setting, if possible
ByteByReference bref = new ByteByReference();
IntByReference iref = new IntByReference();
byte level = getAlpha(win);
try {
// GetLayeredwindowAttributes supported WinXP and later
if (user.GetLayeredWindowAttributes(hWnd, null, bref, iref)
&& (iref.getValue() & WinUser.LWA_ALPHA) != 0) {
level = bref.getValue();
}
}
catch(UnsatisfiedLinkError e) {
}
blend.SourceConstantAlpha = level;
blend.AlphaFormat = WinUser.AC_SRC_ALPHA;
user.UpdateLayeredWindow(hWnd, screenDC, winLoc, winSize, memDC,
srcLoc, 0, blend, WinUser.ULW_ALPHA);
} finally {
user.ReleaseDC(null, screenDC);
if (memDC != null && oldBitmap != null) {
gdi.SelectObject(memDC, oldBitmap);
}
}
}
}
/** Note that w32 does <em>not</em> paint window decorations when
* the window is transparent.
*/
@Override
public void setWindowTransparent(final Window w,
final boolean transparent) {
if (!(w instanceof RootPaneContainer)) {
throw new IllegalArgumentException("Window must be a RootPaneContainer");
}
if (!isWindowAlphaSupported()) {
throw new UnsupportedOperationException("Set sun.java2d.noddraw=true to enable transparent windows");
}
boolean isTransparent = w.getBackground() != null
&& w.getBackground().getAlpha() == 0;
if (transparent == isTransparent)
return;
whenDisplayable(w, new Runnable() {
@Override
public void run() {
User32 user = User32.INSTANCE;
HWND hWnd = getHWnd(w);
int flags = user.GetWindowLong(hWnd, WinUser.GWL_EXSTYLE);
JRootPane root = ((RootPaneContainer)w).getRootPane();
JLayeredPane lp = root.getLayeredPane();
Container content = root.getContentPane();
if (content instanceof W32TransparentContentPane) {
((W32TransparentContentPane)content).setTransparent(transparent);
}
else if (transparent) {
W32TransparentContentPane w32content =
new W32TransparentContentPane(content);
root.setContentPane(w32content);
lp.add(new RepaintTrigger(w32content),
JLayeredPane.DRAG_LAYER);
}
if (transparent && !usingUpdateLayeredWindow(w)) {
flags |= WinUser.WS_EX_LAYERED;
user.SetWindowLong(hWnd, WinUser.GWL_EXSTYLE, flags);
}
else if (!transparent && usingUpdateLayeredWindow(w)) {
flags &= ~WinUser.WS_EX_LAYERED;