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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /*
  2. * Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
  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.actions.ActionManager;
  24. import com.dmdirc.actions.CoreActionType;
  25. import com.dmdirc.commandparser.CommandManager;
  26. import com.dmdirc.commandparser.commands.Command;
  27. import com.dmdirc.commandparser.commands.ValidatingCommand;
  28. import com.dmdirc.commandparser.commands.WrappableCommand;
  29. import com.dmdirc.commandparser.parsers.CommandParser;
  30. import com.dmdirc.config.prefs.validator.ValidationResponse;
  31. import com.dmdirc.interfaces.ConfigChangeListener;
  32. import com.dmdirc.ui.input.tabstyles.BashStyle;
  33. import com.dmdirc.ui.input.tabstyles.MircStyle;
  34. import com.dmdirc.ui.input.tabstyles.TabCompletionResult;
  35. import com.dmdirc.ui.input.tabstyles.TabCompletionStyle;
  36. import com.dmdirc.ui.interfaces.InputField;
  37. import com.dmdirc.ui.interfaces.InputValidationListener;
  38. import com.dmdirc.ui.interfaces.InputWindow;
  39. import com.dmdirc.ui.messages.Styliser;
  40. import com.dmdirc.util.ListenerList;
  41. import com.dmdirc.util.RollingList;
  42. import java.awt.Toolkit;
  43. import java.awt.event.KeyEvent;
  44. import java.util.Arrays;
  45. import java.util.List;
  46. /**
  47. * Handles events generated by a user typing into a textfield. Allows the user
  48. * to use shortcut keys for control characters (ctrl+b, etc), to tab complete
  49. * nicknames/channel names/etc, and to scroll through their previously issued
  50. * commands.
  51. *
  52. * @author chris
  53. */
  54. public abstract class InputHandler implements ConfigChangeListener {
  55. /**
  56. * Indicates that the caret should be moved to the end of a selection when
  57. * a control code has been inserted.
  58. */
  59. private static final int POSITION_END = 1;
  60. /**
  61. * Indicates that the caret should be moved to the start of a selection when
  62. * a control code has been inserted.
  63. */
  64. private static final int POSITION_START = 2;
  65. /** Flag to indicate that this input handler should handle tab completion. */
  66. private static final int HANDLE_TABCOMPLETION = 1;
  67. /** Flag to indicate that this input handler should maintain a back buffer. */
  68. private static final int HANDLE_BACKBUFFER = 2;
  69. /** Flag to indicate that this input handler should handle formatting. */
  70. private static final int HANDLE_FORMATTING = 4;
  71. /** Flag to indicate that this input handler should handle returns. */
  72. private static final int HANDLE_RETURN = 8;
  73. /** The flags for this particular input handler. */
  74. private int flags = HANDLE_TABCOMPLETION | HANDLE_BACKBUFFER
  75. | HANDLE_FORMATTING | HANDLE_RETURN;
  76. /** The input buffer. */
  77. protected RollingList<String> buffer;
  78. /** The textfield that we're handling input for. */
  79. protected final InputField target;
  80. /** The TabCompleter to use for tab completion. */
  81. protected TabCompleter tabCompleter;
  82. /** The CommandParser to use for our input. */
  83. protected final CommandParser commandParser;
  84. /** The frame that we belong to. */
  85. protected final InputWindow parentWindow;
  86. /** The tab completion style. */
  87. protected TabCompletionStyle style;
  88. /** Our listener list. */
  89. private final ListenerList listeners = new ListenerList();
  90. /**
  91. * Creates a new instance of InputHandler. Adds listeners to the target
  92. * that we need to operate.
  93. *
  94. * @param thisTarget The text field this input handler is dealing with.
  95. * @param thisCommandParser The command parser to use for this text field.
  96. * @param thisParentWindow The window that owns this input handler
  97. */
  98. public InputHandler(final InputField thisTarget,
  99. final CommandParser thisCommandParser,
  100. final InputWindow thisParentWindow) {
  101. buffer = new RollingList<String>(thisParentWindow.getConfigManager().
  102. getOptionInt("ui", "inputbuffersize", 50), "");
  103. this.commandParser = thisCommandParser;
  104. this.parentWindow = thisParentWindow;
  105. this.target = thisTarget;
  106. setStyle();
  107. parentWindow.getConfigManager().addChangeListener("tabcompletion",
  108. "style", this);
  109. if ((flags & HANDLE_BACKBUFFER) != 0) {
  110. addUpHandler();
  111. addDownHandler();
  112. }
  113. if ((flags & HANDLE_TABCOMPLETION) != 0) {
  114. addTabHandler();
  115. }
  116. addKeyHandler();
  117. addEnterHandler();
  118. }
  119. /**
  120. * Adds an arrow up key handler.
  121. */
  122. protected abstract void addUpHandler();
  123. /**
  124. * Adds an arrow down key handler.
  125. */
  126. protected abstract void addDownHandler();
  127. /**
  128. * Adds an tab key handler.
  129. */
  130. protected abstract void addTabHandler();
  131. /**
  132. * Adds a key handler.
  133. */
  134. protected abstract void addKeyHandler();
  135. /**
  136. * Adds an enter key handler.
  137. */
  138. protected abstract void addEnterHandler();
  139. /**
  140. * Indicates which types of input this handler should handle.
  141. *
  142. * @param handleTabCompletion Whether or not to handle tab completion
  143. * @param handleBackBuffer Whether or not to maintain an input back buffer
  144. * @param handleFormatting Whether or not to handle formatting
  145. * @param handleReturn Whether or not to handle returns
  146. */
  147. public void setTypes(final boolean handleTabCompletion,
  148. final boolean handleBackBuffer,
  149. final boolean handleFormatting, final boolean handleReturn) {
  150. flags = (handleTabCompletion ? HANDLE_TABCOMPLETION : 0)
  151. | (handleBackBuffer ? HANDLE_BACKBUFFER : 0)
  152. | (handleFormatting ? HANDLE_FORMATTING : 0)
  153. | (handleReturn ? HANDLE_RETURN : 0);
  154. }
  155. /**
  156. * Sets this inputhandler's tab completion style.
  157. */
  158. private void setStyle() {
  159. if ("bash".equals(parentWindow.getConfigManager().getOption("tabcompletion",
  160. "style", "bash"))) {
  161. style = new BashStyle();
  162. } else {
  163. style = new MircStyle();
  164. }
  165. style.setContext(tabCompleter, parentWindow);
  166. }
  167. /**
  168. * Sets this input handler's tab completer.
  169. *
  170. * @param newTabCompleter The new tab completer
  171. */
  172. public void setTabCompleter(final TabCompleter newTabCompleter) {
  173. tabCompleter = newTabCompleter;
  174. style.setContext(tabCompleter, parentWindow);
  175. }
  176. /**
  177. * Handles the pressing of a key. Inserts control chars as appropriate.
  178. *
  179. * @param keyCode Keycode for the pressed key
  180. * @param shiftPressed Was shift pressed
  181. * @param ctrlPressed Was ctrl key pressed
  182. */
  183. protected void handleKeyPressed(final int keyCode,
  184. final boolean shiftPressed, final boolean ctrlPressed) {
  185. target.hideColourPicker();
  186. if (ctrlPressed && (flags & HANDLE_FORMATTING) != 0) {
  187. handleControlKey(keyCode, shiftPressed);
  188. }
  189. validateText();
  190. }
  191. /**
  192. * Validates the text currently entered in the text field.
  193. */
  194. protected void validateText() {
  195. final String text = target.getText();
  196. if (!text.isEmpty() && text.charAt(0) == CommandManager.getCommandChar()) {
  197. final List<String> args = Arrays.asList(text.split(" "));
  198. final String signature = args.get(0).substring(1);
  199. final Command command = CommandManager.getCommand(signature);
  200. if (command instanceof ValidatingCommand) {
  201. final ValidationResponse vr
  202. = ((ValidatingCommand) command).validateArguments(parentWindow, args);
  203. if (vr.isFailure()) {
  204. fireCommandFailure(vr.getFailureReason());
  205. }
  206. }
  207. if (command instanceof WrappableCommand) {
  208. final int count = ((WrappableCommand) command).getLineCount(parentWindow, args);
  209. if (count > 1) {
  210. fireLineWrap(count);
  211. }
  212. }
  213. } else {
  214. final int lines = parentWindow.getContainer().getNumLines(text);
  215. if (lines > 1) {
  216. fireLineWrap(lines);
  217. }
  218. }
  219. }
  220. /**
  221. * Fires the "illegalCommand" method of all validation listeners.
  222. *
  223. * @param reason The reason for the command failure
  224. */
  225. private void fireCommandFailure(final String reason) {
  226. for (InputValidationListener listener : listeners.get(InputValidationListener.class)) {
  227. listener.illegalCommand(reason);
  228. }
  229. }
  230. /**
  231. * Fires the "wrappedText" method of all validation listeners.
  232. *
  233. * @param lines The number of lines that the text will wrap to
  234. */
  235. private void fireLineWrap(final int lines) {
  236. for (InputValidationListener listener : listeners.get(InputValidationListener.class)) {
  237. listener.wrappedText(lines);
  238. }
  239. }
  240. /**
  241. * Adds an InputValidationListener to this input handler.
  242. *
  243. * @param listener The listener to be added
  244. */
  245. public void addValidationListener(final InputValidationListener listener) {
  246. listeners.add(InputValidationListener.class, listener);
  247. }
  248. /**
  249. * Handles the pressing of a key while the control key is pressed.
  250. * Inserts control chars as appropriate.
  251. *
  252. * @param keyCode Keycode for the pressed key
  253. * @param shiftPressed Was shift pressed
  254. */
  255. protected void handleControlKey(final int keyCode,
  256. final boolean shiftPressed) {
  257. switch (keyCode) {
  258. case KeyEvent.VK_B:
  259. addControlCode(Styliser.CODE_BOLD, POSITION_END);
  260. break;
  261. case KeyEvent.VK_U:
  262. addControlCode(Styliser.CODE_UNDERLINE, POSITION_END);
  263. break;
  264. case KeyEvent.VK_O:
  265. addControlCode(Styliser.CODE_STOP, POSITION_END);
  266. break;
  267. case KeyEvent.VK_I:
  268. addControlCode(Styliser.CODE_ITALIC, POSITION_END);
  269. break;
  270. case KeyEvent.VK_F:
  271. if (shiftPressed) {
  272. addControlCode(Styliser.CODE_FIXED, POSITION_END);
  273. }
  274. break;
  275. case KeyEvent.VK_K:
  276. if (shiftPressed) {
  277. addControlCode(Styliser.CODE_HEXCOLOUR, POSITION_START);
  278. target.showColourPicker(false, true);
  279. } else {
  280. addControlCode(Styliser.CODE_COLOUR, POSITION_START);
  281. target.showColourPicker(true, false);
  282. }
  283. break;
  284. case KeyEvent.VK_ENTER:
  285. if ((flags & HANDLE_RETURN) != 0) {
  286. commandParser.parseCommandCtrl(parentWindow,
  287. target.getText());
  288. addToBuffer(target.getText());
  289. }
  290. break;
  291. default:
  292. /* Do nothing. */
  293. break;
  294. }
  295. }
  296. /**
  297. * Calls when the user presses the up key.
  298. * Handles cycling through the input buffer.
  299. */
  300. protected void doBufferUp() {
  301. if (buffer.hasPrevious()) {
  302. target.setText(buffer.getPrevious());
  303. } else {
  304. Toolkit.getDefaultToolkit().beep();
  305. }
  306. }
  307. /**
  308. * Called when the user presses the down key.
  309. * Handles cycling through the input buffer, and storing incomplete lines.
  310. */
  311. protected void doBufferDown() {
  312. if (buffer.hasNext()) {
  313. target.setText(buffer.getNext());
  314. } else if (target.getText().isEmpty()) {
  315. Toolkit.getDefaultToolkit().beep();
  316. } else {
  317. addToBuffer(target.getText());
  318. }
  319. }
  320. /**
  321. * Handles tab completion of a string. Called when the user presses tab.
  322. */
  323. protected void doTabCompletion() {
  324. if (tabCompleter == null) {
  325. return;
  326. }
  327. final String text = target.getText();
  328. if (text.isEmpty()) {
  329. doNormalTabCompletion(text, 0, 0, null);
  330. return;
  331. }
  332. final int pos = target.getCaretPosition() - 1;
  333. int start = (pos < 0) ? 0 : pos;
  334. int end = (pos < 0) ? 0 : pos;
  335. // Traverse backwards
  336. while (start > 0 && text.charAt(start) != ' ') {
  337. start--;
  338. }
  339. if (text.charAt(start) == ' ') {
  340. start++;
  341. }
  342. // And forwards
  343. while (end < text.length() && text.charAt(end) != ' ') {
  344. end++;
  345. }
  346. if (start > end) {
  347. end = start;
  348. }
  349. if (start > 0 && text.charAt(0) == CommandManager.getCommandChar()) {
  350. doCommandTabCompletion(text, start, end);
  351. } else {
  352. doNormalTabCompletion(text, start, end, null);
  353. }
  354. }
  355. /**
  356. * Handles potentially intelligent tab completion.
  357. *
  358. * @param text The text that is being completed
  359. * @param start The start index of the word we're completing
  360. * @param end The end index of the word we're completing
  361. */
  362. private void doCommandTabCompletion(final String text, final int start,
  363. final int end) {
  364. doNormalTabCompletion(text, start, end,
  365. TabCompleter.getIntelligentResults(text.substring(0, start)));
  366. }
  367. /**
  368. * Handles normal (non-intelligent-command) tab completion.
  369. *
  370. * @param text The text that is being completed
  371. * @param start The start index of the word we're completing
  372. * @param end The end index of the word we're completing
  373. * @param additional A list of additional strings to use
  374. */
  375. private void doNormalTabCompletion(final String text, final int start,
  376. final int end, final AdditionalTabTargets additional) {
  377. final TabCompletionResult res = style.getResult(text, start, end,
  378. additional);
  379. if (res != null) {
  380. target.setText(res.getText());
  381. target.setCaretPosition(res.getPosition());
  382. }
  383. }
  384. /**
  385. * Called when the user presses return in the text area. The line they
  386. * typed is added to the buffer for future use.
  387. * @param line The event that was fired
  388. */
  389. public void enterPressed(final String line) {
  390. if (!line.isEmpty()) {
  391. final StringBuffer thisBuffer = new StringBuffer(line);
  392. ActionManager.processEvent(CoreActionType.CLIENT_USER_INPUT, null,
  393. parentWindow.getContainer(), thisBuffer);
  394. addToBuffer(thisBuffer.toString());
  395. commandParser.parseCommand(parentWindow, thisBuffer.toString());
  396. }
  397. }
  398. /**
  399. * Adds the specified control code to the textarea. If the user has a range
  400. * of text selected, the characters are added before and after, and the
  401. * caret is positioned based on the position argument.
  402. * @param code The control code to add
  403. * @param position The position of the caret after a selection is altered
  404. */
  405. protected void addControlCode(final int code, final int position) {
  406. final String insert = String.valueOf((char) code);
  407. final int selectionEnd = target.getSelectionEnd();
  408. final int selectionStart = target.getSelectionStart();
  409. if (selectionStart < selectionEnd) {
  410. final String source = target.getText();
  411. final String before = source.substring(0, selectionStart);
  412. final String selected = target.getSelectedText();
  413. final String after =
  414. source.substring(selectionEnd, source.length());
  415. target.setText(before + insert + selected + insert + after);
  416. if (position == POSITION_START) {
  417. target.setCaretPosition(selectionStart + 1);
  418. } else if (position == POSITION_END) {
  419. target.setCaretPosition(selectionEnd + 2);
  420. }
  421. } else {
  422. final int offset = target.getCaretPosition();
  423. final String source = target.getText();
  424. final String before = target.getText().substring(0, offset);
  425. final String after = target.getText().substring(offset,
  426. source.length());
  427. target.setText(before + insert + after);
  428. target.setCaretPosition(offset + 1);
  429. }
  430. }
  431. /**
  432. * Adds all items in the string array to the buffer.
  433. *
  434. * @param lines lines to add to the buffer
  435. */
  436. public void addToBuffer(final String[] lines) {
  437. for (String line : lines) {
  438. addToBuffer(line);
  439. }
  440. }
  441. /**
  442. * Adds the specified string to the buffer.
  443. *
  444. * @param line The line to be added to the buffer
  445. */
  446. public void addToBuffer(final String line) {
  447. buffer.add(line);
  448. buffer.seekToEnd();
  449. target.setText("");
  450. }
  451. /** {@inheritDoc} */
  452. @Override
  453. public void configChanged(final String domain, final String key) {
  454. setStyle();
  455. }
  456. }