source: josm/trunk/src/org/openstreetmap/josm/gui/layer/geoimage/GeoImageLayer.java@ 8342

Last change on this file since 8342 was 8342, checked in by Don-vip, 9 years ago

code style - Close curly brace and the next "else", "catch" and "finally" keywords should be located on the same line

  • Property svn:eol-style set to native
File size: 39.8 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.gui.layer.geoimage;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.AlphaComposite;
8import java.awt.BasicStroke;
9import java.awt.Color;
10import java.awt.Composite;
11import java.awt.Dimension;
12import java.awt.Graphics2D;
13import java.awt.Image;
14import java.awt.Point;
15import java.awt.Rectangle;
16import java.awt.RenderingHints;
17import java.awt.event.MouseAdapter;
18import java.awt.event.MouseEvent;
19import java.awt.image.BufferedImage;
20import java.beans.PropertyChangeEvent;
21import java.beans.PropertyChangeListener;
22import java.io.File;
23import java.io.IOException;
24import java.text.ParseException;
25import java.util.ArrayList;
26import java.util.Arrays;
27import java.util.Calendar;
28import java.util.Collection;
29import java.util.Collections;
30import java.util.GregorianCalendar;
31import java.util.HashSet;
32import java.util.LinkedHashSet;
33import java.util.LinkedList;
34import java.util.List;
35import java.util.Set;
36import java.util.TimeZone;
37import java.util.concurrent.ExecutorService;
38import java.util.concurrent.Executors;
39import java.util.concurrent.ThreadFactory;
40
41import javax.swing.Action;
42import javax.swing.Icon;
43import javax.swing.JLabel;
44import javax.swing.JOptionPane;
45import javax.swing.SwingConstants;
46
47import org.openstreetmap.josm.Main;
48import org.openstreetmap.josm.actions.LassoModeAction;
49import org.openstreetmap.josm.actions.RenameLayerAction;
50import org.openstreetmap.josm.actions.mapmode.MapMode;
51import org.openstreetmap.josm.actions.mapmode.SelectAction;
52import org.openstreetmap.josm.data.Bounds;
53import org.openstreetmap.josm.data.coor.LatLon;
54import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
55import org.openstreetmap.josm.gui.ExtendedDialog;
56import org.openstreetmap.josm.gui.MapFrame;
57import org.openstreetmap.josm.gui.MapFrame.MapModeChangeListener;
58import org.openstreetmap.josm.gui.MapView;
59import org.openstreetmap.josm.gui.MapView.LayerChangeListener;
60import org.openstreetmap.josm.gui.NavigatableComponent;
61import org.openstreetmap.josm.gui.PleaseWaitRunnable;
62import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
63import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
64import org.openstreetmap.josm.gui.layer.GpxLayer;
65import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToMarkerLayer;
66import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToNextMarker;
67import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToPreviousMarker;
68import org.openstreetmap.josm.gui.layer.Layer;
69import org.openstreetmap.josm.gui.util.GuiHelper;
70import org.openstreetmap.josm.tools.ExifReader;
71import org.openstreetmap.josm.tools.ImageProvider;
72import org.openstreetmap.josm.tools.Utils;
73
74import com.drew.imaging.jpeg.JpegMetadataReader;
75import com.drew.lang.CompoundException;
76import com.drew.metadata.Directory;
77import com.drew.metadata.Metadata;
78import com.drew.metadata.MetadataException;
79import com.drew.metadata.exif.ExifIFD0Directory;
80import com.drew.metadata.exif.GpsDirectory;
81
82/**
83 * Layer displaying geottaged pictures.
84 */
85public class GeoImageLayer extends Layer implements PropertyChangeListener, JumpToMarkerLayer {
86
87 List<ImageEntry> data;
88 GpxLayer gpxLayer;
89
90 private Icon icon = ImageProvider.get("dialogs/geoimage/photo-marker");
91 private Icon selectedIcon = ImageProvider.get("dialogs/geoimage/photo-marker-selected");
92
93 private int currentPhoto = -1;
94
95 boolean useThumbs = false;
96 private ExecutorService thumbsLoaderExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
97 @Override
98 public Thread newThread(Runnable r) {
99 Thread t = new Thread(r);
100 t.setPriority(Thread.MIN_PRIORITY);
101 return t;
102 }
103 });
104 private ThumbsLoader thumbsloader;
105 private boolean thumbsLoaderRunning = false;
106 volatile boolean thumbsLoaded = false;
107 private BufferedImage offscreenBuffer;
108 boolean updateOffscreenBuffer = true;
109
110 /** Loads a set of images, while displaying a dialog that indicates what the plugin is currently doing.
111 * In facts, this object is instantiated with a list of files. These files may be JPEG files or
112 * directories. In case of directories, they are scanned to find all the images they contain.
113 * Then all the images that have be found are loaded as ImageEntry instances.
114 */
115 private static final class Loader extends PleaseWaitRunnable {
116
117 private boolean canceled = false;
118 private GeoImageLayer layer;
119 private Collection<File> selection;
120 private Set<String> loadedDirectories = new HashSet<>();
121 private Set<String> errorMessages;
122 private GpxLayer gpxLayer;
123
124 protected void rememberError(String message) {
125 this.errorMessages.add(message);
126 }
127
128 public Loader(Collection<File> selection, GpxLayer gpxLayer) {
129 super(tr("Extracting GPS locations from EXIF"));
130 this.selection = selection;
131 this.gpxLayer = gpxLayer;
132 errorMessages = new LinkedHashSet<>();
133 }
134
135 @Override protected void realRun() throws IOException {
136
137 progressMonitor.subTask(tr("Starting directory scan"));
138 Collection<File> files = new ArrayList<>();
139 try {
140 addRecursiveFiles(files, selection);
141 } catch (IllegalStateException e) {
142 rememberError(e.getMessage());
143 }
144
145 if (canceled)
146 return;
147 progressMonitor.subTask(tr("Read photos..."));
148 progressMonitor.setTicksCount(files.size());
149
150 progressMonitor.subTask(tr("Read photos..."));
151 progressMonitor.setTicksCount(files.size());
152
153 // read the image files
154 List<ImageEntry> data = new ArrayList<>(files.size());
155
156 for (File f : files) {
157
158 if (canceled) {
159 break;
160 }
161
162 progressMonitor.subTask(tr("Reading {0}...", f.getName()));
163 progressMonitor.worked(1);
164
165 ImageEntry e = new ImageEntry();
166
167 // Changed to silently cope with no time info in exif. One case
168 // of person having time that couldn't be parsed, but valid GPS info
169
170 try {
171 e.setExifTime(ExifReader.readTime(f));
172 } catch (ParseException ex) {
173 e.setExifTime(null);
174 }
175 e.setFile(f);
176 extractExif(e);
177 data.add(e);
178 }
179 layer = new GeoImageLayer(data, gpxLayer);
180 files.clear();
181 }
182
183 private void addRecursiveFiles(Collection<File> files, Collection<File> sel) {
184 boolean nullFile = false;
185
186 for (File f : sel) {
187
188 if(canceled) {
189 break;
190 }
191
192 if (f == null) {
193 nullFile = true;
194
195 } else if (f.isDirectory()) {
196 String canonical = null;
197 try {
198 canonical = f.getCanonicalPath();
199 } catch (IOException e) {
200 Main.error(e);
201 rememberError(tr("Unable to get canonical path for directory {0}\n",
202 f.getAbsolutePath()));
203 }
204
205 if (canonical == null || loadedDirectories.contains(canonical)) {
206 continue;
207 } else {
208 loadedDirectories.add(canonical);
209 }
210
211 File[] children = f.listFiles(JpegFileFilter.getInstance());
212 if (children != null) {
213 progressMonitor.subTask(tr("Scanning directory {0}", f.getPath()));
214 addRecursiveFiles(files, Arrays.asList(children));
215 } else {
216 rememberError(tr("Error while getting files from directory {0}\n", f.getPath()));
217 }
218
219 } else {
220 files.add(f);
221 }
222 }
223
224 if (nullFile) {
225 throw new IllegalStateException(tr("One of the selected files was null"));
226 }
227 }
228
229 protected String formatErrorMessages() {
230 StringBuilder sb = new StringBuilder();
231 sb.append("<html>");
232 if (errorMessages.size() == 1) {
233 sb.append(errorMessages.iterator().next());
234 } else {
235 sb.append(Utils.joinAsHtmlUnorderedList(errorMessages));
236 }
237 sb.append("</html>");
238 return sb.toString();
239 }
240
241 @Override protected void finish() {
242 if (!errorMessages.isEmpty()) {
243 JOptionPane.showMessageDialog(
244 Main.parent,
245 formatErrorMessages(),
246 tr("Error"),
247 JOptionPane.ERROR_MESSAGE
248 );
249 }
250 if (layer != null) {
251 Main.main.addLayer(layer);
252
253 if (!canceled && !layer.data.isEmpty()) {
254 boolean noGeotagFound = true;
255 for (ImageEntry e : layer.data) {
256 if (e.getPos() != null) {
257 noGeotagFound = false;
258 }
259 }
260 if (noGeotagFound) {
261 new CorrelateGpxWithImages(layer).actionPerformed(null);
262 }
263 }
264 }
265 }
266
267 @Override protected void cancel() {
268 canceled = true;
269 }
270 }
271
272 public static void create(Collection<File> files, GpxLayer gpxLayer) {
273 Loader loader = new Loader(files, gpxLayer);
274 Main.worker.execute(loader);
275 }
276
277 /**
278 * Constructs a new {@code GeoImageLayer}.
279 * @param data The list of images to display
280 * @param gpxLayer The associated GPX layer
281 */
282 public GeoImageLayer(final List<ImageEntry> data, GpxLayer gpxLayer) {
283 this(data, gpxLayer, null, false);
284 }
285
286 /**
287 * Constructs a new {@code GeoImageLayer}.
288 * @param data The list of images to display
289 * @param gpxLayer The associated GPX layer
290 * @param name Layer name
291 * @since 6392
292 */
293 public GeoImageLayer(final List<ImageEntry> data, GpxLayer gpxLayer, final String name) {
294 this(data, gpxLayer, name, false);
295 }
296
297 /**
298 * Constructs a new {@code GeoImageLayer}.
299 * @param data The list of images to display
300 * @param gpxLayer The associated GPX layer
301 * @param useThumbs Thumbnail display flag
302 * @since 6392
303 */
304 public GeoImageLayer(final List<ImageEntry> data, GpxLayer gpxLayer, boolean useThumbs) {
305 this(data, gpxLayer, null, useThumbs);
306 }
307
308 /**
309 * Constructs a new {@code GeoImageLayer}.
310 * @param data The list of images to display
311 * @param gpxLayer The associated GPX layer
312 * @param name Layer name
313 * @param useThumbs Thumbnail display flag
314 * @since 6392
315 */
316 public GeoImageLayer(final List<ImageEntry> data, GpxLayer gpxLayer, final String name, boolean useThumbs) {
317 super(name != null ? name : tr("Geotagged Images"));
318 Collections.sort(data);
319 this.data = data;
320 this.gpxLayer = gpxLayer;
321 this.useThumbs = useThumbs;
322 }
323
324 @Override
325 public Icon getIcon() {
326 return ImageProvider.get("dialogs/geoimage");
327 }
328
329 private static List<Action> menuAdditions = new LinkedList<>();
330 public static void registerMenuAddition(Action addition) {
331 menuAdditions.add(addition);
332 }
333
334 @Override
335 public Action[] getMenuEntries() {
336
337 List<Action> entries = new ArrayList<>();
338 entries.add(LayerListDialog.getInstance().createShowHideLayerAction());
339 entries.add(LayerListDialog.getInstance().createDeleteLayerAction());
340 entries.add(new RenameLayerAction(null, this));
341 entries.add(SeparatorLayerAction.INSTANCE);
342 entries.add(new CorrelateGpxWithImages(this));
343 entries.add(new ShowThumbnailAction(this));
344 if (!menuAdditions.isEmpty()) {
345 entries.add(SeparatorLayerAction.INSTANCE);
346 entries.addAll(menuAdditions);
347 }
348 entries.add(SeparatorLayerAction.INSTANCE);
349 entries.add(new JumpToNextMarker(this));
350 entries.add(new JumpToPreviousMarker(this));
351 entries.add(SeparatorLayerAction.INSTANCE);
352 entries.add(new LayerListPopup.InfoAction(this));
353
354 return entries.toArray(new Action[entries.size()]);
355
356 }
357
358 /**
359 * Prepare the string that is displayed if layer information is requested.
360 * @return String with layer information
361 */
362 private String infoText() {
363 int tagged = 0;
364 int newdata = 0;
365 for (ImageEntry e : data) {
366 if (e.getPos() != null) {
367 tagged++;
368 }
369 if (e.hasNewGpsData()) {
370 newdata++;
371 }
372 }
373 return "<html>"
374 + trn("{0} image loaded.", "{0} images loaded.", data.size(), data.size())
375 + " " + trn("{0} was found to be GPS tagged.", "{0} were found to be GPS tagged.", tagged, tagged)
376 + (newdata > 0 ? "<br>" + trn("{0} has updated GPS data.", "{0} have updated GPS data.", newdata, newdata) : "")
377 + "</html>";
378 }
379
380 @Override public Object getInfoComponent() {
381 return infoText();
382 }
383
384 @Override
385 public String getToolTipText() {
386 return infoText();
387 }
388
389 @Override
390 public boolean isMergable(Layer other) {
391 return other instanceof GeoImageLayer;
392 }
393
394 @Override
395 public void mergeFrom(Layer 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 final ImageEntry selected = l.currentPhoto >= 0 ? l.data.get(l.currentPhoto) : null;
404
405 data.addAll(l.data);
406 Collections.sort(data);
407
408 // Supress the double photos.
409 if (data.size() > 1) {
410 ImageEntry cur;
411 ImageEntry prev = data.get(data.size() - 1);
412 for (int i = data.size() - 2; i >= 0; i--) {
413 cur = data.get(i);
414 if (cur.getFile().equals(prev.getFile())) {
415 data.remove(i);
416 } else {
417 prev = cur;
418 }
419 }
420 }
421
422 if (selected != null && !data.isEmpty()) {
423 GuiHelper.runInEDTAndWait(new Runnable() {
424 @Override
425 public void run() {
426 for (int i = 0; i < data.size() ; i++) {
427 if (selected.equals(data.get(i))) {
428 currentPhoto = i;
429 ImageViewerDialog.showImage(GeoImageLayer.this, data.get(i));
430 break;
431 }
432 }
433 }
434 });
435 }
436
437 setName(l.getName());
438 thumbsLoaded &= l.thumbsLoaded;
439 }
440
441 private Dimension scaledDimension(Image thumb) {
442 final double d = Main.map.mapView.getDist100Pixel();
443 final double size = 10 /*meter*/; /* size of the photo on the map */
444 double s = size * 100 /*px*/ / d;
445
446 final double sMin = ThumbsLoader.minSize;
447 final double sMax = ThumbsLoader.maxSize;
448
449 if (s < sMin) {
450 s = sMin;
451 }
452 if (s > sMax) {
453 s = sMax;
454 }
455 final double f = s / sMax; /* scale factor */
456
457 if (thumb == null)
458 return null;
459
460 return new Dimension(
461 (int) Math.round(f * thumb.getWidth(null)),
462 (int) Math.round(f * thumb.getHeight(null)));
463 }
464
465 @Override
466 public void paint(Graphics2D g, MapView mv, Bounds bounds) {
467 int width = mv.getWidth();
468 int height = mv.getHeight();
469 Rectangle clip = g.getClipBounds();
470 if (useThumbs) {
471 if (!thumbsLoaded) {
472 startLoadThumbs();
473 }
474
475 if (null == offscreenBuffer || offscreenBuffer.getWidth() != width // reuse the old buffer if possible
476 || offscreenBuffer.getHeight() != height) {
477 offscreenBuffer = new BufferedImage(width, height,
478 BufferedImage.TYPE_INT_ARGB);
479 updateOffscreenBuffer = true;
480 }
481
482 if (updateOffscreenBuffer) {
483 Graphics2D tempG = offscreenBuffer.createGraphics();
484 tempG.setColor(new Color(0,0,0,0));
485 Composite saveComp = tempG.getComposite();
486 tempG.setComposite(AlphaComposite.Clear); // remove the old images
487 tempG.fillRect(0, 0, width, height);
488 tempG.setComposite(saveComp);
489
490 for (ImageEntry e : data) {
491 if (e.getPos() == null) {
492 continue;
493 }
494 Point p = mv.getPoint(e.getPos());
495 if (e.thumbnail != null) {
496 Dimension d = scaledDimension(e.thumbnail);
497 Rectangle target = new Rectangle(p.x - d.width / 2, p.y - d.height / 2, d.width, d.height);
498 if (clip.intersects(target)) {
499 tempG.drawImage(e.thumbnail, target.x, target.y, target.width, target.height, null);
500 }
501 } else { // thumbnail not loaded yet
502 icon.paintIcon(mv, tempG,
503 p.x - icon.getIconWidth() / 2,
504 p.y - icon.getIconHeight() / 2);
505 }
506 }
507 updateOffscreenBuffer = false;
508 }
509 g.drawImage(offscreenBuffer, 0, 0, null);
510 } else {
511 for (ImageEntry e : data) {
512 if (e.getPos() == null) {
513 continue;
514 }
515 Point p = mv.getPoint(e.getPos());
516 icon.paintIcon(mv, g,
517 p.x - icon.getIconWidth() / 2,
518 p.y - icon.getIconHeight() / 2);
519 }
520 }
521
522 if (currentPhoto >= 0 && currentPhoto < data.size()) {
523 ImageEntry e = data.get(currentPhoto);
524
525 if (e.getPos() != null) {
526 Point p = mv.getPoint(e.getPos());
527
528 int imgWidth = 100;
529 int imgHeight = 100;
530 if (useThumbs && e.thumbnail != null) {
531 Dimension d = scaledDimension(e.thumbnail);
532 imgWidth = d.width;
533 imgHeight = d.height;
534 } else {
535 imgWidth = selectedIcon.getIconWidth();
536 imgHeight = selectedIcon.getIconHeight();
537 }
538
539 if (e.getExifImgDir() != null) {
540 // Multiplier must be larger than sqrt(2)/2=0.71.
541 double arrowlength = Math.max(25, Math.max(imgWidth, imgHeight) * 0.85);
542 double arrowwidth = arrowlength / 1.4;
543
544 double dir = e.getExifImgDir();
545 // Rotate 90 degrees CCW
546 double headdir = ( dir < 90 ) ? dir + 270 : dir - 90;
547 double leftdir = ( headdir < 90 ) ? headdir + 270 : headdir - 90;
548 double rightdir = ( headdir > 270 ) ? headdir - 270 : headdir + 90;
549
550 double ptx = p.x + Math.cos(Math.toRadians(headdir)) * arrowlength;
551 double pty = p.y + Math.sin(Math.toRadians(headdir)) * arrowlength;
552
553 double ltx = p.x + Math.cos(Math.toRadians(leftdir)) * arrowwidth/2;
554 double lty = p.y + Math.sin(Math.toRadians(leftdir)) * arrowwidth/2;
555
556 double rtx = p.x + Math.cos(Math.toRadians(rightdir)) * arrowwidth/2;
557 double rty = p.y + Math.sin(Math.toRadians(rightdir)) * arrowwidth/2;
558
559 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
560 g.setColor(new Color(255, 255, 255, 192));
561 int[] xar = {(int) ltx, (int) ptx, (int) rtx, (int) ltx};
562 int[] yar = {(int) lty, (int) pty, (int) rty, (int) lty};
563 g.fillPolygon(xar, yar, 4);
564 g.setColor(Color.black);
565 g.setStroke(new BasicStroke(1.2f));
566 g.drawPolyline(xar, yar, 3);
567 }
568
569 if (useThumbs && e.thumbnail != null) {
570 g.setColor(new Color(128, 0, 0, 122));
571 g.fillRect(p.x - imgWidth / 2, p.y - imgHeight / 2, imgWidth, imgHeight);
572 } else {
573 selectedIcon.paintIcon(mv, g,
574 p.x - imgWidth / 2,
575 p.y - imgHeight / 2);
576
577 }
578 }
579 }
580 }
581
582 @Override
583 public void visitBoundingBox(BoundingXYVisitor v) {
584 for (ImageEntry e : data) {
585 v.visit(e.getPos());
586 }
587 }
588
589 /**
590 * Extract GPS metadata from image EXIF
591 *
592 * If successful, fills in the LatLon and EastNorth attributes of passed in image
593 */
594 private static void extractExif(ImageEntry e) {
595
596 Metadata metadata;
597 Directory dirExif;
598 GpsDirectory dirGps;
599
600 try {
601 metadata = JpegMetadataReader.readMetadata(e.getFile());
602 dirExif = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
603 dirGps = metadata.getFirstDirectoryOfType(GpsDirectory.class);
604 } catch (CompoundException | IOException p) {
605 e.setExifCoor(null);
606 e.setPos(null);
607 return;
608 }
609
610 try {
611 if (dirExif != null) {
612 int orientation = dirExif.getInt(ExifIFD0Directory.TAG_ORIENTATION);
613 e.setExifOrientation(orientation);
614 }
615 } catch (MetadataException ex) {
616 Main.debug(ex.getMessage());
617 }
618
619 if (dirGps == null) {
620 e.setExifCoor(null);
621 e.setPos(null);
622 return;
623 }
624
625 try {
626 double speed = dirGps.getDouble(GpsDirectory.TAG_SPEED);
627 String speedRef = dirGps.getString(GpsDirectory.TAG_SPEED_REF);
628 if (speedRef != null) {
629 if (speedRef.equalsIgnoreCase("M")) {
630 // miles per hour
631 speed *= 1.609344;
632 } else if (speedRef.equalsIgnoreCase("N")) {
633 // knots == nautical miles per hour
634 speed *= 1.852;
635 }
636 // default is K (km/h)
637 }
638 e.setSpeed(speed);
639 } catch (Exception ex) {
640 Main.debug(ex.getMessage());
641 }
642
643 try {
644 double ele = dirGps.getDouble(GpsDirectory.TAG_ALTITUDE);
645 int d = dirGps.getInt(GpsDirectory.TAG_ALTITUDE_REF);
646 if (d == 1) {
647 ele *= -1;
648 }
649 e.setElevation(ele);
650 } catch (MetadataException ex) {
651 Main.debug(ex.getMessage());
652 }
653
654 try {
655 LatLon latlon = ExifReader.readLatLon(dirGps);
656 e.setExifCoor(latlon);
657 e.setPos(e.getExifCoor());
658
659 } catch (Exception ex) { // (other exceptions, e.g. #5271)
660 Main.error("Error reading EXIF from file: "+ex);
661 e.setExifCoor(null);
662 e.setPos(null);
663 }
664
665 try {
666 Double direction = ExifReader.readDirection(dirGps);
667 if (direction != null) {
668 e.setExifImgDir(direction.doubleValue());
669 }
670 } catch (Exception ex) { // (CompoundException and other exceptions, e.g. #5271)
671 Main.debug(ex.getMessage());
672 }
673
674 // Time and date. We can have these cases:
675 // 1) GPS_TIME_STAMP not set -> date/time will be null
676 // 2) GPS_DATE_STAMP not set -> use EXIF date or set to default
677 // 3) GPS_TIME_STAMP and GPS_DATE_STAMP are set
678 int[] timeStampComps = dirGps.getIntArray(GpsDirectory.TAG_TIME_STAMP);
679 if (timeStampComps != null) {
680 int gpsHour = timeStampComps[0];
681 int gpsMin = timeStampComps[1];
682 int gpsSec = timeStampComps[2];
683 Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
684
685 // We have the time. Next step is to check if the GPS date stamp is set.
686 // dirGps.getString() always succeeds, but the return value might be null.
687 String dateStampStr = dirGps.getString(GpsDirectory.TAG_DATE_STAMP);
688 if (dateStampStr != null && dateStampStr.matches("^\\d+:\\d+:\\d+$")) {
689 String[] dateStampComps = dateStampStr.split(":");
690 cal.set(Calendar.YEAR, Integer.parseInt(dateStampComps[0]));
691 cal.set(Calendar.MONTH, Integer.parseInt(dateStampComps[1]) - 1);
692 cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateStampComps[2]));
693 } else {
694 // No GPS date stamp in EXIF data. Copy it from EXIF time.
695 // Date is not set if EXIF time is not available.
696 if (e.hasExifTime()) {
697 // Time not set yet, so we can copy everything, not just date.
698 cal.setTime(e.getExifTime());
699 }
700 }
701
702 cal.set(Calendar.HOUR_OF_DAY, gpsHour);
703 cal.set(Calendar.MINUTE, gpsMin);
704 cal.set(Calendar.SECOND, gpsSec);
705
706 e.setExifGpsTime(cal.getTime());
707 }
708 }
709
710 public void showNextPhoto() {
711 if (data != null && !data.isEmpty()) {
712 currentPhoto++;
713 if (currentPhoto >= data.size()) {
714 currentPhoto = data.size() - 1;
715 }
716 ImageViewerDialog.showImage(this, data.get(currentPhoto));
717 } else {
718 currentPhoto = -1;
719 }
720 Main.map.repaint();
721 }
722
723 public void showPreviousPhoto() {
724 if (data != null && !data.isEmpty()) {
725 currentPhoto--;
726 if (currentPhoto < 0) {
727 currentPhoto = 0;
728 }
729 ImageViewerDialog.showImage(this, data.get(currentPhoto));
730 } else {
731 currentPhoto = -1;
732 }
733 Main.map.repaint();
734 }
735
736 public void showFirstPhoto() {
737 if (data != null && !data.isEmpty()) {
738 currentPhoto = 0;
739 ImageViewerDialog.showImage(this, data.get(currentPhoto));
740 } else {
741 currentPhoto = -1;
742 }
743 Main.map.repaint();
744 }
745
746 public void showLastPhoto() {
747 if (data != null && !data.isEmpty()) {
748 currentPhoto = data.size() - 1;
749 ImageViewerDialog.showImage(this, data.get(currentPhoto));
750 } else {
751 currentPhoto = -1;
752 }
753 Main.map.repaint();
754 }
755
756 public void checkPreviousNextButtons() {
757 ImageViewerDialog.setNextEnabled(currentPhoto < data.size() - 1);
758 ImageViewerDialog.setPreviousEnabled(currentPhoto > 0);
759 }
760
761 public void removeCurrentPhoto() {
762 if (data != null && !data.isEmpty() && currentPhoto >= 0 && currentPhoto < data.size()) {
763 data.remove(currentPhoto);
764 if (currentPhoto >= data.size()) {
765 currentPhoto = data.size() - 1;
766 }
767 if (currentPhoto >= 0) {
768 ImageViewerDialog.showImage(this, data.get(currentPhoto));
769 } else {
770 ImageViewerDialog.showImage(this, null);
771 }
772 updateOffscreenBuffer = true;
773 Main.map.repaint();
774 }
775 }
776
777 public void removeCurrentPhotoFromDisk() {
778 ImageEntry toDelete = null;
779 if (data != null && !data.isEmpty() && currentPhoto >= 0 && currentPhoto < data.size()) {
780 toDelete = data.get(currentPhoto);
781
782 int result = new ExtendedDialog(
783 Main.parent,
784 tr("Delete image file from disk"),
785 new String[] {tr("Cancel"), tr("Delete")})
786 .setButtonIcons(new String[] {"cancel", "dialogs/delete"})
787 .setContent(new JLabel(tr("<html><h3>Delete the file {0} from disk?<p>The image file will be permanently lost!</h3></html>"
788 ,toDelete.getFile().getName()), ImageProvider.get("dialogs/geoimage/deletefromdisk"),SwingConstants.LEFT))
789 .toggleEnable("geoimage.deleteimagefromdisk")
790 .setCancelButton(1)
791 .setDefaultButton(2)
792 .showDialog()
793 .getValue();
794
795 if(result == 2)
796 {
797 data.remove(currentPhoto);
798 if (currentPhoto >= data.size()) {
799 currentPhoto = data.size() - 1;
800 }
801 if (currentPhoto >= 0) {
802 ImageViewerDialog.showImage(this, data.get(currentPhoto));
803 } else {
804 ImageViewerDialog.showImage(this, null);
805 }
806
807 if (toDelete.getFile().delete()) {
808 Main.info("File "+toDelete.getFile().toString()+" deleted. ");
809 } else {
810 JOptionPane.showMessageDialog(
811 Main.parent,
812 tr("Image file could not be deleted."),
813 tr("Error"),
814 JOptionPane.ERROR_MESSAGE
815 );
816 }
817
818 updateOffscreenBuffer = true;
819 Main.map.repaint();
820 }
821 }
822 }
823
824 public void copyCurrentPhotoPath() {
825 ImageEntry toCopy = null;
826 if (data != null && !data.isEmpty() && currentPhoto >= 0 && currentPhoto < data.size()) {
827 toCopy = data.get(currentPhoto);
828 String copyString = toCopy.getFile().toString();
829 Utils.copyToClipboard(copyString);
830 }
831 }
832
833 /**
834 * Removes a photo from the list of images by index.
835 * @param idx Image index
836 * @since 6392
837 */
838 public void removePhotoByIdx(int idx) {
839 if (idx >= 0 && data != null && idx < data.size()) {
840 data.remove(idx);
841 }
842 }
843
844 /**
845 * Returns the image that matches the position of the mouse event.
846 * @param evt Mouse event
847 * @return Image at mouse position, or {@code null} if there is no image at the mouse position
848 * @since 6392
849 */
850 public ImageEntry getPhotoUnderMouse(MouseEvent evt) {
851 if (data != null) {
852 for (int idx = data.size() - 1; idx >= 0; --idx) {
853 ImageEntry img = data.get(idx);
854 if (img.getPos() == null) {
855 continue;
856 }
857 Point p = Main.map.mapView.getPoint(img.getPos());
858 Rectangle r;
859 if (useThumbs && img.thumbnail != null) {
860 Dimension d = scaledDimension(img.thumbnail);
861 r = new Rectangle(p.x - d.width / 2, p.y - d.height / 2, d.width, d.height);
862 } else {
863 r = new Rectangle(p.x - icon.getIconWidth() / 2,
864 p.y - icon.getIconHeight() / 2,
865 icon.getIconWidth(),
866 icon.getIconHeight());
867 }
868 if (r.contains(evt.getPoint())) {
869 return img;
870 }
871 }
872 }
873 return null;
874 }
875
876 /**
877 * Clears the currentPhoto, i.e. remove select marker, and optionally repaint.
878 * @param repaint Repaint flag
879 * @since 6392
880 */
881 public void clearCurrentPhoto(boolean repaint) {
882 currentPhoto = -1;
883 if (repaint) {
884 updateBufferAndRepaint();
885 }
886 }
887
888 /**
889 * Clears the currentPhoto of the other GeoImageLayer's. Otherwise there could be multiple selected photos.
890 */
891 private void clearOtherCurrentPhotos() {
892 for (GeoImageLayer layer:
893 Main.map.mapView.getLayersOfType(GeoImageLayer.class)) {
894 if (layer != this) {
895 layer.clearCurrentPhoto(false);
896 }
897 }
898 }
899
900 private static volatile List<MapMode> supportedMapModes = null;
901
902 /**
903 * Registers a map mode for which the functionality of this layer should be available.
904 * @param mapMode Map mode to be registered
905 * @since 6392
906 */
907 public static void registerSupportedMapMode(MapMode mapMode) {
908 if (supportedMapModes == null) {
909 supportedMapModes = new ArrayList<>();
910 }
911 supportedMapModes.add(mapMode);
912 }
913
914 /**
915 * Determines if the functionality of this layer is available in
916 * the specified map mode. {@link SelectAction} and {@link LassoModeAction} are supported by default,
917 * other map modes can be registered.
918 * @param mapMode Map mode to be checked
919 * @return {@code true} if the map mode is supported,
920 * {@code false} otherwise
921 */
922 private static final boolean isSupportedMapMode(MapMode mapMode) {
923 if (mapMode instanceof SelectAction || mapMode instanceof LassoModeAction) {
924 return true;
925 }
926 if (supportedMapModes != null) {
927 for (MapMode supmmode: supportedMapModes) {
928 if (mapMode == supmmode) {
929 return true;
930 }
931 }
932 }
933 return false;
934 }
935
936 private MouseAdapter mouseAdapter = null;
937 private MapModeChangeListener mapModeListener = null;
938
939 @Override
940 public void hookUpMapView() {
941 mouseAdapter = new MouseAdapter() {
942 private final boolean isMapModeOk() {
943 return Main.map.mapMode == null || isSupportedMapMode(Main.map.mapMode);
944 }
945 @Override public void mousePressed(MouseEvent e) {
946
947 if (e.getButton() != MouseEvent.BUTTON1)
948 return;
949 if (isVisible() && isMapModeOk()) {
950 Main.map.mapView.repaint();
951 }
952 }
953
954 @Override public void mouseReleased(MouseEvent ev) {
955 if (ev.getButton() != MouseEvent.BUTTON1)
956 return;
957 if (data == null || !isVisible() || !isMapModeOk())
958 return;
959
960 for (int i = data.size() - 1; i >= 0; --i) {
961 ImageEntry e = data.get(i);
962 if (e.getPos() == null) {
963 continue;
964 }
965 Point p = Main.map.mapView.getPoint(e.getPos());
966 Rectangle r;
967 if (useThumbs && e.thumbnail != null) {
968 Dimension d = scaledDimension(e.thumbnail);
969 r = new Rectangle(p.x - d.width / 2, p.y - d.height / 2, d.width, d.height);
970 } else {
971 r = new Rectangle(p.x - icon.getIconWidth() / 2,
972 p.y - icon.getIconHeight() / 2,
973 icon.getIconWidth(),
974 icon.getIconHeight());
975 }
976 if (r.contains(ev.getPoint())) {
977 clearOtherCurrentPhotos();
978 currentPhoto = i;
979 ImageViewerDialog.showImage(GeoImageLayer.this, e);
980 Main.map.repaint();
981 break;
982 }
983 }
984 }
985 };
986
987 mapModeListener = new MapModeChangeListener() {
988 @Override
989 public void mapModeChange(MapMode oldMapMode, MapMode newMapMode) {
990 if (newMapMode == null || isSupportedMapMode(newMapMode)) {
991 Main.map.mapView.addMouseListener(mouseAdapter);
992 } else {
993 Main.map.mapView.removeMouseListener(mouseAdapter);
994 }
995 }
996 };
997
998 MapFrame.addMapModeChangeListener(mapModeListener);
999 mapModeListener.mapModeChange(null, Main.map.mapMode);
1000
1001 MapView.addLayerChangeListener(new LayerChangeListener() {
1002 @Override
1003 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
1004 if (newLayer == GeoImageLayer.this) {
1005 // only in select mode it is possible to click the images
1006 Main.map.selectSelectTool(false);
1007 }
1008 }
1009
1010 @Override
1011 public void layerAdded(Layer newLayer) {
1012 }
1013
1014 @Override
1015 public void layerRemoved(Layer oldLayer) {
1016 if (oldLayer == GeoImageLayer.this) {
1017 stopLoadThumbs();
1018 Main.map.mapView.removeMouseListener(mouseAdapter);
1019 MapFrame.removeMapModeChangeListener(mapModeListener);
1020 currentPhoto = -1;
1021 data.clear();
1022 data = null;
1023 // stop listening to layer change events
1024 MapView.removeLayerChangeListener(this);
1025 }
1026 }
1027 });
1028
1029 Main.map.mapView.addPropertyChangeListener(this);
1030 if (Main.map.getToggleDialog(ImageViewerDialog.class) == null) {
1031 ImageViewerDialog.newInstance();
1032 Main.map.addToggleDialog(ImageViewerDialog.getInstance());
1033 }
1034 }
1035
1036 @Override
1037 public void propertyChange(PropertyChangeEvent evt) {
1038 if (NavigatableComponent.PROPNAME_CENTER.equals(evt.getPropertyName()) || NavigatableComponent.PROPNAME_SCALE.equals(evt.getPropertyName())) {
1039 updateOffscreenBuffer = true;
1040 }
1041 }
1042
1043 /**
1044 * Start to load thumbnails.
1045 */
1046 public synchronized void startLoadThumbs() {
1047 if (useThumbs && !thumbsLoaded && !thumbsLoaderRunning) {
1048 stopLoadThumbs();
1049 thumbsloader = new ThumbsLoader(this);
1050 thumbsLoaderExecutor.submit(thumbsloader);
1051 thumbsLoaderRunning = true;
1052 }
1053 }
1054
1055 /**
1056 * Stop to load thumbnails.
1057 *
1058 * Can be called at any time to make sure that the
1059 * thumbnail loader is stopped.
1060 */
1061 public synchronized void stopLoadThumbs() {
1062 if (thumbsloader != null) {
1063 thumbsloader.stop = true;
1064 }
1065 thumbsLoaderRunning = false;
1066 }
1067
1068 /**
1069 * Called to signal that the loading of thumbnails has finished.
1070 *
1071 * Usually called from {@link ThumbsLoader} in another thread.
1072 */
1073 public void thumbsLoaded() {
1074 thumbsLoaded = true;
1075 }
1076
1077 public void updateBufferAndRepaint() {
1078 updateOffscreenBuffer = true;
1079 Main.map.mapView.repaint();
1080 }
1081
1082 /**
1083 * Get list of images in layer.
1084 * @return List of images in layer
1085 */
1086 public List<ImageEntry> getImages() {
1087 List<ImageEntry> copy = new ArrayList<>(data.size());
1088 for (ImageEntry ie : data) {
1089 copy.add(ie);
1090 }
1091 return copy;
1092 }
1093
1094 /**
1095 * Returns the associated GPX layer.
1096 * @return The associated GPX layer
1097 */
1098 public GpxLayer getGpxLayer() {
1099 return gpxLayer;
1100 }
1101
1102 @Override
1103 public void jumpToNextMarker() {
1104 showNextPhoto();
1105 }
1106
1107 @Override
1108 public void jumpToPreviousMarker() {
1109 showPreviousPhoto();
1110 }
1111
1112 /**
1113 * Returns the current thumbnail display status.
1114 * {@code true}: thumbnails are displayed, {@code false}: an icon is displayed instead of thumbnails.
1115 * @return Current thumbnail display status
1116 * @since 6392
1117 */
1118 public boolean isUseThumbs() {
1119 return useThumbs;
1120 }
1121
1122 /**
1123 * Enables or disables the display of thumbnails. Does not update the display.
1124 * @param useThumbs New thumbnail display status
1125 * @since 6392
1126 */
1127 public void setUseThumbs(boolean useThumbs) {
1128 this.useThumbs = useThumbs;
1129 if (useThumbs && !thumbsLoaded) {
1130 startLoadThumbs();
1131 } else if (!useThumbs) {
1132 stopLoadThumbs();
1133 }
1134 }
1135}
Note: See TracBrowser for help on using the repository browser.