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

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

fix #11756 - NPEs

  • Property svn:eol-style set to native
File size: 39.9 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 != null && !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 if (data != null) {
320 Collections.sort(data);
321 }
322 this.data = data;
323 this.gpxLayer = gpxLayer;
324 this.useThumbs = useThumbs;
325 }
326
327 @Override
328 public Icon getIcon() {
329 return ImageProvider.get("dialogs/geoimage");
330 }
331
332 private static List<Action> menuAdditions = new LinkedList<>();
333
334 public static void registerMenuAddition(Action addition) {
335 menuAdditions.add(addition);
336 }
337
338 @Override
339 public Action[] getMenuEntries() {
340
341 List<Action> entries = new ArrayList<>();
342 entries.add(LayerListDialog.getInstance().createShowHideLayerAction());
343 entries.add(LayerListDialog.getInstance().createDeleteLayerAction());
344 entries.add(new RenameLayerAction(null, this));
345 entries.add(SeparatorLayerAction.INSTANCE);
346 entries.add(new CorrelateGpxWithImages(this));
347 entries.add(new ShowThumbnailAction(this));
348 if (!menuAdditions.isEmpty()) {
349 entries.add(SeparatorLayerAction.INSTANCE);
350 entries.addAll(menuAdditions);
351 }
352 entries.add(SeparatorLayerAction.INSTANCE);
353 entries.add(new JumpToNextMarker(this));
354 entries.add(new JumpToPreviousMarker(this));
355 entries.add(SeparatorLayerAction.INSTANCE);
356 entries.add(new LayerListPopup.InfoAction(this));
357
358 return entries.toArray(new Action[entries.size()]);
359
360 }
361
362 /**
363 * Prepare the string that is displayed if layer information is requested.
364 * @return String with layer information
365 */
366 private String infoText() {
367 int tagged = 0;
368 int newdata = 0;
369 for (ImageEntry e : data) {
370 if (e.getPos() != null) {
371 tagged++;
372 }
373 if (e.hasNewGpsData()) {
374 newdata++;
375 }
376 }
377 return "<html>"
378 + trn("{0} image loaded.", "{0} images loaded.", data.size(), data.size())
379 + " " + trn("{0} was found to be GPS tagged.", "{0} were found to be GPS tagged.", tagged, tagged)
380 + (newdata > 0 ? "<br>" + trn("{0} has updated GPS data.", "{0} have updated GPS data.", newdata, newdata) : "")
381 + "</html>";
382 }
383
384 @Override public Object getInfoComponent() {
385 return infoText();
386 }
387
388 @Override
389 public String getToolTipText() {
390 return infoText();
391 }
392
393 @Override
394 public boolean isMergable(Layer other) {
395 return other instanceof GeoImageLayer;
396 }
397
398 @Override
399 public void mergeFrom(Layer from) {
400 GeoImageLayer l = (GeoImageLayer) from;
401
402 // Stop to load thumbnails on both layers. Thumbnail loading will continue the next time
403 // the layer is painted.
404 stopLoadThumbs();
405 l.stopLoadThumbs();
406
407 final ImageEntry selected = l.currentPhoto >= 0 ? l.data.get(l.currentPhoto) : null;
408
409 data.addAll(l.data);
410 Collections.sort(data);
411
412 // Supress the double photos.
413 if (data.size() > 1) {
414 ImageEntry cur;
415 ImageEntry prev = data.get(data.size() - 1);
416 for (int i = data.size() - 2; i >= 0; i--) {
417 cur = data.get(i);
418 if (cur.getFile().equals(prev.getFile())) {
419 data.remove(i);
420 } else {
421 prev = cur;
422 }
423 }
424 }
425
426 if (selected != null && !data.isEmpty()) {
427 GuiHelper.runInEDTAndWait(new Runnable() {
428 @Override
429 public void run() {
430 for (int i = 0; i < data.size(); i++) {
431 if (selected.equals(data.get(i))) {
432 currentPhoto = i;
433 ImageViewerDialog.showImage(GeoImageLayer.this, data.get(i));
434 break;
435 }
436 }
437 }
438 });
439 }
440
441 setName(l.getName());
442 thumbsLoaded &= l.thumbsLoaded;
443 }
444
445 private Dimension scaledDimension(Image thumb) {
446 final double d = Main.map.mapView.getDist100Pixel();
447 final double size = 10 /*meter*/; /* size of the photo on the map */
448 double s = size * 100 /*px*/ / d;
449
450 final double sMin = ThumbsLoader.minSize;
451 final double sMax = ThumbsLoader.maxSize;
452
453 if (s < sMin) {
454 s = sMin;
455 }
456 if (s > sMax) {
457 s = sMax;
458 }
459 final double f = s / sMax; /* scale factor */
460
461 if (thumb == null)
462 return null;
463
464 return new Dimension(
465 (int) Math.round(f * thumb.getWidth(null)),
466 (int) Math.round(f * thumb.getHeight(null)));
467 }
468
469 @Override
470 public void paint(Graphics2D g, MapView mv, Bounds bounds) {
471 int width = mv.getWidth();
472 int height = mv.getHeight();
473 Rectangle clip = g.getClipBounds();
474 if (useThumbs) {
475 if (!thumbsLoaded) {
476 startLoadThumbs();
477 }
478
479 if (null == offscreenBuffer || offscreenBuffer.getWidth() != width // reuse the old buffer if possible
480 || offscreenBuffer.getHeight() != height) {
481 offscreenBuffer = new BufferedImage(width, height,
482 BufferedImage.TYPE_INT_ARGB);
483 updateOffscreenBuffer = true;
484 }
485
486 if (updateOffscreenBuffer) {
487 Graphics2D tempG = offscreenBuffer.createGraphics();
488 tempG.setColor(new Color(0, 0, 0, 0));
489 Composite saveComp = tempG.getComposite();
490 tempG.setComposite(AlphaComposite.Clear); // remove the old images
491 tempG.fillRect(0, 0, width, height);
492 tempG.setComposite(saveComp);
493
494 for (ImageEntry e : data) {
495 if (e.getPos() == null) {
496 continue;
497 }
498 Point p = mv.getPoint(e.getPos());
499 if (e.thumbnail != null) {
500 Dimension d = scaledDimension(e.thumbnail);
501 Rectangle target = new Rectangle(p.x - d.width / 2, p.y - d.height / 2, d.width, d.height);
502 if (clip.intersects(target)) {
503 tempG.drawImage(e.thumbnail, target.x, target.y, target.width, target.height, null);
504 }
505 } else { // thumbnail not loaded yet
506 icon.paintIcon(mv, tempG,
507 p.x - icon.getIconWidth() / 2,
508 p.y - icon.getIconHeight() / 2);
509 }
510 }
511 updateOffscreenBuffer = false;
512 }
513 g.drawImage(offscreenBuffer, 0, 0, null);
514 } else {
515 for (ImageEntry e : data) {
516 if (e.getPos() == null) {
517 continue;
518 }
519 Point p = mv.getPoint(e.getPos());
520 icon.paintIcon(mv, g,
521 p.x - icon.getIconWidth() / 2,
522 p.y - icon.getIconHeight() / 2);
523 }
524 }
525
526 if (currentPhoto >= 0 && currentPhoto < data.size()) {
527 ImageEntry e = data.get(currentPhoto);
528
529 if (e.getPos() != null) {
530 Point p = mv.getPoint(e.getPos());
531
532 int imgWidth = 100;
533 int imgHeight = 100;
534 if (useThumbs && e.thumbnail != null) {
535 Dimension d = scaledDimension(e.thumbnail);
536 imgWidth = d.width;
537 imgHeight = d.height;
538 } else {
539 imgWidth = selectedIcon.getIconWidth();
540 imgHeight = selectedIcon.getIconHeight();
541 }
542
543 if (e.getExifImgDir() != null) {
544 // Multiplier must be larger than sqrt(2)/2=0.71.
545 double arrowlength = Math.max(25, Math.max(imgWidth, imgHeight) * 0.85);
546 double arrowwidth = arrowlength / 1.4;
547
548 double dir = e.getExifImgDir();
549 // Rotate 90 degrees CCW
550 double headdir = (dir < 90) ? dir + 270 : dir - 90;
551 double leftdir = (headdir < 90) ? headdir + 270 : headdir - 90;
552 double rightdir = (headdir > 270) ? headdir - 270 : headdir + 90;
553
554 double ptx = p.x + Math.cos(Math.toRadians(headdir)) * arrowlength;
555 double pty = p.y + Math.sin(Math.toRadians(headdir)) * arrowlength;
556
557 double ltx = p.x + Math.cos(Math.toRadians(leftdir)) * arrowwidth/2;
558 double lty = p.y + Math.sin(Math.toRadians(leftdir)) * arrowwidth/2;
559
560 double rtx = p.x + Math.cos(Math.toRadians(rightdir)) * arrowwidth/2;
561 double rty = p.y + Math.sin(Math.toRadians(rightdir)) * arrowwidth/2;
562
563 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
564 g.setColor(new Color(255, 255, 255, 192));
565 int[] xar = {(int) ltx, (int) ptx, (int) rtx, (int) ltx};
566 int[] yar = {(int) lty, (int) pty, (int) rty, (int) lty};
567 g.fillPolygon(xar, yar, 4);
568 g.setColor(Color.black);
569 g.setStroke(new BasicStroke(1.2f));
570 g.drawPolyline(xar, yar, 3);
571 }
572
573 if (useThumbs && e.thumbnail != null) {
574 g.setColor(new Color(128, 0, 0, 122));
575 g.fillRect(p.x - imgWidth / 2, p.y - imgHeight / 2, imgWidth, imgHeight);
576 } else {
577 selectedIcon.paintIcon(mv, g,
578 p.x - imgWidth / 2,
579 p.y - imgHeight / 2);
580
581 }
582 }
583 }
584 }
585
586 @Override
587 public void visitBoundingBox(BoundingXYVisitor v) {
588 for (ImageEntry e : data) {
589 v.visit(e.getPos());
590 }
591 }
592
593 /**
594 * Extract GPS metadata from image EXIF
595 *
596 * If successful, fills in the LatLon and EastNorth attributes of passed in image
597 */
598 private static void extractExif(ImageEntry e) {
599
600 Metadata metadata;
601 Directory dirExif;
602 GpsDirectory dirGps;
603
604 try {
605 metadata = JpegMetadataReader.readMetadata(e.getFile());
606 dirExif = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
607 dirGps = metadata.getFirstDirectoryOfType(GpsDirectory.class);
608 } catch (CompoundException | IOException p) {
609 e.setExifCoor(null);
610 e.setPos(null);
611 return;
612 }
613
614 try {
615 if (dirExif != null) {
616 int orientation = dirExif.getInt(ExifIFD0Directory.TAG_ORIENTATION);
617 e.setExifOrientation(orientation);
618 }
619 } catch (MetadataException ex) {
620 Main.debug(ex.getMessage());
621 }
622
623 if (dirGps == null) {
624 e.setExifCoor(null);
625 e.setPos(null);
626 return;
627 }
628
629 try {
630 double speed = dirGps.getDouble(GpsDirectory.TAG_SPEED);
631 String speedRef = dirGps.getString(GpsDirectory.TAG_SPEED_REF);
632 if ("M".equalsIgnoreCase(speedRef)) {
633 // miles per hour
634 speed *= 1.609344;
635 } else if ("N".equalsIgnoreCase(speedRef)) {
636 // knots == nautical miles per hour
637 speed *= 1.852;
638 }
639 // default is K (km/h)
640 e.setSpeed(speed);
641 } catch (Exception ex) {
642 Main.debug(ex.getMessage());
643 }
644
645 try {
646 double ele = dirGps.getDouble(GpsDirectory.TAG_ALTITUDE);
647 int d = dirGps.getInt(GpsDirectory.TAG_ALTITUDE_REF);
648 if (d == 1) {
649 ele *= -1;
650 }
651 e.setElevation(ele);
652 } catch (MetadataException ex) {
653 Main.debug(ex.getMessage());
654 }
655
656 try {
657 LatLon latlon = ExifReader.readLatLon(dirGps);
658 e.setExifCoor(latlon);
659 e.setPos(e.getExifCoor());
660
661 } catch (Exception ex) { // (other exceptions, e.g. #5271)
662 Main.error("Error reading EXIF from file: "+ex);
663 e.setExifCoor(null);
664 e.setPos(null);
665 }
666
667 try {
668 Double direction = ExifReader.readDirection(dirGps);
669 if (direction != null) {
670 e.setExifImgDir(direction.doubleValue());
671 }
672 } catch (Exception ex) { // (CompoundException and other exceptions, e.g. #5271)
673 Main.debug(ex.getMessage());
674 }
675
676 // Time and date. We can have these cases:
677 // 1) GPS_TIME_STAMP not set -> date/time will be null
678 // 2) GPS_DATE_STAMP not set -> use EXIF date or set to default
679 // 3) GPS_TIME_STAMP and GPS_DATE_STAMP are set
680 int[] timeStampComps = dirGps.getIntArray(GpsDirectory.TAG_TIME_STAMP);
681 if (timeStampComps != null) {
682 int gpsHour = timeStampComps[0];
683 int gpsMin = timeStampComps[1];
684 int gpsSec = timeStampComps[2];
685 Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
686
687 // We have the time. Next step is to check if the GPS date stamp is set.
688 // dirGps.getString() always succeeds, but the return value might be null.
689 String dateStampStr = dirGps.getString(GpsDirectory.TAG_DATE_STAMP);
690 if (dateStampStr != null && dateStampStr.matches("^\\d+:\\d+:\\d+$")) {
691 String[] dateStampComps = dateStampStr.split(":");
692 cal.set(Calendar.YEAR, Integer.parseInt(dateStampComps[0]));
693 cal.set(Calendar.MONTH, Integer.parseInt(dateStampComps[1]) - 1);
694 cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateStampComps[2]));
695 } else {
696 // No GPS date stamp in EXIF data. Copy it from EXIF time.
697 // Date is not set if EXIF time is not available.
698 if (e.hasExifTime()) {
699 // Time not set yet, so we can copy everything, not just date.
700 cal.setTime(e.getExifTime());
701 }
702 }
703
704 cal.set(Calendar.HOUR_OF_DAY, gpsHour);
705 cal.set(Calendar.MINUTE, gpsMin);
706 cal.set(Calendar.SECOND, gpsSec);
707
708 e.setExifGpsTime(cal.getTime());
709 }
710 }
711
712 public void showNextPhoto() {
713 if (data != null && !data.isEmpty()) {
714 currentPhoto++;
715 if (currentPhoto >= data.size()) {
716 currentPhoto = data.size() - 1;
717 }
718 ImageViewerDialog.showImage(this, data.get(currentPhoto));
719 } else {
720 currentPhoto = -1;
721 }
722 Main.map.repaint();
723 }
724
725 public void showPreviousPhoto() {
726 if (data != null && !data.isEmpty()) {
727 currentPhoto--;
728 if (currentPhoto < 0) {
729 currentPhoto = 0;
730 }
731 ImageViewerDialog.showImage(this, data.get(currentPhoto));
732 } else {
733 currentPhoto = -1;
734 }
735 Main.map.repaint();
736 }
737
738 public void showFirstPhoto() {
739 if (data != null && !data.isEmpty()) {
740 currentPhoto = 0;
741 ImageViewerDialog.showImage(this, data.get(currentPhoto));
742 } else {
743 currentPhoto = -1;
744 }
745 Main.map.repaint();
746 }
747
748 public void showLastPhoto() {
749 if (data != null && !data.isEmpty()) {
750 currentPhoto = data.size() - 1;
751 ImageViewerDialog.showImage(this, data.get(currentPhoto));
752 } else {
753 currentPhoto = -1;
754 }
755 Main.map.repaint();
756 }
757
758 public void checkPreviousNextButtons() {
759 ImageViewerDialog.setNextEnabled(data != null && currentPhoto < data.size() - 1);
760 ImageViewerDialog.setPreviousEnabled(currentPhoto > 0);
761 }
762
763 public void removeCurrentPhoto() {
764 if (data != null && !data.isEmpty() && currentPhoto >= 0 && currentPhoto < data.size()) {
765 data.remove(currentPhoto);
766 if (currentPhoto >= data.size()) {
767 currentPhoto = data.size() - 1;
768 }
769 if (currentPhoto >= 0) {
770 ImageViewerDialog.showImage(this, data.get(currentPhoto));
771 } else {
772 ImageViewerDialog.showImage(this, null);
773 }
774 updateOffscreenBuffer = true;
775 Main.map.repaint();
776 }
777 }
778
779 public void removeCurrentPhotoFromDisk() {
780 ImageEntry toDelete = null;
781 if (data != null && !data.isEmpty() && currentPhoto >= 0 && currentPhoto < data.size()) {
782 toDelete = data.get(currentPhoto);
783
784 int result = new ExtendedDialog(
785 Main.parent,
786 tr("Delete image file from disk"),
787 new String[] {tr("Cancel"), tr("Delete")})
788 .setButtonIcons(new String[] {"cancel", "dialogs/delete"})
789 .setContent(new JLabel(tr("<html><h3>Delete the file {0} from disk?<p>The image file will be permanently lost!</h3></html>",
790 toDelete.getFile().getName()), ImageProvider.get("dialogs/geoimage/deletefromdisk"), SwingConstants.LEFT))
791 .toggleEnable("geoimage.deleteimagefromdisk")
792 .setCancelButton(1)
793 .setDefaultButton(2)
794 .showDialog()
795 .getValue();
796
797 if (result == 2) {
798 data.remove(currentPhoto);
799 if (currentPhoto >= data.size()) {
800 currentPhoto = data.size() - 1;
801 }
802 if (currentPhoto >= 0) {
803 ImageViewerDialog.showImage(this, data.get(currentPhoto));
804 } else {
805 ImageViewerDialog.showImage(this, null);
806 }
807
808 if (toDelete.getFile().delete()) {
809 Main.info("File "+toDelete.getFile()+" deleted. ");
810 } else {
811 JOptionPane.showMessageDialog(
812 Main.parent,
813 tr("Image file could not be deleted."),
814 tr("Error"),
815 JOptionPane.ERROR_MESSAGE
816 );
817 }
818
819 updateOffscreenBuffer = true;
820 Main.map.repaint();
821 }
822 }
823 }
824
825 public void copyCurrentPhotoPath() {
826 ImageEntry toCopy = null;
827 if (data != null && !data.isEmpty() && currentPhoto >= 0 && currentPhoto < data.size()) {
828 toCopy = data.get(currentPhoto);
829 String copyString = toCopy.getFile().toString();
830 Utils.copyToClipboard(copyString);
831 }
832 }
833
834 /**
835 * Removes a photo from the list of images by index.
836 * @param idx Image index
837 * @since 6392
838 */
839 public void removePhotoByIdx(int idx) {
840 if (idx >= 0 && data != null && idx < data.size()) {
841 data.remove(idx);
842 }
843 }
844
845 /**
846 * Returns the image that matches the position of the mouse event.
847 * @param evt Mouse event
848 * @return Image at mouse position, or {@code null} if there is no image at the mouse position
849 * @since 6392
850 */
851 public ImageEntry getPhotoUnderMouse(MouseEvent evt) {
852 if (data != null) {
853 for (int idx = data.size() - 1; idx >= 0; --idx) {
854 ImageEntry img = data.get(idx);
855 if (img.getPos() == null) {
856 continue;
857 }
858 Point p = Main.map.mapView.getPoint(img.getPos());
859 Rectangle r;
860 if (useThumbs && img.thumbnail != null) {
861 Dimension d = scaledDimension(img.thumbnail);
862 r = new Rectangle(p.x - d.width / 2, p.y - d.height / 2, d.width, d.height);
863 } else {
864 r = new Rectangle(p.x - icon.getIconWidth() / 2,
865 p.y - icon.getIconHeight() / 2,
866 icon.getIconWidth(),
867 icon.getIconHeight());
868 }
869 if (r.contains(evt.getPoint())) {
870 return img;
871 }
872 }
873 }
874 return null;
875 }
876
877 /**
878 * Clears the currentPhoto, i.e. remove select marker, and optionally repaint.
879 * @param repaint Repaint flag
880 * @since 6392
881 */
882 public void clearCurrentPhoto(boolean repaint) {
883 currentPhoto = -1;
884 if (repaint) {
885 updateBufferAndRepaint();
886 }
887 }
888
889 /**
890 * Clears the currentPhoto of the other GeoImageLayer's. Otherwise there could be multiple selected photos.
891 */
892 private void clearOtherCurrentPhotos() {
893 for (GeoImageLayer layer:
894 Main.map.mapView.getLayersOfType(GeoImageLayer.class)) {
895 if (layer != this) {
896 layer.clearCurrentPhoto(false);
897 }
898 }
899 }
900
901 private static volatile List<MapMode> supportedMapModes = null;
902
903 /**
904 * Registers a map mode for which the functionality of this layer should be available.
905 * @param mapMode Map mode to be registered
906 * @since 6392
907 */
908 public static void registerSupportedMapMode(MapMode mapMode) {
909 if (supportedMapModes == null) {
910 supportedMapModes = new ArrayList<>();
911 }
912 supportedMapModes.add(mapMode);
913 }
914
915 /**
916 * Determines if the functionality of this layer is available in
917 * the specified map mode. {@link SelectAction} and {@link LassoModeAction} are supported by default,
918 * other map modes can be registered.
919 * @param mapMode Map mode to be checked
920 * @return {@code true} if the map mode is supported,
921 * {@code false} otherwise
922 */
923 private static boolean isSupportedMapMode(MapMode mapMode) {
924 if (mapMode instanceof SelectAction || mapMode instanceof LassoModeAction) {
925 return true;
926 }
927 if (supportedMapModes != null) {
928 for (MapMode supmmode: supportedMapModes) {
929 if (mapMode == supmmode) {
930 return true;
931 }
932 }
933 }
934 return false;
935 }
936
937 private MouseAdapter mouseAdapter = null;
938 private MapModeChangeListener mapModeListener = null;
939
940 @Override
941 public void hookUpMapView() {
942 mouseAdapter = new MouseAdapter() {
943 private boolean isMapModeOk() {
944 return Main.map.mapMode == null || isSupportedMapMode(Main.map.mapMode);
945 }
946
947 @Override
948 public void mousePressed(MouseEvent e) {
949 if (e.getButton() != MouseEvent.BUTTON1)
950 return;
951 if (isVisible() && isMapModeOk()) {
952 Main.map.mapView.repaint();
953 }
954 }
955
956 @Override
957 public void mouseReleased(MouseEvent ev) {
958 if (ev.getButton() != MouseEvent.BUTTON1)
959 return;
960 if (data == null || !isVisible() || !isMapModeOk())
961 return;
962
963 for (int i = data.size() - 1; i >= 0; --i) {
964 ImageEntry e = data.get(i);
965 if (e.getPos() == null) {
966 continue;
967 }
968 Point p = Main.map.mapView.getPoint(e.getPos());
969 Rectangle r;
970 if (useThumbs && e.thumbnail != null) {
971 Dimension d = scaledDimension(e.thumbnail);
972 r = new Rectangle(p.x - d.width / 2, p.y - d.height / 2, d.width, d.height);
973 } else {
974 r = new Rectangle(p.x - icon.getIconWidth() / 2,
975 p.y - icon.getIconHeight() / 2,
976 icon.getIconWidth(),
977 icon.getIconHeight());
978 }
979 if (r.contains(ev.getPoint())) {
980 clearOtherCurrentPhotos();
981 currentPhoto = i;
982 ImageViewerDialog.showImage(GeoImageLayer.this, e);
983 Main.map.repaint();
984 break;
985 }
986 }
987 }
988 };
989
990 mapModeListener = new MapModeChangeListener() {
991 @Override
992 public void mapModeChange(MapMode oldMapMode, MapMode newMapMode) {
993 if (newMapMode == null || isSupportedMapMode(newMapMode)) {
994 Main.map.mapView.addMouseListener(mouseAdapter);
995 } else {
996 Main.map.mapView.removeMouseListener(mouseAdapter);
997 }
998 }
999 };
1000
1001 MapFrame.addMapModeChangeListener(mapModeListener);
1002 mapModeListener.mapModeChange(null, Main.map.mapMode);
1003
1004 MapView.addLayerChangeListener(new LayerChangeListener() {
1005 @Override
1006 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
1007 if (newLayer == GeoImageLayer.this) {
1008 // only in select mode it is possible to click the images
1009 Main.map.selectSelectTool(false);
1010 }
1011 }
1012
1013 @Override
1014 public void layerAdded(Layer newLayer) {
1015 }
1016
1017 @Override
1018 public void layerRemoved(Layer oldLayer) {
1019 if (oldLayer == GeoImageLayer.this) {
1020 stopLoadThumbs();
1021 Main.map.mapView.removeMouseListener(mouseAdapter);
1022 MapFrame.removeMapModeChangeListener(mapModeListener);
1023 currentPhoto = -1;
1024 data.clear();
1025 data = null;
1026 // stop listening to layer change events
1027 MapView.removeLayerChangeListener(this);
1028 }
1029 }
1030 });
1031
1032 Main.map.mapView.addPropertyChangeListener(this);
1033 if (Main.map.getToggleDialog(ImageViewerDialog.class) == null) {
1034 ImageViewerDialog.newInstance();
1035 Main.map.addToggleDialog(ImageViewerDialog.getInstance());
1036 }
1037 }
1038
1039 @Override
1040 public void propertyChange(PropertyChangeEvent evt) {
1041 if (NavigatableComponent.PROPNAME_CENTER.equals(evt.getPropertyName()) ||
1042 NavigatableComponent.PROPNAME_SCALE.equals(evt.getPropertyName())) {
1043 updateOffscreenBuffer = true;
1044 }
1045 }
1046
1047 /**
1048 * Start to load thumbnails.
1049 */
1050 public synchronized void startLoadThumbs() {
1051 if (useThumbs && !thumbsLoaded && !thumbsLoaderRunning) {
1052 stopLoadThumbs();
1053 thumbsloader = new ThumbsLoader(this);
1054 thumbsLoaderExecutor.submit(thumbsloader);
1055 thumbsLoaderRunning = true;
1056 }
1057 }
1058
1059 /**
1060 * Stop to load thumbnails.
1061 *
1062 * Can be called at any time to make sure that the
1063 * thumbnail loader is stopped.
1064 */
1065 public synchronized void stopLoadThumbs() {
1066 if (thumbsloader != null) {
1067 thumbsloader.stop = true;
1068 }
1069 thumbsLoaderRunning = false;
1070 }
1071
1072 /**
1073 * Called to signal that the loading of thumbnails has finished.
1074 *
1075 * Usually called from {@link ThumbsLoader} in another thread.
1076 */
1077 public void thumbsLoaded() {
1078 thumbsLoaded = true;
1079 }
1080
1081 public void updateBufferAndRepaint() {
1082 updateOffscreenBuffer = true;
1083 Main.map.mapView.repaint();
1084 }
1085
1086 /**
1087 * Get list of images in layer.
1088 * @return List of images in layer
1089 */
1090 public List<ImageEntry> getImages() {
1091 if (data == null) {
1092 return Collections.emptyList();
1093 }
1094 List<ImageEntry> copy = new ArrayList<>(data.size());
1095 for (ImageEntry ie : data) {
1096 copy.add(ie);
1097 }
1098 return copy;
1099 }
1100
1101 /**
1102 * Returns the associated GPX layer.
1103 * @return The associated GPX layer
1104 */
1105 public GpxLayer getGpxLayer() {
1106 return gpxLayer;
1107 }
1108
1109 @Override
1110 public void jumpToNextMarker() {
1111 showNextPhoto();
1112 }
1113
1114 @Override
1115 public void jumpToPreviousMarker() {
1116 showPreviousPhoto();
1117 }
1118
1119 /**
1120 * Returns the current thumbnail display status.
1121 * {@code true}: thumbnails are displayed, {@code false}: an icon is displayed instead of thumbnails.
1122 * @return Current thumbnail display status
1123 * @since 6392
1124 */
1125 public boolean isUseThumbs() {
1126 return useThumbs;
1127 }
1128
1129 /**
1130 * Enables or disables the display of thumbnails. Does not update the display.
1131 * @param useThumbs New thumbnail display status
1132 * @since 6392
1133 */
1134 public void setUseThumbs(boolean useThumbs) {
1135 this.useThumbs = useThumbs;
1136 if (useThumbs && !thumbsLoaded) {
1137 startLoadThumbs();
1138 } else if (!useThumbs) {
1139 stopLoadThumbs();
1140 }
1141 }
1142}
Note: See TracBrowser for help on using the repository browser.