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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. * Copyright (c) 2006-2015 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.FrameContainer;
  24. import com.dmdirc.commandparser.CommandArguments;
  25. import com.dmdirc.commandparser.CommandInfoPair;
  26. import com.dmdirc.commandparser.commands.ValidatingCommand;
  27. import com.dmdirc.commandparser.commands.WrappableCommand;
  28. import com.dmdirc.commandparser.parsers.CommandParser;
  29. import com.dmdirc.events.ClientUserInputEvent;
  30. import com.dmdirc.events.FrameClosingEvent;
  31. import com.dmdirc.interfaces.CommandController;
  32. import com.dmdirc.interfaces.EventBus;
  33. import com.dmdirc.interfaces.WindowModel;
  34. import com.dmdirc.interfaces.config.ConfigChangeListener;
  35. import com.dmdirc.interfaces.ui.InputField;
  36. import com.dmdirc.interfaces.ui.InputValidationListener;
  37. import com.dmdirc.parser.common.CompositionState;
  38. import com.dmdirc.plugins.ServiceManager;
  39. import com.dmdirc.ui.input.tabstyles.TabCompletionResult;
  40. import com.dmdirc.ui.input.tabstyles.TabCompletionStyle;
  41. import com.dmdirc.ui.messages.IRCControlCodes;
  42. import com.dmdirc.util.collections.ListenerList;
  43. import com.dmdirc.util.collections.RollingList;
  44. import com.dmdirc.util.validators.ValidationResponse;
  45. import com.google.common.util.concurrent.ThreadFactoryBuilder;
  46. import java.awt.Toolkit;
  47. import java.awt.event.KeyEvent;
  48. import java.util.ArrayList;
  49. import java.util.List;
  50. import java.util.concurrent.Executors;
  51. import java.util.concurrent.ScheduledExecutorService;
  52. import java.util.concurrent.ScheduledFuture;
  53. import java.util.concurrent.TimeUnit;
  54. import org.slf4j.Logger;
  55. import org.slf4j.LoggerFactory;
  56. import net.engio.mbassy.listener.Handler;
  57. /**
  58. * Handles events generated by a user typing into a textfield. Allows the user to use shortcut keys
  59. * for control characters (ctrl+b, etc), to tab complete nicknames/channel names/etc, and to scroll
  60. * through their previously issued commands.
  61. */
  62. public abstract class InputHandler implements ConfigChangeListener {
  63. private static final Logger LOG = LoggerFactory.getLogger(InputHandler.class);
  64. /**
  65. * Indicates that the caret should be moved to the start of a selection when a control code has
  66. * been inserted.
  67. */
  68. protected static final int POSITION_START = 2;
  69. /** Flag to indicate that this input handler should handle tab completion. */
  70. protected static final int HANDLE_TABCOMPLETION = 1;
  71. /** Flag to indicate that this input handler should maintain a back buffer. */
  72. protected static final int HANDLE_BACKBUFFER = 2;
  73. /** Flag to indicate that this input handler should handle formatting. */
  74. protected static final int HANDLE_FORMATTING = 4;
  75. /** Flag to indicate that this input handler should handle returns. */
  76. protected static final int HANDLE_RETURN = 8;
  77. /**
  78. * Time in milliseconds after which we switch from "typing" to"text entered" composing states.
  79. */
  80. private static final int TYPING_TIMEOUT = 5000;
  81. /**
  82. * Indicates that the caret should be moved to the end of a selection when a control code has
  83. * been inserted.
  84. */
  85. private static final int POSITION_END = 1;
  86. /** Tab-completer utilities. */
  87. private final TabCompleterUtils tabCompleterUtils;
  88. /** The flags for this particular input handler. */
  89. protected int flags = HANDLE_TABCOMPLETION | HANDLE_BACKBUFFER
  90. | HANDLE_FORMATTING | HANDLE_RETURN;
  91. /** The input buffer. */
  92. protected final RollingList<String> buffer;
  93. /** The textfield that we're handling input for. */
  94. protected final InputField target;
  95. /** The TabCompleter to use for tab completion. */
  96. protected TabCompleter tabCompleter;
  97. /** The CommandParser to use for our input. */
  98. protected final CommandParser commandParser;
  99. /** The frame that we belong to. */
  100. protected final WindowModel parentWindow;
  101. /** The tab completion style. */
  102. protected TabCompletionStyle style;
  103. /** Our listener list. */
  104. private final ListenerList listeners = new ListenerList();
  105. /** The current composition state. */
  106. private CompositionState state = CompositionState.IDLE;
  107. /** Timer used to manage timeouts of composition state. */
  108. private ScheduledFuture<?> compositionTimer;
  109. /** Manager to use to look up tab completion services. */
  110. private final ServiceManager serviceManager;
  111. /** The controller to use to retrieve command information. */
  112. private final CommandController commandController;
  113. /** The event bus to use to dispatch input events. */
  114. private final EventBus eventBus;
  115. /** Executor service. */
  116. private final ScheduledExecutorService executorService;
  117. /**
  118. * Creates a new instance of InputHandler. Adds listeners to the target that we need to operate.
  119. *
  120. * @param serviceManager Manager to use to look up tab completion services.
  121. * @param target The text field this input handler is dealing with.
  122. * @param commandController The controller to use to retrieve command information.
  123. * @param commandParser The command parser to use for this text field.
  124. * @param parentWindow The window that owns this input handler
  125. * @param eventBus The event bus to use to dispatch input events.
  126. */
  127. public InputHandler(
  128. final ServiceManager serviceManager,
  129. final InputField target,
  130. final CommandController commandController,
  131. final CommandParser commandParser,
  132. final WindowModel parentWindow,
  133. final TabCompleterUtils tabCompleterUtils,
  134. final EventBus eventBus) {
  135. buffer = new RollingList<>(parentWindow.getConfigManager()
  136. .getOptionInt("ui", "inputbuffersize"), "");
  137. this.serviceManager = serviceManager;
  138. this.target = target;
  139. this.commandController = commandController;
  140. this.commandParser = commandParser;
  141. this.parentWindow = parentWindow;
  142. this.tabCompleterUtils = tabCompleterUtils;
  143. this.eventBus = eventBus;
  144. executorService = Executors.newSingleThreadScheduledExecutor(
  145. new ThreadFactoryBuilder().setNameFormat("Composition state timer-%d").build());
  146. setStyle();
  147. parentWindow.getConfigManager().addChangeListener(
  148. "tabcompletion", "style", this);
  149. addUpHandler();
  150. addDownHandler();
  151. addTabHandler();
  152. addKeyHandler();
  153. addEnterHandler();
  154. eventBus.subscribe(this);
  155. }
  156. /**
  157. * Adds an arrow up key handler.
  158. */
  159. protected abstract void addUpHandler();
  160. /**
  161. * Adds an arrow down key handler.
  162. */
  163. protected abstract void addDownHandler();
  164. /**
  165. * Adds an tab key handler.
  166. */
  167. protected abstract void addTabHandler();
  168. /**
  169. * Adds a key handler.
  170. */
  171. protected abstract void addKeyHandler();
  172. /**
  173. * Adds an enter key handler.
  174. */
  175. protected abstract void addEnterHandler();
  176. /**
  177. * Indicates which types of input this handler should handle.
  178. *
  179. * @param handleTabCompletion Whether or not to handle tab completion
  180. * @param handleBackBuffer Whether or not to maintain an input back buffer
  181. * @param handleFormatting Whether or not to handle formatting
  182. * @param handleReturn Whether or not to handle returns
  183. */
  184. public void setTypes(final boolean handleTabCompletion,
  185. final boolean handleBackBuffer,
  186. final boolean handleFormatting, final boolean handleReturn) {
  187. flags = (handleTabCompletion ? HANDLE_TABCOMPLETION : 0)
  188. | (handleBackBuffer ? HANDLE_BACKBUFFER : 0)
  189. | (handleFormatting ? HANDLE_FORMATTING : 0)
  190. | (handleReturn ? HANDLE_RETURN : 0);
  191. }
  192. /**
  193. * Sets this inputhandler's tab completion style.
  194. */
  195. private void setStyle() {
  196. style = (TabCompletionStyle) serviceManager
  197. .getServiceProvider("tabcompletion", parentWindow
  198. .getConfigManager().getOption("tabcompletion", "style"))
  199. .getExportedService("getCompletionStyle").execute(tabCompleter,
  200. parentWindow);
  201. }
  202. /**
  203. * Sets this input handler's tab completer.
  204. *
  205. * @param newTabCompleter The new tab completer
  206. */
  207. public void setTabCompleter(final TabCompleter newTabCompleter) {
  208. tabCompleter = newTabCompleter;
  209. setStyle();
  210. }
  211. /**
  212. * Handles the pressing of a key. Inserts control chars as appropriate.
  213. *
  214. * @param line Text in the target
  215. * @param caretPosition Position of the caret after the key was pressed
  216. * @param keyCode Keycode for the pressed key
  217. * @param shiftPressed Was shift pressed
  218. * @param ctrlPressed Was ctrl key pressed
  219. */
  220. protected void handleKeyPressed(final String line, final int caretPosition,
  221. final int keyCode, final boolean shiftPressed,
  222. final boolean ctrlPressed) {
  223. target.hideColourPicker();
  224. if (keyCode == KeyEvent.VK_COMMA && caretPosition > 1) {
  225. // Reshow the colour picker dialog if the user follows a colour
  226. // or control code with a comma (so they can pick a background)
  227. final String partialLine = line.substring(0, caretPosition - 1);
  228. if (partialLine.matches("^.*" + IRCControlCodes.COLOUR + "[0-9]{0,2}$")) {
  229. target.showColourPicker(true, false);
  230. } else if (partialLine.matches("^.*" + IRCControlCodes.COLOUR_HEX + "[0-9A-Z]{6}?$")) {
  231. target.showColourPicker(false, true);
  232. }
  233. }
  234. if (ctrlPressed && (flags & HANDLE_FORMATTING) != 0) {
  235. handleControlKey(line, keyCode, shiftPressed);
  236. }
  237. if (target.getText().isEmpty()) {
  238. cancelTypingNotification();
  239. } else {
  240. updateTypingNotification();
  241. }
  242. validateText();
  243. }
  244. /**
  245. * Validates the text currently entered in the text field.
  246. */
  247. protected void validateText() {
  248. final String text = target.getText();
  249. final CommandArguments args = new CommandArguments(commandController, text);
  250. if (args.isCommand()) {
  251. final CommandInfoPair command = commandParser.getCommand(args.getCommandName());
  252. if (command != null && command.getCommand() instanceof ValidatingCommand) {
  253. final ValidationResponse vr = ((ValidatingCommand) command.getCommand())
  254. .validateArguments(parentWindow, args);
  255. if (vr.isFailure()) {
  256. fireCommandFailure(vr.getFailureReason());
  257. } else {
  258. fireCommandPassed();
  259. }
  260. }
  261. if (command != null && command.getCommand() instanceof WrappableCommand) {
  262. final int count = ((WrappableCommand) command.getCommand())
  263. .getLineCount(parentWindow, args);
  264. fireLineWrap(count);
  265. }
  266. } else {
  267. final int lines = parentWindow.getInputModel().get().getNumLines(text);
  268. fireLineWrap(lines);
  269. }
  270. }
  271. /** Resets the composition state to idle and notifies the parent if relevant. */
  272. private void cancelTypingNotification() {
  273. if (compositionTimer != null) {
  274. LOG.debug("Cancelling composition timer");
  275. compositionTimer.cancel(true);
  276. }
  277. LOG.debug("Cancelling typing notification");
  278. setCompositionState(CompositionState.IDLE);
  279. }
  280. /** Updates the composition state to typing and starts/resets the idle timer. */
  281. private void updateTypingNotification() {
  282. if (compositionTimer != null) {
  283. LOG.debug("Cancelling composition timer");
  284. compositionTimer.cancel(true);
  285. }
  286. compositionTimer = executorService.schedule(this::timeoutTypingNotification,
  287. TYPING_TIMEOUT, TimeUnit.MILLISECONDS);
  288. LOG.debug("Setting composition state to typing. Timer scheduled for {}", TYPING_TIMEOUT);
  289. setCompositionState(CompositionState.TYPING);
  290. }
  291. /** Updates the composition state to "entered text". */
  292. private void timeoutTypingNotification() {
  293. LOG.debug("Composition state timeout reached");
  294. setCompositionState(CompositionState.ENTERED_TEXT);
  295. }
  296. /**
  297. * Sets the composition state to the specified one. If the state has changed, the parent window
  298. * is notified of the new state.
  299. *
  300. * @param newState The new composition state
  301. */
  302. private void setCompositionState(final CompositionState newState) {
  303. if (state != newState) {
  304. state = newState;
  305. // TODO: Not sure where this should be exposed...
  306. ((FrameContainer) parentWindow).setCompositionState(state);
  307. }
  308. }
  309. /**
  310. * Fires the "illegalCommand" method of all validation listeners.
  311. *
  312. * @param reason The reason for the command failure
  313. */
  314. private void fireCommandFailure(final String reason) {
  315. for (InputValidationListener listener : listeners.get(InputValidationListener.class)) {
  316. listener.illegalCommand(reason);
  317. }
  318. }
  319. /**
  320. * Fires the "legalCommand" method of all validation listeners.
  321. */
  322. private void fireCommandPassed() {
  323. listeners.get(InputValidationListener.class).forEach(InputValidationListener::legalCommand);
  324. }
  325. /**
  326. * Fires the "wrappedText" method of all validation listeners.
  327. *
  328. * @param lines The number of lines that the text will wrap to
  329. */
  330. private void fireLineWrap(final int lines) {
  331. for (InputValidationListener listener : listeners.get(InputValidationListener.class)) {
  332. listener.wrappedText(lines);
  333. }
  334. }
  335. /**
  336. * Adds an InputValidationListener to this input handler.
  337. *
  338. * @param listener The listener to be added
  339. */
  340. public void addValidationListener(final InputValidationListener listener) {
  341. listeners.add(InputValidationListener.class, listener);
  342. }
  343. /**
  344. * Handles the pressing of a key while the control key is pressed. Inserts control chars as
  345. * appropriate.
  346. *
  347. * @param line Text in the target
  348. * @param keyCode Keycode for the pressed key
  349. * @param shiftPressed Was shift pressed
  350. */
  351. protected void handleControlKey(final String line, final int keyCode,
  352. final boolean shiftPressed) {
  353. switch (keyCode) {
  354. case KeyEvent.VK_B:
  355. addControlCode(IRCControlCodes.BOLD, POSITION_END);
  356. break;
  357. case KeyEvent.VK_U:
  358. addControlCode(IRCControlCodes.UNDERLINE, POSITION_END);
  359. break;
  360. case KeyEvent.VK_O:
  361. addControlCode(IRCControlCodes.STOP, POSITION_END);
  362. break;
  363. case KeyEvent.VK_I:
  364. addControlCode(IRCControlCodes.ITALIC, POSITION_END);
  365. break;
  366. case KeyEvent.VK_F:
  367. if (shiftPressed) {
  368. addControlCode(IRCControlCodes.FIXED, POSITION_END);
  369. }
  370. break;
  371. case KeyEvent.VK_K:
  372. if (shiftPressed) {
  373. addControlCode(IRCControlCodes.COLOUR_HEX, POSITION_START);
  374. target.showColourPicker(false, true);
  375. } else {
  376. addControlCode(IRCControlCodes.COLOUR, POSITION_START);
  377. target.showColourPicker(true, false);
  378. }
  379. break;
  380. case KeyEvent.VK_ENTER:
  381. if ((flags & HANDLE_RETURN) != 0 && !line.isEmpty()) {
  382. commandParser.parseCommandCtrl(parentWindow, line);
  383. addToBuffer(line);
  384. }
  385. break;
  386. default:
  387. /* Do nothing. */
  388. break;
  389. }
  390. }
  391. /**
  392. * Calls when the user presses the up key. Handles cycling through the input buffer.
  393. */
  394. protected void doBufferUp() {
  395. if ((flags & HANDLE_BACKBUFFER) != 0) {
  396. if (buffer.hasPrevious()) {
  397. target.setText(buffer.getPrevious());
  398. } else {
  399. Toolkit.getDefaultToolkit().beep();
  400. }
  401. }
  402. validateText();
  403. }
  404. /**
  405. * Called when the user presses the down key. Handles cycling through the input buffer, and
  406. * storing incomplete lines.
  407. */
  408. protected void doBufferDown() {
  409. if ((flags & HANDLE_BACKBUFFER) != 0) {
  410. if (buffer.hasNext()) {
  411. target.setText(buffer.getNext());
  412. } else if (target.getText().isEmpty()) {
  413. Toolkit.getDefaultToolkit().beep();
  414. } else {
  415. addToBuffer(target.getText());
  416. target.setText("");
  417. }
  418. }
  419. validateText();
  420. }
  421. /**
  422. * Retrieves a list of all known entries in the input backbuffer.
  423. *
  424. * @since 0.6
  425. * @return A copy of the input backbuffer.
  426. */
  427. public List<String> getBackBuffer() {
  428. return new ArrayList<>(buffer.getList());
  429. }
  430. /**
  431. * Handles tab completion of a string. Called when the user presses (shift) tab.
  432. *
  433. * @param shiftPressed True iff shift is pressed
  434. *
  435. * @since 0.6.3
  436. */
  437. protected void doTabCompletion(final boolean shiftPressed) {
  438. if (tabCompleter == null || (flags & HANDLE_TABCOMPLETION) == 0) {
  439. LOG.debug("Aborting tab completion. Completer: {}, flags: {}",
  440. new Object[]{tabCompleter, flags});
  441. return;
  442. }
  443. final String text = target.getText();
  444. LOG.trace("Text for tab completion: {}", text);
  445. if (text.isEmpty()) {
  446. doNormalTabCompletion(text, 0, 0, shiftPressed, null);
  447. return;
  448. }
  449. final int pos = target.getCaretPosition() - 1;
  450. int start = pos < 0 ? 0 : pos;
  451. int end = pos < 0 ? 0 : pos;
  452. // Traverse backwards
  453. while (start > 0 && text.charAt(start) != ' ') {
  454. start--;
  455. }
  456. if (text.charAt(start) == ' ') {
  457. start++;
  458. }
  459. // And forwards
  460. while (end < text.length() && text.charAt(end) != ' ') {
  461. end++;
  462. }
  463. if (start > end) {
  464. end = start;
  465. }
  466. LOG.trace("Offsets: start: {}, end: {}", new Object[]{start, end});
  467. if (start > 0 && text.charAt(0) == commandController.getCommandChar()) {
  468. doCommandTabCompletion(text, start, end, shiftPressed);
  469. } else {
  470. doNormalTabCompletion(text, start, end, shiftPressed, null);
  471. }
  472. }
  473. /**
  474. * Handles potentially intelligent tab completion.
  475. *
  476. * @param text The text that is being completed
  477. * @param start The start index of the word we're completing
  478. * @param end The end index of the word we're completing
  479. * @param shiftPressed True iff shift is pressed
  480. */
  481. private void doCommandTabCompletion(final String text, final int start,
  482. final int end, final boolean shiftPressed) {
  483. doNormalTabCompletion(text, start, end, shiftPressed,
  484. tabCompleterUtils.getIntelligentResults(parentWindow, commandController,
  485. text.substring(0, start), text.substring(start, end)));
  486. }
  487. /**
  488. * Handles normal (non-intelligent-command) tab completion.
  489. *
  490. * @param text The text that is being completed
  491. * @param start The start index of the word we're completing
  492. * @param end The end index of the word we're completing
  493. * @param additional A list of additional strings to use
  494. * @param shiftPressed True iff shift is pressed
  495. */
  496. private void doNormalTabCompletion(final String text, final int start,
  497. final int end, final boolean shiftPressed,
  498. final AdditionalTabTargets additional) {
  499. final TabCompletionResult res = style.getResult(text, start, end,
  500. shiftPressed, additional);
  501. if (res != null) {
  502. target.setText(res.getText());
  503. target.setCaretPosition(res.getPosition());
  504. }
  505. }
  506. /**
  507. * Called when the user presses return in the text area. The line they typed is added to the
  508. * buffer for future use.
  509. *
  510. * @param line The event that was fired
  511. */
  512. public void enterPressed(final String line) {
  513. if (!line.isEmpty()) {
  514. final StringBuffer bufferedLine = new StringBuffer(line);
  515. eventBus.publishAsync(new ClientUserInputEvent(parentWindow, bufferedLine));
  516. addToBuffer(bufferedLine.toString());
  517. commandParser.parseCommand(parentWindow, bufferedLine.toString());
  518. }
  519. cancelTypingNotification();
  520. fireLineWrap(0);
  521. fireCommandPassed();
  522. }
  523. /**
  524. * Adds the specified control code to the textarea. If the user has a range of text selected,
  525. * the characters are added before and after, and the caret is positioned based on the position
  526. * argument.
  527. *
  528. * @param code The control code to add
  529. * @param position The position of the caret after a selection is altered
  530. */
  531. protected void addControlCode(final int code, final int position) {
  532. final String insert = String.valueOf((char) code);
  533. final int selectionEnd = target.getSelectionEnd();
  534. final int selectionStart = target.getSelectionStart();
  535. if (selectionStart < selectionEnd) {
  536. final String source = target.getText();
  537. final String before = source.substring(0, selectionStart);
  538. final String selected = target.getSelectedText();
  539. final String after = source.substring(selectionEnd, source.length());
  540. target.setText(before + insert + selected + insert + after);
  541. if (position == POSITION_START) {
  542. target.setCaretPosition(selectionStart + 1);
  543. } else if (position == POSITION_END) {
  544. target.setCaretPosition(selectionEnd + 2);
  545. }
  546. } else {
  547. final int offset = target.getCaretPosition();
  548. final String source = target.getText();
  549. final String before = target.getText().substring(0, offset);
  550. final String after = target.getText().substring(offset,
  551. source.length());
  552. target.setText(before + insert + after);
  553. target.setCaretPosition(offset + 1);
  554. }
  555. }
  556. /**
  557. * Adds all items in the string array to the buffer.
  558. *
  559. * @param lines lines to add to the buffer
  560. */
  561. public void addToBuffer(final String[] lines) {
  562. for (String line : lines) {
  563. addToBuffer(line);
  564. }
  565. }
  566. /**
  567. * Adds the specified string to the buffer.
  568. *
  569. * @param line The line to be added to the buffer
  570. */
  571. public void addToBuffer(final String line) {
  572. buffer.add(line);
  573. buffer.seekToEnd();
  574. }
  575. @Override
  576. public void configChanged(final String domain, final String key) {
  577. setStyle();
  578. }
  579. /**
  580. * Inserts text to the current inputField.
  581. *
  582. * @param text The text to insert into the inputField
  583. *
  584. * @since 0.6.4
  585. */
  586. public void addToInputField(final String text) {
  587. target.setText(text);
  588. }
  589. /**
  590. * Clears the text from the inputField.
  591. *
  592. * @since 0.6.4
  593. */
  594. public void clearInputField() {
  595. target.setText("");
  596. }
  597. @Handler
  598. void parentClosing(final FrameClosingEvent event) {
  599. if (event.getSource().equals(parentWindow)) {
  600. executorService.shutdown();
  601. eventBus.unsubscribe(this);
  602. }
  603. }
  604. }