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

Last change on this file since 10731 was 10627, checked in by Don-vip, 8 years ago

sonar - squid:S1166 - Exception handlers should preserve the original exceptions

  • Property svn:eol-style set to native
File size: 25.4 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.GraphicsEnvironment;
9import java.awt.event.KeyEvent;
10import java.io.BufferedReader;
11import java.io.BufferedWriter;
12import java.io.File;
13import java.io.FileInputStream;
14import java.io.IOException;
15import java.io.InputStreamReader;
16import java.io.OutputStream;
17import java.io.OutputStreamWriter;
18import java.io.Writer;
19import java.net.URI;
20import java.net.URISyntaxException;
21import java.nio.charset.StandardCharsets;
22import java.nio.file.FileSystems;
23import java.nio.file.Files;
24import java.nio.file.Path;
25import java.nio.file.Paths;
26import java.security.KeyStore;
27import java.security.KeyStoreException;
28import java.security.NoSuchAlgorithmException;
29import java.security.cert.CertificateException;
30import java.util.ArrayList;
31import java.util.Arrays;
32import java.util.Collection;
33import java.util.List;
34import java.util.Locale;
35import java.util.Properties;
36
37import javax.swing.JOptionPane;
38
39import org.openstreetmap.josm.Main;
40import org.openstreetmap.josm.data.Preferences.pref;
41import org.openstreetmap.josm.data.Preferences.writeExplicitly;
42import org.openstreetmap.josm.gui.ExtendedDialog;
43import org.openstreetmap.josm.gui.util.GuiHelper;
44
45/**
46 * {@code PlatformHook} base implementation.
47 *
48 * Don't write (Main.platform instanceof PlatformHookUnixoid) because other platform
49 * hooks are subclasses of this class.
50 */
51public class PlatformHookUnixoid implements PlatformHook {
52
53 /**
54 * Simple data class to hold information about a font.
55 *
56 * Used for fontconfig.properties files.
57 */
58 public static class FontEntry {
59 /**
60 * The character subset. Basically a free identifier, but should be unique.
61 */
62 @pref
63 public String charset;
64
65 /**
66 * Platform font name.
67 */
68 @pref
69 @writeExplicitly
70 public String name = "";
71
72 /**
73 * File name.
74 */
75 @pref
76 @writeExplicitly
77 public String file = "";
78
79 /**
80 * Constructs a new {@code FontEntry}.
81 */
82 public FontEntry() {
83 }
84
85 /**
86 * Constructs a new {@code FontEntry}.
87 * @param charset The character subset. Basically a free identifier, but should be unique
88 * @param name Platform font name
89 * @param file File name
90 */
91 public FontEntry(String charset, String name, String file) {
92 this.charset = charset;
93 this.name = name;
94 this.file = file;
95 }
96 }
97
98 private String osDescription;
99
100 @Override
101 public void preStartupHook() {
102 // See #12022 - Disable GNOME ATK Java wrapper as it causes a lot of serious trouble
103 if ("org.GNOME.Accessibility.AtkWrapper".equals(System.getProperty("assistive_technologies"))) {
104 System.clearProperty("assistive_technologies");
105 }
106 }
107
108 @Override
109 public void afterPrefStartupHook() {
110 // Do nothing
111 }
112
113 @Override
114 public void startupHook() {
115 // Do nothing
116 }
117
118 @Override
119 public void openUrl(String url) throws IOException {
120 for (String program : Main.pref.getCollection("browser.unix",
121 Arrays.asList("xdg-open", "#DESKTOP#", "$BROWSER", "gnome-open", "kfmclient openURL", "firefox"))) {
122 try {
123 if ("#DESKTOP#".equals(program)) {
124 Desktop.getDesktop().browse(new URI(url));
125 } else if (program.startsWith("$")) {
126 program = System.getenv().get(program.substring(1));
127 Runtime.getRuntime().exec(new String[]{program, url});
128 } else {
129 Runtime.getRuntime().exec(new String[]{program, url});
130 }
131 return;
132 } catch (IOException | URISyntaxException e) {
133 Main.warn(e);
134 }
135 }
136 }
137
138 @Override
139 public void initSystemShortcuts() {
140 // CHECKSTYLE.OFF: LineLength
141 // TODO: Insert system shortcuts here. See Windows and especially OSX to see how to.
142 for (int i = KeyEvent.VK_F1; i <= KeyEvent.VK_F12; ++i) {
143 Shortcut.registerSystemShortcut("screen:toogle"+i, tr("reserved"), i, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
144 .setAutomatic();
145 }
146 Shortcut.registerSystemShortcut("system:reset", tr("reserved"), KeyEvent.VK_DELETE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
147 .setAutomatic();
148 Shortcut.registerSystemShortcut("system:resetX", tr("reserved"), KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
149 .setAutomatic();
150 // CHECKSTYLE.ON: LineLength
151 }
152
153 /**
154 * This should work for all platforms. Yeah, should.
155 * See PlatformHook.java for a list of reasons why this is implemented here...
156 */
157 @Override
158 public String makeTooltip(String name, Shortcut sc) {
159 StringBuilder result = new StringBuilder();
160 result.append("<html>").append(name);
161 if (sc != null && !sc.getKeyText().isEmpty()) {
162 result.append(" <font size='-2'>(")
163 .append(sc.getKeyText())
164 .append(")</font>");
165 }
166 return result.append("&nbsp;</html>").toString();
167 }
168
169 @Override
170 public String getDefaultStyle() {
171 return "javax.swing.plaf.metal.MetalLookAndFeel";
172 }
173
174 @Override
175 public boolean canFullscreen() {
176 return !GraphicsEnvironment.isHeadless() &&
177 GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().isFullScreenSupported();
178 }
179
180 @Override
181 public boolean rename(File from, File to) {
182 return from.renameTo(to);
183 }
184
185 /**
186 * Determines if the distribution is Debian or Ubuntu, or a derivative.
187 * @return {@code true} if the distribution is Debian, Ubuntu or Mint, {@code false} otherwise
188 */
189 public static boolean isDebianOrUbuntu() {
190 try {
191 String dist = Utils.execOutput(Arrays.asList("lsb_release", "-i", "-s"));
192 return "Debian".equalsIgnoreCase(dist) || "Ubuntu".equalsIgnoreCase(dist) || "Mint".equalsIgnoreCase(dist);
193 } catch (IOException e) {
194 // lsb_release is not available on all Linux systems, so don't log at warning level
195 Main.debug(e);
196 return false;
197 }
198 }
199
200 /**
201 * Determines if the JVM is OpenJDK-based.
202 * @return {@code true} if {@code java.home} contains "openjdk", {@code false} otherwise
203 * @since 6951
204 */
205 public static boolean isOpenJDK() {
206 String javaHome = System.getProperty("java.home");
207 return javaHome != null && javaHome.contains("openjdk");
208 }
209
210 /**
211 * Get the package name including detailed version.
212 * @param packageNames The possible package names (when a package can have different names on different distributions)
213 * @return The package name and package version if it can be identified, null otherwise
214 * @since 7314
215 */
216 public static String getPackageDetails(String ... packageNames) {
217 try {
218 // CHECKSTYLE.OFF: SingleSpaceSeparator
219 boolean dpkg = Files.exists(Paths.get("/usr/bin/dpkg-query"));
220 boolean eque = Files.exists(Paths.get("/usr/bin/equery"));
221 boolean rpm = Files.exists(Paths.get("/bin/rpm"));
222 // CHECKSTYLE.ON: SingleSpaceSeparator
223 if (dpkg || rpm || eque) {
224 for (String packageName : packageNames) {
225 String[] args;
226 if (dpkg) {
227 args = new String[] {"dpkg-query", "--show", "--showformat", "${Architecture}-${Version}", packageName};
228 } else if (eque) {
229 args = new String[] {"equery", "-q", "list", "-e", "--format=$fullversion", packageName};
230 } else {
231 args = new String[] {"rpm", "-q", "--qf", "%{arch}-%{version}", packageName};
232 }
233 String version = Utils.execOutput(Arrays.asList(args));
234 if (version != null && !version.contains("not installed")) {
235 return packageName + ':' + version;
236 }
237 }
238 }
239 } catch (IOException e) {
240 Main.warn(e);
241 }
242 return null;
243 }
244
245 /**
246 * Get the Java package name including detailed version.
247 *
248 * Some Java bugs are specific to a certain security update, so in addition
249 * to the Java version, we also need the exact package version.
250 *
251 * @return The package name and package version if it can be identified, null otherwise
252 */
253 public String getJavaPackageDetails() {
254 String home = System.getProperty("java.home");
255 if (home.contains("java-8-openjdk") || home.contains("java-1.8.0-openjdk")) {
256 return getPackageDetails("openjdk-8-jre", "java-1_8_0-openjdk", "java-1.8.0-openjdk");
257 } else if (home.contains("java-9-openjdk") || home.contains("java-1.9.0-openjdk")) {
258 return getPackageDetails("openjdk-9-jre", "java-1_9_0-openjdk", "java-1.9.0-openjdk");
259 } else if (home.contains("icedtea")) {
260 return getPackageDetails("icedtea-bin");
261 } else if (home.contains("oracle")) {
262 return getPackageDetails("oracle-jdk-bin", "oracle-jre-bin");
263 }
264 return null;
265 }
266
267 /**
268 * Get the Web Start package name including detailed version.
269 *
270 * OpenJDK packages are shipped with icedtea-web package,
271 * but its version generally does not match main java package version.
272 *
273 * Simply return {@code null} if there's no separate package for Java WebStart.
274 *
275 * @return The package name and package version if it can be identified, null otherwise
276 */
277 public String getWebStartPackageDetails() {
278 if (isOpenJDK()) {
279 return getPackageDetails("icedtea-netx", "icedtea-web");
280 }
281 return null;
282 }
283
284 protected String buildOSDescription() {
285 String osName = System.getProperty("os.name");
286 if ("Linux".equalsIgnoreCase(osName)) {
287 try {
288 // Try lsb_release (only available on LSB-compliant Linux systems,
289 // see https://www.linuxbase.org/lsb-cert/productdir.php?by_prod )
290 Process p = Runtime.getRuntime().exec("lsb_release -ds");
291 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
292 String line = Utils.strip(input.readLine());
293 if (line != null && !line.isEmpty()) {
294 line = line.replaceAll("\"+", "");
295 line = line.replaceAll("NAME=", ""); // strange code for some Gentoo's
296 if (line.startsWith("Linux ")) // e.g. Linux Mint
297 return line;
298 else if (!line.isEmpty())
299 return "Linux " + line;
300 }
301 }
302 } catch (IOException e) {
303 Main.debug(e);
304 // Non LSB-compliant Linux system. List of common fallback release files: http://linuxmafia.com/faq/Admin/release-files.html
305 for (LinuxReleaseInfo info : new LinuxReleaseInfo[]{
306 new LinuxReleaseInfo("/etc/lsb-release", "DISTRIB_DESCRIPTION", "DISTRIB_ID", "DISTRIB_RELEASE"),
307 new LinuxReleaseInfo("/etc/os-release", "PRETTY_NAME", "NAME", "VERSION"),
308 new LinuxReleaseInfo("/etc/arch-release"),
309 new LinuxReleaseInfo("/etc/debian_version", "Debian GNU/Linux "),
310 new LinuxReleaseInfo("/etc/fedora-release"),
311 new LinuxReleaseInfo("/etc/gentoo-release"),
312 new LinuxReleaseInfo("/etc/redhat-release"),
313 new LinuxReleaseInfo("/etc/SuSE-release")
314 }) {
315 String description = info.extractDescription();
316 if (description != null && !description.isEmpty()) {
317 return "Linux " + description;
318 }
319 }
320 }
321 }
322 return osName;
323 }
324
325 @Override
326 public String getOSDescription() {
327 if (osDescription == null) {
328 osDescription = buildOSDescription();
329 }
330 return osDescription;
331 }
332
333 protected static class LinuxReleaseInfo {
334 private final String path;
335 private final String descriptionField;
336 private final String idField;
337 private final String releaseField;
338 private final boolean plainText;
339 private final String prefix;
340
341 public LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField) {
342 this(path, descriptionField, idField, releaseField, false, null);
343 }
344
345 public LinuxReleaseInfo(String path) {
346 this(path, null, null, null, true, null);
347 }
348
349 public LinuxReleaseInfo(String path, String prefix) {
350 this(path, null, null, null, true, prefix);
351 }
352
353 private LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField, boolean plainText, String prefix) {
354 this.path = path;
355 this.descriptionField = descriptionField;
356 this.idField = idField;
357 this.releaseField = releaseField;
358 this.plainText = plainText;
359 this.prefix = prefix;
360 }
361
362 @Override public String toString() {
363 return "ReleaseInfo [path=" + path + ", descriptionField=" + descriptionField +
364 ", idField=" + idField + ", releaseField=" + releaseField + ']';
365 }
366
367 /**
368 * Extracts OS detailed information from a Linux release file (/etc/xxx-release)
369 * @return The OS detailed information, or {@code null}
370 */
371 public String extractDescription() {
372 String result = null;
373 if (path != null) {
374 Path p = Paths.get(path);
375 if (Files.exists(p)) {
376 try (BufferedReader reader = Files.newBufferedReader(p, StandardCharsets.UTF_8)) {
377 String id = null;
378 String release = null;
379 String line;
380 while (result == null && (line = reader.readLine()) != null) {
381 if (line.contains("=")) {
382 String[] tokens = line.split("=");
383 if (tokens.length >= 2) {
384 // Description, if available, contains exactly what we need
385 if (descriptionField != null && descriptionField.equalsIgnoreCase(tokens[0])) {
386 result = Utils.strip(tokens[1]);
387 } else if (idField != null && idField.equalsIgnoreCase(tokens[0])) {
388 id = Utils.strip(tokens[1]);
389 } else if (releaseField != null && releaseField.equalsIgnoreCase(tokens[0])) {
390 release = Utils.strip(tokens[1]);
391 }
392 }
393 } else if (plainText && !line.isEmpty()) {
394 // Files composed of a single line
395 result = Utils.strip(line);
396 }
397 }
398 // If no description has been found, try to rebuild it with "id" + "release" (i.e. "name" + "version")
399 if (result == null && id != null && release != null) {
400 result = id + ' ' + release;
401 }
402 } catch (IOException e) {
403 // Ignore
404 Main.trace(e);
405 }
406 }
407 }
408 // Append prefix if any
409 if (result != null && !result.isEmpty() && prefix != null && !prefix.isEmpty()) {
410 result = prefix + result;
411 }
412 if (result != null)
413 result = result.replaceAll("\"+", "");
414 return result;
415 }
416 }
417
418 // Method unused, but kept for translation already done. To reuse during Java 9 migration
419 protected void askUpdateJava(final String version, final String url) {
420 GuiHelper.runInEDTAndWait(() -> {
421 ExtendedDialog ed = new ExtendedDialog(
422 Main.parent,
423 tr("Outdated Java version"),
424 new String[]{tr("OK"), tr("Update Java"), tr("Cancel")});
425 // Check if the dialog has not already been permanently hidden by user
426 if (!ed.toggleEnable("askUpdateJava9").toggleCheckState()) {
427 ed.setButtonIcons(new String[]{"ok", "java", "cancel"}).setCancelButton(3);
428 ed.setMinimumSize(new Dimension(480, 300));
429 ed.setIcon(JOptionPane.WARNING_MESSAGE);
430 StringBuilder content = new StringBuilder(tr("You are running version {0} of Java.", "<b>"+version+"</b>"))
431 .append("<br><br>");
432 if ("Sun Microsystems Inc.".equals(System.getProperty("java.vendor")) && !isOpenJDK()) {
433 content.append("<b>").append(tr("This version is no longer supported by {0} since {1} and is not recommended for use.",
434 "Oracle", tr("April 2015"))).append("</b><br><br>"); // TODO: change date once Java 8 EOL is announced
435 }
436 content.append("<b>")
437 .append(tr("JOSM will soon stop working with this version; we highly recommend you to update to Java {0}.", "8"))
438 .append("</b><br><br>")
439 .append(tr("Would you like to update now ?"));
440 ed.setContent(content.toString());
441
442 if (ed.showDialog().getValue() == 2) {
443 try {
444 openUrl(url);
445 } catch (IOException e) {
446 Main.warn(e);
447 }
448 }
449 }
450 });
451 }
452
453 @Override
454 public boolean setupHttpsCertificate(String entryAlias, KeyStore.TrustedCertificateEntry trustedCert)
455 throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
456 // TODO setup HTTPS certificate on Unix systems
457 return false;
458 }
459
460 @Override
461 public File getDefaultCacheDirectory() {
462 return new File(Main.pref.getUserDataDirectory(), "cache");
463 }
464
465 @Override
466 public File getDefaultPrefDirectory() {
467 return new File(System.getProperty("user.home"), ".josm");
468 }
469
470 @Override
471 public File getDefaultUserDataDirectory() {
472 // Use preferences directory by default
473 return Main.pref.getPreferencesDirectory();
474 }
475
476 /**
477 * <p>Add more fallback fonts to the Java runtime, in order to get
478 * support for more scripts.</p>
479 *
480 * <p>The font configuration in Java doesn't include some Indic scripts,
481 * even though MS Windows ships with fonts that cover these unicode ranges.</p>
482 *
483 * <p>To fix this, the fontconfig.properties template is copied to the JOSM
484 * cache folder. Then, the additional entries are added to the font
485 * configuration. Finally the system property "sun.awt.fontconfig" is set
486 * to the customized fontconfig.properties file.</p>
487 *
488 * <p>This is a crude hack, but better than no font display at all for these languages.
489 * There is no guarantee, that the template file
490 * ($JAVA_HOME/lib/fontconfig.properties.src) matches the default
491 * configuration (which is in a binary format).
492 * Furthermore, the system property "sun.awt.fontconfig" is undocumented and
493 * may no longer work in future versions of Java.</p>
494 *
495 * <p>Related Java bug: <a href="https://bugs.openjdk.java.net/browse/JDK-8008572">JDK-8008572</a></p>
496 *
497 * @param templateFileName file name of the fontconfig.properties template file
498 */
499 protected void extendFontconfig(String templateFileName) {
500 String customFontconfigFile = Main.pref.get("fontconfig.properties", null);
501 if (customFontconfigFile != null) {
502 Utils.updateSystemProperty("sun.awt.fontconfig", customFontconfigFile);
503 return;
504 }
505 if (!Main.pref.getBoolean("font.extended-unicode", true))
506 return;
507
508 String javaLibPath = System.getProperty("java.home") + File.separator + "lib";
509 Path templateFile = FileSystems.getDefault().getPath(javaLibPath, templateFileName);
510 if (!Files.isReadable(templateFile)) {
511 Main.warn("extended font config - unable to find font config template file "+templateFile.toString());
512 return;
513 }
514 try (FileInputStream fis = new FileInputStream(templateFile.toFile())) {
515 Properties props = new Properties();
516 props.load(fis);
517 byte[] content = Files.readAllBytes(templateFile);
518 File cachePath = Main.pref.getCacheDirectory();
519 Path fontconfigFile = cachePath.toPath().resolve("fontconfig.properties");
520 OutputStream os = Files.newOutputStream(fontconfigFile);
521 os.write(content);
522 try (Writer w = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
523 Collection<FontEntry> extrasPref = Main.pref.getListOfStructs(
524 "font.extended-unicode.extra-items", getAdditionalFonts(), FontEntry.class);
525 Collection<FontEntry> extras = new ArrayList<>();
526 w.append("\n\n# Added by JOSM to extend unicode coverage of Java font support:\n\n");
527 List<String> allCharSubsets = new ArrayList<>();
528 for (FontEntry entry: extrasPref) {
529 Collection<String> fontsAvail = getInstalledFonts();
530 if (fontsAvail != null && fontsAvail.contains(entry.file.toUpperCase(Locale.ENGLISH))) {
531 if (!allCharSubsets.contains(entry.charset)) {
532 allCharSubsets.add(entry.charset);
533 extras.add(entry);
534 } else {
535 Main.trace("extended font config - already registered font for charset ''{0}'' - skipping ''{1}''",
536 entry.charset, entry.name);
537 }
538 } else {
539 Main.trace("extended font config - Font ''{0}'' not found on system - skipping", entry.name);
540 }
541 }
542 for (FontEntry entry: extras) {
543 allCharSubsets.add(entry.charset);
544 if ("".equals(entry.name)) {
545 continue;
546 }
547 String key = "allfonts." + entry.charset;
548 String value = entry.name;
549 String prevValue = props.getProperty(key);
550 if (prevValue != null && !prevValue.equals(value)) {
551 Main.warn("extended font config - overriding ''{0}={1}'' with ''{2}''", key, prevValue, value);
552 }
553 w.append(key + '=' + value + '\n');
554 }
555 w.append('\n');
556 for (FontEntry entry: extras) {
557 if ("".equals(entry.name) || "".equals(entry.file)) {
558 continue;
559 }
560 String key = "filename." + entry.name.replace(' ', '_');
561 String value = entry.file;
562 String prevValue = props.getProperty(key);
563 if (prevValue != null && !prevValue.equals(value)) {
564 Main.warn("extended font config - overriding ''{0}={1}'' with ''{2}''", key, prevValue, value);
565 }
566 w.append(key + '=' + value + '\n');
567 }
568 w.append('\n');
569 String fallback = props.getProperty("sequence.fallback");
570 if (fallback != null) {
571 w.append("sequence.fallback=" + fallback + ',' + Utils.join(",", allCharSubsets) + '\n');
572 } else {
573 w.append("sequence.fallback=" + Utils.join(",", allCharSubsets) + '\n');
574 }
575 }
576 Utils.updateSystemProperty("sun.awt.fontconfig", fontconfigFile.toString());
577 } catch (IOException ex) {
578 Main.error(ex);
579 }
580 }
581
582 /**
583 * Get a list of fonts that are installed on the system.
584 *
585 * Must be done without triggering the Java Font initialization.
586 * (See {@link #extendFontconfig(java.lang.String)}, have to set system
587 * property first, which is then read by sun.awt.FontConfiguration upon initialization.)
588 *
589 * @return list of file names
590 */
591 public Collection<String> getInstalledFonts() {
592 throw new UnsupportedOperationException();
593 }
594
595 /**
596 * Get default list of additional fonts to add to the configuration.
597 *
598 * Java will choose thee first font in the list that can render a certain character.
599 *
600 * @return list of FontEntry objects
601 */
602 public Collection<FontEntry> getAdditionalFonts() {
603 throw new UnsupportedOperationException();
604 }
605}
Note: See TracBrowser for help on using the repository browser.