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

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

sonar - squid:S1166 - Exception handlers should preserve the original exceptions

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