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

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

cleanup for geoimage code (mainly getters and setters)

  • Property svn:eol-style set to native
File size: 51.6 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
5package org.openstreetmap.josm.gui.layer.geoimage;
6
7import static org.openstreetmap.josm.tools.I18n.tr;
8import static org.openstreetmap.josm.tools.I18n.trn;
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.JButton;
43import javax.swing.JCheckBox;
44import javax.swing.JComboBox;
45import javax.swing.JFileChooser;
46import javax.swing.JLabel;
47import javax.swing.JList;
48import javax.swing.JOptionPane;
49import javax.swing.JPanel;
50import javax.swing.JScrollPane;
51import javax.swing.JSeparator;
52import javax.swing.JSlider;
53import javax.swing.JTextField;
54import javax.swing.ListSelectionModel;
55import javax.swing.SwingConstants;
56import javax.swing.event.ChangeEvent;
57import javax.swing.event.ChangeListener;
58import javax.swing.event.DocumentEvent;
59import javax.swing.event.DocumentListener;
60import javax.swing.event.ListSelectionEvent;
61import javax.swing.event.ListSelectionListener;
62import javax.swing.filechooser.FileFilter;
63
64import org.openstreetmap.josm.Main;
65import org.openstreetmap.josm.data.gpx.GpxData;
66import org.openstreetmap.josm.data.gpx.GpxTrack;
67import org.openstreetmap.josm.data.gpx.GpxTrackSegment;
68import org.openstreetmap.josm.data.gpx.WayPoint;
69import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
70import org.openstreetmap.josm.gui.ExtendedDialog;
71import org.openstreetmap.josm.gui.layer.GpxLayer;
72import org.openstreetmap.josm.gui.layer.Layer;
73import org.openstreetmap.josm.io.GpxReader;
74import org.openstreetmap.josm.tools.ExifReader;
75import org.openstreetmap.josm.tools.GBC;
76import org.openstreetmap.josm.tools.ImageProvider;
77import org.openstreetmap.josm.tools.PrimaryDateParser;
78import org.xml.sax.SAXException;
79
80/** This class displays the window to select the GPX file and the offset (timezone + delta).
81 * Then it correlates the images of the layer with that GPX file.
82 */
83public class CorrelateGpxWithImages implements ActionListener {
84
85 private static List<GpxData> loadedGpxData = new ArrayList<GpxData>();
86
87 GeoImageLayer yLayer = null;
88 double timezone;
89 long delta;
90
91 public CorrelateGpxWithImages(GeoImageLayer layer) {
92 this.yLayer = layer;
93 }
94
95 private static class GpxDataWrapper {
96 String name;
97 GpxData data;
98 File file;
99
100 public GpxDataWrapper(String name, GpxData data, File file) {
101 this.name = name;
102 this.data = data;
103 this.file = file;
104 }
105
106 @Override
107 public String toString() {
108 return name;
109 }
110 }
111
112 ExtendedDialog syncDialog;
113 Vector<GpxDataWrapper> gpxLst = new Vector<GpxDataWrapper>();
114 JPanel outerPanel;
115 JComboBox cbGpx;
116 JTextField tfTimezone;
117 JTextField tfOffset;
118 JCheckBox cbExifImg;
119 JCheckBox cbTaggedImg;
120 JCheckBox cbShowThumbs;
121 JLabel statusBarText;
122 StatusBarListener statusBarListener;
123
124 // remember the last number of matched photos
125 int lastNumMatched = 0;
126
127 /** This class is called when the user doesn't find the GPX file he needs in the files that have
128 * been loaded yet. It displays a FileChooser dialog to select the GPX file to be loaded.
129 */
130 private class LoadGpxDataActionListener implements ActionListener {
131
132 public void actionPerformed(ActionEvent arg0) {
133 JFileChooser fc = new JFileChooser(Main.pref.get("lastDirectory"));
134 fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
135 fc.setAcceptAllFileFilterUsed(false);
136 fc.setMultiSelectionEnabled(false);
137 fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
138 fc.setFileFilter(new FileFilter(){
139 @Override public boolean accept(File f) {
140 return (f.isDirectory()
141 || f .getName().toLowerCase().endsWith(".gpx")
142 || f.getName().toLowerCase().endsWith(".gpx.gz"));
143 }
144 @Override public String getDescription() {
145 return tr("GPX Files (*.gpx *.gpx.gz)");
146 }
147 });
148 fc.showOpenDialog(Main.parent);
149 File sel = fc.getSelectedFile();
150 if (sel == null)
151 return;
152
153 try {
154 outerPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
155
156 Main.pref.put("lastDirectory", sel.getPath());
157
158 for (int i = gpxLst.size() - 1 ; i >= 0 ; i--) {
159 GpxDataWrapper wrapper = gpxLst.get(i);
160 if (wrapper.file != null && sel.equals(wrapper.file)) {
161 cbGpx.setSelectedIndex(i);
162 if (!sel.getName().equals(wrapper.name)) {
163 JOptionPane.showMessageDialog(
164 Main.parent,
165 tr("File {0} is loaded yet under the name \"{1}\"", sel.getName(), wrapper.name),
166 tr("Error"),
167 JOptionPane.ERROR_MESSAGE
168 );
169 }
170 return;
171 }
172 }
173 GpxData data = null;
174 try {
175 InputStream iStream;
176 if (sel.getName().toLowerCase().endsWith(".gpx.gz")) {
177 iStream = new GZIPInputStream(new FileInputStream(sel));
178 } else {
179 iStream = new FileInputStream(sel);
180 }
181 GpxReader reader = new GpxReader(iStream);
182 reader.parse(false);
183 data = reader.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 am 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).getFile().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).getFile());
347 Date date = yLayer.data.get(index).getExifTime();
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 another 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.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 JButton buttonViewGpsPhoto = new JButton(tr("<html>Use photo of an accurate clock,<br>"
508 + "e.g. GPS receiver display</html>"));
509 buttonViewGpsPhoto.setIcon(ImageProvider.get("clock"));
510 buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener());
511
512 JButton buttonAutoGuess = new JButton(tr("Auto-Guess"));
513 buttonAutoGuess.addActionListener(new AutoGuessActionListener());
514
515 JButton buttonAdjust = new JButton(tr("Manual adjust"));
516 buttonAdjust.addActionListener(new AdjustActionListener());
517
518 JLabel labelPosition = new JLabel(tr("Override position for: "));
519
520 int numAll = getSortedImgList(true, true).size();
521 int numExif = numAll - getSortedImgList(false, true).size();
522 int numTagged = numAll - getSortedImgList(true, false).size();
523
524 cbExifImg = new JCheckBox(tr("Images with geo location in exif data ({0}/{1})", numExif, numAll));
525 cbExifImg.setEnabled(numExif != 0);
526
527 cbTaggedImg = new JCheckBox(tr("Images that are already tagged ({0}/{1})", numTagged, numAll), true);
528 cbTaggedImg.setEnabled(numTagged != 0);
529
530 labelPosition.setEnabled(cbExifImg.isEnabled() || cbTaggedImg.isEnabled());
531
532 boolean ticked = yLayer.thumbsLoaded || Main.pref.getBoolean("geoimage.showThumbs", false);
533 cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), ticked);
534 cbShowThumbs.setEnabled(!yLayer.thumbsLoaded);
535 /*cbShowThumbs.addItemListener(new ItemListener() {
536 public void itemStateChanged(ItemEvent e) {
537 if (e.getStateChange() == ItemEvent.SELECTED) {
538 yLayer.loadThumbs();
539 } else {
540 }
541 }
542 });*/
543
544 int y=0;
545 GBC gbc = GBC.eol();
546 gbc.gridx = 0;
547 gbc.gridy = y++;
548 panelTf.add(panelCb, gbc);
549
550 gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0,0,0,12);
551 gbc.gridx = 0;
552 gbc.gridy = y++;
553 panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);
554
555 gbc = GBC.std();
556 gbc.gridx = 0;
557 gbc.gridy = y;
558 panelTf.add(new JLabel(tr("Timezone: ")), gbc);
559
560 gbc = GBC.std().fill(GBC.HORIZONTAL);
561 gbc.gridx = 1;
562 gbc.gridy = y++;
563 gbc.weightx = 1.;
564 panelTf.add(tfTimezone, gbc);
565
566 gbc = GBC.std();
567 gbc.gridx = 0;
568 gbc.gridy = y;
569 panelTf.add(new JLabel(tr("Offset:")), gbc);
570
571 gbc = GBC.std().fill(GBC.HORIZONTAL);
572 gbc.gridx = 1;
573 gbc.gridy = y++;
574 gbc.weightx = 1.;
575 panelTf.add(tfOffset, gbc);
576
577 gbc = GBC.std().insets(5,5,5,5);
578 gbc.gridx = 2;
579 gbc.gridy = y-2;
580 gbc.gridheight = 2;
581 gbc.gridwidth = 2;
582 gbc.fill = GridBagConstraints.BOTH;
583 gbc.weightx = 0.5;
584 panelTf.add(buttonViewGpsPhoto, gbc);
585
586 gbc = GBC.std().fill(GBC.BOTH).insets(5,5,5,5);
587 gbc.gridx = 2;
588 gbc.gridy = y++;
589 gbc.weightx = 0.5;
590 panelTf.add(buttonAutoGuess, gbc);
591
592 gbc.gridx = 3;
593 panelTf.add(buttonAdjust, gbc);
594
595 gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0,12,0,0);
596 gbc.gridx = 0;
597 gbc.gridy = y++;
598 panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);
599
600 gbc = GBC.eol();
601 gbc.gridx = 0;
602 gbc.gridy = y++;
603 panelTf.add(labelPosition, gbc);
604
605 gbc = GBC.eol();
606 gbc.gridx = 1;
607 gbc.gridy = y++;
608 panelTf.add(cbExifImg, gbc);
609
610 gbc = GBC.eol();
611 gbc.gridx = 1;
612 gbc.gridy = y++;
613 panelTf.add(cbTaggedImg, gbc);
614
615 gbc = GBC.eol();
616 gbc.gridx = 0;
617 gbc.gridy = y++;
618 panelTf.add(cbShowThumbs, gbc);
619
620 final JPanel statusBar = new JPanel();
621 statusBar.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
622 statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
623 statusBarText = new JLabel(" ");
624 statusBarText.setFont(statusBarText.getFont().deriveFont(8));
625 statusBar.add(statusBarText);
626
627 statusBarListener = new StatusBarListener() {
628 @Override
629 public void updateStatusBar() {
630 statusBarText.setText(statusText());
631 }
632 private String statusText() {
633 try {
634 timezone = parseTimezone(tfTimezone.getText().trim());
635 delta = parseOffset(tfOffset.getText().trim());
636 } catch (ParseException e) {
637 return e.getMessage();
638 }
639
640 // Construct a list of images that have a date, and sort them on the date.
641 ArrayList<ImageEntry> dateImgLst = getSortedImgList();
642 for (ImageEntry ie : dateImgLst) {
643 ie.cleanTmp();
644 }
645
646 GpxDataWrapper selGpx = selectedGPX(false);
647 if (selGpx == null)
648 return tr("No gpx selected");
649
650 final long offset_ms = ((long) (timezone * 3600) + delta) * 1000; // in milliseconds
651 lastNumMatched = matchGpxTrack(dateImgLst, selGpx.data, offset_ms);
652
653 return trn("<html>Matched <b>{0}</b> of <b>{1}</b> photo to GPX track.</html>",
654 "<html>Matched <b>{0}</b> of <b>{1}</b> photos to GPX track.</html>",
655 dateImgLst.size(), lastNumMatched, dateImgLst.size());
656 }
657 };
658
659 tfTimezone.getDocument().addDocumentListener(statusBarListener);
660 tfOffset.getDocument().addDocumentListener(statusBarListener);
661 cbExifImg.addItemListener(statusBarListener);
662 cbTaggedImg.addItemListener(statusBarListener);
663
664 statusBarListener.updateStatusBar();
665
666 outerPanel = new JPanel();
667 outerPanel.setLayout(new BorderLayout());
668 outerPanel.add(statusBar, BorderLayout.PAGE_END);
669
670 syncDialog = new ExtendedDialog(
671 Main.parent,
672 tr("Correlate images with GPX track"),
673 new String[] { tr("Correlate"), tr("Cancel") },
674 false
675 );
676 syncDialog.setContent(panelTf, false);
677 syncDialog.setButtonIcons(new String[] { "ok.png", "cancel.png" });
678 syncDialog.setupDialog();
679 outerPanel.add(syncDialog.getContentPane(), BorderLayout.PAGE_START);
680 syncDialog.setContentPane(outerPanel);
681 syncDialog.pack();
682 syncDialog.addWindowListener(new WindowAdapter() {
683 final static int CANCEL = -1;
684 final static int DONE = 0;
685 final static int AGAIN = 1;
686 final static int NOTHING = 2;
687 private int checkAndSave() {
688 if (syncDialog.isVisible())
689 // nothing happened: JOSM was minimized or similar
690 return NOTHING;
691 int answer = syncDialog.getValue();
692 if(answer != 1)
693 return CANCEL;
694
695 // Parse values again, to display an error if the format is not recognized
696 try {
697 timezone = parseTimezone(tfTimezone.getText().trim());
698 } catch (ParseException e) {
699 JOptionPane.showMessageDialog(Main.parent, e.getMessage(),
700 tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE);
701 return AGAIN;
702 }
703
704 try {
705 delta = parseOffset(tfOffset.getText().trim());
706 } catch (ParseException e) {
707 JOptionPane.showMessageDialog(Main.parent, e.getMessage(),
708 tr("Invalid offset"), JOptionPane.ERROR_MESSAGE);
709 return AGAIN;
710 }
711
712 if (lastNumMatched == 0) {
713 if (new ExtendedDialog(
714 Main.parent,
715 tr("Correlate images with GPX track"),
716 new String[] { tr("OK"), tr("Try Again") }).
717 setContent(tr("No images could be matched!")).
718 setButtonIcons(new String[] { "ok.png", "dialogs/refresh.png"}).
719 showDialog().getValue() == 2)
720 return AGAIN;
721 }
722 return DONE;
723 }
724
725 @Override
726 public void windowDeactivated(WindowEvent e) {
727 int result = checkAndSave();
728 switch (result) {
729 case NOTHING:
730 break;
731 case CANCEL:
732 {
733 for (ImageEntry ie : yLayer.data) {
734 ie.tmp = null;
735 }
736 yLayer.updateBufferAndRepaint();
737 break;
738 }
739 case AGAIN:
740 actionPerformed(null);
741 break;
742 case DONE:
743 {
744 Main.pref.put("geoimage.timezone", formatTimezone(timezone));
745 Main.pref.put("geoimage.delta", Long.toString(delta * 1000));
746 Main.pref.put("geoimage.showThumbs", yLayer.useThumbs);
747
748 yLayer.useThumbs = cbShowThumbs.isSelected();
749 yLayer.loadThumbs();
750
751 // Search whether an other layer has yet defined some bounding box.
752 // If none, we'll zoom to the bounding box of the layer with the photos.
753 boolean boundingBoxedLayerFound = false;
754 for (Layer l: Main.map.mapView.getAllLayers()) {
755 if (l != yLayer) {
756 BoundingXYVisitor bbox = new BoundingXYVisitor();
757 l.visitBoundingBox(bbox);
758 if (bbox.getBounds() != null) {
759 boundingBoxedLayerFound = true;
760 break;
761 }
762 }
763 }
764 if (! boundingBoxedLayerFound) {
765 BoundingXYVisitor bbox = new BoundingXYVisitor();
766 yLayer.visitBoundingBox(bbox);
767 Main.map.mapView.recalculateCenterScale(bbox);
768 }
769
770 for (ImageEntry ie : yLayer.data) {
771 ie.applyTmp();
772 }
773
774 yLayer.updateBufferAndRepaint();
775
776 break;
777 }
778 default:
779 throw new IllegalStateException();
780 }
781 }
782 });
783 syncDialog.showDialog();
784 }
785
786 private static abstract class StatusBarListener implements DocumentListener, ItemListener {
787 public void insertUpdate(DocumentEvent ev) {
788 updateStatusBar();
789 }
790 public void removeUpdate(DocumentEvent ev) {
791 updateStatusBar();
792 }
793 public void changedUpdate(DocumentEvent ev) {
794 }
795 public void itemStateChanged(ItemEvent e) {
796 updateStatusBar();
797 }
798 abstract public void updateStatusBar();
799 }
800
801 /**
802 * Presents dialog with sliders for manual adjust.
803 */
804 private class AdjustActionListener implements ActionListener {
805
806 public void actionPerformed(ActionEvent arg0) {
807
808 long diff = delta + Math.round(timezone*60*60);
809
810 double diffInH = (double)diff/(60*60); // hours
811
812 // Find day difference
813 final int dayOffset = (int)Math.round(diffInH / 24); // days
814 double tmz = diff - dayOffset*24*60*60l; // seconds
815
816 // In hours, rounded to two decimal places
817 tmz = (double)Math.round(tmz*100/(60*60)) / 100;
818
819 // Due to imprecise clocks we might get a "+3:28" timezone, which should obviously be 3:30 with
820 // -2 minutes offset. This determines the real timezone and finds offset.
821 double fixTimezone = (double)Math.round(tmz * 2)/2; // hours, rounded to one decimal place
822 int offset = (int)Math.round(diff - fixTimezone*60*60) - dayOffset*24*60*60; // seconds
823
824 // Info Labels
825 final JLabel lblMatches = new JLabel();
826
827 // Timezone Slider
828 // The slider allows to switch timezon from -12:00 to 12:00 in 30 minutes
829 // steps. Therefore the range is -24 to 24.
830 final JLabel lblTimezone = new JLabel();
831 final JSlider sldTimezone = new JSlider(-24, 24, 0);
832 sldTimezone.setPaintLabels(true);
833 Hashtable<Integer,JLabel> labelTable = new Hashtable<Integer, JLabel>();
834 labelTable.put(-24, new JLabel("-12:00"));
835 labelTable.put(-12, new JLabel( "-6:00"));
836 labelTable.put( 0, new JLabel( "0:00"));
837 labelTable.put( 12, new JLabel( "6:00"));
838 labelTable.put( 24, new JLabel( "12:00"));
839 sldTimezone.setLabelTable(labelTable);
840
841 // Minutes Slider
842 final JLabel lblMinutes = new JLabel();
843 final JSlider sldMinutes = new JSlider(-15, 15, 0);
844 sldMinutes.setPaintLabels(true);
845 sldMinutes.setMajorTickSpacing(5);
846
847 // Seconds slider
848 final JLabel lblSeconds = new JLabel();
849 final JSlider sldSeconds = new JSlider(-60, 60, 0);
850 sldSeconds.setPaintLabels(true);
851 sldSeconds.setMajorTickSpacing(30);
852
853 // This is called whenever one of the sliders is moved.
854 // It updates the labels and also calls the "match photos" code
855 class sliderListener implements ChangeListener {
856 public void stateChanged(ChangeEvent e) {
857 // parse slider position into real timezone
858 double tz = Math.abs(sldTimezone.getValue());
859 String zone = tz % 2 == 0
860 ? (int)Math.floor(tz/2) + ":00"
861 : (int)Math.floor(tz/2) + ":30";
862 if(sldTimezone.getValue() < 0) {
863 zone = "-" + zone;
864 }
865
866 lblTimezone.setText(tr("Timezone: {0}", zone));
867 lblMinutes.setText(tr("Minutes: {0}", sldMinutes.getValue()));
868 lblSeconds.setText(tr("Seconds: {0}", sldSeconds.getValue()));
869
870 try {
871 timezone = parseTimezone(zone);
872 } catch (ParseException pe) {
873 throw new RuntimeException();
874 }
875 delta = sldMinutes.getValue()*60 + sldSeconds.getValue();
876
877 tfTimezone.getDocument().removeDocumentListener(statusBarListener);
878 tfOffset.getDocument().removeDocumentListener(statusBarListener);
879
880 tfTimezone.setText(formatTimezone(timezone));
881 tfOffset.setText(Long.toString(delta + 24*60*60L*dayOffset)); // add the day offset to the offset field
882
883 tfTimezone.getDocument().addDocumentListener(statusBarListener);
884 tfOffset.getDocument().addDocumentListener(statusBarListener);
885
886 lblMatches.setText(statusBarText.getText() + "<br>" + trn("(Time difference of {0} day)", "Time difference of {0} days", Math.abs(dayOffset), Math.abs(dayOffset)));
887
888 statusBarListener.updateStatusBar();
889 yLayer.updateBufferAndRepaint();
890 }
891 }
892
893 // Put everything together
894 JPanel p = new JPanel(new GridBagLayout());
895 p.setPreferredSize(new Dimension(400, 230));
896 p.add(lblMatches, GBC.eol().fill());
897 p.add(lblTimezone, GBC.eol().fill());
898 p.add(sldTimezone, GBC.eol().fill().insets(0, 0, 0, 10));
899 p.add(lblMinutes, GBC.eol().fill());
900 p.add(sldMinutes, GBC.eol().fill().insets(0, 0, 0, 10));
901 p.add(lblSeconds, GBC.eol().fill());
902 p.add(sldSeconds, GBC.eol().fill());
903
904 // If there's an error in the calculation the found values
905 // will be off range for the sliders. Catch this error
906 // and inform the user about it.
907 try {
908 sldTimezone.setValue((int)(fixTimezone*2));
909 sldMinutes.setValue(offset/60);
910 sldSeconds.setValue(offset%60);
911 } catch(Exception e) {
912 JOptionPane.showMessageDialog(Main.parent,
913 tr("An error occurred while trying to match the photos to the GPX track."
914 +" You can adjust the sliders to manually match the photos."),
915 tr("Matching photos to track failed"),
916 JOptionPane.WARNING_MESSAGE);
917 }
918
919 // Call the sliderListener once manually so labels get adjusted
920 new sliderListener().stateChanged(null);
921 // Listeners added here, otherwise it tries to match three times
922 // (when setting the default values)
923 sldTimezone.addChangeListener(new sliderListener());
924 sldMinutes.addChangeListener(new sliderListener());
925 sldSeconds.addChangeListener(new sliderListener());
926
927 // There is no way to cancel this dialog, all changes get applied
928 // immediately. Therefore "Close" is marked with an "OK" icon.
929 // Settings are only saved temporarily to the layer.
930 new ExtendedDialog(Main.parent,
931 tr("Adjust timezone and offset"),
932 new String[] { tr("Close")}).
933 setContent(p).setButtonIcons(new String[] {"ok.png"}).showDialog();
934 }
935 }
936
937 private class AutoGuessActionListener implements ActionListener {
938
939 public void actionPerformed(ActionEvent arg0) {
940 GpxDataWrapper gpxW = selectedGPX(true);
941 if (gpxW == null)
942 return;
943 GpxData gpx = gpxW.data;
944
945 ArrayList<ImageEntry> imgs = getSortedImgList();
946 PrimaryDateParser dateParser = new PrimaryDateParser();
947
948 // no images found, exit
949 if(imgs.size() <= 0) {
950 JOptionPane.showMessageDialog(Main.parent,
951 tr("The selected photos do not contain time information."),
952 tr("Photos do not contain time information"), JOptionPane.WARNING_MESSAGE);
953 return;
954 }
955
956 // Init variables
957 long firstExifDate = imgs.get(0).getExifTime().getTime()/1000;
958
959 long firstGPXDate = -1;
960 // Finds first GPX point
961 outer: for (GpxTrack trk : gpx.tracks) {
962 for (GpxTrackSegment segment : trk.getSegments()) {
963 for (WayPoint curWp : segment.getWayPoints()) {
964 String curDateWpStr = (String) curWp.attr.get("time");
965 if (curDateWpStr == null) {
966 continue;
967 }
968
969 try {
970 firstGPXDate = dateParser.parse(curDateWpStr).getTime()/1000;
971 break outer;
972 } catch(Exception e) {}
973 }
974 }
975 }
976
977 // No GPX timestamps found, exit
978 if(firstGPXDate < 0) {
979 JOptionPane.showMessageDialog(Main.parent,
980 tr("The selected GPX track does not contain timestamps. Please select another one."),
981 tr("GPX Track has no time information"), JOptionPane.WARNING_MESSAGE);
982 return;
983 }
984
985 // seconds
986 long diff = firstExifDate - firstGPXDate;
987
988 double diffInH = (double)diff/(60*60); // hours
989
990 // Find day difference
991 int dayOffset = (int)Math.round(diffInH / 24); // days
992 double tz = diff - dayOffset*24*60*60l; // seconds
993
994 // In hours, rounded to two decimal places
995 tz = (double)Math.round(tz*100/(60*60)) / 100;
996
997 // Due to imprecise clocks we might get a "+3:28" timezone, which should obviously be 3:30 with
998 // -2 minutes offset. This determines the real timezone and finds offset.
999 timezone = (double)Math.round(tz * 2)/2; // hours, rounded to one decimal place
1000 delta = Math.round(diff - timezone*60*60); // seconds
1001
1002 /*System.out.println("phto " + firstExifDate);
1003 System.out.println("gpx " + firstGPXDate);
1004 System.out.println("diff " + diff);
1005 System.out.println("difh " + diffInH);
1006 System.out.println("days " + dayOffset);
1007 System.out.println("time " + tz);
1008 System.out.println("fix " + timezone);
1009 System.out.println("offt " + delta);*/
1010
1011 tfTimezone.getDocument().removeDocumentListener(statusBarListener);
1012 tfOffset.getDocument().removeDocumentListener(statusBarListener);
1013
1014 tfTimezone.setText(formatTimezone(timezone));
1015 tfOffset.setText(Long.toString(delta));
1016 tfOffset.requestFocus();
1017
1018 tfTimezone.getDocument().addDocumentListener(statusBarListener);
1019 tfOffset.getDocument().addDocumentListener(statusBarListener);
1020
1021 statusBarListener.updateStatusBar();
1022 yLayer.updateBufferAndRepaint();
1023 }
1024 }
1025
1026 private ArrayList<ImageEntry> getSortedImgList() {
1027 return getSortedImgList(cbExifImg.isSelected(), cbTaggedImg.isSelected());
1028 }
1029
1030 /**
1031 * Returns a list of images that fulfill the given criteria.
1032 * Default setting is to return untagged images, but may be overwritten.
1033 * @param boolean all -- returns all available images
1034 * @param boolean noexif -- returns untagged images without EXIF-GPS coords
1035 * this parameter is irrelevant if <code>all</code> is true
1036 * @param boolean exif -- also returns images with exif-gps info
1037 * @param boolean tagged -- also returns tagged images
1038 * @return ArrayList<ImageEntry> matching images
1039 */
1040 private ArrayList<ImageEntry> getSortedImgList(boolean exif, boolean tagged) {
1041 ArrayList<ImageEntry> dateImgLst = new ArrayList<ImageEntry>(yLayer.data.size());
1042 for (ImageEntry e : yLayer.data) {
1043 if (e.getExifTime() == null) {
1044 continue;
1045 }
1046
1047 if (e.getExifCoor() != null) {
1048 if (!exif) {
1049 continue;
1050 }
1051 }
1052
1053 if (e.isTagged() && e.getExifCoor() == null) {
1054 if (!tagged) {
1055 continue;
1056 }
1057 }
1058
1059 dateImgLst.add(e);
1060 }
1061
1062 Collections.sort(dateImgLst, new Comparator<ImageEntry>() {
1063 public int compare(ImageEntry arg0, ImageEntry arg1) {
1064 return arg0.getExifTime().compareTo(arg1.getExifTime());
1065 }
1066 });
1067
1068 return dateImgLst;
1069 }
1070
1071 private GpxDataWrapper selectedGPX(boolean complain) {
1072 Object item = cbGpx.getSelectedItem();
1073
1074 if (item == null || ((GpxDataWrapper) item).file == null) {
1075 if (complain) {
1076 JOptionPane.showMessageDialog(Main.parent, tr("You should select a GPX track"),
1077 tr("No selected GPX track"), JOptionPane.ERROR_MESSAGE );
1078 }
1079 return null;
1080 }
1081 return (GpxDataWrapper) item;
1082 }
1083
1084 /**
1085 * Match a list of photos to a gpx track with a given offset.
1086 * All images need a exifTime attribute and the List must be sorted according to these times.
1087 */
1088 private int matchGpxTrack(ArrayList<ImageEntry> images, GpxData selectedGpx, long offset) {
1089 int ret = 0;
1090
1091 PrimaryDateParser dateParser = new PrimaryDateParser();
1092
1093 for (GpxTrack trk : selectedGpx.tracks) {
1094 for (GpxTrackSegment segment : trk.getSegments()) {
1095
1096 long prevWpTime = 0;
1097 WayPoint prevWp = null;
1098
1099 for (WayPoint curWp : segment.getWayPoints()) {
1100
1101 String curWpTimeStr = (String) curWp.attr.get("time");
1102 if (curWpTimeStr != null) {
1103
1104 try {
1105 long curWpTime = dateParser.parse(curWpTimeStr).getTime() + offset;
1106 ret += matchPoints(images, prevWp, prevWpTime, curWp, curWpTime, offset);
1107
1108 prevWp = curWp;
1109 prevWpTime = curWpTime;
1110
1111 } catch(ParseException e) {
1112 System.err.println("Error while parsing date \"" + curWpTimeStr + '"');
1113 e.printStackTrace();
1114 prevWp = null;
1115 prevWpTime = 0;
1116 }
1117 } else {
1118 prevWp = null;
1119 prevWpTime = 0;
1120 }
1121 }
1122 }
1123 }
1124 return ret;
1125 }
1126
1127 private int matchPoints(ArrayList<ImageEntry> images, WayPoint prevWp, long prevWpTime,
1128 WayPoint curWp, long curWpTime, long offset) {
1129 // Time between the track point and the previous one, 5 sec if first point, i.e. photos take
1130 // 5 sec before the first track point can be assumed to be take at the starting position
1131 long interval = prevWpTime > 0 ? ((long)Math.abs(curWpTime - prevWpTime)) : 5*1000;
1132 int ret = 0;
1133
1134 // i is the index of the timewise last photo that has the same or earlier EXIF time
1135 int i = getLastIndexOfListBefore(images, curWpTime);
1136
1137 // no photos match
1138 if (i < 0)
1139 return 0;
1140
1141 Double speed = null;
1142 Double prevElevation = null;
1143 Double curElevation = null;
1144
1145 if (prevWp != null) {
1146 double distance = prevWp.getCoor().greatCircleDistance(curWp.getCoor());
1147 // This is in km/h, 3.6 * m/s
1148 if (curWpTime > prevWpTime) {
1149 speed = 3.6 * distance / (curWpTime - prevWpTime);
1150 }
1151 try {
1152 prevElevation = new Double((String) prevWp.attr.get("ele"));
1153 } catch(Exception e) {}
1154 }
1155
1156 try {
1157 curElevation = new Double((String) curWp.attr.get("ele"));
1158 } catch (Exception e) {}
1159
1160 // First trackpoint, then interval is set to five seconds, i.e. photos up to five seconds
1161 // before the first point will be geotagged with the starting point
1162 if(prevWpTime == 0 || curWpTime <= prevWpTime) {
1163 while (true) {
1164 if (i < 0)
1165 break;
1166 final ImageEntry curImg = images.get(i);
1167 if (curImg.getExifTime().getTime() > curWpTime
1168 || curImg.getExifTime().getTime() < curWpTime - interval)
1169 break;
1170 if(curImg.tmp.getPos() == null) {
1171 curImg.tmp.setPos(curWp.getCoor());
1172 curImg.tmp.setSpeed(speed);
1173 curImg.tmp.setElevation(curElevation);
1174 curImg.tmp.setGpsTime(new Date(curImg.getExifTime().getTime() - offset));
1175 ret++;
1176 }
1177 i--;
1178 }
1179 return ret;
1180 }
1181
1182 // This code gives a simple linear interpolation of the coordinates between current and
1183 // previous track point assuming a constant speed in between
1184 while (true) {
1185 if (i < 0)
1186 break;
1187 ImageEntry curImg = images.get(i);
1188 long imgTime = curImg.getExifTime().getTime();
1189 if (imgTime < prevWpTime)
1190 break;
1191
1192 if(curImg.tmp.getPos() == null) {
1193 // The values of timeDiff are between 0 and 1, it is not seconds but a dimensionless
1194 // variable
1195 double timeDiff = (double)(imgTime - prevWpTime) / interval;
1196 curImg.tmp.setPos(prevWp.getCoor().interpolate(curWp.getCoor(), timeDiff));
1197 curImg.tmp.setSpeed(speed);
1198 if (curElevation != null && prevElevation != null) {
1199 curImg.setElevation(prevElevation + (curElevation - prevElevation) * timeDiff);
1200 }
1201 curImg.tmp.setGpsTime(new Date(curImg.getExifTime().getTime() - offset));
1202
1203 ret++;
1204 }
1205 i--;
1206 }
1207 return ret;
1208 }
1209
1210 private int getLastIndexOfListBefore(ArrayList<ImageEntry> images, long searchedTime) {
1211 int lstSize= images.size();
1212
1213 // No photos or the first photo taken is later than the search period
1214 if(lstSize == 0 || searchedTime < images.get(0).getExifTime().getTime())
1215 return -1;
1216
1217 // The search period is later than the last photo
1218 if (searchedTime > images.get(lstSize - 1).getExifTime().getTime())
1219 return lstSize-1;
1220
1221 // The searched index is somewhere in the middle, do a binary search from the beginning
1222 int curIndex= 0;
1223 int startIndex= 0;
1224 int endIndex= lstSize-1;
1225 while (endIndex - startIndex > 1) {
1226 curIndex= (endIndex + startIndex) / 2;
1227 if (searchedTime > images.get(curIndex).getExifTime().getTime()) {
1228 startIndex= curIndex;
1229 } else {
1230 endIndex= curIndex;
1231 }
1232 }
1233 if (searchedTime < images.get(endIndex).getExifTime().getTime())
1234 return startIndex;
1235
1236 // This final loop is to check if photos with the exact same EXIF time follows
1237 while ((endIndex < (lstSize-1)) && (images.get(endIndex).getExifTime().getTime()
1238 == images.get(endIndex + 1).getExifTime().getTime())) {
1239 endIndex++;
1240 }
1241 return endIndex;
1242 }
1243
1244 private String formatTimezone(double timezone) {
1245 StringBuffer ret = new StringBuffer();
1246
1247 if (timezone < 0) {
1248 ret.append('-');
1249 timezone = -timezone;
1250 } else {
1251 ret.append('+');
1252 }
1253 ret.append((long) timezone).append(':');
1254 int minutes = (int) ((timezone % 1) * 60);
1255 if (minutes < 10) {
1256 ret.append('0');
1257 }
1258 ret.append(minutes);
1259
1260 return ret.toString();
1261 }
1262
1263 private double parseTimezone(String timezone) throws ParseException {
1264
1265 String error = tr("Error while parsing timezone.\nExpected format: {0}", "+H:MM");
1266
1267 if (timezone.length() == 0)
1268 return 0;
1269
1270 char sgnTimezone = '+';
1271 StringBuffer hTimezone = new StringBuffer();
1272 StringBuffer mTimezone = new StringBuffer();
1273 int state = 1; // 1=start/sign, 2=hours, 3=minutes.
1274 for (int i = 0; i < timezone.length(); i++) {
1275 char c = timezone.charAt(i);
1276 switch (c) {
1277 case ' ' :
1278 if (state != 2 || hTimezone.length() != 0)
1279 throw new ParseException(error,0);
1280 break;
1281 case '+' :
1282 case '-' :
1283 if (state == 1) {
1284 sgnTimezone = c;
1285 state = 2;
1286 } else
1287 throw new ParseException(error,0);
1288 break;
1289 case ':' :
1290 case '.' :
1291 if (state == 2) {
1292 state = 3;
1293 } else
1294 throw new ParseException(error,0);
1295 break;
1296 case '0' : case '1' : case '2' : case '3' : case '4' :
1297 case '5' : case '6' : case '7' : case '8' : case '9' :
1298 switch(state) {
1299 case 1 :
1300 case 2 :
1301 state = 2;
1302 hTimezone.append(c);
1303 break;
1304 case 3 :
1305 mTimezone.append(c);
1306 break;
1307 default :
1308 throw new ParseException(error,0);
1309 }
1310 break;
1311 default :
1312 throw new ParseException(error,0);
1313 }
1314 }
1315
1316 int h = 0;
1317 int m = 0;
1318 try {
1319 h = Integer.parseInt(hTimezone.toString());
1320 if (mTimezone.length() > 0) {
1321 m = Integer.parseInt(mTimezone.toString());
1322 }
1323 } catch (NumberFormatException nfe) {
1324 // Invalid timezone
1325 throw new ParseException(error,0);
1326 }
1327
1328 if (h > 12 || m > 59 )
1329 throw new ParseException(error,0);
1330 else
1331 return (h + m / 60.0) * (sgnTimezone == '-' ? -1 : 1);
1332 }
1333
1334 private long parseOffset(String offset) throws ParseException {
1335 String error = tr("Error while parsing offset.\nExpected format: {0}", "number");
1336
1337 if (offset.length() > 0) {
1338 try {
1339 if(offset.startsWith("+")) {
1340 offset = offset.substring(1);
1341 }
1342 return Long.parseLong(offset);
1343 } catch(NumberFormatException nfe) {
1344 throw new ParseException(error,0);
1345 }
1346 } else
1347 return 0;
1348 }
1349}
Note: See TracBrowser for help on using the repository browser.