001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.BorderLayout;
007import java.awt.EventQueue;
008import java.io.IOException;
009import java.net.URL;
010import java.nio.charset.StandardCharsets;
011import java.util.regex.Matcher;
012import java.util.regex.Pattern;
013
014import javax.swing.JComponent;
015import javax.swing.JPanel;
016import javax.swing.JScrollPane;
017import javax.swing.border.EmptyBorder;
018import javax.swing.event.HyperlinkEvent;
019import javax.swing.event.HyperlinkListener;
020
021import org.openstreetmap.josm.Main;
022import org.openstreetmap.josm.actions.DownloadPrimitiveAction;
023import org.openstreetmap.josm.data.Version;
024import org.openstreetmap.josm.gui.datatransfer.OpenTransferHandler;
025import org.openstreetmap.josm.gui.dialogs.MenuItemSearchDialog;
026import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
027import org.openstreetmap.josm.gui.preferences.server.ProxyPreferenceListener;
028import org.openstreetmap.josm.gui.widgets.JosmEditorPane;
029import org.openstreetmap.josm.io.CacheCustomContent;
030import org.openstreetmap.josm.io.OnlineResource;
031import org.openstreetmap.josm.spi.preferences.Config;
032import org.openstreetmap.josm.tools.LanguageInfo;
033import org.openstreetmap.josm.tools.Logging;
034import org.openstreetmap.josm.tools.OpenBrowser;
035import org.openstreetmap.josm.tools.Utils;
036import org.openstreetmap.josm.tools.WikiReader;
037
038/**
039 * Panel that fills the main part of the program window when JOSM has just started.
040 *
041 * It downloads and displays the so called <em>message of the day</em>, which
042 * contains news about recent major changes, warning in case of outdated versions, etc.
043 */
044public final class GettingStarted extends JPanel implements ProxyPreferenceListener {
045
046    private final LinkGeneral lg;
047    private String content = "";
048    private boolean contentInitialized;
049
050    private static final String STYLE = "<style type=\"text/css\">\n"
051            + "body {font-family: sans-serif; font-weight: bold; }\n"
052            + "h1 {text-align: center; }\n"
053            + ".icon {font-size: 0; }\n"
054            + "</style>\n";
055
056    public static class LinkGeneral extends JosmEditorPane implements HyperlinkListener {
057
058        /**
059         * Constructs a new {@code LinkGeneral} with the given HTML text
060         * @param text The text to display
061         */
062        public LinkGeneral(String text) {
063            setContentType("text/html");
064            setText(text);
065            setEditable(false);
066            setOpaque(false);
067            addHyperlinkListener(this);
068            adaptForNimbus(this);
069        }
070
071        @Override
072        public void hyperlinkUpdate(HyperlinkEvent e) {
073            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
074                OpenBrowser.displayUrl(e.getDescription());
075            }
076        }
077    }
078
079    /**
080     * Grabs current MOTD from cache or webpage and parses it.
081     */
082    static class MotdContent extends CacheCustomContent<IOException> {
083        MotdContent() {
084            super("motd.html", CacheCustomContent.INTERVAL_DAILY);
085        }
086
087        private final int myVersion = Version.getInstance().getVersion();
088        private final String myJava = Utils.getSystemProperty("java.version");
089        private final String myLang = LanguageInfo.getWikiLanguagePrefix();
090
091        /**
092         * This function gets executed whenever the cached files need updating
093         * @see org.openstreetmap.josm.io.CacheCustomContent#updateData()
094         */
095        @Override
096        protected byte[] updateData() throws IOException {
097            String motd = new WikiReader().readLang("StartupPage");
098            // Save this to prefs in case JOSM is updated so MOTD can be refreshed
099            Config.getPref().putInt("cache.motd.html.version", myVersion);
100            Config.getPref().put("cache.motd.html.java", myJava);
101            Config.getPref().put("cache.motd.html.lang", myLang);
102            return motd.getBytes(StandardCharsets.UTF_8);
103        }
104
105        @Override
106        protected void checkOfflineAccess() {
107            OnlineResource.JOSM_WEBSITE.checkOfflineAccess(new WikiReader().getBaseUrlWiki(), Main.getJOSMWebsite());
108        }
109
110        /**
111         * Additionally check if JOSM has been updated and refresh MOTD
112         */
113        @Override
114        protected boolean isCacheValid() {
115            // We assume a default of myVersion because it only kicks in in two cases:
116            // 1. Not yet written - but so isn't the interval variable, so it gets updated anyway
117            // 2. Cannot be written (e.g. while developing). Obviously we don't want to update
118            // everytime because of something we can't read.
119            return (Config.getPref().getInt("cache.motd.html.version", -999) == myVersion)
120            && Config.getPref().get("cache.motd.html.java").equals(myJava)
121            && Config.getPref().get("cache.motd.html.lang").equals(myLang);
122        }
123    }
124
125    /**
126     * Initializes getting the MOTD as well as enabling the FileDrop Listener. Displays a message
127     * while the MOTD is downloading.
128     */
129    public GettingStarted() {
130        super(new BorderLayout());
131        lg = new LinkGeneral("<html>" + STYLE + "<h1>" + "JOSM - " + tr("Java OpenStreetMap Editor")
132                + "</h1><h2 align=\"center\">" + tr("Downloading \"Message of the day\"") + "</h2></html>");
133        // clear the build-in command ctrl+shift+O, ctrl+space because it is used as shortcut in JOSM
134        lg.getInputMap(JComponent.WHEN_FOCUSED).put(DownloadPrimitiveAction.SHORTCUT.getKeyStroke(), "none");
135        lg.getInputMap(JComponent.WHEN_FOCUSED).put(MenuItemSearchDialog.Action.SHORTCUT.getKeyStroke(), "none");
136        lg.setTransferHandler(null);
137
138        JScrollPane scroller = new JScrollPane(lg);
139        scroller.setViewportBorder(new EmptyBorder(10, 100, 10, 100));
140        add(scroller, BorderLayout.CENTER);
141
142        getMOTD();
143
144        setTransferHandler(new OpenTransferHandler());
145    }
146
147    private void getMOTD() {
148        // Asynchronously get MOTD to speed-up JOSM startup
149        Thread t = new Thread((Runnable) () -> {
150            if (!contentInitialized && Config.getPref().getBoolean("help.displaymotd", true)) {
151                try {
152                    content = new MotdContent().updateIfRequiredString();
153                    contentInitialized = true;
154                    ProxyPreference.removeProxyPreferenceListener(this);
155                } catch (IOException ex) {
156                    Logging.log(Logging.LEVEL_WARN, tr("Failed to read MOTD. Exception was: {0}", ex.toString()), ex);
157                    content = "<html>" + STYLE + "<h1>" + "JOSM - " + tr("Java OpenStreetMap Editor")
158                            + "</h1>\n<h2 align=\"center\">(" + tr("Message of the day not available") + ")</h2></html>";
159                    // In case of MOTD not loaded because of proxy error, listen to preference changes to retry after update
160                    ProxyPreference.addProxyPreferenceListener(this);
161                }
162            }
163
164            if (content != null) {
165                EventQueue.invokeLater(() -> lg.setText(fixImageLinks(content)));
166            }
167        }, "MOTD-Loader");
168        t.setDaemon(true);
169        t.start();
170    }
171
172    static String fixImageLinks(String s) {
173        Matcher m = Pattern.compile("src=\"/browser/trunk(/images/.*?\\.png)\\?format=raw\"").matcher(s);
174        StringBuffer sb = new StringBuffer();
175        while (m.find()) {
176            String im = m.group(1);
177            URL u = GettingStarted.class.getResource(im);
178            if (u != null) {
179                m.appendReplacement(sb, Matcher.quoteReplacement("src=\"" + u + '\"'));
180            }
181        }
182        m.appendTail(sb);
183        return sb.toString();
184    }
185
186    @Override
187    public void proxyPreferenceChanged() {
188        getMOTD();
189    }
190}