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

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

Sonar - fix various violations

  • 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.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.gui.widgets.JosmTextField;
77import org.openstreetmap.josm.io.GpxReader;
78import org.openstreetmap.josm.tools.ExifReader;
79import org.openstreetmap.josm.tools.GBC;
80import org.openstreetmap.josm.tools.ImageProvider;
81import org.openstreetmap.josm.tools.PrimaryDateParser;
82import org.xml.sax.SAXException;
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 String[] tmp = TimeZone.getAvailableIDs();
294 Vector<String> vtTimezones = new Vector<String>(tmp.length);
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 for (Layer cur : layerLst) {
455 if (cur instanceof GpxLayer) {
456 GpxLayer curGpx = (GpxLayer) cur;
457 GpxDataWrapper gdw = new GpxDataWrapper(curGpx.getName(), curGpx.data, curGpx.data.storageFile);
458 gpxLst.add(gdw);
459 if (cur == yLayer.gpxLayer) {
460 defaultItem = gdw;
461 }
462 }
463 }
464 for (GpxData data : loadedGpxData) {
465 gpxLst.add(new GpxDataWrapper(data.storageFile.getName(),
466 data,
467 data.storageFile));
468 }
469
470 if (gpxLst.isEmpty()) {
471 gpxLst.add(new GpxDataWrapper(tr("<No GPX track loaded yet>"), null, null));
472 }
473
474 JPanel panelCb = new JPanel();
475
476 panelCb.add(new JLabel(tr("GPX track: ")));
477
478 cbGpx = new JosmComboBox(gpxLst);
479 if (defaultItem != null) {
480 cbGpx.setSelectedItem(defaultItem);
481 }
482 cbGpx.addActionListener(statusBarUpdaterWithRepaint);
483 panelCb.add(cbGpx);
484
485 JButton buttonOpen = new JButton(tr("Open another GPX trace"));
486 buttonOpen.addActionListener(new LoadGpxDataActionListener());
487 panelCb.add(buttonOpen);
488
489 JPanel panelTf = new JPanel();
490 panelTf.setLayout(new GridBagLayout());
491
492 String prefTimezone = Main.pref.get("geoimage.timezone", "0:00");
493 if (prefTimezone == null) {
494 prefTimezone = "0:00";
495 }
496 try {
497 timezone = parseTimezone(prefTimezone);
498 } catch (ParseException e) {
499 timezone = 0;
500 }
501
502 tfTimezone = new JosmTextField(10);
503 tfTimezone.setText(formatTimezone(timezone));
504
505 try {
506 delta = parseOffset(Main.pref.get("geoimage.delta", "0"));
507 } catch (ParseException e) {
508 delta = 0;
509 }
510 delta = delta / 1000; // milliseconds -> seconds
511
512 tfOffset = new JosmTextField(10);
513 tfOffset.setText(Long.toString(delta));
514
515 JButton buttonViewGpsPhoto = new JButton(tr("<html>Use photo of an accurate clock,<br>"
516 + "e.g. GPS receiver display</html>"));
517 buttonViewGpsPhoto.setIcon(ImageProvider.get("clock"));
518 buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener());
519
520 JButton buttonAutoGuess = new JButton(tr("Auto-Guess"));
521 buttonAutoGuess.setToolTipText(tr("Matches first photo with first gpx point"));
522 buttonAutoGuess.addActionListener(new AutoGuessActionListener());
523
524 JButton buttonAdjust = new JButton(tr("Manual adjust"));
525 buttonAdjust.addActionListener(new AdjustActionListener());
526
527 JLabel labelPosition = new JLabel(tr("Override position for: "));
528
529 int numAll = getSortedImgList(true, true).size();
530 int numExif = numAll - getSortedImgList(false, true).size();
531 int numTagged = numAll - getSortedImgList(true, false).size();
532
533 cbExifImg = new JCheckBox(tr("Images with geo location in exif data ({0}/{1})", numExif, numAll));
534 cbExifImg.setEnabled(numExif != 0);
535
536 cbTaggedImg = new JCheckBox(tr("Images that are already tagged ({0}/{1})", numTagged, numAll), true);
537 cbTaggedImg.setEnabled(numTagged != 0);
538
539 labelPosition.setEnabled(cbExifImg.isEnabled() || cbTaggedImg.isEnabled());
540
541 boolean ticked = yLayer.thumbsLoaded || Main.pref.getBoolean("geoimage.showThumbs", false);
542 cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), ticked);
543 cbShowThumbs.setEnabled(!yLayer.thumbsLoaded);
544 /*cbShowThumbs.addItemListener(new ItemListener() {
545 public void itemStateChanged(ItemEvent e) {
546 if (e.getStateChange() == ItemEvent.SELECTED) {
547 yLayer.loadThumbs();
548 } else {
549 }
550 }
551 });*/
552
553 int y=0;
554 GBC gbc = GBC.eol();
555 gbc.gridx = 0;
556 gbc.gridy = y++;
557 panelTf.add(panelCb, gbc);
558
559 gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0,0,0,12);
560 gbc.gridx = 0;
561 gbc.gridy = y++;
562 panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);
563
564 gbc = GBC.std();
565 gbc.gridx = 0;
566 gbc.gridy = y;
567 panelTf.add(new JLabel(tr("Timezone: ")), gbc);
568
569 gbc = GBC.std().fill(GBC.HORIZONTAL);
570 gbc.gridx = 1;
571 gbc.gridy = y++;
572 gbc.weightx = 1.;
573 panelTf.add(tfTimezone, gbc);
574
575 gbc = GBC.std();
576 gbc.gridx = 0;
577 gbc.gridy = y;
578 panelTf.add(new JLabel(tr("Offset:")), gbc);
579
580 gbc = GBC.std().fill(GBC.HORIZONTAL);
581 gbc.gridx = 1;
582 gbc.gridy = y++;
583 gbc.weightx = 1.;
584 panelTf.add(tfOffset, gbc);
585
586 gbc = GBC.std().insets(5,5,5,5);
587 gbc.gridx = 2;
588 gbc.gridy = y-2;
589 gbc.gridheight = 2;
590 gbc.gridwidth = 2;
591 gbc.fill = GridBagConstraints.BOTH;
592 gbc.weightx = 0.5;
593 panelTf.add(buttonViewGpsPhoto, gbc);
594
595 gbc = GBC.std().fill(GBC.BOTH).insets(5,5,5,5);
596 gbc.gridx = 2;
597 gbc.gridy = y++;
598 gbc.weightx = 0.5;
599 panelTf.add(buttonAutoGuess, gbc);
600
601 gbc.gridx = 3;
602 panelTf.add(buttonAdjust, gbc);
603
604 gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0,12,0,0);
605 gbc.gridx = 0;
606 gbc.gridy = y++;
607 panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);
608
609 gbc = GBC.eol();
610 gbc.gridx = 0;
611 gbc.gridy = y++;
612 panelTf.add(labelPosition, gbc);
613
614 gbc = GBC.eol();
615 gbc.gridx = 1;
616 gbc.gridy = y++;
617 panelTf.add(cbExifImg, gbc);
618
619 gbc = GBC.eol();
620 gbc.gridx = 1;
621 gbc.gridy = y++;
622 panelTf.add(cbTaggedImg, gbc);
623
624 gbc = GBC.eol();
625 gbc.gridx = 0;
626 gbc.gridy = y++;
627 panelTf.add(cbShowThumbs, gbc);
628
629 final JPanel statusBar = new JPanel();
630 statusBar.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
631 statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
632 statusBarText = new JLabel(" ");
633 statusBarText.setFont(statusBarText.getFont().deriveFont(8));
634 statusBar.add(statusBarText);
635
636 tfTimezone.addFocusListener(repaintTheMap);
637 tfOffset.addFocusListener(repaintTheMap);
638
639 tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
640 tfOffset.getDocument().addDocumentListener(statusBarUpdater);
641 cbExifImg.addItemListener(statusBarUpdaterWithRepaint);
642 cbTaggedImg.addItemListener(statusBarUpdaterWithRepaint);
643
644 statusBarUpdater.updateStatusBar();
645
646 outerPanel = new JPanel();
647 outerPanel.setLayout(new BorderLayout());
648 outerPanel.add(statusBar, BorderLayout.PAGE_END);
649
650 syncDialog = new ExtendedDialog(
651 Main.parent,
652 tr("Correlate images with GPX track"),
653 new String[] { tr("Correlate"), tr("Cancel") },
654 false
655 );
656 syncDialog.setContent(panelTf, false);
657 syncDialog.setButtonIcons(new String[] { "ok.png", "cancel.png" });
658 syncDialog.setupDialog();
659 outerPanel.add(syncDialog.getContentPane(), BorderLayout.PAGE_START);
660 syncDialog.setContentPane(outerPanel);
661 syncDialog.pack();
662 syncDialog.addWindowListener(new WindowAdapter() {
663 final static int CANCEL = -1;
664 final static int DONE = 0;
665 final static int AGAIN = 1;
666 final static int NOTHING = 2;
667 private int checkAndSave() {
668 if (syncDialog.isVisible())
669 // nothing happened: JOSM was minimized or similar
670 return NOTHING;
671 int answer = syncDialog.getValue();
672 if(answer != 1)
673 return CANCEL;
674
675 // Parse values again, to display an error if the format is not recognized
676 try {
677 timezone = parseTimezone(tfTimezone.getText().trim());
678 } catch (ParseException e) {
679 JOptionPane.showMessageDialog(Main.parent, e.getMessage(),
680 tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE);
681 return AGAIN;
682 }
683
684 try {
685 delta = parseOffset(tfOffset.getText().trim());
686 } catch (ParseException e) {
687 JOptionPane.showMessageDialog(Main.parent, e.getMessage(),
688 tr("Invalid offset"), JOptionPane.ERROR_MESSAGE);
689 return AGAIN;
690 }
691
692 if (lastNumMatched == 0) {
693 if (new ExtendedDialog(
694 Main.parent,
695 tr("Correlate images with GPX track"),
696 new String[] { tr("OK"), tr("Try Again") }).
697 setContent(tr("No images could be matched!")).
698 setButtonIcons(new String[] { "ok.png", "dialogs/refresh.png"}).
699 showDialog().getValue() == 2)
700 return AGAIN;
701 }
702 return DONE;
703 }
704
705 @Override
706 public void windowDeactivated(WindowEvent e) {
707 int result = checkAndSave();
708 switch (result) {
709 case NOTHING:
710 break;
711 case CANCEL:
712 {
713 if (yLayer != null) {
714 for (ImageEntry ie : yLayer.data) {
715 ie.tmp = null;
716 }
717 yLayer.updateBufferAndRepaint();
718 }
719 break;
720 }
721 case AGAIN:
722 actionPerformed(null);
723 break;
724 case DONE:
725 {
726 Main.pref.put("geoimage.timezone", formatTimezone(timezone));
727 Main.pref.put("geoimage.delta", Long.toString(delta * 1000));
728 Main.pref.put("geoimage.showThumbs", yLayer.useThumbs);
729
730 yLayer.useThumbs = cbShowThumbs.isSelected();
731 yLayer.loadThumbs();
732
733 // Search whether an other layer has yet defined some bounding box.
734 // If none, we'll zoom to the bounding box of the layer with the photos.
735 boolean boundingBoxedLayerFound = false;
736 for (Layer l: Main.map.mapView.getAllLayers()) {
737 if (l != yLayer) {
738 BoundingXYVisitor bbox = new BoundingXYVisitor();
739 l.visitBoundingBox(bbox);
740 if (bbox.getBounds() != null) {
741 boundingBoxedLayerFound = true;
742 break;
743 }
744 }
745 }
746 if (! boundingBoxedLayerFound) {
747 BoundingXYVisitor bbox = new BoundingXYVisitor();
748 yLayer.visitBoundingBox(bbox);
749 Main.map.mapView.recalculateCenterScale(bbox);
750 }
751
752 for (ImageEntry ie : yLayer.data) {
753 ie.applyTmp();
754 }
755
756 yLayer.updateBufferAndRepaint();
757
758 break;
759 }
760 default:
761 throw new IllegalStateException();
762 }
763 }
764 });
765 syncDialog.showDialog();
766 }
767
768 StatusBarUpdater statusBarUpdater = new StatusBarUpdater(false);
769 StatusBarUpdater statusBarUpdaterWithRepaint = new StatusBarUpdater(true);
770
771 private class StatusBarUpdater implements DocumentListener, ItemListener, ActionListener {
772 private boolean doRepaint;
773
774 public StatusBarUpdater(boolean doRepaint) {
775 this.doRepaint = doRepaint;
776 }
777
778 @Override
779 public void insertUpdate(DocumentEvent ev) {
780 updateStatusBar();
781 }
782 @Override
783 public void removeUpdate(DocumentEvent ev) {
784 updateStatusBar();
785 }
786 @Override
787 public void changedUpdate(DocumentEvent ev) {
788 }
789 @Override
790 public void itemStateChanged(ItemEvent e) {
791 updateStatusBar();
792 }
793 @Override
794 public void actionPerformed(ActionEvent e) {
795 updateStatusBar();
796 }
797
798 public void updateStatusBar() {
799 statusBarText.setText(statusText());
800 if (doRepaint) {
801 yLayer.updateBufferAndRepaint();
802 }
803 }
804
805 private String statusText() {
806 try {
807 timezone = parseTimezone(tfTimezone.getText().trim());
808 delta = parseOffset(tfOffset.getText().trim());
809 } catch (ParseException e) {
810 return e.getMessage();
811 }
812
813 // The selection of images we are about to correlate may have changed.
814 // So reset all images.
815 for (ImageEntry ie: yLayer.data) {
816 ie.tmp = null;
817 }
818
819 // Construct a list of images that have a date, and sort them on the date.
820 ArrayList<ImageEntry> dateImgLst = getSortedImgList();
821 // Create a temporary copy for each image
822 for (ImageEntry ie : dateImgLst) {
823 ie.cleanTmp();
824 }
825
826 GpxDataWrapper selGpx = selectedGPX(false);
827 if (selGpx == null)
828 return tr("No gpx selected");
829
830 final long offset_ms = ((long) (timezone * 3600) + delta) * 1000; // in milliseconds
831 lastNumMatched = matchGpxTrack(dateImgLst, selGpx.data, offset_ms);
832
833 return trn("<html>Matched <b>{0}</b> of <b>{1}</b> photo to GPX track.</html>",
834 "<html>Matched <b>{0}</b> of <b>{1}</b> photos to GPX track.</html>",
835 dateImgLst.size(), lastNumMatched, dateImgLst.size());
836 }
837 }
838
839 RepaintTheMapListener repaintTheMap = new RepaintTheMapListener();
840 private class RepaintTheMapListener implements FocusListener {
841 @Override
842 public void focusGained(FocusEvent e) { // do nothing
843 }
844
845 @Override
846 public void focusLost(FocusEvent e) {
847 yLayer.updateBufferAndRepaint();
848 }
849 }
850
851 /**
852 * Presents dialog with sliders for manual adjust.
853 */
854 private class AdjustActionListener implements ActionListener {
855
856 @Override
857 public void actionPerformed(ActionEvent arg0) {
858
859 long diff = delta + Math.round(timezone*60*60);
860
861 double diffInH = (double)diff/(60*60); // hours
862
863 // Find day difference
864 final int dayOffset = (int)Math.round(diffInH / 24); // days
865 double tmz = diff - dayOffset*24*60*60L; // seconds
866
867 // In hours, rounded to two decimal places
868 tmz = (double)Math.round(tmz*100/(60*60)) / 100;
869
870 // Due to imprecise clocks we might get a "+3:28" timezone, which should obviously be 3:30 with
871 // -2 minutes offset. This determines the real timezone and finds offset.
872 double fixTimezone = (double)Math.round(tmz * 2)/2; // hours, rounded to one decimal place
873 int offset = (int)Math.round(diff - fixTimezone*60*60) - dayOffset*24*60*60; // seconds
874
875 // Info Labels
876 final JLabel lblMatches = new JLabel();
877
878 // Timezone Slider
879 // The slider allows to switch timezon from -12:00 to 12:00 in 30 minutes
880 // steps. Therefore the range is -24 to 24.
881 final JLabel lblTimezone = new JLabel();
882 final JSlider sldTimezone = new JSlider(-24, 24, 0);
883 sldTimezone.setPaintLabels(true);
884 Dictionary<Integer,JLabel> labelTable = new Hashtable<Integer, JLabel>();
885 labelTable.put(-24, new JLabel("-12:00"));
886 labelTable.put(-12, new JLabel( "-6:00"));
887 labelTable.put( 0, new JLabel( "0:00"));
888 labelTable.put( 12, new JLabel( "6:00"));
889 labelTable.put( 24, new JLabel( "12:00"));
890 sldTimezone.setLabelTable(labelTable);
891
892 // Minutes Slider
893 final JLabel lblMinutes = new JLabel();
894 final JSlider sldMinutes = new JSlider(-15, 15, 0);
895 sldMinutes.setPaintLabels(true);
896 sldMinutes.setMajorTickSpacing(5);
897
898 // Seconds slider
899 final JLabel lblSeconds = new JLabel();
900 final JSlider sldSeconds = new JSlider(-60, 60, 0);
901 sldSeconds.setPaintLabels(true);
902 sldSeconds.setMajorTickSpacing(30);
903
904 // This is called whenever one of the sliders is moved.
905 // It updates the labels and also calls the "match photos" code
906 class sliderListener implements ChangeListener {
907 @Override
908 public void stateChanged(ChangeEvent e) {
909 // parse slider position into real timezone
910 double tz = Math.abs(sldTimezone.getValue());
911 String zone = tz % 2 == 0
912 ? (int)Math.floor(tz/2) + ":00"
913 : (int)Math.floor(tz/2) + ":30";
914 if(sldTimezone.getValue() < 0) {
915 zone = "-" + zone;
916 }
917
918 lblTimezone.setText(tr("Timezone: {0}", zone));
919 lblMinutes.setText(tr("Minutes: {0}", sldMinutes.getValue()));
920 lblSeconds.setText(tr("Seconds: {0}", sldSeconds.getValue()));
921
922 try {
923 timezone = parseTimezone(zone);
924 } catch (ParseException pe) {
925 throw new RuntimeException();
926 }
927 delta = sldMinutes.getValue()*60 + sldSeconds.getValue();
928
929 tfTimezone.getDocument().removeDocumentListener(statusBarUpdater);
930 tfOffset.getDocument().removeDocumentListener(statusBarUpdater);
931
932 tfTimezone.setText(formatTimezone(timezone));
933 tfOffset.setText(Long.toString(delta + 24*60*60L*dayOffset)); // add the day offset to the offset field
934
935 tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
936 tfOffset.getDocument().addDocumentListener(statusBarUpdater);
937
938 lblMatches.setText(statusBarText.getText() + "<br>" + trn("(Time difference of {0} day)", "Time difference of {0} days", Math.abs(dayOffset), Math.abs(dayOffset)));
939
940 statusBarUpdater.updateStatusBar();
941 yLayer.updateBufferAndRepaint();
942 }
943 }
944
945 // Put everything together
946 JPanel p = new JPanel(new GridBagLayout());
947 p.setPreferredSize(new Dimension(400, 230));
948 p.add(lblMatches, GBC.eol().fill());
949 p.add(lblTimezone, GBC.eol().fill());
950 p.add(sldTimezone, GBC.eol().fill().insets(0, 0, 0, 10));
951 p.add(lblMinutes, GBC.eol().fill());
952 p.add(sldMinutes, GBC.eol().fill().insets(0, 0, 0, 10));
953 p.add(lblSeconds, GBC.eol().fill());
954 p.add(sldSeconds, GBC.eol().fill());
955
956 // If there's an error in the calculation the found values
957 // will be off range for the sliders. Catch this error
958 // and inform the user about it.
959 try {
960 sldTimezone.setValue((int)(fixTimezone*2));
961 sldMinutes.setValue(offset/60);
962 sldSeconds.setValue(offset%60);
963 } catch(Exception e) {
964 JOptionPane.showMessageDialog(Main.parent,
965 tr("An error occurred while trying to match the photos to the GPX track."
966 +" You can adjust the sliders to manually match the photos."),
967 tr("Matching photos to track failed"),
968 JOptionPane.WARNING_MESSAGE);
969 }
970
971 // Call the sliderListener once manually so labels get adjusted
972 new sliderListener().stateChanged(null);
973 // Listeners added here, otherwise it tries to match three times
974 // (when setting the default values)
975 sldTimezone.addChangeListener(new sliderListener());
976 sldMinutes.addChangeListener(new sliderListener());
977 sldSeconds.addChangeListener(new sliderListener());
978
979 // There is no way to cancel this dialog, all changes get applied
980 // immediately. Therefore "Close" is marked with an "OK" icon.
981 // Settings are only saved temporarily to the layer.
982 new ExtendedDialog(Main.parent,
983 tr("Adjust timezone and offset"),
984 new String[] { tr("Close")}).
985 setContent(p).setButtonIcons(new String[] {"ok.png"}).showDialog();
986 }
987 }
988
989 private class AutoGuessActionListener implements ActionListener {
990
991 @Override
992 public void actionPerformed(ActionEvent arg0) {
993 GpxDataWrapper gpxW = selectedGPX(true);
994 if (gpxW == null)
995 return;
996 GpxData gpx = gpxW.data;
997
998 ArrayList<ImageEntry> imgs = getSortedImgList();
999 PrimaryDateParser dateParser = new PrimaryDateParser();
1000
1001 // no images found, exit
1002 if(imgs.size() <= 0) {
1003 JOptionPane.showMessageDialog(Main.parent,
1004 tr("The selected photos do not contain time information."),
1005 tr("Photos do not contain time information"), JOptionPane.WARNING_MESSAGE);
1006 return;
1007 }
1008
1009 // Init variables
1010 long firstExifDate = imgs.get(0).getExifTime().getTime()/1000;
1011
1012 long firstGPXDate = -1;
1013 // Finds first GPX point
1014 outer: for (GpxTrack trk : gpx.tracks) {
1015 for (GpxTrackSegment segment : trk.getSegments()) {
1016 for (WayPoint curWp : segment.getWayPoints()) {
1017 String curDateWpStr = (String) curWp.attr.get("time");
1018 if (curDateWpStr == null) {
1019 continue;
1020 }
1021
1022 try {
1023 firstGPXDate = dateParser.parse(curDateWpStr).getTime()/1000;
1024 break outer;
1025 } catch(Exception e) {}
1026 }
1027 }
1028 }
1029
1030 // No GPX timestamps found, exit
1031 if(firstGPXDate < 0) {
1032 JOptionPane.showMessageDialog(Main.parent,
1033 tr("The selected GPX track does not contain timestamps. Please select another one."),
1034 tr("GPX Track has no time information"), JOptionPane.WARNING_MESSAGE);
1035 return;
1036 }
1037
1038 // seconds
1039 long diff = firstExifDate - firstGPXDate;
1040
1041 double diffInH = (double)diff/(60*60); // hours
1042
1043 // Find day difference
1044 int dayOffset = (int)Math.round(diffInH / 24); // days
1045 double tz = diff - dayOffset*24*60*60L; // seconds
1046
1047 // In hours, rounded to two decimal places
1048 tz = (double)Math.round(tz*100/(60*60)) / 100;
1049
1050 // Due to imprecise clocks we might get a "+3:28" timezone, which should obviously be 3:30 with
1051 // -2 minutes offset. This determines the real timezone and finds offset.
1052 timezone = (double)Math.round(tz * 2)/2; // hours, rounded to one decimal place
1053 delta = Math.round(diff - timezone*60*60); // seconds
1054
1055 /*System.out.println("phto " + firstExifDate);
1056 System.out.println("gpx " + firstGPXDate);
1057 System.out.println("diff " + diff);
1058 System.out.println("difh " + diffInH);
1059 System.out.println("days " + dayOffset);
1060 System.out.println("time " + tz);
1061 System.out.println("fix " + timezone);
1062 System.out.println("offt " + delta);*/
1063
1064 tfTimezone.getDocument().removeDocumentListener(statusBarUpdater);
1065 tfOffset.getDocument().removeDocumentListener(statusBarUpdater);
1066
1067 tfTimezone.setText(formatTimezone(timezone));
1068 tfOffset.setText(Long.toString(delta));
1069 tfOffset.requestFocus();
1070
1071 tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
1072 tfOffset.getDocument().addDocumentListener(statusBarUpdater);
1073
1074 statusBarUpdater.updateStatusBar();
1075 yLayer.updateBufferAndRepaint();
1076 }
1077 }
1078
1079 private ArrayList<ImageEntry> getSortedImgList() {
1080 return getSortedImgList(cbExifImg.isSelected(), cbTaggedImg.isSelected());
1081 }
1082
1083 /**
1084 * Returns a list of images that fulfill the given criteria.
1085 * Default setting is to return untagged images, but may be overwritten.
1086 * @param exif also returns images with exif-gps info
1087 * @param tagged also returns tagged images
1088 * @return matching images
1089 */
1090 private ArrayList<ImageEntry> getSortedImgList(boolean exif, boolean tagged) {
1091 ArrayList<ImageEntry> dateImgLst = new ArrayList<ImageEntry>(yLayer.data.size());
1092 for (ImageEntry e : yLayer.data) {
1093 if (e.getExifTime() == null) {
1094 continue;
1095 }
1096
1097 if (e.getExifCoor() != null) {
1098 if (!exif) {
1099 continue;
1100 }
1101 }
1102
1103 if (e.isTagged() && e.getExifCoor() == null) {
1104 if (!tagged) {
1105 continue;
1106 }
1107 }
1108
1109 dateImgLst.add(e);
1110 }
1111
1112 Collections.sort(dateImgLst, new Comparator<ImageEntry>() {
1113 @Override
1114 public int compare(ImageEntry arg0, ImageEntry arg1) {
1115 return arg0.getExifTime().compareTo(arg1.getExifTime());
1116 }
1117 });
1118
1119 return dateImgLst;
1120 }
1121
1122 private GpxDataWrapper selectedGPX(boolean complain) {
1123 Object item = cbGpx.getSelectedItem();
1124
1125 if (item == null || ((GpxDataWrapper) item).file == null) {
1126 if (complain) {
1127 JOptionPane.showMessageDialog(Main.parent, tr("You should select a GPX track"),
1128 tr("No selected GPX track"), JOptionPane.ERROR_MESSAGE );
1129 }
1130 return null;
1131 }
1132 return (GpxDataWrapper) item;
1133 }
1134
1135 /**
1136 * Match a list of photos to a gpx track with a given offset.
1137 * All images need a exifTime attribute and the List must be sorted according to these times.
1138 */
1139 private int matchGpxTrack(ArrayList<ImageEntry> images, GpxData selectedGpx, long offset) {
1140 int ret = 0;
1141
1142 PrimaryDateParser dateParser = new PrimaryDateParser();
1143
1144 for (GpxTrack trk : selectedGpx.tracks) {
1145 for (GpxTrackSegment segment : trk.getSegments()) {
1146
1147 long prevWpTime = 0;
1148 WayPoint prevWp = null;
1149
1150 for (WayPoint curWp : segment.getWayPoints()) {
1151
1152 String curWpTimeStr = (String) curWp.attr.get("time");
1153 if (curWpTimeStr != null) {
1154
1155 try {
1156 long curWpTime = dateParser.parse(curWpTimeStr).getTime() + offset;
1157 ret += matchPoints(images, prevWp, prevWpTime, curWp, curWpTime, offset);
1158
1159 prevWp = curWp;
1160 prevWpTime = curWpTime;
1161
1162 } catch(ParseException e) {
1163 System.err.println("Error while parsing date \"" + curWpTimeStr + '"');
1164 e.printStackTrace();
1165 prevWp = null;
1166 prevWpTime = 0;
1167 }
1168 } else {
1169 prevWp = null;
1170 prevWpTime = 0;
1171 }
1172 }
1173 }
1174 }
1175 return ret;
1176 }
1177
1178 private int matchPoints(ArrayList<ImageEntry> images, WayPoint prevWp, long prevWpTime,
1179 WayPoint curWp, long curWpTime, long offset) {
1180 // Time between the track point and the previous one, 5 sec if first point, i.e. photos take
1181 // 5 sec before the first track point can be assumed to be take at the starting position
1182 long interval = prevWpTime > 0 ? ((long)Math.abs(curWpTime - prevWpTime)) : 5*1000;
1183 int ret = 0;
1184
1185 // i is the index of the timewise last photo that has the same or earlier EXIF time
1186 int i = getLastIndexOfListBefore(images, curWpTime);
1187
1188 // no photos match
1189 if (i < 0)
1190 return 0;
1191
1192 Double speed = null;
1193 Double prevElevation = null;
1194 Double curElevation = null;
1195
1196 if (prevWp != null) {
1197 double distance = prevWp.getCoor().greatCircleDistance(curWp.getCoor());
1198 // This is in km/h, 3.6 * m/s
1199 if (curWpTime > prevWpTime) {
1200 speed = 3600 * distance / (curWpTime - prevWpTime);
1201 }
1202 try {
1203 prevElevation = new Double((String) prevWp.attr.get("ele"));
1204 } catch(Exception e) {}
1205 }
1206
1207 try {
1208 curElevation = new Double((String) curWp.attr.get("ele"));
1209 } catch (Exception e) {}
1210
1211 // First trackpoint, then interval is set to five seconds, i.e. photos up to five seconds
1212 // before the first point will be geotagged with the starting point
1213 if(prevWpTime == 0 || curWpTime <= prevWpTime) {
1214 while (true) {
1215 if (i < 0) {
1216 break;
1217 }
1218 final ImageEntry curImg = images.get(i);
1219 if (curImg.getExifTime().getTime() > curWpTime
1220 || curImg.getExifTime().getTime() < curWpTime - interval) {
1221 break;
1222 }
1223 if(curImg.tmp.getPos() == null) {
1224 curImg.tmp.setPos(curWp.getCoor());
1225 curImg.tmp.setSpeed(speed);
1226 curImg.tmp.setElevation(curElevation);
1227 curImg.tmp.setGpsTime(new Date(curImg.getExifTime().getTime() - offset));
1228 ret++;
1229 }
1230 i--;
1231 }
1232 return ret;
1233 }
1234
1235 // This code gives a simple linear interpolation of the coordinates between current and
1236 // previous track point assuming a constant speed in between
1237 while (true) {
1238 if (i < 0) {
1239 break;
1240 }
1241 ImageEntry curImg = images.get(i);
1242 long imgTime = curImg.getExifTime().getTime();
1243 if (imgTime < prevWpTime) {
1244 break;
1245 }
1246
1247 if(curImg.tmp.getPos() == null) {
1248 // The values of timeDiff are between 0 and 1, it is not seconds but a dimensionless
1249 // variable
1250 double timeDiff = (double)(imgTime - prevWpTime) / interval;
1251 curImg.tmp.setPos(prevWp.getCoor().interpolate(curWp.getCoor(), timeDiff));
1252 curImg.tmp.setSpeed(speed);
1253 if (curElevation != null && prevElevation != null) {
1254 curImg.tmp.setElevation(prevElevation + (curElevation - prevElevation) * timeDiff);
1255 }
1256 curImg.tmp.setGpsTime(new Date(curImg.getExifTime().getTime() - offset));
1257
1258 ret++;
1259 }
1260 i--;
1261 }
1262 return ret;
1263 }
1264
1265 private int getLastIndexOfListBefore(ArrayList<ImageEntry> images, long searchedTime) {
1266 int lstSize= images.size();
1267
1268 // No photos or the first photo taken is later than the search period
1269 if(lstSize == 0 || searchedTime < images.get(0).getExifTime().getTime())
1270 return -1;
1271
1272 // The search period is later than the last photo
1273 if (searchedTime > images.get(lstSize - 1).getExifTime().getTime())
1274 return lstSize-1;
1275
1276 // The searched index is somewhere in the middle, do a binary search from the beginning
1277 int curIndex= 0;
1278 int startIndex= 0;
1279 int endIndex= lstSize-1;
1280 while (endIndex - startIndex > 1) {
1281 curIndex= (endIndex + startIndex) / 2;
1282 if (searchedTime > images.get(curIndex).getExifTime().getTime()) {
1283 startIndex= curIndex;
1284 } else {
1285 endIndex= curIndex;
1286 }
1287 }
1288 if (searchedTime < images.get(endIndex).getExifTime().getTime())
1289 return startIndex;
1290
1291 // This final loop is to check if photos with the exact same EXIF time follows
1292 while ((endIndex < (lstSize-1)) && (images.get(endIndex).getExifTime().getTime()
1293 == images.get(endIndex + 1).getExifTime().getTime())) {
1294 endIndex++;
1295 }
1296 return endIndex;
1297 }
1298
1299 private String formatTimezone(double timezone) {
1300 StringBuffer ret = new StringBuffer();
1301
1302 if (timezone < 0) {
1303 ret.append('-');
1304 timezone = -timezone;
1305 } else {
1306 ret.append('+');
1307 }
1308 ret.append((long) timezone).append(':');
1309 int minutes = (int) ((timezone % 1) * 60);
1310 if (minutes < 10) {
1311 ret.append('0');
1312 }
1313 ret.append(minutes);
1314
1315 return ret.toString();
1316 }
1317
1318 private double parseTimezone(String timezone) throws ParseException {
1319
1320 String error = tr("Error while parsing timezone.\nExpected format: {0}", "+H:MM");
1321
1322 if (timezone.length() == 0)
1323 return 0;
1324
1325 char sgnTimezone = '+';
1326 StringBuffer hTimezone = new StringBuffer();
1327 StringBuffer mTimezone = new StringBuffer();
1328 int state = 1; // 1=start/sign, 2=hours, 3=minutes.
1329 for (int i = 0; i < timezone.length(); i++) {
1330 char c = timezone.charAt(i);
1331 switch (c) {
1332 case ' ' :
1333 if (state != 2 || hTimezone.length() != 0)
1334 throw new ParseException(error,0);
1335 break;
1336 case '+' :
1337 case '-' :
1338 if (state == 1) {
1339 sgnTimezone = c;
1340 state = 2;
1341 } else
1342 throw new ParseException(error,0);
1343 break;
1344 case ':' :
1345 case '.' :
1346 if (state == 2) {
1347 state = 3;
1348 } else
1349 throw new ParseException(error,0);
1350 break;
1351 case '0' : case '1' : case '2' : case '3' : case '4' :
1352 case '5' : case '6' : case '7' : case '8' : case '9' :
1353 switch(state) {
1354 case 1 :
1355 case 2 :
1356 state = 2;
1357 hTimezone.append(c);
1358 break;
1359 case 3 :
1360 mTimezone.append(c);
1361 break;
1362 default :
1363 throw new ParseException(error,0);
1364 }
1365 break;
1366 default :
1367 throw new ParseException(error,0);
1368 }
1369 }
1370
1371 int h = 0;
1372 int m = 0;
1373 try {
1374 h = Integer.parseInt(hTimezone.toString());
1375 if (mTimezone.length() > 0) {
1376 m = Integer.parseInt(mTimezone.toString());
1377 }
1378 } catch (NumberFormatException nfe) {
1379 // Invalid timezone
1380 throw new ParseException(error,0);
1381 }
1382
1383 if (h > 12 || m > 59 )
1384 throw new ParseException(error,0);
1385 else
1386 return (h + m / 60.0) * (sgnTimezone == '-' ? -1 : 1);
1387 }
1388
1389 private long parseOffset(String offset) throws ParseException {
1390 String error = tr("Error while parsing offset.\nExpected format: {0}", "number");
1391
1392 if (offset.length() > 0) {
1393 try {
1394 if(offset.startsWith("+")) {
1395 offset = offset.substring(1);
1396 }
1397 return Long.parseLong(offset);
1398 } catch(NumberFormatException nfe) {
1399 throw new ParseException(error,0);
1400 }
1401 } else
1402 return 0;
1403 }
1404}
Note: See TracBrowser for help on using the repository browser.