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

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

sonar - fix consecutive literal appends

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