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

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

geoimage: improved thumbnails (closes #4101)

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