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.

TextPane.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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.addons.ui_swing.textpane;
  23. import com.dmdirc.addons.ui_swing.UIUtilities;
  24. import com.dmdirc.interfaces.WindowModel;
  25. import com.dmdirc.interfaces.config.ConfigChangeListener;
  26. import com.dmdirc.ui.messages.CachingDocument;
  27. import com.dmdirc.ui.messages.Document;
  28. import com.dmdirc.ui.messages.DocumentListener;
  29. import com.dmdirc.ui.messages.LinePosition;
  30. import com.dmdirc.ui.messages.StyledMessageUtils;
  31. import com.dmdirc.ui.messages.Styliser;
  32. import com.dmdirc.util.StringUtils;
  33. import com.dmdirc.util.URLBuilder;
  34. import java.awt.Adjustable;
  35. import java.awt.Color;
  36. import java.awt.Point;
  37. import java.awt.datatransfer.Clipboard;
  38. import java.awt.datatransfer.StringSelection;
  39. import java.awt.event.AdjustmentEvent;
  40. import java.awt.event.AdjustmentListener;
  41. import java.awt.event.InputEvent;
  42. import java.awt.event.MouseEvent;
  43. import java.awt.event.MouseMotionAdapter;
  44. import java.awt.event.MouseMotionListener;
  45. import java.awt.event.MouseWheelEvent;
  46. import java.awt.event.MouseWheelListener;
  47. import javax.swing.BoundedRangeModel;
  48. import javax.swing.DefaultBoundedRangeModel;
  49. import javax.swing.JComponent;
  50. import javax.swing.JLabel;
  51. import javax.swing.JLayer;
  52. import javax.swing.JScrollBar;
  53. import javax.swing.SwingConstants;
  54. import net.miginfocom.swing.MigLayout;
  55. import static com.google.common.base.Preconditions.checkArgument;
  56. /**
  57. * Styled, scrollable text pane.
  58. */
  59. public final class TextPane extends JComponent implements MouseWheelListener,
  60. AdjustmentListener, DocumentListener, ConfigChangeListener {
  61. /** A version number for this class. */
  62. private static final long serialVersionUID = 5;
  63. /** Scrollbar model. */
  64. private final BoundedRangeModel scrollModel;
  65. /** Canvas object, used to draw text. */
  66. private final TextPaneCanvas canvas;
  67. /** IRCDocument. */
  68. private final Document document;
  69. /** Parent window. */
  70. private final WindowModel window;
  71. /** Indicator to show whether new lines have been added. */
  72. private final JLabel newLineIndicator;
  73. /** Background painter. */
  74. private final BackgroundPainter backgroundPainter;
  75. /** The domain to read configuration from. */
  76. private final String configDomain;
  77. /** Clipboard to handle copy and paste cations. */
  78. private final Clipboard clipboard;
  79. /** Style utilities class. */
  80. private final StyledMessageUtils styleUtils;
  81. /** Last seen line. */
  82. private int lastSeenLine;
  83. /** Show new line notifications. */
  84. private boolean showNotification;
  85. /**
  86. * Creates a new instance of TextPane.
  87. *
  88. * @param configDomain The domain to read configuration from.
  89. * @param urlBuilder The builder to use to construct URLs for resources.
  90. * @param clipboard The clipboard to handle copy and paste actions
  91. * @param window Parent window
  92. */
  93. public TextPane(
  94. final String configDomain,
  95. final URLBuilder urlBuilder, final Clipboard clipboard,
  96. final WindowModel window) {
  97. this.window = window;
  98. this.configDomain = configDomain;
  99. this.clipboard = clipboard;
  100. styleUtils = new StyledMessageUtils(); // TODO: inject this
  101. setUI(new TextPaneUI());
  102. document = window.getBackBuffer().getDocument();
  103. newLineIndicator = new JLabel("", SwingConstants.CENTER);
  104. newLineIndicator.setBackground(Color.RED);
  105. newLineIndicator.setForeground(Color.WHITE);
  106. newLineIndicator.setOpaque(true);
  107. newLineIndicator.setVisible(false);
  108. setLayout(new MigLayout("fill, hidemode 3"));
  109. backgroundPainter = new BackgroundPainter(window.getConfigManager(),
  110. urlBuilder, configDomain, "textpanebackground",
  111. "textpanebackgroundoption", "textpanebackgroundopacity");
  112. canvas = new TextPaneCanvas(this,
  113. new CachingDocument<>(document, new AttributedStringMessageMaker()));
  114. final JLayer<JComponent> layer = new JLayer<>(canvas);
  115. layer.setUI(backgroundPainter);
  116. add(layer, "dock center");
  117. add(newLineIndicator, "dock south, center, grow");
  118. scrollModel = new DefaultBoundedRangeModel();
  119. scrollModel.setMaximum(0);
  120. scrollModel.setExtent(0);
  121. final JScrollBar scrollBar = new JScrollBar(Adjustable.VERTICAL);
  122. scrollBar.setModel(scrollModel);
  123. add(scrollBar, "dock east");
  124. scrollBar.addAdjustmentListener(this);
  125. scrollBar.addAdjustmentListener(canvas);
  126. window.getConfigManager().addChangeListener(configDomain, "textpanelinenotification", this);
  127. configChanged("", "textpanelinenotification");
  128. addMouseWheelListener(this);
  129. document.addIRCDocumentListener(this);
  130. setAutoscrolls(true);
  131. final MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
  132. @Override
  133. public void mouseDragged(final MouseEvent e) {
  134. if (e.getXOnScreen() > getLocationOnScreen().getX()
  135. && e.getXOnScreen() < getLocationOnScreen().getX() + getWidth()
  136. && e.getModifiersEx() == InputEvent.BUTTON1_DOWN_MASK) {
  137. if (getLocationOnScreen().getY() > e.getYOnScreen()) {
  138. scrollModel.setValue(scrollBar.getValue() - 1);
  139. } else if (getLocationOnScreen().getY() + getHeight()
  140. < e.getYOnScreen()) {
  141. scrollModel.setValue(scrollBar.getValue() + 1);
  142. }
  143. canvas.highlightEvent(MouseEventType.DRAG, e);
  144. }
  145. }
  146. };
  147. addMouseMotionListener(doScrollRectToVisible);
  148. setRangeProperties(document.getNumLines() - 1, document.getNumLines() - 1);
  149. }
  150. /**
  151. * Sets the range properties of the scroll model. This method takes into account the scroll
  152. * model working with 0 indexed line numbers.
  153. *
  154. * @param max Total number of lines
  155. * @param value Current line
  156. */
  157. private void setRangeProperties(final int max, final int value) {
  158. if (max == 1) {
  159. scrollModel.setRangeProperties(1, 0, 1, 1, false);
  160. } else {
  161. scrollModel.setRangeProperties(value, 0, 0, max - 1, false);
  162. }
  163. }
  164. @Override
  165. public void updateUI() {
  166. setUI(new TextPaneUI());
  167. }
  168. /**
  169. * Returns the last visible line in the TextPane.
  170. *
  171. * @return Last visible line index
  172. */
  173. public int getLastVisibleLine() {
  174. return scrollModel.getValue();
  175. }
  176. /**
  177. * Sets the new position for the scrollbar and the associated position to render the text from.
  178. *
  179. * @param position new position of the scrollbar
  180. */
  181. public void setScrollBarPosition(final int position) {
  182. scrollModel.setValue(position);
  183. }
  184. @Override
  185. public void adjustmentValueChanged(final AdjustmentEvent e) {
  186. if (showNotification && e.getValue() >= scrollModel.getMaximum()) {
  187. newLineIndicator.setVisible(false);
  188. }
  189. lastSeenLine = Math.max(lastSeenLine, e.getValue());
  190. final int lines = scrollModel.getMaximum() - lastSeenLine;
  191. newLineIndicator.setText("↓ " + lines + " new line"
  192. + (lines == 1 ? "" : "s") + " ↓");
  193. }
  194. @Override
  195. public void mouseWheelMoved(final MouseWheelEvent e) {
  196. if (e.getWheelRotation() > 0) {
  197. scrollModel.setValue(scrollModel.getValue() + e.getScrollAmount());
  198. } else {
  199. scrollModel.setValue(scrollModel.getValue() - e.getScrollAmount());
  200. }
  201. }
  202. /**
  203. *
  204. * Returns the line information from a mouse click inside the TextPane.
  205. *
  206. * @param point mouse position
  207. *
  208. * @return line number, line part, position in whole line
  209. */
  210. public LineInfo getClickPosition(final Point point) {
  211. return canvas.getClickPosition(point, true);
  212. }
  213. /**
  214. *
  215. * Returns the line information from a mouse click inside the TextPane.
  216. *
  217. * @param point mouse position
  218. * @param selection Are we selecting text?
  219. *
  220. * @return line number, line part, position in whole line
  221. *
  222. * @since 0.6.3
  223. */
  224. public LineInfo getClickPosition(final Point point,
  225. final boolean selection) {
  226. return canvas.getClickPosition(point, selection);
  227. }
  228. /**
  229. * Returns the selected text.
  230. *
  231. * @param styled Return styled text?
  232. *
  233. * @return Selected text
  234. */
  235. public String getSelectedText(final boolean styled) {
  236. final StringBuilder selectedText = new StringBuilder();
  237. final LinePosition selectedRange = canvas.getSelectedRange();
  238. if (selectedRange.getStartLine() == -1) {
  239. return null;
  240. }
  241. for (int i = selectedRange.getStartLine(); i <= selectedRange.getEndLine(); i++) {
  242. if (i != selectedRange.getStartLine()) {
  243. selectedText.append('\n');
  244. }
  245. if (scrollModel.getMaximum() < i) {
  246. return selectedText.toString();
  247. }
  248. final String line;
  249. if (styled) {
  250. line = document.getLine(i).getStyledText();
  251. } else {
  252. line = document.getLine(i).getText();
  253. }
  254. if (!line.isEmpty()) {
  255. if (selectedRange.getEndLine() == selectedRange.getStartLine()) {
  256. //loop through range
  257. if (selectedRange.getStartPos() != -1 && selectedRange.getEndPos() != -1) {
  258. selectedText.append(getText(line,
  259. selectedRange.getStartPos(),
  260. selectedRange.getEndPos(), styled));
  261. }
  262. } else if (i == selectedRange.getStartLine()) {
  263. //loop from start of range to the end
  264. final int length = styleUtils.stripControlCodes(line).length();
  265. if (selectedRange.getStartPos() != -1 && selectedRange.getStartPos() < length) {
  266. // Ensure that we're actually selecting some text on this line
  267. selectedText.append(getText(line, selectedRange.getStartPos(), length,
  268. styled));
  269. }
  270. } else if (i == selectedRange.getEndLine()) {
  271. //loop from start to end of range
  272. if (selectedRange.getEndPos() > 0) {
  273. selectedText.append(getText(line, 0, selectedRange.getEndPos(), styled));
  274. }
  275. } else {
  276. //loop the whole line
  277. final int length = styleUtils.stripControlCodes(line).length();
  278. selectedText.append(getText(line, 0, length, styled));
  279. }
  280. }
  281. }
  282. return selectedText.toString();
  283. }
  284. /**
  285. * Gets a range of text (styled or unstyled) from the given text.
  286. *
  287. * @param text Text to extract text from
  288. * @param start Start index
  289. * @param end End index
  290. * @param styled Styled text?
  291. *
  292. * @return Requested text range as a String
  293. */
  294. private String getText(final String text, final int start, final int end,
  295. final boolean styled) {
  296. checkArgument(start < end, "'start' (" + start + ") must be less than 'end' (" + end + ')');
  297. checkArgument(start >= 0, "'start' (" + start + ") must be non-negative");
  298. if (styled) {
  299. return styleUtils.getStyledText(text, start, end);
  300. } else {
  301. return text.substring(start, end);
  302. }
  303. }
  304. /**
  305. * Returns the selected range.
  306. *
  307. * @return selected range
  308. */
  309. public LinePosition getSelectedRange() {
  310. return canvas.getSelectedRange();
  311. }
  312. /**
  313. * Returns whether there is a selected range.
  314. *
  315. * @return true iif there is a selected range
  316. */
  317. public boolean hasSelectedRange() {
  318. final LinePosition selectedRange = canvas.getSelectedRange();
  319. return !(selectedRange.getStartLine() == selectedRange.getEndLine()
  320. && selectedRange.getStartPos() == selectedRange.getEndPos());
  321. }
  322. /**
  323. * Selects the specified region of text.
  324. *
  325. * @param position Line position
  326. */
  327. public void setSelectedText(final LinePosition position) {
  328. canvas.setSelectedRange(position);
  329. }
  330. /**
  331. * Returns the type of text this click represents.
  332. *
  333. * @param lineInfo Line info of click.
  334. *
  335. * @return Click type for specified position
  336. */
  337. public ClickTypeValue getClickType(final LineInfo lineInfo) {
  338. return canvas.getClickType(lineInfo);
  339. }
  340. /**
  341. * Returns the surrounding word at the specified position.
  342. *
  343. * @param lineNumber Line number to get word from
  344. * @param index Position to get surrounding word
  345. *
  346. * @return Surrounding word
  347. */
  348. public String getWordAtIndex(final int lineNumber, final int index) {
  349. if (lineNumber == -1) {
  350. return "";
  351. }
  352. final int[] indexes = StringUtils.indiciesOfWord(document.getLine(lineNumber).getText(),
  353. index);
  354. return document.getLine(lineNumber).getText().substring(indexes[0], indexes[1]);
  355. }
  356. /** Adds the selected text to the clipboard. */
  357. public void copy() {
  358. copy(false);
  359. }
  360. /**
  361. * Adds the selected text to the clipboard.
  362. *
  363. * @param copyControlCharacters Should we copy control codes, or strip them?
  364. */
  365. public void copy(final boolean copyControlCharacters) {
  366. if (getSelectedText(false) != null && !getSelectedText(false).isEmpty()) {
  367. clipboard.setContents(new StringSelection(getSelectedText(copyControlCharacters)), null);
  368. }
  369. }
  370. /** Clears the TextPane. */
  371. public void clear() {
  372. UIUtilities.invokeLater(document::clear);
  373. }
  374. /** Clears the selection. */
  375. public void clearSelection() {
  376. canvas.clearSelection();
  377. }
  378. /** Scrolls one page up in the TextPane. */
  379. public void pageDown() {
  380. scrollModel.setValue(scrollModel.getValue() + 10);
  381. }
  382. /** Scrolls one page down in the TextPane. */
  383. public void pageUp() {
  384. scrollModel.setValue(scrollModel.getValue() - 10);
  385. }
  386. /** Scrolls to the beginning of the TextPane. */
  387. public void goToHome() {
  388. scrollModel.setValue(0);
  389. }
  390. /** Scrolls to the end of the TextPane. */
  391. public void goToEnd() {
  392. scrollModel.setValue(scrollModel.getMaximum());
  393. }
  394. @Override
  395. public void trimmed(final int newSize, final int numTrimmed) {
  396. UIUtilities.invokeLater(() -> {
  397. lastSeenLine -= numTrimmed;
  398. final LinePosition selectedRange = getSelectedRange();
  399. selectedRange.setStartLine(selectedRange.getStartLine() - numTrimmed);
  400. selectedRange.setEndLine(selectedRange.getEndLine() - numTrimmed);
  401. if (selectedRange.getStartLine() < 0) {
  402. selectedRange.setStartLine(0);
  403. }
  404. if (selectedRange.getEndLine() < 0) {
  405. selectedRange.setEndLine(0);
  406. }
  407. setSelectedText(selectedRange);
  408. if (scrollModel.getValue() == scrollModel.getMaximum()) {
  409. setRangeProperties(newSize, newSize);
  410. } else {
  411. setRangeProperties(newSize, scrollModel.getValue() - numTrimmed);
  412. }
  413. });
  414. }
  415. @Override
  416. public void cleared() {
  417. UIUtilities.invokeLater(() -> {
  418. scrollModel.setMaximum(0);
  419. scrollModel.setValue(0);
  420. canvas.recalc();
  421. });
  422. }
  423. @Override
  424. public void linesAdded(final int line, final int length, final int size) {
  425. UIUtilities.invokeLater(() -> {
  426. if (scrollModel.getValue() == scrollModel.getMaximum()) {
  427. setRangeProperties(size, size);
  428. } else {
  429. setRangeProperties(size, scrollModel.getValue());
  430. if (showNotification) {
  431. newLineIndicator.setVisible(true);
  432. }
  433. }
  434. });
  435. }
  436. @Override
  437. public void repaintNeeded() {
  438. UIUtilities.invokeLater(canvas::recalc);
  439. }
  440. /**
  441. * Retrieves this TextPane's IRCDocument.
  442. *
  443. * @return This TextPane's IRC document
  444. */
  445. public Document getDocument() {
  446. return document;
  447. }
  448. /**
  449. * Retrieves the parent window for this TextPane.
  450. *
  451. * @return Parent window
  452. */
  453. public WindowModel getWindow() {
  454. return window;
  455. }
  456. /**
  457. * Adds a TextPane listener to this TextPane.
  458. *
  459. * @param listener Listener to add
  460. */
  461. public void addTextPaneListener(final TextPaneListener listener) {
  462. canvas.addTextPaneListener(listener);
  463. }
  464. /**
  465. * Removes a TextPane listener from this TextPane.
  466. *
  467. * @param listener Listener to remove
  468. */
  469. public void removeTextPaneListener(final TextPaneListener listener) {
  470. canvas.removeTextPaneListener(listener);
  471. }
  472. @Override
  473. public void configChanged(final String domain, final String key) {
  474. showNotification = window.getConfigManager().getOptionBool(configDomain, "textpanelinenotification");
  475. if (!showNotification) {
  476. UIUtilities.invokeLater(() -> newLineIndicator.setVisible(false));
  477. }
  478. }
  479. /**
  480. * Called to close this TextPane and any associated resources.
  481. */
  482. public void close() {
  483. backgroundPainter.unbind();
  484. }
  485. }