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

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

geoimage: reworked image correlation dialog. Might still have some quirks here and there. New: displays and updates the number of matched images in the status bar while you type.

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