001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.layer.markerlayer;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.event.ActionEvent;
007import java.io.File;
008import java.net.URL;
009import java.util.Collections;
010
011import javax.swing.JOptionPane;
012
013import org.openstreetmap.josm.Main;
014import org.openstreetmap.josm.data.coor.LatLon;
015import org.openstreetmap.josm.data.gpx.GpxConstants;
016import org.openstreetmap.josm.data.gpx.GpxLink;
017import org.openstreetmap.josm.data.gpx.WayPoint;
018import org.openstreetmap.josm.gui.Notification;
019import org.openstreetmap.josm.tools.CheckParameterUtil;
020import org.openstreetmap.josm.tools.OpenBrowser;
021
022/**
023 * Marker class with Web URL activation.
024 *
025 * @author Frederik Ramm <frederik@remote.org>
026 *
027 */
028public class WebMarker extends ButtonMarker {
029
030    private final URL webUrl;
031
032    public WebMarker(LatLon ll, URL webUrl, MarkerLayer parentLayer, double time, double offset) {
033        super(ll, "web.png", parentLayer, time, offset);
034        CheckParameterUtil.ensureParameterNotNull(webUrl, "webUrl");
035        this.webUrl = webUrl;
036    }
037
038    @Override public void actionPerformed(ActionEvent ev) {
039        String error = OpenBrowser.displayUrl(webUrl.toString());
040        if (error != null) {
041            setErroneous(true);
042            new Notification(
043                    "<b>" + tr("There was an error while trying to display the URL for this marker") + "</b><br>" + 
044                                  tr("(URL was: ") + webUrl.toString() + ")" + "<br>" + error)
045                    .setIcon(JOptionPane.ERROR_MESSAGE)
046                    .setDuration(Notification.TIME_LONG)
047                    .show();
048        } else {
049            updateErroneous();
050        }
051    }
052
053    @Override
054    public WayPoint convertToWayPoint() {
055        WayPoint wpt = super.convertToWayPoint();
056        GpxLink link = new GpxLink(webUrl.toString());
057        link.type = "web";
058        wpt.attr.put(GpxConstants.META_LINKS, Collections.singleton(link));
059        return wpt;
060    }
061    
062    private final void updateErroneous() {
063        if ("file".equals(webUrl.getProtocol())) {
064            String path = webUrl.getPath();
065            try {
066                setErroneous(path.isEmpty() || !new File(path).exists());
067            } catch (Exception e) {
068                Main.warn(e);
069                setErroneous(true);
070            }
071        } else {
072            setErroneous(false);
073        }
074    }
075}