You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InputHandler.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /*
  2. * Copyright (c) 2006-2011 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.ui.input;
  23. import com.dmdirc.WritableFrameContainer;
  24. import com.dmdirc.actions.ActionManager;
  25. import com.dmdirc.actions.CoreActionType;
  26. import com.dmdirc.commandparser.CommandArguments;
  27. import com.dmdirc.commandparser.CommandInfo;
  28. import com.dmdirc.commandparser.CommandManager;
  29. import com.dmdirc.commandparser.commands.Command;
  30. import com.dmdirc.commandparser.commands.ValidatingCommand;
  31. import com.dmdirc.commandparser.commands.WrappableCommand;
  32. import com.dmdirc.commandparser.parsers.CommandParser;
  33. import com.dmdirc.interfaces.ConfigChangeListener;
  34. import com.dmdirc.parser.common.CompositionState;
  35. import com.dmdirc.plugins.PluginManager;
  36. import com.dmdirc.ui.input.tabstyles.TabCompletionResult;
  37. import com.dmdirc.ui.input.tabstyles.TabCompletionStyle;
  38. import com.dmdirc.interfaces.ui.InputField;
  39. import com.dmdirc.interfaces.ui.InputValidationListener;
  40. import com.dmdirc.ui.messages.Styliser;
  41. import com.dmdirc.util.collections.ListenerList;
  42. import com.dmdirc.util.collections.RollingList;
  43. import com.dmdirc.util.validators.ValidationResponse;
  44. import java.awt.Toolkit;
  45. import java.awt.event.KeyEvent;
  46. import java.util.ArrayList;
  47. import java.util.List;
  48. import java.util.Map;
  49. import java.util.Timer;
  50. import java.util.TimerTask;
  51. import java.util.logging.Level;
  52. /**
  53. * Handles events generated by a user typing into a textfield. Allows the user
  54. * to use shortcut keys for control characters (ctrl+b, etc), to tab complete
  55. * nicknames/channel names/etc, and to scroll through their previously issued
  56. * commands.
  57. */
  58. public abstract class InputHandler implements ConfigChangeListener {
  59. /**
  60. * Indicates that the caret should be moved to the start of a selection when
  61. * a control code has been inserted.
  62. */
  63. protected static final int POSITION_START = 2;
  64. /** Flag to indicate that this input handler should handle tab completion. */
  65. protected static final int HANDLE_TABCOMPLETION = 1;
  66. /** Flag to indicate that this input handler should maintain a back buffer. */
  67. protected static final int HANDLE_BACKBUFFER = 2;
  68. /** Flag to indicate that this input handler should handle formatting. */
  69. protected static final int HANDLE_FORMATTING = 4;
  70. /** Flag to indicate that this input handler should handle returns. */
  71. protected static final int HANDLE_RETURN = 8;
  72. /**
  73. * Time in milliseconds after which we switch from "typing" to"text entered"
  74. * composing states.
  75. */
  76. private static final int TYPING_TIMEOUT = 5000;
  77. /**
  78. * Indicates that the caret should be moved to the end of a selection when
  79. * a control code has been inserted.
  80. */
  81. private static final int POSITION_END = 1;
  82. /** A logger for this class. */
  83. private static final java.util.logging.Logger LOGGER = java.util.logging
  84. .Logger.getLogger(InputHandler.class.getName());
  85. /** The flags for this particular input handler. */
  86. protected int flags = HANDLE_TABCOMPLETION | HANDLE_BACKBUFFER
  87. | HANDLE_FORMATTING | HANDLE_RETURN;
  88. /** The input buffer. */
  89. protected RollingList<String> buffer;
  90. /** The textfield that we're handling input for. */
  91. protected final InputField target;
  92. /** The TabCompleter to use for tab completion. */
  93. protected TabCompleter tabCompleter;
  94. /** The CommandParser to use for our input. */
  95. protected final CommandParser commandParser;
  96. /** The frame that we belong to. */
  97. protected final WritableFrameContainer parentWindow;
  98. /** The tab completion style. */
  99. protected TabCompletionStyle style;
  100. /** Our listener list. */
  101. private final ListenerList listeners = new ListenerList();
  102. /** The current composition state. */
  103. private CompositionState state = CompositionState.IDLE;
  104. /** Timer used to manage timeouts of composition state. */
  105. private Timer compositionTimer;
  106. /**
  107. * Creates a new instance of InputHandler. Adds listeners to the target
  108. * that we need to operate.
  109. *
  110. * @param thisTarget The text field this input handler is dealing with.
  111. * @param thisCommandParser The command parser to use for this text field.
  112. * @param thisParentWindow The window that owns this input handler
  113. */
  114. public InputHandler(final InputField thisTarget,
  115. final CommandParser thisCommandParser,
  116. final WritableFrameContainer thisParentWindow) {
  117. buffer = new RollingList<String>(thisParentWindow.getConfigManager()
  118. .getOptionInt("ui", "inputbuffersize"), "");
  119. this.commandParser = thisCommandParser;
  120. this.parentWindow = thisParentWindow;
  121. this.target = thisTarget;
  122. setStyle();
  123. parentWindow.getConfigManager().addChangeListener(
  124. "tabcompletion", "style", this);
  125. addUpHandler();
  126. addDownHandler();
  127. addTabHandler();
  128. addKeyHandler();
  129. addEnterHandler();
  130. }
  131. /**
  132. * Adds an arrow up key handler.
  133. */
  134. protected abstract void addUpHandler();
  135. /**
  136. * Adds an arrow down key handler.
  137. */
  138. protected abstract void addDownHandler();
  139. /**
  140. * Adds an tab key handler.
  141. */
  142. protected abstract void addTabHandler();
  143. /**
  144. * Adds a key handler.
  145. */
  146. protected abstract void addKeyHandler();
  147. /**
  148. * Adds an enter key handler.
  149. */
  150. protected abstract void addEnterHandler();
  151. /**
  152. * Indicates which types of input this handler should handle.
  153. *
  154. * @param handleTabCompletion Whether or not to handle tab completion
  155. * @param handleBackBuffer Whether or not to maintain an input back buffer
  156. * @param handleFormatting Whether or not to handle formatting
  157. * @param handleReturn Whether or not to handle returns
  158. */
  159. public void setTypes(final boolean handleTabCompletion,
  160. final boolean handleBackBuffer,
  161. final boolean handleFormatting, final boolean handleReturn) {
  162. flags = (handleTabCompletion ? HANDLE_TABCOMPLETION : 0)
  163. | (handleBackBuffer ? HANDLE_BACKBUFFER : 0)
  164. | (handleFormatting ? HANDLE_FORMATTING : 0)
  165. | (handleReturn ? HANDLE_RETURN : 0);
  166. }
  167. /**
  168. * Sets this inputhandler's tab completion style.
  169. */
  170. private void setStyle() {
  171. style = (TabCompletionStyle) PluginManager.getPluginManager()
  172. .getServiceProvider("tabcompletion", parentWindow
  173. .getConfigManager().getOption("tabcompletion", "style"))
  174. .getExportedService("getCompletionStyle").execute(tabCompleter,
  175. parentWindow);
  176. }
  177. /**
  178. * Sets this input handler's tab completer.
  179. *
  180. * @param newTabCompleter The new tab completer
  181. */
  182. public void setTabCompleter(final TabCompleter newTabCompleter) {
  183. tabCompleter = newTabCompleter;
  184. setStyle();
  185. }
  186. /**
  187. * Handles the pressing of a key. Inserts control chars as appropriate.
  188. *
  189. * @param line Text in the target
  190. * @param keyCode Keycode for the pressed key
  191. * @param shiftPressed Was shift pressed
  192. * @param ctrlPressed Was ctrl key pressed
  193. */
  194. protected void handleKeyPressed(final String line, final int keyCode,
  195. final boolean shiftPressed, final boolean ctrlPressed) {
  196. target.hideColourPicker();
  197. if (keyCode == KeyEvent.VK_COMMA) {
  198. // Reshow the colour picker dialog if the user follows a colour
  199. // or control code with a comma (so they can pick a background)
  200. final String partialLine = line.substring(0, target.getCaretPosition() - 1);
  201. if (partialLine.matches("^.*" + Styliser.CODE_COLOUR + "[0-9]{0,2}$")) {
  202. target.showColourPicker(true, false);
  203. } else if (partialLine.matches("^.*" + Styliser.CODE_HEXCOLOUR + "[0-9A-Z]{6}?$")) {
  204. target.showColourPicker(false, true);
  205. }
  206. }
  207. if (ctrlPressed && (flags & HANDLE_FORMATTING) != 0) {
  208. handleControlKey(line, keyCode, shiftPressed);
  209. }
  210. if (target.getText().isEmpty()) {
  211. cancelTypingNotification();
  212. } else {
  213. updateTypingNotification();
  214. }
  215. validateText();
  216. }
  217. /**
  218. * Validates the text currently entered in the text field.
  219. */
  220. protected void validateText() {
  221. final String text = target.getText();
  222. final CommandArguments args = new CommandArguments(text);
  223. if (args.isCommand()) {
  224. final Map.Entry<CommandInfo, Command> command
  225. = CommandManager.getCommandManager().getCommand(args.getCommandName());
  226. if (command != null && command.getValue() instanceof ValidatingCommand) {
  227. final ValidationResponse vr = ((ValidatingCommand) command.getValue())
  228. .validateArguments(parentWindow, args);
  229. if (vr.isFailure()) {
  230. fireCommandFailure(vr.getFailureReason());
  231. } else {
  232. fireCommandPassed();
  233. }
  234. }
  235. if (command != null && command.getValue() instanceof WrappableCommand) {
  236. final int count = ((WrappableCommand) command.getValue())
  237. .getLineCount(parentWindow, args);
  238. fireLineWrap(count);
  239. }
  240. } else {
  241. final int lines = parentWindow.getNumLines(text);
  242. fireLineWrap(lines);
  243. }
  244. }
  245. /** Resets the composition state to idle and notifies the parent if relevant. */
  246. private void cancelTypingNotification() {
  247. setCompositionState(CompositionState.IDLE);
  248. }
  249. /** Updates the composition state to typing and starts/resets the idle timer. */
  250. private void updateTypingNotification() {
  251. if (compositionTimer != null) {
  252. compositionTimer.cancel();
  253. }
  254. compositionTimer = new Timer("Composition state timer");
  255. compositionTimer.schedule(new TimerTask() {
  256. /** {@inheritDoc} */
  257. @Override
  258. public void run() {
  259. timeoutTypingNotification();
  260. }
  261. }, TYPING_TIMEOUT);
  262. setCompositionState(CompositionState.TYPING);
  263. }
  264. /** Updates the composition state to "entered text". */
  265. private void timeoutTypingNotification() {
  266. setCompositionState(CompositionState.ENTERED_TEXT);
  267. }
  268. /**
  269. * Sets the composition state to the specified one. If the state has
  270. * changed, the parent window is notified of the new state.
  271. *
  272. * @param newState The new composition state
  273. */
  274. private void setCompositionState(final CompositionState newState) {
  275. if (state != newState) {
  276. state = newState;
  277. if (parentWindow != null) {
  278. parentWindow.setCompositionState(state);
  279. }
  280. }
  281. }
  282. /**
  283. * Fires the "illegalCommand" method of all validation listeners.
  284. *
  285. * @param reason The reason for the command failure
  286. */
  287. private void fireCommandFailure(final String reason) {
  288. for (InputValidationListener listener : listeners.get(InputValidationListener.class)) {
  289. listener.illegalCommand(reason);
  290. }
  291. }
  292. /**
  293. * Fires the "legalCommand" method of all validation listeners.
  294. */
  295. private void fireCommandPassed() {
  296. for (InputValidationListener listener : listeners.get(InputValidationListener.class)) {
  297. listener.legalCommand();
  298. }
  299. }
  300. /**
  301. * Fires the "wrappedText" method of all validation listeners.
  302. *
  303. * @param lines The number of lines that the text will wrap to
  304. */
  305. private void fireLineWrap(final int lines) {
  306. for (InputValidationListener listener : listeners.get(InputValidationListener.class)) {
  307. listener.wrappedText(lines);
  308. }
  309. }
  310. /**
  311. * Adds an InputValidationListener to this input handler.
  312. *
  313. * @param listener The listener to be added
  314. */
  315. public void addValidationListener(final InputValidationListener listener) {
  316. listeners.add(InputValidationListener.class, listener);
  317. }
  318. /**
  319. * Handles the pressing of a key while the control key is pressed.
  320. * Inserts control chars as appropriate.
  321. *
  322. * @param line Text in the target
  323. * @param keyCode Keycode for the pressed key
  324. * @param shiftPressed Was shift pressed
  325. */
  326. protected void handleControlKey(final String line, final int keyCode,
  327. final boolean shiftPressed) {
  328. switch (keyCode) {
  329. case KeyEvent.VK_B:
  330. addControlCode(Styliser.CODE_BOLD, POSITION_END);
  331. break;
  332. case KeyEvent.VK_U:
  333. addControlCode(Styliser.CODE_UNDERLINE, POSITION_END);
  334. break;
  335. case KeyEvent.VK_O:
  336. addControlCode(Styliser.CODE_STOP, POSITION_END);
  337. break;
  338. case KeyEvent.VK_I:
  339. addControlCode(Styliser.CODE_ITALIC, POSITION_END);
  340. break;
  341. case KeyEvent.VK_F:
  342. if (shiftPressed) {
  343. addControlCode(Styliser.CODE_FIXED, POSITION_END);
  344. }
  345. break;
  346. case KeyEvent.VK_K:
  347. if (shiftPressed) {
  348. addControlCode(Styliser.CODE_HEXCOLOUR, POSITION_START);
  349. target.showColourPicker(false, true);
  350. } else {
  351. addControlCode(Styliser.CODE_COLOUR, POSITION_START);
  352. target.showColourPicker(true, false);
  353. }
  354. break;
  355. case KeyEvent.VK_ENTER:
  356. if ((flags & HANDLE_RETURN) != 0 && !line.isEmpty()) {
  357. commandParser.parseCommandCtrl(parentWindow, line);
  358. addToBuffer(line);
  359. }
  360. break;
  361. default:
  362. /* Do nothing. */
  363. break;
  364. }
  365. }
  366. /**
  367. * Calls when the user presses the up key.
  368. * Handles cycling through the input buffer.
  369. */
  370. protected void doBufferUp() {
  371. if ((flags & HANDLE_BACKBUFFER) != 0) {
  372. if (buffer.hasPrevious()) {
  373. target.setText(buffer.getPrevious());
  374. } else {
  375. Toolkit.getDefaultToolkit().beep();
  376. }
  377. }
  378. validateText();
  379. }
  380. /**
  381. * Called when the user presses the down key.
  382. * Handles cycling through the input buffer, and storing incomplete lines.
  383. */
  384. protected void doBufferDown() {
  385. if ((flags & HANDLE_BACKBUFFER) != 0) {
  386. if (buffer.hasNext()) {
  387. target.setText(buffer.getNext());
  388. } else if (target.getText().isEmpty()) {
  389. Toolkit.getDefaultToolkit().beep();
  390. } else {
  391. addToBuffer(target.getText());
  392. target.setText("");
  393. }
  394. }
  395. validateText();
  396. }
  397. /**
  398. * Retrieves a list of all known entries in the input backbuffer.
  399. *
  400. * @since 0.6
  401. * @return A copy of the input backbuffer.
  402. */
  403. public List<String> getBackBuffer() {
  404. return new ArrayList<String>(buffer.getList());
  405. }
  406. /**
  407. * Handles tab completion of a string. Called when the user presses
  408. * (shift) tab.
  409. *
  410. * @param shiftPressed True iff shift is pressed
  411. * @since 0.6.3
  412. */
  413. protected void doTabCompletion(final boolean shiftPressed) {
  414. if (tabCompleter == null || (flags & HANDLE_TABCOMPLETION) == 0) {
  415. LOGGER.log(Level.FINE,
  416. "Aborting tab completion. Completer: {0}, flags: {1}",
  417. new Object[]{tabCompleter, flags});
  418. return;
  419. }
  420. final String text = target.getText();
  421. LOGGER.log(Level.FINER, "Text for tab completion: {0}", text);
  422. if (text.isEmpty()) {
  423. doNormalTabCompletion(text, 0, 0, shiftPressed, null);
  424. return;
  425. }
  426. final int pos = target.getCaretPosition() - 1;
  427. int start = (pos < 0) ? 0 : pos;
  428. int end = (pos < 0) ? 0 : pos;
  429. // Traverse backwards
  430. while (start > 0 && text.charAt(start) != ' ') {
  431. start--;
  432. }
  433. if (text.charAt(start) == ' ') {
  434. start++;
  435. }
  436. // And forwards
  437. while (end < text.length() && text.charAt(end) != ' ') {
  438. end++;
  439. }
  440. if (start > end) {
  441. end = start;
  442. }
  443. LOGGER.log(Level.FINER, "Offsets: start: {0}, end: {1}",
  444. new Object[]{start, end});
  445. if (start > 0 && text.charAt(0) == CommandManager.getCommandManager().getCommandChar()) {
  446. doCommandTabCompletion(text, start, end, shiftPressed);
  447. } else {
  448. doNormalTabCompletion(text, start, end, shiftPressed, null);
  449. }
  450. }
  451. /**
  452. * Handles potentially intelligent tab completion.
  453. *
  454. * @param text The text that is being completed
  455. * @param start The start index of the word we're completing
  456. * @param end The end index of the word we're completing
  457. * @param shiftPressed True iff shift is pressed
  458. */
  459. private void doCommandTabCompletion(final String text, final int start,
  460. final int end, final boolean shiftPressed) {
  461. doNormalTabCompletion(text, start, end, shiftPressed,
  462. TabCompleter.getIntelligentResults(parentWindow,
  463. text.substring(0, start), text.substring(start, end)));
  464. }
  465. /**
  466. * Handles normal (non-intelligent-command) tab completion.
  467. *
  468. * @param text The text that is being completed
  469. * @param start The start index of the word we're completing
  470. * @param end The end index of the word we're completing
  471. * @param additional A list of additional strings to use
  472. * @param shiftPressed True iff shift is pressed
  473. */
  474. private void doNormalTabCompletion(final String text, final int start,
  475. final int end, final boolean shiftPressed,
  476. final AdditionalTabTargets additional) {
  477. final TabCompletionResult res = style.getResult(text, start, end,
  478. shiftPressed, additional);
  479. if (res != null) {
  480. target.setText(res.getText());
  481. target.setCaretPosition(res.getPosition());
  482. }
  483. }
  484. /**
  485. * Called when the user presses return in the text area. The line they
  486. * typed is added to the buffer for future use.
  487. * @param line The event that was fired
  488. */
  489. public void enterPressed(final String line) {
  490. if (!line.isEmpty()) {
  491. final StringBuffer thisBuffer = new StringBuffer(line);
  492. ActionManager.getActionManager().triggerEvent(
  493. CoreActionType.CLIENT_USER_INPUT, null,
  494. parentWindow, thisBuffer);
  495. addToBuffer(thisBuffer.toString());
  496. commandParser.parseCommand(parentWindow, thisBuffer.toString());
  497. }
  498. cancelTypingNotification();
  499. fireLineWrap(0);
  500. fireCommandPassed();
  501. }
  502. /**
  503. * Adds the specified control code to the textarea. If the user has a range
  504. * of text selected, the characters are added before and after, and the
  505. * caret is positioned based on the position argument.
  506. * @param code The control code to add
  507. * @param position The position of the caret after a selection is altered
  508. */
  509. protected void addControlCode(final int code, final int position) {
  510. final String insert = String.valueOf((char) code);
  511. final int selectionEnd = target.getSelectionEnd();
  512. final int selectionStart = target.getSelectionStart();
  513. if (selectionStart < selectionEnd) {
  514. final String source = target.getText();
  515. final String before = source.substring(0, selectionStart);
  516. final String selected = target.getSelectedText();
  517. final String after =
  518. source.substring(selectionEnd, source.length());
  519. target.setText(before + insert + selected + insert + after);
  520. if (position == POSITION_START) {
  521. target.setCaretPosition(selectionStart + 1);
  522. } else if (position == POSITION_END) {
  523. target.setCaretPosition(selectionEnd + 2);
  524. }
  525. } else {
  526. final int offset = target.getCaretPosition();
  527. final String source = target.getText();
  528. final String before = target.getText().substring(0, offset);
  529. final String after = target.getText().substring(offset,
  530. source.length());
  531. target.setText(before + insert + after);
  532. target.setCaretPosition(offset + 1);
  533. }
  534. }
  535. /**
  536. * Adds all items in the string array to the buffer.
  537. *
  538. * @param lines lines to add to the buffer
  539. */
  540. public void addToBuffer(final String[] lines) {
  541. for (String line : lines) {
  542. addToBuffer(line);
  543. }
  544. }
  545. /**
  546. * Adds the specified string to the buffer.
  547. *
  548. * @param line The line to be added to the buffer
  549. */
  550. public void addToBuffer(final String line) {
  551. buffer.add(line);
  552. buffer.seekToEnd();
  553. }
  554. /** {@inheritDoc} */
  555. @Override
  556. public void configChanged(final String domain, final String key) {
  557. setStyle();
  558. }
  559. /**
  560. * Inserts text to the current inputField.
  561. *
  562. * @param text The text to insert into the inputField
  563. * @since 0.6.4
  564. */
  565. public void addToInputField(final String text) {
  566. target.setText(text);
  567. }
  568. /**
  569. * Clears the text from the inputField.
  570. * @since 0.6.4
  571. */
  572. public void clearInputField() {
  573. target.setText("");
  574. }
  575. }