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

Last change on this file since 12780 was 12776, checked in by bastiK, 7 years ago

see #15229 - remove dependency of NTV2GridShiftFileWrapper on Main.platform

  • PlatformHook bundles all application-wide platform dependent code, which is

convenient, but problematic for separating modules

  • introduces lightweight tools.Platform for adding platform dependent code more locally
  • Property svn:eol-style set to native
File size: 18.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.event.KeyEvent;
8import java.io.BufferedReader;
9import java.io.File;
10import java.io.FileInputStream;
11import java.io.IOException;
12import java.net.URI;
13import java.net.URISyntaxException;
14import java.nio.charset.StandardCharsets;
15import java.nio.file.Files;
16import java.nio.file.Path;
17import java.nio.file.Paths;
18import java.security.KeyStoreException;
19import java.security.NoSuchAlgorithmException;
20import java.security.cert.CertificateException;
21import java.security.cert.CertificateFactory;
22import java.security.cert.X509Certificate;
23import java.util.Arrays;
24import java.util.Locale;
25
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.io.CertificateAmendment.CertAmend;
28
29/**
30 * {@code PlatformHook} implementation for Unix systems.
31 * @since 1023
32 */
33public class PlatformHookUnixoid implements PlatformHook {
34
35 private String osDescription;
36
37 // rpm returns translated string "package %s is not installed\n", can't find a way to force english output
38 // translations from https://github.com/rpm-software-management/rpm
39 private static final String[] NOT_INSTALLED = {
40 "not installed", // en
41 "no s'ha instal·lat", // ca
42 "尚未安裝", // cmn
43 "není nainstalován", // cs
44 "ikke installeret", // da
45 "nicht installiert", // de
46 "ne estas instalita", // eo
47 "no está instalado", // es
48 "ole asennettu", // fi
49 "pas installé", // fr
50 "non è stato installato", // it
51 "はインストールされていません。", // ja
52 "패키지가 설치되어 있지 않습니다", // ko
53 "ikke installert", // nb
54 "nie jest zainstalowany", // pl
55 "não está instalado", // pt
56 "не установлен", // ru
57 "ni nameščen", // sl
58 "nie je nainštalovaný", // sk
59 "није инсталиран", // sr
60 "inte installerat", // sv
61 "kurulu değil", // tr
62 "не встановлено", // uk
63 "chưa cài đặt gói", // vi
64 "未安装软件包", // zh_CN
65 "尚未安裝" // zh_TW
66 };
67
68 @Override
69 public Platform getPlatform() {
70 return Platform.UNIXOID;
71 }
72
73 @Override
74 public void preStartupHook() {
75 // See #12022 - Disable GNOME ATK Java wrapper as it causes a lot of serious trouble
76 if ("org.GNOME.Accessibility.AtkWrapper".equals(System.getProperty("assistive_technologies"))) {
77 System.clearProperty("assistive_technologies");
78 }
79 }
80
81 @Override
82 public void openUrl(String url) throws IOException {
83 for (String program : Main.pref.getCollection("browser.unix",
84 Arrays.asList("xdg-open", "#DESKTOP#", "$BROWSER", "gnome-open", "kfmclient openURL", "firefox"))) {
85 try {
86 if ("#DESKTOP#".equals(program)) {
87 Desktop.getDesktop().browse(new URI(url));
88 } else if (program.startsWith("$")) {
89 program = System.getenv().get(program.substring(1));
90 Runtime.getRuntime().exec(new String[]{program, url});
91 } else {
92 Runtime.getRuntime().exec(new String[]{program, url});
93 }
94 return;
95 } catch (IOException | URISyntaxException e) {
96 Logging.warn(e);
97 }
98 }
99 }
100
101 @Override
102 public void initSystemShortcuts() {
103 // CHECKSTYLE.OFF: LineLength
104 // TODO: Insert system shortcuts here. See Windows and especially OSX to see how to.
105 for (int i = KeyEvent.VK_F1; i <= KeyEvent.VK_F12; ++i) {
106 Shortcut.registerSystemShortcut("screen:toogle"+i, tr("reserved"), i, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
107 .setAutomatic();
108 }
109 Shortcut.registerSystemShortcut("system:reset", tr("reserved"), KeyEvent.VK_DELETE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
110 .setAutomatic();
111 Shortcut.registerSystemShortcut("system:resetX", tr("reserved"), KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
112 .setAutomatic();
113 // CHECKSTYLE.ON: LineLength
114 }
115
116 @Override
117 public String getDefaultStyle() {
118 return "javax.swing.plaf.metal.MetalLookAndFeel";
119 }
120
121 /**
122 * Determines if the distribution is Debian or Ubuntu, or a derivative.
123 * @return {@code true} if the distribution is Debian, Ubuntu or Mint, {@code false} otherwise
124 */
125 public static boolean isDebianOrUbuntu() {
126 try {
127 String dist = Utils.execOutput(Arrays.asList("lsb_release", "-i", "-s"));
128 return "Debian".equalsIgnoreCase(dist) || "Ubuntu".equalsIgnoreCase(dist) || "Mint".equalsIgnoreCase(dist);
129 } catch (IOException e) {
130 // lsb_release is not available on all Linux systems, so don't log at warning level
131 Logging.debug(e);
132 return false;
133 }
134 }
135
136 /**
137 * Get the package name including detailed version.
138 * @param packageNames The possible package names (when a package can have different names on different distributions)
139 * @return The package name and package version if it can be identified, null otherwise
140 * @since 7314
141 */
142 public static String getPackageDetails(String... packageNames) {
143 try {
144 // CHECKSTYLE.OFF: SingleSpaceSeparator
145 boolean dpkg = Paths.get("/usr/bin/dpkg-query").toFile().exists();
146 boolean eque = Paths.get("/usr/bin/equery").toFile().exists();
147 boolean rpm = Paths.get("/bin/rpm").toFile().exists();
148 // CHECKSTYLE.ON: SingleSpaceSeparator
149 if (dpkg || rpm || eque) {
150 for (String packageName : packageNames) {
151 String[] args;
152 if (dpkg) {
153 args = new String[] {"dpkg-query", "--show", "--showformat", "${Architecture}-${Version}", packageName};
154 } else if (eque) {
155 args = new String[] {"equery", "-q", "list", "-e", "--format=$fullversion", packageName};
156 } else {
157 args = new String[] {"rpm", "-q", "--qf", "%{arch}-%{version}", packageName};
158 }
159 String version = Utils.execOutput(Arrays.asList(args));
160 if (version != null) {
161 for (String notInstalled : NOT_INSTALLED) {
162 if (version.contains(notInstalled))
163 break;
164 }
165 return packageName + ':' + version;
166 }
167 }
168 }
169 } catch (IOException e) {
170 Logging.warn(e);
171 }
172 return null;
173 }
174
175 /**
176 * Get the Java package name including detailed version.
177 *
178 * Some Java bugs are specific to a certain security update, so in addition
179 * to the Java version, we also need the exact package version.
180 *
181 * @return The package name and package version if it can be identified, null otherwise
182 */
183 public String getJavaPackageDetails() {
184 String home = System.getProperty("java.home");
185 if (home.contains("java-8-openjdk") || home.contains("java-1.8.0-openjdk")) {
186 return getPackageDetails("openjdk-8-jre", "java-1_8_0-openjdk", "java-1.8.0-openjdk");
187 } else if (home.contains("java-9-openjdk") || home.contains("java-1.9.0-openjdk")) {
188 return getPackageDetails("openjdk-9-jre", "java-1_9_0-openjdk", "java-1.9.0-openjdk");
189 } else if (home.contains("icedtea")) {
190 return getPackageDetails("icedtea-bin");
191 } else if (home.contains("oracle")) {
192 return getPackageDetails("oracle-jdk-bin", "oracle-jre-bin");
193 }
194 return null;
195 }
196
197 /**
198 * Get the Web Start package name including detailed version.
199 *
200 * OpenJDK packages are shipped with icedtea-web package,
201 * but its version generally does not match main java package version.
202 *
203 * Simply return {@code null} if there's no separate package for Java WebStart.
204 *
205 * @return The package name and package version if it can be identified, null otherwise
206 */
207 public String getWebStartPackageDetails() {
208 if (isOpenJDK()) {
209 return getPackageDetails("icedtea-netx", "icedtea-web");
210 }
211 return null;
212 }
213
214 /**
215 * Get the Gnome ATK wrapper package name including detailed version.
216 *
217 * Debian and Ubuntu derivatives come with a pre-enabled accessibility software
218 * completely buggy that makes Swing crash in a lot of different ways.
219 *
220 * Simply return {@code null} if it's not found.
221 *
222 * @return The package name and package version if it can be identified, null otherwise
223 */
224 public String getAtkWrapperPackageDetails() {
225 if (isOpenJDK() && isDebianOrUbuntu()) {
226 return getPackageDetails("libatk-wrapper-java");
227 }
228 return null;
229 }
230
231 private String buildOSDescription() {
232 String osName = System.getProperty("os.name");
233 if ("Linux".equalsIgnoreCase(osName)) {
234 try {
235 // Try lsb_release (only available on LSB-compliant Linux systems,
236 // see https://www.linuxbase.org/lsb-cert/productdir.php?by_prod )
237 String line = exec("lsb_release", "-ds");
238 if (line != null && !line.isEmpty()) {
239 line = line.replaceAll("\"+", "");
240 line = line.replaceAll("NAME=", ""); // strange code for some Gentoo's
241 if (line.startsWith("Linux ")) // e.g. Linux Mint
242 return line;
243 else if (!line.isEmpty())
244 return "Linux " + line;
245 }
246 } catch (IOException e) {
247 Logging.debug(e);
248 // Non LSB-compliant Linux system. List of common fallback release files: http://linuxmafia.com/faq/Admin/release-files.html
249 for (LinuxReleaseInfo info : new LinuxReleaseInfo[]{
250 new LinuxReleaseInfo("/etc/lsb-release", "DISTRIB_DESCRIPTION", "DISTRIB_ID", "DISTRIB_RELEASE"),
251 new LinuxReleaseInfo("/etc/os-release", "PRETTY_NAME", "NAME", "VERSION"),
252 new LinuxReleaseInfo("/etc/arch-release"),
253 new LinuxReleaseInfo("/etc/debian_version", "Debian GNU/Linux "),
254 new LinuxReleaseInfo("/etc/fedora-release"),
255 new LinuxReleaseInfo("/etc/gentoo-release"),
256 new LinuxReleaseInfo("/etc/redhat-release"),
257 new LinuxReleaseInfo("/etc/SuSE-release")
258 }) {
259 String description = info.extractDescription();
260 if (description != null && !description.isEmpty()) {
261 return "Linux " + description;
262 }
263 }
264 }
265 }
266 return osName;
267 }
268
269 @Override
270 public String getOSDescription() {
271 if (osDescription == null) {
272 osDescription = buildOSDescription();
273 }
274 return osDescription;
275 }
276
277 private static class LinuxReleaseInfo {
278 private final String path;
279 private final String descriptionField;
280 private final String idField;
281 private final String releaseField;
282 private final boolean plainText;
283 private final String prefix;
284
285 LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField) {
286 this(path, descriptionField, idField, releaseField, false, null);
287 }
288
289 LinuxReleaseInfo(String path) {
290 this(path, null, null, null, true, null);
291 }
292
293 LinuxReleaseInfo(String path, String prefix) {
294 this(path, null, null, null, true, prefix);
295 }
296
297 private LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField, boolean plainText, String prefix) {
298 this.path = path;
299 this.descriptionField = descriptionField;
300 this.idField = idField;
301 this.releaseField = releaseField;
302 this.plainText = plainText;
303 this.prefix = prefix;
304 }
305
306 @Override
307 public String toString() {
308 return "ReleaseInfo [path=" + path + ", descriptionField=" + descriptionField +
309 ", idField=" + idField + ", releaseField=" + releaseField + ']';
310 }
311
312 /**
313 * Extracts OS detailed information from a Linux release file (/etc/xxx-release)
314 * @return The OS detailed information, or {@code null}
315 */
316 public String extractDescription() {
317 String result = null;
318 if (path != null) {
319 Path p = Paths.get(path);
320 if (p.toFile().exists()) {
321 try (BufferedReader reader = Files.newBufferedReader(p, StandardCharsets.UTF_8)) {
322 String id = null;
323 String release = null;
324 String line;
325 while (result == null && (line = reader.readLine()) != null) {
326 if (line.contains("=")) {
327 String[] tokens = line.split("=");
328 if (tokens.length >= 2) {
329 // Description, if available, contains exactly what we need
330 if (descriptionField != null && descriptionField.equalsIgnoreCase(tokens[0])) {
331 result = Utils.strip(tokens[1]);
332 } else if (idField != null && idField.equalsIgnoreCase(tokens[0])) {
333 id = Utils.strip(tokens[1]);
334 } else if (releaseField != null && releaseField.equalsIgnoreCase(tokens[0])) {
335 release = Utils.strip(tokens[1]);
336 }
337 }
338 } else if (plainText && !line.isEmpty()) {
339 // Files composed of a single line
340 result = Utils.strip(line);
341 }
342 }
343 // If no description has been found, try to rebuild it with "id" + "release" (i.e. "name" + "version")
344 if (result == null && id != null && release != null) {
345 result = id + ' ' + release;
346 }
347 } catch (IOException e) {
348 // Ignore
349 Logging.trace(e);
350 }
351 }
352 }
353 // Append prefix if any
354 if (result != null && !result.isEmpty() && prefix != null && !prefix.isEmpty()) {
355 result = prefix + result;
356 }
357 if (result != null)
358 result = result.replaceAll("\"+", "");
359 return result;
360 }
361 }
362
363 /**
364 * Get the dot directory <code>~/.josm</code>.
365 * @return the dot directory
366 */
367 private static File getDotDirectory() {
368 String dirName = "." + Main.pref.getJOSMDirectoryBaseName().toLowerCase(Locale.ENGLISH);
369 return new File(System.getProperty("user.home"), dirName);
370 }
371
372 /**
373 * Returns true if the dot directory should be used for storing preferences,
374 * cache and user data.
375 * Currently this is the case, if the dot directory already exists.
376 * @return true if the dot directory should be used
377 */
378 private static boolean useDotDirectory() {
379 return getDotDirectory().exists();
380 }
381
382 @Override
383 public File getDefaultCacheDirectory() {
384 if (useDotDirectory()) {
385 return new File(getDotDirectory(), "cache");
386 } else {
387 String xdgCacheDir = System.getenv("XDG_CACHE_HOME");
388 if (xdgCacheDir != null && !xdgCacheDir.isEmpty()) {
389 return new File(xdgCacheDir, Main.pref.getJOSMDirectoryBaseName());
390 } else {
391 return new File(System.getProperty("user.home") + File.separator +
392 ".cache" + File.separator + Main.pref.getJOSMDirectoryBaseName());
393 }
394 }
395 }
396
397 @Override
398 public File getDefaultPrefDirectory() {
399 if (useDotDirectory()) {
400 return getDotDirectory();
401 } else {
402 String xdgConfigDir = System.getenv("XDG_CONFIG_HOME");
403 if (xdgConfigDir != null && !xdgConfigDir.isEmpty()) {
404 return new File(xdgConfigDir, Main.pref.getJOSMDirectoryBaseName());
405 } else {
406 return new File(System.getProperty("user.home") + File.separator +
407 ".config" + File.separator + Main.pref.getJOSMDirectoryBaseName());
408 }
409 }
410 }
411
412 @Override
413 public File getDefaultUserDataDirectory() {
414 if (useDotDirectory()) {
415 return getDotDirectory();
416 } else {
417 String xdgDataDir = System.getenv("XDG_DATA_HOME");
418 if (xdgDataDir != null && !xdgDataDir.isEmpty()) {
419 return new File(xdgDataDir, Main.pref.getJOSMDirectoryBaseName());
420 } else {
421 return new File(System.getProperty("user.home") + File.separator +
422 ".local" + File.separator + "share" + File.separator + Main.pref.getJOSMDirectoryBaseName());
423 }
424 }
425 }
426
427 @Override
428 public X509Certificate getX509Certificate(CertAmend certAmend)
429 throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
430 File f = new File("/usr/share/ca-certificates/mozilla", certAmend.getFilename());
431 if (f.exists()) {
432 CertificateFactory fact = CertificateFactory.getInstance("X.509");
433 try (FileInputStream is = new FileInputStream(f)) {
434 return (X509Certificate) fact.generateCertificate(is);
435 }
436 }
437 return null;
438 }
439}
Note: See TracBrowser for help on using the repository browser.