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

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

see #15229 - code refactoring - make Preferences.getJOSMDirectoryBaseName() static

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