001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.dialogs.properties;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005import static org.openstreetmap.josm.tools.I18n.tr;
006import static org.openstreetmap.josm.tools.I18n.trn;
007
008import java.awt.Color;
009import java.awt.Component;
010import java.awt.Font;
011import java.util.Collection;
012import java.util.Map;
013import java.util.Objects;
014import java.util.Optional;
015import java.util.concurrent.CopyOnWriteArrayList;
016
017import javax.swing.JLabel;
018import javax.swing.JTable;
019import javax.swing.UIManager;
020import javax.swing.table.DefaultTableCellRenderer;
021import javax.swing.table.TableCellRenderer;
022
023import org.openstreetmap.josm.data.osm.OsmPrimitive;
024import org.openstreetmap.josm.data.preferences.BooleanProperty;
025import org.openstreetmap.josm.data.preferences.CachingProperty;
026import org.openstreetmap.josm.data.preferences.NamedColorProperty;
027
028/**
029 * Cell renderer of tags table.
030 * @since 6314
031 */
032public class PropertiesCellRenderer extends DefaultTableCellRenderer {
033
034    private static final CachingProperty<Color> SELECTED_FG
035            = new NamedColorProperty(marktr("Discardable key: selection Foreground"), Color.GRAY).cached();
036    private static final CachingProperty<Color> SELECTED_BG;
037    private static final CachingProperty<Color> NORMAL_FG
038            = new NamedColorProperty(marktr("Discardable key: foreground"), Color.GRAY).cached();
039    private static final CachingProperty<Color> NORMAL_BG;
040    private static final CachingProperty<Boolean> DISCARDABLE
041            = new BooleanProperty("display.discardable-keys", false).cached();
042
043    static {
044        SELECTED_BG = new NamedColorProperty(marktr("Discardable key: selection Background"),
045                Optional.ofNullable(UIManager.getColor("Table.selectionBackground")).orElse(Color.BLUE)).cached();
046        NORMAL_BG = new NamedColorProperty(marktr("Discardable key: background"),
047                Optional.ofNullable(UIManager.getColor("Table.background")).orElse(Color.WHITE)).cached();
048    }
049
050    private final Collection<TableCellRenderer> customRenderer = new CopyOnWriteArrayList<>();
051
052    private static void setColors(Component c, String key, boolean isSelected) {
053
054        if (OsmPrimitive.getDiscardableKeys().contains(key)) {
055            c.setForeground((isSelected ? SELECTED_FG : NORMAL_FG).get());
056            c.setBackground((isSelected ? SELECTED_BG : NORMAL_BG).get());
057        } else {
058            c.setForeground(UIManager.getColor("Table."+(isSelected ? "selectionF" : "f")+"oreground"));
059            c.setBackground(UIManager.getColor("Table."+(isSelected ? "selectionB" : "b")+"ackground"));
060        }
061    }
062
063    @Override
064    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
065        for (TableCellRenderer renderer : customRenderer) {
066            final Component component = renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
067            if (component != null) {
068                return component;
069            }
070        }
071        if (value == null)
072            return this;
073        Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
074        if (c instanceof JLabel) {
075            String str = null;
076            if (value instanceof String) {
077                str = (String) value;
078            } else if (value instanceof Map<?, ?>) {
079                Map<?, ?> v = (Map<?, ?>) value;
080                if (v.size() != 1) {    // Multiple values: give user a short summary of the values
081                    Integer blankCount;
082                    Integer otherCount;
083                    if (v.get("") == null) {
084                        blankCount = 0;
085                        otherCount = v.size();
086                    } else {
087                        blankCount = (Integer) v.get("");
088                        otherCount = v.size()-1;
089                    }
090                    StringBuilder sb = new StringBuilder("<");
091                    if (otherCount == 1) {
092                        // Find the non-blank value in the map
093                        v.entrySet().stream().filter(entry -> !Objects.equals(entry.getKey(), ""))
094                            /* I18n: properties display partial string joined with comma, first is count, second is value */
095                            .findAny().ifPresent(entry -> sb.append(tr("{0} ''{1}''", entry.getValue().toString(), entry.getKey())));
096                    } else {
097                        /* I18n: properties display partial string joined with comma */
098                        sb.append(trn("{0} different", "{0} different", otherCount, otherCount));
099                    }
100                    if (blankCount > 0) {
101                        /* I18n: properties display partial string joined with comma */
102                        sb.append(trn(", {0} unset", ", {0} unset", blankCount, blankCount));
103                    }
104                    sb.append('>');
105                    str = sb.toString();
106                    c.setFont(c.getFont().deriveFont(Font.ITALIC));
107
108                } else {                // One value: display the value
109                    final Map.Entry<?, ?> entry = v.entrySet().iterator().next();
110                    str = (String) entry.getKey();
111                }
112            }
113            ((JLabel) c).putClientProperty("html.disable", Boolean.TRUE); // Fix #8730
114            ((JLabel) c).setText(str);
115            if (DISCARDABLE.get()) {
116                String key = null;
117                if (column == 0) {
118                    key = str;
119                } else if (column == 1) {
120                    Object value0 = table.getModel().getValueAt(row, 0);
121                    if (value0 instanceof String) {
122                        key = (String) value0;
123                    }
124                }
125                setColors(c, key, isSelected);
126            }
127        }
128        return c;
129    }
130
131    /**
132     * Adds a custom table cell renderer to render cells of the tags table.
133     *
134     * If the renderer is not capable performing a {@link TableCellRenderer#getTableCellRendererComponent},
135     * it should return {@code null} to fall back to the
136     * {@link PropertiesCellRenderer#getTableCellRendererComponent default implementation}.
137     * @param renderer the renderer to add
138     * @since 9149
139     */
140    public void addCustomRenderer(TableCellRenderer renderer) {
141        customRenderer.add(renderer);
142    }
143
144    /**
145     * Removes a custom table cell renderer.
146     * @param renderer the renderer to remove
147     * @since 9149
148     */
149    public void removeCustomRenderer(TableCellRenderer renderer) {
150        customRenderer.remove(renderer);
151    }
152}