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

Last change on this file since 2646 was 2646, checked in by bastiK, 14 years ago

geoimage: select correct gpx track by default in the drop down menu (and not always the first)

  • Property svn:eol-style set to native
File size: 45.3 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 GpxDataWrapper defaultItem = null;
434 Iterator<Layer> iterLayer = layerLst.iterator();
435 while (iterLayer.hasNext()) {
436 Layer cur = iterLayer.next();
437 if (cur instanceof GpxLayer) {
438 GpxDataWrapper gdw = new GpxDataWrapper(((GpxLayer) cur).getName(),
439 ((GpxLayer) cur).data,
440 ((GpxLayer) cur).data.storageFile);
441 gpxLst.add(gdw);
442 if (cur == yLayer.gpxLayer) {
443 System.err.println("Hier!");
444 defaultItem = gdw;
445 }
446 }
447 }
448 for (GpxData data : loadedGpxData) {
449 gpxLst.add(new GpxDataWrapper(data.storageFile.getName(),
450 data,
451 data.storageFile));
452 }
453
454 if (gpxLst.size() == 0) {
455 gpxLst.add(tr("<No GPX track loaded yet>"));
456 }
457
458 JPanel panelCb = new JPanel();
459 panelCb.setLayout(new FlowLayout());
460
461 panelCb.add(new JLabel(tr("GPX track: ")));
462
463 cbGpx = new JComboBox(gpxLst);
464 if (defaultItem != null) {
465 cbGpx.setSelectedItem(defaultItem);
466 }
467 panelCb.add(cbGpx);
468
469 JButton buttonOpen = new JButton(tr("Open another GPX trace"));
470 buttonOpen.setIcon(ImageProvider.get("dialogs/geoimage/geoimage-open"));
471 buttonOpen.addActionListener(new LoadGpxDataActionListener());
472
473 panelCb.add(buttonOpen);
474
475 JPanel panelTf = new JPanel();
476 panelTf.setLayout(new GridBagLayout());
477
478 GridBagConstraints gc = new GridBagConstraints();
479 gc.anchor = GridBagConstraints.WEST;
480
481 gc.gridx = gc.gridy = 0;
482 gc.gridwidth = gc.gridheight = 1;
483 gc.fill = GridBagConstraints.NONE;
484 gc.weightx = gc.weighty = 0.0;
485 panelTf.add(new JLabel(tr("Timezone: ")), gc);
486
487 float gpstimezone = Float.parseFloat(Main.pref.get("geoimage.doublegpstimezone", "0.0"));
488 if (gpstimezone == 0.0) {
489 gpstimezone = - Long.parseLong(Main.pref.get("geoimage.gpstimezone", "0"));
490 }
491 tfTimezone = new JTextField();
492 tfTimezone.setText(formatTimezone(gpstimezone));
493
494 gc.gridx = 1;
495 gc.gridy = 0;
496 gc.gridwidth = gc.gridheight = 1;
497 gc.fill = GridBagConstraints.HORIZONTAL;
498 gc.weightx = 1.0;
499 gc.weighty = 0.0;
500 panelTf.add(tfTimezone, gc);
501
502 gc.gridx = 0;
503 gc.gridy = 1;
504 gc.gridwidth = gc.gridheight = 1;
505 gc.fill = GridBagConstraints.NONE;
506 gc.weightx = gc.weighty = 0.0;
507 panelTf.add(new JLabel(tr("Offset:")), gc);
508
509 long delta = Long.parseLong(Main.pref.get("geoimage.delta", "0")) / 1000;
510 tfOffset = new JTextField();
511 tfOffset.setText(Long.toString(delta));
512 gc.gridx = gc.gridy = 1;
513 gc.gridwidth = gc.gridheight = 1;
514 gc.fill = GridBagConstraints.HORIZONTAL;
515 gc.weightx = 1.0;
516 gc.weighty = 0.0;
517 panelTf.add(tfOffset, gc);
518
519 JButton buttonViewGpsPhoto = new JButton(tr("<html>I can take a picture of my GPS receiver.<br>"
520 + "Can this help?</html>"));
521 buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener());
522 gc.gridx = 2;
523 gc.gridy = 0;
524 gc.gridwidth = 1;
525 gc.gridheight = 2;
526 gc.fill = GridBagConstraints.BOTH;
527 gc.weightx = 0.5;
528 gc.weighty = 1.0;
529 panelTf.add(buttonViewGpsPhoto, gc);
530
531 gc.gridx = 0;
532 gc.gridy = 2;
533 gc.gridwidth = gc.gridheight = 1;
534 gc.fill = GridBagConstraints.NONE;
535 gc.weightx = gc.weighty = 0.0;
536 panelTf.add(new JLabel(tr("Update position for: ")), gc);
537
538 gc.gridx = 1;
539 gc.gridy = 2;
540 gc.gridwidth = 2;
541 gc.gridheight = 1;
542 gc.fill = GridBagConstraints.HORIZONTAL;
543 gc.weightx = 1.0;
544 gc.weighty = 0.0;
545 rbAllImg = new JRadioButton(tr("All images"));
546 panelTf.add(rbAllImg, gc);
547
548 gc.gridx = 1;
549 gc.gridy = 3;
550 gc.gridwidth = 2;
551 gc.gridheight = 1;
552 gc.fill = GridBagConstraints.HORIZONTAL;
553 gc.weightx = 1.0;
554 gc.weighty = 0.0;
555 rbNoExifImg = new JRadioButton(tr("Images with no exif position"));
556 panelTf.add(rbNoExifImg, gc);
557
558 gc.gridx = 1;
559 gc.gridy = 4;
560 gc.gridwidth = 2;
561 gc.gridheight = 1;
562 gc.fill = GridBagConstraints.HORIZONTAL;
563 gc.weightx = 1.0;
564 gc.weighty = 0.0;
565 rbUntaggedImg = new JRadioButton(tr("Not yet tagged images"));
566 panelTf.add(rbUntaggedImg, gc);
567
568 gc.gridx = 0;
569 gc.gridy = 5;
570 gc.gridwidth = 2;
571 gc.gridheight = 1;
572 gc.fill = GridBagConstraints.NONE;
573 gc.weightx = gc.weighty = 0.0;
574 yLayer.useThumbs = Main.pref.getBoolean("geoimage.showThumbs", false);
575 JCheckBox cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), yLayer.useThumbs);
576 panelTf.add(cbShowThumbs, gc);
577
578 ButtonGroup group = new ButtonGroup();
579 group.add(rbAllImg);
580 group.add(rbNoExifImg);
581 group.add(rbUntaggedImg);
582
583 rbUntaggedImg.setSelected(true);
584
585 panel = new JPanel();
586 panel.setLayout(new BorderLayout());
587
588 panel.add(panelCb, BorderLayout.PAGE_START);
589 panel.add(panelTf, BorderLayout.CENTER);
590
591 boolean isOk = false;
592 GpxDataWrapper selectedGpx = null;
593 while (! isOk) {
594 ExtendedDialog dialog = new ExtendedDialog(
595 Main.parent,
596 tr("Correlate images with GPX track"),
597 new String[] { tr("Correlate"), tr("Auto-Guess"), tr("Cancel") }
598 );
599
600 dialog.setContent(panel);
601 dialog.setButtonIcons(new String[] { "ok.png", "dialogs/geoimage/gpx2imgManual.png", "cancel.png" });
602 dialog.showDialog();
603 int answer = dialog.getValue();
604 if(answer != 1 && answer != 2)
605 return;
606
607 // Check the selected values
608 Object item = cbGpx.getSelectedItem();
609
610 if (item == null || ! (item instanceof GpxDataWrapper)) {
611 JOptionPane.showMessageDialog(Main.parent, tr("You should select a GPX track"),
612 tr("No selected GPX track"), JOptionPane.ERROR_MESSAGE );
613 continue;
614 }
615 selectedGpx = ((GpxDataWrapper) item);
616
617 if (answer == 2) {
618 autoGuess(selectedGpx.data);
619 return;
620 }
621
622 Float timezoneValue = parseTimezone(tfTimezone.getText().trim());
623 if (timezoneValue == null) {
624 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing timezone.\nExpected format: {0}", "+H:MM"),
625 tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE);
626 continue;
627 }
628 gpstimezone = timezoneValue.floatValue();
629
630 String deltaText = tfOffset.getText().trim();
631 if (deltaText.length() > 0) {
632 try {
633 if(deltaText.startsWith("+")) {
634 deltaText = deltaText.substring(1);
635 }
636 delta = Long.parseLong(deltaText);
637 } catch(NumberFormatException nfe) {
638 JOptionPane.showMessageDialog(Main.parent, tr("Error while parsing offset.\nExpected format: {0}", "number"),
639 tr("Invalid offset"), JOptionPane.ERROR_MESSAGE);
640 continue;
641 }
642 } else {
643 delta = 0;
644 }
645
646 yLayer.useThumbs = cbShowThumbs.isSelected();
647
648 Main.pref.put("geoimage.doublegpstimezone", Double.toString(gpstimezone));
649 Main.pref.put("geoimage.gpstimezone", Long.toString(- ((long) gpstimezone)));
650 Main.pref.put("geoimage.delta", Long.toString(delta * 1000));
651 Main.pref.put("geoimage.showThumbs", yLayer.useThumbs);
652 isOk = true;
653
654 if (yLayer.useThumbs) {
655 yLayer.thumbsloader = new ThumbsLoader(yLayer);
656 Thread t = new Thread(yLayer.thumbsloader);
657 t.setPriority(Thread.MIN_PRIORITY);
658 t.start();
659 }
660
661 }
662
663 // Construct a list of images that have a date, and sort them on the date.
664 ArrayList<ImageEntry> dateImgLst = getSortedImgList(rbAllImg.isSelected(), rbNoExifImg.isSelected());
665
666 int matched = matchGpxTrack(dateImgLst, selectedGpx.data, (long) (gpstimezone * 3600) + delta);
667
668 // Search whether an other layer has yet defined some bounding box.
669 // If none, we'll zoom to the bounding box of the layer with the photos.
670 boolean boundingBoxedLayerFound = false;
671 for (Layer l: Main.map.mapView.getAllLayers()) {
672 if (l != yLayer) {
673 BoundingXYVisitor bbox = new BoundingXYVisitor();
674 l.visitBoundingBox(bbox);
675 if (bbox.getBounds() != null) {
676 boundingBoxedLayerFound = true;
677 break;
678 }
679 }
680 }
681 if (! boundingBoxedLayerFound) {
682 BoundingXYVisitor bbox = new BoundingXYVisitor();
683 yLayer.visitBoundingBox(bbox);
684 Main.map.mapView.recalculateCenterScale(bbox);
685 }
686
687 Main.map.repaint();
688
689 JOptionPane.showMessageDialog(Main.parent, tr("Found {0} matches of {1} in GPX track {2}", matched, dateImgLst.size(), selectedGpx.name),
690 tr("GPX Track loaded"),
691 ((dateImgLst.size() > 0 && matched == 0) ? JOptionPane.WARNING_MESSAGE
692 : JOptionPane.INFORMATION_MESSAGE));
693
694 }
695
696 // These variables all belong to "auto guess" but need to be accessible
697 // from the slider change listener
698 private int dayOffset;
699 private JLabel lblMatches;
700 private JLabel lblOffset;
701 private JLabel lblTimezone;
702 private JLabel lblMinutes;
703 private JLabel lblSeconds;
704 private JSlider sldTimezone;
705 private JSlider sldMinutes;
706 private JSlider sldSeconds;
707 private GpxData autoGpx;
708 private ArrayList<ImageEntry> autoImgs;
709 private long firstGPXDate = -1;
710 private long firstExifDate = -1;
711
712 /**
713 * Tries to automatically match opened photos to a given GPX track. Changes are applied
714 * immediately. Presents dialog with sliders for manual adjust.
715 * @param GpxData The GPX track to match against
716 */
717 private void autoGuess(GpxData gpx) {
718 autoGpx = gpx;
719 autoImgs = getSortedImgList(true, false);
720 PrimaryDateParser dateParser = new PrimaryDateParser();
721
722 // no images found, exit
723 if(autoImgs.size() <= 0) {
724 JOptionPane.showMessageDialog(Main.parent,
725 tr("The selected photos don't contain time information."),
726 tr("Photos don't contain time information"), JOptionPane.WARNING_MESSAGE);
727 return;
728 }
729
730 ImageViewerDialog dialog = ImageViewerDialog.getInstance();
731 dialog.showDialog();
732 // Will show first photo if none is selected yet
733 if(!dialog.hasImage()) {
734 yLayer.showNextPhoto();
735 // FIXME: If the dialog is minimized it will not be maximized. ToggleDialog is
736 // in need of a complete re-write to allow this in a reasonable way.
737 }
738
739 // Init variables
740 firstExifDate = autoImgs.get(0).time.getTime()/1000;
741
742
743 // Finds first GPX point
744 outer: for (GpxTrack trk : gpx.tracks) {
745 for (Collection<WayPoint> segment : trk.trackSegs) {
746 for (WayPoint curWp : segment) {
747 String curDateWpStr = (String) curWp.attr.get("time");
748 if (curDateWpStr == null) {
749 continue;
750 }
751
752 try {
753 firstGPXDate = dateParser.parse(curDateWpStr).getTime()/1000;
754 break outer;
755 } catch(Exception e) {}
756 }
757 }
758 }
759
760 // No GPX timestamps found, exit
761 if(firstGPXDate < 0) {
762 JOptionPane.showMessageDialog(Main.parent,
763 tr("The selected GPX track doesn't contain timestamps. Please select another one."),
764 tr("GPX Track has no time information"), JOptionPane.WARNING_MESSAGE);
765 return;
766 }
767
768 // seconds
769 long diff = (yLayer.hasTimeoffset)
770 ? yLayer.timeoffset
771 : firstExifDate - firstGPXDate;
772 yLayer.timeoffset = diff;
773 yLayer.hasTimeoffset = true;
774
775 double diffInH = (double)diff/(60*60); // hours
776
777 // Find day difference
778 dayOffset = (int)Math.round(diffInH / 24); // days
779 double timezone = diff - dayOffset*24*60*60; // seconds
780
781 // In hours, rounded to two decimal places
782 timezone = (double)Math.round(timezone*100/(60*60)) / 100;
783
784 // Due to imprecise clocks we might get a "+3:28" timezone, which should obviously be 3:30 with
785 // -2 minutes offset. This determines the real timezone and finds offset.
786 double fixTimezone = (double)Math.round(timezone * 2)/2; // hours, rounded to one decimal place
787 int offset = (int)Math.round(diff - fixTimezone*60*60) - dayOffset*24*60*60; // seconds
788
789 /*System.out.println("phto " + firstExifDate);
790 System.out.println("gpx " + firstGPXDate);
791 System.out.println("diff " + diff);
792 System.out.println("difh " + diffInH);
793 System.out.println("days " + dayOffset);
794 System.out.println("time " + timezone);
795 System.out.println("fix " + fixTimezone);
796 System.out.println("offt " + offset);*/
797
798 // This is called whenever one of the sliders is moved.
799 // It updates the labels and also calls the "match photos" code
800 class sliderListener implements ChangeListener {
801 public void stateChanged(ChangeEvent e) {
802 // parse slider position into real timezone
803 double tz = Math.abs(sldTimezone.getValue());
804 String zone = tz % 2 == 0
805 ? (int)Math.floor(tz/2) + ":00"
806 : (int)Math.floor(tz/2) + ":30";
807 if(sldTimezone.getValue() < 0) {
808 zone = "-" + zone;
809 }
810
811 lblTimezone.setText(tr("Timezone: {0}", zone));
812 lblMinutes.setText(tr("Minutes: {0}", sldMinutes.getValue()));
813 lblSeconds.setText(tr("Seconds: {0}", sldSeconds.getValue()));
814
815 float gpstimezone = parseTimezone(zone).floatValue();
816
817 // Reset previous position
818 for(ImageEntry x : autoImgs) {
819 x.pos = null;
820 }
821
822 long timediff = (long) (gpstimezone * 3600)
823 + dayOffset*24*60*60
824 + sldMinutes.getValue()*60
825 + sldSeconds.getValue();
826
827 int matched = matchGpxTrack(autoImgs, autoGpx, timediff);
828
829 lblMatches.setText(
830 tr("Matched {0} of {1} photos to GPX track.", matched, autoImgs.size())
831 + ((Math.abs(dayOffset) == 0)
832 ? ""
833 : " " + tr("(Time difference of {0} days)", Math.abs(dayOffset))
834 )
835 );
836
837 int offset = (int)(firstGPXDate+timediff-firstExifDate);
838 int o = Math.abs(offset);
839 lblOffset.setText(
840 tr("Offset between track and photos: {0}m {1}s",
841 (offset < 0 ? "-" : "") + Long.toString(o/60),
842 Long.toString(o%60)
843 )
844 );
845
846 yLayer.timeoffset = timediff;
847 Main.main.map.repaint();
848 }
849 }
850
851 // Info Labels
852 lblMatches = new JLabel();
853 lblOffset = new JLabel();
854
855 // Timezone Slider
856 // The slider allows to switch timezon from -12:00 to 12:00 in 30 minutes
857 // steps. Therefore the range is -24 to 24.
858 lblTimezone = new JLabel();
859 sldTimezone = new JSlider(-24, 24, 0);
860 sldTimezone.setPaintLabels(true);
861 Hashtable<Integer,JLabel> labelTable = new Hashtable<Integer, JLabel>();
862 labelTable.put(-24, new JLabel("-12:00"));
863 labelTable.put(-12, new JLabel( "-6:00"));
864 labelTable.put( 0, new JLabel( "0:00"));
865 labelTable.put( 12, new JLabel( "6:00"));
866 labelTable.put( 24, new JLabel( "12:00"));
867 sldTimezone.setLabelTable(labelTable);
868
869 // Minutes Slider
870 lblMinutes = new JLabel();
871 sldMinutes = new JSlider(-15, 15, 0);
872 sldMinutes.setPaintLabels(true);
873 sldMinutes.setMajorTickSpacing(5);
874
875 // Seconds slider
876 lblSeconds = new JLabel();
877 sldSeconds = new JSlider(-60, 60, 0);
878 sldSeconds.setPaintLabels(true);
879 sldSeconds.setMajorTickSpacing(30);
880
881 // Put everything together
882 JPanel p = new JPanel(new GridBagLayout());
883 p.setPreferredSize(new Dimension(400, 230));
884 p.add(lblMatches, GBC.eol().fill());
885 p.add(lblOffset, GBC.eol().fill().insets(0, 0, 0, 10));
886 p.add(lblTimezone, GBC.eol().fill());
887 p.add(sldTimezone, GBC.eol().fill().insets(0, 0, 0, 10));
888 p.add(lblMinutes, GBC.eol().fill());
889 p.add(sldMinutes, GBC.eol().fill().insets(0, 0, 0, 10));
890 p.add(lblSeconds, GBC.eol().fill());
891 p.add(sldSeconds, GBC.eol().fill());
892
893 // If there's an error in the calculation the found values
894 // will be off range for the sliders. Catch this error
895 // and inform the user about it.
896 try {
897 sldTimezone.setValue((int)(fixTimezone*2));
898 sldMinutes.setValue(offset/60);
899 sldSeconds.setValue(offset%60);
900 } catch(Exception e) {
901 JOptionPane.showMessageDialog(Main.parent,
902 tr("An error occurred while trying to match the photos to the GPX track."
903 +" You can adjust the sliders to manually match the photos."),
904 tr("Matching photos to track failed"),
905 JOptionPane.WARNING_MESSAGE);
906 }
907
908 // Call the sliderListener once manually so labels get adjusted
909 new sliderListener().stateChanged(null);
910 // Listeners added here, otherwise it tries to match three times
911 // (when setting the default values)
912 sldTimezone.addChangeListener(new sliderListener());
913 sldMinutes.addChangeListener(new sliderListener());
914 sldSeconds.addChangeListener(new sliderListener());
915
916 // There is no way to cancel this dialog, all changes get applied
917 // immediately. Therefore "Close" is marked with an "OK" icon.
918 // Settings are only saved temporarily to the layer.
919 ExtendedDialog d = new ExtendedDialog(Main.parent,
920 tr("Adjust timezone and offset"),
921 new String[] { tr("Close"), tr("Default Values") }
922 );
923
924 d.setContent(p);
925 d.setButtonIcons(new String[] { "ok.png", "dialogs/refresh.png"});
926 d.showDialog();
927 int answer = d.getValue();
928 // User wants default values; discard old result and re-open dialog
929 if(answer == 2) {
930 yLayer.hasTimeoffset = false;
931 autoGuess(gpx);
932 }
933 }
934
935 /**
936 * Returns a list of images that fulfill the given criteria.
937 * Default setting is to return untagged images, but may be overwritten.
938 * @param boolean all -- returns all available images
939 * @param boolean noexif -- returns untagged images without EXIF-GPS coords
940 * @return ArrayList<ImageEntry> matching images
941 */
942 private ArrayList<ImageEntry> getSortedImgList(boolean all, boolean noexif) {
943 ArrayList<ImageEntry> dateImgLst = new ArrayList<ImageEntry>(yLayer.data.size());
944 if (all) {
945 for (ImageEntry e : yLayer.data) {
946 if (e.time != null) {
947 // Reset previous position
948 e.pos = null;
949 dateImgLst.add(e);
950 }
951 }
952
953 } else if (noexif) {
954 for (ImageEntry e : yLayer.data) {
955 if (e.time != null && e.exifCoor == null) {
956 dateImgLst.add(e);
957 }
958 }
959
960 } else {
961 for (ImageEntry e : yLayer.data) {
962 if (e.time != null && e.pos == null) {
963 dateImgLst.add(e);
964 }
965 }
966 }
967
968 Collections.sort(dateImgLst, new Comparator<ImageEntry>() {
969 public int compare(ImageEntry arg0, ImageEntry arg1) {
970 return arg0.time.compareTo(arg1.time);
971 }
972 });
973
974 return dateImgLst;
975 }
976
977 private int matchGpxTrack(ArrayList<ImageEntry> dateImgLst, GpxData selectedGpx, long offset) {
978 int ret = 0;
979
980 PrimaryDateParser dateParser = new PrimaryDateParser();
981
982 for (GpxTrack trk : selectedGpx.tracks) {
983 for (Collection<WayPoint> segment : trk.trackSegs) {
984
985 long prevDateWp = 0;
986 WayPoint prevWp = null;
987
988 for (WayPoint curWp : segment) {
989
990 String curDateWpStr = (String) curWp.attr.get("time");
991 if (curDateWpStr != null) {
992
993 try {
994 long curDateWp = dateParser.parse(curDateWpStr).getTime()/1000 + offset;
995 ret += matchPoints(dateImgLst, prevWp, prevDateWp, curWp, curDateWp);
996
997 prevWp = curWp;
998 prevDateWp = curDateWp;
999
1000 } catch(ParseException e) {
1001 System.err.println("Error while parsing date \"" + curDateWpStr + '"');
1002 e.printStackTrace();
1003 prevWp = null;
1004 prevDateWp = 0;
1005 }
1006 } else {
1007 prevWp = null;
1008 prevDateWp = 0;
1009 }
1010 }
1011 }
1012 }
1013 return ret;
1014 }
1015
1016 private int matchPoints(ArrayList<ImageEntry> dateImgLst, WayPoint prevWp, long prevDateWp,
1017 WayPoint curWp, long curDateWp) {
1018 // Time between the track point and the previous one, 5 sec if first point, i.e. photos take
1019 // 5 sec before the first track point can be assumed to be take at the starting position
1020 long interval = prevDateWp > 0 ? ((int)Math.abs(curDateWp - prevDateWp)) : 5;
1021 int ret = 0;
1022
1023 // i is the index of the timewise last photo that has the same or earlier EXIF time
1024 int i = getLastIndexOfListBefore(dateImgLst, curDateWp);
1025
1026 // no photos match
1027 if (i < 0)
1028 return 0;
1029
1030 Double speed = null;
1031 Double prevElevation = null;
1032 Double curElevation = null;
1033
1034 if (prevWp != null) {
1035 double distance = prevWp.getCoor().greatCircleDistance(curWp.getCoor());
1036 // This is in km/h, 3.6 * m/s
1037 if (curDateWp > prevDateWp) {
1038 speed = 3.6 * distance / (curDateWp - prevDateWp);
1039 }
1040 try {
1041 prevElevation = new Double((String) prevWp.attr.get("ele"));
1042 } catch(Exception e) {}
1043 }
1044
1045 try {
1046 curElevation = new Double((String) curWp.attr.get("ele"));
1047 } catch (Exception e) {}
1048
1049 // First trackpoint, then interval is set to five seconds, i.e. photos up to five seconds
1050 // before the first point will be geotagged with the starting point
1051 if(prevDateWp == 0 || curDateWp <= prevDateWp) {
1052 while(i >= 0 && (dateImgLst.get(i).time.getTime()/1000) <= curDateWp
1053 && (dateImgLst.get(i).time.getTime()/1000) >= (curDateWp - interval)) {
1054 if(dateImgLst.get(i).pos == null) {
1055 dateImgLst.get(i).setCoor(curWp.getCoor());
1056 dateImgLst.get(i).speed = speed;
1057 dateImgLst.get(i).elevation = curElevation;
1058 ret++;
1059 }
1060 i--;
1061 }
1062 return ret;
1063 }
1064
1065 // This code gives a simple linear interpolation of the coordinates between current and
1066 // previous track point assuming a constant speed in between
1067 long imgDate;
1068 while(i >= 0 && (imgDate = dateImgLst.get(i).time.getTime()/1000) >= prevDateWp) {
1069
1070 if(dateImgLst.get(i).pos == null) {
1071 // The values of timeDiff are between 0 and 1, it is not seconds but a dimensionless
1072 // variable
1073 double timeDiff = (double)(imgDate - prevDateWp) / interval;
1074 dateImgLst.get(i).setCoor(prevWp.getCoor().interpolate(curWp.getCoor(), timeDiff));
1075 dateImgLst.get(i).speed = speed;
1076
1077 if (curElevation != null && prevElevation != null) {
1078 dateImgLst.get(i).elevation = prevElevation + (curElevation - prevElevation) * timeDiff;
1079 }
1080
1081 ret++;
1082 }
1083 i--;
1084 }
1085 return ret;
1086 }
1087
1088 private int getLastIndexOfListBefore(ArrayList<ImageEntry> dateImgLst, long searchedDate) {
1089 int lstSize= dateImgLst.size();
1090
1091 // No photos or the first photo taken is later than the search period
1092 if(lstSize == 0 || searchedDate < dateImgLst.get(0).time.getTime()/1000)
1093 return -1;
1094
1095 // The search period is later than the last photo
1096 if (searchedDate > dateImgLst.get(lstSize - 1).time.getTime() / 1000)
1097 return lstSize-1;
1098
1099 // The searched index is somewhere in the middle, do a binary search from the beginning
1100 int curIndex= 0;
1101 int startIndex= 0;
1102 int endIndex= lstSize-1;
1103 while (endIndex - startIndex > 1) {
1104 curIndex= (int) Math.round((double)(endIndex + startIndex)/2);
1105 if (searchedDate > dateImgLst.get(curIndex).time.getTime()/1000) {
1106 startIndex= curIndex;
1107 } else {
1108 endIndex= curIndex;
1109 }
1110 }
1111 if (searchedDate < dateImgLst.get(endIndex).time.getTime()/1000)
1112 return startIndex;
1113
1114 // This final loop is to check if photos with the exact same EXIF time follows
1115 while ((endIndex < (lstSize-1)) && (dateImgLst.get(endIndex).time.getTime()
1116 == dateImgLst.get(endIndex + 1).time.getTime())) {
1117 endIndex++;
1118 }
1119 return endIndex;
1120 }
1121
1122
1123 private String formatTimezone(double timezone) {
1124 StringBuffer ret = new StringBuffer();
1125
1126 if (timezone < 0) {
1127 ret.append('-');
1128 timezone = -timezone;
1129 } else {
1130 ret.append('+');
1131 }
1132 ret.append((long) timezone).append(':');
1133 int minutes = (int) ((timezone % 1) * 60);
1134 if (minutes < 10) {
1135 ret.append('0');
1136 }
1137 ret.append(minutes);
1138
1139 return ret.toString();
1140 }
1141
1142 private Float parseTimezone(String timezone) {
1143 if (timezone.length() == 0)
1144 return new Float(0);
1145
1146 char sgnTimezone = '+';
1147 StringBuffer hTimezone = new StringBuffer();
1148 StringBuffer mTimezone = new StringBuffer();
1149 int state = 1; // 1=start/sign, 2=hours, 3=minutes.
1150 for (int i = 0; i < timezone.length(); i++) {
1151 char c = timezone.charAt(i);
1152 switch (c) {
1153 case ' ' :
1154 if (state != 2 || hTimezone.length() != 0)
1155 return null;
1156 break;
1157 case '+' :
1158 case '-' :
1159 if (state == 1) {
1160 sgnTimezone = c;
1161 state = 2;
1162 } else
1163 return null;
1164 break;
1165 case ':' :
1166 case '.' :
1167 if (state == 2) {
1168 state = 3;
1169 } else
1170 return null;
1171 break;
1172 case '0' : case '1' : case '2' : case '3' : case '4' :
1173 case '5' : case '6' : case '7' : case '8' : case '9' :
1174 switch(state) {
1175 case 1 :
1176 case 2 :
1177 state = 2;
1178 hTimezone.append(c);
1179 break;
1180 case 3 :
1181 mTimezone.append(c);
1182 break;
1183 default :
1184 return null;
1185 }
1186 break;
1187 default :
1188 return null;
1189 }
1190 }
1191
1192 int h = 0;
1193 int m = 0;
1194 try {
1195 h = Integer.parseInt(hTimezone.toString());
1196 if (mTimezone.length() > 0) {
1197 m = Integer.parseInt(mTimezone.toString());
1198 }
1199 } catch (NumberFormatException nfe) {
1200 // Invalid timezone
1201 return null;
1202 }
1203
1204 if (h > 12 || m > 59 )
1205 return null;
1206 else
1207 return new Float((h + m / 60.0) * (sgnTimezone == '-' ? -1 : 1));
1208 }
1209}
Note: See TracBrowser for help on using the repository browser.