source: osm/applications/editors/josm/plugins/wikipedia/src/org/wikipedia/WikidataTagCellRenderer.java@ 31857

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

JOSM/wikipedia: Demystify Wikidata tags - see #josm9775

File size: 2.5 KB
Line 
1package org.wikipedia;
2
3import java.awt.Component;
4import java.util.Map;
5import java.util.concurrent.Callable;
6import java.util.concurrent.ConcurrentHashMap;
7import java.util.concurrent.ExecutionException;
8import java.util.concurrent.Future;
9
10import javax.swing.JLabel;
11import javax.swing.JTable;
12import javax.swing.table.DefaultTableCellRenderer;
13
14import org.openstreetmap.josm.Main;
15import org.openstreetmap.josm.tools.LanguageInfo;
16import org.testng.internal.Utils;
17
18public 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}
Note: See TracBrowser for help on using the repository browser.