source: josm/trunk/src/org/openstreetmap/josm/gui/preferences/SourceEditor.java@ 8681

Last change on this file since 8681 was 8681, checked in by simon04, 9 years ago

see #11795 - taginfo-extract also external presets

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