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

Last change on this file since 12846 was 12846, checked in by bastiK, 7 years ago

see #15229 - use Config.getPref() wherever possible

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