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

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

fix many checkstyle violations

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