source: josm/trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java@ 13220

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

see #15574:

  • additionally refactors ImageDisplay to use ImageEntry instead; stores width and height info while metadata of images are read; might break plugin code (patch by cmuelle8, minor changes)
  • remove double semicolon causing https://github.com/pmd/pmd/issues/785
  • enable PMD rule DoNotCallGarbageCollectionExplicitly
  • disable SpotBugs rule ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD
  • Property svn:eol-style set to native
File size: 48.6 KB
RevLine 
[8378]1// License: GPL. For details, see LICENSE file.
[2566]2package org.openstreetmap.josm.gui.layer.geoimage;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
[2732]5import static org.openstreetmap.josm.tools.I18n.trn;
[2566]6
7import java.awt.BorderLayout;
8import java.awt.Cursor;
9import java.awt.Dimension;
10import java.awt.FlowLayout;
[9660]11import java.awt.GraphicsEnvironment;
[2566]12import java.awt.GridBagConstraints;
13import java.awt.GridBagLayout;
14import java.awt.event.ActionEvent;
15import java.awt.event.ActionListener;
[3052]16import java.awt.event.FocusEvent;
17import java.awt.event.FocusListener;
[2662]18import java.awt.event.ItemEvent;
19import java.awt.event.ItemListener;
20import java.awt.event.WindowAdapter;
21import java.awt.event.WindowEvent;
[2566]22import java.io.File;
23import java.io.IOException;
24import java.io.InputStream;
[13204]25import java.nio.file.Files;
[7299]26import java.text.DateFormat;
[2566]27import java.text.ParseException;
28import java.text.SimpleDateFormat;
29import java.util.ArrayList;
30import java.util.Collection;
31import java.util.Collections;
[10647]32import java.util.Comparator;
[2566]33import java.util.Date;
[6223]34import java.util.Dictionary;
[4242]35import java.util.Hashtable;
[2566]36import java.util.List;
[11553]37import java.util.Optional;
[2566]38import java.util.TimeZone;
[11288]39import java.util.concurrent.TimeUnit;
[2566]40import java.util.zip.GZIPInputStream;
41
[3408]42import javax.swing.AbstractAction;
[2566]43import javax.swing.AbstractListModel;
[2662]44import javax.swing.BorderFactory;
[2566]45import javax.swing.JButton;
[2592]46import javax.swing.JCheckBox;
[2566]47import javax.swing.JFileChooser;
48import javax.swing.JLabel;
49import javax.swing.JList;
50import javax.swing.JOptionPane;
51import javax.swing.JPanel;
52import javax.swing.JScrollPane;
[2662]53import javax.swing.JSeparator;
[2566]54import javax.swing.JSlider;
55import javax.swing.ListSelectionModel;
[10176]56import javax.swing.MutableComboBoxModel;
[2662]57import javax.swing.SwingConstants;
[2566]58import javax.swing.event.ChangeEvent;
59import javax.swing.event.ChangeListener;
[2662]60import javax.swing.event.DocumentEvent;
61import javax.swing.event.DocumentListener;
[2566]62import javax.swing.filechooser.FileFilter;
63
64import org.openstreetmap.josm.Main;
[5438]65import org.openstreetmap.josm.actions.DiskAccessAction;
[7518]66import org.openstreetmap.josm.data.gpx.GpxConstants;
[2566]67import org.openstreetmap.josm.data.gpx.GpxData;
68import org.openstreetmap.josm.data.gpx.GpxTrack;
[2907]69import org.openstreetmap.josm.data.gpx.GpxTrackSegment;
[2566]70import org.openstreetmap.josm.data.gpx.WayPoint;
71import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
72import org.openstreetmap.josm.gui.ExtendedDialog;
[12630]73import org.openstreetmap.josm.gui.MainApplication;
[12671]74import org.openstreetmap.josm.gui.io.importexport.JpgImporter;
[2566]75import org.openstreetmap.josm.gui.layer.GpxLayer;
76import org.openstreetmap.josm.gui.layer.Layer;
[7578]77import org.openstreetmap.josm.gui.widgets.AbstractFileChooser;
[5429]78import org.openstreetmap.josm.gui.widgets.JosmComboBox;
[6223]79import org.openstreetmap.josm.gui.widgets.JosmTextField;
[2566]80import org.openstreetmap.josm.io.GpxReader;
[12846]81import org.openstreetmap.josm.spi.preferences.Config;
[2566]82import org.openstreetmap.josm.tools.GBC;
83import org.openstreetmap.josm.tools.ImageProvider;
[11746]84import org.openstreetmap.josm.tools.JosmRuntimeException;
[12620]85import org.openstreetmap.josm.tools.Logging;
[9726]86import org.openstreetmap.josm.tools.Pair;
[8404]87import org.openstreetmap.josm.tools.Utils;
[7299]88import org.openstreetmap.josm.tools.date.DateUtils;
[2566]89import org.xml.sax.SAXException;
90
[6643]91/**
[6296]92 * This class displays the window to select the GPX file and the offset (timezone + delta).
[2566]93 * Then it correlates the images of the layer with that GPX file.
94 */
[3408]95public class CorrelateGpxWithImages extends AbstractAction {
[2566]96
[7005]97 private static List<GpxData> loadedGpxData = new ArrayList<>();
[2566]98
[9078]99 private final transient GeoImageLayer yLayer;
[9752]100 private transient Timezone timezone;
101 private transient Offset delta;
[2676]102
[6792]103 /**
104 * Constructs a new {@code CorrelateGpxWithImages} action.
105 * @param layer The image layer
106 */
[2662]107 public CorrelateGpxWithImages(GeoImageLayer layer) {
[13130]108 super(tr("Correlate to GPX"));
109 new ImageProvider("dialogs/geoimage/gpx2img").getResource().attachImageIcon(this, true);
[2662]110 this.yLayer = layer;
[2566]111 }
112
[8509]113 private final class SyncDialogWindowListener extends WindowAdapter {
114 private static final int CANCEL = -1;
115 private static final int DONE = 0;
116 private static final int AGAIN = 1;
117 private static final int NOTHING = 2;
118
119 private int checkAndSave() {
120 if (syncDialog.isVisible())
121 // nothing happened: JOSM was minimized or similar
122 return NOTHING;
123 int answer = syncDialog.getValue();
[8510]124 if (answer != 1)
[8509]125 return CANCEL;
126
127 // Parse values again, to display an error if the format is not recognized
128 try {
[9741]129 timezone = Timezone.parseTimezone(tfTimezone.getText().trim());
[8509]130 } catch (ParseException e) {
131 JOptionPane.showMessageDialog(Main.parent, e.getMessage(),
132 tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE);
133 return AGAIN;
134 }
135
136 try {
[9741]137 delta = Offset.parseOffset(tfOffset.getText().trim());
[8509]138 } catch (ParseException e) {
139 JOptionPane.showMessageDialog(Main.parent, e.getMessage(),
140 tr("Invalid offset"), JOptionPane.ERROR_MESSAGE);
141 return AGAIN;
142 }
143
144 if (lastNumMatched == 0 && new ExtendedDialog(
145 Main.parent,
146 tr("Correlate images with GPX track"),
[12279]147 tr("OK"), tr("Try Again")).
[8509]148 setContent(tr("No images could be matched!")).
[12279]149 setButtonIcons("ok", "dialogs/refresh").
[8509]150 showDialog().getValue() == 2)
151 return AGAIN;
152 return DONE;
153 }
154
155 @Override
156 public void windowDeactivated(WindowEvent e) {
157 int result = checkAndSave();
158 switch (result) {
159 case NOTHING:
160 break;
161 case CANCEL:
162 if (yLayer != null) {
[8645]163 if (yLayer.data != null) {
164 for (ImageEntry ie : yLayer.data) {
[9270]165 ie.discardTmp();
[8645]166 }
[8509]167 }
168 yLayer.updateBufferAndRepaint();
169 }
170 break;
171 case AGAIN:
172 actionPerformed(null);
173 break;
174 case DONE:
[12846]175 Config.getPref().put("geoimage.timezone", timezone.formatTimezone());
176 Config.getPref().put("geoimage.delta", delta.formatOffset());
177 Config.getPref().putBoolean("geoimage.showThumbs", yLayer.useThumbs);
[8509]178
179 yLayer.useThumbs = cbShowThumbs.isSelected();
180 yLayer.startLoadThumbs();
181
182 // Search whether an other layer has yet defined some bounding box.
183 // If none, we'll zoom to the bounding box of the layer with the photos.
184 boolean boundingBoxedLayerFound = false;
[12636]185 for (Layer l: MainApplication.getLayerManager().getLayers()) {
[8509]186 if (l != yLayer) {
187 BoundingXYVisitor bbox = new BoundingXYVisitor();
188 l.visitBoundingBox(bbox);
189 if (bbox.getBounds() != null) {
190 boundingBoxedLayerFound = true;
191 break;
192 }
193 }
194 }
195 if (!boundingBoxedLayerFound) {
196 BoundingXYVisitor bbox = new BoundingXYVisitor();
197 yLayer.visitBoundingBox(bbox);
[12630]198 MainApplication.getMap().mapView.zoomTo(bbox);
[8509]199 }
200
[8653]201 if (yLayer.data != null) {
202 for (ImageEntry ie : yLayer.data) {
203 ie.applyTmp();
204 }
[8509]205 }
206
207 yLayer.updateBufferAndRepaint();
208
209 break;
210 default:
211 throw new IllegalStateException();
212 }
213 }
214 }
215
[2566]216 private static class GpxDataWrapper {
[9078]217 private final String name;
218 private final GpxData data;
219 private final File file;
[2566]220
[8836]221 GpxDataWrapper(String name, GpxData data, File file) {
[2566]222 this.name = name;
223 this.data = data;
224 this.file = file;
225 }
226
[2626]227 @Override
[2566]228 public String toString() {
229 return name;
230 }
231 }
232
[8285]233 private ExtendedDialog syncDialog;
[9078]234 private final transient List<GpxDataWrapper> gpxLst = new ArrayList<>();
[8285]235 private JPanel outerPanel;
236 private JosmComboBox<GpxDataWrapper> cbGpx;
237 private JosmTextField tfTimezone;
238 private JosmTextField tfOffset;
239 private JCheckBox cbExifImg;
240 private JCheckBox cbTaggedImg;
241 private JCheckBox cbShowThumbs;
242 private JLabel statusBarText;
[2676]243
[2662]244 // remember the last number of matched photos
[8840]245 private int lastNumMatched;
[2566]246
247 /** This class is called when the user doesn't find the GPX file he needs in the files that have
248 * been loaded yet. It displays a FileChooser dialog to select the GPX file to be loaded.
249 */
250 private class LoadGpxDataActionListener implements ActionListener {
251
[6084]252 @Override
[2566]253 public void actionPerformed(ActionEvent arg0) {
[8510]254 FileFilter filter = new FileFilter() {
255 @Override
256 public boolean accept(File f) {
[8404]257 return f.isDirectory() || Utils.hasExtension(f, "gpx", "gpx.gz");
[2566]258 }
[8510]259
260 @Override
261 public String getDescription() {
[2566]262 return tr("GPX Files (*.gpx *.gpx.gz)");
263 }
[5438]264 };
[7578]265 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true, false, null, filter, JFileChooser.FILES_ONLY, null);
[5438]266 if (fc == null)
267 return;
[2566]268 File sel = fc.getSelectedFile();
269
270 try {
[2662]271 outerPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
[2566]272
[8449]273 for (int i = gpxLst.size() - 1; i >= 0; i--) {
[2649]274 GpxDataWrapper wrapper = gpxLst.get(i);
[11739]275 if (sel.equals(wrapper.file)) {
[2649]276 cbGpx.setSelectedIndex(i);
277 if (!sel.getName().equals(wrapper.name)) {
278 JOptionPane.showMessageDialog(
279 Main.parent,
280 tr("File {0} is loaded yet under the name \"{1}\"", sel.getName(), wrapper.name),
281 tr("Error"),
282 JOptionPane.ERROR_MESSAGE
283 );
[2566]284 }
[2649]285 return;
[2566]286 }
287 }
288 GpxData data = null;
[7033]289 try (InputStream iStream = createInputStream(sel)) {
[2795]290 GpxReader reader = new GpxReader(iStream);
291 reader.parse(false);
[5679]292 data = reader.getGpxData();
[2566]293 data.storageFile = sel;
294
[11620]295 } catch (SAXException ex) {
[12620]296 Logging.error(ex);
[2566]297 JOptionPane.showMessageDialog(
[2592]298 Main.parent,
[11620]299 tr("Error while parsing {0}", sel.getName())+": "+ex.getMessage(),
[2592]300 tr("Error"),
301 JOptionPane.ERROR_MESSAGE
[2626]302 );
[2566]303 return;
[11620]304 } catch (IOException ex) {
[12620]305 Logging.error(ex);
[2566]306 JOptionPane.showMessageDialog(
[2592]307 Main.parent,
[11620]308 tr("Could not read \"{0}\"", sel.getName())+'\n'+ex.getMessage(),
[2592]309 tr("Error"),
310 JOptionPane.ERROR_MESSAGE
[2626]311 );
[2566]312 return;
313 }
314
[10176]315 MutableComboBoxModel<GpxDataWrapper> model = (MutableComboBoxModel<GpxDataWrapper>) cbGpx.getModel();
[2566]316 loadedGpxData.add(data);
[2649]317 if (gpxLst.get(0).file == null) {
[2566]318 gpxLst.remove(0);
[10176]319 model.removeElementAt(0);
[2566]320 }
[10176]321 GpxDataWrapper elem = new GpxDataWrapper(sel.getName(), data, sel);
322 gpxLst.add(elem);
323 model.addElement(elem);
[2566]324 cbGpx.setSelectedIndex(cbGpx.getItemCount() - 1);
325 } finally {
[2662]326 outerPanel.setCursor(Cursor.getDefaultCursor());
[2566]327 }
328 }
[7033]329
[8506]330 private InputStream createInputStream(File sel) throws IOException {
[8404]331 if (Utils.hasExtension(sel, "gpx.gz")) {
[13204]332 return new GZIPInputStream(Files.newInputStream(sel.toPath()));
[7033]333 } else {
[13204]334 return Files.newInputStream(sel.toPath());
[7033]335 }
336 }
[2566]337 }
338
[3408]339 /**
[3052]340 * This action listener is called when the user has a photo of the time of his GPS receiver. It
[2566]341 * displays the list of photos of the layer, and upon selection displays the selected photo.
342 * From that photo, the user can key in the time of the GPS.
343 * Then values of timezone and delta are set.
344 * @author chris
345 *
346 */
347 private class SetOffsetActionListener implements ActionListener {
348
[6084]349 @Override
[2566]350 public void actionPerformed(ActionEvent arg0) {
[7320]351 SimpleDateFormat dateFormat = (SimpleDateFormat) DateUtils.getDateTimeFormat(DateFormat.SHORT, DateFormat.MEDIUM);
[2566]352
[10938]353 JPanel panel = new JPanel(new BorderLayout());
[2566]354 panel.add(new JLabel(tr("<html>Take a photo of your GPS receiver while it displays the time.<br>"
[2626]355 + "Display that photo here.<br>"
356 + "And then, simply capture the time you read on the photo and select a timezone<hr></html>")),
357 BorderLayout.NORTH);
[2566]358
[10938]359 ImageDisplay imgDisp = new ImageDisplay();
[2566]360 imgDisp.setPreferredSize(new Dimension(300, 225));
361 panel.add(imgDisp, BorderLayout.CENTER);
362
[9543]363 JPanel panelTf = new JPanel(new GridBagLayout());
[2566]364
365 GridBagConstraints gc = new GridBagConstraints();
366 gc.gridx = gc.gridy = 0;
367 gc.gridwidth = gc.gridheight = 1;
368 gc.weightx = gc.weighty = 0.0;
369 gc.fill = GridBagConstraints.NONE;
370 gc.anchor = GridBagConstraints.WEST;
371 panelTf.add(new JLabel(tr("Photo time (from exif):")), gc);
372
[10938]373 JLabel lbExifTime = new JLabel();
[2566]374 gc.gridx = 1;
375 gc.weightx = 1.0;
376 gc.fill = GridBagConstraints.HORIZONTAL;
377 gc.gridwidth = 2;
378 panelTf.add(lbExifTime, gc);
379
380 gc.gridx = 0;
381 gc.gridy = 1;
382 gc.gridwidth = gc.gridheight = 1;
383 gc.weightx = gc.weighty = 0.0;
384 gc.fill = GridBagConstraints.NONE;
385 gc.anchor = GridBagConstraints.WEST;
386 panelTf.add(new JLabel(tr("Gps time (read from the above photo): ")), gc);
387
[10938]388 JosmTextField tfGpsTime = new JosmTextField(12);
[2566]389 tfGpsTime.setEnabled(false);
[2662]390 tfGpsTime.setMinimumSize(new Dimension(155, tfGpsTime.getMinimumSize().height));
[2566]391 gc.gridx = 1;
392 gc.weightx = 1.0;
393 gc.fill = GridBagConstraints.HORIZONTAL;
394 panelTf.add(tfGpsTime, gc);
395
396 gc.gridx = 2;
397 gc.weightx = 0.2;
[8846]398 panelTf.add(new JLabel(" ["+dateFormat.toLocalizedPattern()+']'), gc);
[2566]399
400 gc.gridx = 0;
401 gc.gridy = 2;
402 gc.gridwidth = gc.gridheight = 1;
403 gc.weightx = gc.weighty = 0.0;
404 gc.fill = GridBagConstraints.NONE;
405 gc.anchor = GridBagConstraints.WEST;
[2850]406 panelTf.add(new JLabel(tr("I am in the timezone of: ")), gc);
[2566]407
408 String[] tmp = TimeZone.getAvailableIDs();
[7005]409 List<String> vtTimezones = new ArrayList<>(tmp.length);
[2566]410
411 for (String tzStr : tmp) {
412 TimeZone tz = TimeZone.getTimeZone(tzStr);
413
[11288]414 String tzDesc = tzStr + " (" +
415 new Timezone(((double) tz.getRawOffset()) / TimeUnit.HOURS.toMillis(1)).formatTimezone() +
416 ')';
[2566]417 vtTimezones.add(tzDesc);
418 }
419
420 Collections.sort(vtTimezones);
421
[13206]422 JosmComboBox<String> cbTimezones = new JosmComboBox<>(vtTimezones.toArray(new String[0]));
[2566]423
[12846]424 String tzId = Config.getPref().get("geoimage.timezoneid", "");
[2566]425 TimeZone defaultTz;
[8394]426 if (tzId.isEmpty()) {
[2566]427 defaultTz = TimeZone.getDefault();
428 } else {
429 defaultTz = TimeZone.getTimeZone(tzId);
430 }
431
[11288]432 cbTimezones.setSelectedItem(defaultTz.getID() + " (" +
433 new Timezone(((double) defaultTz.getRawOffset()) / TimeUnit.HOURS.toMillis(1)).formatTimezone() +
434 ')');
[2566]435
436 gc.gridx = 1;
437 gc.weightx = 1.0;
438 gc.gridwidth = 2;
439 gc.fill = GridBagConstraints.HORIZONTAL;
440 panelTf.add(cbTimezones, gc);
441
442 panel.add(panelTf, BorderLayout.SOUTH);
443
[9543]444 JPanel panelLst = new JPanel(new BorderLayout());
[2566]445
[10938]446 JList<String> imgList = new JList<>(new AbstractListModel<String>() {
[6084]447 @Override
[7001]448 public String getElementAt(int i) {
[2931]449 return yLayer.data.get(i).getFile().getName();
[2566]450 }
451
[6084]452 @Override
[2566]453 public int getSize() {
[8660]454 return yLayer.data != null ? yLayer.data.size() : 0;
[2566]455 }
456 });
457 imgList.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
[10611]458 imgList.getSelectionModel().addListSelectionListener(evt -> {
459 int index = imgList.getSelectedIndex();
[13220]460 imgDisp.setImage(yLayer.data.get(index));
[10611]461 Date date = yLayer.data.get(index).getExifTime();
462 if (date != null) {
463 DateFormat df = DateUtils.getDateTimeFormat(DateFormat.SHORT, DateFormat.MEDIUM);
464 lbExifTime.setText(df.format(date));
465 tfGpsTime.setText(df.format(date));
466 tfGpsTime.setCaretPosition(tfGpsTime.getText().length());
467 tfGpsTime.setEnabled(true);
468 tfGpsTime.requestFocus();
469 } else {
470 lbExifTime.setText(tr("No date"));
471 tfGpsTime.setText("");
472 tfGpsTime.setEnabled(false);
[2566]473 }
474 });
475 panelLst.add(new JScrollPane(imgList), BorderLayout.CENTER);
476
[2850]477 JButton openButton = new JButton(tr("Open another photo"));
[10611]478 openButton.addActionListener(ae -> {
479 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true, false, null,
480 JpgImporter.FILE_FILTER_WITH_FOLDERS, JFileChooser.FILES_ONLY, "geoimage.lastdirectory");
481 if (fc == null)
482 return;
[13220]483 ImageEntry entry = new ImageEntry(fc.getSelectedFile());
484 entry.extractExif();
485 imgDisp.setImage(entry);
[2566]486
[13220]487 Date date = entry.getExifTime();
[10611]488 if (date != null) {
489 lbExifTime.setText(DateUtils.getDateTimeFormat(DateFormat.SHORT, DateFormat.MEDIUM).format(date));
490 tfGpsTime.setText(DateUtils.getDateFormat(DateFormat.SHORT).format(date)+' ');
491 tfGpsTime.setEnabled(true);
492 } else {
493 lbExifTime.setText(tr("No date"));
494 tfGpsTime.setText("");
495 tfGpsTime.setEnabled(false);
[2566]496 }
497 });
498 panelLst.add(openButton, BorderLayout.PAGE_END);
499
500 panel.add(panelLst, BorderLayout.LINE_START);
501
502 boolean isOk = false;
[8444]503 while (!isOk) {
[2566]504 int answer = JOptionPane.showConfirmDialog(
[2592]505 Main.parent, panel,
506 tr("Synchronize time from a photo of the GPS receiver"),
507 JOptionPane.OK_CANCEL_OPTION,
508 JOptionPane.QUESTION_MESSAGE
[2626]509 );
510 if (answer == JOptionPane.CANCEL_OPTION)
[2566]511 return;
512
513 long delta;
514
515 try {
516 delta = dateFormat.parse(lbExifTime.getText()).getTime()
[2626]517 - dateFormat.parse(tfGpsTime.getText()).getTime();
[8510]518 } catch (ParseException e) {
[2566]519 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing the date.\n"
520 + "Please use the requested format"),
[8444]521 tr("Invalid date"), JOptionPane.ERROR_MESSAGE);
[2566]522 continue;
523 }
524
525 String selectedTz = (String) cbTimezones.getSelectedItem();
526 int pos = selectedTz.lastIndexOf('(');
527 tzId = selectedTz.substring(0, pos - 1);
528 String tzValue = selectedTz.substring(pos + 1, selectedTz.length() - 1);
529
[12846]530 Config.getPref().put("geoimage.timezoneid", tzId);
[9741]531 tfOffset.setText(Offset.milliseconds(delta).formatOffset());
[2566]532 tfTimezone.setText(tzValue);
533
534 isOk = true;
535
536 }
[3052]537 statusBarUpdater.updateStatusBar();
[2662]538 yLayer.updateBufferAndRepaint();
[2566]539 }
540 }
541
[6084]542 @Override
[11457]543 public void actionPerformed(ActionEvent ae) {
[2566]544 // Construct the list of loaded GPX tracks
[12636]545 Collection<Layer> layerLst = MainApplication.getLayerManager().getLayers();
[13056]546 gpxLst.clear();
[2646]547 GpxDataWrapper defaultItem = null;
[6104]548 for (Layer cur : layerLst) {
[2566]549 if (cur instanceof GpxLayer) {
[3052]550 GpxLayer curGpx = (GpxLayer) cur;
551 GpxDataWrapper gdw = new GpxDataWrapper(curGpx.getName(), curGpx.data, curGpx.data.storageFile);
[2646]552 gpxLst.add(gdw);
553 if (cur == yLayer.gpxLayer) {
554 defaultItem = gdw;
555 }
[2566]556 }
557 }
558 for (GpxData data : loadedGpxData) {
559 gpxLst.add(new GpxDataWrapper(data.storageFile.getName(),
[2626]560 data,
561 data.storageFile));
[2566]562 }
563
[6093]564 if (gpxLst.isEmpty()) {
[2649]565 gpxLst.add(new GpxDataWrapper(tr("<No GPX track loaded yet>"), null, null));
[2566]566 }
567
568 JPanel panelCb = new JPanel();
569
570 panelCb.add(new JLabel(tr("GPX track: ")));
571
[13206]572 cbGpx = new JosmComboBox<>(gpxLst.toArray(new GpxDataWrapper[0]));
[2646]573 if (defaultItem != null) {
574 cbGpx.setSelectedItem(defaultItem);
[13056]575 } else {
576 // select first GPX track associated to a file
577 for (GpxDataWrapper item : gpxLst) {
578 if (item.file != null) {
579 cbGpx.setSelectedItem(item);
580 break;
581 }
582 }
[2646]583 }
[3052]584 cbGpx.addActionListener(statusBarUpdaterWithRepaint);
[2566]585 panelCb.add(cbGpx);
586
587 JButton buttonOpen = new JButton(tr("Open another GPX trace"));
588 buttonOpen.addActionListener(new LoadGpxDataActionListener());
589 panelCb.add(buttonOpen);
590
[9543]591 JPanel panelTf = new JPanel(new GridBagLayout());
[2566]592
[2662]593 try {
[12846]594 timezone = Timezone.parseTimezone(Optional.ofNullable(Config.getPref().get("geoimage.timezone", "0:00")).orElse("0:00"));
[2662]595 } catch (ParseException e) {
[9741]596 timezone = Timezone.ZERO;
[2662]597 }
[2676]598
[5886]599 tfTimezone = new JosmTextField(10);
[9741]600 tfTimezone.setText(timezone.formatTimezone());
[2566]601
[2662]602 try {
[12846]603 delta = Offset.parseOffset(Config.getPref().get("geoimage.delta", "0"));
[2662]604 } catch (ParseException e) {
[9741]605 delta = Offset.ZERO;
[2566]606 }
[2676]607
[5886]608 tfOffset = new JosmTextField(10);
[9741]609 tfOffset.setText(delta.formatOffset());
[2676]610
[2662]611 JButton buttonViewGpsPhoto = new JButton(tr("<html>Use photo of an accurate clock,<br>"
612 + "e.g. GPS receiver display</html>"));
613 buttonViewGpsPhoto.setIcon(ImageProvider.get("clock"));
614 buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener());
[2566]615
[2662]616 JButton buttonAutoGuess = new JButton(tr("Auto-Guess"));
[3310]617 buttonAutoGuess.setToolTipText(tr("Matches first photo with first gpx point"));
[2662]618 buttonAutoGuess.addActionListener(new AutoGuessActionListener());
[2566]619
[2662]620 JButton buttonAdjust = new JButton(tr("Manual adjust"));
621 buttonAdjust.addActionListener(new AdjustActionListener());
[2566]622
[2662]623 JLabel labelPosition = new JLabel(tr("Override position for: "));
[2676]624
[2662]625 int numAll = getSortedImgList(true, true).size();
626 int numExif = numAll - getSortedImgList(false, true).size();
627 int numTagged = numAll - getSortedImgList(true, false).size();
[2566]628
[2662]629 cbExifImg = new JCheckBox(tr("Images with geo location in exif data ({0}/{1})", numExif, numAll));
630 cbExifImg.setEnabled(numExif != 0);
[2566]631
[2662]632 cbTaggedImg = new JCheckBox(tr("Images that are already tagged ({0}/{1})", numTagged, numAll), true);
633 cbTaggedImg.setEnabled(numTagged != 0);
[2676]634
[2662]635 labelPosition.setEnabled(cbExifImg.isEnabled() || cbTaggedImg.isEnabled());
[2566]636
[12846]637 boolean ticked = yLayer.thumbsLoaded || Config.getPref().getBoolean("geoimage.showThumbs", false);
[2662]638 cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), ticked);
639 cbShowThumbs.setEnabled(!yLayer.thumbsLoaded);
[2566]640
[8510]641 int y = 0;
[2662]642 GBC gbc = GBC.eol();
643 gbc.gridx = 0;
644 gbc.gridy = y++;
645 panelTf.add(panelCb, gbc);
[2676]646
[8510]647 gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 12);
[2662]648 gbc.gridx = 0;
649 gbc.gridy = y++;
650 panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);
[2566]651
[2662]652 gbc = GBC.std();
653 gbc.gridx = 0;
654 gbc.gridy = y;
655 panelTf.add(new JLabel(tr("Timezone: ")), gbc);
[2592]656
[2662]657 gbc = GBC.std().fill(GBC.HORIZONTAL);
658 gbc.gridx = 1;
659 gbc.gridy = y++;
660 gbc.weightx = 1.;
661 panelTf.add(tfTimezone, gbc);
[2566]662
[2662]663 gbc = GBC.std();
664 gbc.gridx = 0;
665 gbc.gridy = y;
666 panelTf.add(new JLabel(tr("Offset:")), gbc);
[2566]667
[2662]668 gbc = GBC.std().fill(GBC.HORIZONTAL);
669 gbc.gridx = 1;
670 gbc.gridy = y++;
671 gbc.weightx = 1.;
672 panelTf.add(tfOffset, gbc);
[2676]673
[8510]674 gbc = GBC.std().insets(5, 5, 5, 5);
[2662]675 gbc.gridx = 2;
676 gbc.gridy = y-2;
677 gbc.gridheight = 2;
678 gbc.gridwidth = 2;
679 gbc.fill = GridBagConstraints.BOTH;
680 gbc.weightx = 0.5;
681 panelTf.add(buttonViewGpsPhoto, gbc);
[2566]682
[8510]683 gbc = GBC.std().fill(GBC.BOTH).insets(5, 5, 5, 5);
[2662]684 gbc.gridx = 2;
685 gbc.gridy = y++;
686 gbc.weightx = 0.5;
687 panelTf.add(buttonAutoGuess, gbc);
[2676]688
[2662]689 gbc.gridx = 3;
690 panelTf.add(buttonAdjust, gbc);
[2566]691
[8510]692 gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 12, 0, 0);
[2662]693 gbc.gridx = 0;
694 gbc.gridy = y++;
695 panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);
[2566]696
[2662]697 gbc = GBC.eol();
698 gbc.gridx = 0;
699 gbc.gridy = y++;
700 panelTf.add(labelPosition, gbc);
[2566]701
[2662]702 gbc = GBC.eol();
703 gbc.gridx = 1;
704 gbc.gridy = y++;
705 panelTf.add(cbExifImg, gbc);
[2566]706
[2662]707 gbc = GBC.eol();
708 gbc.gridx = 1;
709 gbc.gridy = y++;
710 panelTf.add(cbTaggedImg, gbc);
[2566]711
[2662]712 gbc = GBC.eol();
713 gbc.gridx = 0;
[10308]714 gbc.gridy = y;
[2662]715 panelTf.add(cbShowThumbs, gbc);
716
[9543]717 final JPanel statusBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
[2662]718 statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
719 statusBarText = new JLabel(" ");
720 statusBarText.setFont(statusBarText.getFont().deriveFont(8));
721 statusBar.add(statusBarText);
[2676]722
[3052]723 tfTimezone.addFocusListener(repaintTheMap);
724 tfOffset.addFocusListener(repaintTheMap);
[3408]725
[3052]726 tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
727 tfOffset.getDocument().addDocumentListener(statusBarUpdater);
728 cbExifImg.addItemListener(statusBarUpdaterWithRepaint);
729 cbTaggedImg.addItemListener(statusBarUpdaterWithRepaint);
[2676]730
[3052]731 statusBarUpdater.updateStatusBar();
[2676]732
[9543]733 outerPanel = new JPanel(new BorderLayout());
[2662]734 outerPanel.add(statusBar, BorderLayout.PAGE_END);
735
[9660]736 if (!GraphicsEnvironment.isHeadless()) {
737 syncDialog = new ExtendedDialog(
738 Main.parent,
739 tr("Correlate images with GPX track"),
740 new String[] {tr("Correlate"), tr("Cancel")},
741 false
742 );
743 syncDialog.setContent(panelTf, false);
[12279]744 syncDialog.setButtonIcons("ok", "cancel");
[9660]745 syncDialog.setupDialog();
746 outerPanel.add(syncDialog.getContentPane(), BorderLayout.PAGE_START);
747 syncDialog.setContentPane(outerPanel);
748 syncDialog.pack();
749 syncDialog.addWindowListener(new SyncDialogWindowListener());
750 syncDialog.showDialog();
751 }
[2662]752 }
753
[9078]754 private final transient StatusBarUpdater statusBarUpdater = new StatusBarUpdater(false);
755 private final transient StatusBarUpdater statusBarUpdaterWithRepaint = new StatusBarUpdater(true);
[3408]756
[10378]757 private class StatusBarUpdater implements DocumentListener, ItemListener, ActionListener {
[9078]758 private final boolean doRepaint;
[3052]759
[8836]760 StatusBarUpdater(boolean doRepaint) {
[3052]761 this.doRepaint = doRepaint;
762 }
[3408]763
[6084]764 @Override
[2662]765 public void insertUpdate(DocumentEvent ev) {
766 updateStatusBar();
[2566]767 }
[8510]768
[6084]769 @Override
[2662]770 public void removeUpdate(DocumentEvent ev) {
771 updateStatusBar();
[2566]772 }
[8510]773
[6084]774 @Override
[2662]775 public void changedUpdate(DocumentEvent ev) {
[10173]776 // Do nothing
[2662]777 }
[8510]778
[6084]779 @Override
[2662]780 public void itemStateChanged(ItemEvent e) {
781 updateStatusBar();
782 }
[8510]783
[6084]784 @Override
[3052]785 public void actionPerformed(ActionEvent e) {
786 updateStatusBar();
787 }
788
789 public void updateStatusBar() {
790 statusBarText.setText(statusText());
791 if (doRepaint) {
792 yLayer.updateBufferAndRepaint();
793 }
794 }
[3408]795
[3052]796 private String statusText() {
797 try {
[9741]798 timezone = Timezone.parseTimezone(tfTimezone.getText().trim());
799 delta = Offset.parseOffset(tfOffset.getText().trim());
[3052]800 } catch (ParseException e) {
801 return e.getMessage();
802 }
803
804 // The selection of images we are about to correlate may have changed.
805 // So reset all images.
[8660]806 if (yLayer.data != null) {
807 for (ImageEntry ie: yLayer.data) {
[9270]808 ie.discardTmp();
[8660]809 }
[3052]810 }
[3408]811
[3052]812 // Construct a list of images that have a date, and sort them on the date.
[6316]813 List<ImageEntry> dateImgLst = getSortedImgList();
[3052]814 // Create a temporary copy for each image
815 for (ImageEntry ie : dateImgLst) {
[9270]816 ie.createTmp();
817 ie.tmp.setPos(null);
[3052]818 }
819
820 GpxDataWrapper selGpx = selectedGPX(false);
821 if (selGpx == null)
822 return tr("No gpx selected");
823
[11288]824 final long offsetMs = ((long) (timezone.getHours() * TimeUnit.HOURS.toMillis(1))) + delta.getMilliseconds(); // in milliseconds
[10001]825 lastNumMatched = matchGpxTrack(dateImgLst, selGpx.data, offsetMs);
[3052]826
827 return trn("<html>Matched <b>{0}</b> of <b>{1}</b> photo to GPX track.</html>",
828 "<html>Matched <b>{0}</b> of <b>{1}</b> photos to GPX track.</html>",
829 dateImgLst.size(), lastNumMatched, dateImgLst.size());
830 }
[2662]831 }
[2566]832
[9078]833 private final transient RepaintTheMapListener repaintTheMap = new RepaintTheMapListener();
[8510]834
[3052]835 private class RepaintTheMapListener implements FocusListener {
[6084]836 @Override
[3052]837 public void focusGained(FocusEvent e) { // do nothing
838 }
[3408]839
[6084]840 @Override
[3052]841 public void focusLost(FocusEvent e) {
842 yLayer.updateBufferAndRepaint();
843 }
844 }
845
[2662]846 /**
847 * Presents dialog with sliders for manual adjust.
848 */
849 private class AdjustActionListener implements ActionListener {
[2676]850
[6084]851 @Override
[2662]852 public void actionPerformed(ActionEvent arg0) {
[2566]853
[9742]854 final Offset offset = Offset.milliseconds(
[11288]855 delta.getMilliseconds() + Math.round(timezone.getHours() * TimeUnit.HOURS.toMillis(1)));
[9742]856 final int dayOffset = offset.getDayOffset();
857 final Pair<Timezone, Offset> timezoneOffsetPair = offset.withoutDayOffset().splitOutTimezone();
[2676]858
[2662]859 // Info Labels
860 final JLabel lblMatches = new JLabel();
[2566]861
[2662]862 // Timezone Slider
[8510]863 // The slider allows to switch timezon from -12:00 to 12:00 in 30 minutes steps. Therefore the range is -24 to 24.
[2662]864 final JLabel lblTimezone = new JLabel();
865 final JSlider sldTimezone = new JSlider(-24, 24, 0);
866 sldTimezone.setPaintLabels(true);
[8510]867 Dictionary<Integer, JLabel> labelTable = new Hashtable<>();
868 // CHECKSTYLE.OFF: ParenPad
[9742]869 for (int i = -12; i <= 12; i += 6) {
870 labelTable.put(i * 2, new JLabel(new Timezone(i).formatTimezone()));
871 }
[8510]872 // CHECKSTYLE.ON: ParenPad
[2662]873 sldTimezone.setLabelTable(labelTable);
[2566]874
[2662]875 // Minutes Slider
876 final JLabel lblMinutes = new JLabel();
877 final JSlider sldMinutes = new JSlider(-15, 15, 0);
878 sldMinutes.setPaintLabels(true);
879 sldMinutes.setMajorTickSpacing(5);
[2566]880
[2662]881 // Seconds slider
882 final JLabel lblSeconds = new JLabel();
[9742]883 final JSlider sldSeconds = new JSlider(-600, 600, 0);
[2662]884 sldSeconds.setPaintLabels(true);
[9742]885 labelTable = new Hashtable<>();
886 // CHECKSTYLE.OFF: ParenPad
887 for (int i = -60; i <= 60; i += 30) {
888 labelTable.put(i * 10, new JLabel(Offset.seconds(i).formatOffset()));
889 }
890 // CHECKSTYLE.ON: ParenPad
891 sldSeconds.setLabelTable(labelTable);
892 sldSeconds.setMajorTickSpacing(300);
[2566]893
[2662]894 // This is called whenever one of the sliders is moved.
895 // It updates the labels and also calls the "match photos" code
[6246]896 class SliderListener implements ChangeListener {
[6084]897 @Override
[2662]898 public void stateChanged(ChangeEvent e) {
[9742]899 timezone = new Timezone(sldTimezone.getValue() / 2.);
[2566]900
[9742]901 lblTimezone.setText(tr("Timezone: {0}", timezone.formatTimezone()));
[2662]902 lblMinutes.setText(tr("Minutes: {0}", sldMinutes.getValue()));
[10181]903 lblSeconds.setText(tr("Seconds: {0}", Offset.milliseconds(100L * sldSeconds.getValue()).formatOffset()));
[2662]904
[10234]905 delta = Offset.milliseconds(100L * sldSeconds.getValue()
[11288]906 + TimeUnit.MINUTES.toMillis(sldMinutes.getValue())
907 + TimeUnit.DAYS.toMillis(dayOffset));
[2566]908
[3052]909 tfTimezone.getDocument().removeDocumentListener(statusBarUpdater);
910 tfOffset.getDocument().removeDocumentListener(statusBarUpdater);
[2676]911
[9741]912 tfTimezone.setText(timezone.formatTimezone());
913 tfOffset.setText(delta.formatOffset());
[2566]914
[3052]915 tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
916 tfOffset.getDocument().addDocumentListener(statusBarUpdater);
[2566]917
[7299]918 lblMatches.setText(statusBarText.getText() + "<br>" + trn("(Time difference of {0} day)",
919 "Time difference of {0} days", Math.abs(dayOffset), Math.abs(dayOffset)));
[2566]920
[3052]921 statusBarUpdater.updateStatusBar();
[2662]922 yLayer.updateBufferAndRepaint();
923 }
924 }
[2566]925
[2662]926 // Put everything together
927 JPanel p = new JPanel(new GridBagLayout());
928 p.setPreferredSize(new Dimension(400, 230));
929 p.add(lblMatches, GBC.eol().fill());
930 p.add(lblTimezone, GBC.eol().fill());
931 p.add(sldTimezone, GBC.eol().fill().insets(0, 0, 0, 10));
932 p.add(lblMinutes, GBC.eol().fill());
933 p.add(sldMinutes, GBC.eol().fill().insets(0, 0, 0, 10));
934 p.add(lblSeconds, GBC.eol().fill());
935 p.add(sldSeconds, GBC.eol().fill());
[2566]936
[2662]937 // If there's an error in the calculation the found values
938 // will be off range for the sliders. Catch this error
939 // and inform the user about it.
940 try {
[9742]941 sldTimezone.setValue((int) (timezoneOffsetPair.a.getHours() * 2));
942 sldMinutes.setValue((int) (timezoneOffsetPair.b.getSeconds() / 60));
943 final long deciSeconds = timezoneOffsetPair.b.getMilliseconds() / 100;
944 sldSeconds.setValue((int) (deciSeconds % 60));
[11746]945 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
[12620]946 Logging.warn(e);
[2662]947 JOptionPane.showMessageDialog(Main.parent,
948 tr("An error occurred while trying to match the photos to the GPX track."
949 +" You can adjust the sliders to manually match the photos."),
950 tr("Matching photos to track failed"),
951 JOptionPane.WARNING_MESSAGE);
952 }
[2566]953
[2662]954 // Call the sliderListener once manually so labels get adjusted
[6246]955 new SliderListener().stateChanged(null);
[2662]956 // Listeners added here, otherwise it tries to match three times
957 // (when setting the default values)
[6246]958 sldTimezone.addChangeListener(new SliderListener());
959 sldMinutes.addChangeListener(new SliderListener());
960 sldSeconds.addChangeListener(new SliderListener());
[2566]961
[2662]962 // There is no way to cancel this dialog, all changes get applied
963 // immediately. Therefore "Close" is marked with an "OK" icon.
964 // Settings are only saved temporarily to the layer.
965 new ExtendedDialog(Main.parent,
966 tr("Adjust timezone and offset"),
[12279]967 tr("Close")).
968 setContent(p).setButtonIcons("ok").showDialog();
[2662]969 }
970 }
[2566]971
[9726]972 static class NoGpxTimestamps extends Exception {
973 }
974
975 /**
976 * Tries to auto-guess the timezone and offset.
977 *
978 * @param imgs the images to correlate
979 * @param gpx the gpx track to correlate to
[9741]980 * @return a pair of timezone and offset
[9726]981 * @throws IndexOutOfBoundsException when there are no images
982 * @throws NoGpxTimestamps when the gpx track does not contain a timestamp
983 */
[10632]984 static Pair<Timezone, Offset> autoGuess(List<ImageEntry> imgs, GpxData gpx) throws NoGpxTimestamps {
[9726]985
986 // Init variables
[9742]987 long firstExifDate = imgs.get(0).getExifTime().getTime();
[9726]988
989 long firstGPXDate = -1;
990 // Finds first GPX point
991 outer: for (GpxTrack trk : gpx.tracks) {
992 for (GpxTrackSegment segment : trk.getSegments()) {
993 for (WayPoint curWp : segment.getWayPoints()) {
[10212]994 final Date parsedTime = curWp.setTimeFromAttribute();
995 if (parsedTime != null) {
996 firstGPXDate = parsedTime.getTime();
997 break outer;
[9726]998 }
999 }
1000 }
1001 }
1002
1003 if (firstGPXDate < 0) {
1004 throw new NoGpxTimestamps();
1005 }
1006
[9742]1007 return Offset.milliseconds(firstExifDate - firstGPXDate).splitOutTimezone();
[9726]1008 }
1009
[2662]1010 private class AutoGuessActionListener implements ActionListener {
[2676]1011
[6084]1012 @Override
[2662]1013 public void actionPerformed(ActionEvent arg0) {
1014 GpxDataWrapper gpxW = selectedGPX(true);
1015 if (gpxW == null)
1016 return;
1017 GpxData gpx = gpxW.data;
[2676]1018
[6316]1019 List<ImageEntry> imgs = getSortedImgList();
[2566]1020
[9726]1021 try {
[9741]1022 final Pair<Timezone, Offset> r = autoGuess(imgs, gpx);
[9726]1023 timezone = r.a;
1024 delta = r.b;
1025 } catch (IndexOutOfBoundsException ex) {
[12620]1026 Logging.debug(ex);
[2662]1027 JOptionPane.showMessageDialog(Main.parent,
[2850]1028 tr("The selected photos do not contain time information."),
1029 tr("Photos do not contain time information"), JOptionPane.WARNING_MESSAGE);
[2662]1030 return;
[9726]1031 } catch (NoGpxTimestamps ex) {
[12620]1032 Logging.debug(ex);
[2662]1033 JOptionPane.showMessageDialog(Main.parent,
[2850]1034 tr("The selected GPX track does not contain timestamps. Please select another one."),
[2662]1035 tr("GPX Track has no time information"), JOptionPane.WARNING_MESSAGE);
1036 return;
[2566]1037 }
1038
[3052]1039 tfTimezone.getDocument().removeDocumentListener(statusBarUpdater);
1040 tfOffset.getDocument().removeDocumentListener(statusBarUpdater);
[2676]1041
[9741]1042 tfTimezone.setText(timezone.formatTimezone());
1043 tfOffset.setText(delta.formatOffset());
[2662]1044 tfOffset.requestFocus();
[2566]1045
[3052]1046 tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
1047 tfOffset.getDocument().addDocumentListener(statusBarUpdater);
[2676]1048
[3052]1049 statusBarUpdater.updateStatusBar();
[2662]1050 yLayer.updateBufferAndRepaint();
[2566]1051 }
1052 }
1053
[6316]1054 private List<ImageEntry> getSortedImgList() {
[2662]1055 return getSortedImgList(cbExifImg.isSelected(), cbTaggedImg.isSelected());
1056 }
[2676]1057
[2566]1058 /**
1059 * Returns a list of images that fulfill the given criteria.
1060 * Default setting is to return untagged images, but may be overwritten.
[5891]1061 * @param exif also returns images with exif-gps info
1062 * @param tagged also returns tagged images
1063 * @return matching images
[2566]1064 */
[6316]1065 private List<ImageEntry> getSortedImgList(boolean exif, boolean tagged) {
[8658]1066 if (yLayer.data == null) {
1067 return Collections.emptyList();
1068 }
[7005]1069 List<ImageEntry> dateImgLst = new ArrayList<>(yLayer.data.size());
[2662]1070 for (ImageEntry e : yLayer.data) {
[6450]1071 if (!e.hasExifTime()) {
[2662]1072 continue;
[2676]1073 }
1074
[6883]1075 if (e.getExifCoor() != null && !exif) {
1076 continue;
[2566]1077 }
[2676]1078
[11452]1079 if (!tagged && e.isTagged() && e.getExifCoor() == null) {
[6883]1080 continue;
[2566]1081 }
[2676]1082
[2662]1083 dateImgLst.add(e);
[2566]1084 }
[2676]1085
[10647]1086 dateImgLst.sort(Comparator.comparing(ImageEntry::getExifTime));
[2566]1087
1088 return dateImgLst;
1089 }
1090
[2662]1091 private GpxDataWrapper selectedGPX(boolean complain) {
1092 Object item = cbGpx.getSelectedItem();
1093
[2702]1094 if (item == null || ((GpxDataWrapper) item).file == null) {
[2662]1095 if (complain) {
1096 JOptionPane.showMessageDialog(Main.parent, tr("You should select a GPX track"),
[8444]1097 tr("No selected GPX track"), JOptionPane.ERROR_MESSAGE);
[2662]1098 }
1099 return null;
1100 }
1101 return (GpxDataWrapper) item;
1102 }
1103
[2931]1104 /**
1105 * Match a list of photos to a gpx track with a given offset.
1106 * All images need a exifTime attribute and the List must be sorted according to these times.
[9243]1107 * @param images images to match
1108 * @param selectedGpx selected GPX data
1109 * @param offset offset
1110 * @return number of matched points
[2931]1111 */
[9384]1112 static int matchGpxTrack(List<ImageEntry> images, GpxData selectedGpx, long offset) {
[2566]1113 int ret = 0;
1114
1115 for (GpxTrack trk : selectedGpx.tracks) {
[2907]1116 for (GpxTrackSegment segment : trk.getSegments()) {
[2566]1117
[2931]1118 long prevWpTime = 0;
[2566]1119 WayPoint prevWp = null;
1120
[2907]1121 for (WayPoint curWp : segment.getWayPoints()) {
[10212]1122 final Date parsedTime = curWp.setTimeFromAttribute();
1123 if (parsedTime != null) {
1124 final long curWpTime = parsedTime.getTime() + offset;
1125 ret += matchPoints(images, prevWp, prevWpTime, curWp, curWpTime, offset);
[2566]1126
[10212]1127 prevWp = curWp;
1128 prevWpTime = curWpTime;
1129 continue;
[2566]1130 }
[9383]1131 prevWp = null;
1132 prevWpTime = 0;
[2566]1133 }
1134 }
1135 }
1136 return ret;
1137 }
1138
[6450]1139 private static Double getElevation(WayPoint wp) {
[7518]1140 String value = wp.getString(GpxConstants.PT_ELE);
[9698]1141 if (value != null && !value.isEmpty()) {
[6450]1142 try {
[10209]1143 return Double.valueOf(value);
[6450]1144 } catch (NumberFormatException e) {
[12620]1145 Logging.warn(e);
[6450]1146 }
1147 }
1148 return null;
1149 }
[6792]1150
[9384]1151 static int matchPoints(List<ImageEntry> images, WayPoint prevWp, long prevWpTime,
[2931]1152 WayPoint curWp, long curWpTime, long offset) {
[2566]1153 // Time between the track point and the previous one, 5 sec if first point, i.e. photos take
1154 // 5 sec before the first track point can be assumed to be take at the starting position
[11288]1155 long interval = prevWpTime > 0 ? Math.abs(curWpTime - prevWpTime) : TimeUnit.SECONDS.toMillis(5);
[2566]1156 int ret = 0;
1157
1158 // i is the index of the timewise last photo that has the same or earlier EXIF time
[2931]1159 int i = getLastIndexOfListBefore(images, curWpTime);
[2566]1160
1161 // no photos match
1162 if (i < 0)
1163 return 0;
1164
1165 Double speed = null;
1166 Double prevElevation = null;
1167
1168 if (prevWp != null) {
1169 double distance = prevWp.getCoor().greatCircleDistance(curWp.getCoor());
1170 // This is in km/h, 3.6 * m/s
[2931]1171 if (curWpTime > prevWpTime) {
[3288]1172 speed = 3600 * distance / (curWpTime - prevWpTime);
[2626]1173 }
[6450]1174 prevElevation = getElevation(prevWp);
[2566]1175 }
1176
[6450]1177 Double curElevation = getElevation(curWp);
[2566]1178
1179 // First trackpoint, then interval is set to five seconds, i.e. photos up to five seconds
1180 // before the first point will be geotagged with the starting point
[6450]1181 if (prevWpTime == 0 || curWpTime <= prevWpTime) {
[8318]1182 while (i >= 0) {
[2931]1183 final ImageEntry curImg = images.get(i);
[6450]1184 long time = curImg.getExifTime().getTime();
1185 if (time > curWpTime || time < curWpTime - interval) {
[3408]1186 break;
1187 }
[6450]1188 if (curImg.tmp.getPos() == null) {
[2931]1189 curImg.tmp.setPos(curWp.getCoor());
1190 curImg.tmp.setSpeed(speed);
1191 curImg.tmp.setElevation(curElevation);
1192 curImg.tmp.setGpsTime(new Date(curImg.getExifTime().getTime() - offset));
[13093]1193 curImg.tmp.flagNewGpsData();
[2566]1194 ret++;
1195 }
1196 i--;
1197 }
1198 return ret;
1199 }
1200
1201 // This code gives a simple linear interpolation of the coordinates between current and
1202 // previous track point assuming a constant speed in between
[8318]1203 while (i >= 0) {
[2931]1204 ImageEntry curImg = images.get(i);
1205 long imgTime = curImg.getExifTime().getTime();
[3408]1206 if (imgTime < prevWpTime) {
[2931]1207 break;
[3408]1208 }
[2566]1209
[11452]1210 if (prevWp != null && curImg.tmp.getPos() == null) {
[6450]1211 // The values of timeDiff are between 0 and 1, it is not seconds but a dimensionless variable
[8510]1212 double timeDiff = (double) (imgTime - prevWpTime) / interval;
[2931]1213 curImg.tmp.setPos(prevWp.getCoor().interpolate(curWp.getCoor(), timeDiff));
1214 curImg.tmp.setSpeed(speed);
[2626]1215 if (curElevation != null && prevElevation != null) {
[5242]1216 curImg.tmp.setElevation(prevElevation + (curElevation - prevElevation) * timeDiff);
[2626]1217 }
[2931]1218 curImg.tmp.setGpsTime(new Date(curImg.getExifTime().getTime() - offset));
[13093]1219 curImg.tmp.flagNewGpsData();
[2566]1220
1221 ret++;
1222 }
1223 i--;
1224 }
1225 return ret;
1226 }
1227
[8870]1228 private static int getLastIndexOfListBefore(List<ImageEntry> images, long searchedTime) {
[8510]1229 int lstSize = images.size();
[2566]1230
1231 // No photos or the first photo taken is later than the search period
[8510]1232 if (lstSize == 0 || searchedTime < images.get(0).getExifTime().getTime())
[2566]1233 return -1;
1234
1235 // The search period is later than the last photo
[2931]1236 if (searchedTime > images.get(lstSize - 1).getExifTime().getTime())
[2566]1237 return lstSize-1;
1238
1239 // The searched index is somewhere in the middle, do a binary search from the beginning
[10308]1240 int curIndex;
[8510]1241 int startIndex = 0;
1242 int endIndex = lstSize-1;
[2566]1243 while (endIndex - startIndex > 1) {
[8510]1244 curIndex = (endIndex + startIndex) / 2;
[2931]1245 if (searchedTime > images.get(curIndex).getExifTime().getTime()) {
[8510]1246 startIndex = curIndex;
[2626]1247 } else {
[8510]1248 endIndex = curIndex;
[2626]1249 }
[2566]1250 }
[2931]1251 if (searchedTime < images.get(endIndex).getExifTime().getTime())
[2566]1252 return startIndex;
1253
1254 // This final loop is to check if photos with the exact same EXIF time follows
[2931]1255 while ((endIndex < (lstSize-1)) && (images.get(endIndex).getExifTime().getTime()
1256 == images.get(endIndex + 1).getExifTime().getTime())) {
[2566]1257 endIndex++;
[2626]1258 }
[2566]1259 return endIndex;
1260 }
1261}
Note: See TracBrowser for help on using the repository browser.