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

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

see #11390 - switch to Java 8

  • Property svn:eol-style set to native
File size: 25.7 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 if (Main.isDebugEnabled()) {
195 // lsb_release is not available on all Linux systems, so don't log at warning level
196 Main.debug(e.getMessage());
197 }
198 return false;
199 }
200 }
201
202 /**
203 * Determines if the JVM is OpenJDK-based.
204 * @return {@code true} if {@code java.home} contains "openjdk", {@code false} otherwise
205 * @since 6951
206 */
207 public static boolean isOpenJDK() {
208 String javaHome = System.getProperty("java.home");
209 return javaHome != null && javaHome.contains("openjdk");
210 }
211
212 /**
213 * Get the package name including detailed version.
214 * @param packageNames The possible package names (when a package can have different names on different distributions)
215 * @return The package name and package version if it can be identified, null otherwise
216 * @since 7314
217 */
218 public static String getPackageDetails(String ... packageNames) {
219 try {
220 // CHECKSTYLE.OFF: SingleSpaceSeparator
221 boolean dpkg = Files.exists(Paths.get("/usr/bin/dpkg-query"));
222 boolean eque = Files.exists(Paths.get("/usr/bin/equery"));
223 boolean rpm = Files.exists(Paths.get("/bin/rpm"));
224 // CHECKSTYLE.ON: SingleSpaceSeparator
225 if (dpkg || rpm || eque) {
226 for (String packageName : packageNames) {
227 String[] args;
228 if (dpkg) {
229 args = new String[] {"dpkg-query", "--show", "--showformat", "${Architecture}-${Version}", packageName};
230 } else if (eque) {
231 args = new String[] {"equery", "-q", "list", "-e", "--format=$fullversion", packageName};
232 } else {
233 args = new String[] {"rpm", "-q", "--qf", "%{arch}-%{version}", packageName};
234 }
235 String version = Utils.execOutput(Arrays.asList(args));
236 if (version != null && !version.contains("not installed")) {
237 return packageName + ':' + version;
238 }
239 }
240 }
241 } catch (IOException e) {
242 Main.warn(e);
243 }
244 return null;
245 }
246
247 /**
248 * Get the Java package name including detailed version.
249 *
250 * Some Java bugs are specific to a certain security update, so in addition
251 * to the Java version, we also need the exact package version.
252 *
253 * @return The package name and package version if it can be identified, null otherwise
254 */
255 public String getJavaPackageDetails() {
256 String home = System.getProperty("java.home");
257 if (home.contains("java-8-openjdk") || home.contains("java-1.8.0-openjdk")) {
258 return getPackageDetails("openjdk-8-jre", "java-1_8_0-openjdk", "java-1.8.0-openjdk");
259 } else if (home.contains("java-9-openjdk") || home.contains("java-1.9.0-openjdk")) {
260 return getPackageDetails("openjdk-9-jre", "java-1_9_0-openjdk", "java-1.9.0-openjdk");
261 } else if (home.contains("icedtea")) {
262 return getPackageDetails("icedtea-bin");
263 } else if (home.contains("oracle")) {
264 return getPackageDetails("oracle-jdk-bin", "oracle-jre-bin");
265 }
266 return null;
267 }
268
269 /**
270 * Get the Web Start package name including detailed version.
271 *
272 * OpenJDK packages are shipped with icedtea-web package,
273 * but its version generally does not match main java package version.
274 *
275 * Simply return {@code null} if there's no separate package for Java WebStart.
276 *
277 * @return The package name and package version if it can be identified, null otherwise
278 */
279 public String getWebStartPackageDetails() {
280 if (isOpenJDK()) {
281 return getPackageDetails("icedtea-netx", "icedtea-web");
282 }
283 return null;
284 }
285
286 protected String buildOSDescription() {
287 String osName = System.getProperty("os.name");
288 if ("Linux".equalsIgnoreCase(osName)) {
289 try {
290 // Try lsb_release (only available on LSB-compliant Linux systems,
291 // see https://www.linuxbase.org/lsb-cert/productdir.php?by_prod )
292 Process p = Runtime.getRuntime().exec("lsb_release -ds");
293 try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
294 String line = Utils.strip(input.readLine());
295 if (line != null && !line.isEmpty()) {
296 line = line.replaceAll("\"+", "");
297 line = line.replaceAll("NAME=", ""); // strange code for some Gentoo's
298 if (line.startsWith("Linux ")) // e.g. Linux Mint
299 return line;
300 else if (!line.isEmpty())
301 return "Linux " + line;
302 }
303 }
304 } catch (IOException e) {
305 // Non LSB-compliant Linux system. List of common fallback release files: http://linuxmafia.com/faq/Admin/release-files.html
306 for (LinuxReleaseInfo info : new LinuxReleaseInfo[]{
307 new LinuxReleaseInfo("/etc/lsb-release", "DISTRIB_DESCRIPTION", "DISTRIB_ID", "DISTRIB_RELEASE"),
308 new LinuxReleaseInfo("/etc/os-release", "PRETTY_NAME", "NAME", "VERSION"),
309 new LinuxReleaseInfo("/etc/arch-release"),
310 new LinuxReleaseInfo("/etc/debian_version", "Debian GNU/Linux "),
311 new LinuxReleaseInfo("/etc/fedora-release"),
312 new LinuxReleaseInfo("/etc/gentoo-release"),
313 new LinuxReleaseInfo("/etc/redhat-release"),
314 new LinuxReleaseInfo("/etc/SuSE-release")
315 }) {
316 String description = info.extractDescription();
317 if (description != null && !description.isEmpty()) {
318 return "Linux " + description;
319 }
320 }
321 }
322 }
323 return osName;
324 }
325
326 @Override
327 public String getOSDescription() {
328 if (osDescription == null) {
329 osDescription = buildOSDescription();
330 }
331 return osDescription;
332 }
333
334 protected static class LinuxReleaseInfo {
335 private final String path;
336 private final String descriptionField;
337 private final String idField;
338 private final String releaseField;
339 private final boolean plainText;
340 private final String prefix;
341
342 public LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField) {
343 this(path, descriptionField, idField, releaseField, false, null);
344 }
345
346 public LinuxReleaseInfo(String path) {
347 this(path, null, null, null, true, null);
348 }
349
350 public LinuxReleaseInfo(String path, String prefix) {
351 this(path, null, null, null, true, prefix);
352 }
353
354 private LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField, boolean plainText, String prefix) {
355 this.path = path;
356 this.descriptionField = descriptionField;
357 this.idField = idField;
358 this.releaseField = releaseField;
359 this.plainText = plainText;
360 this.prefix = prefix;
361 }
362
363 @Override public String toString() {
364 return "ReleaseInfo [path=" + path + ", descriptionField=" + descriptionField +
365 ", idField=" + idField + ", releaseField=" + releaseField + ']';
366 }
367
368 /**
369 * Extracts OS detailed information from a Linux release file (/etc/xxx-release)
370 * @return The OS detailed information, or {@code null}
371 */
372 public String extractDescription() {
373 String result = null;
374 if (path != null) {
375 Path p = Paths.get(path);
376 if (Files.exists(p)) {
377 try (BufferedReader reader = Files.newBufferedReader(p, StandardCharsets.UTF_8)) {
378 String id = null;
379 String release = null;
380 String line;
381 while (result == null && (line = reader.readLine()) != null) {
382 if (line.contains("=")) {
383 String[] tokens = line.split("=");
384 if (tokens.length >= 2) {
385 // Description, if available, contains exactly what we need
386 if (descriptionField != null && descriptionField.equalsIgnoreCase(tokens[0])) {
387 result = Utils.strip(tokens[1]);
388 } else if (idField != null && idField.equalsIgnoreCase(tokens[0])) {
389 id = Utils.strip(tokens[1]);
390 } else if (releaseField != null && releaseField.equalsIgnoreCase(tokens[0])) {
391 release = Utils.strip(tokens[1]);
392 }
393 }
394 } else if (plainText && !line.isEmpty()) {
395 // Files composed of a single line
396 result = Utils.strip(line);
397 }
398 }
399 // If no description has been found, try to rebuild it with "id" + "release" (i.e. "name" + "version")
400 if (result == null && id != null && release != null) {
401 result = id + ' ' + release;
402 }
403 } catch (IOException e) {
404 // Ignore
405 if (Main.isTraceEnabled()) {
406 Main.trace(e.getMessage());
407 }
408 }
409 }
410 }
411 // Append prefix if any
412 if (result != null && !result.isEmpty() && prefix != null && !prefix.isEmpty()) {
413 result = prefix + result;
414 }
415 if (result != null)
416 result = result.replaceAll("\"+", "");
417 return result;
418 }
419 }
420
421 // Method unused, but kept for translation already done. To reuse during Java 9 migration
422 protected void askUpdateJava(final String version, final String url) {
423 GuiHelper.runInEDTAndWait(new Runnable() {
424 @Override
425 public void run() {
426 ExtendedDialog ed = new ExtendedDialog(
427 Main.parent,
428 tr("Outdated Java version"),
429 new String[]{tr("OK"), tr("Update Java"), tr("Cancel")});
430 // Check if the dialog has not already been permanently hidden by user
431 if (!ed.toggleEnable("askUpdateJava9").toggleCheckState()) {
432 ed.setButtonIcons(new String[]{"ok", "java", "cancel"}).setCancelButton(3);
433 ed.setMinimumSize(new Dimension(480, 300));
434 ed.setIcon(JOptionPane.WARNING_MESSAGE);
435 StringBuilder content = new StringBuilder(tr("You are running version {0} of Java.", "<b>"+version+"</b>"))
436 .append("<br><br>");
437 if ("Sun Microsystems Inc.".equals(System.getProperty("java.vendor")) && !isOpenJDK()) {
438 content.append("<b>").append(tr("This version is no longer supported by {0} since {1} and is not recommended for use.",
439 "Oracle", tr("April 2015"))).append("</b><br><br>"); // TODO: change date once Java 8 EOL is announced
440 }
441 content.append("<b>")
442 .append(tr("JOSM will soon stop working with this version; we highly recommend you to update to Java {0}.", "8"))
443 .append("</b><br><br>")
444 .append(tr("Would you like to update now ?"));
445 ed.setContent(content.toString());
446
447 if (ed.showDialog().getValue() == 2) {
448 try {
449 openUrl(url);
450 } catch (IOException e) {
451 Main.warn(e);
452 }
453 }
454 }
455 }
456 });
457 }
458
459 @Override
460 public boolean setupHttpsCertificate(String entryAlias, KeyStore.TrustedCertificateEntry trustedCert)
461 throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
462 // TODO setup HTTPS certificate on Unix systems
463 return false;
464 }
465
466 @Override
467 public File getDefaultCacheDirectory() {
468 return new File(Main.pref.getUserDataDirectory(), "cache");
469 }
470
471 @Override
472 public File getDefaultPrefDirectory() {
473 return new File(System.getProperty("user.home"), ".josm");
474 }
475
476 @Override
477 public File getDefaultUserDataDirectory() {
478 // Use preferences directory by default
479 return Main.pref.getPreferencesDirectory();
480 }
481
482 /**
483 * <p>Add more fallback fonts to the Java runtime, in order to get
484 * support for more scripts.</p>
485 *
486 * <p>The font configuration in Java doesn't include some Indic scripts,
487 * even though MS Windows ships with fonts that cover these unicode ranges.</p>
488 *
489 * <p>To fix this, the fontconfig.properties template is copied to the JOSM
490 * cache folder. Then, the additional entries are added to the font
491 * configuration. Finally the system property "sun.awt.fontconfig" is set
492 * to the customized fontconfig.properties file.</p>
493 *
494 * <p>This is a crude hack, but better than no font display at all for these languages.
495 * There is no guarantee, that the template file
496 * ($JAVA_HOME/lib/fontconfig.properties.src) matches the default
497 * configuration (which is in a binary format).
498 * Furthermore, the system property "sun.awt.fontconfig" is undocumented and
499 * may no longer work in future versions of Java.</p>
500 *
501 * <p>Related Java bug: <a href="https://bugs.openjdk.java.net/browse/JDK-8008572">JDK-8008572</a></p>
502 *
503 * @param templateFileName file name of the fontconfig.properties template file
504 */
505 protected void extendFontconfig(String templateFileName) {
506 String customFontconfigFile = Main.pref.get("fontconfig.properties", null);
507 if (customFontconfigFile != null) {
508 Utils.updateSystemProperty("sun.awt.fontconfig", customFontconfigFile);
509 return;
510 }
511 if (!Main.pref.getBoolean("font.extended-unicode", true))
512 return;
513
514 String javaLibPath = System.getProperty("java.home") + File.separator + "lib";
515 Path templateFile = FileSystems.getDefault().getPath(javaLibPath, templateFileName);
516 if (!Files.isReadable(templateFile)) {
517 Main.warn("extended font config - unable to find font config template file "+templateFile.toString());
518 return;
519 }
520 try (FileInputStream fis = new FileInputStream(templateFile.toFile())) {
521 Properties props = new Properties();
522 props.load(fis);
523 byte[] content = Files.readAllBytes(templateFile);
524 File cachePath = Main.pref.getCacheDirectory();
525 Path fontconfigFile = cachePath.toPath().resolve("fontconfig.properties");
526 OutputStream os = Files.newOutputStream(fontconfigFile);
527 os.write(content);
528 try (Writer w = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
529 Collection<FontEntry> extrasPref = Main.pref.getListOfStructs(
530 "font.extended-unicode.extra-items", getAdditionalFonts(), FontEntry.class);
531 Collection<FontEntry> extras = new ArrayList<>();
532 w.append("\n\n# Added by JOSM to extend unicode coverage of Java font support:\n\n");
533 List<String> allCharSubsets = new ArrayList<>();
534 for (FontEntry entry: extrasPref) {
535 Collection<String> fontsAvail = getInstalledFonts();
536 if (fontsAvail != null && fontsAvail.contains(entry.file.toUpperCase(Locale.ENGLISH))) {
537 if (!allCharSubsets.contains(entry.charset)) {
538 allCharSubsets.add(entry.charset);
539 extras.add(entry);
540 } else {
541 Main.trace("extended font config - already registered font for charset ''{0}'' - skipping ''{1}''",
542 entry.charset, entry.name);
543 }
544 } else {
545 Main.trace("extended font config - Font ''{0}'' not found on system - skipping", entry.name);
546 }
547 }
548 for (FontEntry entry: extras) {
549 allCharSubsets.add(entry.charset);
550 if ("".equals(entry.name)) {
551 continue;
552 }
553 String key = "allfonts." + entry.charset;
554 String value = entry.name;
555 String prevValue = props.getProperty(key);
556 if (prevValue != null && !prevValue.equals(value)) {
557 Main.warn("extended font config - overriding ''{0}={1}'' with ''{2}''", key, prevValue, value);
558 }
559 w.append(key + '=' + value + '\n');
560 }
561 w.append('\n');
562 for (FontEntry entry: extras) {
563 if ("".equals(entry.name) || "".equals(entry.file)) {
564 continue;
565 }
566 String key = "filename." + entry.name.replace(' ', '_');
567 String value = entry.file;
568 String prevValue = props.getProperty(key);
569 if (prevValue != null && !prevValue.equals(value)) {
570 Main.warn("extended font config - overriding ''{0}={1}'' with ''{2}''", key, prevValue, value);
571 }
572 w.append(key + '=' + value + '\n');
573 }
574 w.append('\n');
575 String fallback = props.getProperty("sequence.fallback");
576 if (fallback != null) {
577 w.append("sequence.fallback=" + fallback + ',' + Utils.join(",", allCharSubsets) + '\n');
578 } else {
579 w.append("sequence.fallback=" + Utils.join(",", allCharSubsets) + '\n');
580 }
581 }
582 Utils.updateSystemProperty("sun.awt.fontconfig", fontconfigFile.toString());
583 } catch (IOException ex) {
584 Main.error(ex);
585 }
586 }
587
588 /**
589 * Get a list of fonts that are installed on the system.
590 *
591 * Must be done without triggering the Java Font initialization.
592 * (See {@link #extendFontconfig(java.lang.String)}, have to set system
593 * property first, which is then read by sun.awt.FontConfiguration upon initialization.)
594 *
595 * @return list of file names
596 */
597 public Collection<String> getInstalledFonts() {
598 throw new UnsupportedOperationException();
599 }
600
601 /**
602 * Get default list of additional fonts to add to the configuration.
603 *
604 * Java will choose thee first font in the list that can render a certain character.
605 *
606 * @return list of FontEntry objects
607 */
608 public Collection<FontEntry> getAdditionalFonts() {
609 throw new UnsupportedOperationException();
610 }
611}
Note: See TracBrowser for help on using the repository browser.