Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.desktop/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java
41159 views
1
/*
2
* Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.java2d.d3d;
27
28
import java.awt.Color;
29
import java.awt.Component;
30
import java.awt.Container;
31
import java.awt.Font;
32
import java.awt.Graphics2D;
33
import java.awt.Rectangle;
34
import java.awt.Window;
35
import java.security.AccessController;
36
import java.security.PrivilegedAction;
37
import java.util.ArrayList;
38
import java.util.HashMap;
39
40
import sun.awt.AWTAccessor;
41
import sun.awt.AWTAccessor.ComponentAccessor;
42
import sun.awt.util.ThreadGroupUtils;
43
import sun.awt.Win32GraphicsConfig;
44
import sun.awt.windows.WComponentPeer;
45
import sun.java2d.InvalidPipeException;
46
import sun.java2d.ScreenUpdateManager;
47
import sun.java2d.SunGraphics2D;
48
import sun.java2d.SurfaceData;
49
import sun.java2d.windows.GDIWindowSurfaceData;
50
import sun.java2d.d3d.D3DSurfaceData.D3DWindowSurfaceData;
51
import sun.java2d.windows.WindowsFlags;
52
53
/**
54
* This class handles rendering to the screen with the D3D pipeline.
55
*
56
* Since it is not possible to render directly to the front buffer
57
* with D3D9, we create a swap chain surface (with COPY effect) in place of the
58
* GDIWindowSurfaceData. A background thread handles the swap chain flips.
59
*
60
* There are some restrictions to which windows we would use this for.
61
* @see #createScreenSurface
62
*/
63
public class D3DScreenUpdateManager extends ScreenUpdateManager
64
implements Runnable
65
{
66
/**
67
* A window must be at least MIN_WIN_SIZE in one or both dimensions
68
* to be considered for the update manager.
69
*/
70
private static final int MIN_WIN_SIZE = 150;
71
72
private volatile boolean done;
73
private volatile Thread screenUpdater;
74
private boolean needsUpdateNow;
75
76
/**
77
* Object used by the screen updater thread for waiting
78
*/
79
private Object runLock = new Object();
80
/**
81
* List of D3DWindowSurfaceData surfaces. Surfaces are added to the
82
* list when a graphics object is created, and removed when the surface
83
* is invalidated.
84
*/
85
private ArrayList<D3DWindowSurfaceData> d3dwSurfaces;
86
/**
87
* Cache of GDIWindowSurfaceData surfaces corresponding to the
88
* D3DWindowSurfaceData surfaces. Surfaces are added to the list when
89
* a d3dw surface is lost and could not be restored (due to lack of vram,
90
* for example), and removed then the d3dw surface is invalidated.
91
*/
92
private HashMap<D3DWindowSurfaceData, GDIWindowSurfaceData> gdiSurfaces;
93
94
@SuppressWarnings("removal")
95
public D3DScreenUpdateManager() {
96
done = false;
97
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
98
Runnable shutdownRunnable = () -> {
99
done = true;
100
wakeUpUpdateThread();
101
};
102
Thread shutdown = new Thread(
103
ThreadGroupUtils.getRootThreadGroup(), shutdownRunnable,
104
"ScreenUpdater", 0, false);
105
shutdown.setContextClassLoader(null);
106
try {
107
Runtime.getRuntime().addShutdownHook(shutdown);
108
} catch (Exception e) {
109
done = true;
110
}
111
return null;
112
});
113
}
114
115
/**
116
* If possible, creates a D3DWindowSurfaceData (which is actually
117
* a back-buffer surface). If the creation fails, returns GDI
118
* onscreen surface instead.
119
*
120
* Note that the created D3D surface does not initialize the native
121
* resources (and is marked lost) to avoid wasting video memory. It is
122
* restored when a graphics object is requested from the peer.
123
*
124
* Note that this method is called from a synchronized block in
125
* WComponentPeer, so we don't need to synchronize
126
*
127
* Note that we only create a substibute d3dw surface if certain conditions
128
* are met
129
* <ul>
130
* <li>the fake d3d rendering on screen is not disabled via flag
131
* <li>d3d on the device is enabled
132
* <li>surface is larger than MIN_WIN_SIZE (don't bother for smaller ones)
133
* <li>it doesn't have a backBuffer for a BufferStrategy already
134
* <li>the peer is either Canvas, Panel, Window, Frame,
135
* Dialog or EmbeddedFrame
136
* </ul>
137
*
138
* @param gc GraphicsConfiguration on associated with the surface
139
* @param peer peer for which the surface is to be created
140
* @param bbNum number of back-buffers requested. if this number is >0,
141
* method returns GDI surface (we don't want to have two swap chains)
142
* @param isResize whether this surface is being created in response to
143
* a component resize event. This determines whether a repaint event will
144
* be issued after a surface is created: it will be if {@code isResize}
145
* is {@code true}.
146
* @return surface data to be use for onscreen rendering
147
*/
148
@Override
149
public SurfaceData createScreenSurface(Win32GraphicsConfig gc,
150
WComponentPeer peer,
151
int bbNum, boolean isResize)
152
{
153
if (done || !(gc instanceof D3DGraphicsConfig)) {
154
return super.createScreenSurface(gc, peer, bbNum, isResize);
155
}
156
157
SurfaceData sd = null;
158
159
if (canUseD3DOnScreen(peer, gc, bbNum)) {
160
try {
161
// note that the created surface will be in the "lost"
162
// state, it will be restored prior to rendering to it
163
// for the first time. This is done so that vram is not
164
// wasted for surfaces never rendered to
165
sd = D3DSurfaceData.createData(peer);
166
} catch (InvalidPipeException ipe) {
167
sd = null;
168
}
169
}
170
if (sd == null) {
171
sd = GDIWindowSurfaceData.createData(peer);
172
// note that we do not add this surface to the list of cached gdi
173
// surfaces as there's no d3dw surface to associate it with;
174
// this peer will have a gdi surface until next time a surface
175
// will need to be replaced
176
}
177
178
if (isResize) {
179
// since we'd potentially replaced the back-buffer surface
180
// (either with another bb, or a gdi one), the
181
// component will need to be completely repainted;
182
// this only need to be done when the surface is created in
183
// response to a resize event since when a component is created it
184
// will be repainted anyway
185
repaintPeerTarget(peer);
186
}
187
188
return sd;
189
}
190
191
/**
192
* Determines if we can use a d3d surface for onscreen rendering for this
193
* peer.
194
* We only create onscreen d3d surfaces if the following conditions are met:
195
* - d3d is enabled on this device and onscreen emulation is enabled
196
* - window is big enough to bother (either dimension > MIN_WIN_SIZE)
197
* - this heavyweight doesn't have a BufferStrategy
198
* - if we are in full-screen mode then it must be the peer of the
199
* full-screen window (since there could be only one SwapChain in fs)
200
* and it must not have any heavyweight children
201
* (as Present() doesn't respect component clipping in fullscreen mode)
202
* - it's one of the classes likely to have custom rendering worth
203
* accelerating
204
*
205
* @return true if we can use a d3d surface for this peer's onscreen
206
* rendering
207
*/
208
public static boolean canUseD3DOnScreen(final WComponentPeer peer,
209
final Win32GraphicsConfig gc,
210
final int bbNum)
211
{
212
if (!(gc instanceof D3DGraphicsConfig)) {
213
return false;
214
}
215
D3DGraphicsConfig d3dgc = (D3DGraphicsConfig)gc;
216
D3DGraphicsDevice d3dgd = d3dgc.getD3DDevice();
217
String peerName = peer.getClass().getName();
218
Rectangle r = peer.getBounds();
219
Component target = (Component)peer.getTarget();
220
Window fsw = d3dgd.getFullScreenWindow();
221
222
return
223
WindowsFlags.isD3DOnScreenEnabled() &&
224
d3dgd.isD3DEnabledOnDevice() &&
225
peer.isAccelCapable() &&
226
(r.width > MIN_WIN_SIZE || r.height > MIN_WIN_SIZE) &&
227
bbNum == 0 &&
228
(fsw == null || (fsw == target && !hasHWChildren(target))) &&
229
(peerName.equals("sun.awt.windows.WCanvasPeer") ||
230
peerName.equals("sun.awt.windows.WDialogPeer") ||
231
peerName.equals("sun.awt.windows.WPanelPeer") ||
232
peerName.equals("sun.awt.windows.WWindowPeer") ||
233
peerName.equals("sun.awt.windows.WFramePeer") ||
234
peerName.equals("sun.awt.windows.WEmbeddedFramePeer"));
235
}
236
237
/**
238
* Creates a graphics object for the passed in surface data. If
239
* the surface is lost, it is restored.
240
* If the surface wasn't lost or the restoration was successful
241
* the surface is added to the list of maintained surfaces
242
* (if it hasn't been already).
243
*
244
* If the updater thread hasn't been created yet , it will be created and
245
* started.
246
*
247
* @param sd surface data for which to create SunGraphics2D
248
* @param peer peer associated with the surface data
249
* @param fgColor fg color to be used in graphics
250
* @param bgColor bg color to be used in graphics
251
* @param font font to be used in graphics
252
* @return a SunGraphics2D object for the surface (or for temp GDI
253
* surface data)
254
*/
255
@Override
256
public Graphics2D createGraphics(SurfaceData sd,
257
WComponentPeer peer, Color fgColor, Color bgColor, Font font)
258
{
259
if (!done && sd instanceof D3DWindowSurfaceData) {
260
D3DWindowSurfaceData d3dw = (D3DWindowSurfaceData)sd;
261
if (!d3dw.isSurfaceLost() || validate(d3dw)) {
262
trackScreenSurface(d3dw);
263
return new SunGraphics2D(sd, fgColor, bgColor, font);
264
}
265
// could not restore the d3dw surface, use the cached gdi surface
266
// instead for this graphics object; note that we do not track
267
// this new gdi surface, it is only used for this graphics
268
// object
269
sd = getGdiSurface(d3dw);
270
}
271
return super.createGraphics(sd, peer, fgColor, bgColor, font);
272
}
273
274
/**
275
* Posts a repaint event for the peer's target to the EDT
276
* @param peer for which target's the repaint should be issued
277
*/
278
private void repaintPeerTarget(WComponentPeer peer) {
279
Component target = (Component)peer.getTarget();
280
Rectangle bounds = AWTAccessor.getComponentAccessor().getBounds(target);
281
// the system-level painting operations should call the handlePaint()
282
// method of the WComponentPeer class to repaint the component;
283
// calling repaint() forces AWT to make call to update()
284
peer.handlePaint(0, 0, bounds.width, bounds.height);
285
}
286
287
/**
288
* Adds a surface to the list of tracked surfaces.
289
*
290
* @param sd the surface to be added
291
*/
292
private void trackScreenSurface(SurfaceData sd) {
293
if (!done && sd instanceof D3DWindowSurfaceData) {
294
synchronized (this) {
295
if (d3dwSurfaces == null) {
296
d3dwSurfaces = new ArrayList<D3DWindowSurfaceData>();
297
}
298
D3DWindowSurfaceData d3dw = (D3DWindowSurfaceData)sd;
299
if (!d3dwSurfaces.contains(d3dw)) {
300
d3dwSurfaces.add(d3dw);
301
}
302
}
303
startUpdateThread();
304
}
305
}
306
307
@Override
308
public synchronized void dropScreenSurface(SurfaceData sd) {
309
if (d3dwSurfaces != null && sd instanceof D3DWindowSurfaceData) {
310
D3DWindowSurfaceData d3dw = (D3DWindowSurfaceData)sd;
311
removeGdiSurface(d3dw);
312
d3dwSurfaces.remove(d3dw);
313
}
314
}
315
316
@Override
317
public SurfaceData getReplacementScreenSurface(WComponentPeer peer,
318
SurfaceData sd)
319
{
320
SurfaceData newSurface = super.getReplacementScreenSurface(peer, sd);
321
// if some outstanding graphics context wants to get a replacement we
322
// need to make sure that the new surface (if it is accelerated) is
323
// being tracked
324
trackScreenSurface(newSurface);
325
return newSurface;
326
}
327
328
/**
329
* Remove the gdi surface corresponding to the passed d3dw surface
330
* from list of the cached gdi surfaces.
331
*
332
* @param d3dw surface for which associated gdi surface is to be removed
333
*/
334
private void removeGdiSurface(final D3DWindowSurfaceData d3dw) {
335
if (gdiSurfaces != null) {
336
GDIWindowSurfaceData gdisd = gdiSurfaces.get(d3dw);
337
if (gdisd != null) {
338
gdisd.invalidate();
339
gdiSurfaces.remove(d3dw);
340
}
341
}
342
}
343
344
/**
345
* If the update thread hasn't yet been created, it will be;
346
* otherwise it is awaken
347
*/
348
@SuppressWarnings("removal")
349
private synchronized void startUpdateThread() {
350
if (screenUpdater == null) {
351
screenUpdater = AccessController.doPrivileged((PrivilegedAction<Thread>) () -> {
352
String name = "D3D Screen Updater";
353
Thread t = new Thread(
354
ThreadGroupUtils.getRootThreadGroup(), this, name,
355
0, false);
356
// REMIND: should it be higher?
357
t.setPriority(Thread.NORM_PRIORITY + 2);
358
t.setDaemon(true);
359
return t;
360
});
361
screenUpdater.start();
362
} else {
363
wakeUpUpdateThread();
364
}
365
}
366
367
/**
368
* Wakes up the screen updater thread.
369
*
370
* This method is not synchronous, it doesn't wait
371
* for the updater thread to complete the updates.
372
*
373
* It should be used when it is not necessary to wait for the
374
* completion, for example, when a new surface had been added
375
* to the list of tracked surfaces (which means that it's about
376
* to be rendered to).
377
*/
378
public void wakeUpUpdateThread() {
379
synchronized (runLock) {
380
runLock.notifyAll();
381
}
382
}
383
384
/**
385
* Wakes up the screen updater thread and waits for the completion
386
* of the update.
387
*
388
* This method is called from Toolkit.sync() or
389
* when there was a copy from a VI to the screen
390
* so that swing applications would not appear to be
391
* sluggish.
392
*/
393
public void runUpdateNow() {
394
synchronized (this) {
395
// nothing to do if the updater thread hadn't been started or if
396
// there are no tracked surfaces
397
if (done || screenUpdater == null ||
398
d3dwSurfaces == null || d3dwSurfaces.size() == 0)
399
{
400
return;
401
}
402
}
403
synchronized (runLock) {
404
needsUpdateNow = true;
405
runLock.notifyAll();
406
while (needsUpdateNow) {
407
try {
408
runLock.wait();
409
} catch (InterruptedException e) {}
410
}
411
}
412
}
413
414
public void run() {
415
while (!done) {
416
synchronized (runLock) {
417
// If the list is empty, suspend the thread until a
418
// new surface is added. Note that we have to check before
419
// wait() (and inside the runLock), otherwise we could miss a
420
// notify() when a new surface is added and sleep forever.
421
long timeout = d3dwSurfaces.size() > 0 ? 100 : 0;
422
423
// don't go to sleep if there's a thread waiting for an update
424
if (!needsUpdateNow) {
425
try { runLock.wait(timeout); }
426
catch (InterruptedException e) {}
427
}
428
// if we were woken up, there are probably surfaces in the list,
429
// no need to check if the list is empty
430
}
431
432
// make a copy to avoid synchronization during the loop
433
D3DWindowSurfaceData[] surfaces = new D3DWindowSurfaceData[] {};
434
synchronized (this) {
435
surfaces = d3dwSurfaces.toArray(surfaces);
436
}
437
for (D3DWindowSurfaceData sd : surfaces) {
438
// skip invalid surfaces (they could have become invalid
439
// after we made a copy of the list) - just a precaution
440
if (sd.isValid() && (sd.isDirty() || sd.isSurfaceLost())) {
441
if (!sd.isSurfaceLost()) {
442
// the flip and the clearing of the dirty state
443
// must be done under the lock, otherwise it's
444
// possible to miss an update to the surface
445
D3DRenderQueue rq = D3DRenderQueue.getInstance();
446
rq.lock();
447
try {
448
Rectangle r = sd.getBounds();
449
D3DSurfaceData.swapBuffers(sd, 0, 0,
450
r.width, r.height);
451
sd.markClean();
452
} finally {
453
rq.unlock();
454
}
455
} else if (!validate(sd)) {
456
// it is possible that the validation may never
457
// succeed, we need to detect this and replace
458
// the d3dw surface with gdi; the replacement of
459
// the surface will also trigger a repaint
460
sd.getPeer().replaceSurfaceDataLater();
461
}
462
}
463
}
464
synchronized (runLock) {
465
needsUpdateNow = false;
466
runLock.notifyAll();
467
}
468
}
469
}
470
471
/**
472
* Restores the passed surface if it was lost, resets the lost status.
473
* @param sd surface to be validated
474
* @return true if surface wasn't lost or if restoration was successful,
475
* false otherwise
476
*/
477
private boolean validate(D3DWindowSurfaceData sd) {
478
if (sd.isSurfaceLost()) {
479
try {
480
sd.restoreSurface();
481
// if succeeded, first fill the surface with bg color
482
// note: use the non-synch method to avoid incorrect lock order
483
Color bg = sd.getPeer().getBackgroundNoSync();
484
SunGraphics2D sg2d = new SunGraphics2D(sd, bg, bg, null);
485
sg2d.fillRect(0, 0, sd.getBounds().width, sd.getBounds().height);
486
sg2d.dispose();
487
// now clean the dirty status so that we don't flip it
488
// next time before it gets repainted; it is safe
489
// to do without the lock because we will issue a
490
// repaint anyway so we will not lose any rendering
491
sd.markClean();
492
// since the surface was successfully restored we need to
493
// repaint whole window to repopulate the back-buffer
494
repaintPeerTarget(sd.getPeer());
495
} catch (InvalidPipeException ipe) {
496
return false;
497
}
498
}
499
return true;
500
}
501
502
/**
503
* Creates (or returns a cached one) gdi surface for the same peer as
504
* the passed d3dw surface has.
505
*
506
* @param d3dw surface used as key into the cache
507
* @return gdi window surface associated with the d3d window surfaces' peer
508
*/
509
private synchronized SurfaceData getGdiSurface(D3DWindowSurfaceData d3dw) {
510
if (gdiSurfaces == null) {
511
gdiSurfaces =
512
new HashMap<D3DWindowSurfaceData, GDIWindowSurfaceData>();
513
}
514
GDIWindowSurfaceData gdisd = gdiSurfaces.get(d3dw);
515
if (gdisd == null) {
516
gdisd = GDIWindowSurfaceData.createData(d3dw.getPeer());
517
gdiSurfaces.put(d3dw, gdisd);
518
}
519
return gdisd;
520
}
521
522
/**
523
* Returns true if the component has heavyweight children.
524
*
525
* @param comp component to check for hw children
526
* @return true if Component has heavyweight children
527
*/
528
private static boolean hasHWChildren(Component comp) {
529
final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
530
if (comp instanceof Container) {
531
for (Component c : ((Container)comp).getComponents()) {
532
if (acc.getPeer(c) instanceof WComponentPeer || hasHWChildren(c)) {
533
return true;
534
}
535
}
536
}
537
return false;
538
}
539
}
540
541