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