選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

InputHandler.java 24KB

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