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