source: josm/trunk/src/org/openstreetmap/josm/tools/PlatformHookWindows.java@ 19103

Last change on this file since 19103 was 19103, checked in by taylor.smock, 8 months ago

Cleanup some new PMD warnings from PMD 7.x (followup of r19101)

  • Property svn:eol-style set to native
File size: 39.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static java.awt.event.InputEvent.ALT_DOWN_MASK;
5import static java.awt.event.InputEvent.CTRL_DOWN_MASK;
6import static java.awt.event.InputEvent.SHIFT_DOWN_MASK;
7import static java.awt.event.KeyEvent.VK_A;
8import static java.awt.event.KeyEvent.VK_C;
9import static java.awt.event.KeyEvent.VK_D;
10import static java.awt.event.KeyEvent.VK_DELETE;
11import static java.awt.event.KeyEvent.VK_DOWN;
12import static java.awt.event.KeyEvent.VK_ENTER;
13import static java.awt.event.KeyEvent.VK_ESCAPE;
14import static java.awt.event.KeyEvent.VK_F10;
15import static java.awt.event.KeyEvent.VK_F4;
16import static java.awt.event.KeyEvent.VK_LEFT;
17import static java.awt.event.KeyEvent.VK_NUM_LOCK;
18import static java.awt.event.KeyEvent.VK_PRINTSCREEN;
19import static java.awt.event.KeyEvent.VK_RIGHT;
20import static java.awt.event.KeyEvent.VK_SHIFT;
21import static java.awt.event.KeyEvent.VK_SPACE;
22import static java.awt.event.KeyEvent.VK_TAB;
23import static java.awt.event.KeyEvent.VK_UP;
24import static java.awt.event.KeyEvent.VK_V;
25import static java.awt.event.KeyEvent.VK_X;
26import static java.awt.event.KeyEvent.VK_Y;
27import static java.awt.event.KeyEvent.VK_Z;
28import static org.openstreetmap.josm.tools.I18n.marktr;
29import static org.openstreetmap.josm.tools.I18n.tr;
30import static org.openstreetmap.josm.tools.Utils.getSystemEnv;
31import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
32import static org.openstreetmap.josm.tools.WinRegistry.HKEY_LOCAL_MACHINE;
33
34import java.awt.Desktop;
35import java.io.BufferedWriter;
36import java.io.File;
37import java.io.IOException;
38import java.io.InputStream;
39import java.io.OutputStream;
40import java.io.OutputStreamWriter;
41import java.io.Writer;
42import java.lang.reflect.InvocationTargetException;
43import java.net.URISyntaxException;
44import java.nio.charset.StandardCharsets;
45import java.nio.file.DirectoryIteratorException;
46import java.nio.file.DirectoryStream;
47import java.nio.file.FileSystems;
48import java.nio.file.Files;
49import java.nio.file.InvalidPathException;
50import java.nio.file.Path;
51import java.security.KeyStore;
52import java.security.KeyStoreException;
53import java.security.MessageDigest;
54import java.security.NoSuchAlgorithmException;
55import java.security.cert.Certificate;
56import java.security.cert.CertificateEncodingException;
57import java.security.cert.CertificateException;
58import java.security.cert.X509Certificate;
59import java.text.ParseException;
60import java.util.ArrayList;
61import java.util.Arrays;
62import java.util.Collection;
63import java.util.Enumeration;
64import java.util.HashSet;
65import java.util.List;
66import java.util.Locale;
67import java.util.Properties;
68import java.util.Set;
69import java.util.concurrent.ExecutionException;
70import java.util.concurrent.TimeUnit;
71import java.util.regex.Matcher;
72import java.util.regex.Pattern;
73
74import org.openstreetmap.josm.data.Preferences;
75import org.openstreetmap.josm.data.StructUtils;
76import org.openstreetmap.josm.data.StructUtils.StructEntry;
77import org.openstreetmap.josm.data.StructUtils.WriteExplicitly;
78import org.openstreetmap.josm.io.CertificateAmendment.NativeCertAmend;
79import org.openstreetmap.josm.io.NetworkManager;
80import org.openstreetmap.josm.io.OnlineResource;
81import org.openstreetmap.josm.spi.preferences.Config;
82
83/**
84 * {@code PlatformHook} implementation for Microsoft Windows systems.
85 * @since 1023
86 */
87public class PlatformHookWindows implements PlatformHook {
88
89 /**
90 * Pattern of Microsoft .NET and Powershell version numbers in registry.
91 */
92 private static final Pattern MS_VERSION_PATTERN = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+.*)?");
93
94 /**
95 * Simple data class to hold information about a font.
96 * <p>
97 * Used for fontconfig.properties files.
98 */
99 public static class FontEntry {
100 /**
101 * The character subset. Basically a free identifier, but should be unique.
102 */
103 @StructEntry
104 public String charset;
105
106 /**
107 * Platform font name.
108 */
109 @StructEntry
110 @WriteExplicitly
111 public String name = "";
112
113 /**
114 * File name.
115 */
116 @StructEntry
117 @WriteExplicitly
118 public String file = "";
119
120 /**
121 * Constructs a new {@code FontEntry}.
122 */
123 public FontEntry() {
124 // Default constructor needed for construction by reflection
125 }
126
127 /**
128 * Constructs a new {@code FontEntry}.
129 * @param charset The character subset. Basically a free identifier, but should be unique
130 * @param name Platform font name
131 * @param file File name
132 */
133 public FontEntry(String charset, String name, String file) {
134 this.charset = charset;
135 this.name = name;
136 this.file = file;
137 }
138 }
139
140 private static final String WINDOWS_ROOT = "Windows-ROOT";
141
142 private static final String CURRENT_VERSION = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
143
144 private String oSBuildNumber;
145
146 @Override
147 public Platform getPlatform() {
148 return Platform.WINDOWS;
149 }
150
151 @Override
152 public void afterPrefStartupHook() {
153 extendFontconfig("fontconfig.properties.src");
154 }
155
156 @Override
157 public void startupHook(JavaExpirationCallback javaCallback, SanityCheckCallback sanityCheckCallback) {
158 warnSoonToBeUnsupportedJava(javaCallback);
159 checkExpiredJava(javaCallback);
160 PlatformHook.super.startupHook(javaCallback, sanityCheckCallback);
161 }
162
163 @Override
164 public void openUrl(String url) throws IOException {
165 if (!url.startsWith("file:/")) {
166 final String customBrowser = Config.getPref().get("browser.windows", "");
167 if (!customBrowser.isEmpty()) {
168 Runtime.getRuntime().exec(new String[]{customBrowser, url});
169 return;
170 }
171 }
172 try {
173 // Desktop API works fine under Windows
174 Desktop.getDesktop().browse(Utils.urlToURI(url));
175 } catch (IOException | URISyntaxException e) {
176 Logging.log(Logging.LEVEL_WARN, "Desktop class failed. Platform dependent fall back for open url in browser.", e);
177 Runtime.getRuntime().exec(new String[]{"rundll32", "url.dll,FileProtocolHandler", url});
178 }
179 }
180
181 @Override
182 @SuppressWarnings("squid:S103") // NOSONAR LineLength
183 public void initSystemShortcuts() {
184 final String reserved = marktr("reserved");
185 // CHECKSTYLE.OFF: LineLength
186 //Shortcut.registerSystemCut("system:menuexit", tr(reserved), VK_Q, CTRL_DOWN_MASK);
187 Shortcut.registerSystemShortcut("system:duplicate", tr(reserved), VK_D, CTRL_DOWN_MASK); // not really system, but to avoid odd results
188
189 // Windows 7 shortcuts: http://windows.microsoft.com/en-US/windows7/Keyboard-shortcuts
190
191 // Shortcuts with setAutomatic(): items with automatic shortcuts will not be added to the menu bar at all
192
193 // Don't know why Ctrl-Alt-Del isn't even listed on official Microsoft support page
194 Shortcut.registerSystemShortcut("system:reset", tr(reserved), VK_DELETE, CTRL_DOWN_MASK | ALT_DOWN_MASK).setAutomatic();
195
196 // Ease of Access keyboard shortcuts
197 Shortcut.registerSystemShortcut("microsoft-reserved-01", tr(reserved), VK_PRINTSCREEN, ALT_DOWN_MASK | SHIFT_DOWN_MASK).setAutomatic(); // Turn High Contrast on or off
198 Shortcut.registerSystemShortcut("microsoft-reserved-02", tr(reserved), VK_NUM_LOCK, ALT_DOWN_MASK | SHIFT_DOWN_MASK).setAutomatic(); // Turn Mouse Keys on or off
199 //Shortcut.registerSystemCut("microsoft-reserved-03", tr(reserved), VK_U, );// Open the Ease of Access Center (TODO: Windows-U, how to handle it in Java ?)
200
201 // General keyboard shortcuts
202 //Shortcut.registerSystemShortcut("system:help", tr(reserved), VK_F1, 0); // Display Help
203 Shortcut.registerSystemShortcut("system:copy", tr(reserved), VK_C, CTRL_DOWN_MASK); // Copy the selected item
204 Shortcut.registerSystemShortcut("system:cut", tr(reserved), VK_X, CTRL_DOWN_MASK); // Cut the selected item
205 Shortcut.registerSystemShortcut("system:paste", tr(reserved), VK_V, CTRL_DOWN_MASK); // Paste the selected item
206 Shortcut.registerSystemShortcut("system:undo", tr(reserved), VK_Z, CTRL_DOWN_MASK); // Undo an action
207 Shortcut.registerSystemShortcut("system:redo", tr(reserved), VK_Y, CTRL_DOWN_MASK); // Redo an action
208 //Shortcut.registerSystemCut("microsoft-reserved-10", tr(reserved), VK_DELETE, 0); // Delete the selected item and move it to the Recycle Bin
209 //Shortcut.registerSystemCut("microsoft-reserved-11", tr(reserved), VK_DELETE, SHIFT_DOWN_MASK); // Delete the selected item without moving it to the Recycle Bin first
210 //Shortcut.registerSystemCut("system:rename", tr(reserved), VK_F2, 0); // Rename the selected item
211 Shortcut.registerSystemShortcut("system:movefocusright", tr(reserved), VK_RIGHT, CTRL_DOWN_MASK); // Move the cursor to the beginning of the next word
212 Shortcut.registerSystemShortcut("system:movefocusleft", tr(reserved), VK_LEFT, CTRL_DOWN_MASK); // Move the cursor to the beginning of the previous word
213 Shortcut.registerSystemShortcut("system:movefocusdown", tr(reserved), VK_DOWN, CTRL_DOWN_MASK); // Move the cursor to the beginning of the next paragraph
214 Shortcut.registerSystemShortcut("system:movefocusup", tr(reserved), VK_UP, CTRL_DOWN_MASK); // Move the cursor to the beginning of the previous paragraph
215 //Shortcut.registerSystemCut("microsoft-reserved-17", tr(reserved), VK_RIGHT, CTRL_DOWN_MASK | SHIFT_DOWN_MASK); // Select a block of text
216 //Shortcut.registerSystemCut("microsoft-reserved-18", tr(reserved), VK_LEFT, CTRL_DOWN_MASK | SHIFT_DOWN_MASK); // Select a block of text
217 //Shortcut.registerSystemCut("microsoft-reserved-19", tr(reserved), VK_DOWN, CTRL_DOWN_MASK | SHIFT_DOWN_MASK); // Select a block of text
218 //Shortcut.registerSystemCut("microsoft-reserved-20", tr(reserved), VK_UP, CTRL_DOWN_MASK | SHIFT_DOWN_MASK); // Select a block of text
219 //Shortcut.registerSystemCut("microsoft-reserved-21", tr(reserved), VK_RIGHT, SHIFT_DOWN_MASK); // Select more than one item in a window or on the desktop, or select text within a document
220 //Shortcut.registerSystemCut("microsoft-reserved-22", tr(reserved), VK_LEFT, SHIFT_DOWN_MASK); // Select more than one item in a window or on the desktop, or select text within a document
221 //Shortcut.registerSystemCut("microsoft-reserved-23", tr(reserved), VK_DOWN, SHIFT_DOWN_MASK); // Select more than one item in a window or on the desktop, or select text within a document
222 //Shortcut.registerSystemCut("microsoft-reserved-24", tr(reserved), VK_UP, SHIFT_DOWN_MASK); // Select more than one item in a window or on the desktop, or select text within a document
223 //Shortcut.registerSystemCut("microsoft-reserved-25", tr(reserved), VK_RIGHT+, CTRL_DOWN_MASK); // Select multiple individual items in a window or on the desktop (TODO: ctrl+arrow+spacebar, how to handle it in Java ?)
224 //Shortcut.registerSystemCut("microsoft-reserved-26", tr(reserved), VK_LEFT+, CTRL_DOWN_MASK); // Select multiple individual items in a window or on the desktop (TODO: ctrl+arrow+spacebar, how to handle it in Java ?)
225 //Shortcut.registerSystemCut("microsoft-reserved-27", tr(reserved), VK_DOWN+, CTRL_DOWN_MASK); // Select multiple individual items in a window or on the desktop (TODO: ctrl+arrow+spacebar, how to handle it in Java ?)
226 //Shortcut.registerSystemCut("microsoft-reserved-28", tr(reserved), VK_UP+, CTRL_DOWN_MASK); // Select multiple individual items in a window or on the desktop (TODO: ctrl+arrow+spacebar, how to handle it in Java ?)
227 Shortcut.registerSystemShortcut("system:selectall", tr(reserved), VK_A, CTRL_DOWN_MASK); // Select all items in a document or window
228 //Shortcut.registerSystemCut("system:search", tr(reserved), VK_F3, 0); // Search for a file or folder
229 Shortcut.registerSystemShortcut("microsoft-reserved-31", tr(reserved), VK_ENTER, ALT_DOWN_MASK).setAutomatic(); // Display properties for the selected item
230 Shortcut.registerSystemShortcut("system:exit", tr(reserved), VK_F4, ALT_DOWN_MASK).setAutomatic(); // Close the active item, or exit the active program
231 Shortcut.registerSystemShortcut("microsoft-reserved-33", tr(reserved), VK_SPACE, ALT_DOWN_MASK).setAutomatic(); // Open the shortcut menu for the active window
232 //Shortcut.registerSystemCut("microsoft-reserved-34", tr(reserved), VK_F4, CTRL_DOWN_MASK); // Close the active document (in programs that allow you to have multiple documents open simultaneously)
233 Shortcut.registerSystemShortcut("microsoft-reserved-35", tr(reserved), VK_TAB, ALT_DOWN_MASK).setAutomatic(); // Switch between open items
234 Shortcut.registerSystemShortcut("microsoft-reserved-36", tr(reserved), VK_TAB, CTRL_DOWN_MASK | ALT_DOWN_MASK).setAutomatic(); // Use the arrow keys to switch between open items
235 //Shortcut.registerSystemCut("microsoft-reserved-37", tr(reserved), VK_TAB, ); // Cycle through programs on the taskbar by using Aero Flip 3-D (TODO: Windows-Tab, how to handle it in Java ?)
236 //Shortcut.registerSystemCut("microsoft-reserved-38", tr(reserved), VK_TAB, CTRL_DOWN_MASK | ); // Use the arrow keys to cycle through programs on the taskbar by using Aero Flip 3-D (TODO: Ctrl-Windows-Tab, how to handle it in Java ?)
237 Shortcut.registerSystemShortcut("microsoft-reserved-39", tr(reserved), VK_ESCAPE, ALT_DOWN_MASK).setAutomatic(); // Cycle through items in the order in which they were opened
238 //Shortcut.registerSystemCut("microsoft-reserved-40", tr(reserved), VK_F6, 0); // Cycle through screen elements in a window or on the desktop
239 //Shortcut.registerSystemCut("microsoft-reserved-41", tr(reserved), VK_F4, 0); // Display the address bar list in Windows Explorer
240 Shortcut.registerSystemShortcut("microsoft-reserved-42", tr(reserved), VK_F10, SHIFT_DOWN_MASK); // Display the shortcut menu for the selected item
241 Shortcut.registerSystemShortcut("microsoft-reserved-43", tr(reserved), VK_ESCAPE, CTRL_DOWN_MASK).setAutomatic(); // Open the Start menu
242 //Shortcut.registerSystemShortcut("microsoft-reserved-44", tr(reserved), VK_F10, 0); // Activate the menu bar in the active program
243 //Shortcut.registerSystemCut("microsoft-reserved-45", tr(reserved), VK_RIGHT, 0); // Open the next menu to the right, or open a submenu
244 //Shortcut.registerSystemCut("microsoft-reserved-46", tr(reserved), VK_LEFT, 0); // Open the next menu to the left, or close a submenu
245 //Shortcut.registerSystemCut("microsoft-reserved-47", tr(reserved), VK_F5, 0); // Refresh the active window
246 //Shortcut.registerSystemCut("microsoft-reserved-48", tr(reserved), VK_UP, ALT_DOWN_MASK); // View the folder one level up in Windows Explorer
247 //Shortcut.registerSystemCut("microsoft-reserved-49", tr(reserved), VK_ESCAPE, 0); // Cancel the current task
248 Shortcut.registerSystemShortcut("microsoft-reserved-50", tr(reserved), VK_ESCAPE, CTRL_DOWN_MASK | SHIFT_DOWN_MASK).setAutomatic(); // Open Task Manager
249 Shortcut.registerSystemShortcut("microsoft-reserved-51", tr(reserved), VK_SHIFT, ALT_DOWN_MASK).setAutomatic(); // Switch the input language when multiple input languages are enabled
250 Shortcut.registerSystemShortcut("microsoft-reserved-52", tr(reserved), VK_SHIFT, CTRL_DOWN_MASK).setAutomatic(); // Switch the keyboard layout when multiple keyboard layouts are enabled
251 //Shortcut.registerSystemCut("microsoft-reserved-53", tr(reserved), ); // Change the reading direction of text in right-to-left reading languages (TODO: unclear)
252 // CHECKSTYLE.ON: LineLength
253 }
254
255 @Override
256 public String getDefaultStyle() {
257 return "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
258 }
259
260 @Override
261 public boolean rename(File from, File to) {
262 if (to.exists())
263 Utils.deleteFile(to);
264 return from.renameTo(to);
265 }
266
267 @Override
268 public String getOSDescription() {
269 return Utils.strip(getSystemProperty("os.name")) + ' ' +
270 ((getSystemEnv("ProgramFiles(x86)") == null) ? "32" : "64") + "-Bit";
271 }
272
273 /**
274 * Returns the Windows product name from registry (example: "Windows 10 Pro")
275 * @return the Windows product name from registry
276 * @throws IllegalAccessException if Java language access control is enforced and the underlying method is inaccessible
277 * @throws InvocationTargetException if the underlying method throws an exception
278 * @since 12744
279 */
280 public static String getProductName() throws IllegalAccessException, InvocationTargetException {
281 return WinRegistry.readString(HKEY_LOCAL_MACHINE, CURRENT_VERSION, "ProductName");
282 }
283
284 /**
285 * Returns the Windows release identifier from registry (example: "1703")
286 * @return the Windows release identifier from registry
287 * @throws IllegalAccessException if Java language access control is enforced and the underlying method is inaccessible
288 * @throws InvocationTargetException if the underlying method throws an exception
289 * @since 12744
290 */
291 public static String getReleaseId() throws IllegalAccessException, InvocationTargetException {
292 return WinRegistry.readString(HKEY_LOCAL_MACHINE, CURRENT_VERSION, "ReleaseId");
293 }
294
295 /**
296 * Returns the Windows display version from registry (example: "22H2")
297 * @return the Windows display version from registry
298 * @throws IllegalAccessException if Java language access control is enforced and the underlying method is inaccessible
299 * @throws InvocationTargetException if the underlying method throws an exception
300 * @since 19041
301 */
302 public static String getDisplayVersion() throws IllegalAccessException, InvocationTargetException {
303 return WinRegistry.readString(HKEY_LOCAL_MACHINE, CURRENT_VERSION, "DisplayVersion");
304 }
305
306 /**
307 * Returns the Windows current build number from registry (example: "15063")
308 * @return the Windows current build number from registry
309 * @throws IllegalAccessException if Java language access control is enforced and the underlying method is inaccessible
310 * @throws InvocationTargetException if the underlying method throws an exception
311 * @since 12744
312 */
313 public static String getCurrentBuild() throws IllegalAccessException, InvocationTargetException {
314 return WinRegistry.readString(HKEY_LOCAL_MACHINE, CURRENT_VERSION, "CurrentBuild");
315 }
316
317 private static String buildOSBuildNumber() {
318 StringBuilder sb = new StringBuilder();
319 try {
320 sb.append(getProductName());
321 String displayVersion = getDisplayVersion();
322 if (displayVersion != null) {
323 sb.append(' ').append(displayVersion);
324 } else {
325 String releaseId = getReleaseId();
326 if (releaseId != null) {
327 sb.append(' ').append(releaseId);
328 }
329 }
330 sb.append(" (").append(getCurrentBuild()).append(')');
331 } catch (ReflectiveOperationException | JosmRuntimeException | NoClassDefFoundError e) {
332 Logging.log(Logging.LEVEL_ERROR, "Unable to get Windows build number", e);
333 Logging.debug(e);
334 }
335 return sb.toString();
336 }
337
338 @Override
339 public String getOSBuildNumber() {
340 if (oSBuildNumber == null) {
341 oSBuildNumber = buildOSBuildNumber();
342 }
343 return oSBuildNumber;
344 }
345
346 /**
347 * Loads Windows-ROOT keystore.
348 * @return Windows-ROOT keystore
349 * @throws NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
350 * @throws CertificateException if any of the certificates in the keystore could not be loaded
351 * @throws IOException if there is an I/O or format problem with the keystore data, if a password is required but not given
352 * @throws KeyStoreException if no Provider supports a KeyStore implementation for the type "Windows-ROOT"
353 * @since 7343
354 */
355 public static KeyStore getRootKeystore() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
356 KeyStore ks = KeyStore.getInstance(WINDOWS_ROOT);
357 ks.load(null, null);
358 return ks;
359 }
360
361 @Override
362 public X509Certificate getX509Certificate(NativeCertAmend certAmend)
363 throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
364 MessageDigest md = MessageDigest.getInstance("SHA-256");
365 // Get Windows Trust Root Store
366 KeyStore ks = getRootKeystore();
367 // Search by alias (fast)
368 for (String winAlias : certAmend.getNativeAliases()) {
369 Certificate result = ks.getCertificate(winAlias);
370 // Check for SHA-256 signature, as sometimes Microsoft can ship several certificates with the same alias, for example:
371 // AC RAIZ FNMT-RCM: EBC5570C29018C4D67B1AA127BAF12F703B4611EBC17B7DAB5573894179B93FA (SHA256)
372 // AC RAIZ FNMT-RCM: 4D9EBB28825C9643AB15D54E5F9614F13CB3E95DE3CF4EAC971301F320F9226E (SHA1)
373 if (!sha256matches(result, certAmend, md)) {
374 Logging.trace("Ignoring {0} as SHA-256 signature does not match", result);
375 result = null;
376 }
377 if (result == null && !NetworkManager.isOffline(OnlineResource.CERTIFICATES)) {
378 // Make a web request to target site to force Windows to update if needed its trust root store from its certificate trust list
379 // A better, but a lot more complex method might be to get certificate list from Windows Registry with PowerShell
380 // using (Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\SystemCertificates\\AuthRoot\\AutoUpdate').EncodedCtl)
381 // then decode it using CertUtil -dump or calling CertCreateCTLContext API using JNI, and finally find and decode the certificate
382 Logging.trace(webRequest(certAmend.getWebSite()));
383 // Reload Windows Trust Root Store and search again by alias (fast)
384 ks = getRootKeystore();
385 result = ks.getCertificate(winAlias);
386 }
387 if (result instanceof X509Certificate) {
388 return (X509Certificate) result;
389 }
390 }
391 // If not found, search by SHA-256 (slower)
392 for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
393 String alias = aliases.nextElement();
394 Certificate result = ks.getCertificate(alias);
395 if (sha256matches(result, certAmend, md)) {
396 Logging.warn("Certificate not found for alias ''{0}'' but found for alias ''{1}''", certAmend.getNativeAliases(), alias);
397 return (X509Certificate) result;
398 }
399 }
400 // Not found
401 return null;
402 }
403
404 private static boolean sha256matches(Certificate result, NativeCertAmend certAmend, MessageDigest md) throws CertificateEncodingException {
405 return result instanceof X509Certificate
406 && certAmend.getSha256().equalsIgnoreCase(Utils.toHexString(md.digest(result.getEncoded())));
407 }
408
409 @Override
410 public File getDefaultCacheDirectory() {
411 String p = getSystemEnv("LOCALAPPDATA");
412 if (Utils.isEmpty(p)) {
413 // Fallback for Windows OS earlier than Windows Vista, where the variable is not defined
414 p = getSystemEnv("APPDATA");
415 }
416 return new File(new File(p, Preferences.getJOSMDirectoryBaseName()), "cache");
417 }
418
419 @Override
420 public File getDefaultPrefDirectory() {
421 return new File(getSystemEnv("APPDATA"), Preferences.getJOSMDirectoryBaseName());
422 }
423
424 @Override
425 public File getDefaultUserDataDirectory() {
426 // Use preferences directory by default
427 return Config.getDirs().getPreferencesDirectory(false);
428 }
429
430 /**
431 * <p>Add more fallback fonts to the Java runtime, in order to get
432 * support for more scripts.</p>
433 *
434 * <p>The font configuration in Java doesn't include some Indic scripts,
435 * even though MS Windows ships with fonts that cover these unicode ranges.</p>
436 *
437 * <p>To fix this, the fontconfig.properties template is copied to the JOSM
438 * cache folder. Then, the additional entries are added to the font
439 * configuration. Finally the system property "sun.awt.fontconfig" is set
440 * to the customized fontconfig.properties file.</p>
441 *
442 * <p>This is a crude hack, but better than no font display at all for these languages.
443 * There is no guarantee, that the template file
444 * ($JAVA_HOME/lib/fontconfig.properties.src) matches the default
445 * configuration (which is in a binary format).
446 * Furthermore, the system property "sun.awt.fontconfig" is undocumented and
447 * may no longer work in future versions of Java.</p>
448 *
449 * <p>Related Java bug: <a href="https://bugs.openjdk.java.net/browse/JDK-8008572">JDK-8008572</a></p>
450 *
451 * @param templateFileName file name of the fontconfig.properties template file
452 */
453 protected void extendFontconfig(String templateFileName) {
454 String customFontconfigFile = Config.getPref().get("fontconfig.properties", null);
455 if (customFontconfigFile != null) {
456 Utils.updateSystemProperty("sun.awt.fontconfig", customFontconfigFile);
457 return;
458 }
459 if (!Config.getPref().getBoolean("font.extended-unicode", true))
460 return;
461
462 String javaLibPath = getSystemProperty("java.home") + File.separator + "lib";
463 Path templateFile = FileSystems.getDefault().getPath(javaLibPath, templateFileName);
464 String templatePath = templateFile.toString();
465 if (templatePath.startsWith("null") || !Files.isReadable(templateFile)) {
466 Logging.warn("extended font config - unable to find font config template file {0}", templatePath);
467 return;
468 }
469 try (InputStream fis = Files.newInputStream(templateFile)) {
470 Properties props = new Properties();
471 props.load(fis);
472 byte[] content = Files.readAllBytes(templateFile);
473 File cachePath = Config.getDirs().getCacheDirectory(true);
474 Path fontconfigFile = cachePath.toPath().resolve("fontconfig.properties");
475 OutputStream os = Files.newOutputStream(fontconfigFile); // NOPMD
476 os.write(content);
477 try (Writer w = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
478 Collection<FontEntry> extrasPref = StructUtils.getListOfStructs(Config.getPref(),
479 "font.extended-unicode.extra-items", getAdditionalFonts(), FontEntry.class);
480 Collection<FontEntry> extras = new ArrayList<>();
481 w.append("\n\n# Added by JOSM to extend unicode coverage of Java font support:\n\n");
482 List<String> allCharSubsets = new ArrayList<>();
483 for (FontEntry entry: extrasPref) {
484 Collection<String> fontsAvail = getInstalledFonts();
485 if (fontsAvail != null && fontsAvail.contains(entry.file.toUpperCase(Locale.ENGLISH))) {
486 if (!allCharSubsets.contains(entry.charset)) {
487 allCharSubsets.add(entry.charset);
488 extras.add(entry);
489 } else {
490 Logging.trace("extended font config - already registered font for charset ''{0}'' - skipping ''{1}''",
491 entry.charset, entry.name);
492 }
493 } else {
494 Logging.trace("extended font config - Font ''{0}'' not found on system - skipping", entry.name);
495 }
496 }
497 for (FontEntry entry: extras) {
498 allCharSubsets.add(entry.charset);
499 if ("".equals(entry.name)) {
500 continue;
501 }
502 String key = "allfonts." + entry.charset;
503 String value = entry.name;
504 String prevValue = props.getProperty(key);
505 if (prevValue != null && !prevValue.equals(value)) {
506 Logging.warn("extended font config - overriding ''{0}={1}'' with ''{2}''", key, prevValue, value);
507 }
508 w.append(key).append('=').append(value).append('\n');
509 }
510 w.append('\n');
511 for (FontEntry entry: extras) {
512 if ("".equals(entry.name) || "".equals(entry.file)) {
513 continue;
514 }
515 String key = "filename." + entry.name.replace(' ', '_');
516 String value = entry.file;
517 String prevValue = props.getProperty(key);
518 if (prevValue != null && !prevValue.equals(value)) {
519 Logging.warn("extended font config - overriding ''{0}={1}'' with ''{2}''", key, prevValue, value);
520 }
521 w.append(key).append('=').append(value).append('\n');
522 }
523 w.append('\n');
524 w.append("sequence.fallback=");
525 String fallback = props.getProperty("sequence.fallback");
526 if (fallback != null) {
527 w.append(fallback).append(",");
528 }
529 w.append(String.join(",", allCharSubsets)).append("\n");
530 }
531 Utils.updateSystemProperty("sun.awt.fontconfig", fontconfigFile.toString());
532 } catch (IOException | InvalidPathException ex) {
533 Logging.error(ex);
534 }
535 }
536
537 /**
538 * Get a list of fonts that are installed on the system.
539 *
540 * Must be done without triggering the Java Font initialization.
541 * (See {@link #extendFontconfig(java.lang.String)}, have to set system
542 * property first, which is then read by sun.awt.FontConfiguration upon initialization.)
543 *
544 * @return list of file names
545 */
546 protected Collection<String> getInstalledFonts() {
547 // Cannot use GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()
548 // because we have to set the system property before Java initializes its fonts.
549 // Use more low-level method to find the installed fonts.
550 List<String> fontsAvail = new ArrayList<>();
551 String systemRoot = getSystemEnv("SYSTEMROOT");
552 if (systemRoot == null) {
553 return fontsAvail;
554 }
555 Path fontPath = FileSystems.getDefault().getPath(systemRoot, "Fonts");
556 try (DirectoryStream<Path> ds = Files.newDirectoryStream(fontPath)) {
557 for (Path p : ds) {
558 Path filename = p.getFileName();
559 if (filename != null) {
560 fontsAvail.add(filename.toString().toUpperCase(Locale.ENGLISH));
561 }
562 }
563 fontsAvail.add(""); // for devanagari
564 } catch (IOException | DirectoryIteratorException ex) {
565 Logging.log(Logging.LEVEL_ERROR, ex);
566 Logging.warn("extended font config - failed to load available Fonts");
567 fontsAvail = null;
568 }
569 return fontsAvail;
570 }
571
572 /**
573 * Get default list of additional fonts to add to the configuration.
574 *
575 * Java will choose thee first font in the list that can render a certain character.
576 *
577 * @return list of FontEntry objects
578 */
579 protected Collection<FontEntry> getAdditionalFonts() {
580 Collection<FontEntry> def = new ArrayList<>(33);
581 def.add(new FontEntry("devanagari", "", "")); // just include in fallback list font already defined in template
582
583 // Windows scripts: https://msdn.microsoft.com/en-us/goglobal/bb688099.aspx
584 // IE default fonts: https://msdn.microsoft.com/en-us/library/ie/dn467844(v=vs.85).aspx
585
586 // Windows 10 and later
587 def.add(new FontEntry("historic", "Segoe UI Historic", "SEGUIHIS.TTF")); // historic charsets
588
589 // Windows 8/8.1 and later
590 def.add(new FontEntry("javanese", "Javanese Text", "JAVATEXT.TTF")); // ISO 639: jv
591 def.add(new FontEntry("leelawadee", "Leelawadee", "LEELAWAD.TTF")); // ISO 639: bug
592 def.add(new FontEntry("malgun", "Malgun Gothic", "MALGUN.TTF")); // ISO 639: ko
593 def.add(new FontEntry("myanmar", "Myanmar Text", "MMRTEXT.TTF")); // ISO 639: my
594 def.add(new FontEntry("nirmala", "Nirmala UI", "NIRMALA.TTF")); // ISO 639: sat,srb
595 def.add(new FontEntry("segoeui", "Segoe UI", "SEGOEUI.TTF")); // ISO 639: lis
596 def.add(new FontEntry("emoji", "Segoe UI Emoji", "SEGUIEMJ.TTF")); // emoji symbol characters
597
598 // Windows 7 and later
599 def.add(new FontEntry("nko_tifinagh_vai_osmanya", "Ebrima", "EBRIMA.TTF")); // ISO 639: ber. Nko only since Win 8
600 def.add(new FontEntry("khmer1", "Khmer UI", "KHMERUI.TTF")); // ISO 639: km
601 def.add(new FontEntry("lao1", "Lao UI", "LAOUI.TTF")); // ISO 639: lo
602 def.add(new FontEntry("tai_le", "Microsoft Tai Le", "TAILE.TTF")); // ISO 639: khb
603 def.add(new FontEntry("new_tai_lue", "Microsoft New Tai Lue", "NTHAILU.TTF")); // ISO 639: khb
604
605 // Windows Vista and later:
606 def.add(new FontEntry("ethiopic", "Nyala", "NYALA.TTF")); // ISO 639: am,gez,ti
607 def.add(new FontEntry("tibetan", "Microsoft Himalaya", "HIMALAYA.TTF")); // ISO 639: bo,dz
608 def.add(new FontEntry("cherokee", "Plantagenet Cherokee", "PLANTC.TTF")); // ISO 639: chr
609 def.add(new FontEntry("unified_canadian", "Euphemia", "EUPHEMIA.TTF")); // ISO 639: cr,in
610 def.add(new FontEntry("khmer2", "DaunPenh", "DAUNPENH.TTF")); // ISO 639: km
611 def.add(new FontEntry("khmer3", "MoolBoran", "MOOLBOR.TTF")); // ISO 639: km
612 def.add(new FontEntry("lao_thai", "DokChampa", "DOKCHAMP.TTF")); // ISO 639: lo
613 def.add(new FontEntry("mongolian", "Mongolian Baiti", "MONBAITI.TTF")); // ISO 639: mn
614 def.add(new FontEntry("oriya", "Kalinga", "KALINGA.TTF")); // ISO 639: or
615 def.add(new FontEntry("sinhala", "Iskoola Pota", "ISKPOTA.TTF")); // ISO 639: si
616 def.add(new FontEntry("yi", "Yi Baiti", "MSYI.TTF")); // ISO 639: ii
617
618 // Windows XP and later
619 def.add(new FontEntry("gujarati", "Shruti", "SHRUTI.TTF"));
620 def.add(new FontEntry("kannada", "Tunga", "TUNGA.TTF"));
621 def.add(new FontEntry("gurmukhi", "Raavi", "RAAVI.TTF"));
622 def.add(new FontEntry("telugu", "Gautami", "GAUTAMI.TTF"));
623 def.add(new FontEntry("bengali", "Vrinda", "VRINDA.TTF")); // since XP SP2
624 def.add(new FontEntry("syriac", "Estrangelo Edessa", "ESTRE.TTF")); // ISO 639: arc
625 def.add(new FontEntry("thaana", "MV Boli", "MVBOLI.TTF")); // ISO 639: dv
626 def.add(new FontEntry("malayalam", "Kartika", "KARTIKA.TTF")); // ISO 639: ml; since XP SP2
627
628 // Windows 2000 and later
629 def.add(new FontEntry("tamil", "Latha", "LATHA.TTF"));
630
631 // Comes with MS Office & Outlook 2000. Good unicode coverage, so add if available.
632 def.add(new FontEntry("arialuni", "Arial Unicode MS", "ARIALUNI.TTF"));
633
634 return def;
635 }
636
637 /**
638 * Determines if the .NET framework 4.5 (or later) is installed.
639 * Windows 7 ships by default with an older version.
640 * @return {@code true} if the .NET framework 4.5 (or later) is installed.
641 * @since 13463
642 */
643 public static boolean isDotNet45Installed() {
644 try {
645 // https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed#net_d
646 // "The existence of the Release DWORD indicates that the .NET Framework 4.5 or later has been installed"
647 // Great, but our WinRegistry only handles REG_SZ type, so we have to check the Version key
648 String version = WinRegistry.readString(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full", "Version");
649 if (version != null) {
650 Matcher m = MS_VERSION_PATTERN.matcher(version);
651 if (m.matches()) {
652 int maj = Integer.parseInt(m.group(1));
653 int min = Integer.parseInt(m.group(2));
654 return (maj == 4 && min >= 5) || maj > 4;
655 }
656 }
657 } catch (IllegalAccessException | InvocationTargetException | NumberFormatException e) {
658 Logging.error(e);
659 }
660 return false;
661 }
662
663 /**
664 * Returns the major version number of PowerShell.
665 * @return the major version number of PowerShell. -1 in case of error
666 * @since 13465
667 */
668 public static int getPowerShellVersion() {
669 try {
670 String version = WinRegistry.readString(
671 HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Powershell\\3\\PowershellEngine", "PowershellVersion");
672 if (version != null) {
673 Matcher m = MS_VERSION_PATTERN.matcher(version);
674 if (m.matches()) {
675 return Integer.parseInt(m.group(1));
676 }
677 }
678 } catch (NumberFormatException | IllegalAccessException | InvocationTargetException e) {
679 Logging.error(e);
680 }
681 return -1;
682 }
683
684 /**
685 * Performs a web request using Windows CryptoAPI (through PowerShell).
686 * This is useful to ensure Windows trust store will contain a specific root CA.
687 * @param uri the web URI to request
688 * @return HTTP response from the given URI
689 * @throws IOException if any I/O error occurs
690 * @since 13458
691 */
692 public static String webRequest(String uri) throws IOException {
693 // With PS 6.0 (not yet released in Windows) we could simply use:
694 // Invoke-WebRequest -SSlProtocol Tsl12 $uri
695 // .NET framework < 4.5 does not support TLS 1.2 (https://stackoverflow.com/a/43240673/2257172)
696 if (isDotNet45Installed() && getPowerShellVersion() >= 3) {
697 try {
698 // The following works with PS 3.0 (Windows 8+), https://stackoverflow.com/a/41618979/2257172
699 return Utils.execOutput(Arrays.asList("powershell", "-Command",
700 "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;"+
701 "[System.Net.WebRequest]::Create('"+uri+"').GetResponse()"
702 ), 5, TimeUnit.SECONDS);
703 } catch (ExecutionException | InterruptedException e) {
704 Logging.warn("Unable to request certificate of " + uri);
705 Logging.debug(e);
706 }
707 }
708 return null;
709 }
710
711 @Override
712 public File resolveFileLink(File file) {
713 if (file.getName().endsWith(".lnk")) {
714 try {
715 return new File(new WindowsShortcut(file).getRealFilename());
716 } catch (IOException | ParseException e) {
717 Logging.error(e);
718 }
719 }
720 return file;
721 }
722
723 @Override
724 public Collection<String> getPossiblePreferenceDirs() {
725 Set<String> locations = new HashSet<>();
726 String appdata = getSystemEnv("APPDATA");
727 if (appdata != null && getSystemEnv("ALLUSERSPROFILE") != null
728 && appdata.lastIndexOf(File.separator) != -1) {
729 appdata = appdata.substring(appdata.lastIndexOf(File.separator));
730 locations.add(new File(new File(getSystemEnv("ALLUSERSPROFILE"), appdata), "JOSM").getPath());
731 }
732 return locations;
733 }
734}
Note: See TracBrowser for help on using the repository browser.