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

Last change on this file since 5886 was 5886, checked in by Don-vip, 11 years ago

see #4429 - Right click menu "undo, cut, copy, paste, delete, select all" for each text component (originally based on patch by NooN)

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