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

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