1 | package org.wikipedia;
|
---|
2 |
|
---|
3 | import java.awt.Component;
|
---|
4 | import java.util.Map;
|
---|
5 | import java.util.concurrent.Callable;
|
---|
6 | import java.util.concurrent.ConcurrentHashMap;
|
---|
7 | import java.util.concurrent.ExecutionException;
|
---|
8 | import java.util.concurrent.Future;
|
---|
9 |
|
---|
10 | import javax.swing.JLabel;
|
---|
11 | import javax.swing.JTable;
|
---|
12 | import javax.swing.table.DefaultTableCellRenderer;
|
---|
13 |
|
---|
14 | import org.openstreetmap.josm.Main;
|
---|
15 | import org.openstreetmap.josm.tools.LanguageInfo;
|
---|
16 | import org.testng.internal.Utils;
|
---|
17 |
|
---|
18 | public class WikidataTagCellRenderer extends DefaultTableCellRenderer {
|
---|
19 |
|
---|
20 | final Map<String, Future<String>> labelCache = new ConcurrentHashMap<>();
|
---|
21 |
|
---|
22 | static class LabelLoader implements Callable<String> {
|
---|
23 | final String id;
|
---|
24 | JTable table;
|
---|
25 |
|
---|
26 | public LabelLoader(String id, JTable table) {
|
---|
27 | this.id = id;
|
---|
28 | this.table = table;
|
---|
29 | }
|
---|
30 |
|
---|
31 | @Override
|
---|
32 | public String call() throws Exception {
|
---|
33 | final String label = WikipediaApp.getLabelForWikidata(id, LanguageInfo.getJOSMLocaleCode());
|
---|
34 | table.repaint();
|
---|
35 | table = null;
|
---|
36 | return label;
|
---|
37 | }
|
---|
38 | }
|
---|
39 |
|
---|
40 | @Override
|
---|
41 | public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
|
---|
42 | if (column != 1
|
---|
43 | || !(value instanceof Map<?, ?> && ((Map<?, ?>) value).size() == 1)
|
---|
44 | || !"wikidata".equals(table.getValueAt(row, 0).toString())) {
|
---|
45 | return null;
|
---|
46 | }
|
---|
47 | final String id = ((Map<?, ?>) value).keySet().iterator().next().toString();
|
---|
48 | if (!WikipediaApp.WIKIDATA_PATTERN.matcher(id).matches()) {
|
---|
49 | return null;
|
---|
50 | }
|
---|
51 |
|
---|
52 | if (!labelCache.containsKey(id)) {
|
---|
53 | labelCache.put(id, Main.worker.submit(new LabelLoader(id, table)));
|
---|
54 | }
|
---|
55 | try {
|
---|
56 | final String label = labelCache.get(id).isDone() ? labelCache.get(id).get() : null;
|
---|
57 | final JLabel component = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
|
---|
58 | component.setText("<html>" + Utils.escapeHtml(id) + (label != null
|
---|
59 | ? " <span color='gray'>" + Utils.escapeHtml(label) + "</span>"
|
---|
60 | : ""));
|
---|
61 | component.setToolTipText(label);
|
---|
62 | return component;
|
---|
63 | } catch (InterruptedException | ExecutionException e) {
|
---|
64 | Main.warn("Could not fetch Wikidata label for " + id);
|
---|
65 | Main.warn(e);
|
---|
66 | return null;
|
---|
67 | }
|
---|
68 | }
|
---|
69 | }
|
---|