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

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

remove duplicated class JpegFileFilter

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