001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.layer.geoimage;
003
004import static java.util.stream.Collectors.toList;
005import static org.openstreetmap.josm.tools.I18n.tr;
006import static org.openstreetmap.josm.tools.I18n.trn;
007
008import java.awt.AlphaComposite;
009import java.awt.BasicStroke;
010import java.awt.Color;
011import java.awt.Composite;
012import java.awt.Dimension;
013import java.awt.Graphics2D;
014import java.awt.Image;
015import java.awt.Point;
016import java.awt.Rectangle;
017import java.awt.RenderingHints;
018import java.awt.event.MouseAdapter;
019import java.awt.event.MouseEvent;
020import java.awt.event.MouseMotionAdapter;
021import java.awt.image.BufferedImage;
022import java.io.File;
023import java.util.ArrayList;
024import java.util.Collection;
025import java.util.Collections;
026import java.util.Comparator;
027import java.util.LinkedList;
028import java.util.List;
029import java.util.Objects;
030import java.util.concurrent.ExecutorService;
031import java.util.concurrent.Executors;
032
033import javax.swing.Action;
034import javax.swing.Icon;
035import javax.swing.ImageIcon;
036
037import org.openstreetmap.josm.actions.AutoScaleAction;
038import org.openstreetmap.josm.actions.ExpertToggleAction;
039import org.openstreetmap.josm.actions.RenameLayerAction;
040import org.openstreetmap.josm.actions.mapmode.MapMode;
041import org.openstreetmap.josm.actions.mapmode.SelectAction;
042import org.openstreetmap.josm.actions.mapmode.SelectLassoAction;
043import org.openstreetmap.josm.data.Bounds;
044import org.openstreetmap.josm.data.Data;
045import org.openstreetmap.josm.data.ImageData;
046import org.openstreetmap.josm.data.ImageData.ImageDataUpdateListener;
047import org.openstreetmap.josm.data.gpx.GpxData;
048import org.openstreetmap.josm.data.gpx.GpxImageEntry;
049import org.openstreetmap.josm.data.gpx.GpxTrack;
050import org.openstreetmap.josm.data.gpx.TimeSource;
051import org.openstreetmap.josm.data.imagery.street_level.IImageEntry;
052import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
053import org.openstreetmap.josm.data.preferences.NamedColorProperty;
054import org.openstreetmap.josm.gui.MainApplication;
055import org.openstreetmap.josm.gui.MapFrame;
056import org.openstreetmap.josm.gui.MapFrame.MapModeChangeListener;
057import org.openstreetmap.josm.gui.MapView;
058import org.openstreetmap.josm.gui.NavigatableComponent;
059import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
060import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
061import org.openstreetmap.josm.gui.layer.AbstractModifiableLayer;
062import org.openstreetmap.josm.gui.layer.GpxLayer;
063import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToMarkerLayer;
064import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToNextMarker;
065import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToPreviousMarker;
066import org.openstreetmap.josm.gui.layer.Layer;
067import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
068import org.openstreetmap.josm.gui.util.imagery.Vector3D;
069import org.openstreetmap.josm.tools.ImageProvider;
070import org.openstreetmap.josm.tools.ListenerList;
071import org.openstreetmap.josm.tools.Utils;
072
073/**
074 * Layer displaying geotagged pictures.
075 * @since 99
076 */
077public class GeoImageLayer extends AbstractModifiableLayer implements
078        JumpToMarkerLayer, NavigatableComponent.ZoomChangeListener, ImageDataUpdateListener,
079        IGeoImageLayer {
080
081    private static final List<Action> menuAdditions = new LinkedList<>();
082
083    private static volatile List<MapMode> supportedMapModes;
084
085    private final ImageData data;
086    private final ListenerList<IGeoImageLayer.ImageChangeListener> imageChangeListeners = ListenerList.create();
087    GpxData gpxData;
088    GpxLayer gpxFauxLayer;
089    GpxData gpxFauxData;
090
091    private CorrelateGpxWithImages gpxCorrelateAction;
092
093    private final Icon icon = ImageProvider.get("dialogs/geoimage/photo-marker");
094    private final Icon selectedIcon = ImageProvider.get("dialogs/geoimage/photo-marker-selected");
095    private final Icon selectedIconNotImageViewer = generateSelectedIconNotImageViewer(this.selectedIcon);
096
097    private static Icon generateSelectedIconNotImageViewer(Icon selectedIcon) {
098        Color color = new NamedColorProperty("geoimage.selected.not.image.viewer", new Color(50, 0, 0)).get();
099        BufferedImage bi = new BufferedImage(selectedIcon.getIconWidth(), selectedIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
100        Graphics2D g2d = bi.createGraphics();
101        selectedIcon.paintIcon(null, g2d, 0, 0);
102        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
103        g2d.setColor(color);
104        g2d.fillRect(0, 0, selectedIcon.getIconWidth(), selectedIcon.getIconHeight());
105        g2d.dispose();
106        return new ImageIcon(bi);
107    }
108
109    boolean useThumbs;
110    private final ExecutorService thumbsLoaderExecutor =
111            Executors.newSingleThreadExecutor(Utils.newThreadFactory("thumbnail-loader-%d", Thread.MIN_PRIORITY));
112    private ThumbsLoader thumbsloader;
113    private boolean thumbsLoaderRunning;
114    volatile boolean thumbsLoaded;
115    private BufferedImage offscreenBuffer;
116    private boolean updateOffscreenBuffer = true;
117
118    private MouseAdapter mouseAdapter;
119    private MouseMotionAdapter mouseMotionAdapter;
120    private MapModeChangeListener mapModeListener;
121    private ActiveLayerChangeListener activeLayerChangeListener;
122
123    /** Mouse position where the last image was selected. */
124    private Point lastSelPos;
125    /** The mouse point */
126    private Point startPoint;
127
128    /**
129     * Image cycle mode flag.
130     * It is possible that a mouse button release triggers multiple mouseReleased() events.
131     * To prevent the cycling in such a case we wait for the next mouse button press event
132     * before it is cycled to the next image.
133     */
134    private boolean cycleModeArmed;
135
136    /**
137     * Constructs a new {@code GeoImageLayer}.
138     * @param data The list of images to display
139     * @param gpxLayer The associated GPX layer
140     */
141    public GeoImageLayer(final List<ImageEntry> data, GpxLayer gpxLayer) {
142        this(data, gpxLayer, null, false);
143    }
144
145    /**
146     * Constructs a new {@code GeoImageLayer}.
147     * @param data The list of images to display
148     * @param gpxLayer The associated GPX layer
149     * @param name Layer name
150     * @since 6392
151     */
152    public GeoImageLayer(final List<ImageEntry> data, GpxLayer gpxLayer, final String name) {
153        this(data, gpxLayer, name, false);
154    }
155
156    /**
157     * Constructs a new {@code GeoImageLayer}.
158     * @param data The list of images to display
159     * @param gpxLayer The associated GPX layer
160     * @param useThumbs Thumbnail display flag
161     * @since 6392
162     */
163    public GeoImageLayer(final List<ImageEntry> data, GpxLayer gpxLayer, boolean useThumbs) {
164        this(data, gpxLayer, null, useThumbs);
165    }
166
167    /**
168     * Constructs a new {@code GeoImageLayer}.
169     * @param data The list of images to display
170     * @param gpxLayer The associated GPX layer
171     * @param name Layer name
172     * @param useThumbs Thumbnail display flag
173     * @since 6392
174     */
175    public GeoImageLayer(final List<ImageEntry> data, GpxLayer gpxLayer, final String name, boolean useThumbs) {
176        this(data, gpxLayer != null ? gpxLayer.data : null, name, useThumbs);
177    }
178
179    /**
180     * Constructs a new {@code GeoImageLayer}.
181     * @param data The list of images to display
182     * @param gpxData The associated GPX data
183     * @param name Layer name
184     * @param useThumbs Thumbnail display flag
185     * @since 18078
186     */
187    public GeoImageLayer(final List<ImageEntry> data, GpxData gpxData, final String name, boolean useThumbs) {
188        super(!Utils.isStripEmpty(name) ? name : tr("Geotagged Images"));
189        this.data = new ImageData(data);
190        this.gpxData = gpxData;
191        this.useThumbs = useThumbs;
192        this.data.addImageDataUpdateListener(this);
193        this.data.setLayer(this);
194    }
195
196    private final class ImageMouseListener extends MouseAdapter {
197        private boolean isMapModeOk() {
198            MapMode mapMode = MainApplication.getMap().mapMode;
199            return mapMode == null || isSupportedMapMode(mapMode);
200        }
201
202        @Override
203        public void mousePressed(MouseEvent e) {
204            if (e.getButton() != MouseEvent.BUTTON1)
205                return;
206            if (isVisible() && isMapModeOk()) {
207                cycleModeArmed = true;
208                invalidate();
209                startPoint = e.getPoint();
210            }
211        }
212
213        @Override
214        public void mouseReleased(MouseEvent ev) {
215            if (ev.getButton() != MouseEvent.BUTTON1)
216                return;
217            if (!isVisible() || !isMapModeOk())
218                return;
219            if (!cycleModeArmed) {
220                return;
221            }
222
223            Rectangle hitBoxClick = new Rectangle((int) startPoint.getX() - 10, (int) startPoint.getY() - 10, 15, 15);
224            if (!hitBoxClick.contains(ev.getPoint())) {
225                return;
226            }
227
228            Point mousePos = ev.getPoint();
229            boolean cycle = cycleModeArmed && lastSelPos != null && lastSelPos.equals(mousePos);
230            final boolean isShift = (ev.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) == MouseEvent.SHIFT_DOWN_MASK;
231            final boolean isCtrl = (ev.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) == MouseEvent.CTRL_DOWN_MASK;
232            int idx = getPhotoIdxUnderMouse(ev, cycle);
233            if (idx >= 0) {
234                lastSelPos = mousePos;
235                cycleModeArmed = false;
236                ImageEntry img = data.getImages().get(idx);
237                if (isShift) {
238                    if (isCtrl && !data.getSelectedImages().isEmpty()) {
239                        int idx2 = data.getImages().indexOf(data.getSelectedImages().get(data.getSelectedImages().size() - 1));
240                        int startIndex = Math.min(idx, idx2);
241                        int endIndex = Math.max(idx, idx2);
242                        for (int i = startIndex; i <= endIndex; i++) {
243                            data.addImageToSelection(data.getImages().get(i));
244                        }
245                    } else {
246                        if (data.isImageSelected(img)) {
247                            data.removeImageToSelection(img);
248                        } else {
249                            data.addImageToSelection(img);
250                        }
251                    }
252                } else {
253                    data.setSelectedImage(img);
254                    ImageViewerDialog.getInstance().displayImages(Collections.singletonList(img));
255                }
256                GeoImageLayer.this.invalidate(); // Needed to update which image is being shown in the image viewer in the mapview
257            }
258        }
259    }
260
261    /**
262     * Create a GeoImageLayer asynchronously
263     * @param files the list of image files to display
264     * @param gpxLayer the gpx layer
265     */
266    public static void create(Collection<File> files, GpxLayer gpxLayer) {
267        MainApplication.worker.execute(new ImagesLoader(files, gpxLayer));
268    }
269
270    @Override
271    public void clearSelection() {
272        this.getImageData().clearSelectedImage();
273    }
274
275    @Override
276    public boolean containsImage(IImageEntry<?> imageEntry) {
277        if (imageEntry instanceof ImageEntry) {
278            return this.data.getImages().contains(imageEntry);
279        }
280        return false;
281    }
282
283    @Override
284    public Icon getIcon() {
285        return ImageProvider.get("dialogs/geoimage", ImageProvider.ImageSizes.LAYER);
286    }
287
288    @Override
289    public List<ImageEntry> getSelection() {
290        return this.getImageData().getSelectedImages();
291    }
292
293    @Override
294    public List<IImageEntry<?>> getInvalidGeoImages() {
295        return this.getImageData().getImages().stream().filter(entry -> entry.getPos() == null || !entry.getPos().isValid()).collect(toList());
296    }
297
298    @Override
299    public void addImageChangeListener(ImageChangeListener listener) {
300        this.imageChangeListeners.addListener(listener);
301    }
302
303    @Override
304    public void removeImageChangeListener(ImageChangeListener listener) {
305        this.imageChangeListeners.removeListener(listener);
306    }
307
308    /**
309     * Register actions on the layer
310     * @param addition the action to be added
311     */
312    public static void registerMenuAddition(Action addition) {
313        menuAdditions.add(addition);
314    }
315
316    @Override
317    public Action[] getMenuEntries() {
318        List<Action> entries = new ArrayList<>();
319        entries.add(LayerListDialog.getInstance().createShowHideLayerAction());
320        entries.add(LayerListDialog.getInstance().createDeleteLayerAction());
321        entries.add(MainApplication.getMenu().autoScaleActions.get(AutoScaleAction.AutoScaleMode.LAYER));
322        entries.add(LayerListDialog.getInstance().createMergeLayerAction(this));
323        entries.add(new RenameLayerAction(null, this));
324        entries.add(SeparatorLayerAction.INSTANCE);
325        entries.add(getGpxCorrelateAction());
326        if (ExpertToggleAction.isExpert()) {
327            entries.add(new EditImagesSequenceAction(this));
328            entries.add(new LayerGpxExportAction(this));
329        }
330        entries.add(new ShowThumbnailAction(this));
331        if (!menuAdditions.isEmpty()) {
332            entries.add(SeparatorLayerAction.INSTANCE);
333            entries.addAll(menuAdditions);
334        }
335        entries.add(SeparatorLayerAction.INSTANCE);
336        entries.add(new JumpToNextMarker(this));
337        entries.add(new JumpToPreviousMarker(this));
338        entries.add(SeparatorLayerAction.INSTANCE);
339        entries.add(new LayerListPopup.InfoAction(this));
340
341        return entries.toArray(new Action[0]);
342    }
343
344    /**
345     * Prepare the string that is displayed if layer information is requested.
346     * @return String with layer information
347     */
348    private String infoText() {
349        int tagged = 0;
350        int newdata = 0;
351        int n = data.getImages().size();
352        for (ImageEntry e : data.getImages()) {
353            if (e.getPos() != null) {
354                tagged++;
355            }
356            if (e.hasNewGpsData()) {
357                newdata++;
358            }
359        }
360        return "<html>"
361                + trn("{0} image loaded.", "{0} images loaded.", n, n)
362                + ' ' + trn("{0} was found to be GPS tagged.", "{0} were found to be GPS tagged.", tagged, tagged)
363                + (newdata > 0 ? "<br>" + trn("{0} has updated GPS data.", "{0} have updated GPS data.", newdata, newdata) : "")
364                + "</html>";
365    }
366
367    @Override
368    public Object getInfoComponent() {
369        return infoText();
370    }
371
372    @Override
373    public String getToolTipText() {
374        return infoText();
375    }
376
377    /**
378     * Determines if data managed by this layer has been modified.  That is
379     * the case if one image has modified GPS data.
380     * @return {@code true} if data has been modified; {@code false}, otherwise
381     */
382    @Override
383    public boolean isModified() {
384        return this.data.isModified();
385    }
386
387    @Override
388    public boolean isMergable(Layer other) {
389        return other instanceof GeoImageLayer;
390    }
391
392    @Override
393    public void mergeFrom(Layer from) {
394        if (!(from instanceof GeoImageLayer))
395            throw new IllegalArgumentException("not a GeoImageLayer: " + from);
396        GeoImageLayer l = (GeoImageLayer) from;
397
398        // Stop to load thumbnails on both layers.  Thumbnail loading will continue the next time
399        // the layer is painted.
400        stopLoadThumbs();
401        l.stopLoadThumbs();
402
403        this.data.mergeFrom(l.getImageData());
404
405        setName(l.getName());
406        thumbsLoaded &= l.thumbsLoaded;
407    }
408
409    private static Dimension scaledDimension(Image thumb) {
410        final double d = MainApplication.getMap().mapView.getDist100Pixel();
411        final double size = 10 /*meter*/;     /* size of the photo on the map */
412        double s = size * 100 /*px*/ / d;
413
414        final double sMin = ThumbsLoader.minSize;
415        final double sMax = ThumbsLoader.maxSize;
416
417        if (s < sMin) {
418            s = sMin;
419        }
420        if (s > sMax) {
421            s = sMax;
422        }
423        final double f = s / sMax;  /* scale factor */
424
425        if (thumb == null)
426            return null;
427
428        return new Dimension(
429                (int) Math.round(f * thumb.getWidth(null)),
430                (int) Math.round(f * thumb.getHeight(null)));
431    }
432
433    /**
434     * Paint one image.
435     * @param e Image to be painted
436     * @param mv Map view
437     * @param clip Bounding rectangle of the current clipping area
438     * @param tempG Temporary offscreen buffer
439     */
440    private void paintImage(ImageEntry e, MapView mv, Rectangle clip, Graphics2D tempG) {
441        if (e.getPos() == null) {
442            return;
443        }
444        Point p = mv.getPoint(e.getPos());
445        if (e.hasThumbnail()) {
446            Dimension d = scaledDimension(e.getThumbnail());
447            if (d != null) {
448                Rectangle target = new Rectangle(p.x - d.width / 2, p.y - d.height / 2, d.width, d.height);
449                if (clip.intersects(target)) {
450                    tempG.drawImage(e.getThumbnail(), target.x, target.y, target.width, target.height, null);
451                }
452            }
453        } else { // thumbnail not loaded yet
454            icon.paintIcon(mv, tempG,
455                p.x - icon.getIconWidth() / 2,
456                p.y - icon.getIconHeight() / 2);
457        }
458    }
459
460    @Override
461    public void paint(Graphics2D g, MapView mv, Bounds bounds) {
462        int width = mv.getWidth();
463        int height = mv.getHeight();
464        Rectangle clip = g.getClipBounds();
465        if (useThumbs) {
466            if (!thumbsLoaded) {
467                startLoadThumbs();
468            }
469
470            if (null == offscreenBuffer
471                    || offscreenBuffer.getWidth() != width  // reuse the old buffer if possible
472                    || offscreenBuffer.getHeight() != height) {
473                offscreenBuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
474                updateOffscreenBuffer = true;
475            }
476
477            if (updateOffscreenBuffer) {
478                Graphics2D tempG = offscreenBuffer.createGraphics();
479                tempG.setColor(new Color(0, 0, 0, 0));
480                Composite saveComp = tempG.getComposite();
481                tempG.setComposite(AlphaComposite.Clear);   // remove the old images
482                tempG.fillRect(0, 0, width, height);
483                tempG.setComposite(saveComp);
484
485                for (ImageEntry e : data.searchImages(bounds)) {
486                    paintImage(e, mv, clip, tempG);
487                }
488                for (ImageEntry img: this.data.getSelectedImages()) {
489                    // Make sure the selected image is on top in case multiple images overlap.
490                    paintImage(img, mv, clip, tempG);
491                }
492                updateOffscreenBuffer = false;
493            }
494            g.drawImage(offscreenBuffer, 0, 0, null);
495        } else {
496            for (ImageEntry e : data.searchImages(bounds)) {
497                if (e.getPos() == null) {
498                    continue;
499                }
500                Point p = mv.getPoint(e.getPos());
501                icon.paintIcon(mv, g,
502                        p.x - icon.getIconWidth() / 2,
503                        p.y - icon.getIconHeight() / 2);
504            }
505        }
506
507        for (ImageEntry e: data.getSelectedImages()) {
508            if (e != null && e.getPos() != null) {
509                Point p = mv.getPoint(e.getPos());
510                Dimension imgDim = getImageDimension(e);
511
512                Double direction = e.getExifImgDir();
513                if (direction == null)
514                    direction = e.getExifGpsTrack(); // see #24762
515                if (direction != null) {
516                    Vector3D imgRotation = ImageViewerDialog.getInstance().getRotation(e);
517                    final Color color = e.getExifImgDir() != null ? new Color(255, 255, 255, 192) : Color.darkGray;
518                    drawDirectionArrow(g, p,
519                            direction + (imgRotation != null ? Utils.toDegrees(imgRotation.getPolarAngle()) : 0d),
520                            imgDim, color);
521                }
522
523                if (useThumbs && e.hasThumbnail()) {
524                    g.setColor(new Color(128, 0, 0, 122));
525                    g.fillRect(p.x - imgDim.width / 2, p.y - imgDim.height / 2, imgDim.width, imgDim.height);
526                } else if (e.equals(ImageViewerDialog.getCurrentImage())) {
527                    selectedIcon.paintIcon(mv, g,
528                            p.x - imgDim.width / 2,
529                            p.y - imgDim.height / 2);
530                } else {
531                    selectedIconNotImageViewer.paintIcon(mv, g,
532                            p.x - imgDim.width / 2,
533                            p.y - imgDim.height / 2);
534                }
535            }
536        }
537    }
538
539    protected Dimension getImageDimension(ImageEntry e) {
540        if (useThumbs && e.hasThumbnail()) {
541            Dimension d = scaledDimension(e.getThumbnail());
542            return d != null ? d : new Dimension(-1, -1);
543        } else {
544            return new Dimension(selectedIcon.getIconWidth(), selectedIcon.getIconHeight());
545        }
546    }
547
548    protected static void drawDirectionArrow(Graphics2D g, Point p, double dir, Dimension imgDim) {
549        drawDirectionArrow(g, p, dir, imgDim, new Color(255, 255, 255, 192));
550    }
551
552    protected static void drawDirectionArrow(Graphics2D g, Point p, double dir, Dimension imgDim, Color color) {
553        // Multiplier must be larger than sqrt(2)/2=0.71.
554        double arrowlength = Math.max(25, Math.max(imgDim.width, imgDim.height) * 0.85);
555        double arrowwidth = arrowlength / 1.4;
556
557        // Rotate 90 degrees CCW
558        double headdir = (dir < 90) ? dir + 270 : dir - 90;
559        double leftdir = (headdir < 90) ? headdir + 270 : headdir - 90;
560        double rightdir = (headdir > 270) ? headdir - 270 : headdir + 90;
561
562        double ptx = p.x + Math.cos(Utils.toRadians(headdir)) * arrowlength;
563        double pty = p.y + Math.sin(Utils.toRadians(headdir)) * arrowlength;
564
565        double ltx = p.x + Math.cos(Utils.toRadians(leftdir)) * arrowwidth/2;
566        double lty = p.y + Math.sin(Utils.toRadians(leftdir)) * arrowwidth/2;
567
568        double rtx = p.x + Math.cos(Utils.toRadians(rightdir)) * arrowwidth/2;
569        double rty = p.y + Math.sin(Utils.toRadians(rightdir)) * arrowwidth/2;
570
571        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
572        g.setColor(color);
573        int[] xar = {(int) ltx, (int) ptx, (int) rtx, (int) ltx};
574        int[] yar = {(int) lty, (int) pty, (int) rty, (int) lty};
575        g.fillPolygon(xar, yar, 4);
576        g.setColor(Color.black);
577        g.setStroke(new BasicStroke(1.2f));
578        g.drawPolyline(xar, yar, 3);
579    }
580
581    @Override
582    public void visitBoundingBox(BoundingXYVisitor v) {
583        for (ImageEntry e : data.getImages()) {
584            v.visit(e.getPos());
585        }
586    }
587
588    /**
589     * Show current photo on map and in image viewer.
590     */
591    public void showCurrentPhoto() {
592        updateBufferAndRepaint();
593    }
594
595    /**
596     * Check if the position of the mouse event is within the rectangle of the photo icon or thumbnail.
597     * @param idx the image index
598     * @param evt Mouse event
599     * @return {@code true} if the photo matches the mouse position, {@code false} otherwise
600     */
601    private boolean isPhotoIdxUnderMouse(int idx, MouseEvent evt) {
602        ImageEntry img = data.getImages().get(idx);
603        if (img.getPos() != null) {
604            Point imgCenter = MainApplication.getMap().mapView.getPoint(img.getPos());
605            Rectangle imgRect;
606            if (useThumbs && img.hasThumbnail()) {
607                Dimension imgDim = scaledDimension(img.getThumbnail());
608                if (imgDim != null) {
609                    imgRect = new Rectangle(imgCenter.x - imgDim.width / 2,
610                                            imgCenter.y - imgDim.height / 2,
611                                            imgDim.width, imgDim.height);
612                } else {
613                    imgRect = null;
614                }
615            } else {
616                imgRect = new Rectangle(imgCenter.x - icon.getIconWidth() / 2,
617                                        imgCenter.y - icon.getIconHeight() / 2,
618                                        icon.getIconWidth(), icon.getIconHeight());
619            }
620            if (imgRect != null && imgRect.contains(evt.getPoint())) {
621                return true;
622            }
623        }
624        return false;
625    }
626
627    /**
628     * Returns index of the image that matches the position of the mouse event.
629     * @param evt    Mouse event
630     * @param cycle  Set to {@code true} to cycle through the photos at the
631     *               current mouse position if multiple icons or thumbnails overlap.
632     *               If set to {@code false} the topmost photo will be used.
633     * @return       Image index at mouse position, range 0 .. size-1,
634     *               or {@code -1} if there is no image at the mouse position
635     */
636    private int getPhotoIdxUnderMouse(MouseEvent evt, boolean cycle) {
637        ImageEntry selectedImage = data.getSelectedImage();
638        int selectedIndex = data.getImages().indexOf(selectedImage);
639
640        if (cycle && selectedImage != null) {
641            // Cycle loop is forward as that is the natural order.
642            // Loop 1: One after current photo up to last one.
643            for (int idx = selectedIndex + 1; idx < data.getImages().size(); ++idx) {
644                if (isPhotoIdxUnderMouse(idx, evt)) {
645                    return idx;
646                }
647            }
648            // Loop 2: First photo up to current one.
649            for (int idx = 0; idx <= selectedIndex; ++idx) {
650                if (isPhotoIdxUnderMouse(idx, evt)) {
651                    return idx;
652                }
653            }
654        } else {
655            // Check for current photo first, i.e. keep it selected if it is under the mouse.
656            if (selectedImage != null && isPhotoIdxUnderMouse(selectedIndex, evt)) {
657                return selectedIndex;
658            }
659            // Loop from last to first to prefer topmost image.
660            for (int idx = data.getImages().size() - 1; idx >= 0; --idx) {
661                if (isPhotoIdxUnderMouse(idx, evt)) {
662                    return idx;
663                }
664            }
665        }
666        return -1;
667    }
668
669    /**
670     * Returns index of the image that matches the position of the mouse event.
671     * The topmost photo is picked if multiple icons or thumbnails overlap.
672     * @param evt Mouse event
673     * @return Image index at mouse position, range 0 .. size-1,
674     *         or {@code -1} if there is no image at the mouse position
675     */
676    private int getPhotoIdxUnderMouse(MouseEvent evt) {
677        return getPhotoIdxUnderMouse(evt, false);
678    }
679
680    /**
681     * Returns the image that matches the position of the mouse event.
682     * The topmost photo is picked of multiple icons or thumbnails overlap.
683     * @param evt Mouse event
684     * @return Image at mouse position, or {@code null} if there is no image at the mouse position
685     * @since 6392
686     */
687    public ImageEntry getPhotoUnderMouse(MouseEvent evt) {
688        int idx = getPhotoIdxUnderMouse(evt);
689        if (idx >= 0) {
690            return data.getImages().get(idx);
691        } else {
692            return null;
693        }
694    }
695
696    /**
697     * Registers a map mode for which the functionality of this layer should be available.
698     * @param mapMode Map mode to be registered
699     * @since 6392
700     */
701    public static void registerSupportedMapMode(MapMode mapMode) {
702        if (supportedMapModes == null) {
703            supportedMapModes = new ArrayList<>();
704        }
705        supportedMapModes.add(mapMode);
706    }
707
708    /**
709     * Determines if the functionality of this layer is available in
710     * the specified map mode. {@link SelectAction} and {@link SelectLassoAction} are supported by default,
711     * other map modes can be registered.
712     * @param mapMode Map mode to be checked
713     * @return {@code true} if the map mode is supported,
714     *         {@code false} otherwise
715     */
716    private static boolean isSupportedMapMode(MapMode mapMode) {
717        if (mapMode instanceof SelectAction || mapMode instanceof SelectLassoAction) {
718            return true;
719        }
720        return supportedMapModes != null && supportedMapModes.stream().anyMatch(supmmode -> mapMode == supmmode);
721    }
722
723    @Override
724    public void hookUpMapView() {
725        mouseAdapter = new ImageMouseListener();
726
727        mouseMotionAdapter = new MouseMotionAdapter() {
728            @Override
729            public void mouseMoved(MouseEvent evt) {
730                lastSelPos = null;
731            }
732
733            @Override
734            public void mouseDragged(MouseEvent evt) {
735                lastSelPos = null;
736            }
737        };
738
739        mapModeListener = (oldMapMode, newMapMode) -> {
740            MapView mapView = MainApplication.getMap().mapView;
741            mapView.removeMouseListener(mouseAdapter);
742            mapView.removeMouseMotionListener(mouseMotionAdapter);
743            if (newMapMode == null || isSupportedMapMode(newMapMode)) {
744                mapView.addMouseListener(mouseAdapter);
745                mapView.addMouseMotionListener(mouseMotionAdapter);
746            }
747        };
748
749        MapFrame.addMapModeChangeListener(mapModeListener);
750        mapModeListener.mapModeChange(null, MainApplication.getMap().mapMode);
751
752        activeLayerChangeListener = e -> {
753            if (MainApplication.getLayerManager().getActiveLayer() == this) {
754                // only in select mode it is possible to click the images
755                MainApplication.getMap().selectSelectTool(false);
756            }
757        };
758        MainApplication.getLayerManager().addActiveLayerChangeListener(activeLayerChangeListener);
759    }
760
761    @Override
762    public synchronized void destroy() {
763        super.destroy();
764        stopLoadThumbs();
765        if (gpxCorrelateAction != null) {
766            gpxCorrelateAction.destroy();
767            gpxCorrelateAction = null;
768        }
769        MapView mapView = MainApplication.getMap().mapView;
770        mapView.removeMouseListener(mouseAdapter);
771        mapView.removeMouseMotionListener(mouseMotionAdapter);
772        MapView.removeZoomChangeListener(this);
773        MapFrame.removeMapModeChangeListener(mapModeListener);
774        MainApplication.getLayerManager().removeActiveLayerChangeListener(activeLayerChangeListener);
775        data.removeImageDataUpdateListener(this);
776    }
777
778    @Override
779    public LayerPainter attachToMapView(MapViewEvent event) {
780        MapView.addZoomChangeListener(this);
781        return new CompatibilityModeLayerPainter() {
782            @Override
783            public void detachFromMapView(MapViewEvent event) {
784                MapView.removeZoomChangeListener(GeoImageLayer.this);
785            }
786        };
787    }
788
789    @Override
790    public void zoomChanged() {
791        updateBufferAndRepaint();
792    }
793
794    /**
795     * Start to load thumbnails.
796     */
797    public synchronized void startLoadThumbs() {
798        if (useThumbs && !thumbsLoaded && !thumbsLoaderRunning) {
799            stopLoadThumbs();
800            thumbsloader = new ThumbsLoader(this);
801            thumbsLoaderExecutor.submit(thumbsloader);
802            thumbsLoaderRunning = true;
803        }
804    }
805
806    /**
807     * Stop to load thumbnails.
808     * <p>
809     * Can be called at any time to make sure that the
810     * thumbnail loader is stopped.
811     */
812    public synchronized void stopLoadThumbs() {
813        if (thumbsloader != null) {
814            thumbsloader.stop = true;
815        }
816        thumbsLoaderRunning = false;
817    }
818
819    /**
820     * Called to signal that the loading of thumbnails has finished.
821     * <p>
822     * Usually called from {@link ThumbsLoader} in another thread.
823     */
824    public void thumbsLoaded() {
825        thumbsLoaded = true;
826    }
827
828    /**
829     * Marks the offscreen buffer to be updated.
830     */
831    public void updateBufferAndRepaint() {
832        updateOffscreenBuffer = true;
833        invalidate();
834    }
835
836    /**
837     * Get list of images in layer.
838     * @return List of images in layer
839     */
840    public List<ImageEntry> getImages() {
841        return new ArrayList<>(data.getImages());
842    }
843
844    /**
845     * Returns the image data store being used by this layer
846     * @return imageData
847     * @since 14590
848     */
849    public ImageData getImageData() {
850        return data;
851    }
852
853    /**
854     * Returns the associated GPX data if any.
855     * @return The associated GPX data or {@code null}
856     * @since 18078
857     */
858    public GpxData getGpxData() {
859        return gpxData;
860    }
861
862    /**
863     * Returns the associated GPX layer if any.
864     * @return The associated GPX layer or {@code null}
865     */
866    public GpxLayer getGpxLayer() {
867        return gpxData != null ? MainApplication.getLayerManager().getLayersOfType(GpxLayer.class)
868                .stream().filter(l -> gpxData.equals(l.getGpxData()))
869                .findFirst().orElseThrow(IllegalStateException::new) : null;
870    }
871
872    /**
873     * Returns the gpxCorrelateAction
874     * @return the gpxCorrelateAction
875     */
876    public synchronized CorrelateGpxWithImages getGpxCorrelateAction() {
877        if (gpxCorrelateAction == null) {
878            gpxCorrelateAction = new CorrelateGpxWithImages(this);
879        }
880        return gpxCorrelateAction;
881    }
882
883    /**
884     * Returns a faux GPX layer built from the images or the associated GPX layer.
885     * @return A faux GPX layer or the associated GPX layer
886     * @since 14802
887     */
888    public synchronized GpxLayer getFauxGpxLayer() {
889        GpxLayer gpxLayer = getGpxLayer();
890        if (gpxLayer != null) return gpxLayer;
891        if (gpxFauxLayer == null) {
892            gpxFauxLayer = new GpxLayer(getFauxGpxData());
893        }
894        return gpxFauxLayer;
895    }
896
897    /**
898     * Returns a faux GPX data built from the images or the associated GPX layer data.
899     * @return A faux GPX data or the associated GPX layer data
900     * @since 18065
901     */
902    public synchronized GpxData getFauxGpxData() {
903        GpxLayer gpxLayer = getGpxLayer();
904        if (gpxLayer != null) return gpxLayer.data;
905        if (gpxFauxData == null) {
906            gpxFauxData = new GpxData();
907            gpxFauxData.addTrack(new GpxTrack(Collections.singletonList(
908                    data.getImages().stream().map(ImageEntry::asWayPoint).filter(Objects::nonNull).collect(toList())),
909                    Collections.emptyMap()));
910        }
911        return gpxFauxData;
912    }
913
914    @Override
915    public void jumpToNextMarker() {
916        data.setSelectedImage(data.getNextImage());
917        if (data.getSelectedImage() != null)
918            ImageViewerDialog.getInstance().displayImages(Collections.singletonList(data.getSelectedImage()));
919
920    }
921
922    @Override
923    public void jumpToPreviousMarker() {
924        data.setSelectedImage(data.getPreviousImage());
925        if (data.getSelectedImage() != null)
926            ImageViewerDialog.getInstance().displayImages(Collections.singletonList(data.getSelectedImage()));
927    }
928
929    /**
930     * Returns the current thumbnail display status.
931     * {@code true}: thumbnails are displayed, {@code false}: an icon is displayed instead of thumbnails.
932     * @return Current thumbnail display status
933     * @since 6392
934     */
935    public boolean isUseThumbs() {
936        return useThumbs;
937    }
938
939    /**
940     * Enables or disables the display of thumbnails.  Does not update the display.
941     * @param useThumbs New thumbnail display status
942     * @since 6392
943     */
944    public void setUseThumbs(boolean useThumbs) {
945        this.useThumbs = useThumbs;
946        if (useThumbs && !thumbsLoaded) {
947            startLoadThumbs();
948        } else if (!useThumbs) {
949            stopLoadThumbs();
950        }
951        invalidate();
952    }
953
954    @Override
955    public void selectedImageChanged(ImageData data) {
956        showCurrentPhoto();
957        this.imageChangeListeners.fireEvent(e -> e.imageChanged(this, null, data.getSelectedImages()));
958    }
959
960    @Override
961    public void imageDataUpdated(ImageData data) {
962        this.gpxFauxLayer = null;
963        this.gpxFauxData = null;
964        updateBufferAndRepaint();
965    }
966
967    @Override
968    public String getChangesetSourceTag() {
969        return "Geotagged Images";
970    }
971
972    @Override
973    public Data getData() {
974        return getImageData();
975    }
976
977    void applyTmp() {
978        data.getImages().forEach(ImageEntry::applyTmp);
979    }
980
981    void discardTmp() {
982        data.getImages().forEach(ImageEntry::discardTmp);
983    }
984
985    /**
986     * Returns a list of images that fulfill the given criteria.
987     * Default setting is to return untagged images, but may be overwritten.
988     * @param exif also returns images with exif-gps info
989     * @param tagged also returns tagged images
990     * @param timeSource allows to use GPS Time or Camera RTC Time
991     * @return matching images
992     * @since 19455 gpsTime was added
993     */
994    List<ImageEntry> getSortedImgList(boolean exif, boolean tagged, TimeSource timeSource) {
995        return data.getImages().stream()
996                .filter(timeSource == TimeSource.EXIFGPSTIME ? GpxImageEntry::hasExifGpsTime : GpxImageEntry::hasExifTime)
997                .filter(e -> e.getExifCoor() == null || exif)
998                .filter(e -> tagged || !e.isTagged() || e.getExifCoor() != null)
999                .sorted(timeSource == TimeSource.EXIFGPSTIME
1000                    ? Comparator.comparing(ImageEntry::getExifGpsInstant)
1001                    : Comparator.comparing(ImageEntry::getExifInstant))
1002                .collect(toList());
1003    }
1004}