source: josm/trunk/src/org/openstreetmap/josm/actions/RestartAction.java@ 12772

Last change on this file since 12772 was 12637, checked in by Don-vip, 7 years ago

see #15182 - deprecate Main.toolbar. Replacement: gui.MainApplication.getToolbar()

  • Property svn:eol-style set to native
File size: 9.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.event.ActionEvent;
8import java.awt.event.KeyEvent;
9import java.io.File;
10import java.io.IOException;
11import java.lang.management.ManagementFactory;
12import java.util.ArrayList;
13import java.util.Arrays;
14import java.util.Collection;
15import java.util.List;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
19import org.openstreetmap.josm.gui.MainApplication;
20import org.openstreetmap.josm.gui.io.SaveLayersDialog;
21import org.openstreetmap.josm.tools.ImageProvider;
22import org.openstreetmap.josm.tools.Logging;
23import org.openstreetmap.josm.tools.Shortcut;
24
25/**
26 * Restarts JOSM as it was launched. Comes from "restart" plugin, originally written by Upliner.
27 * <br><br>
28 * Mechanisms have been improved based on #8561 discussions and
29 * <a href="http://lewisleo.blogspot.jp/2012/08/programmatically-restart-java.html">this article</a>.
30 * @since 5857
31 */
32public class RestartAction extends JosmAction {
33
34 // AppleScript to restart OS X package
35 private static final String RESTART_APPLE_SCRIPT =
36 "tell application \"System Events\"\n"
37 + "repeat until not (exists process \"JOSM\")\n"
38 + "delay 0.2\n"
39 + "end repeat\n"
40 + "end tell\n"
41 + "tell application \"JOSM\" to activate";
42
43 /**
44 * Constructs a new {@code RestartAction}.
45 */
46 public RestartAction() {
47 super(tr("Restart"), "restart", tr("Restart the application."),
48 Shortcut.registerShortcut("file:restart", tr("File: {0}", tr("Restart")), KeyEvent.VK_J, Shortcut.ALT_CTRL_SHIFT), false);
49 putValue("help", ht("/Action/Restart"));
50 putValue("toolbar", "action/restart");
51 if (MainApplication.getToolbar() != null) {
52 MainApplication.getToolbar().register(this);
53 }
54 setEnabled(isRestartSupported());
55 }
56
57 @Override
58 public void actionPerformed(ActionEvent e) {
59 try {
60 restartJOSM();
61 } catch (IOException ex) {
62 Logging.error(ex);
63 }
64 }
65
66 /**
67 * Determines if restarting the application should be possible on this platform.
68 * @return {@code true} if the mandatory system property {@code sun.java.command} is defined, {@code false} otherwise.
69 * @since 5951
70 */
71 public static boolean isRestartSupported() {
72 return System.getProperty("sun.java.command") != null;
73 }
74
75 /**
76 * Restarts the current Java application.
77 * @throws IOException in case of any I/O error
78 */
79 public static void restartJOSM() throws IOException {
80 // If JOSM has been started with property 'josm.restart=true' this means
81 // it is executed by a start script that can handle restart.
82 // Request for restart is indicated by exit code 9.
83 String scriptRestart = System.getProperty("josm.restart");
84 if ("true".equals(scriptRestart)) {
85 MainApplication.exitJosm(true, 9, SaveLayersDialog.Reason.RESTART);
86 }
87
88 if (isRestartSupported() && !MainApplication.exitJosm(false, 0, SaveLayersDialog.Reason.RESTART)) return;
89 final List<String> cmd;
90 // special handling for OSX .app package
91 if (Main.isPlatformOsx() && System.getProperty("java.library.path").contains("/JOSM.app/Contents/MacOS")) {
92 cmd = getAppleCommands();
93 } else {
94 cmd = getCommands();
95 }
96 Logging.info("Restart "+cmd);
97 if (Logging.isDebugEnabled() && Main.pref.getBoolean("restart.debug.simulation")) {
98 Logging.debug("Restart cancelled to get debug info");
99 return;
100 }
101 // execute the command in a shutdown hook, to be sure that all the
102 // resources have been disposed before restarting the application
103 Runtime.getRuntime().addShutdownHook(new Thread("josm-restarter") {
104 @Override
105 public void run() {
106 try {
107 Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
108 } catch (IOException e) {
109 Logging.error(e);
110 }
111 }
112 });
113 // exit
114 System.exit(0);
115 }
116
117 private static List<String> getAppleCommands() {
118 final List<String> cmd = new ArrayList<>();
119 cmd.add("/usr/bin/osascript");
120 for (String line : RESTART_APPLE_SCRIPT.split("\n")) {
121 cmd.add("-e");
122 cmd.add(line);
123 }
124 return cmd;
125 }
126
127 private static List<String> getCommands() throws IOException {
128 final List<String> cmd = new ArrayList<>();
129 // java binary
130 cmd.add(getJavaRuntime());
131 // vm arguments
132 addVMArguments(cmd);
133 // Determine webstart JNLP file. Use jnlpx.origFilenameArg instead of jnlp.application.href,
134 // because only this one is present when run from j2plauncher.exe (see #10795)
135 final String jnlp = System.getProperty("jnlpx.origFilenameArg");
136 // program main and program arguments (be careful a sun property. might not be supported by all JVM)
137 final String javaCommand = System.getProperty("sun.java.command");
138 String[] mainCommand = javaCommand.split(" ");
139 if (javaCommand.endsWith(".jnlp") && jnlp == null) {
140 // see #11751 - jnlp on Linux
141 Logging.debug("Detected jnlp without jnlpx.origFilenameArg property set");
142 cmd.addAll(Arrays.asList(mainCommand));
143 } else {
144 // look for a .jar in all chunks to support paths with spaces (fix #9077)
145 StringBuilder sb = new StringBuilder(mainCommand[0]);
146 for (int i = 1; i < mainCommand.length && !mainCommand[i-1].endsWith(".jar"); i++) {
147 sb.append(' ').append(mainCommand[i]);
148 }
149 String jarPath = sb.toString();
150 // program main is a jar
151 if (jarPath.endsWith(".jar")) {
152 // if it's a jar, add -jar mainJar
153 cmd.add("-jar");
154 cmd.add(new File(jarPath).getPath());
155 } else {
156 // else it's a .class, add the classpath and mainClass
157 cmd.add("-cp");
158 cmd.add('"' + System.getProperty("java.class.path") + '"');
159 cmd.add(mainCommand[0]);
160 }
161 // add JNLP file.
162 if (jnlp != null) {
163 cmd.add(jnlp);
164 }
165 }
166 // finally add program arguments
167 cmd.addAll(MainApplication.getCommandLineArgs());
168 return cmd;
169 }
170
171 private static String getJavaRuntime() throws IOException {
172 final String java = System.getProperty("java.home") + File.separator + "bin" + File.separator +
173 (Main.isPlatformWindows() ? "java.exe" : "java");
174 if (!new File(java).isFile()) {
175 throw new IOException("Unable to find suitable java runtime at "+java);
176 }
177 return java;
178 }
179
180 private static void addVMArguments(Collection<String> cmd) {
181 List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
182 Logging.debug("VM arguments: {0}", arguments);
183 for (String arg : arguments) {
184 // When run from jp2launcher.exe, jnlpx.remove is true, while it is not when run from javaws
185 // Always set it to false to avoid error caused by a missing jnlp file on the second restart
186 arg = arg.replace("-Djnlpx.remove=true", "-Djnlpx.remove=false");
187 // if it's the agent argument : we ignore it otherwise the
188 // address of the old application and the new one will be in conflict
189 if (!arg.contains("-agentlib")) {
190 cmd.add(arg);
191 }
192 }
193 }
194
195 /**
196 * Returns a new {@code ButtonSpec} instance that performs this action.
197 * @return A new {@code ButtonSpec} instance that performs this action.
198 */
199 public static ButtonSpec getRestartButtonSpec() {
200 return new ButtonSpec(
201 tr("Restart"),
202 ImageProvider.get("restart"),
203 tr("Restart the application."),
204 ht("/Action/Restart"),
205 isRestartSupported()
206 );
207 }
208
209 /**
210 * Returns a new {@code ButtonSpec} instance that do not perform this action.
211 * @return A new {@code ButtonSpec} instance that do not perform this action.
212 */
213 public static ButtonSpec getCancelButtonSpec() {
214 return new ButtonSpec(
215 tr("Cancel"),
216 ImageProvider.get("cancel"),
217 tr("Click to restart later."),
218 null /* no specific help context */
219 );
220 }
221
222 /**
223 * Returns default {@code ButtonSpec} instances for this action (Restart/Cancel).
224 * @return Default {@code ButtonSpec} instances for this action.
225 * @see #getRestartButtonSpec
226 * @see #getCancelButtonSpec
227 */
228 public static ButtonSpec[] getButtonSpecs() {
229 return new ButtonSpec[] {
230 getRestartButtonSpec(),
231 getCancelButtonSpec()
232 };
233 }
234}
Note: See TracBrowser for help on using the repository browser.