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

Last change on this file since 2627 was 2626, checked in by jttt, 14 years ago

Fixed some of the warnings found by FindBugs

  • Property svn:eol-style set to native
File size: 45.0 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// and the core JOSM source code (by Immanuel Scholz and others)
5
6package org.openstreetmap.josm.gui.layer.geoimage;
7
8import static org.openstreetmap.josm.tools.I18n.tr;
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.io.File;
19import java.io.FileInputStream;
20import java.io.IOException;
21import java.io.InputStream;
22import java.text.ParseException;
23import java.text.SimpleDateFormat;
24import java.util.ArrayList;
25import java.util.Collection;
26import java.util.Collections;
27import java.util.Comparator;
28import java.util.Date;
29import java.util.Hashtable;
30import java.util.Iterator;
31import java.util.List;
32import java.util.TimeZone;
33import java.util.Vector;
34import java.util.zip.GZIPInputStream;
35
36import javax.swing.AbstractListModel;
37import javax.swing.ButtonGroup;
38import javax.swing.JButton;
39import javax.swing.JCheckBox;
40import javax.swing.JComboBox;
41import javax.swing.JFileChooser;
42import javax.swing.JLabel;
43import javax.swing.JList;
44import javax.swing.JOptionPane;
45import javax.swing.JPanel;
46import javax.swing.JRadioButton;
47import javax.swing.JScrollPane;
48import javax.swing.JSlider;
49import javax.swing.JTextField;
50import javax.swing.ListSelectionModel;
51import javax.swing.event.ChangeEvent;
52import javax.swing.event.ChangeListener;
53import javax.swing.event.ListSelectionEvent;
54import javax.swing.event.ListSelectionListener;
55import javax.swing.filechooser.FileFilter;
56
57import org.openstreetmap.josm.Main;
58import org.openstreetmap.josm.data.gpx.GpxData;
59import org.openstreetmap.josm.data.gpx.GpxTrack;
60import org.openstreetmap.josm.data.gpx.WayPoint;
61import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
62import org.openstreetmap.josm.gui.ExtendedDialog;
63import org.openstreetmap.josm.gui.layer.GpxLayer;
64import org.openstreetmap.josm.gui.layer.Layer;
65import org.openstreetmap.josm.gui.layer.geoimage.GeoImageLayer.ImageEntry;
66import org.openstreetmap.josm.io.GpxReader;
67import org.openstreetmap.josm.tools.ExifReader;
68import org.openstreetmap.josm.tools.GBC;
69import org.openstreetmap.josm.tools.ImageProvider;
70import org.openstreetmap.josm.tools.PrimaryDateParser;
71import org.xml.sax.SAXException;
72
73
74/** This class displays the window to select the GPX file and the offset (timezone + delta).
75 * Then it correlates the images of the layer with that GPX file.
76 */
77public class CorrelateGpxWithImages implements ActionListener {
78
79 private static List<GpxData> loadedGpxData = new ArrayList<GpxData>();
80
81 public static class CorrelateParameters {
82 GpxData gpxData;
83 float timezone;
84 long offset;
85 }
86
87 GeoImageLayer yLayer = null;
88
89 private static class GpxDataWrapper {
90 String name;
91 GpxData data;
92 File file;
93
94 public GpxDataWrapper(String name, GpxData data, File file) {
95 this.name = name;
96 this.data = data;
97 this.file = file;
98 }
99
100 @Override
101 public String toString() {
102 return name;
103 }
104 }
105
106 Vector gpxLst = new Vector();
107 JPanel panel = null;
108 JComboBox cbGpx = null;
109 JTextField tfTimezone = null;
110 JTextField tfOffset = null;
111 JRadioButton rbAllImg = null;
112 JRadioButton rbUntaggedImg = null;
113 JRadioButton rbNoExifImg = null;
114
115 /** This class is called when the user doesn't find the GPX file he needs in the files that have
116 * been loaded yet. It displays a FileChooser dialog to select the GPX file to be loaded.
117 */
118 private class LoadGpxDataActionListener implements ActionListener {
119
120 public void actionPerformed(ActionEvent arg0) {
121 JFileChooser fc = new JFileChooser(Main.pref.get("lastDirectory"));
122 fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
123 fc.setAcceptAllFileFilterUsed(false);
124 fc.setMultiSelectionEnabled(false);
125 fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
126 fc.setFileFilter(new FileFilter(){
127 @Override public boolean accept(File f) {
128 return (f.isDirectory()
129 || f .getName().toLowerCase().endsWith(".gpx")
130 || f.getName().toLowerCase().endsWith(".gpx.gz"));
131 }
132 @Override public String getDescription() {
133 return tr("GPX Files (*.gpx *.gpx.gz)");
134 }
135 });
136 fc.showOpenDialog(Main.parent);
137 File sel = fc.getSelectedFile();
138 if (sel == null)
139 return;
140
141 try {
142 panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
143
144 Main.pref.put("lastDirectory", sel.getPath());
145
146 for (int i = gpxLst.size() - 1 ; i >= 0 ; i--) {
147 if (gpxLst.get(i) instanceof GpxDataWrapper) {
148 GpxDataWrapper wrapper = (GpxDataWrapper) gpxLst.get(i);
149 if (sel.equals(wrapper.file)) {
150 cbGpx.setSelectedIndex(i);
151 if (!sel.getName().equals(wrapper.name)) {
152 JOptionPane.showMessageDialog(
153 Main.parent,
154 tr("File {0} is loaded yet under the name \"{1}\"", sel.getName(), wrapper.name),
155 tr("Error"),
156 JOptionPane.ERROR_MESSAGE
157 );
158 }
159 return;
160 }
161 }
162 }
163 GpxData data = null;
164 try {
165 InputStream iStream;
166 if (sel.getName().toLowerCase().endsWith(".gpx.gz")) {
167 iStream = new GZIPInputStream(new FileInputStream(sel));
168 } else {
169 iStream = new FileInputStream(sel);
170 }
171 data = new GpxReader(iStream, sel).data;
172 data.storageFile = sel;
173
174 } catch (SAXException x) {
175 x.printStackTrace();
176 JOptionPane.showMessageDialog(
177 Main.parent,
178 tr("Error while parsing {0}",sel.getName())+": "+x.getMessage(),
179 tr("Error"),
180 JOptionPane.ERROR_MESSAGE
181 );
182 return;
183 } catch (IOException x) {
184 x.printStackTrace();
185 JOptionPane.showMessageDialog(
186 Main.parent,
187 tr("Could not read \"{0}\"",sel.getName())+"\n"+x.getMessage(),
188 tr("Error"),
189 JOptionPane.ERROR_MESSAGE
190 );
191 return;
192 }
193
194 loadedGpxData.add(data);
195 if (gpxLst.get(0) instanceof String) {
196 gpxLst.remove(0);
197 }
198 gpxLst.add(new GpxDataWrapper(sel.getName(), data, sel));
199 cbGpx.setSelectedIndex(cbGpx.getItemCount() - 1);
200 } finally {
201 panel.setCursor(Cursor.getDefaultCursor());
202 }
203 }
204 }
205
206 /** This action listener is called when the user has a photo of the time of his GPS receiver. It
207 * displays the list of photos of the layer, and upon selection displays the selected photo.
208 * From that photo, the user can key in the time of the GPS.
209 * Then values of timezone and delta are set.
210 * @author chris
211 *
212 */
213 private class SetOffsetActionListener implements ActionListener {
214 JPanel panel;
215 JLabel lbExifTime;
216 JTextField tfGpsTime;
217 JComboBox cbTimezones;
218 ImageDisplay imgDisp;
219 JList imgList;
220
221 public void actionPerformed(ActionEvent arg0) {
222 SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
223
224 panel = new JPanel();
225 panel.setLayout(new BorderLayout());
226 panel.add(new JLabel(tr("<html>Take a photo of your GPS receiver while it displays the time.<br>"
227 + "Display that photo here.<br>"
228 + "And then, simply capture the time you read on the photo and select a timezone<hr></html>")),
229 BorderLayout.NORTH);
230
231 imgDisp = new ImageDisplay();
232 imgDisp.setPreferredSize(new Dimension(300, 225));
233 panel.add(imgDisp, BorderLayout.CENTER);
234
235 JPanel panelTf = new JPanel();
236 panelTf.setLayout(new GridBagLayout());
237
238 GridBagConstraints gc = new GridBagConstraints();
239 gc.gridx = gc.gridy = 0;
240 gc.gridwidth = gc.gridheight = 1;
241 gc.weightx = gc.weighty = 0.0;
242 gc.fill = GridBagConstraints.NONE;
243 gc.anchor = GridBagConstraints.WEST;
244 panelTf.add(new JLabel(tr("Photo time (from exif):")), gc);
245
246 lbExifTime = new JLabel();
247 gc.gridx = 1;
248 gc.weightx = 1.0;
249 gc.fill = GridBagConstraints.HORIZONTAL;
250 gc.gridwidth = 2;
251 panelTf.add(lbExifTime, gc);
252
253 gc.gridx = 0;
254 gc.gridy = 1;
255 gc.gridwidth = gc.gridheight = 1;
256 gc.weightx = gc.weighty = 0.0;
257 gc.fill = GridBagConstraints.NONE;
258 gc.anchor = GridBagConstraints.WEST;
259 panelTf.add(new JLabel(tr("Gps time (read from the above photo): ")), gc);
260
261 tfGpsTime = new JTextField();
262 tfGpsTime.setEnabled(false);
263 tfGpsTime.setMinimumSize(new Dimension(150, tfGpsTime.getMinimumSize().height));
264 gc.gridx = 1;
265 gc.weightx = 1.0;
266 gc.fill = GridBagConstraints.HORIZONTAL;
267 panelTf.add(tfGpsTime, gc);
268
269 gc.gridx = 2;
270 gc.weightx = 0.2;
271 panelTf.add(new JLabel(tr(" [dd/mm/yyyy hh:mm:ss]")), gc);
272
273 gc.gridx = 0;
274 gc.gridy = 2;
275 gc.gridwidth = gc.gridheight = 1;
276 gc.weightx = gc.weighty = 0.0;
277 gc.fill = GridBagConstraints.NONE;
278 gc.anchor = GridBagConstraints.WEST;
279 panelTf.add(new JLabel(tr("I'm in the timezone of: ")), gc);
280
281 Vector vtTimezones = new Vector<String>();
282 String[] tmp = TimeZone.getAvailableIDs();
283
284 for (String tzStr : tmp) {
285 TimeZone tz = TimeZone.getTimeZone(tzStr);
286
287 String tzDesc = new StringBuffer(tzStr).append(" (")
288 .append(formatTimezone(tz.getRawOffset() / 3600000.0))
289 .append(')').toString();
290 vtTimezones.add(tzDesc);
291 }
292
293 Collections.sort(vtTimezones);
294
295 cbTimezones = new JComboBox(vtTimezones);
296
297 String tzId = Main.pref.get("geoimage.timezoneid", "");
298 TimeZone defaultTz;
299 if (tzId.length() == 0) {
300 defaultTz = TimeZone.getDefault();
301 } else {
302 defaultTz = TimeZone.getTimeZone(tzId);
303 }
304
305 cbTimezones.setSelectedItem(new StringBuffer(defaultTz.getID()).append(" (")
306 .append(formatTimezone(defaultTz.getRawOffset() / 3600000.0))
307 .append(')').toString());
308
309 gc.gridx = 1;
310 gc.weightx = 1.0;
311 gc.gridwidth = 2;
312 gc.fill = GridBagConstraints.HORIZONTAL;
313 panelTf.add(cbTimezones, gc);
314
315 panel.add(panelTf, BorderLayout.SOUTH);
316
317 JPanel panelLst = new JPanel();
318 panelLst.setLayout(new BorderLayout());
319
320 imgList = new JList(new AbstractListModel() {
321 public Object getElementAt(int i) {
322 return yLayer.data.get(i).file.getName();
323 }
324
325 public int getSize() {
326 return yLayer.data.size();
327 }
328 });
329 imgList.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
330 imgList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
331
332 public void valueChanged(ListSelectionEvent arg0) {
333 int index = imgList.getSelectedIndex();
334 imgDisp.setImage(yLayer.data.get(index).file);
335 Date date = yLayer.data.get(index).time;
336 if (date != null) {
337 lbExifTime.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date));
338 tfGpsTime.setText(new SimpleDateFormat("dd/MM/yyyy ").format(date));
339 tfGpsTime.setCaretPosition(tfGpsTime.getText().length());
340 tfGpsTime.setEnabled(true);
341 } else {
342 lbExifTime.setText(tr("No date"));
343 tfGpsTime.setText("");
344 tfGpsTime.setEnabled(false);
345 }
346 }
347
348 });
349 panelLst.add(new JScrollPane(imgList), BorderLayout.CENTER);
350
351 JButton openButton = new JButton(tr("Open an other photo"));
352 openButton.addActionListener(new ActionListener() {
353
354 public void actionPerformed(ActionEvent arg0) {
355 JFileChooser fc = new JFileChooser(Main.pref.get("geoimage.lastdirectory"));
356 fc.setAcceptAllFileFilterUsed(false);
357 fc.setMultiSelectionEnabled(false);
358 fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
359 fc.setFileFilter(JpegFileFilter.getInstance());
360 fc.showOpenDialog(Main.parent);
361 File sel = fc.getSelectedFile();
362 if (sel == null)
363 return;
364
365 imgDisp.setImage(sel);
366
367 Date date = null;
368 try {
369 date = ExifReader.readTime(sel);
370 } catch (Exception e) {
371 }
372 if (date != null) {
373 lbExifTime.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date));
374 tfGpsTime.setText(new SimpleDateFormat("dd/MM/yyyy ").format(date));
375 tfGpsTime.setEnabled(true);
376 } else {
377 lbExifTime.setText(tr("No date"));
378 tfGpsTime.setText("");
379 tfGpsTime.setEnabled(false);
380 }
381 }
382 });
383 panelLst.add(openButton, BorderLayout.PAGE_END);
384
385 panel.add(panelLst, BorderLayout.LINE_START);
386
387 boolean isOk = false;
388 while (! isOk) {
389 int answer = JOptionPane.showConfirmDialog(
390 Main.parent, panel,
391 tr("Synchronize time from a photo of the GPS receiver"),
392 JOptionPane.OK_CANCEL_OPTION,
393 JOptionPane.QUESTION_MESSAGE
394 );
395 if (answer == JOptionPane.CANCEL_OPTION)
396 return;
397
398 long delta;
399
400 try {
401 delta = dateFormat.parse(lbExifTime.getText()).getTime()
402 - dateFormat.parse(tfGpsTime.getText()).getTime();
403 } catch(ParseException e) {
404 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing the date.\n"
405 + "Please use the requested format"),
406 tr("Invalid date"), JOptionPane.ERROR_MESSAGE );
407 continue;
408 }
409
410 String selectedTz = (String) cbTimezones.getSelectedItem();
411 int pos = selectedTz.lastIndexOf('(');
412 tzId = selectedTz.substring(0, pos - 1);
413 String tzValue = selectedTz.substring(pos + 1, selectedTz.length() - 1);
414
415 Main.pref.put("geoimage.timezoneid", tzId);
416 tfOffset.setText(Long.toString(delta / 1000));
417 tfTimezone.setText(tzValue);
418
419 isOk = true;
420
421 }
422
423 }
424 }
425
426 public CorrelateGpxWithImages(GeoImageLayer layer) {
427 this.yLayer = layer;
428 }
429
430 public void actionPerformed(ActionEvent arg0) {
431 // Construct the list of loaded GPX tracks
432 Collection<Layer> layerLst = Main.main.map.mapView.getAllLayers();
433 Iterator<Layer> iterLayer = layerLst.iterator();
434 while (iterLayer.hasNext()) {
435 Layer cur = iterLayer.next();
436 if (cur instanceof GpxLayer) {
437 gpxLst.add(new GpxDataWrapper(((GpxLayer) cur).getName(),
438 ((GpxLayer) cur).data,
439 ((GpxLayer) cur).data.storageFile));
440 }
441 }
442 for (GpxData data : loadedGpxData) {
443 gpxLst.add(new GpxDataWrapper(data.storageFile.getName(),
444 data,
445 data.storageFile));
446 }
447
448 if (gpxLst.size() == 0) {
449 gpxLst.add(tr("<No GPX track loaded yet>"));
450 }
451
452 JPanel panelCb = new JPanel();
453 panelCb.setLayout(new FlowLayout());
454
455 panelCb.add(new JLabel(tr("GPX track: ")));
456
457 cbGpx = new JComboBox(gpxLst);
458 panelCb.add(cbGpx);
459
460 JButton buttonOpen = new JButton(tr("Open another GPX trace"));
461 buttonOpen.setIcon(ImageProvider.get("dialogs/geoimage/geoimage-open"));
462 buttonOpen.addActionListener(new LoadGpxDataActionListener());
463
464 panelCb.add(buttonOpen);
465
466 JPanel panelTf = new JPanel();
467 panelTf.setLayout(new GridBagLayout());
468
469 GridBagConstraints gc = new GridBagConstraints();
470 gc.anchor = GridBagConstraints.WEST;
471
472 gc.gridx = gc.gridy = 0;
473 gc.gridwidth = gc.gridheight = 1;
474 gc.fill = GridBagConstraints.NONE;
475 gc.weightx = gc.weighty = 0.0;
476 panelTf.add(new JLabel(tr("Timezone: ")), gc);
477
478 float gpstimezone = Float.parseFloat(Main.pref.get("geoimage.doublegpstimezone", "0.0"));
479 if (gpstimezone == 0.0) {
480 gpstimezone = - Long.parseLong(Main.pref.get("geoimage.gpstimezone", "0"));
481 }
482 tfTimezone = new JTextField();
483 tfTimezone.setText(formatTimezone(gpstimezone));
484
485 gc.gridx = 1;
486 gc.gridy = 0;
487 gc.gridwidth = gc.gridheight = 1;
488 gc.fill = GridBagConstraints.HORIZONTAL;
489 gc.weightx = 1.0;
490 gc.weighty = 0.0;
491 panelTf.add(tfTimezone, gc);
492
493 gc.gridx = 0;
494 gc.gridy = 1;
495 gc.gridwidth = gc.gridheight = 1;
496 gc.fill = GridBagConstraints.NONE;
497 gc.weightx = gc.weighty = 0.0;
498 panelTf.add(new JLabel(tr("Offset:")), gc);
499
500 long delta = Long.parseLong(Main.pref.get("geoimage.delta", "0")) / 1000;
501 tfOffset = new JTextField();
502 tfOffset.setText(Long.toString(delta));
503 gc.gridx = gc.gridy = 1;
504 gc.gridwidth = gc.gridheight = 1;
505 gc.fill = GridBagConstraints.HORIZONTAL;
506 gc.weightx = 1.0;
507 gc.weighty = 0.0;
508 panelTf.add(tfOffset, gc);
509
510 JButton buttonViewGpsPhoto = new JButton(tr("<html>I can take a picture of my GPS receiver.<br>"
511 + "Can this help?</html>"));
512 buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener());
513 gc.gridx = 2;
514 gc.gridy = 0;
515 gc.gridwidth = 1;
516 gc.gridheight = 2;
517 gc.fill = GridBagConstraints.BOTH;
518 gc.weightx = 0.5;
519 gc.weighty = 1.0;
520 panelTf.add(buttonViewGpsPhoto, gc);
521
522 gc.gridx = 0;
523 gc.gridy = 2;
524 gc.gridwidth = gc.gridheight = 1;
525 gc.fill = GridBagConstraints.NONE;
526 gc.weightx = gc.weighty = 0.0;
527 panelTf.add(new JLabel(tr("Update position for: ")), gc);
528
529 gc.gridx = 1;
530 gc.gridy = 2;
531 gc.gridwidth = 2;
532 gc.gridheight = 1;
533 gc.fill = GridBagConstraints.HORIZONTAL;
534 gc.weightx = 1.0;
535 gc.weighty = 0.0;
536 rbAllImg = new JRadioButton(tr("All images"));
537 panelTf.add(rbAllImg, gc);
538
539 gc.gridx = 1;
540 gc.gridy = 3;
541 gc.gridwidth = 2;
542 gc.gridheight = 1;
543 gc.fill = GridBagConstraints.HORIZONTAL;
544 gc.weightx = 1.0;
545 gc.weighty = 0.0;
546 rbNoExifImg = new JRadioButton(tr("Images with no exif position"));
547 panelTf.add(rbNoExifImg, gc);
548
549 gc.gridx = 1;
550 gc.gridy = 4;
551 gc.gridwidth = 2;
552 gc.gridheight = 1;
553 gc.fill = GridBagConstraints.HORIZONTAL;
554 gc.weightx = 1.0;
555 gc.weighty = 0.0;
556 rbUntaggedImg = new JRadioButton(tr("Not yet tagged images"));
557 panelTf.add(rbUntaggedImg, gc);
558
559 gc.gridx = 0;
560 gc.gridy = 5;
561 gc.gridwidth = 2;
562 gc.gridheight = 1;
563 gc.fill = GridBagConstraints.NONE;
564 gc.weightx = gc.weighty = 0.0;
565 yLayer.useThumbs = Main.pref.getBoolean("geoimage.showThumbs", false);
566 JCheckBox cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), yLayer.useThumbs);
567 panelTf.add(cbShowThumbs, gc);
568
569 ButtonGroup group = new ButtonGroup();
570 group.add(rbAllImg);
571 group.add(rbNoExifImg);
572 group.add(rbUntaggedImg);
573
574 rbUntaggedImg.setSelected(true);
575
576 panel = new JPanel();
577 panel.setLayout(new BorderLayout());
578
579 panel.add(panelCb, BorderLayout.PAGE_START);
580 panel.add(panelTf, BorderLayout.CENTER);
581
582 boolean isOk = false;
583 GpxDataWrapper selectedGpx = null;
584 while (! isOk) {
585 ExtendedDialog dialog = new ExtendedDialog(
586 Main.parent,
587 tr("Correlate images with GPX track"),
588 new String[] { tr("Correlate"), tr("Auto-Guess"), tr("Cancel") }
589 );
590
591 dialog.setContent(panel);
592 dialog.setButtonIcons(new String[] { "ok.png", "dialogs/geoimage/gpx2imgManual.png", "cancel.png" });
593 dialog.showDialog();
594 int answer = dialog.getValue();
595 if(answer != 1 && answer != 2)
596 return;
597
598 // Check the selected values
599 Object item = cbGpx.getSelectedItem();
600
601 if (item == null || ! (item instanceof GpxDataWrapper)) {
602 JOptionPane.showMessageDialog(Main.parent, tr("You should select a GPX track"),
603 tr("No selected GPX track"), JOptionPane.ERROR_MESSAGE );
604 continue;
605 }
606 selectedGpx = ((GpxDataWrapper) item);
607
608 if (answer == 2) {
609 autoGuess(selectedGpx.data);
610 return;
611 }
612
613 Float timezoneValue = parseTimezone(tfTimezone.getText().trim());
614 if (timezoneValue == null) {
615 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing timezone.\nExpected format: {0}", "+H:MM"),
616 tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE);
617 continue;
618 }
619 gpstimezone = timezoneValue.floatValue();
620
621 String deltaText = tfOffset.getText().trim();
622 if (deltaText.length() > 0) {
623 try {
624 if(deltaText.startsWith("+")) {
625 deltaText = deltaText.substring(1);
626 }
627 delta = Long.parseLong(deltaText);
628 } catch(NumberFormatException nfe) {
629 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing offset.\nExpected format: {0}", "number"),
630 tr("Invalid offset"), JOptionPane.ERROR_MESSAGE);
631 continue;
632 }
633 } else {
634 delta = 0;
635 }
636
637 yLayer.useThumbs = cbShowThumbs.isSelected();
638
639 Main.pref.put("geoimage.doublegpstimezone", Double.toString(gpstimezone));
640 Main.pref.put("geoimage.gpstimezone", Long.toString(- ((long) gpstimezone)));
641 Main.pref.put("geoimage.delta", Long.toString(delta * 1000));
642 Main.pref.put("geoimage.showThumbs", yLayer.useThumbs);
643 isOk = true;
644
645 if (yLayer.useThumbs) {
646 yLayer.thumbsloader = new ThumbsLoader(yLayer);
647 Thread t = new Thread(yLayer.thumbsloader);
648 t.setPriority(Thread.MIN_PRIORITY);
649 t.start();
650 }
651
652 }
653
654 // Construct a list of images that have a date, and sort them on the date.
655 ArrayList<ImageEntry> dateImgLst = getSortedImgList(rbAllImg.isSelected(), rbNoExifImg.isSelected());
656
657 int matched = matchGpxTrack(dateImgLst, selectedGpx.data, (long) (gpstimezone * 3600) + delta);
658
659 // Search whether an other layer has yet defined some bounding box.
660 // If none, we'll zoom to the bounding box of the layer with the photos.
661 boolean boundingBoxedLayerFound = false;
662 for (Layer l: Main.map.mapView.getAllLayers()) {
663 if (l != yLayer) {
664 BoundingXYVisitor bbox = new BoundingXYVisitor();
665 l.visitBoundingBox(bbox);
666 if (bbox.getBounds() != null) {
667 boundingBoxedLayerFound = true;
668 break;
669 }
670 }
671 }
672 if (! boundingBoxedLayerFound) {
673 BoundingXYVisitor bbox = new BoundingXYVisitor();
674 yLayer.visitBoundingBox(bbox);
675 Main.map.mapView.recalculateCenterScale(bbox);
676 }
677
678 Main.map.repaint();
679
680 JOptionPane.showMessageDialog(Main.parent, tr("Found {0} matches of {1} in GPX track {2}", matched, dateImgLst.size(), selectedGpx.name),
681 tr("GPX Track loaded"),
682 ((dateImgLst.size() > 0 && matched == 0) ? JOptionPane.WARNING_MESSAGE
683 : JOptionPane.INFORMATION_MESSAGE));
684
685 }
686
687 // These variables all belong to "auto guess" but need to be accessible
688 // from the slider change listener
689 private int dayOffset;
690 private JLabel lblMatches;
691 private JLabel lblOffset;
692 private JLabel lblTimezone;
693 private JLabel lblMinutes;
694 private JLabel lblSeconds;
695 private JSlider sldTimezone;
696 private JSlider sldMinutes;
697 private JSlider sldSeconds;
698 private GpxData autoGpx;
699 private ArrayList<ImageEntry> autoImgs;
700 private long firstGPXDate = -1;
701 private long firstExifDate = -1;
702
703 /**
704 * Tries to automatically match opened photos to a given GPX track. Changes are applied
705 * immediately. Presents dialog with sliders for manual adjust.
706 * @param GpxData The GPX track to match against
707 */
708 private void autoGuess(GpxData gpx) {
709 autoGpx = gpx;
710 autoImgs = getSortedImgList(true, false);
711 PrimaryDateParser dateParser = new PrimaryDateParser();
712
713 // no images found, exit
714 if(autoImgs.size() <= 0) {
715 JOptionPane.showMessageDialog(Main.parent,
716 tr("The selected photos don't contain time information."),
717 tr("Photos don't contain time information"), JOptionPane.WARNING_MESSAGE);
718 return;
719 }
720
721 ImageViewerDialog dialog = ImageViewerDialog.getInstance();
722 dialog.showDialog();
723 // Will show first photo if none is selected yet
724 if(!dialog.hasImage()) {
725 yLayer.showNextPhoto();
726 // FIXME: If the dialog is minimized it will not be maximized. ToggleDialog is
727 // in need of a complete re-write to allow this in a reasonable way.
728 }
729
730 // Init variables
731 firstExifDate = autoImgs.get(0).time.getTime()/1000;
732
733
734 // Finds first GPX point
735 outer: for (GpxTrack trk : gpx.tracks) {
736 for (Collection<WayPoint> segment : trk.trackSegs) {
737 for (WayPoint curWp : segment) {
738 String curDateWpStr = (String) curWp.attr.get("time");
739 if (curDateWpStr == null) {
740 continue;
741 }
742
743 try {
744 firstGPXDate = dateParser.parse(curDateWpStr).getTime()/1000;
745 break outer;
746 } catch(Exception e) {}
747 }
748 }
749 }
750
751 // No GPX timestamps found, exit
752 if(firstGPXDate < 0) {
753 JOptionPane.showMessageDialog(Main.parent,
754 tr("The selected GPX track doesn't contain timestamps. Please select another one."),
755 tr("GPX Track has no time information"), JOptionPane.WARNING_MESSAGE);
756 return;
757 }
758
759 // seconds
760 long diff = (yLayer.hasTimeoffset)
761 ? yLayer.timeoffset
762 : firstExifDate - firstGPXDate;
763 yLayer.timeoffset = diff;
764 yLayer.hasTimeoffset = true;
765
766 double diffInH = (double)diff/(60*60); // hours
767
768 // Find day difference
769 dayOffset = (int)Math.round(diffInH / 24); // days
770 double timezone = diff - dayOffset*24*60*60; // seconds
771
772 // In hours, rounded to two decimal places
773 timezone = (double)Math.round(timezone*100/(60*60)) / 100;
774
775 // Due to imprecise clocks we might get a "+3:28" timezone, which should obviously be 3:30 with
776 // -2 minutes offset. This determines the real timezone and finds offset.
777 double fixTimezone = (double)Math.round(timezone * 2)/2; // hours, rounded to one decimal place
778 int offset = (int)Math.round(diff - fixTimezone*60*60) - dayOffset*24*60*60; // seconds
779
780 /*System.out.println("phto " + firstExifDate);
781 System.out.println("gpx " + firstGPXDate);
782 System.out.println("diff " + diff);
783 System.out.println("difh " + diffInH);
784 System.out.println("days " + dayOffset);
785 System.out.println("time " + timezone);
786 System.out.println("fix " + fixTimezone);
787 System.out.println("offt " + offset);*/
788
789 // This is called whenever one of the sliders is moved.
790 // It updates the labels and also calls the "match photos" code
791 class sliderListener implements ChangeListener {
792 public void stateChanged(ChangeEvent e) {
793 // parse slider position into real timezone
794 double tz = Math.abs(sldTimezone.getValue());
795 String zone = tz % 2 == 0
796 ? (int)Math.floor(tz/2) + ":00"
797 : (int)Math.floor(tz/2) + ":30";
798 if(sldTimezone.getValue() < 0) {
799 zone = "-" + zone;
800 }
801
802 lblTimezone.setText(tr("Timezone: {0}", zone));
803 lblMinutes.setText(tr("Minutes: {0}", sldMinutes.getValue()));
804 lblSeconds.setText(tr("Seconds: {0}", sldSeconds.getValue()));
805
806 float gpstimezone = parseTimezone(zone).floatValue();
807
808 // Reset previous position
809 for(ImageEntry x : autoImgs) {
810 x.pos = null;
811 }
812
813 long timediff = (long) (gpstimezone * 3600)
814 + dayOffset*24*60*60
815 + sldMinutes.getValue()*60
816 + sldSeconds.getValue();
817
818 int matched = matchGpxTrack(autoImgs, autoGpx, timediff);
819
820 lblMatches.setText(
821 tr("Matched {0} of {1} photos to GPX track.", matched, autoImgs.size())
822 + ((Math.abs(dayOffset) == 0)
823 ? ""
824 : " " + tr("(Time difference of {0} days)", Math.abs(dayOffset))
825 )
826 );
827
828 int offset = (int)(firstGPXDate+timediff-firstExifDate);
829 int o = Math.abs(offset);
830 lblOffset.setText(
831 tr("Offset between track and photos: {0}m {1}s",
832 (offset < 0 ? "-" : "") + Long.toString(o/60),
833 Long.toString(o%60)
834 )
835 );
836
837 yLayer.timeoffset = timediff;
838 Main.main.map.repaint();
839 }
840 }
841
842 // Info Labels
843 lblMatches = new JLabel();
844 lblOffset = new JLabel();
845
846 // Timezone Slider
847 // The slider allows to switch timezon from -12:00 to 12:00 in 30 minutes
848 // steps. Therefore the range is -24 to 24.
849 lblTimezone = new JLabel();
850 sldTimezone = new JSlider(-24, 24, 0);
851 sldTimezone.setPaintLabels(true);
852 Hashtable<Integer,JLabel> labelTable = new Hashtable<Integer, JLabel>();
853 labelTable.put(-24, new JLabel("-12:00"));
854 labelTable.put(-12, new JLabel( "-6:00"));
855 labelTable.put( 0, new JLabel( "0:00"));
856 labelTable.put( 12, new JLabel( "6:00"));
857 labelTable.put( 24, new JLabel( "12:00"));
858 sldTimezone.setLabelTable(labelTable);
859
860 // Minutes Slider
861 lblMinutes = new JLabel();
862 sldMinutes = new JSlider(-15, 15, 0);
863 sldMinutes.setPaintLabels(true);
864 sldMinutes.setMajorTickSpacing(5);
865
866 // Seconds slider
867 lblSeconds = new JLabel();
868 sldSeconds = new JSlider(-60, 60, 0);
869 sldSeconds.setPaintLabels(true);
870 sldSeconds.setMajorTickSpacing(30);
871
872 // Put everything together
873 JPanel p = new JPanel(new GridBagLayout());
874 p.setPreferredSize(new Dimension(400, 230));
875 p.add(lblMatches, GBC.eol().fill());
876 p.add(lblOffset, GBC.eol().fill().insets(0, 0, 0, 10));
877 p.add(lblTimezone, GBC.eol().fill());
878 p.add(sldTimezone, GBC.eol().fill().insets(0, 0, 0, 10));
879 p.add(lblMinutes, GBC.eol().fill());
880 p.add(sldMinutes, GBC.eol().fill().insets(0, 0, 0, 10));
881 p.add(lblSeconds, GBC.eol().fill());
882 p.add(sldSeconds, GBC.eol().fill());
883
884 // If there's an error in the calculation the found values
885 // will be off range for the sliders. Catch this error
886 // and inform the user about it.
887 try {
888 sldTimezone.setValue((int)(fixTimezone*2));
889 sldMinutes.setValue(offset/60);
890 sldSeconds.setValue(offset%60);
891 } catch(Exception e) {
892 JOptionPane.showMessageDialog(Main.parent,
893 tr("An error occurred while trying to match the photos to the GPX track."
894 +" You can adjust the sliders to manually match the photos."),
895 tr("Matching photos to track failed"),
896 JOptionPane.WARNING_MESSAGE);
897 }
898
899 // Call the sliderListener once manually so labels get adjusted
900 new sliderListener().stateChanged(null);
901 // Listeners added here, otherwise it tries to match three times
902 // (when setting the default values)
903 sldTimezone.addChangeListener(new sliderListener());
904 sldMinutes.addChangeListener(new sliderListener());
905 sldSeconds.addChangeListener(new sliderListener());
906
907 // There is no way to cancel this dialog, all changes get applied
908 // immediately. Therefore "Close" is marked with an "OK" icon.
909 // Settings are only saved temporarily to the layer.
910 ExtendedDialog d = new ExtendedDialog(Main.parent,
911 tr("Adjust timezone and offset"),
912 new String[] { tr("Close"), tr("Default Values") }
913 );
914
915 d.setContent(p);
916 d.setButtonIcons(new String[] { "ok.png", "dialogs/refresh.png"});
917 d.showDialog();
918 int answer = d.getValue();
919 // User wants default values; discard old result and re-open dialog
920 if(answer == 2) {
921 yLayer.hasTimeoffset = false;
922 autoGuess(gpx);
923 }
924 }
925
926 /**
927 * Returns a list of images that fulfill the given criteria.
928 * Default setting is to return untagged images, but may be overwritten.
929 * @param boolean all -- returns all available images
930 * @param boolean noexif -- returns untagged images without EXIF-GPS coords
931 * @return ArrayList<ImageEntry> matching images
932 */
933 private ArrayList<ImageEntry> getSortedImgList(boolean all, boolean noexif) {
934 ArrayList<ImageEntry> dateImgLst = new ArrayList<ImageEntry>(yLayer.data.size());
935 if (all) {
936 for (ImageEntry e : yLayer.data) {
937 if (e.time != null) {
938 // Reset previous position
939 e.pos = null;
940 dateImgLst.add(e);
941 }
942 }
943
944 } else if (noexif) {
945 for (ImageEntry e : yLayer.data) {
946 if (e.time != null && e.exifCoor == null) {
947 dateImgLst.add(e);
948 }
949 }
950
951 } else {
952 for (ImageEntry e : yLayer.data) {
953 if (e.time != null && e.pos == null) {
954 dateImgLst.add(e);
955 }
956 }
957 }
958
959 Collections.sort(dateImgLst, new Comparator<ImageEntry>() {
960 public int compare(ImageEntry arg0, ImageEntry arg1) {
961 return arg0.time.compareTo(arg1.time);
962 }
963 });
964
965 return dateImgLst;
966 }
967
968 private int matchGpxTrack(ArrayList<ImageEntry> dateImgLst, GpxData selectedGpx, long offset) {
969 int ret = 0;
970
971 PrimaryDateParser dateParser = new PrimaryDateParser();
972
973 for (GpxTrack trk : selectedGpx.tracks) {
974 for (Collection<WayPoint> segment : trk.trackSegs) {
975
976 long prevDateWp = 0;
977 WayPoint prevWp = null;
978
979 for (WayPoint curWp : segment) {
980
981 String curDateWpStr = (String) curWp.attr.get("time");
982 if (curDateWpStr != null) {
983
984 try {
985 long curDateWp = dateParser.parse(curDateWpStr).getTime()/1000 + offset;
986 ret += matchPoints(dateImgLst, prevWp, prevDateWp, curWp, curDateWp);
987
988 prevWp = curWp;
989 prevDateWp = curDateWp;
990
991 } catch(ParseException e) {
992 System.err.println("Error while parsing date \"" + curDateWpStr + '"');
993 e.printStackTrace();
994 prevWp = null;
995 prevDateWp = 0;
996 }
997 } else {
998 prevWp = null;
999 prevDateWp = 0;
1000 }
1001 }
1002 }
1003 }
1004 return ret;
1005 }
1006
1007 private int matchPoints(ArrayList<ImageEntry> dateImgLst, WayPoint prevWp, long prevDateWp,
1008 WayPoint curWp, long curDateWp) {
1009 // Time between the track point and the previous one, 5 sec if first point, i.e. photos take
1010 // 5 sec before the first track point can be assumed to be take at the starting position
1011 long interval = prevDateWp > 0 ? ((int)Math.abs(curDateWp - prevDateWp)) : 5;
1012 int ret = 0;
1013
1014 // i is the index of the timewise last photo that has the same or earlier EXIF time
1015 int i = getLastIndexOfListBefore(dateImgLst, curDateWp);
1016
1017 // no photos match
1018 if (i < 0)
1019 return 0;
1020
1021 Double speed = null;
1022 Double prevElevation = null;
1023 Double curElevation = null;
1024
1025 if (prevWp != null) {
1026 double distance = prevWp.getCoor().greatCircleDistance(curWp.getCoor());
1027 // This is in km/h, 3.6 * m/s
1028 if (curDateWp > prevDateWp) {
1029 speed = 3.6 * distance / (curDateWp - prevDateWp);
1030 }
1031 try {
1032 prevElevation = new Double((String) prevWp.attr.get("ele"));
1033 } catch(Exception e) {}
1034 }
1035
1036 try {
1037 curElevation = new Double((String) curWp.attr.get("ele"));
1038 } catch (Exception e) {}
1039
1040 // First trackpoint, then interval is set to five seconds, i.e. photos up to five seconds
1041 // before the first point will be geotagged with the starting point
1042 if(prevDateWp == 0 || curDateWp <= prevDateWp) {
1043 while(i >= 0 && (dateImgLst.get(i).time.getTime()/1000) <= curDateWp
1044 && (dateImgLst.get(i).time.getTime()/1000) >= (curDateWp - interval)) {
1045 if(dateImgLst.get(i).pos == null) {
1046 dateImgLst.get(i).setCoor(curWp.getCoor());
1047 dateImgLst.get(i).speed = speed;
1048 dateImgLst.get(i).elevation = curElevation;
1049 ret++;
1050 }
1051 i--;
1052 }
1053 return ret;
1054 }
1055
1056 // This code gives a simple linear interpolation of the coordinates between current and
1057 // previous track point assuming a constant speed in between
1058 long imgDate;
1059 while(i >= 0 && (imgDate = dateImgLst.get(i).time.getTime()/1000) >= prevDateWp) {
1060
1061 if(dateImgLst.get(i).pos == null) {
1062 // The values of timeDiff are between 0 and 1, it is not seconds but a dimensionless
1063 // variable
1064 double timeDiff = (double)(imgDate - prevDateWp) / interval;
1065 dateImgLst.get(i).setCoor(prevWp.getCoor().interpolate(curWp.getCoor(), timeDiff));
1066 dateImgLst.get(i).speed = speed;
1067
1068 if (curElevation != null && prevElevation != null) {
1069 dateImgLst.get(i).elevation = prevElevation + (curElevation - prevElevation) * timeDiff;
1070 }
1071
1072 ret++;
1073 }
1074 i--;
1075 }
1076 return ret;
1077 }
1078
1079 private int getLastIndexOfListBefore(ArrayList<ImageEntry> dateImgLst, long searchedDate) {
1080 int lstSize= dateImgLst.size();
1081
1082 // No photos or the first photo taken is later than the search period
1083 if(lstSize == 0 || searchedDate < dateImgLst.get(0).time.getTime()/1000)
1084 return -1;
1085
1086 // The search period is later than the last photo
1087 if (searchedDate > dateImgLst.get(lstSize - 1).time.getTime() / 1000)
1088 return lstSize-1;
1089
1090 // The searched index is somewhere in the middle, do a binary search from the beginning
1091 int curIndex= 0;
1092 int startIndex= 0;
1093 int endIndex= lstSize-1;
1094 while (endIndex - startIndex > 1) {
1095 curIndex= (int) Math.round((double)(endIndex + startIndex)/2);
1096 if (searchedDate > dateImgLst.get(curIndex).time.getTime()/1000) {
1097 startIndex= curIndex;
1098 } else {
1099 endIndex= curIndex;
1100 }
1101 }
1102 if (searchedDate < dateImgLst.get(endIndex).time.getTime()/1000)
1103 return startIndex;
1104
1105 // This final loop is to check if photos with the exact same EXIF time follows
1106 while ((endIndex < (lstSize-1)) && (dateImgLst.get(endIndex).time.getTime()
1107 == dateImgLst.get(endIndex + 1).time.getTime())) {
1108 endIndex++;
1109 }
1110 return endIndex;
1111 }
1112
1113
1114 private String formatTimezone(double timezone) {
1115 StringBuffer ret = new StringBuffer();
1116
1117 if (timezone < 0) {
1118 ret.append('-');
1119 timezone = -timezone;
1120 } else {
1121 ret.append('+');
1122 }
1123 ret.append((long) timezone).append(':');
1124 int minutes = (int) ((timezone % 1) * 60);
1125 if (minutes < 10) {
1126 ret.append('0');
1127 }
1128 ret.append(minutes);
1129
1130 return ret.toString();
1131 }
1132
1133 private Float parseTimezone(String timezone) {
1134 if (timezone.length() == 0)
1135 return new Float(0);
1136
1137 char sgnTimezone = '+';
1138 StringBuffer hTimezone = new StringBuffer();
1139 StringBuffer mTimezone = new StringBuffer();
1140 int state = 1; // 1=start/sign, 2=hours, 3=minutes.
1141 for (int i = 0; i < timezone.length(); i++) {
1142 char c = timezone.charAt(i);
1143 switch (c) {
1144 case ' ' :
1145 if (state != 2 || hTimezone.length() != 0)
1146 return null;
1147 break;
1148 case '+' :
1149 case '-' :
1150 if (state == 1) {
1151 sgnTimezone = c;
1152 state = 2;
1153 } else
1154 return null;
1155 break;
1156 case ':' :
1157 case '.' :
1158 if (state == 2) {
1159 state = 3;
1160 } else
1161 return null;
1162 break;
1163 case '0' : case '1' : case '2' : case '3' : case '4' :
1164 case '5' : case '6' : case '7' : case '8' : case '9' :
1165 switch(state) {
1166 case 1 :
1167 case 2 :
1168 state = 2;
1169 hTimezone.append(c);
1170 break;
1171 case 3 :
1172 mTimezone.append(c);
1173 break;
1174 default :
1175 return null;
1176 }
1177 break;
1178 default :
1179 return null;
1180 }
1181 }
1182
1183 int h = 0;
1184 int m = 0;
1185 try {
1186 h = Integer.parseInt(hTimezone.toString());
1187 if (mTimezone.length() > 0) {
1188 m = Integer.parseInt(mTimezone.toString());
1189 }
1190 } catch (NumberFormatException nfe) {
1191 // Invalid timezone
1192 return null;
1193 }
1194
1195 if (h > 12 || m > 59 )
1196 return null;
1197 else
1198 return new Float((h + m / 60.0) * (sgnTimezone == '-' ? -1 : 1));
1199 }
1200}
Note: See TracBrowser for help on using the repository browser.