001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.awt.event.ActionEvent;
008import java.awt.event.KeyEvent;
009import java.io.File;
010import java.io.IOException;
011import java.lang.management.ManagementFactory;
012import java.util.ArrayList;
013import java.util.Arrays;
014import java.util.Collection;
015import java.util.List;
016
017import org.openstreetmap.josm.Main;
018import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
019import org.openstreetmap.josm.tools.ImageProvider;
020import org.openstreetmap.josm.tools.Shortcut;
021
022/**
023 * Restarts JOSM as it was launched. Comes from "restart" plugin, originally written by Upliner.
024 * <br><br>
025 * Mechanisms have been improved based on #8561 discussions and
026 * <a href="http://lewisleo.blogspot.jp/2012/08/programmatically-restart-java.html">this article</a>.
027 * @since 5857
028 */
029public class RestartAction extends JosmAction {
030
031    // AppleScript to restart OS X package
032    private static final String RESTART_APPLE_SCRIPT =
033              "tell application \"System Events\"\n"
034            + "repeat until not (exists process \"JOSM\")\n"
035            + "delay 0.2\n"
036            + "end repeat\n"
037            + "end tell\n"
038            + "tell application \"JOSM\" to activate";
039
040    /**
041     * Constructs a new {@code RestartAction}.
042     */
043    public RestartAction() {
044        super(tr("Restart"), "restart", tr("Restart the application."),
045                Shortcut.registerShortcut("file:restart", tr("File: {0}", tr("Restart")), KeyEvent.VK_J, Shortcut.ALT_CTRL_SHIFT), false);
046        putValue("help", ht("/Action/Restart"));
047        putValue("toolbar", "action/restart");
048        Main.toolbar.register(this);
049        setEnabled(isRestartSupported());
050    }
051
052    @Override
053    public void actionPerformed(ActionEvent e) {
054        // If JOSM has been started with property 'josm.restart=true' this means
055        // it is executed by a start script that can handle restart.
056        // Request for restart is indicated by exit code 9.
057        String scriptRestart = System.getProperty("josm.restart");
058        if ("true".equals(scriptRestart)) {
059            Main.exitJosm(true, 9);
060        }
061
062        try {
063            restartJOSM();
064        } catch (IOException ex) {
065            Main.error(ex);
066        }
067    }
068
069    /**
070     * Determines if restarting the application should be possible on this platform.
071     * @return {@code true} if the mandatory system property {@code sun.java.command} is defined, {@code false} otherwise.
072     * @since 5951
073     */
074    public static boolean isRestartSupported() {
075        return System.getProperty("sun.java.command") != null;
076    }
077
078    /**
079     * Restarts the current Java application
080     * @throws IOException in case of any error
081     */
082    public static void restartJOSM() throws IOException {
083        if (isRestartSupported() && !Main.exitJosm(false, 0)) return;
084        final List<String> cmd;
085        try {
086            // special handling for OSX .app package
087            if (Main.isPlatformOsx() && System.getProperty("java.library.path").contains("/JOSM.app/Contents/MacOS")) {
088                cmd = getAppleCommands();
089            } else {
090                cmd = getCommands();
091            }
092            Main.info("Restart "+cmd);
093            if (Main.isDebugEnabled() && Main.pref.getBoolean("restart.debug.simulation")) {
094                Main.debug("Restart cancelled to get debug info");
095                return;
096            }
097            // execute the command in a shutdown hook, to be sure that all the
098            // resources have been disposed before restarting the application
099            Runtime.getRuntime().addShutdownHook(new Thread("josm-restarter") {
100                @Override
101                public void run() {
102                    try {
103                        Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
104                    } catch (IOException e) {
105                        Main.error(e);
106                    }
107                }
108            });
109            // exit
110            System.exit(0);
111        } catch (Exception e) {
112            // something went wrong
113            throw new IOException("Error while trying to restart the application", e);
114        }
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            if (Main.isDebugEnabled()) {
142                Main.debug("Detected jnlp without jnlpx.origFilenameArg property set");
143            }
144            cmd.addAll(Arrays.asList(mainCommand));
145        } else {
146            // look for a .jar in all chunks to support paths with spaces (fix #9077)
147            StringBuilder sb = new StringBuilder(mainCommand[0]);
148            for (int i = 1; i < mainCommand.length && !mainCommand[i-1].endsWith(".jar"); i++) {
149                sb.append(' ').append(mainCommand[i]);
150            }
151            String jarPath = sb.toString();
152            // program main is a jar
153            if (jarPath.endsWith(".jar")) {
154                // if it's a jar, add -jar mainJar
155                cmd.add("-jar");
156                cmd.add(new File(jarPath).getPath());
157            } else {
158                // else it's a .class, add the classpath and mainClass
159                cmd.add("-cp");
160                cmd.add('"' + System.getProperty("java.class.path") + '"');
161                cmd.add(mainCommand[0]);
162            }
163            // add JNLP file.
164            if (jnlp != null) {
165                cmd.add(jnlp);
166            }
167        }
168        // finally add program arguments
169        cmd.addAll(Main.getCommandLineArgs());
170        return cmd;
171    }
172
173    private static String getJavaRuntime() throws IOException {
174        final String java = System.getProperty("java.home") + File.separator + "bin" + File.separator +
175                (Main.isPlatformWindows() ? "java.exe" : "java");
176        if (!new File(java).isFile()) {
177            throw new IOException("Unable to find suitable java runtime at "+java);
178        }
179        return java;
180    }
181
182    private static void addVMArguments(Collection<String> cmd) {
183        List<String> arguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
184        if (Main.isDebugEnabled()) {
185            Main.debug("VM arguments: "+arguments);
186        }
187        for (String arg : arguments) {
188            // When run from jp2launcher.exe, jnlpx.remove is true, while it is not when run from javaws
189            // Always set it to false to avoid error caused by a missing jnlp file on the second restart
190            arg = arg.replace("-Djnlpx.remove=true", "-Djnlpx.remove=false");
191            // if it's the agent argument : we ignore it otherwise the
192            // address of the old application and the new one will be in conflict
193            if (!arg.contains("-agentlib")) {
194                cmd.add(arg);
195            }
196        }
197    }
198
199    /**
200     * Returns a new {@code ButtonSpec} instance that performs this action.
201     * @return A new {@code ButtonSpec} instance that performs this action.
202     */
203    public static ButtonSpec getRestartButtonSpec() {
204        return new ButtonSpec(
205                tr("Restart"),
206                ImageProvider.get("restart"),
207                tr("Restart the application."),
208                ht("/Action/Restart"),
209                isRestartSupported()
210        );
211    }
212
213    /**
214     * Returns a new {@code ButtonSpec} instance that do not perform this action.
215     * @return A new {@code ButtonSpec} instance that do not perform this action.
216     */
217    public static ButtonSpec getCancelButtonSpec() {
218        return new ButtonSpec(
219                tr("Cancel"),
220                ImageProvider.get("cancel"),
221                tr("Click to restart later."),
222                null /* no specific help context */
223        );
224    }
225
226    /**
227     * Returns default {@code ButtonSpec} instances for this action (Restart/Cancel).
228     * @return Default {@code ButtonSpec} instances for this action.
229     * @see #getRestartButtonSpec
230     * @see #getCancelButtonSpec
231     */
232    public static ButtonSpec[] getButtonSpecs() {
233        return new ButtonSpec[] {
234                getRestartButtonSpec(),
235                getCancelButtonSpec()
236        };
237    }
238}