/
FlatWindowsNativeWindowBorder.java
476 lines (402 loc) · 14.8 KB
/
FlatWindowsNativeWindowBorder.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
/*
* Copyright 2021 FormDev Software GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.formdev.flatlaf.ui;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
import com.formdev.flatlaf.FlatSystemProperties;
import com.formdev.flatlaf.util.LoggingFacade;
import com.formdev.flatlaf.util.NativeLibrary;
import com.formdev.flatlaf.util.SystemInfo;
//
// Interesting resources:
// https://github.com/microsoft/terminal/blob/main/src/cascadia/WindowsTerminal/NonClientIslandWindow.cpp
// https://docs.microsoft.com/en-us/windows/win32/dwm/customframe
// https://github.com/JetBrains/JetBrainsRuntime/blob/master/src/java.desktop/windows/native/libawt/windows/awt_Frame.cpp
// https://github.com/JetBrains/JetBrainsRuntime/commit/d2820524a1aa211b1c49b30f659b9b4d07a6f96e
// https://github.com/JetBrains/JetBrainsRuntime/pull/18
// https://medium.com/swlh/customizing-the-title-bar-of-an-application-window-50a4ac3ed27e
// https://github.com/kalbetredev/CustomDecoratedJFrame
// https://github.com/Guerra24/NanoUI-win32
// https://github.com/oberth/custom-chrome
// https://github.com/rossy/borderless-window
//
// Windows 11
// https://docs.microsoft.com/en-us/windows/apps/desktop/modernize/apply-snap-layout-menu
// https://github.com/dotnet/wpf/issues/4825#issuecomment-930442736
//
/**
* Native window border support for Windows 10 when using custom decorations.
* <p>
* If the application wants to use custom decorations, the Windows 10 title bar is hidden
* (including minimize, maximize and close buttons), but not the resize borders (including drop shadow).
* Windows 10 window snapping functionality will remain unaffected:
* https://support.microsoft.com/en-us/windows/snap-your-windows-885a9b1e-a983-a3b1-16cd-c531795e6241
*
* @author Karl Tauber
* @since 1.1
*/
class FlatWindowsNativeWindowBorder
implements FlatNativeWindowBorder.Provider
{
private final Map<Window, WndProc> windowsMap = Collections.synchronizedMap( new IdentityHashMap<>() );
private final EventListenerList listenerList = new EventListenerList();
private Timer fireStateChangedTimer;
private boolean colorizationUpToDate;
private boolean colorizationColorAffectsBorders;
private Color colorizationColor;
private int colorizationColorBalance;
private static NativeLibrary nativeLibrary;
private static FlatWindowsNativeWindowBorder instance;
static FlatNativeWindowBorder.Provider getInstance() {
// requires Windows 10
if( !SystemInfo.isWindows_10_orLater )
return null;
// requires x86 architecture
if( !SystemInfo.isX86 && !SystemInfo.isX86_64 )
return null;
// load native library
if( nativeLibrary == null ) {
if( !SystemInfo.isJava_9_orLater ) {
// In Java 8, load jawt.dll (part of JRE) explicitly because it
// is not found when running application with <jdk>/bin/java.exe.
// When using <jdk>/jre/bin/java.exe, it is found.
// jawt.dll is located in <jdk>/jre/bin/.
// Java 9 and later does not have this problem.
try {
System.loadLibrary( "jawt" );
} catch( UnsatisfiedLinkError ex ) {
// log error only if native library jawt.dll not already loaded
String message = ex.getMessage();
if( message == null || !message.contains( "already loaded in another classloader" ) )
LoggingFacade.INSTANCE.logSevere( null, ex );
} catch( Exception ex ) {
LoggingFacade.INSTANCE.logSevere( null, ex );
}
}
nativeLibrary = createNativeLibrary();
}
// check whether native library was successfully loaded
if( !nativeLibrary.isLoaded() )
return null;
// create new instance
if( instance == null )
instance = new FlatWindowsNativeWindowBorder();
return instance;
}
private static NativeLibrary createNativeLibrary() {
String libraryName = "flatlaf-windows-x86";
if( SystemInfo.isX86_64 )
libraryName += "_64";
String libraryPath = System.getProperty( FlatSystemProperties.NATIVE_LIBRARY_PATH );
if( libraryPath != null ) {
File libraryFile = new File( libraryPath, System.mapLibraryName( libraryName ) );
if( libraryFile.exists() )
return new NativeLibrary( libraryFile, true );
else
LoggingFacade.INSTANCE.logSevere( "Did not find external library " + libraryFile + ", using extracted library instead", null );
}
return new NativeLibrary( "com/formdev/flatlaf/natives/" + libraryName, null, true );
}
private FlatWindowsNativeWindowBorder() {
}
@Override
public boolean hasCustomDecoration( Window window ) {
return windowsMap.containsKey( window );
}
/**
* Tell the window whether the application wants to use custom decorations.
* If {@code true}, the Windows 10 title bar is hidden (including minimize,
* maximize and close buttons), but not the resize borders (including drop shadow).
*/
@Override
public void setHasCustomDecoration( Window window, boolean hasCustomDecoration ) {
if( hasCustomDecoration )
install( window );
else
uninstall( window );
}
private void install( Window window ) {
// requires Windows 10
if( !SystemInfo.isWindows_10_orLater )
return;
// only JFrame and JDialog are supported
if( !(window instanceof JFrame) && !(window instanceof JDialog) )
return;
// not supported if frame/dialog is undecorated
if( (window instanceof Frame && ((Frame)window).isUndecorated()) ||
(window instanceof Dialog && ((Dialog)window).isUndecorated()) )
return;
// check whether already installed
if( windowsMap.containsKey( window ) )
return;
// install
try {
WndProc wndProc = new WndProc( window );
if( wndProc.hwnd == 0 )
return;
windowsMap.put( window, wndProc );
} catch( UnsatisfiedLinkError ex ) {
// catch for the case that the operating system prevents execution of DLL
// (e.g. if DLLs in temp folder are restricted)
// --> continue application without custom decorations
LoggingFacade.INSTANCE.logSevere( null, ex );
}
}
private void uninstall( Window window ) {
WndProc wndProc = windowsMap.remove( window );
if( wndProc != null )
wndProc.uninstall();
}
@Override
public void updateTitleBarInfo( Window window, int titleBarHeight, List<Rectangle> hitTestSpots,
Rectangle appIconBounds, Rectangle minimizeButtonBounds, Rectangle maximizeButtonBounds,
Rectangle closeButtonBounds )
{
WndProc wndProc = windowsMap.get( window );
if( wndProc == null )
return;
wndProc.titleBarHeight = titleBarHeight;
wndProc.hitTestSpots = hitTestSpots.toArray( new Rectangle[hitTestSpots.size()] );
wndProc.appIconBounds = cloneRectange( appIconBounds );
wndProc.minimizeButtonBounds = cloneRectange( minimizeButtonBounds );
wndProc.maximizeButtonBounds = cloneRectange( maximizeButtonBounds );
wndProc.closeButtonBounds = cloneRectange( closeButtonBounds );
}
private static Rectangle cloneRectange( Rectangle rect ) {
return (rect != null) ? new Rectangle( rect ) : null;
}
@Override
public boolean showWindow( Window window, int cmd ) {
WndProc wndProc = windowsMap.get( window );
if( wndProc == null )
return false;
wndProc.showWindow( wndProc.hwnd, cmd );
return true;
}
@Override
public boolean isColorizationColorAffectsBorders() {
updateColorization();
return colorizationColorAffectsBorders;
}
@Override
public Color getColorizationColor() {
updateColorization();
return colorizationColor;
}
@Override
public int getColorizationColorBalance() {
updateColorization();
return colorizationColorBalance;
}
private void updateColorization() {
if( colorizationUpToDate )
return;
colorizationUpToDate = true;
String subKey = "SOFTWARE\\Microsoft\\Windows\\DWM";
int value = registryGetIntValue( subKey, "ColorPrevalence", -1 );
colorizationColorAffectsBorders = (value > 0);
value = registryGetIntValue( subKey, "ColorizationColor", -1 );
colorizationColor = (value != -1) ? new Color( value ) : null;
colorizationColorBalance = registryGetIntValue( subKey, "ColorizationColorBalance", -1 );
}
private native static int registryGetIntValue( String key, String valueName, int defaultValue );
@Override
public void addChangeListener( ChangeListener l ) {
listenerList.add( ChangeListener.class, l );
}
@Override
public void removeChangeListener( ChangeListener l ) {
listenerList.remove( ChangeListener.class, l );
}
private void fireStateChanged() {
Object[] listeners = listenerList.getListenerList();
if( listeners.length == 0 )
return;
ChangeEvent e = new ChangeEvent( this );
for( int i = 0; i < listeners.length; i += 2 ) {
if( listeners[i] == ChangeListener.class )
((ChangeListener)listeners[i+1]).stateChanged( e );
}
}
/**
* Because there may be sent many WM_DWMCOLORIZATIONCOLORCHANGED messages,
* slightly delay event firing and fire it only once (on the AWT thread).
*/
void fireStateChangedLaterOnce() {
EventQueue.invokeLater( () -> {
if( fireStateChangedTimer != null ) {
fireStateChangedTimer.restart();
return;
}
fireStateChangedTimer = new Timer( 300, e -> {
fireStateChangedTimer = null;
colorizationUpToDate = false;
fireStateChanged();
} );
fireStateChangedTimer.setRepeats( false );
fireStateChangedTimer.start();
} );
}
//---- class WndProc ------------------------------------------------------
private class WndProc
implements PropertyChangeListener
{
// WM_NCHITTEST mouse position codes
private static final int
HTCLIENT = 1,
HTCAPTION = 2,
HTSYSMENU = 3,
HTMINBUTTON = 8,
HTMAXBUTTON = 9,
HTTOP = 12,
HTCLOSE = 20;
private Window window;
private final long hwnd;
// Swing coordinates/values may be scaled on a HiDPI screen
private int titleBarHeight;
private Rectangle[] hitTestSpots;
private Rectangle appIconBounds;
private Rectangle minimizeButtonBounds;
private Rectangle maximizeButtonBounds;
private Rectangle closeButtonBounds;
WndProc( Window window ) {
this.window = window;
hwnd = installImpl( window );
if( hwnd == 0 )
return;
// remove the OS window title bar
updateFrame( hwnd, (window instanceof JFrame) ? ((JFrame)window).getExtendedState() : 0 );
// set window background (used when resizing window)
updateWindowBackground();
window.addPropertyChangeListener( "background", this );
}
void uninstall() {
window.removePropertyChangeListener( "background", this );
uninstallImpl( hwnd );
// cleanup
window = null;
}
@Override
public void propertyChange( PropertyChangeEvent e ) {
updateWindowBackground();
}
private void updateWindowBackground() {
Color bg = window.getBackground();
if( bg != null )
setWindowBackground( hwnd, bg.getRed(), bg.getGreen(), bg.getBlue() );
}
private native long installImpl( Window window );
private native void uninstallImpl( long hwnd );
private native void updateFrame( long hwnd, int state );
private native void setWindowBackground( long hwnd, int r, int g, int b );
private native void showWindow( long hwnd, int cmd );
// invoked from native code
private int onNcHitTest( int x, int y, boolean isOnResizeBorder ) {
// scale-down mouse x/y because Swing coordinates/values may be scaled on a HiDPI screen
Point pt = scaleDown( x, y );
int sx = pt.x;
int sy = pt.y;
// return HTSYSMENU if mouse is over application icon
// - left-click on HTSYSMENU area shows system menu
// - double-left-click sends WM_CLOSE
if( contains( appIconBounds, sx, sy ) )
return HTSYSMENU;
// return HTMINBUTTON if mouse is over minimize button
// - hovering mouse over HTMINBUTTON area shows tooltip on Windows 10/11
if( contains( minimizeButtonBounds, sx, sy ) )
return HTMINBUTTON;
// return HTMAXBUTTON if mouse is over maximize/restore button
// - hovering mouse over HTMAXBUTTON area shows tooltip on Windows 10
// - hovering mouse over HTMAXBUTTON area shows snap layouts menu on Windows 11
// https://docs.microsoft.com/en-us/windows/apps/desktop/modernize/apply-snap-layout-menu
if( contains( maximizeButtonBounds, sx, sy ) )
return HTMAXBUTTON;
// return HTCLOSE if mouse is over close button
// - hovering mouse over HTCLOSE area shows tooltip on Windows 10/11
if( contains( closeButtonBounds, sx, sy ) )
return HTCLOSE;
boolean isOnTitleBar = (sy < titleBarHeight);
if( isOnTitleBar ) {
// use a second reference to the array to avoid that it can be changed
// in another thread while processing the array
Rectangle[] hitTestSpots2 = hitTestSpots;
for( Rectangle spot : hitTestSpots2 ) {
if( spot.contains( sx, sy ) )
return HTCLIENT;
}
return isOnResizeBorder ? HTTOP : HTCAPTION;
}
return isOnResizeBorder ? HTTOP : HTCLIENT;
}
private boolean contains( Rectangle rect, int x, int y ) {
return (rect != null && rect.contains( x, y ) );
}
/**
* Scales down in the same way as AWT.
* See AwtWin32GraphicsDevice::ScaleDownX() and ::ScaleDownY()
*/
private Point scaleDown( int x, int y ) {
GraphicsConfiguration gc = window.getGraphicsConfiguration();
if( gc == null )
return new Point( x, y );
AffineTransform t = gc.getDefaultTransform();
return new Point( clipRound( x / t.getScaleX() ), clipRound( y / t.getScaleY() ) );
}
/**
* Rounds in the same way as AWT.
* See AwtWin32GraphicsDevice::ClipRound()
*/
private int clipRound( double value ) {
value -= 0.5;
if( value < Integer.MIN_VALUE )
return Integer.MIN_VALUE;
if( value > Integer.MAX_VALUE )
return Integer.MAX_VALUE;
return (int) Math.ceil( value );
}
// invoked from native code
private boolean isFullscreen() {
GraphicsConfiguration gc = window.getGraphicsConfiguration();
if( gc == null )
return false;
return gc.getDevice().getFullScreenWindow() == window;
}
// invoked from native code
private void fireStateChangedLaterOnce() {
FlatWindowsNativeWindowBorder.this.fireStateChangedLaterOnce();
}
}
}