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

Last change on this file since 6093 was 6093, checked in by akks, 11 years ago

see #8902 - collection size ==/!= 0 -> isEmpty()/!isEmpty() (patch by shinigami)

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