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

Last change on this file since 4283 was 4242, checked in by bastiK, 13 years ago

fix imports

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