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

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

geoimage: make thumbnails optional + cosmetics (see #4101)

  • Property svn:eol-style set to native
File size: 45.2 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.loadThumbs = Main.pref.getBoolean("geoimage.showThumbs", false);
567 JCheckBox cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), yLayer.loadThumbs);
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.loadThumbs = 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.loadThumbs);
643 isOk = true;
644
645 if (yLayer.loadThumbs) {
646 Thread tl = new Thread(new ThumbsLoader(yLayer.data));
647 tl.setPriority(Thread.MIN_PRIORITY);
648 tl.start();
649 }
650
651 }
652
653 // Construct a list of images that have a date, and sort them on the date.
654 ArrayList<ImageEntry> dateImgLst = getSortedImgList(rbAllImg.isSelected(), rbNoExifImg.isSelected());
655
656 int matched = matchGpxTrack(dateImgLst, selectedGpx.data, (long) (gpstimezone * 3600) + delta);
657
658 // Search whether an other layer has yet defined some bounding box.
659 // If none, we'll zoom to the bounding box of the layer with the photos.
660 boolean boundingBoxedLayerFound = false;
661 for (Layer l: Main.map.mapView.getAllLayers()) {
662 if (l != yLayer) {
663 BoundingXYVisitor bbox = new BoundingXYVisitor();
664 l.visitBoundingBox(bbox);
665 if (bbox.getBounds() != null) {
666 boundingBoxedLayerFound = true;
667 break;
668 }
669 }
670 }
671 if (! boundingBoxedLayerFound) {
672 BoundingXYVisitor bbox = new BoundingXYVisitor();
673 yLayer.visitBoundingBox(bbox);
674 Main.map.mapView.recalculateCenterScale(bbox);
675 }
676
677 Main.map.repaint();
678
679 JOptionPane.showMessageDialog(Main.parent, tr("Found {0} matches of {1} in GPX track {2}", matched, dateImgLst.size(), selectedGpx.name),
680 tr("GPX Track loaded"),
681 ((dateImgLst.size() > 0 && matched == 0) ? JOptionPane.WARNING_MESSAGE
682 : JOptionPane.INFORMATION_MESSAGE));
683
684 }
685
686 // These variables all belong to "auto guess" but need to be accessible
687 // from the slider change listener
688 private int dayOffset;
689 private JLabel lblMatches;
690 private JLabel lblOffset;
691 private JLabel lblTimezone;
692 private JLabel lblMinutes;
693 private JLabel lblSeconds;
694 private JSlider sldTimezone;
695 private JSlider sldMinutes;
696 private JSlider sldSeconds;
697 private GpxData autoGpx;
698 private ArrayList<ImageEntry> autoImgs;
699 private long firstGPXDate = -1;
700 private long firstExifDate = -1;
701
702 /**
703 * Tries to automatically match opened photos to a given GPX track. Changes are applied
704 * immediately. Presents dialog with sliders for manual adjust.
705 * @param GpxData The GPX track to match against
706 */
707 private void autoGuess(GpxData gpx) {
708 autoGpx = gpx;
709 autoImgs = getSortedImgList(true, false);
710 PrimaryDateParser dateParser = new PrimaryDateParser();
711
712 // no images found, exit
713 if(autoImgs.size() <= 0) {
714 JOptionPane.showMessageDialog(Main.parent,
715 tr("The selected photos don't contain time information."),
716 tr("Photos don't contain time information"), JOptionPane.WARNING_MESSAGE);
717 return;
718 }
719
720 ImageViewerDialog dialog = ImageViewerDialog.getInstance();
721 dialog.showDialog();
722 // Will show first photo if none is selected yet
723 if(!dialog.hasImage())
724 yLayer.showNextPhoto();
725 // FIXME: If the dialog is minimized it will not be maximized. ToggleDialog is
726 // in need of a complete re-write to allow this in a reasonable way.
727
728 // Init variables
729 firstExifDate = autoImgs.get(0).time.getTime()/1000;
730
731
732 // Finds first GPX point
733 outer: for (GpxTrack trk : gpx.tracks) {
734 for (Collection<WayPoint> segment : trk.trackSegs) {
735 for (WayPoint curWp : segment) {
736 String curDateWpStr = (String) curWp.attr.get("time");
737 if (curDateWpStr == null) continue;
738
739 try {
740 firstGPXDate = dateParser.parse(curDateWpStr).getTime()/1000;
741 break outer;
742 } catch(Exception e) {}
743 }
744 }
745 }
746
747 // No GPX timestamps found, exit
748 if(firstGPXDate < 0) {
749 JOptionPane.showMessageDialog(Main.parent,
750 tr("The selected GPX track doesn't contain timestamps. Please select another one."),
751 tr("GPX Track has no time information"), JOptionPane.WARNING_MESSAGE);
752 return;
753 }
754
755 // seconds
756 long diff = (yLayer.hasTimeoffset)
757 ? yLayer.timeoffset
758 : firstExifDate - firstGPXDate;
759 yLayer.timeoffset = diff;
760 yLayer.hasTimeoffset = true;
761
762 double diffInH = (double)diff/(60*60); // hours
763
764 // Find day difference
765 dayOffset = (int)Math.round(diffInH / 24); // days
766 double timezone = diff - dayOffset*24*60*60; // seconds
767
768 // In hours, rounded to two decimal places
769 timezone = (double)Math.round(timezone*100/(60*60)) / 100;
770
771 // Due to imprecise clocks we might get a "+3:28" timezone, which should obviously be 3:30 with
772 // -2 minutes offset. This determines the real timezone and finds offset.
773 double fixTimezone = (double)Math.round(timezone * 2)/2; // hours, rounded to one decimal place
774 int offset = (int)Math.round(diff - fixTimezone*60*60) - dayOffset*24*60*60; // seconds
775
776 /*System.out.println("phto " + firstExifDate);
777 System.out.println("gpx " + firstGPXDate);
778 System.out.println("diff " + diff);
779 System.out.println("difh " + diffInH);
780 System.out.println("days " + dayOffset);
781 System.out.println("time " + timezone);
782 System.out.println("fix " + fixTimezone);
783 System.out.println("offt " + offset);*/
784
785 // This is called whenever one of the sliders is moved.
786 // It updates the labels and also calls the "match photos" code
787 class sliderListener implements ChangeListener {
788 public void stateChanged(ChangeEvent e) {
789 // parse slider position into real timezone
790 double tz = Math.abs(sldTimezone.getValue());
791 String zone = tz % 2 == 0
792 ? (int)Math.floor(tz/2) + ":00"
793 : (int)Math.floor(tz/2) + ":30";
794 if(sldTimezone.getValue() < 0) zone = "-" + zone;
795
796 lblTimezone.setText(tr("Timezone: {0}", zone));
797 lblMinutes.setText(tr("Minutes: {0}", sldMinutes.getValue()));
798 lblSeconds.setText(tr("Seconds: {0}", sldSeconds.getValue()));
799
800 float gpstimezone = parseTimezone(zone).floatValue();
801
802 // Reset previous position
803 for(ImageEntry x : autoImgs) {
804 x.pos = null;
805 }
806
807 long timediff = (long) (gpstimezone * 3600)
808 + dayOffset*24*60*60
809 + sldMinutes.getValue()*60
810 + sldSeconds.getValue();
811
812 int matched = matchGpxTrack(autoImgs, autoGpx, timediff);
813
814 lblMatches.setText(
815 tr("Matched {0} of {1} photos to GPX track.", matched, autoImgs.size())
816 + ((Math.abs(dayOffset) == 0)
817 ? ""
818 : " " + tr("(Time difference of {0} days)", Math.abs(dayOffset))
819 )
820 );
821
822 int offset = (int)(firstGPXDate+timediff-firstExifDate);
823 int o = Math.abs(offset);
824 lblOffset.setText(
825 tr("Offset between track and photos: {0}m {1}s",
826 (offset < 0 ? "-" : "") + Long.toString(Math.round(o/60)),
827 Long.toString(Math.round(o%60))
828 )
829 );
830
831 yLayer.timeoffset = timediff;
832 Main.main.map.repaint();
833 }
834 }
835
836 // Info Labels
837 lblMatches = new JLabel();
838 lblOffset = new JLabel();
839
840 // Timezone Slider
841 // The slider allows to switch timezon from -12:00 to 12:00 in 30 minutes
842 // steps. Therefore the range is -24 to 24.
843 lblTimezone = new JLabel();
844 sldTimezone = new JSlider(-24, 24, 0);
845 sldTimezone.setPaintLabels(true);
846 Hashtable<Integer,JLabel> labelTable = new Hashtable<Integer, JLabel>();
847 labelTable.put(-24, new JLabel("-12:00"));
848 labelTable.put(-12, new JLabel( "-6:00"));
849 labelTable.put( 0, new JLabel( "0:00"));
850 labelTable.put( 12, new JLabel( "6:00"));
851 labelTable.put( 24, new JLabel( "12:00"));
852 sldTimezone.setLabelTable(labelTable);
853
854 // Minutes Slider
855 lblMinutes = new JLabel();
856 sldMinutes = new JSlider(-15, 15, 0);
857 sldMinutes.setPaintLabels(true);
858 sldMinutes.setMajorTickSpacing(5);
859
860 // Seconds slider
861 lblSeconds = new JLabel();
862 sldSeconds = new JSlider(-60, 60, 0);
863 sldSeconds.setPaintLabels(true);
864 sldSeconds.setMajorTickSpacing(30);
865
866 // Put everything together
867 JPanel p = new JPanel(new GridBagLayout());
868 p.setPreferredSize(new Dimension(400, 230));
869 p.add(lblMatches, GBC.eol().fill());
870 p.add(lblOffset, GBC.eol().fill().insets(0, 0, 0, 10));
871 p.add(lblTimezone, GBC.eol().fill());
872 p.add(sldTimezone, GBC.eol().fill().insets(0, 0, 0, 10));
873 p.add(lblMinutes, GBC.eol().fill());
874 p.add(sldMinutes, GBC.eol().fill().insets(0, 0, 0, 10));
875 p.add(lblSeconds, GBC.eol().fill());
876 p.add(sldSeconds, GBC.eol().fill());
877
878 // If there's an error in the calculation the found values
879 // will be off range for the sliders. Catch this error
880 // and inform the user about it.
881 try {
882 sldTimezone.setValue((int)(fixTimezone*2));
883 sldMinutes.setValue(offset/60);
884 sldSeconds.setValue(offset%60);
885 } catch(Exception e) {
886 JOptionPane.showMessageDialog(Main.parent,
887 tr("An error occurred while trying to match the photos to the GPX track."
888 +" You can adjust the sliders to manually match the photos."),
889 tr("Matching photos to track failed"),
890 JOptionPane.WARNING_MESSAGE);
891 }
892
893 // Call the sliderListener once manually so labels get adjusted
894 new sliderListener().stateChanged(null);
895 // Listeners added here, otherwise it tries to match three times
896 // (when setting the default values)
897 sldTimezone.addChangeListener(new sliderListener());
898 sldMinutes.addChangeListener(new sliderListener());
899 sldSeconds.addChangeListener(new sliderListener());
900
901 // There is no way to cancel this dialog, all changes get applied
902 // immediately. Therefore "Close" is marked with an "OK" icon.
903 // Settings are only saved temporarily to the layer.
904 ExtendedDialog d = new ExtendedDialog(Main.parent,
905 tr("Adjust timezone and offset"),
906 new String[] { tr("Close"), tr("Default Values") }
907 );
908
909 d.setContent(p);
910 d.setButtonIcons(new String[] { "ok.png", "dialogs/refresh.png"});
911 d.showDialog();
912 int answer = d.getValue();
913 // User wants default values; discard old result and re-open dialog
914 if(answer == 2) {
915 yLayer.hasTimeoffset = false;
916 autoGuess(gpx);
917 }
918 }
919
920 /**
921 * Returns a list of images that fulfill the given criteria.
922 * Default setting is to return untagged images, but may be overwritten.
923 * @param boolean all -- returns all available images
924 * @param boolean noexif -- returns untagged images without EXIF-GPS coords
925 * @return ArrayList<ImageEntry> matching images
926 */
927 private ArrayList<ImageEntry> getSortedImgList(boolean all, boolean noexif) {
928 ArrayList<ImageEntry> dateImgLst = new ArrayList<ImageEntry>(yLayer.data.size());
929 if (all) {
930 for (ImageEntry e : yLayer.data) {
931 if (e.time != null) {
932 // Reset previous position
933 e.pos = null;
934 dateImgLst.add(e);
935 }
936 }
937
938 } else if (noexif) {
939 for (ImageEntry e : yLayer.data) {
940 if (e.time != null && e.exifCoor == null) {
941 dateImgLst.add(e);
942 }
943 }
944
945 } else {
946 for (ImageEntry e : yLayer.data) {
947 if (e.time != null && e.pos == null) {
948 dateImgLst.add(e);
949 }
950 }
951 }
952
953 Collections.sort(dateImgLst, new Comparator<ImageEntry>() {
954 public int compare(ImageEntry arg0, ImageEntry arg1) {
955 return arg0.time.compareTo(arg1.time);
956 }
957 });
958
959 return dateImgLst;
960 }
961
962 private int matchGpxTrack(ArrayList<ImageEntry> dateImgLst, GpxData selectedGpx, long offset) {
963 int ret = 0;
964
965 PrimaryDateParser dateParser = new PrimaryDateParser();
966
967 for (GpxTrack trk : selectedGpx.tracks) {
968 for (Collection<WayPoint> segment : trk.trackSegs) {
969
970 long prevDateWp = 0;
971 WayPoint prevWp = null;
972
973 for (WayPoint curWp : segment) {
974
975 String curDateWpStr = (String) curWp.attr.get("time");
976 if (curDateWpStr != null) {
977
978 try {
979 long curDateWp = dateParser.parse(curDateWpStr).getTime()/1000 + offset;
980 ret += matchPoints(dateImgLst, prevWp, prevDateWp, curWp, curDateWp);
981
982 prevWp = curWp;
983 prevDateWp = curDateWp;
984
985 } catch(ParseException e) {
986 System.err.println("Error while parsing date \"" + curDateWpStr + '"');
987 e.printStackTrace();
988 prevWp = null;
989 prevDateWp = 0;
990 }
991 } else {
992 prevWp = null;
993 prevDateWp = 0;
994 }
995 }
996 }
997 }
998 return ret;
999 }
1000
1001 private int matchPoints(ArrayList<ImageEntry> dateImgLst, WayPoint prevWp, long prevDateWp,
1002 WayPoint curWp, long curDateWp) {
1003 // Time between the track point and the previous one, 5 sec if first point, i.e. photos take
1004 // 5 sec before the first track point can be assumed to be take at the starting position
1005 long interval = prevDateWp > 0 ? ((int)Math.abs(curDateWp - prevDateWp)) : 5;
1006 int ret = 0;
1007
1008 // i is the index of the timewise last photo that has the same or earlier EXIF time
1009 int i = getLastIndexOfListBefore(dateImgLst, curDateWp);
1010
1011 // no photos match
1012 if (i < 0)
1013 return 0;
1014
1015 Double speed = null;
1016 Double prevElevation = null;
1017 Double curElevation = null;
1018
1019 if (prevWp != null) {
1020 double distance = prevWp.getCoor().greatCircleDistance(curWp.getCoor());
1021 // This is in km/h, 3.6 * m/s
1022 if (curDateWp > prevDateWp)
1023 speed = 3.6 * distance / (curDateWp - prevDateWp);
1024 try {
1025 prevElevation = new Double((String) prevWp.attr.get("ele"));
1026 } catch(Exception e) {}
1027 }
1028
1029 try {
1030 curElevation = new Double((String) curWp.attr.get("ele"));
1031 } catch (Exception e) {}
1032
1033 // First trackpoint, then interval is set to five seconds, i.e. photos up to five seconds
1034 // before the first point will be geotagged with the starting point
1035 if(prevDateWp == 0 || curDateWp <= prevDateWp) {
1036 while(i >= 0 && (dateImgLst.get(i).time.getTime()/1000) <= curDateWp
1037 && (dateImgLst.get(i).time.getTime()/1000) >= (curDateWp - interval)) {
1038 if(dateImgLst.get(i).pos == null) {
1039 dateImgLst.get(i).setCoor(curWp.getCoor());
1040 dateImgLst.get(i).speed = speed;
1041 dateImgLst.get(i).elevation = curElevation;
1042 ret++;
1043 }
1044 i--;
1045 }
1046 return ret;
1047 }
1048
1049 // This code gives a simple linear interpolation of the coordinates between current and
1050 // previous track point assuming a constant speed in between
1051 long imgDate;
1052 while(i >= 0 && (imgDate = dateImgLst.get(i).time.getTime()/1000) >= prevDateWp) {
1053
1054 if(dateImgLst.get(i).pos == null) {
1055 // The values of timeDiff are between 0 and 1, it is not seconds but a dimensionless
1056 // variable
1057 double timeDiff = (double)(imgDate - prevDateWp) / interval;
1058 dateImgLst.get(i).setCoor(prevWp.getCoor().interpolate(curWp.getCoor(), timeDiff));
1059 dateImgLst.get(i).speed = speed;
1060
1061 if (curElevation != null && prevElevation != null)
1062 dateImgLst.get(i).elevation = prevElevation + (curElevation - prevElevation) * timeDiff;
1063
1064 ret++;
1065 }
1066 i--;
1067 }
1068 return ret;
1069 }
1070
1071 private int getLastIndexOfListBefore(ArrayList<ImageEntry> dateImgLst, long searchedDate) {
1072 int lstSize= dateImgLst.size();
1073
1074 // No photos or the first photo taken is later than the search period
1075 if(lstSize == 0 || searchedDate < dateImgLst.get(0).time.getTime()/1000)
1076 return -1;
1077
1078 // The search period is later than the last photo
1079 if (searchedDate > dateImgLst.get(lstSize - 1).time.getTime() / 1000)
1080 return lstSize-1;
1081
1082 // The searched index is somewhere in the middle, do a binary search from the beginning
1083 int curIndex= 0;
1084 int startIndex= 0;
1085 int endIndex= lstSize-1;
1086 while (endIndex - startIndex > 1) {
1087 curIndex= (int) Math.round((double)(endIndex + startIndex)/2);
1088 if (searchedDate > dateImgLst.get(curIndex).time.getTime()/1000)
1089 startIndex= curIndex;
1090 else
1091 endIndex= curIndex;
1092 }
1093 if (searchedDate < dateImgLst.get(endIndex).time.getTime()/1000)
1094 return startIndex;
1095
1096 // This final loop is to check if photos with the exact same EXIF time follows
1097 while ((endIndex < (lstSize-1)) && (dateImgLst.get(endIndex).time.getTime()
1098 == dateImgLst.get(endIndex + 1).time.getTime()))
1099 endIndex++;
1100 return endIndex;
1101 }
1102
1103
1104 private String formatTimezone(double timezone) {
1105 StringBuffer ret = new StringBuffer();
1106
1107 if (timezone < 0) {
1108 ret.append('-');
1109 timezone = -timezone;
1110 } else {
1111 ret.append('+');
1112 }
1113 ret.append((long) timezone).append(':');
1114 int minutes = (int) ((timezone % 1) * 60);
1115 if (minutes < 10) {
1116 ret.append('0');
1117 }
1118 ret.append(minutes);
1119
1120 return ret.toString();
1121 }
1122
1123 private Float parseTimezone(String timezone) {
1124 if (timezone.length() == 0) {
1125 return new Float(0);
1126 }
1127
1128 char sgnTimezone = '+';
1129 StringBuffer hTimezone = new StringBuffer();
1130 StringBuffer mTimezone = new StringBuffer();
1131 int state = 1; // 1=start/sign, 2=hours, 3=minutes.
1132 for (int i = 0; i < timezone.length(); i++) {
1133 char c = timezone.charAt(i);
1134 switch (c) {
1135 case ' ' :
1136 if (state != 2 || hTimezone.length() != 0) {
1137 return null;
1138 }
1139 break;
1140 case '+' :
1141 case '-' :
1142 if (state == 1) {
1143 sgnTimezone = c;
1144 state = 2;
1145 } else {
1146 return null;
1147 }
1148 break;
1149 case ':' :
1150 case '.' :
1151 if (state == 2) {
1152 state = 3;
1153 } else {
1154 return null;
1155 }
1156 break;
1157 case '0' : case '1' : case '2' : case '3' : case '4' :
1158 case '5' : case '6' : case '7' : case '8' : case '9' :
1159 switch(state) {
1160 case 1 :
1161 case 2 :
1162 state = 2;
1163 hTimezone.append(c);
1164 break;
1165 case 3 :
1166 mTimezone.append(c);
1167 break;
1168 default :
1169 return null;
1170 }
1171 break;
1172 default :
1173 return null;
1174 }
1175 }
1176
1177 int h = 0;
1178 int m = 0;
1179 try {
1180 h = Integer.parseInt(hTimezone.toString());
1181 if (mTimezone.length() > 0) {
1182 m = Integer.parseInt(mTimezone.toString());
1183 }
1184 } catch (NumberFormatException nfe) {
1185 // Invalid timezone
1186 return null;
1187 }
1188
1189 if (h > 12 || m > 59 ) {
1190 return null;
1191 } else {
1192 return new Float((h + m / 60.0) * (sgnTimezone == '-' ? -1 : 1));
1193 }
1194 }
1195}
Note: See TracBrowser for help on using the repository browser.