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

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

Sonar/FindBugs - various bugfixes / violation fixes

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