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

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