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

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