001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.layer.geoimage;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005import static org.openstreetmap.josm.tools.I18n.trn;
006
007import java.awt.BorderLayout;
008import java.awt.Cursor;
009import java.awt.FlowLayout;
010import java.awt.Font;
011import java.awt.GraphicsEnvironment;
012import java.awt.GridBagConstraints;
013import java.awt.GridBagLayout;
014import java.awt.event.ActionEvent;
015import java.awt.event.ActionListener;
016import java.awt.event.FocusEvent;
017import java.awt.event.FocusListener;
018import java.awt.event.ItemEvent;
019import java.awt.event.ItemListener;
020import java.awt.event.WindowAdapter;
021import java.awt.event.WindowEvent;
022import java.beans.PropertyChangeEvent;
023import java.beans.PropertyChangeListener;
024import java.io.File;
025import java.text.ParseException;
026import java.util.List;
027import java.util.Objects;
028import java.util.Optional;
029import java.util.TimeZone;
030import java.util.concurrent.TimeUnit;
031import java.util.function.Consumer;
032
033import javax.swing.AbstractAction;
034import javax.swing.BorderFactory;
035import javax.swing.ButtonGroup;
036import javax.swing.DefaultComboBoxModel;
037import javax.swing.JButton;
038import javax.swing.JCheckBox;
039import javax.swing.JLabel;
040import javax.swing.JOptionPane;
041import javax.swing.JPanel;
042import javax.swing.JRadioButton;
043import javax.swing.JSeparator;
044import javax.swing.SwingConstants;
045import javax.swing.event.ChangeEvent;
046import javax.swing.event.ChangeListener;
047import javax.swing.event.DocumentEvent;
048import javax.swing.event.DocumentListener;
049
050import org.openstreetmap.josm.actions.ExpertToggleAction;
051import org.openstreetmap.josm.actions.ExpertToggleAction.ExpertModeChangeListener;
052import org.openstreetmap.josm.data.gpx.GpxData;
053import org.openstreetmap.josm.data.gpx.GpxData.GpxDataChangeEvent;
054import org.openstreetmap.josm.data.gpx.GpxData.GpxDataChangeListener;
055import org.openstreetmap.josm.data.gpx.GpxDataContainer;
056import org.openstreetmap.josm.data.gpx.GpxImageCorrelation;
057import org.openstreetmap.josm.data.gpx.GpxImageCorrelationSettings;
058import org.openstreetmap.josm.data.gpx.GpxImageDatumSettings;
059import org.openstreetmap.josm.data.gpx.GpxTimeOffset;
060import org.openstreetmap.josm.data.gpx.GpxTimezone;
061import org.openstreetmap.josm.data.gpx.TimeSource;
062import org.openstreetmap.josm.data.gpx.WayPoint;
063import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
064import org.openstreetmap.josm.gui.ExtendedDialog;
065import org.openstreetmap.josm.gui.MainApplication;
066import org.openstreetmap.josm.gui.layer.AbstractModifiableLayer;
067import org.openstreetmap.josm.gui.layer.Layer;
068import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
069import org.openstreetmap.josm.gui.layer.LayerManager.LayerChangeListener;
070import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
071import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
072import org.openstreetmap.josm.gui.layer.geoimage.AdjustTimezoneAndOffsetDialog.AdjustListener;
073import org.openstreetmap.josm.gui.layer.geoimage.SynchronizeTimeFromPhotoDialog.TimeZoneItem;
074import org.openstreetmap.josm.gui.layer.gpx.GpxDataHelper;
075import org.openstreetmap.josm.gui.widgets.JosmComboBox;
076import org.openstreetmap.josm.gui.widgets.JosmComboBoxModel;
077import org.openstreetmap.josm.gui.widgets.JosmTextField;
078import org.openstreetmap.josm.spi.preferences.Config;
079import org.openstreetmap.josm.tools.Destroyable;
080import org.openstreetmap.josm.tools.GBC;
081import org.openstreetmap.josm.tools.ImageProvider;
082import org.openstreetmap.josm.tools.Logging;
083import org.openstreetmap.josm.tools.Pair;
084
085/**
086 * This class displays the window to select the GPX file and the offset (timezone + delta).
087 * Then it correlates the images of the layer with that GPX file.
088 * @since 2566
089 */
090public class CorrelateGpxWithImages extends AbstractAction implements ExpertModeChangeListener, Destroyable {
091
092    private static JosmComboBoxModel<GpxDataWrapper> gpxModel;
093    private static boolean forceTags;
094    private static TimeSource imgTimeSource;
095
096    private final transient GeoImageLayer yLayer;
097    private transient CorrelationSupportLayer supportLayer;
098    private transient GpxTimezone timezone;
099    private transient GpxTimeOffset delta;
100
101    /**
102     * Constructs a new {@code CorrelateGpxWithImages} action.
103     * @param layer The image layer
104     */
105    public CorrelateGpxWithImages(GeoImageLayer layer) {
106        super(tr("Correlate to GPX"));
107        new ImageProvider("dialogs/geoimage/gpx2img").getResource().attachImageIcon(this, true);
108        this.yLayer = layer;
109        ExpertToggleAction.addExpertModeChangeListener(this);
110    }
111
112    private final class SyncDialogWindowListener extends WindowAdapter {
113        private static final int CANCEL = -1;
114        private static final int DONE = 0;
115        private static final int AGAIN = 1;
116        private static final int NOTHING = 2;
117
118        private int checkAndSave() {
119            if (syncDialog.isVisible())
120                // nothing happened: JOSM was minimized or similar
121                return NOTHING;
122            int answer = syncDialog.getValue();
123            if (answer != 1)
124                return CANCEL;
125
126            // Parse values again, to display an error if the format is not recognized
127            try {
128                timezone = GpxTimezone.parseTimezone(tfTimezone.getText().trim());
129            } catch (ParseException e) {
130                JOptionPane.showMessageDialog(MainApplication.getMainFrame(), e.getMessage(),
131                        tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE);
132                return AGAIN;
133            }
134
135            try {
136                delta = GpxTimeOffset.parseOffset(tfOffset.getText().trim());
137            } catch (ParseException e) {
138                JOptionPane.showMessageDialog(MainApplication.getMainFrame(), e.getMessage(),
139                        tr("Invalid offset"), JOptionPane.ERROR_MESSAGE);
140                return AGAIN;
141            }
142
143            if (lastNumMatched == 0 && new ExtendedDialog(
144                        MainApplication.getMainFrame(),
145                        tr("Correlate images with GPX track"),
146                        tr("OK"), tr("Try Again")).
147                        setContent(tr("No images could be matched!")).
148                        setButtonIcons("ok", "dialogs/refresh").
149                        showDialog().getValue() == 2)
150                return AGAIN;
151            return DONE;
152        }
153
154        @Override
155        public void windowDeactivated(WindowEvent e) {
156            int result = checkAndSave();
157            switch (result) {
158            case NOTHING:
159                break;
160            case CANCEL:
161                if (yLayer != null) {
162                    yLayer.discardTmp();
163                    yLayer.updateBufferAndRepaint();
164                }
165                if (Config.getPref().getBoolean("geoimage.supportlayer.delete_on_close", false)) {
166                    removeSupportLayer();
167                }
168                break;
169            case AGAIN:
170                actionPerformed(null);
171                break;
172            case DONE:
173                Config.getPref().put("geoimage.timezone", timezone.formatTimezone());
174                Config.getPref().put("geoimage.delta", delta.formatOffset());
175                Config.getPref().putBoolean("geoimage.showThumbs", yLayer.useThumbs);
176                Config.getPref().put("geoimage.datum", tfDatum.getText());
177
178                yLayer.useThumbs = cbShowThumbs.isSelected();
179                yLayer.startLoadThumbs();
180
181                // Search whether an other layer has yet defined some bounding box.
182                // If none, we'll zoom to the bounding box of the layer with the photos.
183                boolean boundingBoxedLayerFound = false;
184                for (Layer l: MainApplication.getLayerManager().getLayers()) {
185                    if (l != yLayer) {
186                        BoundingXYVisitor bbox = new BoundingXYVisitor();
187                        l.visitBoundingBox(bbox);
188                        if (bbox.getBounds() != null) {
189                            boundingBoxedLayerFound = true;
190                            break;
191                        }
192                    }
193                }
194                if (!boundingBoxedLayerFound) {
195                    BoundingXYVisitor bbox = new BoundingXYVisitor();
196                    yLayer.visitBoundingBox(bbox);
197                    MainApplication.getMap().mapView.zoomTo(bbox);
198                }
199
200                yLayer.applyTmp();
201                yLayer.updateBufferAndRepaint();
202                if (Config.getPref().getBoolean("geoimage.supportlayer.delete_on_close", true)) {
203                    removeSupportLayer();
204                }
205
206                break;
207            default:
208                throw new IllegalStateException(Integer.toString(result));
209            }
210        }
211    }
212
213    private void removeSupportLayer() {
214        if (supportLayer != null) {
215            MainApplication.getLayerManager().removeLayer(supportLayer);
216            supportLayer = null;
217        }
218    }
219
220    private static class GpxDataWrapper {
221        private String name;
222        private final GpxData data;
223        private final File file;
224
225        GpxDataWrapper(String name, GpxData data, File file) {
226            this.name = name;
227            this.data = data;
228            this.file = file;
229        }
230
231        void setName(String name) {
232            this.name = name;
233            forEachLayer(CorrelateGpxWithImages::repaintCombobox);
234        }
235
236        @Override
237        public String toString() {
238            return name;
239        }
240    }
241
242    private static class NoGpxDataWrapper extends GpxDataWrapper {
243        NoGpxDataWrapper() {
244            super(null, null, null);
245        }
246
247        @Override
248        public String toString() {
249            return tr("<No GPX track loaded yet>");
250        }
251    }
252
253    private ExtendedDialog syncDialog;
254    private JPanel outerPanel;
255    private JPanel expertPanel;
256    private JosmComboBox<GpxDataWrapper> cbGpx;
257    private JButton buttonSupport;
258    private JosmTextField tfTimezone;
259    private JosmTextField tfOffset;
260    private JRadioButton rbTimeFromCamera;
261    private JRadioButton rbTimeFromGps;
262    private JCheckBox cbExifImg;
263    private JCheckBox cbTaggedImg;
264    private JCheckBox cbShowThumbs;
265    private JSeparator sepExtendedTags;
266    private JLabel labelExtTags;
267    private JLabel labelDatum;
268    private JLabel statusBarText;
269    private JSeparator sepDirectionPosition;
270    private ImageDirectionPositionPanel pDirectionPosition;
271    private JCheckBox cbAddGpsDatum;
272    private JosmTextField tfDatum;
273
274    // remember the last number of matched photos
275    private int lastNumMatched;
276
277    /**
278     * This class is called when the user doesn't find the GPX file he needs in the files that have
279     * been loaded yet. It displays a FileChooser dialog to select the GPX file to be loaded.
280     */
281    private final class LoadGpxDataActionListener implements ActionListener {
282
283        @Override
284        public void actionPerformed(ActionEvent e) {
285            File sel = GpxDataHelper.chooseGpxDataFile();
286            if (sel != null) {
287                try {
288                    outerPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
289                    removeDuplicates(sel);
290                    GpxData data = GpxDataHelper.loadGpxData(sel);
291                    if (data != null) {
292                        GpxDataWrapper elem = new GpxDataWrapper(sel.getName(), data, sel);
293                        gpxModel.addElement(elem);
294                        gpxModel.setSelectedItem(elem);
295                        statusBarUpdater.matchAndUpdateStatusBar();
296                    }
297                } finally {
298                    outerPanel.setCursor(Cursor.getDefaultCursor());
299                }
300            }
301        }
302    }
303
304    private final class UseSupportLayerActionListener implements ActionListener {
305
306        @Override
307        public void actionPerformed(ActionEvent e) {
308            Optional.ofNullable(selectedGPX(true)).ifPresent(gpx -> {
309                supportLayer = new CorrelationSupportLayer(gpx.data);
310                supportLayer.getGpxData().addChangeListener(statusBarUpdaterWithRepaint);
311                MainApplication.getLayerManager().addLayer(supportLayer);
312            });
313        }
314    }
315
316    private final class AdvancedSettingsActionListener implements ActionListener {
317
318        @Override
319        public void actionPerformed(ActionEvent e) {
320            AdvancedCorrelationSettingsDialog ed = new AdvancedCorrelationSettingsDialog(MainApplication.getMainFrame(), forceTags);
321            if (ed.showDialog().getValue() == 1) {
322                forceTags = ed.isForceTaggingSelected(); // This setting is not supposed to be saved permanently
323
324                statusBarUpdater.matchAndUpdateStatusBar();
325                yLayer.updateBufferAndRepaint();
326            }
327        }
328    }
329
330    /**
331     * This action listener is called when the user has a photo of the time of his GPS receiver. It
332     * displays the list of photos of the layer, and upon selection displays the selected photo.
333     * From that photo, the user can key in the time of the GPS.
334     * Then values of timezone and delta are set.
335     * @author chris
336     */
337    private final class SetOffsetActionListener implements ActionListener {
338
339        @Override
340        public void actionPerformed(ActionEvent e) {
341            boolean isOk = false;
342            while (!isOk) {
343                SynchronizeTimeFromPhotoDialog ed = new SynchronizeTimeFromPhotoDialog(
344                        MainApplication.getMainFrame(), yLayer.getImageData().getImages());
345                int answer = ed.showDialog().getValue();
346                if (answer != 1)
347                    return;
348
349                long delta;
350
351                try {
352                    delta = ed.getDelta();
353                } catch (ParseException ex) {
354                    JOptionPane.showMessageDialog(MainApplication.getMainFrame(), tr("Error while parsing the date.\n"
355                            + "Please use the requested format"),
356                            tr("Invalid date"), JOptionPane.ERROR_MESSAGE);
357                    continue;
358                }
359
360                TimeZoneItem selectedTz = ed.getTimeZoneItem();
361
362                Config.getPref().put("geoimage.timezoneid", selectedTz.getID());
363                Config.getPref().putBoolean("geoimage.timezoneid.dst", ed.isDstSelected());
364                tfOffset.setText(GpxTimeOffset.milliseconds(delta).formatOffset());
365                tfTimezone.setText(selectedTz.getFormattedString());
366
367                isOk = true;
368            }
369            statusBarUpdater.matchAndUpdateStatusBar();
370            yLayer.updateBufferAndRepaint();
371        }
372    }
373
374    private static final class GpxLayerAddedListener implements LayerChangeListener {
375        @Override
376        public void layerAdded(LayerAddEvent e) {
377            Layer layer = e.getAddedLayer();
378            if (layer instanceof GpxDataContainer) {
379                GpxData gpx = ((GpxDataContainer) layer).getGpxData();
380                File file = gpx.storageFile;
381                removeDuplicates(file);
382                GpxDataWrapper gdw = new GpxDataWrapper(layer.getName(), gpx, file);
383                layer.addPropertyChangeListener(new GpxLayerRenamedListener(gdw));
384                gpxModel.addElement(gdw);
385                forEachLayer(correlateAction -> {
386                    correlateAction.repaintCombobox();
387                    if (layer.equals(correlateAction.supportLayer)) {
388                        correlateAction.buttonSupport.setEnabled(false);
389                    }
390                });
391            }
392        }
393
394        @Override
395        public void layerRemoving(LayerRemoveEvent e) {
396            Layer layer = e.getRemovedLayer();
397            if (layer instanceof GpxDataContainer) {
398                GpxData removedGpxData = ((GpxDataContainer) layer).getGpxData();
399                for (int i = gpxModel.getSize() - 1; i >= 0; i--) {
400                    GpxData data = gpxModel.getElementAt(i).data;
401                    // removedGpxData can be null if gpx layer has been destroyed before this listener
402                    if (data.equals(removedGpxData) || (removedGpxData == null && data.isEmpty())) {
403                        gpxModel.removeElementAt(i);
404                        forEachLayer(correlateAction -> {
405                            correlateAction.repaintCombobox();
406                            if (layer.equals(correlateAction.supportLayer)) {
407                                correlateAction.supportLayer.getGpxData()
408                                    .removeChangeListener(correlateAction.statusBarUpdaterWithRepaint);
409                                correlateAction.supportLayer = null;
410                                correlateAction.buttonSupport.setEnabled(true);
411                            }
412                        });
413                        break;
414                    }
415                }
416            }
417        }
418
419        @Override
420        public void layerOrderChanged(LayerOrderChangeEvent e) {
421            // Not used
422        }
423    }
424
425    private static class GpxLayerRenamedListener implements PropertyChangeListener {
426        private final GpxDataWrapper gdw;
427        GpxLayerRenamedListener(GpxDataWrapper gdw) {
428            this.gdw = gdw;
429        }
430
431        @Override
432        public void propertyChange(PropertyChangeEvent e) {
433            if (Layer.NAME_PROP.equals(e.getPropertyName())) {
434                gdw.setName(e.getNewValue().toString());
435            }
436        }
437    }
438
439    /**
440     * Construct the list of loaded GPX tracks
441     * @param nogdw Data wrapper with no GPX data
442     */
443    private void constructGpxModel(NoGpxDataWrapper nogdw) {
444        gpxModel = new JosmComboBoxModel<>();
445        GpxDataWrapper defaultItem = null;
446        for (AbstractModifiableLayer cur : MainApplication.getLayerManager().getLayersOfType(AbstractModifiableLayer.class)) {
447            if (cur instanceof GpxDataContainer) {
448                GpxData data = ((GpxDataContainer) cur).getGpxData();
449                GpxDataWrapper gdw = new GpxDataWrapper(cur.getName(), data, data.storageFile);
450                cur.addPropertyChangeListener(new GpxLayerRenamedListener(gdw));
451                gpxModel.addElement(gdw);
452                if (data.equals(yLayer.gpxData) || defaultItem == null) {
453                    defaultItem = gdw;
454                }
455            }
456        }
457
458        if (gpxModel.getSize() == 0) {
459            gpxModel.addElement(nogdw);
460        } else if (defaultItem != null) {
461            gpxModel.setSelectedItem(defaultItem);
462        }
463        MainApplication.getLayerManager().addLayerChangeListener(new GpxLayerAddedListener());
464    }
465
466    static GpxTimezone loadTimezone() {
467        try {
468            String tz = Config.getPref().get("geoimage.timezone");
469            if (!tz.isEmpty()) {
470                return GpxTimezone.parseTimezone(tz);
471            } else {
472                return new GpxTimezone(TimeUnit.MILLISECONDS.toMinutes(TimeZone.getDefault().getRawOffset()) / 60.); //hours is double
473            }
474        } catch (ParseException e) {
475            Logging.trace(e);
476            return GpxTimezone.ZERO;
477        }
478    }
479
480    static GpxTimeOffset loadDelta() {
481        try {
482            return GpxTimeOffset.parseOffset(Config.getPref().get("geoimage.delta", "0"));
483        } catch (ParseException e) {
484            Logging.trace(e);
485            return GpxTimeOffset.ZERO;
486        }
487    }
488
489    static String loadGpsDatum() {
490        return Config.getPref().get("geoimage.datum", "WGS-84");
491    }
492
493    // CHECKSTYLE.OFF: ExecutableStatementCount
494    @Override
495    public void actionPerformed(ActionEvent ae) {
496        NoGpxDataWrapper nogdw = new NoGpxDataWrapper();
497        if (gpxModel == null) {
498            constructGpxModel(nogdw);
499        }
500
501        JPanel panelCb = new JPanel();
502
503        panelCb.add(new JLabel(tr("GPX track: ")));
504
505        cbGpx = new JosmComboBox<>(gpxModel);
506        cbGpx.setPrototypeDisplayValue(nogdw);
507        cbGpx.addActionListener(statusBarUpdaterWithRepaint);
508        panelCb.add(cbGpx);
509
510        JButton buttonOpen = new JButton(tr("Open another GPX trace"));
511        buttonOpen.addActionListener(new LoadGpxDataActionListener());
512        panelCb.add(buttonOpen);
513
514        buttonSupport = new JButton(tr("Use support layer"));
515        buttonSupport.addActionListener(new UseSupportLayerActionListener());
516        panelCb.add(buttonSupport);
517
518        JPanel panelTf = new JPanel(new GridBagLayout());
519
520        timezone = loadTimezone();
521
522        tfTimezone = new JosmTextField(10);
523        tfTimezone.setText(timezone.formatTimezone());
524
525        delta = loadDelta();
526
527        tfOffset = new JosmTextField(10);
528        tfOffset.setText(delta.formatOffset());
529
530        // Image Time/Clock source choice 
531        rbTimeFromCamera = new JRadioButton(tr("Camera clock"));
532        rbTimeFromCamera.setSelected(true);
533        rbTimeFromGps = new JRadioButton(tr("Camera GPS clock"));        
534        ButtonGroup timeSourceGroup = new ButtonGroup();
535        timeSourceGroup.add(rbTimeFromCamera);
536        timeSourceGroup.add(rbTimeFromGps);
537
538        JButton buttonViewGpsPhoto = new JButton(tr("<html>Use photo of an accurate clock,<br>e.g. GPS receiver display</html>"));
539        buttonViewGpsPhoto.setIcon(ImageProvider.get("clock"));
540        buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener());
541
542        JButton buttonAutoGuess = new JButton(tr("Auto-Guess"));
543        buttonAutoGuess.setToolTipText(tr("Matches first photo with first gpx point"));
544        buttonAutoGuess.addActionListener(new AutoGuessActionListener());
545
546        JButton buttonAdjust = new JButton(tr("Manual adjust"));
547        buttonAdjust.addActionListener(new AdjustActionListener());
548
549        JButton buttonAdvanced = new JButton(tr("Advanced settings..."));
550        buttonAdvanced.addActionListener(new AdvancedSettingsActionListener());
551
552        JLabel labelPosition = new JLabel(tr("Override position for: "));
553
554        int numAll = yLayer.getSortedImgList(true, true, imgTimeSource).size();
555        int numExif = numAll - yLayer.getSortedImgList(false, true, imgTimeSource).size();
556        int numTagged = numAll - yLayer.getSortedImgList(true, false, imgTimeSource).size();
557
558        cbExifImg = new JCheckBox(tr("Images with geo location in exif data ({0}/{1})", numExif, numAll));
559        cbExifImg.setEnabled(numExif != 0);
560
561        cbTaggedImg = new JCheckBox(tr("Images that are already tagged ({0}/{1})", numTagged, numAll), true);
562        cbTaggedImg.setEnabled(numTagged != 0);
563
564        labelPosition.setEnabled(cbExifImg.isEnabled() || cbTaggedImg.isEnabled());
565
566        boolean ticked = yLayer.thumbsLoaded || Config.getPref().getBoolean("geoimage.showThumbs", false);
567        cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), ticked);
568        cbShowThumbs.setEnabled(!yLayer.thumbsLoaded);
569
570        int y = 0;
571        panelTf.add(panelCb, GBC.eol().grid(0, y++));
572
573        GBC gbc = GBC.eol().grid(0, y++).fill(GridBagConstraints.HORIZONTAL).insets(0, 0, 0, 12);
574        panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);
575
576        panelTf.add(new JLabel(tr("Timezone: ")), GBC.std(0, y));
577
578        gbc = GBC.std(1, y++).fill(GridBagConstraints.HORIZONTAL);
579        gbc.weightx = 1.;
580        panelTf.add(tfTimezone, gbc);
581
582        gbc = GBC.std(0, y);
583        panelTf.add(new JLabel(tr("Offset:")), gbc);
584
585        gbc = GBC.std(1, y++).fill(GridBagConstraints.HORIZONTAL);
586        gbc.weightx = 1.;
587        panelTf.add(tfOffset, gbc);
588
589        gbc = GBC.std(2, y-2).insets(5, 5, 5, 5).span(2, 2);
590        gbc.fill = GridBagConstraints.BOTH;
591        gbc.weightx = 0.5;
592        panelTf.add(buttonViewGpsPhoto, gbc);
593
594        gbc = GBC.std(1, y++).fill(GridBagConstraints.BOTH).insets(5, 5, 5, 5);
595        gbc.weightx = 0.5;
596        panelTf.add(buttonAdvanced, gbc);
597
598        gbc.gridx = 2;
599        panelTf.add(buttonAutoGuess, gbc);
600
601        gbc.gridx = 3;
602        panelTf.add(buttonAdjust, gbc);
603
604        // Image time source choice
605        gbc = GBC.eol();
606        gbc.gridx = 0;
607        gbc.gridy = y++;
608        panelTf.add(new JLabel(tr("Image time source:")), gbc);
609
610        gbc = GBC.eol();
611        gbc.gridx = 1;
612        gbc.gridy = y++;
613        panelTf.add(rbTimeFromCamera, gbc);
614
615        gbc = GBC.eol();
616        gbc.gridx = 1;
617        gbc.gridy = y++;
618        panelTf.add(rbTimeFromGps, gbc);
619
620        gbc = GBC.eol().grid(0, y++).fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0);
621        panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc);
622        panelTf.add(labelPosition, GBC.eol().grid(0, y++));
623        panelTf.add(cbExifImg, GBC.eol().grid(1, y++));
624        panelTf.add(cbTaggedImg, GBC.eol().grid(1, y++));
625        panelTf.add(cbShowThumbs, GBC.eol().grid(0, y++));
626
627        //Image direction and position offset GUI
628        gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0);
629        sepDirectionPosition = new JSeparator(SwingConstants.HORIZONTAL);
630        gbc.gridy = y++;
631        panelTf.add(sepDirectionPosition, gbc);
632
633        gbc = GBC.eol();
634        gbc.gridwidth = 3;
635        gbc.gridy = y++;
636        pDirectionPosition = ImageDirectionPositionPanel.forGpxTrace();
637        panelTf.add(pDirectionPosition, gbc);
638
639        //Extended tags GUI panel
640        expertPanel = new JPanel(new GridBagLayout());
641        gbc = GBC.eol().grid(0, 0).fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0);
642        sepExtendedTags = new JSeparator(SwingConstants.HORIZONTAL);
643        expertPanel.add(sepExtendedTags, gbc);
644
645        labelExtTags = new JLabel(tr("Extended tags"));
646        cbAddGpsDatum = new JCheckBox(tr("Set datum for images coordinates"));
647        cbAddGpsDatum.addActionListener(e -> tfDatum.setEnabled(!tfDatum.isEnabled()));
648
649        labelDatum = new JLabel(tr("Datum: "));
650        //TODO An AutoCompComboBox would be nice to list the recent datum values. I don't have the skill to add it.
651        tfDatum = new JosmTextField(loadGpsDatum(), 8);
652        tfDatum.setToolTipText(tr("<html>Enter the datum for your images coordinates. Default value is WGS-84.<br>" + 
653                                "For RTK it could be your local CRS epsg code.<br>(e.g. EPSG:9782 for France mainland.)</html>"));
654        tfDatum.setEnabled(false);
655
656        expertPanel.add(labelExtTags, GBC.eol().grid(0, 1));
657        expertPanel.add(cbAddGpsDatum, GBC.eol().grid(0, 2));
658        expertPanel.add(labelDatum, GBC.std(1, 3));
659        expertPanel.add(tfDatum, GBC.eol().grid(2, 3));
660
661        //Add expertPanel to panelTf
662        gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0);
663        gbc.gridy = y++;
664        panelTf.add(expertPanel, gbc);
665        
666        final JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
667        statusPanel.setBorder(BorderFactory.createLoweredBevelBorder());
668        statusBarText = new JLabel(" ");
669        statusBarText.setFont(statusBarText.getFont().deriveFont(Font.PLAIN, 12));
670        statusPanel.add(statusBarText);
671
672        gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(20, 12, 20, 0);
673        gbc.gridy = y;
674        panelTf.add(statusPanel, gbc);
675
676        expertChanged(ExpertToggleAction.isExpert());
677
678        RepaintTheMapListener repaintTheMap = new RepaintTheMapListener(yLayer);
679        pDirectionPosition.addFocusListenerOnComponent(repaintTheMap);
680        tfTimezone.addFocusListener(repaintTheMap);
681        tfOffset.addFocusListener(repaintTheMap);
682
683        tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
684        tfOffset.getDocument().addDocumentListener(statusBarUpdater);
685        rbTimeFromCamera.addItemListener(statusBarUpdaterWithRepaint);
686        rbTimeFromGps.addItemListener(statusBarUpdaterWithRepaint);
687        cbExifImg.addItemListener(statusBarUpdaterWithRepaint);
688        cbTaggedImg.addItemListener(statusBarUpdaterWithRepaint);
689        cbAddGpsDatum.addItemListener(statusBarUpdaterWithRepaint);
690        tfDatum.getDocument().addDocumentListener(statusBarUpdater);
691        pDirectionPosition.addChangeListenerOnComponents(statusBarUpdaterWithRepaint);
692        pDirectionPosition.addItemListenerOnComponents(statusBarUpdaterWithRepaint);
693
694        outerPanel = new JPanel(new BorderLayout());
695
696        if (!GraphicsEnvironment.isHeadless()) {
697            forEachLayer(CorrelateGpxWithImages::closeDialog);
698            syncDialog = new ExtendedDialog(
699                    MainApplication.getMainFrame(),
700                    tr("Correlate images with GPX track"),
701                    new String[] {tr("Correlate"), tr("Cancel")},
702                    false
703            );
704            syncDialog.setContent(panelTf, false);
705            syncDialog.setButtonIcons("ok", "cancel");
706            syncDialog.setupDialog();
707            outerPanel.add(syncDialog.getContentPane(), BorderLayout.PAGE_START);
708            syncDialog.setContentPane(outerPanel);
709            syncDialog.pack();
710            syncDialog.addWindowListener(new SyncDialogWindowListener());
711            syncDialog.showDialog();
712
713            statusBarUpdater.matchAndUpdateStatusBar();
714            yLayer.updateBufferAndRepaint();
715        }
716    }
717    // CHECKSTYLE.ON: ExecutableStatementCount
718
719    public GpxImageDatumSettings getSettings() {
720        return new GpxImageDatumSettings(
721            cbAddGpsDatum.isSelected(),
722            tfDatum.getText());
723    }
724
725    @Override
726    public void expertChanged(boolean isExpert) {
727        if (buttonSupport != null) {
728            buttonSupport.setVisible(isExpert);
729        }
730        if (sepDirectionPosition != null) {
731            sepDirectionPosition.setVisible(isExpert);
732        }
733        if (pDirectionPosition != null) {
734            pDirectionPosition.setVisible(isExpert);
735        }
736        if (expertPanel != null) {
737            expertPanel.setVisible(isExpert);
738        }
739        if (syncDialog != null) {
740            syncDialog.pack();
741        }
742    }
743
744    private static void removeDuplicates(File file) {
745        for (int i = gpxModel.getSize() - 1; i >= 0; i--) {
746            GpxDataWrapper wrapper = gpxModel.getElementAt(i);
747            if (wrapper instanceof NoGpxDataWrapper || (file != null && file.equals(wrapper.file))) {
748                gpxModel.removeElement(wrapper);
749            }
750        }
751    }
752
753    private static void forEachLayer(Consumer<CorrelateGpxWithImages> action) {
754        MainApplication.getLayerManager().getLayersOfType(GeoImageLayer.class)
755                .forEach(geo -> action.accept(geo.getGpxCorrelateAction()));
756    }
757
758    private final transient StatusBarUpdater statusBarUpdater = new StatusBarUpdater(false);
759    private final transient StatusBarUpdater statusBarUpdaterWithRepaint = new StatusBarUpdater(true);
760
761    private class StatusBarUpdater implements DocumentListener, ItemListener, ChangeListener, ActionListener, GpxDataChangeListener {
762        private final boolean doRepaint;
763
764        StatusBarUpdater(boolean doRepaint) {
765            this.doRepaint = doRepaint;
766        }
767
768        @Override
769        public void insertUpdate(DocumentEvent e) {
770            matchAndUpdateStatusBar();
771        }
772
773        @Override
774        public void removeUpdate(DocumentEvent e) {
775            matchAndUpdateStatusBar();
776        }
777
778        @Override
779        public void changedUpdate(DocumentEvent e) {
780            // Do nothing
781        }
782
783        @Override
784        public void itemStateChanged(ItemEvent e) {
785            matchAndUpdateStatusBar();
786        }
787
788        @Override
789        public void stateChanged(ChangeEvent e) {
790            matchAndUpdateStatusBar();
791        }
792
793        @Override
794        public void actionPerformed(ActionEvent e) {
795            matchAndUpdateStatusBar();
796        }
797
798        @Override
799        public void gpxDataChanged(GpxDataChangeEvent e) {
800            matchAndUpdateStatusBar();
801        }
802
803        public void matchAndUpdateStatusBar() {
804            if (syncDialog != null && syncDialog.isVisible()) {
805                statusBarText.setText(matchAndGetStatusText());
806                if (doRepaint) {
807                    yLayer.updateBufferAndRepaint();
808                }
809            }
810        }
811
812        private String matchAndGetStatusText() {
813            try {
814                timezone = GpxTimezone.parseTimezone(tfTimezone.getText().trim());
815                delta = GpxTimeOffset.parseOffset(tfOffset.getText().trim());
816            } catch (ParseException e) {
817                return e.getMessage();
818            }
819
820            // Set image time source from the radio button status
821            if (rbTimeFromGps.isSelected()) {
822                imgTimeSource = TimeSource.EXIFGPSTIME;
823            } else {
824                imgTimeSource = TimeSource.EXIFCAMTIME;
825            }
826
827            // The selection of images we are about to correlate may have changed.
828            // So reset all images.
829            yLayer.discardTmp();
830
831            //Get how many images are present in the layer
832            int totalImg = yLayer.getImages().size();
833            
834            // Construct a list of images that have a date, and sort them on the date.
835            List<ImageEntry> dateImgLst = getSortedImgList();
836            // Create a temporary copy for each image
837            dateImgLst.forEach(ie -> ie.createTmp().unflagNewGpsData());
838
839            GpxDataWrapper selGpx = selectedGPX(false);
840            if (selGpx == null)
841                return tr("No gpx selected");
842
843            final long offsetMs = ((long) (timezone.getHours() * TimeUnit.HOURS.toMillis(1))) + delta.getMilliseconds(); // in milliseconds
844            lastNumMatched = GpxImageCorrelation.matchGpxTrack(dateImgLst, selGpx.data,
845                    pDirectionPosition.isVisible() ?
846                            new GpxImageCorrelationSettings(offsetMs, forceTags, imgTimeSource, pDirectionPosition.getSettings(),
847                                                            new GpxImageDatumSettings(cbAddGpsDatum.isSelected(), tfDatum.getText())) :
848                            new GpxImageCorrelationSettings(offsetMs, forceTags));
849
850            return trn("<html>Matched <b>{0}</b> of <b>{1}</b> photo to GPX track.</html>",
851                    "<html>Matched <b>{0}</b> of <b>{1}</b> photos to GPX track.</html>",
852                    totalImg, lastNumMatched, totalImg);
853        }
854    }
855
856    static class RepaintTheMapListener implements FocusListener {
857
858        private final GeoImageLayer yLayer;
859
860        RepaintTheMapListener(GeoImageLayer yLayer) {
861            this.yLayer = Objects.requireNonNull(yLayer);
862        }
863
864        @Override
865        public void focusGained(FocusEvent e) { // do nothing
866        }
867
868        @Override
869        public void focusLost(FocusEvent e) {
870            yLayer.updateBufferAndRepaint();
871        }
872    }
873
874    /**
875     * Presents dialog with sliders for manual adjust.
876     */
877    private final class AdjustActionListener implements ActionListener {
878
879        @Override
880        public void actionPerformed(ActionEvent e) {
881
882            final GpxTimeOffset offset = GpxTimeOffset.milliseconds(
883                    delta.getMilliseconds() + Math.round(timezone.getHours() * TimeUnit.HOURS.toMillis(1)));
884            final int dayOffset = offset.getDayOffset();
885            final Pair<GpxTimezone, GpxTimeOffset> timezoneOffsetPair = offset.withoutDayOffset().splitOutTimezone();
886
887            // This is called whenever one of the sliders is moved.
888            // It calls the "match photos" code
889            AdjustListener listener = (tz, min, sec) -> {
890                timezone = tz;
891
892                delta = GpxTimeOffset.milliseconds(100L * sec
893                        + TimeUnit.MINUTES.toMillis(min)
894                        + TimeUnit.DAYS.toMillis(dayOffset));
895
896                tfTimezone.getDocument().removeDocumentListener(statusBarUpdater);
897                tfOffset.getDocument().removeDocumentListener(statusBarUpdater);
898
899                tfTimezone.setText(timezone.formatTimezone());
900                tfOffset.setText(delta.formatOffset());
901
902                tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
903                tfOffset.getDocument().addDocumentListener(statusBarUpdater);
904
905                statusBarUpdater.matchAndUpdateStatusBar();
906                yLayer.updateBufferAndRepaint();
907
908                return statusBarText.getText();
909            };
910
911            // There is no way to cancel this dialog, all changes get applied
912            // immediately. Therefore "Close" is marked with an "OK" icon.
913            // Settings are only saved temporarily to the layer.
914            new AdjustTimezoneAndOffsetDialog(MainApplication.getMainFrame(),
915                    timezoneOffsetPair.a, timezoneOffsetPair.b, dayOffset)
916            .adjustListener(listener).showDialog();
917        }
918    }
919
920    static class NoGpxTimestamps extends Exception {
921    }
922
923    void closeDialog() {
924        if (syncDialog != null) {
925            syncDialog.setVisible(false);
926            new SyncDialogWindowListener().windowDeactivated(null);
927            syncDialog.dispose();
928            syncDialog = null;
929        }
930    }
931
932    void repaintCombobox() {
933        if (cbGpx != null) {
934            cbGpx.repaint();
935        }
936    }
937
938    /**
939     * Tries to auto-guess the timezone and offset.
940     *
941     * @param imgs the images to correlate
942     * @param gpx the gpx track to correlate to
943     * @return a pair of timezone and offset
944     * @throws IndexOutOfBoundsException when there are no images
945     * @throws NoGpxTimestamps when the gpx track does not contain a timestamp
946     */
947    static Pair<GpxTimezone, GpxTimeOffset> autoGuess(List<ImageEntry> imgs, GpxData gpx) throws NoGpxTimestamps {
948
949        // Init variables
950        long firstExifDate = imgs.get(0).getExifInstant().toEpochMilli();
951
952        // Finds first GPX point
953        long firstGPXDate = gpx.tracks.stream()
954                .flatMap(trk -> trk.getSegments().stream())
955                .flatMap(segment -> segment.getWayPoints().stream())
956                .filter(WayPoint::hasDate)
957                .map(WayPoint::getTimeInMillis)
958                .findFirst()
959                .orElseThrow(NoGpxTimestamps::new);
960
961        return GpxTimeOffset.milliseconds(firstExifDate - firstGPXDate).splitOutTimezone();
962    }
963
964    private final class AutoGuessActionListener implements ActionListener {
965
966        @Override
967        public void actionPerformed(ActionEvent e) {
968            GpxDataWrapper gpxW = selectedGPX(true);
969            if (gpxW == null)
970                return;
971            GpxData gpx = gpxW.data;
972
973            List<ImageEntry> imgs = getSortedImgList();
974
975            try {
976                final Pair<GpxTimezone, GpxTimeOffset> r = autoGuess(imgs, gpx);
977                timezone = r.a;
978                delta = r.b;
979            } catch (IndexOutOfBoundsException ex) {
980                Logging.debug(ex);
981                JOptionPane.showMessageDialog(MainApplication.getMainFrame(),
982                        tr("The selected photos do not contain time information."),
983                        tr("Photos do not contain time information"), JOptionPane.WARNING_MESSAGE);
984                return;
985            } catch (NoGpxTimestamps ex) {
986                Logging.debug(ex);
987                JOptionPane.showMessageDialog(MainApplication.getMainFrame(),
988                        tr("The selected GPX track does not contain timestamps. Please select another one."),
989                        tr("GPX Track has no time information"), JOptionPane.WARNING_MESSAGE);
990                return;
991            }
992
993            tfTimezone.getDocument().removeDocumentListener(statusBarUpdater);
994            tfOffset.getDocument().removeDocumentListener(statusBarUpdater);
995
996            tfTimezone.setText(timezone.formatTimezone());
997            tfOffset.setText(delta.formatOffset());
998            tfOffset.requestFocus();
999
1000            tfTimezone.getDocument().addDocumentListener(statusBarUpdater);
1001            tfOffset.getDocument().addDocumentListener(statusBarUpdater);
1002
1003            statusBarUpdater.matchAndUpdateStatusBar();
1004            yLayer.updateBufferAndRepaint();
1005        }
1006    }
1007
1008    private List<ImageEntry> getSortedImgList() {
1009        return yLayer.getSortedImgList(cbExifImg.isSelected(), cbTaggedImg.isSelected(), imgTimeSource);
1010    }
1011
1012    private static GpxDataWrapper selectedGPX(boolean complain) {
1013        Object item = gpxModel.getSelectedItem();
1014
1015        if (item == null || ((GpxDataWrapper) item).data == null) {
1016            if (complain) {
1017                JOptionPane.showMessageDialog(MainApplication.getMainFrame(), tr("You should select a GPX track"),
1018                        tr("No selected GPX track"), JOptionPane.ERROR_MESSAGE);
1019            }
1020            return null;
1021        }
1022        return (GpxDataWrapper) item;
1023    }
1024
1025    @Override
1026    public void destroy() {
1027        ExpertToggleAction.removeExpertModeChangeListener(this);
1028        if (cbGpx != null) {
1029            // Force the JCombobox to remove its eventListener from the static GpxDataWrapper
1030            cbGpx.setModel(new DefaultComboBoxModel<>());
1031            cbGpx = null;
1032        }
1033
1034        closeDialog();
1035
1036        outerPanel = null;
1037        tfTimezone = null;
1038        tfOffset = null;
1039        cbExifImg = null;
1040        cbTaggedImg = null;
1041        cbShowThumbs = null;
1042        statusBarText = null;
1043        sepDirectionPosition = null;
1044        pDirectionPosition = null;
1045    }
1046}