source: josm/trunk/src/org/openstreetmap/josm/gui/tagging/ac/AutoCompletingComboBox.java@ 10102

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

fix #12720 - NPE

  • Property svn:eol-style set to native
File size: 14.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.tagging.ac;
3
4import java.awt.Component;
5import java.awt.datatransfer.Clipboard;
6import java.awt.datatransfer.Transferable;
7import java.awt.event.FocusEvent;
8import java.awt.event.FocusListener;
9import java.awt.im.InputContext;
10import java.util.Collection;
11import java.util.Locale;
12
13import javax.swing.ComboBoxEditor;
14import javax.swing.ComboBoxModel;
15import javax.swing.DefaultComboBoxModel;
16import javax.swing.JLabel;
17import javax.swing.JList;
18import javax.swing.ListCellRenderer;
19import javax.swing.text.AttributeSet;
20import javax.swing.text.BadLocationException;
21import javax.swing.text.JTextComponent;
22import javax.swing.text.PlainDocument;
23import javax.swing.text.StyleConstants;
24
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.gui.util.GuiHelper;
27import org.openstreetmap.josm.gui.widgets.JosmComboBox;
28import org.openstreetmap.josm.tools.Utils;
29
30/**
31 * Auto-completing ComboBox.
32 * @author guilhem.bonnefille@gmail.com
33 * @since 272
34 */
35public class AutoCompletingComboBox extends JosmComboBox<AutoCompletionListItem> {
36
37 private boolean autocompleteEnabled = true;
38
39 private int maxTextLength = -1;
40 private boolean useFixedLocale;
41
42 /**
43 * Auto-complete a JosmComboBox.
44 * <br>
45 * Inspired by <a href="http://www.orbital-computer.de/JComboBox">Thomas Bierhance example</a>.
46 */
47 class AutoCompletingComboBoxDocument extends PlainDocument {
48 private final JosmComboBox<AutoCompletionListItem> comboBox;
49 private boolean selecting;
50
51 /**
52 * Constructs a new {@code AutoCompletingComboBoxDocument}.
53 * @param comboBox the combobox
54 */
55 AutoCompletingComboBoxDocument(final JosmComboBox<AutoCompletionListItem> comboBox) {
56 this.comboBox = comboBox;
57 }
58
59 @Override
60 public void remove(int offs, int len) throws BadLocationException {
61 if (selecting)
62 return;
63 super.remove(offs, len);
64 }
65
66 @Override
67 public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
68 // TODO get rid of code duplication w.r.t. AutoCompletingTextField.AutoCompletionDocument.insertString
69
70 if (selecting || (offs == 0 && str.equals(getText(0, getLength()))))
71 return;
72 if (maxTextLength > -1 && str.length()+getLength() > maxTextLength)
73 return;
74 boolean initial = offs == 0 && getLength() == 0 && str.length() > 1;
75 super.insertString(offs, str, a);
76
77 // return immediately when selecting an item
78 // Note: this is done after calling super method because we need
79 // ActionListener informed
80 if (selecting)
81 return;
82 if (!autocompleteEnabled)
83 return;
84 // input method for non-latin characters (e.g. scim)
85 if (a != null && a.isDefined(StyleConstants.ComposedTextAttribute))
86 return;
87
88 // if the current offset isn't at the end of the document we don't autocomplete.
89 // If a highlighted autocompleted suffix was present and we get here Swing has
90 // already removed it from the document. getLength() therefore doesn't include the autocompleted suffix.
91 if (offs + str.length() < getLength()) {
92 return;
93 }
94
95 int size = getLength();
96 int start = offs+str.length();
97 int end = start;
98 String curText = getText(0, size);
99
100 // item for lookup and selection
101 Object item = null;
102 // if the text is a number we don't autocomplete
103 if (Main.pref.getBoolean("autocomplete.dont_complete_numbers", true)) {
104 try {
105 Long.parseLong(str);
106 if (!curText.isEmpty())
107 Long.parseLong(curText);
108 item = lookupItem(curText, true);
109 } catch (NumberFormatException e) {
110 // either the new text or the current text isn't a number. We continue with autocompletion
111 item = lookupItem(curText, false);
112 }
113 } else {
114 item = lookupItem(curText, false);
115 }
116
117 setSelectedItem(item);
118 if (initial) {
119 start = 0;
120 }
121 if (item != null) {
122 String newText = ((AutoCompletionListItem) item).getValue();
123 if (!newText.equals(curText)) {
124 selecting = true;
125 super.remove(0, size);
126 super.insertString(0, newText, a);
127 selecting = false;
128 start = size;
129 end = getLength();
130 }
131 }
132 final JTextComponent editorComponent = comboBox.getEditorComponent();
133 // save unix system selection (middle mouse paste)
134 Clipboard sysSel = GuiHelper.getSystemSelection();
135 if (sysSel != null) {
136 Transferable old = Utils.getTransferableContent(sysSel);
137 editorComponent.select(start, end);
138 if (old != null) {
139 sysSel.setContents(old, null);
140 }
141 } else {
142 editorComponent.select(start, end);
143 }
144 }
145
146 private void setSelectedItem(Object item) {
147 selecting = true;
148 comboBox.setSelectedItem(item);
149 selecting = false;
150 }
151
152 private Object lookupItem(String pattern, boolean match) {
153 ComboBoxModel<AutoCompletionListItem> model = comboBox.getModel();
154 AutoCompletionListItem bestItem = null;
155 for (int i = 0, n = model.getSize(); i < n; i++) {
156 AutoCompletionListItem currentItem = model.getElementAt(i);
157 if (currentItem.getValue().equals(pattern))
158 return currentItem;
159 if (!match && currentItem.getValue().startsWith(pattern)
160 && (bestItem == null || currentItem.getPriority().compareTo(bestItem.getPriority()) > 0)) {
161 bestItem = currentItem;
162 }
163 }
164 return bestItem; // may be null
165 }
166 }
167
168 /**
169 * Creates a <code>AutoCompletingComboBox</code> with a default prototype display value.
170 */
171 public AutoCompletingComboBox() {
172 this("Foo");
173 }
174
175 /**
176 * Creates a <code>AutoCompletingComboBox</code> with the specified prototype display value.
177 * @param prototype the <code>Object</code> used to compute the maximum number of elements to be displayed at once
178 * before displaying a scroll bar. It also affects the initial width of the combo box.
179 * @since 5520
180 */
181 public AutoCompletingComboBox(String prototype) {
182 super(new AutoCompletionListItem(prototype));
183 setRenderer(new AutoCompleteListCellRenderer());
184 final JTextComponent editorComponent = this.getEditorComponent();
185 editorComponent.setDocument(new AutoCompletingComboBoxDocument(this));
186 editorComponent.addFocusListener(
187 new FocusListener() {
188 @Override
189 public void focusLost(FocusEvent e) {
190 if (Main.map != null) {
191 Main.map.keyDetector.setEnabled(true);
192 }
193 }
194
195 @Override
196 public void focusGained(FocusEvent e) {
197 if (Main.map != null) {
198 Main.map.keyDetector.setEnabled(false);
199 }
200 // save unix system selection (middle mouse paste)
201 Clipboard sysSel = GuiHelper.getSystemSelection();
202 if (sysSel != null) {
203 Transferable old = Utils.getTransferableContent(sysSel);
204 editorComponent.selectAll();
205 sysSel.setContents(old, null);
206 } else {
207 editorComponent.selectAll();
208 }
209 }
210 }
211 );
212 }
213
214 /**
215 * Sets the maximum text length.
216 * @param length the maximum text length in number of characters
217 */
218 public void setMaxTextLength(int length) {
219 this.maxTextLength = length;
220 }
221
222 /**
223 * Convert the selected item into a String that can be edited in the editor component.
224 *
225 * @param cbEditor the editor
226 * @param item excepts AutoCompletionListItem, String and null
227 */
228 @Override
229 public void configureEditor(ComboBoxEditor cbEditor, Object item) {
230 if (item == null) {
231 cbEditor.setItem(null);
232 } else if (item instanceof String) {
233 cbEditor.setItem(item);
234 } else if (item instanceof AutoCompletionListItem) {
235 cbEditor.setItem(((AutoCompletionListItem) item).getValue());
236 } else
237 throw new IllegalArgumentException("Unsupported item: "+item);
238 }
239
240 /**
241 * Selects a given item in the ComboBox model
242 * @param item excepts AutoCompletionListItem, String and null
243 */
244 @Override
245 public void setSelectedItem(Object item) {
246 if (item == null) {
247 super.setSelectedItem(null);
248 } else if (item instanceof AutoCompletionListItem) {
249 super.setSelectedItem(item);
250 } else if (item instanceof String) {
251 String s = (String) item;
252 // find the string in the model or create a new item
253 for (int i = 0; i < getModel().getSize(); i++) {
254 AutoCompletionListItem acItem = getModel().getElementAt(i);
255 if (s.equals(acItem.getValue())) {
256 super.setSelectedItem(acItem);
257 return;
258 }
259 }
260 super.setSelectedItem(new AutoCompletionListItem(s, AutoCompletionItemPriority.UNKNOWN));
261 } else {
262 throw new IllegalArgumentException("Unsupported item: "+item);
263 }
264 }
265
266 /**
267 * Sets the items of the combobox to the given {@code String}s.
268 * @param elems String items
269 */
270 public void setPossibleItems(Collection<String> elems) {
271 DefaultComboBoxModel<AutoCompletionListItem> model = (DefaultComboBoxModel<AutoCompletionListItem>) this.getModel();
272 Object oldValue = this.getEditor().getItem(); // Do not use getSelectedItem(); (fix #8013)
273 model.removeAllElements();
274 for (String elem : elems) {
275 model.addElement(new AutoCompletionListItem(elem, AutoCompletionItemPriority.UNKNOWN));
276 }
277 // disable autocomplete to prevent unnecessary actions in AutoCompletingComboBoxDocument#insertString
278 autocompleteEnabled = false;
279 this.getEditor().setItem(oldValue); // Do not use setSelectedItem(oldValue); (fix #8013)
280 autocompleteEnabled = true;
281 }
282
283 /**
284 * Sets the items of the combobox to the given {@code AutoCompletionListItem}s.
285 * @param elems AutoCompletionListItem items
286 */
287 public void setPossibleACItems(Collection<AutoCompletionListItem> elems) {
288 DefaultComboBoxModel<AutoCompletionListItem> model = (DefaultComboBoxModel<AutoCompletionListItem>) this.getModel();
289 Object oldValue = getSelectedItem();
290 Object editorOldValue = this.getEditor().getItem();
291 model.removeAllElements();
292 for (AutoCompletionListItem elem : elems) {
293 model.addElement(elem);
294 }
295 setSelectedItem(oldValue);
296 this.getEditor().setItem(editorOldValue);
297 }
298
299 /**
300 * Determines if autocompletion is enabled.
301 * @return {@code true} if autocompletion is enabled, {@code false} otherwise.
302 */
303 public final boolean isAutocompleteEnabled() {
304 return autocompleteEnabled;
305 }
306
307 protected void setAutocompleteEnabled(boolean autocompleteEnabled) {
308 this.autocompleteEnabled = autocompleteEnabled;
309 }
310
311 /**
312 * If the locale is fixed, English keyboard layout will be used by default for this combobox
313 * all other components can still have different keyboard layout selected
314 * @param f fixed locale
315 */
316 public void setFixedLocale(boolean f) {
317 useFixedLocale = f;
318 if (useFixedLocale) {
319 Locale oldLocale = privateInputContext.getLocale();
320 Main.info("Using English input method");
321 if (!privateInputContext.selectInputMethod(new Locale("en", "US"))) {
322 // Unable to use English keyboard layout, disable the feature
323 Main.warn("Unable to use English input method");
324 useFixedLocale = false;
325 if (oldLocale != null) {
326 Main.info("Restoring input method to " + oldLocale);
327 if (!privateInputContext.selectInputMethod(oldLocale)) {
328 Main.warn("Unable to restore input method to " + oldLocale);
329 }
330 }
331 }
332 }
333 }
334
335 private final InputContext privateInputContext = InputContext.getInstance();
336
337 @Override
338 public InputContext getInputContext() {
339 if (useFixedLocale) {
340 return privateInputContext;
341 }
342 return super.getInputContext();
343 }
344
345 /**
346 * ListCellRenderer for AutoCompletingComboBox
347 * renders an AutoCompletionListItem by showing only the string value part
348 */
349 public static class AutoCompleteListCellRenderer extends JLabel implements ListCellRenderer<AutoCompletionListItem> {
350
351 /**
352 * Constructs a new {@code AutoCompleteListCellRenderer}.
353 */
354 public AutoCompleteListCellRenderer() {
355 setOpaque(true);
356 }
357
358 @Override
359 public Component getListCellRendererComponent(
360 JList<? extends AutoCompletionListItem> list,
361 AutoCompletionListItem item,
362 int index,
363 boolean isSelected,
364 boolean cellHasFocus) {
365 if (isSelected) {
366 setBackground(list.getSelectionBackground());
367 setForeground(list.getSelectionForeground());
368 } else {
369 setBackground(list.getBackground());
370 setForeground(list.getForeground());
371 }
372
373 setText(item.getValue());
374 return this;
375 }
376 }
377}
Note: See TracBrowser for help on using the repository browser.