-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsDisplayInfo.java
More file actions
301 lines (245 loc) · 11.3 KB
/
WindowsDisplayInfo.java
File metadata and controls
301 lines (245 loc) · 11.3 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
import com.sun.jna.platform.win32.GDI32;
import com.sun.jna.platform.win32.WinDef;
import java.awt.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* <p>This <code>WindowsDisplayInfo</code> class retrieves the current <code>Windows Resolution(s)</code>, <code>Aspect ratio(s)</code>,
* and <code>Scale factor</code> throughout a <code>Java</code> applications' runtime.</p>
*
* <p>It uses <code>Java AWT</code> and the <code>Java Native Access (JNA) platform</code>
* to access the <code>Display Device Context (DC)</code> from <code>Microsoft
* Windows graphics device interface (GDI)</code></p>
*
* @implNote Requires <code>net.java.dev.jna.platform (Maven)</code>
* <p>Full support for <code>Java 8</code>: Value updates throughout runtime</p>
* <p>Partial support for <code>Java 11+</code>: Value from application startup</p>
*
* @author <a href="https://github.com/jcoester/Java-WindowsDisplayInfo/">jcoester</a>
* @version 1.2 (2024 May. 05)
*/
public class WindowsDisplayInfo {
private static final int HORZ_RES = 8;
private static final int VERT_RES = 10;
private static final int DESKTOP_VERT_RES = 117;
private static final int DESKTOP_HORZ_RES = 118;
public static void main(String[] args) {
// For demonstration: Check Windows Display every 5 seconds
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(WindowsDisplayInfo::update, 0, 5, TimeUnit.SECONDS);
}
private static void update() {
// Usage
System.out.println("Scale (double) : " + retrieveScaleFactor()); // e.g. 1.0, 1.25, 1.5, 2.0
System.out.println("Scale ( int% ) : " + retrieveScaleFactorPercentage()); // e.g. 100%, 125%, 150%, 200%
System.out.println("Native : " + retrieveNativeResolution()); // Native
System.out.println("Adjusted : " + retrieveAdjustedResolution()); // Native, adjusted by scale factor
System.out.println("Maximum : " + retrieveMaximumResolution()); // Maximum
System.out.println("All (Ascending) : " + retrieveAllResolutions(true)); // List of all, sorted smallest to largest
System.out.println("All (Descending): " + retrieveAllResolutions(false)); // List of all, sorted largest to smallest
System.out.println(); // Empty line for easier readability during demonstration
}
public static double retrieveScaleFactor() {
WinDef.HDC hdc = null;
try {
// Using AWT, retrieve the initial scaleFactor from application startup
double awtScale = Toolkit.getDefaultToolkit().getScreenResolution() / 96.0f;
// Retrieve HDC (Handle to Device Context (DC))
hdc = GDI32.INSTANCE.CreateCompatibleDC(null);
if (hdc == null)
return 0;
// Using HDC, detect changes to the scaleFactor during the runtime
double a = GDI32.INSTANCE.GetDeviceCaps(hdc, VERT_RES);
double b = GDI32.INSTANCE.GetDeviceCaps(hdc, DESKTOP_VERT_RES);
if (a == 0 || b == 0)
return 0;
// Offset DESKTOP_VERT_RES with the initial AWT scaleFactor
b = b * awtScale;
// Calculate scaleFactor
double scaleFactor = a > b ? a / b : b / a;
// Round to two decimals and return
return BigDecimal.valueOf(scaleFactor).setScale(2, RoundingMode.HALF_UP).doubleValue();
} catch (Exception e) {
// Handle Exception
e.printStackTrace();
} finally {
// Close HDC (Handle to Device Context (DC))
if (hdc != null) {
GDI32.INSTANCE.DeleteDC(hdc);
}
}
return 0;
}
public static int retrieveScaleFactorPercentage() {
return (int) (retrieveScaleFactor() * 100);
}
public static Resolution retrieveNativeResolution() {
WinDef.HDC hdc = null;
try {
// Retrieve HDC (Handle to Device Context (DC))
hdc = GDI32.INSTANCE.CreateCompatibleDC(null);
if (hdc == null)
return null;
// Using HDC, detect changes to the scaleFactor during the runtime
double a = GDI32.INSTANCE.GetDeviceCaps(hdc, DESKTOP_HORZ_RES);
double b = GDI32.INSTANCE.GetDeviceCaps(hdc, DESKTOP_VERT_RES);
if (a == 0 || b == 0)
return null;
// Return Native Resolution
return new Resolution((int) a, (int) b, determineAspectRatio((int) a, (int) b));
} catch (Exception e) {
// Handle Exception
e.printStackTrace();
} finally {
// Close HDC (Handle to Device Context (DC))
if (hdc != null) {
GDI32.INSTANCE.DeleteDC(hdc);
}
}
return null;
}
public static Resolution retrieveEffectiveResolution() {
WinDef.HDC hdc = null;
try {
// Using AWT, retrieve the initial scaleFactor from application startup
double awtScale = Toolkit.getDefaultToolkit().getScreenResolution() / 96.0f;
// Retrieve HDC (Handle to Device Context (DC))
hdc = GDI32.INSTANCE.CreateCompatibleDC(null);
if (hdc == null)
return null;
// Using HDC, detect changes to the scaleFactor during the runtime
double a = GDI32.INSTANCE.GetDeviceCaps(hdc, HORZ_RES);
double b = GDI32.INSTANCE.GetDeviceCaps(hdc, VERT_RES);
if (a == 0 || b == 0)
return null;
// Offset HORZ_RES and VERT_RES with the initial AWT scaleFactor
a = a / awtScale;
b = b / awtScale;
// Return Resolution
return new Resolution((int) a, (int) b, determineAspectRatio((int) a, (int) b));
} catch (Exception e) {
// Handle Exception
e.printStackTrace();
} finally {
// Close HDC (Handle to Device Context (DC))
if (hdc != null) {
GDI32.INSTANCE.DeleteDC(hdc);
}
}
return null;
}
public static Resolution retrieveAdjustedResolution() {
Resolution effective = retrieveEffectiveResolution();
List<Resolution> allResolutions = retrieveAllResolutions(true);
// If Effective is valid
if (allResolutions.contains(effective))
return effective;
// If Effective is not valid, look for closest larger resolution
for (Resolution res : allResolutions) {
// Same aspect ratio
if (effective != null && res.getAspectRatio().equals(effective.getAspectRatio()))
// First larger resolution
if (res.getWidth() >= effective.getWidth())
return res;
}
return retrieveNativeResolution(); // Fallback: Return Native
}
public static Resolution retrieveMaximumResolution() {
List<Resolution> resolutions = retrieveAllResolutions(false);
return resolutions.isEmpty() ? null : resolutions.get(0);
}
public static List<Resolution> retrieveAllResolutions(boolean ascending) {
Resolution minimum = new Resolution(800, 600, "4:3"); // Minimum resolution available in Windows 11
Set<Resolution> resolutionSet = new HashSet<>(); // Set for unique resolutions
GraphicsDevice dev = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0]; // [0] main display
for (DisplayMode m : dev.getDisplayModes())
if (m.getWidth() >= minimum.getWidth() && m.getHeight() >= minimum.getHeight())
resolutionSet.add(new Resolution(m.getWidth(), m.getHeight(), determineAspectRatio(m.getWidth(), m.getHeight())));
List<Resolution> sortResolutions = new ArrayList<>(resolutionSet);
sortResolutions.sort(ascending ? Comparator.naturalOrder() : Comparator.reverseOrder());
return sortResolutions;
}
/**
* <p>Returns the aspect ratio of given width and height in "X:Y"-format </p>
* <p>
* e.g. <code>1024 x 768</code> > <code>4:3</code><br>
* e.g <code>1920 x 1080</code> > <code>16:9</code><br>
* e.g. <code>3440 x 1440</code> > <code>21:9</code>
* </p>
* <p>This also works for <code>1366 x 768</code> which is mathematically not <code>16:9</code> but marketed as such.</p>
*
* @param width e.g. 1920
* @param height e.g. 1080
* @return aspectRatio "16:9"
*/
private static String determineAspectRatio(int width, int height) {
// Define aspect ratios and calculate their decimal conversions
// List from https://en.wikipedia.org/wiki/Display_aspect_ratio
List<String> ratios = Arrays.asList("1:1", "5:4", "4:3", "3:2", "16:10", "16:9", "17:9", "21:9", "32:9");
List<Double> ratiosDecimals = ratioDecimalFromStrings(ratios);
// Calculate absolute difference between given the resolution's aspect ratio and the defined list of aspect ratios
double ratioArgs = (double) width / height;
List<Double> ratiosDiffs = new ArrayList<>();
for (Double ratioDec : ratiosDecimals) {
ratiosDiffs.add(Math.abs(ratioArgs - ratioDec));
}
// Determine and return closest available aspect ratio
int index = ratiosDiffs.indexOf(Collections.min(ratiosDiffs));
return ratios.get(index);
}
private static List<Double> ratioDecimalFromStrings(List<String> ratios) {
List<Double> ratiosDecimals = new LinkedList<>();
for (String ratio : ratios) {
int w = Integer.parseInt(ratio.split(":")[0]);
int h = Integer.parseInt(ratio.split(":")[1]);
ratiosDecimals.add((double) w / h);
}
return ratiosDecimals;
}
public static class Resolution implements Comparable<Resolution> {
private final int width;
private final int height;
private final String aspectRatio;
public Resolution(int width, int height, String aspectRatio) {
this.width = width;
this.height = height;
this.aspectRatio = aspectRatio;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public String getAspectRatio() {
return aspectRatio;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Resolution that = (Resolution) o;
return width == that.width && height == that.height && Objects.equals(aspectRatio, that.aspectRatio);
}
@Override
public int hashCode() {
return Objects.hash(width, height, aspectRatio);
}
@Override
public int compareTo(Resolution res) {
return Comparator
.comparingInt(Resolution::getWidth)
.thenComparingInt(Resolution::getHeight)
.compare(this, res);
}
@Override
public String toString() {
return width + " x " + height + " (" + aspectRatio + ")";
}
}
}