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

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

code style - Method stores return result in local before immediately returning it

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