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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright (c) 2006-2007 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.Config;
  24. import com.dmdirc.commandparser.Command;
  25. import com.dmdirc.commandparser.CommandManager;
  26. import com.dmdirc.commandparser.CommandParser;
  27. import com.dmdirc.commandparser.IntelligentCommand;
  28. import com.dmdirc.ui.interfaces.InputWindow;
  29. import com.dmdirc.ui.components.ColourPickerDialog;
  30. import com.dmdirc.ui.messages.Styliser;
  31. import java.awt.event.ActionEvent;
  32. import java.awt.event.ActionListener;
  33. import java.awt.event.KeyEvent;
  34. import java.awt.event.KeyListener;
  35. import java.util.ArrayList;
  36. import java.util.List;
  37. import javax.swing.JTextField;
  38. /**
  39. * Handles events generated by a user typing into a textfield. Allows the user
  40. * to use shortcut keys for control characters (ctrl+b, etc), to tab complete
  41. * nicknames/channel names/etc, and to scroll through their previously issued
  42. * commands.
  43. * @author chris
  44. */
  45. public final class InputHandler implements KeyListener, ActionListener {
  46. /**
  47. * Indicates that the caret should be moved to the end of a selection when
  48. * a control code has been inserted.
  49. */
  50. private static final int POSITION_END = 1;
  51. /**
  52. * Indicates that the caret should be moved to the start of a selection when
  53. * a control code has been inserted.
  54. */
  55. private static final int POSITION_START = 2;
  56. /**
  57. * The current position in the buffer (where the user has scrolled back
  58. * to).
  59. */
  60. private int bufferPosition;
  61. /**
  62. * The maximum size of the buffer.
  63. */
  64. private final int bufferSize;
  65. /**
  66. * The maximum position we've got to in the buffer. This will be the
  67. * position that is inserted to next. Note that it will wrap around once
  68. * we hit the maximum size.
  69. */
  70. private int bufferMaximum;
  71. /**
  72. * The lowest entry we've used in the buffer.
  73. */
  74. private int bufferMinimum;
  75. /**
  76. * The buffer itself.
  77. */
  78. private String[] buffer;
  79. /**
  80. * The textfield that we're handling input for.
  81. */
  82. private final JTextField target;
  83. /**
  84. * The TabCompleter to use for tab completion.
  85. */
  86. private TabCompleter tabCompleter;
  87. /**
  88. * The CommandParser to use for our input.
  89. */
  90. private final CommandParser commandParser;
  91. /**
  92. * The frame that we belong to.
  93. */
  94. private final InputWindow parentWindow;
  95. /** Colour picker dialog. */
  96. private ColourPickerDialog colourPicker;
  97. /**
  98. * Creates a new instance of InputHandler. Adds listeners to the target
  99. * that we need to operate.
  100. * @param thisTarget The text field this input handler is dealing with.
  101. * @param thisCommandParser The command parser to use for this text field.
  102. * @param thisParentWindow The window that owns this input handler
  103. */
  104. public InputHandler(final JTextField thisTarget,
  105. final CommandParser thisCommandParser,
  106. final InputWindow thisParentWindow) {
  107. bufferSize = thisParentWindow.getConfigManager().getOptionInt("ui", "inputbuffersize", 50);
  108. this.commandParser = thisCommandParser;
  109. this.parentWindow = thisParentWindow;
  110. this.target = thisTarget;
  111. this.buffer = new String[bufferSize];
  112. bufferPosition = 0;
  113. bufferMinimum = 0;
  114. bufferMaximum = 0;
  115. target.addKeyListener(this);
  116. target.addActionListener(this);
  117. target.setFocusTraversalKeysEnabled(false);
  118. }
  119. /**
  120. * Sets this input handler's tab completer.
  121. * @param newTabCompleter The new tab completer
  122. */
  123. public void setTabCompleter(final TabCompleter newTabCompleter) {
  124. tabCompleter = newTabCompleter;
  125. }
  126. /**
  127. * Called when the user types a normal character.
  128. * @param keyEvent The event that was fired
  129. */
  130. public void keyTyped(final KeyEvent keyEvent) {
  131. //Ignore.
  132. }
  133. /**
  134. * Called when the user presses down any key. Handles the insertion of
  135. * control codes, tab completion, and scrolling the back buffer.
  136. * @param keyEvent The event that was fired
  137. */
  138. public void keyPressed(final KeyEvent keyEvent) {
  139. if (colourPicker != null) {
  140. colourPicker.dispose();
  141. colourPicker = null;
  142. }
  143. // Formatting codes
  144. if ((keyEvent.getModifiers() & KeyEvent.CTRL_MASK) != 0) {
  145. handleControlKey(keyEvent);
  146. }
  147. // Back buffer scrolling
  148. if (keyEvent.getKeyCode() == KeyEvent.VK_UP) {
  149. doBufferUp();
  150. } else if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) {
  151. doBufferDown();
  152. }
  153. // Tab completion
  154. if (keyEvent.getKeyCode() == KeyEvent.VK_TAB && tabCompleter != null) {
  155. doTabCompletion();
  156. }
  157. }
  158. /**
  159. * Handles the pressing of a key while the control key is pressed.
  160. * Inserts control chars as appropriate.
  161. * @param keyEvent The key event that triggered this event.
  162. */
  163. private void handleControlKey(final KeyEvent keyEvent) {
  164. switch (keyEvent.getKeyCode()) {
  165. case KeyEvent.VK_B:
  166. addControlCode(Styliser.CODE_BOLD, POSITION_END);
  167. break;
  168. case KeyEvent.VK_U:
  169. addControlCode(Styliser.CODE_UNDERLINE, POSITION_END);
  170. break;
  171. case KeyEvent.VK_O:
  172. addControlCode(Styliser.CODE_STOP, POSITION_END);
  173. break;
  174. case KeyEvent.VK_I:
  175. addControlCode(Styliser.CODE_ITALIC, POSITION_END);
  176. break;
  177. case KeyEvent.VK_F:
  178. if ((keyEvent.getModifiers() & KeyEvent.SHIFT_MASK) != 0) {
  179. addControlCode(Styliser.CODE_FIXED, POSITION_END);
  180. }
  181. break;
  182. case KeyEvent.VK_K:
  183. if ((keyEvent.getModifiers() & KeyEvent.SHIFT_MASK) == 0) {
  184. addControlCode(Styliser.CODE_COLOUR, POSITION_START);
  185. showColourPicker(true, false);
  186. } else {
  187. addControlCode(Styliser.CODE_HEXCOLOUR, POSITION_START);
  188. showColourPicker(false, true);
  189. }
  190. break;
  191. case KeyEvent.VK_ENTER:
  192. commandParser.parseCommandCtrl(parentWindow, target.getText());
  193. addToBuffer(target.getText());
  194. break;
  195. default:
  196. /* Do nothing. */
  197. break;
  198. }
  199. }
  200. /**
  201. * Calls when the user presses the up key.
  202. * Handles cycling through the input buffer.
  203. */
  204. private void doBufferUp() {
  205. if (bufferPosition == bufferMinimum) {
  206. // TODO: Beep, or something.
  207. } else {
  208. bufferPosition = normalise(bufferPosition - 1);
  209. retrieveBuffer();
  210. }
  211. }
  212. /**
  213. * Called when the user presses the down key.
  214. * Handles cycling through the input buffer, and storing incomplete lines.
  215. */
  216. private void doBufferDown() {
  217. if (bufferPosition != bufferMaximum) {
  218. bufferPosition = normalise(bufferPosition + 1);
  219. retrieveBuffer();
  220. } else if (target.getText().length() == 0) {
  221. // Beep or something
  222. } else {
  223. addToBuffer(target.getText());
  224. }
  225. }
  226. /**
  227. * Handles tab completion of a string. Called when the user presses tab.
  228. */
  229. private void doTabCompletion() {
  230. String text = target.getText();
  231. if (text.length() == 0) {
  232. return;
  233. }
  234. final int pos = target.getCaretPosition() - 1;
  235. int start = (pos < 0) ? 0 : pos;
  236. int end = (pos < 0) ? 0 : pos;
  237. // Traverse backwards
  238. while (start > 0 && text.charAt(start) != ' ') {
  239. start--;
  240. }
  241. if (text.charAt(start) == ' ') { start++; }
  242. // And forwards
  243. while (end < text.length() && text.charAt(end) != ' ') {
  244. end++;
  245. }
  246. if (start > end) {
  247. return;
  248. }
  249. if (start > 0 && text.charAt(0) == Config.getCommandChar().charAt(0)) {
  250. doCommandTabCompletion(text, start, end);
  251. } else {
  252. doNormalTabCompletion(text, start, end, null);
  253. }
  254. }
  255. /**
  256. * Handles potentially intelligent tab completion.
  257. *
  258. * @param text The text that is being completed
  259. * @param start The start index of the word we're completing
  260. * @param end The end index of the word we're completing
  261. */
  262. private void doCommandTabCompletion(final String text, final int start,
  263. final int end) {
  264. final String signature = text.substring(1, text.indexOf(' '));
  265. final Command command = CommandManager.getCommand(signature);
  266. if (command instanceof IntelligentCommand) {
  267. int args = 0;
  268. int lastArg = signature.length() + 2;
  269. final List<String> previousArgs = new ArrayList<String>();
  270. final String word = text.substring(start, end);
  271. for (int i = lastArg; i < start; i++) {
  272. if (text.charAt(i) == ' ') {
  273. args++;
  274. previousArgs.add(text.substring(lastArg, i));
  275. lastArg = i + 1;
  276. }
  277. }
  278. final List<String> results = ((IntelligentCommand) command).getSuggestions(args, previousArgs);
  279. doNormalTabCompletion(text, start, end, results);
  280. } else {
  281. doNormalTabCompletion(text, start, end, null);
  282. }
  283. }
  284. /**
  285. * Handles normal (non-intelligent-command) tab completion.
  286. *
  287. * @param text The text that is being completed
  288. * @param start The start index of the word we're completing
  289. * @param end The end index of the word we're completing
  290. * @param additional A list of additional strings to use
  291. */
  292. private void doNormalTabCompletion(final String text, final int start,
  293. final int end, final List<String> additional) {
  294. final String word = text.substring(start, end);
  295. final TabCompleterResult res = tabCompleter.complete(word, additional);
  296. if (res.getResultCount() == 0) {
  297. // TODO: Beep, or something
  298. } else if (res.getResultCount() == 1) {
  299. // One result, just replace it
  300. final String result = res.getResults().get(0);
  301. target.setText(text.substring(0, start) + result + text.substring(end));
  302. target.setCaretPosition(start + result.length());
  303. } else {
  304. // Multiple results
  305. final String sub = res.getBestSubstring();
  306. if (sub.equalsIgnoreCase(word)) {
  307. // TODO: Other possible actions (mIRC-style etc)
  308. if (Config.getOption("tabcompletion", "style", "bash").equals("bash")) {
  309. parentWindow.addLine("tabCompletion", res.toString());
  310. }
  311. } else {
  312. target.setText(text.substring(0, start) + sub + text.substring(end));
  313. target.setCaretPosition(start + sub.length());
  314. }
  315. }
  316. }
  317. /**
  318. * Called when the user releases any key.
  319. * @param keyEvent The event that was fired
  320. */
  321. public void keyReleased(final KeyEvent keyEvent) {
  322. //Ignore.
  323. }
  324. /**
  325. * Called when the user presses return in the text area. The line they
  326. * typed is added to the buffer for future use.
  327. * @param actionEvent The event that was fired
  328. */
  329. public void actionPerformed(final ActionEvent actionEvent) {
  330. final String line = actionEvent.getActionCommand();
  331. if (line.length() > 0) {
  332. addToBuffer(line);
  333. commandParser.parseCommand(parentWindow, line);
  334. }
  335. }
  336. /**
  337. * Adds the specified control code to the textarea. If the user has a range
  338. * of text selected, the characters are added before and after, and the
  339. * caret is positioned based on the position argument.
  340. * @param code The control code to add
  341. * @param position The position of the caret after a selection is altered
  342. */
  343. private void addControlCode(final int code, final int position) {
  344. final String insert = "" + (char) code;
  345. final int selectionEnd = target.getSelectionEnd();
  346. final int selectionStart = target.getSelectionStart();
  347. if (selectionStart < selectionEnd) {
  348. final String source = target.getText();
  349. final String before = source.substring(0, selectionStart);
  350. final String selected = target.getSelectedText();
  351. final String after = source.substring(selectionEnd, source.length());
  352. target.setText(before + insert + selected + insert + after);
  353. if (position == POSITION_START) {
  354. target.setCaretPosition(selectionStart + 1);
  355. } else if (position == POSITION_END) {
  356. target.setCaretPosition(selectionEnd + 2);
  357. }
  358. } else {
  359. final int offset = target.getCaretPosition();
  360. final String source = target.getText();
  361. final String before = target.getText().substring(0, offset);
  362. final String after = target.getText().substring(offset, source.length());
  363. target.setText(before + insert + after);
  364. target.setCaretPosition(offset + 1);
  365. }
  366. }
  367. /**
  368. * Retrieves the buffered text stored at the position indicated by
  369. * bufferPos, and replaces the current textbox content with it.
  370. */
  371. private void retrieveBuffer() {
  372. target.setText(buffer[bufferPosition]);
  373. }
  374. /**
  375. * Normalises the input so that it is in the range 0 <= x < bufferSize.
  376. * @param input The number to normalise
  377. * @return The normalised number
  378. */
  379. private int normalise(final int input) {
  380. int res = input;
  381. while (res < 0) {
  382. res += bufferSize;
  383. }
  384. return res % bufferSize;
  385. }
  386. /**
  387. * Adds all items in the string array to the buffer.
  388. *
  389. * @param lines lines to add to the buffer
  390. */
  391. public void addToBuffer(final String[] lines) {
  392. for (String line : lines) {
  393. addToBuffer(line);
  394. }
  395. }
  396. /**
  397. * Adds the specified string to the buffer.
  398. * @param line The line to be added to the buffer
  399. */
  400. public void addToBuffer(final String line) {
  401. buffer[bufferMaximum] = line;
  402. bufferMaximum = normalise(bufferMaximum + 1);
  403. bufferPosition = bufferMaximum;
  404. if (buffer[bufferSize - 1] != null) {
  405. bufferMinimum = normalise(bufferMaximum + 1);
  406. buffer[bufferMaximum] = null;
  407. }
  408. target.setText("");
  409. }
  410. /**
  411. * Displays a colour picker for the target.
  412. *
  413. * @param irc show irc colours in the colour picker
  414. * @param hex show hex colours in the colour picker
  415. */
  416. private void showColourPicker(final boolean irc, final boolean hex) {
  417. if (Config.getOptionBool("general", "showcolourdialog")) {
  418. colourPicker = new ColourPickerDialog(irc, hex);
  419. colourPicker.addActionListener(new ActionListener() {
  420. public void actionPerformed(final ActionEvent actionEvent) {
  421. target.setText(target.getText() + actionEvent.getActionCommand());
  422. colourPicker.dispose();
  423. colourPicker = null;
  424. } });
  425. colourPicker.setLocation((int) target.getLocationOnScreen().getX(), (int) target.getLocationOnScreen().getY() - colourPicker.getHeight());
  426. colourPicker.setVisible(true);
  427. }
  428. }
  429. }