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

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

fix copyright/license headers globally

  • 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.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 ("M".equalsIgnoreCase(speedRef)) {
629 // miles per hour
630 speed *= 1.609344;
631 } else if ("N".equalsIgnoreCase(speedRef)) {
632 // knots == nautical miles per hour
633 speed *= 1.852;
634 }
635 // default is K (km/h)
636 e.setSpeed(speed);
637 } catch (Exception ex) {
638 Main.debug(ex.getMessage());
639 }
640
641 try {
642 double ele = dirGps.getDouble(GpsDirectory.TAG_ALTITUDE);
643 int d = dirGps.getInt(GpsDirectory.TAG_ALTITUDE_REF);
644 if (d == 1) {
645 ele *= -1;
646 }
647 e.setElevation(ele);
648 } catch (MetadataException ex) {
649 Main.debug(ex.getMessage());
650 }
651
652 try {
653 LatLon latlon = ExifReader.readLatLon(dirGps);
654 e.setExifCoor(latlon);
655 e.setPos(e.getExifCoor());
656
657 } catch (Exception ex) { // (other exceptions, e.g. #5271)
658 Main.error("Error reading EXIF from file: "+ex);
659 e.setExifCoor(null);
660 e.setPos(null);
661 }
662
663 try {
664 Double direction = ExifReader.readDirection(dirGps);
665 if (direction != null) {
666 e.setExifImgDir(direction.doubleValue());
667 }
668 } catch (Exception ex) { // (CompoundException and other exceptions, e.g. #5271)
669 Main.debug(ex.getMessage());
670 }
671
672 // Time and date. We can have these cases:
673 // 1) GPS_TIME_STAMP not set -> date/time will be null
674 // 2) GPS_DATE_STAMP not set -> use EXIF date or set to default
675 // 3) GPS_TIME_STAMP and GPS_DATE_STAMP are set
676 int[] timeStampComps = dirGps.getIntArray(GpsDirectory.TAG_TIME_STAMP);
677 if (timeStampComps != null) {
678 int gpsHour = timeStampComps[0];
679 int gpsMin = timeStampComps[1];
680 int gpsSec = timeStampComps[2];
681 Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
682
683 // We have the time. Next step is to check if the GPS date stamp is set.
684 // dirGps.getString() always succeeds, but the return value might be null.
685 String dateStampStr = dirGps.getString(GpsDirectory.TAG_DATE_STAMP);
686 if (dateStampStr != null && dateStampStr.matches("^\\d+:\\d+:\\d+$")) {
687 String[] dateStampComps = dateStampStr.split(":");
688 cal.set(Calendar.YEAR, Integer.parseInt(dateStampComps[0]));
689 cal.set(Calendar.MONTH, Integer.parseInt(dateStampComps[1]) - 1);
690 cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateStampComps[2]));
691 } else {
692 // No GPS date stamp in EXIF data. Copy it from EXIF time.
693 // Date is not set if EXIF time is not available.
694 if (e.hasExifTime()) {
695 // Time not set yet, so we can copy everything, not just date.
696 cal.setTime(e.getExifTime());
697 }
698 }
699
700 cal.set(Calendar.HOUR_OF_DAY, gpsHour);
701 cal.set(Calendar.MINUTE, gpsMin);
702 cal.set(Calendar.SECOND, gpsSec);
703
704 e.setExifGpsTime(cal.getTime());
705 }
706 }
707
708 public void showNextPhoto() {
709 if (data != null && !data.isEmpty()) {
710 currentPhoto++;
711 if (currentPhoto >= data.size()) {
712 currentPhoto = data.size() - 1;
713 }
714 ImageViewerDialog.showImage(this, data.get(currentPhoto));
715 } else {
716 currentPhoto = -1;
717 }
718 Main.map.repaint();
719 }
720
721 public void showPreviousPhoto() {
722 if (data != null && !data.isEmpty()) {
723 currentPhoto--;
724 if (currentPhoto < 0) {
725 currentPhoto = 0;
726 }
727 ImageViewerDialog.showImage(this, data.get(currentPhoto));
728 } else {
729 currentPhoto = -1;
730 }
731 Main.map.repaint();
732 }
733
734 public void showFirstPhoto() {
735 if (data != null && !data.isEmpty()) {
736 currentPhoto = 0;
737 ImageViewerDialog.showImage(this, data.get(currentPhoto));
738 } else {
739 currentPhoto = -1;
740 }
741 Main.map.repaint();
742 }
743
744 public void showLastPhoto() {
745 if (data != null && !data.isEmpty()) {
746 currentPhoto = data.size() - 1;
747 ImageViewerDialog.showImage(this, data.get(currentPhoto));
748 } else {
749 currentPhoto = -1;
750 }
751 Main.map.repaint();
752 }
753
754 public void checkPreviousNextButtons() {
755 ImageViewerDialog.setNextEnabled(currentPhoto < data.size() - 1);
756 ImageViewerDialog.setPreviousEnabled(currentPhoto > 0);
757 }
758
759 public void removeCurrentPhoto() {
760 if (data != null && !data.isEmpty() && currentPhoto >= 0 && currentPhoto < data.size()) {
761 data.remove(currentPhoto);
762 if (currentPhoto >= data.size()) {
763 currentPhoto = data.size() - 1;
764 }
765 if (currentPhoto >= 0) {
766 ImageViewerDialog.showImage(this, data.get(currentPhoto));
767 } else {
768 ImageViewerDialog.showImage(this, null);
769 }
770 updateOffscreenBuffer = true;
771 Main.map.repaint();
772 }
773 }
774
775 public void removeCurrentPhotoFromDisk() {
776 ImageEntry toDelete = null;
777 if (data != null && !data.isEmpty() && currentPhoto >= 0 && currentPhoto < data.size()) {
778 toDelete = data.get(currentPhoto);
779
780 int result = new ExtendedDialog(
781 Main.parent,
782 tr("Delete image file from disk"),
783 new String[] {tr("Cancel"), tr("Delete")})
784 .setButtonIcons(new String[] {"cancel", "dialogs/delete"})
785 .setContent(new JLabel(tr("<html><h3>Delete the file {0} from disk?<p>The image file will be permanently lost!</h3></html>"
786 ,toDelete.getFile().getName()), ImageProvider.get("dialogs/geoimage/deletefromdisk"),SwingConstants.LEFT))
787 .toggleEnable("geoimage.deleteimagefromdisk")
788 .setCancelButton(1)
789 .setDefaultButton(2)
790 .showDialog()
791 .getValue();
792
793 if(result == 2)
794 {
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.