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

Last change on this file since 8811 was 8540, checked in by Don-vip, 9 years ago

fix remaining checkstyle issues

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