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