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