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

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

see #15182 - move file importers/exporters from io package to gui.io.importexport package, as they rely heavily on GUI and are mainly used from Open/Save actions

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