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.Dimension;
008import java.awt.DisplayMode;
009import java.awt.GraphicsEnvironment;
010import java.awt.event.ActionEvent;
011import java.awt.event.KeyEvent;
012import java.lang.management.ManagementFactory;
013import java.util.ArrayList;
014import java.util.Arrays;
015import java.util.Collection;
016import java.util.HashSet;
017import java.util.List;
018import java.util.ListIterator;
019import java.util.Locale;
020import java.util.Map;
021import java.util.Map.Entry;
022import java.util.Set;
023import java.util.stream.Collectors;
024
025import org.openstreetmap.josm.Main;
026import org.openstreetmap.josm.data.Version;
027import org.openstreetmap.josm.data.osm.DataSet;
028import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
029import org.openstreetmap.josm.data.preferences.sources.MapPaintPrefHelper;
030import org.openstreetmap.josm.data.preferences.sources.PresetPrefHelper;
031import org.openstreetmap.josm.data.preferences.sources.SourcePrefHelper;
032import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper;
033import org.openstreetmap.josm.gui.ExtendedDialog;
034import org.openstreetmap.josm.gui.MainApplication;
035import org.openstreetmap.josm.gui.bugreport.DebugTextDisplay;
036import org.openstreetmap.josm.gui.util.GuiHelper;
037import org.openstreetmap.josm.io.OsmApi;
038import org.openstreetmap.josm.plugins.PluginHandler;
039import org.openstreetmap.josm.spi.preferences.Config;
040import org.openstreetmap.josm.spi.preferences.Setting;
041import org.openstreetmap.josm.tools.Logging;
042import org.openstreetmap.josm.tools.PlatformHookUnixoid;
043import org.openstreetmap.josm.tools.Shortcut;
044import org.openstreetmap.josm.tools.Utils;
045import org.openstreetmap.josm.tools.bugreport.BugReportSender;
046
047/**
048 * Opens a dialog with useful status information like version numbers for Java, JOSM and plugins
049 * Also includes preferences with stripped username and password.
050 *
051 * @author xeen
052 */
053public final class ShowStatusReportAction extends JosmAction {
054
055    /**
056     * Constructs a new {@code ShowStatusReportAction}
057     */
058    public ShowStatusReportAction() {
059        super(
060                tr("Show Status Report"),
061                "clock",
062                tr("Show status report with useful information that can be attached to bugs"),
063                Shortcut.registerShortcut("help:showstatusreport", tr("Help: {0}",
064                        tr("Show Status Report")), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE), false);
065
066        putValue("help", ht("/Action/ShowStatusReport"));
067        putValue("toolbar", "help/showstatusreport");
068        MainApplication.getToolbar().register(this);
069    }
070
071    private static boolean isRunningJavaWebStart() {
072        try {
073            // See http://stackoverflow.com/a/16200769/2257172
074            return Class.forName("javax.jnlp.ServiceManager") != null;
075        } catch (ClassNotFoundException e) {
076            return false;
077        }
078    }
079
080    /**
081     * Replies the report header (software and system info)
082     * @return The report header (software and system info)
083     */
084    public static String getReportHeader() {
085        StringBuilder text = new StringBuilder(256);
086        String runtimeVersion = System.getProperty("java.runtime.version");
087        text.append(Version.getInstance().getReleaseAttributes())
088            .append("\nIdentification: ").append(Version.getInstance().getAgentString());
089        String buildNumber = Main.platform.getOSBuildNumber();
090        if (!buildNumber.isEmpty()) {
091            text.append("\nOS Build number: ").append(buildNumber);
092        }
093        text.append("\nMemory Usage: ")
094            .append(Runtime.getRuntime().totalMemory()/1024/1024)
095            .append(" MB / ")
096            .append(Runtime.getRuntime().maxMemory()/1024/1024)
097            .append(" MB (")
098            .append(Runtime.getRuntime().freeMemory()/1024/1024)
099            .append(" MB allocated, but free)\nJava version: ")
100            .append(runtimeVersion != null ? runtimeVersion : System.getProperty("java.version")).append(", ")
101            .append(System.getProperty("java.vendor")).append(", ")
102            .append(System.getProperty("java.vm.name"))
103            .append("\nScreen: ");
104        if (!GraphicsEnvironment.isHeadless()) {
105            text.append(Arrays.stream(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()).map(gd -> {
106                        StringBuilder b = new StringBuilder(gd.getIDstring());
107                        DisplayMode dm = gd.getDisplayMode();
108                        if (dm != null) {
109                            b.append(' ').append(dm.getWidth()).append('x').append(dm.getHeight());
110                        }
111                        return b.toString();
112                    }).collect(Collectors.joining(", ")));
113        }
114        Dimension maxScreenSize = GuiHelper.getMaximumScreenSize();
115        text.append("\nMaximum Screen Size: ")
116            .append((int) maxScreenSize.getWidth()).append('x')
117            .append((int) maxScreenSize.getHeight()).append('\n');
118
119        if (Main.platform instanceof PlatformHookUnixoid) {
120            // Add Java package details
121            String packageDetails = ((PlatformHookUnixoid) Main.platform).getJavaPackageDetails();
122            if (packageDetails != null) {
123                text.append("Java package: ")
124                    .append(packageDetails)
125                    .append('\n');
126            }
127            // Add WebStart package details if run from JNLP
128            if (isRunningJavaWebStart()) {
129                String webStartDetails = ((PlatformHookUnixoid) Main.platform).getWebStartPackageDetails();
130                if (webStartDetails != null) {
131                    text.append("WebStart package: ")
132                        .append(webStartDetails)
133                        .append('\n');
134                }
135            }
136            // Add Gnome Atk wrapper details if found
137            String atkWrapperDetails = ((PlatformHookUnixoid) Main.platform).getAtkWrapperPackageDetails();
138            if (atkWrapperDetails != null) {
139                text.append("Java ATK Wrapper package: ")
140                    .append(atkWrapperDetails)
141                    .append('\n');
142            }
143        }
144        try {
145            // Build a new list of VM parameters to modify it below if needed (default implementation returns an UnmodifiableList instance)
146            List<String> vmArguments = new ArrayList<>(ManagementFactory.getRuntimeMXBean().getInputArguments());
147            for (ListIterator<String> it = vmArguments.listIterator(); it.hasNext();) {
148                String value = it.next();
149                if (value.contains("=")) {
150                    String[] param = value.split("=");
151                    // Hide some parameters for privacy concerns
152                    if (param[0].toLowerCase(Locale.ENGLISH).startsWith("-dproxy")) {
153                        it.set(param[0]+"=xxx");
154                    } else if ("-Djnlpx.vmargs".equals(param[0])) {
155                        // Remove jnlpx.vmargs (base64 encoded copy of VM arguments already included in clear)
156                        it.remove();
157                    } else {
158                        // Replace some paths for readability and privacy concerns
159                        String val = paramCleanup(param[1]);
160                        if (!val.equals(param[1])) {
161                            it.set(param[0] + '=' + val);
162                        }
163                    }
164                } else if (value.startsWith("-X")) {
165                    // Remove arguments like -Xbootclasspath/a, -Xverify:remote, that can be very long and unhelpful
166                    it.remove();
167                }
168            }
169            if (!vmArguments.isEmpty()) {
170                text.append("VM arguments: ").append(vmArguments.toString().replace("\\\\", "\\")).append('\n');
171            }
172        } catch (SecurityException e) {
173            Logging.trace(e);
174        }
175        List<String> commandLineArgs = MainApplication.getCommandLineArgs();
176        if (!commandLineArgs.isEmpty()) {
177            text.append("Program arguments: ").append(Arrays.toString(paramCleanup(commandLineArgs).toArray())).append('\n');
178        }
179        if (Main.main != null) {
180            DataSet dataset = MainApplication.getLayerManager().getActiveDataSet();
181            if (dataset != null) {
182                String result = DatasetConsistencyTest.runTests(dataset);
183                if (result.isEmpty()) {
184                    text.append("Dataset consistency test: No problems found\n");
185                } else {
186                    text.append("\nDataset consistency test:\n").append(result).append('\n');
187                }
188            }
189        }
190        text.append('\n');
191        appendCollection(text, "Plugins", Utils.transform(PluginHandler.getBugReportInformation(), i -> "+ " + i));
192        appendCollection(text, "Tagging presets", getCustomUrls(PresetPrefHelper.INSTANCE));
193        appendCollection(text, "Map paint styles", getCustomUrls(MapPaintPrefHelper.INSTANCE));
194        appendCollection(text, "Validator rules", getCustomUrls(ValidatorPrefHelper.INSTANCE));
195        appendCollection(text, "Last errors/warnings", Utils.transform(Logging.getLastErrorAndWarnings(), i -> "- " + i));
196
197        String osmApi = OsmApi.getOsmApi().getServerUrl();
198        if (!OsmApi.DEFAULT_API_URL.equals(osmApi.trim())) {
199            text.append("OSM API: ").append(osmApi).append("\n\n");
200        }
201
202        return text.toString();
203    }
204
205    private static Collection<String> getCustomUrls(SourcePrefHelper helper) {
206        final Set<String> defaultUrls = helper.getDefault().stream()
207                .map(i -> i.url)
208                .collect(Collectors.toSet());
209        return helper.get().stream()
210                .filter(i -> !defaultUrls.contains(i.url))
211                .map(i -> (i.active ? "+ " : "- ") + i.url)
212                .collect(Collectors.toList());
213    }
214
215    private static List<String> paramCleanup(Collection<String> params) {
216        List<String> result = new ArrayList<>(params.size());
217        for (String param : params) {
218            result.add(paramCleanup(param));
219        }
220        return result;
221    }
222
223    /**
224     * Shortens and removes private informations from a parameter used for status report.
225     * @param param parameter to cleanup
226     * @return shortened/anonymized parameter
227     */
228    private static String paramCleanup(String param) {
229        final String envJavaHome = System.getenv("JAVA_HOME");
230        final String envJavaHomeAlt = Main.isPlatformWindows() ? "%JAVA_HOME%" : "${JAVA_HOME}";
231        final String propJavaHome = System.getProperty("java.home");
232        final String propJavaHomeAlt = "<java.home>";
233        final String prefDir = Config.getDirs().getPreferencesDirectory(false).toString();
234        final String prefDirAlt = "<josm.pref>";
235        final String userDataDir = Config.getDirs().getUserDataDirectory(false).toString();
236        final String userDataDirAlt = "<josm.userdata>";
237        final String userCacheDir = Config.getDirs().getCacheDirectory(false).toString();
238        final String userCacheDirAlt = "<josm.cache>";
239        final String userHomeDir = System.getProperty("user.home");
240        final String userHomeDirAlt = Main.isPlatformWindows() ? "%UserProfile%" : "${HOME}";
241        final String userName = System.getProperty("user.name");
242        final String userNameAlt = "<user.name>";
243
244        String val = param;
245        val = paramReplace(val, envJavaHome, envJavaHomeAlt);
246        val = paramReplace(val, envJavaHome, envJavaHomeAlt);
247        val = paramReplace(val, propJavaHome, propJavaHomeAlt);
248        val = paramReplace(val, prefDir, prefDirAlt);
249        val = paramReplace(val, userDataDir, userDataDirAlt);
250        val = paramReplace(val, userCacheDir, userCacheDirAlt);
251        val = paramReplace(val, userHomeDir, userHomeDirAlt);
252        if (userName.length() >= 3) {
253            val = paramReplace(val, userName, userNameAlt);
254        }
255        return val;
256    }
257
258    private static String paramReplace(String str, String target, String replacement) {
259        return target == null ? str : str.replace(target, replacement);
260    }
261
262    private static void appendCollection(StringBuilder text, String label, Collection<String> col) {
263        if (!col.isEmpty()) {
264            text.append(label).append(":\n");
265            for (String o : col) {
266                text.append(paramCleanup(o)).append('\n');
267            }
268            text.append('\n');
269        }
270    }
271
272    @Override
273    public void actionPerformed(ActionEvent e) {
274        StringBuilder text = new StringBuilder();
275        String reportHeader = getReportHeader();
276        text.append(reportHeader);
277        Map<String, Setting<?>> settings = Main.pref.getAllSettings();
278        Set<String> keys = new HashSet<>(settings.keySet());
279        for (String key : keys) {
280            // Remove sensitive information from status report
281            if (key.startsWith("marker.show") || key.contains("username") || key.contains("password") || key.contains("access-token")) {
282                settings.remove(key);
283            }
284        }
285        for (Entry<String, Setting<?>> entry : settings.entrySet()) {
286            text.append(paramCleanup(entry.getKey()))
287                .append('=')
288                .append(paramCleanup(entry.getValue().getValue().toString())).append('\n');
289        }
290
291        DebugTextDisplay ta = new DebugTextDisplay(text.toString());
292
293        ExtendedDialog ed = new ExtendedDialog(Main.parent,
294                tr("Status Report"),
295                tr("Copy to clipboard and close"), tr("Report bug"), tr("Close"));
296        ed.setButtonIcons("copy", "bug", "cancel");
297        ed.setContent(ta, false);
298        ed.setMinimumSize(new Dimension(380, 200));
299        ed.setPreferredSize(new Dimension(700, Main.parent.getHeight()-50));
300
301        switch (ed.showDialog().getValue()) {
302            case 1: ta.copyToClipboard(); break;
303            case 2: BugReportSender.reportBug(reportHeader); break;
304            default: // Do nothing
305        }
306    }
307}