001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.preferences;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.marktr;
006import static org.openstreetmap.josm.tools.I18n.tr;
007
008import java.awt.Color;
009import java.awt.Component;
010import java.awt.Dimension;
011import java.awt.GridBagConstraints;
012import java.awt.GridBagLayout;
013import java.awt.Insets;
014import java.awt.Rectangle;
015import java.awt.event.ActionEvent;
016import java.awt.event.FocusAdapter;
017import java.awt.event.FocusEvent;
018import java.awt.event.KeyEvent;
019import java.awt.event.MouseAdapter;
020import java.awt.event.MouseEvent;
021import java.io.BufferedReader;
022import java.io.File;
023import java.io.IOException;
024import java.net.MalformedURLException;
025import java.net.URL;
026import java.util.ArrayList;
027import java.util.Arrays;
028import java.util.Collection;
029import java.util.Collections;
030import java.util.EventObject;
031import java.util.HashMap;
032import java.util.Iterator;
033import java.util.List;
034import java.util.Map;
035import java.util.Objects;
036import java.util.concurrent.CopyOnWriteArrayList;
037import java.util.regex.Matcher;
038import java.util.regex.Pattern;
039import java.util.stream.Collectors;
040import java.util.stream.IntStream;
041import java.util.stream.Stream;
042
043import javax.swing.AbstractAction;
044import javax.swing.BorderFactory;
045import javax.swing.Box;
046import javax.swing.DefaultListSelectionModel;
047import javax.swing.JButton;
048import javax.swing.JCheckBox;
049import javax.swing.JComponent;
050import javax.swing.JFileChooser;
051import javax.swing.JLabel;
052import javax.swing.JOptionPane;
053import javax.swing.JPanel;
054import javax.swing.JScrollPane;
055import javax.swing.JSeparator;
056import javax.swing.JTabbedPane;
057import javax.swing.JTable;
058import javax.swing.JToolBar;
059import javax.swing.KeyStroke;
060import javax.swing.ListSelectionModel;
061import javax.swing.SwingConstants;
062import javax.swing.UIManager;
063import javax.swing.event.CellEditorListener;
064import javax.swing.event.ChangeEvent;
065import javax.swing.event.ListSelectionEvent;
066import javax.swing.event.ListSelectionListener;
067import javax.swing.event.TableModelEvent;
068import javax.swing.event.TableModelListener;
069import javax.swing.filechooser.FileFilter;
070import javax.swing.table.AbstractTableModel;
071import javax.swing.table.DefaultTableCellRenderer;
072import javax.swing.table.TableCellEditor;
073import javax.swing.table.TableModel;
074
075import org.openstreetmap.josm.actions.ExtensionFileFilter;
076import org.openstreetmap.josm.data.Version;
077import org.openstreetmap.josm.data.preferences.NamedColorProperty;
078import org.openstreetmap.josm.data.preferences.sources.ExtendedSourceEntry;
079import org.openstreetmap.josm.data.preferences.sources.SourceEntry;
080import org.openstreetmap.josm.data.preferences.sources.SourcePrefHelper;
081import org.openstreetmap.josm.data.preferences.sources.SourceProvider;
082import org.openstreetmap.josm.data.preferences.sources.SourceType;
083import org.openstreetmap.josm.gui.ExtendedDialog;
084import org.openstreetmap.josm.gui.HelpAwareOptionPane;
085import org.openstreetmap.josm.gui.MainApplication;
086import org.openstreetmap.josm.gui.PleaseWaitRunnable;
087import org.openstreetmap.josm.gui.util.DocumentAdapter;
088import org.openstreetmap.josm.gui.util.FileFilterAllFiles;
089import org.openstreetmap.josm.gui.util.GuiHelper;
090import org.openstreetmap.josm.gui.util.ReorderableTableModel;
091import org.openstreetmap.josm.gui.util.TableHelper;
092import org.openstreetmap.josm.gui.widgets.AbstractFileChooser;
093import org.openstreetmap.josm.gui.widgets.FileChooserManager;
094import org.openstreetmap.josm.gui.widgets.FilterField;
095import org.openstreetmap.josm.gui.widgets.JosmTextField;
096import org.openstreetmap.josm.io.CachedFile;
097import org.openstreetmap.josm.io.NetworkManager;
098import org.openstreetmap.josm.io.OnlineResource;
099import org.openstreetmap.josm.io.OsmTransferException;
100import org.openstreetmap.josm.spi.preferences.Config;
101import org.openstreetmap.josm.tools.GBC;
102import org.openstreetmap.josm.tools.ImageOverlay;
103import org.openstreetmap.josm.tools.ImageProvider;
104import org.openstreetmap.josm.tools.ImageProvider.ImageSizes;
105import org.openstreetmap.josm.tools.LanguageInfo;
106import org.openstreetmap.josm.tools.Logging;
107import org.openstreetmap.josm.tools.Utils;
108import org.xml.sax.SAXException;
109
110/**
111 * Editor for JOSM extensions source entries.
112 * @since 1743
113 */
114public abstract class SourceEditor extends JPanel {
115    private static final String DELETE = "delete";
116    private static final String DIALOGS = "dialogs";
117
118    /** the type of source entry **/
119    protected final SourceType sourceType;
120    /** determines if the entry type can be enabled (set as active) **/
121    protected final boolean canEnable;
122
123    /** the table of active sources **/
124    protected final JTable tblActiveSources;
125    /** the underlying model of active sources **/
126    protected final ActiveSourcesModel activeSourcesModel;
127    /** the list of available sources **/
128    protected final JTable tblAvailableSources;
129    /** the underlying model of available sources **/
130    protected final AvailableSourcesModel availableSourcesModel;
131    /** the URL from which the available sources are fetched **/
132    protected final String availableSourcesUrl;
133    /** the list of source providers **/
134    protected final transient List<SourceProvider> sourceProviders;
135
136    private JTable tblIconPaths;
137    private IconPathTableModel iconPathsModel;
138
139    /** determines if the source providers have been initially loaded **/
140    protected boolean sourcesInitiallyLoaded;
141
142    /**
143     * Constructs a new {@code SourceEditor}.
144     * @param sourceType the type of source managed by this editor
145     * @param availableSourcesUrl the URL to the list of available sources
146     * @param sourceProviders the list of additional source providers, from plugins
147     * @param handleIcons {@code true} if icons may be managed, {@code false} otherwise
148     */
149    protected SourceEditor(SourceType sourceType, String availableSourcesUrl, List<SourceProvider> sourceProviders, boolean handleIcons) {
150
151        this.sourceType = sourceType;
152        this.canEnable = sourceType == SourceType.MAP_PAINT_STYLE || sourceType == SourceType.TAGCHECKER_RULE;
153
154        DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
155        this.availableSourcesModel = new AvailableSourcesModel();
156        this.tblAvailableSources = new ScrollHackTable(availableSourcesModel);
157        // This add/remove listener code is needed to fix #20849. Java fires table listeners in the reverse order
158        // in which they were added, and we need the model to have been updated before we call the adjustColumnWidth code.
159        // So we remove the JTable and re-add it as a listener after we add the column width adjustment
160        availableSourcesModel.addTableModelListener(e -> TableHelper.adjustColumnWidth(tblAvailableSources, 0, 800));
161        availableSourcesModel.removeTableModelListener(this.tblAvailableSources);
162        availableSourcesModel.addTableModelListener(this.tblAvailableSources);
163        this.tblAvailableSources.setAutoCreateRowSorter(true);
164        this.tblAvailableSources.setSelectionModel(selectionModel);
165        final FancySourceEntryTableCellRenderer availableSourcesEntryRenderer = new FancySourceEntryTableCellRenderer();
166        this.tblAvailableSources.getColumnModel().getColumn(0).setCellRenderer(availableSourcesEntryRenderer);
167        GuiHelper.extendTooltipDelay(tblAvailableSources);
168        this.availableSourcesUrl = availableSourcesUrl;
169        this.sourceProviders = sourceProviders;
170
171        selectionModel = new DefaultListSelectionModel();
172        activeSourcesModel = new ActiveSourcesModel(selectionModel);
173        tblActiveSources = new ScrollHackTable(activeSourcesModel);
174        tblActiveSources.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
175        tblActiveSources.setSelectionModel(selectionModel);
176        Stream.of(tblAvailableSources, tblActiveSources).forEach(t -> {
177            t.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
178            t.setShowGrid(false);
179            t.setIntercellSpacing(new Dimension(0, 0));
180            t.setTableHeader(null);
181            t.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
182        });
183        SourceEntryTableCellRenderer sourceEntryRenderer = new SourceEntryTableCellRenderer();
184        if (canEnable) {
185            tblActiveSources.getColumnModel().getColumn(0).setMaxWidth(1);
186            tblActiveSources.getColumnModel().getColumn(0).setResizable(false);
187            tblActiveSources.getColumnModel().getColumn(1).setCellRenderer(sourceEntryRenderer);
188        } else {
189            tblActiveSources.getColumnModel().getColumn(0).setCellRenderer(sourceEntryRenderer);
190        }
191
192        activeSourcesModel.addTableModelListener(e -> {
193            availableSourcesEntryRenderer.updateSources(activeSourcesModel.getSources());
194            tblAvailableSources.repaint();
195        });
196        tblActiveSources.addPropertyChangeListener(evt -> {
197            availableSourcesEntryRenderer.updateSources(activeSourcesModel.getSources());
198            tblAvailableSources.repaint();
199        });
200        // Force Swing to show horizontal scrollbars for the JTable
201        // Yes, this is a little ugly, but should work
202        activeSourcesModel.addTableModelListener(e -> TableHelper.adjustColumnWidth(tblActiveSources, canEnable ? 1 : 0, 800));
203        activeSourcesModel.setActiveSources(getInitialSourcesList());
204
205        final EditActiveSourceAction editActiveSourceAction = new EditActiveSourceAction();
206        tblActiveSources.getSelectionModel().addListSelectionListener(editActiveSourceAction);
207        tblActiveSources.addMouseListener(new MouseAdapter() {
208            @Override
209            public void mouseClicked(MouseEvent e) {
210                if (e.getClickCount() == 2) {
211                    int row = tblActiveSources.rowAtPoint(e.getPoint());
212                    int col = tblActiveSources.columnAtPoint(e.getPoint());
213                    if (row < 0 || row >= tblActiveSources.getRowCount())
214                        return;
215                    if (canEnable && col != 1)
216                        return;
217                    editActiveSourceAction.actionPerformed(null);
218                }
219            }
220        });
221
222        RemoveActiveSourcesAction removeActiveSourcesAction = new RemoveActiveSourcesAction();
223        tblActiveSources.getSelectionModel().addListSelectionListener(removeActiveSourcesAction);
224        tblActiveSources.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), DELETE);
225        tblActiveSources.getActionMap().put(DELETE, removeActiveSourcesAction);
226
227        MoveUpDownAction moveUp = null;
228        MoveUpDownAction moveDown = null;
229        if (sourceType == SourceType.MAP_PAINT_STYLE) {
230            moveUp = new MoveUpDownAction(false);
231            moveDown = new MoveUpDownAction(true);
232            tblActiveSources.getSelectionModel().addListSelectionListener(moveUp);
233            tblActiveSources.getSelectionModel().addListSelectionListener(moveDown);
234            activeSourcesModel.addTableModelListener(moveUp);
235            activeSourcesModel.addTableModelListener(moveDown);
236        }
237
238        ActivateSourcesAction activateSourcesAction = new ActivateSourcesAction();
239        tblAvailableSources.getSelectionModel().addListSelectionListener(activateSourcesAction);
240        JButton activate = new JButton(activateSourcesAction);
241
242        setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
243        setLayout(new GridBagLayout());
244
245        GridBagConstraints gbc = new GridBagConstraints();
246        gbc.gridx = 0;
247        gbc.gridy = 0;
248        gbc.weightx = 0.5;
249        gbc.gridwidth = 2;
250        gbc.anchor = GBC.WEST;
251        gbc.insets = new Insets(5, 11, 0, 0);
252
253        add(new JLabel(getStr(I18nString.AVAILABLE_SOURCES)), gbc);
254
255        gbc.gridx = 2;
256        gbc.insets = new Insets(5, 0, 0, 6);
257
258        add(new JLabel(getStr(I18nString.ACTIVE_SOURCES)), gbc);
259
260        gbc.gridwidth = 1;
261        gbc.gridx = 0;
262        gbc.gridy++;
263        gbc.weighty = 0.8;
264        gbc.fill = GBC.BOTH;
265        gbc.anchor = GBC.CENTER;
266        gbc.insets = new Insets(0, 11, 0, 0);
267
268        FilterField availableSourcesFilter = new FilterField().filter(tblAvailableSources, availableSourcesModel);
269        JPanel defaultPane = new JPanel(new GridBagLayout());
270        JScrollPane sp1 = new JScrollPane(tblAvailableSources);
271        defaultPane.add(availableSourcesFilter, GBC.eol().insets(0, 0, 0, 0).fill(GridBagConstraints.HORIZONTAL));
272        defaultPane.add(sp1, GBC.eol().insets(0, 0, 0, 0).fill(GridBagConstraints.BOTH));
273        add(defaultPane, gbc);
274
275        gbc.gridx = 1;
276        gbc.weightx = 0.0;
277        gbc.fill = GBC.VERTICAL;
278        gbc.insets = new Insets(0, 0, 0, 0);
279
280        JToolBar middleTB = new JToolBar();
281        middleTB.setFloatable(false);
282        middleTB.setBorderPainted(false);
283        middleTB.setOpaque(false);
284        middleTB.add(Box.createHorizontalGlue());
285        middleTB.add(activate);
286        middleTB.add(Box.createHorizontalGlue());
287        add(middleTB, gbc);
288
289        gbc.gridx++;
290        gbc.weightx = 0.5;
291        gbc.fill = GBC.BOTH;
292
293        JScrollPane sp = new JScrollPane(tblActiveSources);
294        add(sp, gbc);
295        sp.setColumnHeaderView(null);
296
297        gbc.gridx++;
298        gbc.weightx = 0.0;
299        gbc.fill = GBC.VERTICAL;
300        gbc.insets = new Insets(0, 0, 0, 6);
301
302        JToolBar sideButtonTB = new JToolBar(SwingConstants.VERTICAL);
303        sideButtonTB.setFloatable(false);
304        sideButtonTB.setBorderPainted(false);
305        sideButtonTB.setOpaque(false);
306        sideButtonTB.add(new NewActiveSourceAction());
307        sideButtonTB.add(editActiveSourceAction);
308        sideButtonTB.add(removeActiveSourcesAction);
309        sideButtonTB.addSeparator(new Dimension(12, 30));
310        if (sourceType == SourceType.MAP_PAINT_STYLE) {
311            sideButtonTB.add(moveUp);
312            sideButtonTB.add(moveDown);
313        }
314        add(sideButtonTB, gbc);
315
316        gbc.gridx = 0;
317        gbc.gridy++;
318        gbc.weighty = 0.0;
319        gbc.weightx = 0.5;
320        gbc.fill = GBC.HORIZONTAL;
321        gbc.anchor = GBC.WEST;
322        gbc.insets = new Insets(0, 11, 0, 0);
323
324        JToolBar bottomLeftTB = new JToolBar();
325        bottomLeftTB.setFloatable(false);
326        bottomLeftTB.setBorderPainted(false);
327        bottomLeftTB.setOpaque(false);
328        bottomLeftTB.add(new ReloadSourcesAction(availableSourcesUrl, sourceProviders));
329        bottomLeftTB.add(Box.createHorizontalGlue());
330        add(bottomLeftTB, gbc);
331
332        gbc.gridx = 2;
333        gbc.anchor = GBC.CENTER;
334        gbc.insets = new Insets(0, 0, 0, 0);
335
336        JToolBar bottomRightTB = new JToolBar();
337        bottomRightTB.setFloatable(false);
338        bottomRightTB.setBorderPainted(false);
339        bottomRightTB.setOpaque(false);
340        bottomRightTB.add(Box.createHorizontalGlue());
341        bottomRightTB.add(new JButton(new ResetAction()));
342        add(bottomRightTB, gbc);
343
344        // Icon configuration
345        if (handleIcons) {
346            buildIcons(gbc);
347        }
348    }
349
350    private void buildIcons(GridBagConstraints gbc) {
351        DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
352        iconPathsModel = new IconPathTableModel(selectionModel);
353        tblIconPaths = new JTable(iconPathsModel);
354        TableHelper.setFont(tblIconPaths, getClass());
355        tblIconPaths.setSelectionModel(selectionModel);
356        tblIconPaths.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
357        tblIconPaths.setTableHeader(null);
358        tblIconPaths.getColumnModel().getColumn(0).setCellEditor(new FileOrUrlCellEditor(false));
359        tblIconPaths.setRowHeight(20);
360        tblIconPaths.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
361        iconPathsModel.setIconPaths(getInitialIconPathsList());
362
363        EditIconPathAction editIconPathAction = new EditIconPathAction();
364        tblIconPaths.getSelectionModel().addListSelectionListener(editIconPathAction);
365
366        RemoveIconPathAction removeIconPathAction = new RemoveIconPathAction();
367        tblIconPaths.getSelectionModel().addListSelectionListener(removeIconPathAction);
368        tblIconPaths.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), DELETE);
369        tblIconPaths.getActionMap().put(DELETE, removeIconPathAction);
370
371        gbc.gridx = 0;
372        gbc.gridy++;
373        gbc.weightx = 1.0;
374        gbc.gridwidth = GBC.REMAINDER;
375        gbc.insets = new Insets(8, 11, 8, 6);
376
377        add(new JSeparator(), gbc);
378
379        gbc.gridy++;
380        gbc.insets = new Insets(0, 11, 0, 6);
381
382        add(new JLabel(tr("Icon paths:")), gbc);
383
384        gbc.gridy++;
385        gbc.weighty = 0.2;
386        gbc.gridwidth = 3;
387        gbc.fill = GBC.BOTH;
388        gbc.insets = new Insets(0, 11, 0, 0);
389
390        JScrollPane sp = new JScrollPane(tblIconPaths);
391        add(sp, gbc);
392        sp.setColumnHeaderView(null);
393
394        gbc.gridx = 3;
395        gbc.gridwidth = 1;
396        gbc.weightx = 0.0;
397        gbc.fill = GBC.VERTICAL;
398        gbc.insets = new Insets(0, 0, 0, 6);
399
400        JToolBar sideButtonTBIcons = new JToolBar(JToolBar.VERTICAL);
401        sideButtonTBIcons.setFloatable(false);
402        sideButtonTBIcons.setBorderPainted(false);
403        sideButtonTBIcons.setOpaque(false);
404        sideButtonTBIcons.add(new NewIconPathAction());
405        sideButtonTBIcons.add(editIconPathAction);
406        sideButtonTBIcons.add(removeIconPathAction);
407        add(sideButtonTBIcons, gbc);
408    }
409
410    /**
411     * Load the list of source entries that the user has configured.
412     * @return list of source entries that the user has configured
413     */
414    public abstract Collection<? extends SourceEntry> getInitialSourcesList();
415
416    /**
417     * Load the list of configured icon paths.
418     * @return list of configured icon paths
419     */
420    public abstract Collection<String> getInitialIconPathsList();
421
422    /**
423     * Get the default list of entries (used when resetting the list).
424     * @return default list of entries
425     */
426    public abstract Collection<ExtendedSourceEntry> getDefault();
427
428    /**
429     * Save the settings after user clicked "Ok".
430     * @return true if restart is required
431     */
432    public abstract boolean finish();
433
434    /**
435     * Default implementation of {@link #finish}.
436     * @param prefHelper Helper class for specialized extensions preferences
437     * @param iconPref icons path preference
438     * @return true if restart is required
439     */
440    protected boolean doFinish(SourcePrefHelper prefHelper, String iconPref) {
441        boolean changed = prefHelper.put(activeSourcesModel.getSources());
442
443        if (tblIconPaths != null) {
444            List<String> iconPaths = iconPathsModel.getIconPaths();
445
446            if (!iconPaths.isEmpty()) {
447                if (Config.getPref().putList(iconPref, iconPaths)) {
448                    changed = true;
449                }
450            } else if (Config.getPref().putList(iconPref, null)) {
451                changed = true;
452            }
453        }
454        return changed;
455    }
456
457    /**
458     * Provide the GUI strings. (There are differences for MapPaint, Preset and TagChecker Rule)
459     * @param ident any {@link I18nString} value
460     * @return the translated string for {@code ident}
461     */
462    protected abstract String getStr(I18nString ident);
463
464    static final class ScrollHackTable extends JTable {
465        ScrollHackTable(TableModel dm) {
466            super(dm);
467        }
468
469        // some kind of hack to prevent the table from scrolling slightly to the right when clicking on the text
470        @Override
471        public void scrollRectToVisible(Rectangle aRect) {
472            super.scrollRectToVisible(new Rectangle(0, aRect.y, aRect.width, aRect.height));
473        }
474    }
475
476    /**
477     * Identifiers for strings that need to be provided.
478     */
479    public enum I18nString {
480        /** Available (styles|presets|rules) */
481        AVAILABLE_SOURCES,
482        /** Active (styles|presets|rules) */
483        ACTIVE_SOURCES,
484        /** Add a new (style|preset|rule) by entering filename or URL */
485        NEW_SOURCE_ENTRY_TOOLTIP,
486        /** New (style|preset|rule) entry */
487        NEW_SOURCE_ENTRY,
488        /** Remove the selected (styles|presets|rules) from the list of active (styles|presets|rules) */
489        REMOVE_SOURCE_TOOLTIP,
490        /** Edit the filename or URL for the selected active (style|preset|rule) */
491        EDIT_SOURCE_TOOLTIP,
492        /** Add the selected available (styles|presets|rules) to the list of active (styles|presets|rules) */
493        ACTIVATE_TOOLTIP,
494        /** Reloads the list of available (styles|presets|rules) */
495        RELOAD_ALL_AVAILABLE,
496        /** Loading (style|preset|rule) sources */
497        LOADING_SOURCES_FROM,
498        /** Failed to load the list of (style|preset|rule) sources */
499        FAILED_TO_LOAD_SOURCES_FROM,
500        /** /Preferences/(Styles|Presets|Rules)#FailedToLoad(Style|Preset|Rule)Sources */
501        FAILED_TO_LOAD_SOURCES_FROM_HELP_TOPIC,
502        /** Illegal format of entry in (style|preset|rule) list */
503        ILLEGAL_FORMAT_OF_ENTRY
504    }
505
506    /**
507     * Determines whether the list of active sources has changed.
508     * @return {@code true} if the list of active sources has changed, {@code false} otherwise
509     */
510    public boolean hasActiveSourcesChanged() {
511        Collection<? extends SourceEntry> prev = getInitialSourcesList();
512        List<SourceEntry> cur = activeSourcesModel.getSources();
513        if (prev.size() != cur.size())
514            return true;
515        Iterator<? extends SourceEntry> p = prev.iterator();
516        Iterator<SourceEntry> c = cur.iterator();
517        while (p.hasNext()) {
518            SourceEntry pe = p.next();
519            SourceEntry ce = c.next();
520            if (!Objects.equals(pe.url, ce.url) || !Objects.equals(pe.name, ce.name) || pe.active != ce.active)
521                return true;
522        }
523        return false;
524    }
525
526    /**
527     * Returns the list of active sources.
528     * @return the list of active sources
529     */
530    public Collection<SourceEntry> getActiveSources() {
531        return activeSourcesModel.getSources();
532    }
533
534    /**
535     * Synchronously loads available sources and returns the parsed list.
536     * @return list of available sources
537     * @throws OsmTransferException in case of OSM transfer error
538     * @throws IOException in case of any I/O error
539     * @throws SAXException in case of any SAX error
540     */
541    public final Collection<ExtendedSourceEntry> loadAndGetAvailableSources() throws SAXException, IOException, OsmTransferException {
542        final SourceLoader loader = new SourceLoader(availableSourcesUrl, sourceProviders);
543        loader.realRun();
544        return loader.sources;
545    }
546
547    /**
548     * Remove sources associated with given indexes from active list.
549     * @param idxs indexes of sources to remove
550     */
551    public void removeSources(Collection<Integer> idxs) {
552        activeSourcesModel.removeIdxs(idxs);
553    }
554
555    /**
556     * Reload available sources.
557     * @param url the URL from which the available sources are fetched
558     * @param sourceProviders the list of source providers
559     */
560    protected void reloadAvailableSources(String url, List<SourceProvider> sourceProviders) {
561        MainApplication.worker.submit(new SourceLoader(url, sourceProviders));
562    }
563
564    /**
565     * Performs the initial loading of source providers. Does nothing if already done.
566     */
567    public void initiallyLoadAvailableSources() {
568        if (!sourcesInitiallyLoaded && !NetworkManager.isOffline(OnlineResource.CACHE_UPDATES)) {
569            reloadAvailableSources(availableSourcesUrl, sourceProviders);
570        }
571        sourcesInitiallyLoaded = true;
572    }
573
574    /**
575     * List model of available sources.
576     */
577    protected static class AvailableSourcesModel extends AbstractTableModel {
578        private final transient List<ExtendedSourceEntry> data;
579
580        /**
581         * Constructs a new {@code AvailableSourcesListModel}
582         */
583        public AvailableSourcesModel() {
584            data = new ArrayList<>();
585        }
586
587        /**
588         * Sets the source list.
589         * @param sources source list
590         */
591        public void setSources(List<ExtendedSourceEntry> sources) {
592            data.clear();
593            if (sources != null) {
594                data.addAll(sources);
595            }
596            fireTableDataChanged();
597        }
598
599        public ExtendedSourceEntry getValueAt(int rowIndex) {
600            return data.get(rowIndex);
601        }
602
603        @Override
604        public ExtendedSourceEntry getValueAt(int rowIndex, int ignored) {
605            return getValueAt(rowIndex);
606        }
607
608        @Override
609        public int getRowCount() {
610            if (data == null) return 0;
611            return data.size();
612        }
613
614        @Override
615        public int getColumnCount() {
616            return 1;
617        }
618    }
619
620    /**
621     * Table model of active sources.
622     */
623    protected class ActiveSourcesModel extends AbstractTableModel implements ReorderableTableModel<SourceEntry> {
624        private transient List<SourceEntry> data;
625        private final DefaultListSelectionModel selectionModel;
626
627        /**
628         * Constructs a new {@code ActiveSourcesModel}.
629         * @param selectionModel selection model
630         */
631        public ActiveSourcesModel(DefaultListSelectionModel selectionModel) {
632            this.selectionModel = selectionModel;
633            this.data = new ArrayList<>();
634        }
635
636        @Override
637        public int getColumnCount() {
638            return canEnable ? 2 : 1;
639        }
640
641        @Override
642        public int getRowCount() {
643            return data == null ? 0 : data.size();
644        }
645
646        @Override
647        public Object getValueAt(int rowIndex, int columnIndex) {
648            if (canEnable && columnIndex == 0)
649                return data.get(rowIndex).active;
650            else
651                return data.get(rowIndex);
652        }
653
654        @Override
655        public boolean isCellEditable(int rowIndex, int columnIndex) {
656            return canEnable && columnIndex == 0;
657        }
658
659        @Override
660        public Class<?> getColumnClass(int column) {
661            if (canEnable && column == 0)
662                return Boolean.class;
663            else return SourceEntry.class;
664        }
665
666        @Override
667        public void setValueAt(Object aValue, int row, int column) {
668            if (row < 0 || row >= getRowCount() || aValue == null)
669                return;
670            if (canEnable && column == 0) {
671                data.get(row).active = !data.get(row).active;
672            }
673        }
674
675        /**
676         * Sets active sources.
677         * @param sources active sources
678         */
679        public void setActiveSources(Collection<? extends SourceEntry> sources) {
680            data.clear();
681            if (sources != null) {
682                for (SourceEntry e : sources) {
683                    data.add(new SourceEntry(e));
684                }
685            }
686            fireTableDataChanged();
687        }
688
689        /**
690         * Adds an active source.
691         * @param entry source to add
692         */
693        public void addSource(SourceEntry entry) {
694            if (entry == null) return;
695            data.add(entry);
696            fireTableDataChanged();
697            int idx = data.indexOf(entry);
698            if (idx >= 0) {
699                selectionModel.setSelectionInterval(idx, idx);
700            }
701        }
702
703        /**
704         * Removes the selected sources.
705         */
706        public void removeSelected() {
707            Iterator<SourceEntry> it = data.iterator();
708            int i = 0;
709            while (it.hasNext()) {
710                it.next();
711                if (selectionModel.isSelectedIndex(i)) {
712                    it.remove();
713                }
714                i++;
715            }
716            fireTableDataChanged();
717        }
718
719        /**
720         * Removes the sources at given indexes.
721         * @param idxs indexes to remove
722         */
723        public void removeIdxs(Collection<Integer> idxs) {
724            data = IntStream.range(0, data.size())
725                    .filter(i -> !idxs.contains(i))
726                    .mapToObj(data::get)
727                    .collect(Collectors.toList());
728            fireTableDataChanged();
729        }
730
731        /**
732         * Adds multiple sources.
733         * @param sources source entries
734         */
735        public void addExtendedSourceEntries(List<ExtendedSourceEntry> sources) {
736            if (sources == null) return;
737            for (ExtendedSourceEntry info: sources) {
738                data.add(new SourceEntry(info.type, info.url, info.name, info.getDisplayName(), true));
739            }
740            fireTableDataChanged();
741            TableHelper.setSelectedIndices(selectionModel, sources.stream().mapToInt(data::indexOf));
742        }
743
744        /**
745         * Returns the active sources.
746         * @return the active sources
747         */
748        public List<SourceEntry> getSources() {
749            return new ArrayList<>(data);
750        }
751
752        @Override
753        public DefaultListSelectionModel getSelectionModel() {
754            return selectionModel;
755        }
756
757        @Override
758        public SourceEntry getValue(int index) {
759            return data.get(index);
760        }
761
762        @Override
763        public SourceEntry setValue(int index, SourceEntry value) {
764            return data.set(index, value);
765        }
766    }
767
768    private static void prepareFileChooser(String url, AbstractFileChooser fc) {
769        if (Utils.isStripEmpty(url)) return;
770        URL sourceUrl;
771        try {
772            sourceUrl = new URL(url);
773        } catch (MalformedURLException e) {
774            File f = new File(url);
775            if (f.isFile()) {
776                f = f.getParentFile();
777            }
778            if (f != null) {
779                fc.setCurrentDirectory(f);
780            }
781            return;
782        }
783        if (sourceUrl.getProtocol().startsWith("file")) {
784            File f = new File(sourceUrl.getPath());
785            if (f.isFile()) {
786                f = f.getParentFile();
787            }
788            if (f != null) {
789                fc.setCurrentDirectory(f);
790            }
791        }
792    }
793
794    /**
795     * Dialog to edit a source entry.
796     */
797    protected class EditSourceEntryDialog extends ExtendedDialog {
798
799        private final JosmTextField tfTitle;
800        private final JosmTextField tfURL;
801        private JCheckBox cbActive;
802
803        /**
804         * Constructs a new {@code EditSourceEntryDialog}.
805         * @param parent parent component
806         * @param title dialog title
807         * @param e source entry to edit
808         */
809        public EditSourceEntryDialog(Component parent, String title, SourceEntry e) {
810            super(parent, title, tr("Ok"), tr("Cancel"));
811
812            JPanel p = new JPanel(new GridBagLayout());
813
814            tfTitle = new JosmTextField(60);
815            p.add(new JLabel(tr("Name (optional):")), GBC.std().insets(15, 0, 5, 5));
816            p.add(tfTitle, GBC.eol().insets(0, 0, 5, 5));
817
818            tfURL = new JosmTextField(60);
819            p.add(new JLabel(tr("URL / File:")), GBC.std().insets(15, 0, 5, 0));
820            p.add(tfURL, GBC.std().insets(0, 0, 5, 5));
821            JButton fileChooser = new JButton(new LaunchFileChooserSourceTypeAction());
822            fileChooser.setMargin(new Insets(0, 0, 0, 0));
823            p.add(fileChooser, GBC.eol().insets(0, 0, 5, 5));
824
825            if (e != null) {
826                if (e.title != null) {
827                    tfTitle.setText(e.title);
828                }
829                tfURL.setText(e.url);
830            }
831
832            if (canEnable) {
833                cbActive = new JCheckBox(tr("active"), e == null || e.active);
834                p.add(cbActive, GBC.eol().insets(15, 0, 5, 0));
835            }
836            setButtonIcons("ok", "cancel");
837            setContent(p);
838
839            // Make OK button enabled only when a file/URL has been set
840            tfURL.getDocument().addDocumentListener(DocumentAdapter.create(ignore -> updateOkButtonState()));
841        }
842
843        private void updateOkButtonState() {
844            buttons.get(0).setEnabled(!Utils.isStripEmpty(tfURL.getText()));
845        }
846
847        @Override
848        public void setupDialog() {
849            super.setupDialog();
850            updateOkButtonState();
851        }
852
853        class LaunchFileChooserSourceTypeAction extends AbstractAction {
854            LaunchFileChooserSourceTypeAction() {
855                new ImageProvider("open").getResource().attachImageIcon(this);
856                putValue(SHORT_DESCRIPTION, tr("Launch a file chooser to select a file"));
857            }
858
859            @Override
860            public void actionPerformed(ActionEvent e) {
861                FileFilter ff;
862                switch (sourceType) {
863                case MAP_PAINT_STYLE:
864                    ff = new ExtensionFileFilter("xml,mapcss,css,zip", "xml", tr("Map paint style file (*.xml, *.mapcss, *.zip)"));
865                    break;
866                case TAGGING_PRESET:
867                    ff = new ExtensionFileFilter("xml,zip", "xml", tr("Preset definition file (*.xml, *.zip)"));
868                    break;
869                case TAGCHECKER_RULE:
870                    ff = new ExtensionFileFilter("validator.mapcss,zip", "validator.mapcss", tr("Tag checker rule (*.validator.mapcss, *.zip)"));
871                    break;
872                default:
873                    Logging.error("Unsupported source type: "+sourceType);
874                    return;
875                }
876                FileChooserManager fcm = new FileChooserManager(true)
877                        .createFileChooser(true, null, Arrays.asList(ff, FileFilterAllFiles.getInstance()), ff, JFileChooser.FILES_ONLY);
878                prepareFileChooser(tfURL.getText(), fcm.getFileChooser());
879                AbstractFileChooser fc = fcm.openFileChooser(GuiHelper.getFrameForComponent(SourceEditor.this));
880                if (fc != null) {
881                    tfURL.setText(fc.getSelectedFile().toString());
882                }
883            }
884        }
885
886        @Override
887        public String getTitle() {
888            return tfTitle.getText();
889        }
890
891        /**
892         * Returns the entered URL / File.
893         * @return the entered URL / File
894         */
895        public String getURL() {
896            return tfURL.getText();
897        }
898
899        /**
900         * Determines if the active combobox is selected.
901         * @return {@code true} if the active combobox is selected
902         */
903        public boolean active() {
904            if (!canEnable)
905                throw new UnsupportedOperationException();
906            return cbActive.isSelected();
907        }
908    }
909
910    class NewActiveSourceAction extends AbstractAction {
911        NewActiveSourceAction() {
912            putValue(NAME, tr("New"));
913            putValue(SHORT_DESCRIPTION, getStr(I18nString.NEW_SOURCE_ENTRY_TOOLTIP));
914            new ImageProvider(DIALOGS, "add").getResource().attachImageIcon(this);
915        }
916
917        @Override
918        public void actionPerformed(ActionEvent evt) {
919            EditSourceEntryDialog editEntryDialog = new EditSourceEntryDialog(
920                    SourceEditor.this,
921                    getStr(I18nString.NEW_SOURCE_ENTRY),
922                    null);
923            editEntryDialog.showDialog();
924            if (editEntryDialog.getValue() == 1) {
925                boolean active = true;
926                if (canEnable) {
927                    active = editEntryDialog.active();
928                }
929                final SourceEntry entry = new SourceEntry(sourceType,
930                        editEntryDialog.getURL(),
931                        null, editEntryDialog.getTitle(), active);
932                entry.title = getTitleForSourceEntry(entry);
933                activeSourcesModel.addSource(entry);
934                activeSourcesModel.fireTableDataChanged();
935            }
936        }
937    }
938
939    class RemoveActiveSourcesAction extends AbstractAction implements ListSelectionListener {
940
941        RemoveActiveSourcesAction() {
942            putValue(NAME, tr("Remove"));
943            putValue(SHORT_DESCRIPTION, getStr(I18nString.REMOVE_SOURCE_TOOLTIP));
944            new ImageProvider(DIALOGS, DELETE).getResource().attachImageIcon(this);
945            updateEnabledState();
946        }
947
948        protected final void updateEnabledState() {
949            setEnabled(tblActiveSources.getSelectedRowCount() > 0);
950        }
951
952        @Override
953        public void valueChanged(ListSelectionEvent e) {
954            updateEnabledState();
955        }
956
957        @Override
958        public void actionPerformed(ActionEvent e) {
959            activeSourcesModel.removeSelected();
960        }
961    }
962
963    class EditActiveSourceAction extends AbstractAction implements ListSelectionListener {
964        EditActiveSourceAction() {
965            putValue(NAME, tr("Edit"));
966            putValue(SHORT_DESCRIPTION, getStr(I18nString.EDIT_SOURCE_TOOLTIP));
967            new ImageProvider(DIALOGS, "edit").getResource().attachImageIcon(this);
968            updateEnabledState();
969        }
970
971        protected final void updateEnabledState() {
972            setEnabled(tblActiveSources.getSelectedRowCount() == 1);
973        }
974
975        @Override
976        public void valueChanged(ListSelectionEvent e) {
977            updateEnabledState();
978        }
979
980        @Override
981        public void actionPerformed(ActionEvent evt) {
982            int pos = tblActiveSources.getSelectedRow();
983            if (pos < 0 || pos >= tblActiveSources.getRowCount())
984                return;
985
986            SourceEntry e = (SourceEntry) activeSourcesModel.getValueAt(pos, 1);
987
988            EditSourceEntryDialog editEntryDialog = new EditSourceEntryDialog(
989                    SourceEditor.this, tr("Edit source entry:"), e);
990            editEntryDialog.showDialog();
991            if (editEntryDialog.getValue() == 1) {
992                if (e.title != null || !"".equals(editEntryDialog.getTitle())) {
993                    e.title = editEntryDialog.getTitle();
994                    e.title = getTitleForSourceEntry(e);
995                }
996                e.url = editEntryDialog.getURL();
997                if (canEnable) {
998                    e.active = editEntryDialog.active();
999                }
1000                activeSourcesModel.fireTableRowsUpdated(pos, pos);
1001            }
1002        }
1003    }
1004
1005    /**
1006     * The action to move the currently selected entries up or down in the list.
1007     */
1008    class MoveUpDownAction extends AbstractAction implements ListSelectionListener, TableModelListener {
1009        private final int increment;
1010
1011        MoveUpDownAction(boolean isDown) {
1012            increment = isDown ? 1 : -1;
1013            new ImageProvider(DIALOGS, isDown ? "down" : "up").getResource().attachImageIcon(this, true);
1014            putValue(SHORT_DESCRIPTION, isDown ? tr("Move the selected entry one row down.") : tr("Move the selected entry one row up."));
1015            updateEnabledState();
1016        }
1017
1018        public final void updateEnabledState() {
1019            setEnabled(activeSourcesModel.canMove(increment));
1020        }
1021
1022        @Override
1023        public void actionPerformed(ActionEvent e) {
1024            activeSourcesModel.move(increment, tblActiveSources.getSelectedRows());
1025        }
1026
1027        @Override
1028        public void valueChanged(ListSelectionEvent e) {
1029            updateEnabledState();
1030        }
1031
1032        @Override
1033        public void tableChanged(TableModelEvent e) {
1034            updateEnabledState();
1035        }
1036    }
1037
1038    class ActivateSourcesAction extends AbstractAction implements ListSelectionListener {
1039        ActivateSourcesAction() {
1040            putValue(SHORT_DESCRIPTION, getStr(I18nString.ACTIVATE_TOOLTIP));
1041            new ImageProvider("preferences", "activate-right").getResource().attachImageIcon(this);
1042            updateEnabledState();
1043        }
1044
1045        protected final void updateEnabledState() {
1046            setEnabled(tblAvailableSources.getSelectedRowCount() > 0);
1047        }
1048
1049        @Override
1050        public void valueChanged(ListSelectionEvent e) {
1051            updateEnabledState();
1052        }
1053
1054        @Override
1055        public void actionPerformed(ActionEvent e) {
1056            List<ExtendedSourceEntry> sources = Arrays.stream(tblAvailableSources.getSelectedRows())
1057                    .map(tblAvailableSources::convertRowIndexToModel)
1058                    .mapToObj(availableSourcesModel::getValueAt)
1059                    .collect(Collectors.toList());
1060
1061            int josmVersion = Version.getInstance().getVersion();
1062            if (josmVersion != Version.JOSM_UNKNOWN_VERSION) {
1063                Collection<String> messages = new ArrayList<>();
1064                for (ExtendedSourceEntry entry : sources) {
1065                    if (entry.minJosmVersion != null && entry.minJosmVersion > josmVersion) {
1066                        messages.add(tr("Entry ''{0}'' requires JOSM Version {1}. (Currently running: {2})",
1067                                entry.title,
1068                                Integer.toString(entry.minJosmVersion),
1069                                Integer.toString(josmVersion))
1070                        );
1071                    }
1072                }
1073                if (!messages.isEmpty()) {
1074                    ExtendedDialog dlg = new ExtendedDialog(MainApplication.getMainFrame(), tr("Warning"), tr("Cancel"), tr("Continue anyway"));
1075                    dlg.setButtonIcons(
1076                        ImageProvider.get("cancel"),
1077                        new ImageProvider("ok").setMaxSize(ImageSizes.LARGEICON).addOverlay(
1078                                new ImageOverlay(new ImageProvider("warning-small"), 0.5, 0.5, 1.0, 1.0)).get()
1079                    );
1080                    dlg.setToolTipTexts(
1081                        tr("Cancel and return to the previous dialog"),
1082                        tr("Ignore warning and install style anyway"));
1083                    dlg.setContent("<html>" + tr("Some entries have unmet dependencies:") +
1084                            "<br>" + String.join("<br>", messages) + "</html>");
1085                    dlg.setIcon(JOptionPane.WARNING_MESSAGE);
1086                    if (dlg.showDialog().getValue() != 2)
1087                        return;
1088                }
1089            }
1090            activeSourcesModel.addExtendedSourceEntries(sources);
1091        }
1092    }
1093
1094    class ResetAction extends AbstractAction {
1095
1096        ResetAction() {
1097            putValue(NAME, tr("Reset"));
1098            putValue(SHORT_DESCRIPTION, tr("Reset to default"));
1099            new ImageProvider("preferences", "reset").getResource().attachImageIcon(this);
1100        }
1101
1102        @Override
1103        public void actionPerformed(ActionEvent e) {
1104            activeSourcesModel.setActiveSources(getDefault());
1105        }
1106    }
1107
1108    class ReloadSourcesAction extends AbstractAction {
1109        private final String url;
1110        private final transient List<SourceProvider> sourceProviders;
1111
1112        ReloadSourcesAction(String url, List<SourceProvider> sourceProviders) {
1113            putValue(NAME, tr("Reload"));
1114            putValue(SHORT_DESCRIPTION, tr(getStr(I18nString.RELOAD_ALL_AVAILABLE), url));
1115            new ImageProvider(DIALOGS, "refresh").getResource().attachImageIcon(this);
1116            this.url = url;
1117            this.sourceProviders = sourceProviders;
1118            setEnabled(!NetworkManager.isOffline(OnlineResource.JOSM_WEBSITE));
1119        }
1120
1121        @Override
1122        public void actionPerformed(ActionEvent e) {
1123            CachedFile.cleanup(url);
1124            reloadAvailableSources(url, sourceProviders);
1125        }
1126    }
1127
1128    /**
1129     * Table model for icons paths.
1130     */
1131    protected static class IconPathTableModel extends AbstractTableModel {
1132        private final List<String> data;
1133        private final DefaultListSelectionModel selectionModel;
1134
1135        /**
1136         * Constructs a new {@code IconPathTableModel}.
1137         * @param selectionModel selection model
1138         */
1139        public IconPathTableModel(DefaultListSelectionModel selectionModel) {
1140            this.selectionModel = selectionModel;
1141            this.data = new ArrayList<>();
1142        }
1143
1144        @Override
1145        public int getColumnCount() {
1146            return 1;
1147        }
1148
1149        @Override
1150        public int getRowCount() {
1151            return data == null ? 0 : data.size();
1152        }
1153
1154        @Override
1155        public Object getValueAt(int rowIndex, int columnIndex) {
1156            return data.get(rowIndex);
1157        }
1158
1159        @Override
1160        public boolean isCellEditable(int rowIndex, int columnIndex) {
1161            return true;
1162        }
1163
1164        @Override
1165        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
1166            updatePath(rowIndex, (String) aValue);
1167        }
1168
1169        /**
1170         * Sets the icons paths.
1171         * @param paths icons paths
1172         */
1173        public void setIconPaths(Collection<String> paths) {
1174            data.clear();
1175            if (paths != null) {
1176                data.addAll(paths);
1177            }
1178            sort();
1179            fireTableDataChanged();
1180        }
1181
1182        /**
1183         * Adds an icon path.
1184         * @param path icon path to add
1185         */
1186        public void addPath(String path) {
1187            if (path == null) return;
1188            data.add(path);
1189            sort();
1190            fireTableDataChanged();
1191            int idx = data.indexOf(path);
1192            if (idx >= 0) {
1193                selectionModel.setSelectionInterval(idx, idx);
1194            }
1195        }
1196
1197        /**
1198         * Updates icon path at given index.
1199         * @param pos position
1200         * @param path new path
1201         */
1202        public void updatePath(int pos, String path) {
1203            if (path == null) return;
1204            if (pos < 0 || pos >= getRowCount()) return;
1205            data.set(pos, path);
1206            sort();
1207            fireTableDataChanged();
1208            int idx = data.indexOf(path);
1209            if (idx >= 0) {
1210                selectionModel.setSelectionInterval(idx, idx);
1211            }
1212        }
1213
1214        /**
1215         * Removes the selected path.
1216         */
1217        public void removeSelected() {
1218            Iterator<String> it = data.iterator();
1219            int i = 0;
1220            while (it.hasNext()) {
1221                it.next();
1222                if (selectionModel.isSelectedIndex(i)) {
1223                    it.remove();
1224                }
1225                i++;
1226            }
1227            fireTableDataChanged();
1228            selectionModel.clearSelection();
1229        }
1230
1231        /**
1232         * Sorts paths lexicographically.
1233         */
1234        protected void sort() {
1235            data.sort((o1, o2) -> {
1236                    if (o1.isEmpty() && o2.isEmpty())
1237                        return 0;
1238                    if (o1.isEmpty()) return 1;
1239                    if (o2.isEmpty()) return -1;
1240                    return o1.compareTo(o2);
1241                });
1242        }
1243
1244        /**
1245         * Returns the icon paths.
1246         * @return the icon paths
1247         */
1248        public List<String> getIconPaths() {
1249            return new ArrayList<>(data);
1250        }
1251    }
1252
1253    class NewIconPathAction extends AbstractAction {
1254        NewIconPathAction() {
1255            putValue(NAME, tr("New"));
1256            putValue(SHORT_DESCRIPTION, tr("Add a new icon path"));
1257            new ImageProvider(DIALOGS, "add").getResource().attachImageIcon(this);
1258        }
1259
1260        @Override
1261        public void actionPerformed(ActionEvent e) {
1262            iconPathsModel.addPath("");
1263            tblIconPaths.editCellAt(iconPathsModel.getRowCount() -1, 0);
1264        }
1265    }
1266
1267    class RemoveIconPathAction extends AbstractAction implements ListSelectionListener {
1268        RemoveIconPathAction() {
1269            putValue(NAME, tr("Remove"));
1270            putValue(SHORT_DESCRIPTION, tr("Remove the selected icon paths"));
1271            new ImageProvider(DIALOGS, DELETE).getResource().attachImageIcon(this);
1272            updateEnabledState();
1273        }
1274
1275        protected final void updateEnabledState() {
1276            setEnabled(tblIconPaths.getSelectedRowCount() > 0);
1277        }
1278
1279        @Override
1280        public void valueChanged(ListSelectionEvent e) {
1281            updateEnabledState();
1282        }
1283
1284        @Override
1285        public void actionPerformed(ActionEvent e) {
1286            iconPathsModel.removeSelected();
1287        }
1288    }
1289
1290    class EditIconPathAction extends AbstractAction implements ListSelectionListener {
1291        EditIconPathAction() {
1292            putValue(NAME, tr("Edit"));
1293            putValue(SHORT_DESCRIPTION, tr("Edit the selected icon path"));
1294            new ImageProvider(DIALOGS, "edit").getResource().attachImageIcon(this);
1295            updateEnabledState();
1296        }
1297
1298        protected final void updateEnabledState() {
1299            setEnabled(tblIconPaths.getSelectedRowCount() == 1);
1300        }
1301
1302        @Override
1303        public void valueChanged(ListSelectionEvent e) {
1304            updateEnabledState();
1305        }
1306
1307        @Override
1308        public void actionPerformed(ActionEvent e) {
1309            int row = tblIconPaths.getSelectedRow();
1310            tblIconPaths.editCellAt(row, 0);
1311        }
1312    }
1313
1314    static class FancySourceEntryTableCellRenderer extends DefaultTableCellRenderer {
1315
1316        private static final NamedColorProperty SOURCE_ENTRY_ACTIVE_BACKGROUND_COLOR = new NamedColorProperty(
1317                marktr("External resource entry: Active"),
1318                new Color(200, 255, 200));
1319        private static final NamedColorProperty SOURCE_ENTRY_INACTIVE_BACKGROUND_COLOR = new NamedColorProperty(
1320                marktr("External resource entry: Inactive"),
1321                new Color(200, 200, 200));
1322
1323        private final Map<String, SourceEntry> entryByUrl = new HashMap<>();
1324
1325        @Override
1326        public Component getTableCellRendererComponent(JTable list, Object object, boolean isSelected, boolean hasFocus, int row, int column) {
1327            super.getTableCellRendererComponent(list, object, isSelected, hasFocus, row, column);
1328            if (object instanceof ExtendedSourceEntry) {
1329                final ExtendedSourceEntry value = (ExtendedSourceEntry) object;
1330                String s = value.toString();
1331                setText(s);
1332                setToolTipText(value.getTooltip());
1333                if (!isSelected) {
1334                    final SourceEntry sourceEntry = entryByUrl.get(value.url);
1335                    GuiHelper.setBackgroundReadable(this, sourceEntry == null ? UIManager.getColor("Table.background") :
1336                        sourceEntry.active ? SOURCE_ENTRY_ACTIVE_BACKGROUND_COLOR.get() : SOURCE_ENTRY_INACTIVE_BACKGROUND_COLOR.get());
1337                }
1338                final ImageSizes size = ImageSizes.TABLE;
1339                setIcon(value.icon == null ? ImageProvider.getEmpty(size) : value.icon.getPaddedIcon(size.getImageDimension()));
1340            }
1341            return this;
1342        }
1343
1344        public void updateSources(List<SourceEntry> sources) {
1345            synchronized (entryByUrl) {
1346                entryByUrl.clear();
1347                for (SourceEntry i : sources) {
1348                    entryByUrl.put(i.url, i);
1349                }
1350            }
1351        }
1352    }
1353
1354    class SourceLoader extends PleaseWaitRunnable {
1355        private final String url;
1356        private final List<SourceProvider> sourceProviders;
1357        private CachedFile cachedFile;
1358        private boolean canceled;
1359        private final List<ExtendedSourceEntry> sources = new ArrayList<>();
1360
1361        SourceLoader(String url, List<SourceProvider> sourceProviders) {
1362            super(tr(getStr(I18nString.LOADING_SOURCES_FROM), url));
1363            this.url = url;
1364            this.sourceProviders = sourceProviders;
1365        }
1366
1367        @Override
1368        protected void cancel() {
1369            canceled = true;
1370            Utils.close(cachedFile);
1371        }
1372
1373        protected void warn(Exception e) {
1374            String emsg = Utils.escapeReservedCharactersHTML(e.getMessage() != null ? e.getMessage() : e.toString());
1375            final String msg = tr(getStr(I18nString.FAILED_TO_LOAD_SOURCES_FROM), url, emsg);
1376
1377            GuiHelper.runInEDT(() -> HelpAwareOptionPane.showOptionDialog(
1378                    MainApplication.getMainFrame(),
1379                    msg,
1380                    tr("Error"),
1381                    JOptionPane.ERROR_MESSAGE,
1382                    ht(getStr(I18nString.FAILED_TO_LOAD_SOURCES_FROM_HELP_TOPIC))
1383                    ));
1384        }
1385
1386        @Override
1387        protected void realRun() throws SAXException, IOException, OsmTransferException {
1388            try {
1389                sources.addAll(getDefault());
1390
1391                for (SourceProvider provider : sourceProviders) {
1392                    for (SourceEntry src : provider.getSources()) {
1393                        if (src instanceof ExtendedSourceEntry) {
1394                            sources.add((ExtendedSourceEntry) src);
1395                        }
1396                    }
1397                }
1398                readFile();
1399                if (sources.removeIf(extendedSourceEntry -> "xml".equals(extendedSourceEntry.styleType))) {
1400                    Logging.debug("Removing XML source entry");
1401                }
1402            } catch (IOException e) {
1403                if (canceled)
1404                    // ignore the exception and return
1405                    return;
1406                OsmTransferException ex = new OsmTransferException(e);
1407                ex.setUrl(url);
1408                warn(ex);
1409            }
1410        }
1411
1412        protected void readFile() throws IOException {
1413            final String lang = LanguageInfo.getLanguageCodeXML();
1414            cachedFile = new CachedFile(url);
1415            try (BufferedReader reader = cachedFile.getContentReader()) {
1416
1417                String line;
1418                ExtendedSourceEntry last = null;
1419
1420                while ((line = reader.readLine()) != null && !canceled) {
1421                    if (line.isBlank()) {
1422                        continue; // skip empty lines
1423                    }
1424                    if (line.startsWith("\t")) {
1425                        Matcher m = Pattern.compile("^\t([^:]+): *(.+)$").matcher(line);
1426                        if (!m.matches()) {
1427                            Logging.error(tr(getStr(I18nString.ILLEGAL_FORMAT_OF_ENTRY), url, line));
1428                            continue;
1429                        }
1430                        if (last != null) {
1431                            String key = m.group(1);
1432                            String value = m.group(2);
1433                            if ("author".equals(key) && last.author == null) {
1434                                last.author = value;
1435                            } else if ("version".equals(key)) {
1436                                last.version = value;
1437                            } else if ("icon".equals(key) && last.icon == null) {
1438                                last.icon = new ImageProvider(value).setOptional(true).getResource();
1439                            } else if ("link".equals(key) && last.link == null) {
1440                                last.link = value;
1441                            } else if ("description".equals(key) && last.description == null) {
1442                                last.description = value;
1443                            } else if ((lang + "shortdescription").equals(key) && last.title == null) {
1444                                last.title = value;
1445                            } else if ("shortdescription".equals(key) && last.title == null) {
1446                                last.title = value;
1447                            } else if ((lang + "title").equals(key) && last.title == null) {
1448                                last.title = value;
1449                            } else if ("title".equals(key) && last.title == null) {
1450                                last.title = value;
1451                            } else if ("name".equals(key) && last.name == null) {
1452                                last.name = value;
1453                            } else if ((lang + "author").equals(key)) {
1454                                last.author = value;
1455                            } else if ((lang + "link").equals(key)) {
1456                                last.link = value;
1457                            } else if ((lang + "description").equals(key)) {
1458                                last.description = value;
1459                            } else if ("min-josm-version".equals(key)) {
1460                                try {
1461                                    last.minJosmVersion = Integer.valueOf(value);
1462                                } catch (NumberFormatException e) {
1463                                    // ignore
1464                                    Logging.trace(e);
1465                                }
1466                            } else if ("style-type".equals(key)) {
1467                                last.styleType = value;
1468                            }
1469                        }
1470                    } else {
1471                        last = null;
1472                        Matcher m = Pattern.compile("^(.+);(.+)$").matcher(line);
1473                        if (m.matches()) {
1474                            last = new ExtendedSourceEntry(sourceType, m.group(1), m.group(2));
1475                            sources.add(last);
1476                        } else {
1477                            Logging.error(tr(getStr(I18nString.ILLEGAL_FORMAT_OF_ENTRY), url, line));
1478                        }
1479                    }
1480                }
1481            }
1482        }
1483
1484        @Override
1485        protected void finish() {
1486            Collections.sort(sources);
1487            availableSourcesModel.setSources(sources);
1488        }
1489    }
1490
1491    static class SourceEntryTableCellRenderer extends DefaultTableCellRenderer {
1492        @Override
1493        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
1494            if (value == null)
1495                return this;
1496            return super.getTableCellRendererComponent(table,
1497                    fromSourceEntry((SourceEntry) value), isSelected, hasFocus, row, column);
1498        }
1499
1500        private static String fromSourceEntry(SourceEntry entry) {
1501            if (entry == null)
1502                return null;
1503            StringBuilder s = new StringBuilder(128).append("<html><b>");
1504            if (entry.title != null) {
1505                s.append(Utils.escapeReservedCharactersHTML(entry.title)).append("</b> <span color=\"gray\">");
1506            }
1507            s.append(entry.url);
1508            if (entry.title != null) {
1509                s.append("</span>");
1510            }
1511            s.append("</html>");
1512            return s.toString();
1513        }
1514    }
1515
1516    class FileOrUrlCellEditor extends JPanel implements TableCellEditor {
1517        private final JosmTextField tfFileName = new JosmTextField();
1518        private final CopyOnWriteArrayList<CellEditorListener> listeners;
1519        private String value;
1520        private final boolean isFile;
1521
1522        /**
1523         * build the GUI
1524         */
1525        protected final void build() {
1526            setLayout(new GridBagLayout());
1527            GridBagConstraints gc = new GridBagConstraints();
1528            gc.gridx = 0;
1529            gc.gridy = 0;
1530            gc.fill = GridBagConstraints.BOTH;
1531            gc.weightx = 1.0;
1532            gc.weighty = 1.0;
1533            add(tfFileName, gc);
1534
1535            gc.gridx = 1;
1536            gc.gridy = 0;
1537            gc.fill = GridBagConstraints.BOTH;
1538            gc.weightx = 0.0;
1539            gc.weighty = 1.0;
1540            add(new JButton(new LaunchFileChooserEditCellAction()));
1541
1542            tfFileName.addFocusListener(
1543                    new FocusAdapter() {
1544                        @Override
1545                        public void focusGained(FocusEvent e) {
1546                            tfFileName.selectAll();
1547                        }
1548                    }
1549                    );
1550        }
1551
1552        FileOrUrlCellEditor(boolean isFile) {
1553            this.isFile = isFile;
1554            listeners = new CopyOnWriteArrayList<>();
1555            build();
1556        }
1557
1558        @Override
1559        public void addCellEditorListener(CellEditorListener l) {
1560            if (l != null) {
1561                listeners.addIfAbsent(l);
1562            }
1563        }
1564
1565        protected void fireEditingCanceled() {
1566            for (CellEditorListener l: listeners) {
1567                l.editingCanceled(new ChangeEvent(this));
1568            }
1569        }
1570
1571        protected void fireEditingStopped() {
1572            for (CellEditorListener l: listeners) {
1573                l.editingStopped(new ChangeEvent(this));
1574            }
1575        }
1576
1577        @Override
1578        public void cancelCellEditing() {
1579            fireEditingCanceled();
1580        }
1581
1582        @Override
1583        public Object getCellEditorValue() {
1584            return value;
1585        }
1586
1587        @Override
1588        public boolean isCellEditable(EventObject anEvent) {
1589            if (anEvent instanceof MouseEvent)
1590                return ((MouseEvent) anEvent).getClickCount() >= 2;
1591            return true;
1592        }
1593
1594        @Override
1595        public void removeCellEditorListener(CellEditorListener l) {
1596            listeners.remove(l);
1597        }
1598
1599        @Override
1600        public boolean shouldSelectCell(EventObject anEvent) {
1601            return true;
1602        }
1603
1604        @Override
1605        public boolean stopCellEditing() {
1606            value = tfFileName.getText();
1607            fireEditingStopped();
1608            return true;
1609        }
1610
1611        public void setInitialValue(String initialValue) {
1612            this.value = initialValue;
1613            this.tfFileName.setText(Objects.requireNonNullElse(initialValue, ""));
1614        }
1615
1616        @Override
1617        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
1618            setInitialValue((String) value);
1619            tfFileName.selectAll();
1620            return this;
1621        }
1622
1623        class LaunchFileChooserEditCellAction extends AbstractAction {
1624            LaunchFileChooserEditCellAction() {
1625                putValue(NAME, "...");
1626                putValue(SHORT_DESCRIPTION, tr("Launch a file chooser to select a file"));
1627            }
1628
1629            @Override
1630            public void actionPerformed(ActionEvent e) {
1631                FileChooserManager fcm = new FileChooserManager(true).createFileChooser();
1632                if (!isFile) {
1633                    fcm.getFileChooser().setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
1634                }
1635                prepareFileChooser(tfFileName.getText(), fcm.getFileChooser());
1636                AbstractFileChooser fc = fcm.openFileChooser(GuiHelper.getFrameForComponent(SourceEditor.this));
1637                if (fc != null) {
1638                    tfFileName.setText(fc.getSelectedFile().toString());
1639                }
1640            }
1641        }
1642    }
1643
1644    /**
1645     * Defers loading of sources to the first time the adequate tab is selected.
1646     * @param tab The preferences tab
1647     * @param component The tab component
1648     * @since 6670
1649     */
1650    public final void deferLoading(final DefaultTabPreferenceSetting tab, final Component component) {
1651        deferLoading(tab.getTabPane(), component);
1652    }
1653
1654    /**
1655     * Defers loading of sources to the first time the adequate tab is selected.
1656     * @param tab The tabbed pane
1657     * @param component The tab component
1658     * @since 17161
1659     */
1660    public final void deferLoading(final JTabbedPane tab, final Component component) {
1661        tab.addChangeListener(e -> {
1662            if (tab.getSelectedComponent() == component) {
1663                initiallyLoadAvailableSources();
1664            }
1665        });
1666    }
1667
1668    /**
1669     * Returns the title of the given source entry.
1670     * @param entry source entry
1671     * @return the title of the given source entry, or null if empty
1672     */
1673    protected String getTitleForSourceEntry(SourceEntry entry) {
1674        return "".equals(entry.title) ? null : entry.title;
1675    }
1676}