Debian Codegraph @

src/com/jidesoft/hints/AbstractIntelliHints.java

raw
1 /*
2 * @(#)AbstractIntelliHints.java 7/24/2005
3 *
4 * Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
5 */
6 package com.jidesoft.hints;
7
8 import com.jidesoft.plaf.UIDefaultsLookup;
9 import com.jidesoft.popup.JidePopup;
10 import com.jidesoft.swing.DelegateAction;
11
12 import javax.swing.*;
13 import javax.swing.event.DocumentEvent;
14 import javax.swing.event.DocumentListener;
15 import javax.swing.event.PopupMenuEvent;
16 import javax.swing.event.PopupMenuListener;
17 import javax.swing.text.BadLocationException;
18 import javax.swing.text.JTextComponent;
19 import java.awt.*;
20 import java.awt.event.*;
21 import java.util.ArrayList;
22 import java.util.List;
23
24
25 /**
26 * <code>AbstractIntelliHints</code> is an abstract implementation of {@link com.jidesoft.hints.IntelliHints}. It covers
27 * functions such as showing the hint popup at the correct position, delegating keystrokes, updating and selecting hint.
28 * The only thing that is left out to subclasses is the creation of the hint popup.
29 *
30 * @author Santhosh Kumar T
31 * @author JIDE Software, Inc.
32 */
33 public abstract class AbstractIntelliHints implements IntelliHints {
34
35 private JidePopup _popup;
36 private JTextComponent _textComponent;
37 private JComponent _hintsComponent;
38
39 private boolean _followCaret = false;
40
41 // we use this flag to workaround the bug that setText() will trigger the hint popup.
42 private boolean _keyTyped = false;
43
44 // Specifies whether the hints popup should be displayed automatically.
45 // Default is true for backward compatibility.
46 private boolean _autoPopup = true;
47 private int _showHintsDelay = 200;
48 private List<KeyStroke> _showHintsKeyStrokes;
49 private DelegateAction _showAction;
50
51 /**
52 * Creates an IntelliHints object for a given JTextComponent.
53 *
54 * @param textComponent the text component.
55 */
56 public AbstractIntelliHints(JTextComponent textComponent) {
57 _textComponent = textComponent;
58 getTextComponent().putClientProperty(CLIENT_PROPERTY_INTELLI_HINTS, this);
59
60 _popup = createPopup();
61
62 getTextComponent().getDocument().addDocumentListener(documentListener);
63 getTextComponent().addKeyListener(new KeyListener() {
64 public void keyTyped(KeyEvent e) {
65 }
66
67 public void keyPressed(KeyEvent e) {
68 }
69
70 public void keyReleased(KeyEvent e) {
71 if (KeyEvent.VK_ESCAPE != e.getKeyCode() && KeyEvent.VK_ENTER != e.getKeyCode()) {
72 setKeyTyped(true);
73 }
74 }
75 });
76 getTextComponent().addFocusListener(new FocusListener() {
77 public void focusGained(FocusEvent e) {
78 }
79
80 public void focusLost(FocusEvent e) {
81 Container topLevelAncestor = _popup.getTopLevelAncestor();
82 if (topLevelAncestor == null) {
83 return;
84 }
85 Component oppositeComponent = e.getOppositeComponent();
86 if (topLevelAncestor == oppositeComponent || topLevelAncestor.isAncestorOf(oppositeComponent)) {
87 return;
88 }
89 hideHintsPopup();
90 }
91 });
92
93 _showAction = new DelegateAction() {
94 private static final long serialVersionUID = 2243999895981912016L;
95
96 @Override
97 public boolean delegateActionPerformed(ActionEvent e) {
98 JComponent tf = (JComponent) e.getSource();
99 IntelliHints hints = getIntelliHints(tf);
100 if (hints instanceof AbstractIntelliHints) {
101 AbstractIntelliHints aih = (AbstractIntelliHints) hints;
102 if (tf.isEnabled() && !aih.isHintsPopupVisible()) {
103 aih.showHintsPopup(false);
104 return true;
105 }
106 }
107 return false;
108 }
109
110 @Override
111 public boolean isDelegateEnabled() {
112 return !isHintsPopupVisible();
113 }
114 };
115 addShowHintsKeyStroke(getShowHintsKeyStroke());
116
117 KeyStroke[] keyStrokes = getDelegateKeyStrokes();
118 for (KeyStroke keyStroke : keyStrokes) {
119 DelegateAction.replaceAction(getTextComponent(), JComponent.WHEN_FOCUSED, keyStroke, new LazyDelegateAction(keyStroke));
120 }
121 }
122
123 protected JidePopup createPopup() {
124 JidePopup popup = com.jidesoft.popup.JidePopupFactory.getSharedInstance().createPopup();
125 popup.setLayout(new BorderLayout());
126 popup.setResizable(true);
127 popup.setPopupBorder(BorderFactory.createLineBorder(UIDefaultsLookup.getColor("controlDkShadow"), 1));
128 popup.setMovable(false);
129 popup.addPopupMenuListener(new PopupMenuListener() {
130 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
131 }
132
133 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
134 DelegateAction.restoreAction(getTextComponent(), JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), hideAction);
135 DelegateAction.restoreAction(getTextComponent(), JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), acceptAction);
136 }
137
138 public void popupMenuCanceled(PopupMenuEvent e) {
139 }
140 });
141 popup.setTransient(true);
142 popup.setKeepPreviousSize(false);
143 popup.setReturnFocusToOwner(false);
144 return popup;
145 }
146
147 public JTextComponent getTextComponent() {
148 return _textComponent;
149 }
150
151
152 /**
153 * After user has selected a item in the hints popup, this method will update JTextComponent accordingly to accept
154 * the hint.
155 * <p/>
156 * For JTextArea, the default implementation will insert the hint into current caret position. For JTextField, by
157 * default it will replace the whole content with the item user selected. Subclass can always choose to override it
158 * to accept the hint in a different way. For example, {@link com.jidesoft.hints.FileIntelliHints} will append the
159 * selected item at the end of the existing text in order to complete a full file path.
160 */
161 public void acceptHint(Object selected) {
162 if (selected == null)
163 return;
164
165 String newText;
166 int pos = getTextComponent().getCaretPosition();
167 if (isMultilineTextComponent()) {
168 String text = getTextComponent().getText();
169 int start = text.lastIndexOf('\n', pos - 1);
170 String remain = pos == -1 ? "" : text.substring(pos);
171 text = text.substring(0, start + 1);
172 text += selected;
173 text += remain;
174 newText = text;
175 }
176 else {
177 newText = selected.toString();
178 }
179
180 getTextComponent().setText(newText);
181 // DocumentFilters in JTextComponent's document model may alter the
182 // provided text. The line separator has to be searched in the actual text
183 String actualText = getTextComponent().getText();
184 int separatorIndex = actualText.indexOf('\n', pos);
185 getTextComponent().setCaretPosition(
186 separatorIndex == -1 ? actualText.length() : separatorIndex);
187 }
188
189 /**
190 * Returns whether this IntelliHints' <code>JTextComponent</code> supports single-line text or multi-line text.
191 *
192 * @return <code>true</code> if the component supports multiple text lines, <code>false</code> otherwise
193 */
194 protected boolean isMultilineTextComponent() {
195 return getTextComponent() instanceof JTextArea ||
196 getTextComponent() instanceof JEditorPane;
197 }
198
199 /**
200 * This method will call {@link #showHints(boolean)} if and only if the text component is enabled and has focus.
201 *
202 * @param autoPopup
203 */
204 protected void showHintsPopup(boolean autoPopup) {
205 if (!getTextComponent().isEnabled() || !getTextComponent().isEditable() || !getTextComponent().hasFocus()) {
206 return;
207 }
208 showHints(autoPopup);
209 }
210
211 @Override
212 public boolean updateHints(Object context) {
213 return false;
214 }
215
216 @Override
217 public boolean updateHints(Object context, boolean autoPopup) {
218 return updateHints(context);
219 }
220
221 /**
222 * Shows the hints popup which contains the hints. It will call {@link #updateHints(Object, boolean)}. Only if it returns
223 * true, the popup will be shown. You can call this method to fore the hints to be displayed.
224 *
225 * @param autoPopup
226 */
227 public void showHints(boolean autoPopup) {
228 if (_popup == null) {
229 return;
230 }
231 if (_hintsComponent == null) {
232 _hintsComponent = createHintsComponent();
233 _popup.add(_hintsComponent);
234 getDelegateComponent().setRequestFocusEnabled(false);
235 getDelegateComponent().addMouseListener(new MouseAdapter() {
236 @Override
237 public void mouseClicked(MouseEvent e) {
238 hideHintsPopup();
239 setHintsEnabled(false);
240 acceptHint(getSelectedHint());
241 setHintsEnabled(true);
242 }
243 });
244 }
245 if (updateHints(getContext(), autoPopup)) {
246 if (!isHintsPopupVisible()) {
247 DelegateAction.replaceAction(getTextComponent(), JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), hideAction);
248 DelegateAction.replaceAction(getTextComponent(), JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), acceptAction, true);
249 }
250
251 int x = 0;
252 int y = 0;
253 int height = 0;
254
255 try {
256 int pos = getCaretPositionForPopup();
257 Rectangle position = getCaretRectangleForPopup(pos);
258 y = position.y;
259 x = position.x;
260 height = position.height;
261 }
262 catch (BadLocationException e) {
263 // this should never happen!!!
264 }
265
266 _popup.setOwner(getTextComponent());
267 _popup.showPopup(new Insets(y, x, getTextComponent().getHeight() - height - y, 0));
268 }
269 else {
270 _popup.hidePopup();
271 }
272 }
273
274 /**
275 * Gets the caret rectangle where caret is displayed. The popup will be show around the area so that the returned
276 * rectangle area is always visible. This method will be called twice.
277 *
278 * @param caretPosition the caret position.
279 *
280 * @return the popup position relative to the text component. <br>Please note, this position is actually a rectangle
281 * area. The reason is the popup could be shown below or above the rectangle. Usually, the popup will be shown below
282 * the rectangle. In this case, the x and y of the rectangle will be the top-left corner of the popup. However if
283 * there isn't enough space for the popup because it's close to screen bottom border, we will show the popup above
284 * the rectangle. In this case, the bottom-left corner of the popup will be at x and (y - height). Simply speaking,
285 * the popup will never cover the area specified by the rectangle (either below it or above it).
286 *
287 * @throws BadLocationException if the given position does not represent a valid location in the associated
288 * document.
289 */
290 protected Rectangle getCaretRectangleForPopup(int caretPosition) throws BadLocationException {
291 return getTextComponent().getUI().modelToView(getTextComponent(), caretPosition);
292 }
293
294
295 /**
296 * Gets the caret position which is used as the anchor point to display the popup. By default, it {@link
297 * #isFollowCaret()} is true, it will return caret position. Otherwise it will return the caret position at the
298 * beginning of the caret line. Subclass can override to return any caret position.
299 *
300 * @return the caret position which is used as the anchor point to display the popup.
301 */
302 protected int getCaretPositionForPopup() {
303 int caretPosition = Math.min(getTextComponent().getCaret().getDot(), getTextComponent().getCaret().getMark());
304 if (isFollowCaret()) {
305 return caretPosition;
306 }
307 else {
308 try {
309 Rectangle viewRect = getTextComponent().getUI().modelToView(getTextComponent(), caretPosition);
310 viewRect.x = 0;
311 return getTextComponent().getUI().viewToModel(getTextComponent(), viewRect.getLocation());
312 }
313 catch (BadLocationException e) {
314 return 0;
315 }
316 }
317 }
318
319 /**
320 * Gets the context for hints. The context is the information that IntelliHints needs in order to generate a list of
321 * hints. For example, for code-completion, the context is current word the cursor is on. for file completion, the
322 * context is the full string starting from the file system root. <p>We provide a default context in
323 * AbstractIntelliHints. If it's a JTextArea, the context will be the string at the caret line from line beginning
324 * to the caret position. If it's a JTextField, the context will be whatever string in the text field. Subclass can
325 * always override it to return the context that is appropriate.
326 *
327 * @return the context.
328 */
329 protected Object getContext() {
330 if (isMultilineTextComponent()) {
331 int pos = getTextComponent().getCaretPosition();
332 if (pos == 0) {
333 return "";
334 }
335 else {
336 String text = getTextComponent().getText();
337 int start = text.lastIndexOf('\n', pos - 1);
338 return text.substring(start + 1, pos);
339 }
340 }
341 else {
342 return getTextComponent().getText();
343 }
344 }
345
346 /**
347 * Hides the hints popup.
348 */
349 protected void hideHintsPopup() {
350 if (_popup != null) {
351 _popup.hidePopup();
352 }
353 setKeyTyped(false);
354 }
355
356 /**
357 * Enables or disables the hints popup.
358 *
359 * @param enabled true to enable the hints popup. Otherwise false.
360 */
361 public void setHintsEnabled(boolean enabled) {
362 if (!enabled) {
363 // disable show hint temporarily
364 getTextComponent().getDocument().removeDocumentListener(documentListener);
365 }
366 else {
367 // enable show hint again
368 getTextComponent().getDocument().addDocumentListener(documentListener);
369 }
370
371 }
372
373 /**
374 * Checks if the hints popup is visible.
375 *
376 * @return true if it's visible. Otherwise, false.
377 */
378 public boolean isHintsPopupVisible() {
379 return _popup != null && _popup.isPopupVisible();
380 }
381
382 /**
383 * Should the hints popup follows the caret.
384 *
385 * @return true if the popup shows up right below the caret. False if the popup always shows at the bottom-left
386 * corner (or top-left if there isn't enough on the bottom of the screen) of the JTextComponent.
387 */
388 public boolean isFollowCaret() {
389 return _followCaret;
390 }
391
392 /**
393 * Sets the position of the hints popup. If followCaret is true, the popup shows up right below the caret.
394 * Otherwise, it will stay at the bottom-left corner (or top-left if there isn't enough on the bottom of the screen)
395 * of JTextComponent.
396 *
397 * @param followCaret true or false.
398 */
399 public void setFollowCaret(boolean followCaret) {
400 _followCaret = followCaret;
401 }
402
403 /**
404 * Returns whether the hints popup is automatically displayed. Default is true
405 *
406 * @return true if the popup should be automatically displayed. False will never show it automatically and then need
407 * the user to manually activate it via the getShowHintsKeyStroke() key binding.
408 *
409 * @see #setAutoPopup(boolean)
410 */
411 public boolean isAutoPopup() {
412 return _autoPopup;
413 }
414
415 /**
416 * Sets whether the popup should be displayed automatically. If autoPopup is true then is the popup automatically
417 * displayed whenever updateHints() return true. If autoPopup is false it's not automatically displayed and will
418 * need the user to activate the key binding defined by getShowHintsKeyStroke().
419 *
420 * @param autoPopup true or false
421 */
422 public void setAutoPopup(boolean autoPopup) {
423 this._autoPopup = autoPopup;
424 }
425
426 /**
427 * Gets the delegate keystrokes.
428 * <p/>
429 * When hint popup is visible, the keyboard focus never leaves the text component. However the hint popup usually
430 * contains a component that user will try to use navigation key to select an item. For example, use UP and DOWN key
431 * to navigate the list. Those keystrokes, if the popup is visible, will be delegated to the the component that
432 * returns from {@link #getDelegateComponent()}.
433 * <p/>
434 * NOTE: Since this method would be invoked inside the constructor of AbstractIntelliHints, please do not try to
435 * return a field because the field is not initiated yet at this time.
436 *
437 * @return an array of keystrokes that will be delegate to {@link #getDelegateComponent()} when hint popup is shown.
438 */
439 abstract protected KeyStroke[] getDelegateKeyStrokes();
440
441 /**
442 * Gets the delegate component in the hint popup.
443 *
444 * @return the component that will receive the keystrokes that are delegated to hint popup.
445 */
446 abstract protected JComponent getDelegateComponent();
447
448 /**
449 * Gets the keystroke that will trigger the hint popup. Usually the hints popup will be shown automatically when
450 * user types. Only when the hint popup is hidden accidentally, this keystroke will show the popup again.
451 * <p/>
452 * By default, it's the DOWN key for JTextField and CTRL+SPACE for JTextArea.
453 *
454 * @return the keystroke that will trigger the hint popup.
455 */
456 protected KeyStroke getShowHintsKeyStroke() {
457 if (isMultilineTextComponent()) {
458 return KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, KeyEvent.CTRL_MASK);
459 }
460 else {
461 return KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
462 }
463 }
464
465 private DelegateAction acceptAction = new DelegateAction() {
466 private static final long serialVersionUID = -2516216121942080133L;
467
468 @Override
469 public boolean isDelegateEnabled() {
470 return isHintsPopupVisible() && getSelectedHint() != null;
471 }
472
473 @Override
474 public boolean delegateActionPerformed(ActionEvent e) {
475 JComponent tf = (JComponent) e.getSource();
476 IntelliHints hints = getIntelliHints(tf);
477 if (hints instanceof AbstractIntelliHints) {
478 AbstractIntelliHints aih = (AbstractIntelliHints) hints;
479 aih.hideHintsPopup();
480 if (aih.getSelectedHint() != null) {
481 aih.setHintsEnabled(false);
482 aih.acceptHint(hints.getSelectedHint());
483 aih.setHintsEnabled(true);
484 return true;
485 }
486 }
487 return false;
488 }
489 };
490
491 private DelegateAction hideAction = new DelegateAction() {
492 private static final long serialVersionUID = 1921213578011852535L;
493
494 @Override
495 public boolean isDelegateEnabled() {
496 return _textComponent.isEnabled() && isHintsPopupVisible();
497 }
498
499 @Override
500 public boolean delegateActionPerformed(ActionEvent e) {
501 if (isEnabled()) {
502 hideHintsPopup();
503 return true;
504 }
505 return false;
506 }
507 };
508
509 private DocumentListener documentListener = new DocumentListener() {
510 private Timer timer = new Timer(getShowHintsDelay(), new ActionListener() {
511 public void actionPerformed(ActionEvent e) {
512 if (isKeyTyped()) {
513 if (isHintsPopupVisible() || isAutoPopup()) {
514 showHintsPopup(true);
515 }
516 setKeyTyped(false);
517 }
518 }
519 });
520
521 public void insertUpdate(DocumentEvent e) {
522 startTimer();
523 }
524
525 public void removeUpdate(DocumentEvent e) {
526 startTimer();
527 }
528
529 public void changedUpdate(DocumentEvent e) {
530 }
531
532 void startTimer() {
533 if (timer.isRunning()) {
534 timer.setInitialDelay(getShowHintsDelay());
535 timer.setDelay(getShowHintsDelay());
536 timer.restart();
537 }
538 else {
539 timer.setRepeats(false);
540 timer.setInitialDelay(getShowHintsDelay());
541 timer.setDelay(getShowHintsDelay());
542 timer.start();
543 }
544 }
545 };
546
547 private boolean isKeyTyped() {
548 return _keyTyped;
549 }
550
551 private void setKeyTyped(boolean keyTyped) {
552 _keyTyped = keyTyped;
553 }
554
555 /**
556 * Gets the delay after the key is pressed to show hints.
557 *
558 * @return the delay time on milliseconds.
559 *
560 * @see #setShowHintsDelay(int)
561 */
562 public int getShowHintsDelay() {
563 return _showHintsDelay;
564 }
565
566 /**
567 * Sets the delay after the key is pressed to show hints.
568 * <p/>
569 * By default, the delay time is 200ms.
570 *
571 * @param showHintsDelay the delay time
572 */
573 public void setShowHintsDelay(int showHintsDelay) {
574 _showHintsDelay = showHintsDelay;
575 }
576
577 /**
578 * Adds a new key stroke to show hints popup.
579 *
580 * @param keyStroke the key stroke
581 *
582 * @see #removeShowHintsKeyStroke(javax.swing.KeyStroke)
583 * @see #getAllShowHintsKeyStrokes()
584 * @since 3.2.2
585 */
586 public void addShowHintsKeyStroke(KeyStroke keyStroke) {
587 if (_showHintsKeyStrokes == null) {
588 _showHintsKeyStrokes = new ArrayList<KeyStroke>();
589 }
590 _showHintsKeyStrokes.add(keyStroke);
591 DelegateAction.replaceAction(getTextComponent(), JComponent.WHEN_FOCUSED, keyStroke, _showAction);
592 }
593
594 /**
595 * Removes a key stroke from the list to show hints popup.
596 *
597 * @param keyStroke the key stroke
598 *
599 * @since 3.2.2
600 */
601 public void removeShowHintsKeyStroke(KeyStroke keyStroke) {
602 if (_showHintsKeyStrokes != null) {
603 _showHintsKeyStrokes.remove(keyStroke);
604 DelegateAction.restoreAction(getTextComponent(), JComponent.WHEN_FOCUSED, keyStroke, _showAction);
605 }
606 }
607
608 /**
609 * Gets all key strokes that will show hints popup.
610 *
611 * @return the key stroke array.
612 *
613 * @since 3.2.2
614 */
615 public KeyStroke[] getAllShowHintsKeyStrokes() {
616 if (_showHintsKeyStrokes == null) {
617 return new KeyStroke[0];
618 }
619 return _showHintsKeyStrokes.toArray(new KeyStroke[_showHintsKeyStrokes.size()]);
620 }
621
622 private class LazyDelegateAction extends DelegateAction {
623 private KeyStroke _keyStroke;
624 private static final long serialVersionUID = -5799290233797844786L;
625
626 public LazyDelegateAction(KeyStroke keyStroke) {
627 _keyStroke = keyStroke;
628 }
629
630 @Override
631 public boolean isDelegateEnabled() {
632 Action action = getHintsPopupAction();
633 return action != null && action.isEnabled();
634 }
635
636 private Action getHintsPopupAction() {
637 if (isHintsPopupVisible() && getDelegateComponent() != null) {
638 Object key = getDelegateComponent().getInputMap().get(_keyStroke);
639 key = key == null ? getTextComponent().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).get(_keyStroke) : key;
640 if (key != null) {
641 return getDelegateComponent().getActionMap().get(key);
642 }
643 }
644 return null;
645 }
646
647 @Override
648 public boolean delegateActionPerformed(ActionEvent e) {
649 JComponent tf = (JComponent) e.getSource();
650 IntelliHints hints = getIntelliHints(tf);
651 if (hints instanceof AbstractIntelliHints) {
652 AbstractIntelliHints aih = (AbstractIntelliHints) hints;
653 if (tf.isEnabled()) {
654 if (aih.isHintsPopupVisible()) {
655 Object key = aih.getDelegateComponent().getInputMap().get(_keyStroke);
656 key = key == null ? aih.getTextComponent().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).get(_keyStroke) : key;
657 if (key != null) {
658 Object action = aih.getDelegateComponent().getActionMap().get(key);
659 if (action instanceof Action) {
660 ((Action) action).actionPerformed(new ActionEvent(aih.getDelegateComponent(), 0, "" + key));
661 return true;
662 }
663 }
664 }
665 }
666 }
667 return false;
668 }
669 }
670
671 /**
672 * Gets the IntelliHints object if it was installed on the component before.
673 *
674 * @param component the component that has IntelliHints installed
675 *
676 * @return the IntelliHints.
677 */
678 public static IntelliHints getIntelliHints(JComponent component) {
679 return (IntelliHints) component.getClientProperty(CLIENT_PROPERTY_INTELLI_HINTS);
680 }
681 }