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