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

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

fix #12776 - "Correlate to gpx" doesn't refresh combo box after GPX file selection

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