summaryrefslogtreecommitdiff
path: root/platform/platform-api/src/com/intellij/openapi/ui/ComboBoxTableRenderer.java
blob: c02f27af5d4b7cbbf9744387732aa623c4f8641d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.openapi.ui;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.lang.ref.WeakReference;
import java.util.EventObject;
import java.util.List;

/**
 * @author spleaner
 */
public class ComboBoxTableRenderer<T> extends JLabel implements TableCellRenderer, TableCellEditor, JBPopupListener {

  private final T[] myValues;
  private WeakReference<ListPopup> myPopupRef;
  private ChangeEvent myChangeEvent = null;
  private T myValue;
  private boolean myPaintArrow = true;

  protected EventListenerList myListenerList = new EventListenerList();

  private Runnable myFinalRunnable;

  public ComboBoxTableRenderer(final T[] values) {
    myValues = values;
    setFont(UIUtil.getButtonFont());
    setBorder(new EmptyBorder(0, 5, 0, 5));
  }

  @Override
  public Dimension getPreferredSize() {
    return addIconSize(super.getPreferredSize());
  }

  @Override
  public Dimension getMinimumSize() {
    return getPreferredSize();
  }

  private static Dimension addIconSize(final Dimension d) {
    return new Dimension(d.width + AllIcons.General.ArrowDown.getIconWidth() + 2, Math.max(d.height, AllIcons.General.ArrowDown
      .getIconHeight()));
  }

  protected String getTextFor(@NotNull T value) {
    return value.toString();
  }

  protected Icon getIconFor(@NotNull T value) {
    return null;
  }

  public void setPaintArrow(final boolean paintArrow) {
    myPaintArrow = paintArrow;
  }

  protected Runnable onChosen(@NotNull final T value) {
    stopCellEditing(value);

    return new Runnable() {
      public void run() {
        stopCellEditing(value);
      }
    };
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (!StringUtil.isEmpty(getText()) && myPaintArrow) {
      final Rectangle r = getBounds();
      final Insets i = getInsets();
      final int x = r.width - i.right - AllIcons.General.ArrowDown.getIconWidth();
      final int y = i.top + (r.height - i.top - i.bottom - AllIcons.General.ArrowDown.getIconHeight()) / 2;
      AllIcons.General.ArrowDown.paintIcon(this, g, x, y);
    }
  }

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    @SuppressWarnings("unchecked") final T t = (T)value;
    customizeComponent(t, table, isSelected);
    return this;
  }

  public Component getTableCellEditorComponent(JTable table, final Object value, boolean isSelected, final int row, final int column) {
    @SuppressWarnings("unchecked") final T t = (T)value;
    myValue = t;
    customizeComponent(t, table, isSelected);

    //noinspection SSBasedInspection
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        showPopup(t, row);
      }
    });

    return this;
  }

  protected boolean isApplicable(final T value, final int row) {
    return true;
  }

  private void showPopup(final T value, final int row) {
    List<T> filtered = ContainerUtil.findAll(myValues, new Condition<T>() {
      @Override
      public boolean value(T t) {
        return isApplicable(t, row);
      }
    });
    final ListPopup popup = JBPopupFactory.getInstance().createListPopup(new ListStep<T>(filtered, value) {
      @NotNull
      public String getTextFor(T value) {
        return ComboBoxTableRenderer.this.getTextFor(value);
      }

      @Override
      public Icon getIconFor(T value) {
        return ComboBoxTableRenderer.this.getIconFor(value);
      }

      public PopupStep onChosen(T selectedValue, boolean finalChoice) {
        myFinalRunnable = ComboBoxTableRenderer.this.onChosen(selectedValue);
        return FINAL_CHOICE;
      }

      public void canceled() {
        ComboBoxTableRenderer.this.cancelCellEditing();
      }

      public Runnable getFinalRunnable() {
        return myFinalRunnable;
      }
    });

    popup.addListener(this);
    popup.setRequestFocus(false);

    myPopupRef = new WeakReference<ListPopup>(popup);
    popup.showUnderneathOf(this);
  }

  public void beforeShown(LightweightWindowEvent event) {
  }

  public void onClosed(LightweightWindowEvent event) {
    event.asPopup().removeListener(this);
    fireEditingCanceled();
  }

  protected void customizeComponent(final T value, final JTable table, final boolean isSelected) {
    setOpaque(true);
    setText(value == null ? "" : getTextFor(value));
    if (value != null) {
      setIcon(getIconFor(value));
    }
    setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
    setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
  }

  public Object getCellEditorValue() {
    return myValue;
  }

  public boolean isCellEditable(EventObject event) {
    if (event instanceof MouseEvent) {
      return ((MouseEvent)event).getClickCount() >= 2;
    }

    return true;
  }

  public boolean shouldSelectCell(EventObject event) {
    return true;
  }

  private void stopCellEditing(final T value) {
    myValue = value;
    stopCellEditing();
  }

  public boolean stopCellEditing() {
    fireEditingStopped();
    hidePopup();
    return true;
  }

  public void cancelCellEditing() {
    fireEditingCanceled();
    hidePopup();
  }

  protected void fireEditingStopped() {
    // Guaranteed to return a non-null array
    Object[] listeners = myListenerList.getListenerList();
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == CellEditorListener.class) {
        // Lazily create the event:
        if (myChangeEvent == null) {
          myChangeEvent = new ChangeEvent(this);
        }
        ((CellEditorListener)listeners[i + 1]).editingStopped(myChangeEvent);
      }
    }
  }

  protected void fireEditingCanceled() {
    // Guaranteed to return a non-null array
    Object[] listeners = myListenerList.getListenerList();
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == CellEditorListener.class) {
        // Lazily create the event:
        if (myChangeEvent == null) {
          myChangeEvent = new ChangeEvent(this);
        }
        ((CellEditorListener)listeners[i + 1]).editingCanceled(myChangeEvent);
      }
    }
  }

  private void hidePopup() {
    if (myPopupRef != null) {
      final ListPopup popup = myPopupRef.get();
      if (popup != null && popup.isVisible()) {
        popup.cancel();
      }

      myPopupRef = null;
    }
  }

  public void addCellEditorListener(CellEditorListener l) {
    myListenerList.add(CellEditorListener.class, l);
  }

  public void removeCellEditorListener(CellEditorListener l) {
    myListenerList.remove(CellEditorListener.class, l);
  }

  private abstract static class ListStep<T> implements ListPopupStep<T> {
    private final List<T> myValues;
    private final T mySelected;

    protected ListStep(List<T> values, T selected) {
      myValues = values;
      mySelected = selected;
    }

    public String getTitle() {
      return null;
    }

    public boolean hasSubstep(T selectedValue) {
      return false;
    }

    public boolean isMnemonicsNavigationEnabled() {
      return false;
    }

    public boolean isSpeedSearchEnabled() {
      return false;
    }

    public boolean isAutoSelectionEnabled() {
      return false;
    }

    @NotNull
    public List<T> getValues() {
      return myValues;
    }

    public boolean isSelectable(T value) {
      return true;
    }

    public Icon getIconFor(T aValue) {
      return null;
    }

    public ListSeparator getSeparatorAbove(T value) {
      return null;
    }

    public int getDefaultOptionIndex() {
      return mySelected == null ? 0 : myValues.indexOf(mySelected);
    }

    public MnemonicNavigationFilter<T> getMnemonicNavigationFilter() {
      return null;
    }

    public SpeedSearchFilter<T> getSpeedSearchFilter() {
      return null;
    }
  }
}