source: josm/trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java@ 12218

Last change on this file since 12218 was 12217, checked in by Don-vip, 7 years ago

see #14821 - workaround for JDK-8180379/JDK-8179014 : prevent JVM crash when opening a file chooser on Windows 10 Creators Update with Windows look & feel + add information about OS build number for Windows & macOS + add utilities to get Java update/build version numbers

  • Property svn:eol-style set to native
File size: 18.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Desktop;
7import java.awt.Dimension;
8import java.awt.event.KeyEvent;
9import java.io.BufferedReader;
10import java.io.File;
11import java.io.IOException;
12import java.net.URI;
13import java.net.URISyntaxException;
14import java.nio.charset.StandardCharsets;
15import java.nio.file.Files;
16import java.nio.file.Path;
17import java.nio.file.Paths;
18import java.util.Arrays;
19import java.util.List;
20import java.util.Locale;
21
22import javax.swing.JOptionPane;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.gui.ExtendedDialog;
26import org.openstreetmap.josm.gui.util.GuiHelper;
27
28/**
29 * {@code PlatformHook} base implementation.
30 *
31 * Don't write (Main.platform instanceof PlatformHookUnixoid) because other platform
32 * hooks are subclasses of this class.
33 */
34public class PlatformHookUnixoid implements PlatformHook {
35
36 private String osDescription;
37
38 @Override
39 public void preStartupHook() {
40 // See #12022 - Disable GNOME ATK Java wrapper as it causes a lot of serious trouble
41 if ("org.GNOME.Accessibility.AtkWrapper".equals(System.getProperty("assistive_technologies"))) {
42 System.clearProperty("assistive_technologies");
43 }
44 }
45
46 @Override
47 public void openUrl(String url) throws IOException {
48 for (String program : Main.pref.getCollection("browser.unix",
49 Arrays.asList("xdg-open", "#DESKTOP#", "$BROWSER", "gnome-open", "kfmclient openURL", "firefox"))) {
50 try {
51 if ("#DESKTOP#".equals(program)) {
52 Desktop.getDesktop().browse(new URI(url));
53 } else if (program.startsWith("$")) {
54 program = System.getenv().get(program.substring(1));
55 Runtime.getRuntime().exec(new String[]{program, url});
56 } else {
57 Runtime.getRuntime().exec(new String[]{program, url});
58 }
59 return;
60 } catch (IOException | URISyntaxException e) {
61 Main.warn(e);
62 }
63 }
64 }
65
66 @Override
67 public void initSystemShortcuts() {
68 // CHECKSTYLE.OFF: LineLength
69 // TODO: Insert system shortcuts here. See Windows and especially OSX to see how to.
70 for (int i = KeyEvent.VK_F1; i <= KeyEvent.VK_F12; ++i) {
71 Shortcut.registerSystemShortcut("screen:toogle"+i, tr("reserved"), i, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
72 .setAutomatic();
73 }
74 Shortcut.registerSystemShortcut("system:reset", tr("reserved"), KeyEvent.VK_DELETE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
75 .setAutomatic();
76 Shortcut.registerSystemShortcut("system:resetX", tr("reserved"), KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
77 .setAutomatic();
78 // CHECKSTYLE.ON: LineLength
79 }
80
81 @Override
82 public String getDefaultStyle() {
83 return "javax.swing.plaf.metal.MetalLookAndFeel";
84 }
85
86 /**
87 * Determines if the distribution is Debian or Ubuntu, or a derivative.
88 * @return {@code true} if the distribution is Debian, Ubuntu or Mint, {@code false} otherwise
89 */
90 public static boolean isDebianOrUbuntu() {
91 try {
92 String dist = Utils.execOutput(Arrays.asList("lsb_release", "-i", "-s"));
93 return "Debian".equalsIgnoreCase(dist) || "Ubuntu".equalsIgnoreCase(dist) || "Mint".equalsIgnoreCase(dist);
94 } catch (IOException e) {
95 // lsb_release is not available on all Linux systems, so don't log at warning level
96 Main.debug(e);
97 return false;
98 }
99 }
100
101 /**
102 * Determines if the JVM is OpenJDK-based.
103 * @return {@code true} if {@code java.home} contains "openjdk", {@code false} otherwise
104 * @since 6951
105 */
106 public static boolean isOpenJDK() {
107 String javaHome = System.getProperty("java.home");
108 return javaHome != null && javaHome.contains("openjdk");
109 }
110
111 /**
112 * Get the package name including detailed version.
113 * @param packageNames The possible package names (when a package can have different names on different distributions)
114 * @return The package name and package version if it can be identified, null otherwise
115 * @since 7314
116 */
117 public static String getPackageDetails(String... packageNames) {
118 try {
119 // CHECKSTYLE.OFF: SingleSpaceSeparator
120 boolean dpkg = Paths.get("/usr/bin/dpkg-query").toFile().exists();
121 boolean eque = Paths.get("/usr/bin/equery").toFile().exists();
122 boolean rpm = Paths.get("/bin/rpm").toFile().exists();
123 // CHECKSTYLE.ON: SingleSpaceSeparator
124 if (dpkg || rpm || eque) {
125 for (String packageName : packageNames) {
126 String[] args;
127 if (dpkg) {
128 args = new String[] {"dpkg-query", "--show", "--showformat", "${Architecture}-${Version}", packageName};
129 } else if (eque) {
130 args = new String[] {"equery", "-q", "list", "-e", "--format=$fullversion", packageName};
131 } else {
132 args = new String[] {"rpm", "-q", "--qf", "%{arch}-%{version}", packageName};
133 }
134 String version = Utils.execOutput(Arrays.asList(args));
135 if (version != null && !version.contains("not installed")) {
136 return packageName + ':' + version;
137 }
138 }
139 }
140 } catch (IOException e) {
141 Main.warn(e);
142 }
143 return null;
144 }
145
146 /**
147 * Get the Java package name including detailed version.
148 *
149 * Some Java bugs are specific to a certain security update, so in addition
150 * to the Java version, we also need the exact package version.
151 *
152 * @return The package name and package version if it can be identified, null otherwise
153 */
154 public String getJavaPackageDetails() {
155 String home = System.getProperty("java.home");
156 if (home.contains("java-8-openjdk") || home.contains("java-1.8.0-openjdk")) {
157 return getPackageDetails("openjdk-8-jre", "java-1_8_0-openjdk", "java-1.8.0-openjdk");
158 } else if (home.contains("java-9-openjdk") || home.contains("java-1.9.0-openjdk")) {
159 return getPackageDetails("openjdk-9-jre", "java-1_9_0-openjdk", "java-1.9.0-openjdk");
160 } else if (home.contains("icedtea")) {
161 return getPackageDetails("icedtea-bin");
162 } else if (home.contains("oracle")) {
163 return getPackageDetails("oracle-jdk-bin", "oracle-jre-bin");
164 }
165 return null;
166 }
167
168 /**
169 * Get the Web Start package name including detailed version.
170 *
171 * OpenJDK packages are shipped with icedtea-web package,
172 * but its version generally does not match main java package version.
173 *
174 * Simply return {@code null} if there's no separate package for Java WebStart.
175 *
176 * @return The package name and package version if it can be identified, null otherwise
177 */
178 public String getWebStartPackageDetails() {
179 if (isOpenJDK()) {
180 return getPackageDetails("icedtea-netx", "icedtea-web");
181 }
182 return null;
183 }
184
185 /**
186 * Get the Gnome ATK wrapper package name including detailed version.
187 *
188 * Debian and Ubuntu derivatives come with a pre-enabled accessibility software
189 * completely buggy that makes Swing crash in a lot of different ways.
190 *
191 * Simply return {@code null} if it's not found.
192 *
193 * @return The package name and package version if it can be identified, null otherwise
194 */
195 public String getAtkWrapperPackageDetails() {
196 if (isOpenJDK() && isDebianOrUbuntu()) {
197 return getPackageDetails("libatk-wrapper-java");
198 }
199 return null;
200 }
201
202 protected String buildOSDescription() {
203 String osName = System.getProperty("os.name");
204 if ("Linux".equalsIgnoreCase(osName)) {
205 try {
206 // Try lsb_release (only available on LSB-compliant Linux systems,
207 // see https://www.linuxbase.org/lsb-cert/productdir.php?by_prod )
208 String line = exec("lsb_release -ds");
209 if (line != null && !line.isEmpty()) {
210 line = line.replaceAll("\"+", "");
211 line = line.replaceAll("NAME=", ""); // strange code for some Gentoo's
212 if (line.startsWith("Linux ")) // e.g. Linux Mint
213 return line;
214 else if (!line.isEmpty())
215 return "Linux " + line;
216 }
217 } catch (IOException e) {
218 Main.debug(e);
219 // Non LSB-compliant Linux system. List of common fallback release files: http://linuxmafia.com/faq/Admin/release-files.html
220 for (LinuxReleaseInfo info : new LinuxReleaseInfo[]{
221 new LinuxReleaseInfo("/etc/lsb-release", "DISTRIB_DESCRIPTION", "DISTRIB_ID", "DISTRIB_RELEASE"),
222 new LinuxReleaseInfo("/etc/os-release", "PRETTY_NAME", "NAME", "VERSION"),
223 new LinuxReleaseInfo("/etc/arch-release"),
224 new LinuxReleaseInfo("/etc/debian_version", "Debian GNU/Linux "),
225 new LinuxReleaseInfo("/etc/fedora-release"),
226 new LinuxReleaseInfo("/etc/gentoo-release"),
227 new LinuxReleaseInfo("/etc/redhat-release"),
228 new LinuxReleaseInfo("/etc/SuSE-release")
229 }) {
230 String description = info.extractDescription();
231 if (description != null && !description.isEmpty()) {
232 return "Linux " + description;
233 }
234 }
235 }
236 }
237 return osName;
238 }
239
240 @Override
241 public String getOSDescription() {
242 if (osDescription == null) {
243 osDescription = buildOSDescription();
244 }
245 return osDescription;
246 }
247
248 protected static class LinuxReleaseInfo {
249 private final String path;
250 private final String descriptionField;
251 private final String idField;
252 private final String releaseField;
253 private final boolean plainText;
254 private final String prefix;
255
256 public LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField) {
257 this(path, descriptionField, idField, releaseField, false, null);
258 }
259
260 public LinuxReleaseInfo(String path) {
261 this(path, null, null, null, true, null);
262 }
263
264 public LinuxReleaseInfo(String path, String prefix) {
265 this(path, null, null, null, true, prefix);
266 }
267
268 private LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField, boolean plainText, String prefix) {
269 this.path = path;
270 this.descriptionField = descriptionField;
271 this.idField = idField;
272 this.releaseField = releaseField;
273 this.plainText = plainText;
274 this.prefix = prefix;
275 }
276
277 @Override public String toString() {
278 return "ReleaseInfo [path=" + path + ", descriptionField=" + descriptionField +
279 ", idField=" + idField + ", releaseField=" + releaseField + ']';
280 }
281
282 /**
283 * Extracts OS detailed information from a Linux release file (/etc/xxx-release)
284 * @return The OS detailed information, or {@code null}
285 */
286 public String extractDescription() {
287 String result = null;
288 if (path != null) {
289 Path p = Paths.get(path);
290 if (p.toFile().exists()) {
291 try (BufferedReader reader = Files.newBufferedReader(p, StandardCharsets.UTF_8)) {
292 String id = null;
293 String release = null;
294 String line;
295 while (result == null && (line = reader.readLine()) != null) {
296 if (line.contains("=")) {
297 String[] tokens = line.split("=");
298 if (tokens.length >= 2) {
299 // Description, if available, contains exactly what we need
300 if (descriptionField != null && descriptionField.equalsIgnoreCase(tokens[0])) {
301 result = Utils.strip(tokens[1]);
302 } else if (idField != null && idField.equalsIgnoreCase(tokens[0])) {
303 id = Utils.strip(tokens[1]);
304 } else if (releaseField != null && releaseField.equalsIgnoreCase(tokens[0])) {
305 release = Utils.strip(tokens[1]);
306 }
307 }
308 } else if (plainText && !line.isEmpty()) {
309 // Files composed of a single line
310 result = Utils.strip(line);
311 }
312 }
313 // If no description has been found, try to rebuild it with "id" + "release" (i.e. "name" + "version")
314 if (result == null && id != null && release != null) {
315 result = id + ' ' + release;
316 }
317 } catch (IOException e) {
318 // Ignore
319 Main.trace(e);
320 }
321 }
322 }
323 // Append prefix if any
324 if (result != null && !result.isEmpty() && prefix != null && !prefix.isEmpty()) {
325 result = prefix + result;
326 }
327 if (result != null)
328 result = result.replaceAll("\"+", "");
329 return result;
330 }
331 }
332
333 // Method unused, but kept for translation already done. To reuse during Java 9 migration
334 protected void askUpdateJava(final String version, final String url) {
335 GuiHelper.runInEDTAndWait(() -> {
336 ExtendedDialog ed = new ExtendedDialog(
337 Main.parent,
338 tr("Outdated Java version"),
339 new String[]{tr("OK"), tr("Update Java"), tr("Cancel")});
340 // Check if the dialog has not already been permanently hidden by user
341 if (!ed.toggleEnable("askUpdateJava9").toggleCheckState()) {
342 ed.setButtonIcons(new String[]{"ok", "java", "cancel"}).setCancelButton(3);
343 ed.setMinimumSize(new Dimension(480, 300));
344 ed.setIcon(JOptionPane.WARNING_MESSAGE);
345 StringBuilder content = new StringBuilder(tr("You are running version {0} of Java.", "<b>"+version+"</b>"))
346 .append("<br><br>");
347 if ("Sun Microsystems Inc.".equals(System.getProperty("java.vendor")) && !isOpenJDK()) {
348 content.append("<b>").append(tr("This version is no longer supported by {0} since {1} and is not recommended for use.",
349 "Oracle", tr("April 2015"))).append("</b><br><br>"); // TODO: change date once Java 8 EOL is announced
350 }
351 content.append("<b>")
352 .append(tr("JOSM will soon stop working with this version; we highly recommend you to update to Java {0}.", "8"))
353 .append("</b><br><br>")
354 .append(tr("Would you like to update now ?"));
355 ed.setContent(content.toString());
356
357 if (ed.showDialog().getValue() == 2) {
358 try {
359 openUrl(url);
360 } catch (IOException e) {
361 Main.warn(e);
362 }
363 }
364 }
365 });
366 }
367
368 /**
369 * Get the dot directory <code>~/.josm</code>.
370 * @return the dot directory
371 */
372 private static File getDotDirectory() {
373 String dirName = "." + Main.pref.getJOSMDirectoryBaseName().toLowerCase(Locale.ENGLISH);
374 return new File(System.getProperty("user.home"), dirName);
375 }
376
377 /**
378 * Returns true if the dot directory should be used for storing preferences,
379 * cache and user data.
380 * Currently this is the case, if the dot directory already exists.
381 * @return true if the dot directory should be used
382 */
383 private static boolean useDotDirectory() {
384 return getDotDirectory().exists();
385 }
386
387 @Override
388 public File getDefaultCacheDirectory() {
389 if (useDotDirectory()) {
390 return new File(getDotDirectory(), "cache");
391 } else {
392 String xdgCacheDir = System.getenv("XDG_CACHE_HOME");
393 if (xdgCacheDir != null && !xdgCacheDir.isEmpty()) {
394 return new File(xdgCacheDir, Main.pref.getJOSMDirectoryBaseName());
395 } else {
396 return new File(System.getProperty("user.home") + File.separator +
397 ".cache" + File.separator + Main.pref.getJOSMDirectoryBaseName());
398 }
399 }
400 }
401
402 @Override
403 public File getDefaultPrefDirectory() {
404 if (useDotDirectory()) {
405 return getDotDirectory();
406 } else {
407 String xdgConfigDir = System.getenv("XDG_CONFIG_HOME");
408 if (xdgConfigDir != null && !xdgConfigDir.isEmpty()) {
409 return new File(xdgConfigDir, Main.pref.getJOSMDirectoryBaseName());
410 } else {
411 return new File(System.getProperty("user.home") + File.separator +
412 ".config" + File.separator + Main.pref.getJOSMDirectoryBaseName());
413 }
414 }
415 }
416
417 @Override
418 public File getDefaultUserDataDirectory() {
419 if (useDotDirectory()) {
420 return getDotDirectory();
421 } else {
422 String xdgDataDir = System.getenv("XDG_DATA_HOME");
423 if (xdgDataDir != null && !xdgDataDir.isEmpty()) {
424 return new File(xdgDataDir, Main.pref.getJOSMDirectoryBaseName());
425 } else {
426 return new File(System.getProperty("user.home") + File.separator +
427 ".local" + File.separator + "share" + File.separator + Main.pref.getJOSMDirectoryBaseName());
428 }
429 }
430 }
431
432 @Override
433 public List<File> getDefaultProj4NadshiftDirectories() {
434 return Arrays.asList(new File("/usr/local/share/proj"), new File("/usr/share/proj"));
435 }
436}
Note: See TracBrowser for help on using the repository browser.