Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TextPane.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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.config.ConfigChangeListener;
  25. import com.dmdirc.interfaces.ui.Window;
  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 Frame. */
  69. private final Window frame;
  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 frame Parent Frame
  89. */
  90. public TextPane(
  91. final String configDomain,
  92. final URLBuilder urlBuilder, final Clipboard clipboard,
  93. final Window frame) {
  94. this.frame = frame;
  95. this.configDomain = configDomain;
  96. this.clipboard = clipboard;
  97. setUI(new TextPaneUI());
  98. document = frame.getContainer().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(frame.getContainer().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. frame.getContainer().getConfigManager().addChangeListener(configDomain,
  123. "textpanelinenotification", this);
  124. configChanged("", "textpanelinenotification");
  125. addMouseWheelListener(this);
  126. document.addIRCDocumentListener(this);
  127. setAutoscrolls(true);
  128. final MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
  129. @Override
  130. public void mouseDragged(final MouseEvent e) {
  131. if (e.getXOnScreen() > getLocationOnScreen().getX()
  132. && e.getXOnScreen() < getLocationOnScreen().getX() + getWidth()
  133. && e.getModifiersEx() == InputEvent.BUTTON1_DOWN_MASK) {
  134. if (getLocationOnScreen().getY() > e.getYOnScreen()) {
  135. scrollModel.setValue(scrollBar.getValue() - 1);
  136. } else if (getLocationOnScreen().getY() + getHeight()
  137. < e.getYOnScreen()) {
  138. scrollModel.setValue(scrollBar.getValue() + 1);
  139. }
  140. canvas.highlightEvent(MouseEventType.DRAG, e);
  141. }
  142. }
  143. };
  144. addMouseMotionListener(doScrollRectToVisible);
  145. setRangeProperties(document.getNumLines() - 1, document.getNumLines() - 1);
  146. }
  147. /**
  148. * Sets the range properties of the scroll model. This method takes into account the scroll
  149. * model working with 0 indexed line numbers.
  150. *
  151. * @param max Total number of lines
  152. * @param value Current line
  153. */
  154. private void setRangeProperties(final int max, final int value) {
  155. if (max == 1) {
  156. scrollModel.setRangeProperties(1, 0, 1, 1, false);
  157. } else {
  158. scrollModel.setRangeProperties(value, 0, 0, max - 1, false);
  159. }
  160. }
  161. @Override
  162. public void updateUI() {
  163. setUI(new TextPaneUI());
  164. }
  165. /**
  166. * Returns the last visible line in the TextPane.
  167. *
  168. * @return Last visible line index
  169. */
  170. public int getLastVisibleLine() {
  171. return scrollModel.getValue();
  172. }
  173. /**
  174. * Sets the new position for the scrollbar and the associated position to render the text from.
  175. *
  176. * @param position new position of the scrollbar
  177. */
  178. public void setScrollBarPosition(final int position) {
  179. scrollModel.setValue(position);
  180. }
  181. @Override
  182. public void adjustmentValueChanged(final AdjustmentEvent e) {
  183. if (showNotification && e.getValue() >= scrollModel.getMaximum()) {
  184. newLineIndicator.setVisible(false);
  185. }
  186. lastSeenLine = Math.max(lastSeenLine, e.getValue());
  187. final int lines = scrollModel.getMaximum() - lastSeenLine;
  188. newLineIndicator.setText("↓ " + lines + " new line"
  189. + (lines == 1 ? "" : "s") + " ↓");
  190. }
  191. @Override
  192. public void mouseWheelMoved(final MouseWheelEvent e) {
  193. if (e.getWheelRotation() > 0) {
  194. scrollModel.setValue(scrollModel.getValue() + e.getScrollAmount());
  195. } else {
  196. scrollModel.setValue(scrollModel.getValue() - e.getScrollAmount());
  197. }
  198. }
  199. /**
  200. *
  201. * Returns the line information from a mouse click inside the TextPane.
  202. *
  203. * @param point mouse position
  204. *
  205. * @return line number, line part, position in whole line
  206. */
  207. public LineInfo getClickPosition(final Point point) {
  208. return canvas.getClickPosition(point, true);
  209. }
  210. /**
  211. *
  212. * Returns the line information from a mouse click inside the TextPane.
  213. *
  214. * @param point mouse position
  215. * @param selection Are we selecting text?
  216. *
  217. * @return line number, line part, position in whole line
  218. *
  219. * @since 0.6.3
  220. */
  221. public LineInfo getClickPosition(final Point point,
  222. final boolean selection) {
  223. return canvas.getClickPosition(point, selection);
  224. }
  225. /**
  226. * Returns the selected text.
  227. *
  228. * @param styled Return styled text?
  229. *
  230. * @return Selected text
  231. */
  232. public String getSelectedText(final boolean styled) {
  233. final StringBuilder selectedText = new StringBuilder();
  234. final LinePosition selectedRange = canvas.getSelectedRange();
  235. if (selectedRange.getStartLine() == -1) {
  236. return null;
  237. }
  238. for (int i = selectedRange.getStartLine(); i <= selectedRange.getEndLine(); i++) {
  239. if (i != selectedRange.getStartLine()) {
  240. selectedText.append('\n');
  241. }
  242. if (scrollModel.getMaximum() < i) {
  243. return selectedText.toString();
  244. }
  245. final String line;
  246. if (styled) {
  247. line = document.getLine(i).getStyledText();
  248. } else {
  249. line = document.getLine(i).getText();
  250. }
  251. if (!line.isEmpty()) {
  252. if (selectedRange.getEndLine() == selectedRange.getStartLine()) {
  253. //loop through range
  254. if (selectedRange.getStartPos() != -1 && selectedRange.getEndPos() != -1) {
  255. selectedText.append(getText(line,
  256. selectedRange.getStartPos(),
  257. selectedRange.getEndPos(), styled));
  258. }
  259. } else if (i == selectedRange.getStartLine()) {
  260. //loop from start of range to the end
  261. final int length = Styliser.stipControlCodes(line).length();
  262. if (selectedRange.getStartPos() != -1 && selectedRange.getStartPos() < length) {
  263. // Ensure that we're actually selecting some text on this line
  264. selectedText.append(getText(line, selectedRange.getStartPos(), length,
  265. styled));
  266. }
  267. } else if (i == selectedRange.getEndLine()) {
  268. //loop from start to end of range
  269. if (selectedRange.getEndPos() > 0) {
  270. selectedText.append(getText(line, 0, selectedRange.getEndPos(), styled));
  271. }
  272. } else {
  273. //loop the whole line
  274. final int length = Styliser.stipControlCodes(line).length();
  275. selectedText.append(getText(line, 0, length, styled));
  276. }
  277. }
  278. }
  279. return selectedText.toString();
  280. }
  281. /**
  282. * Gets a range of text (styled or unstyled) from the given text.
  283. *
  284. * @param text Text to extract text from
  285. * @param start Start index
  286. * @param end End index
  287. * @param styled Styled text?
  288. *
  289. * @return Requested text range as a String
  290. */
  291. private String getText(final String text, final int start, final int end,
  292. final boolean styled) {
  293. checkArgument(start < end, "'start' (" + start + ") must be less than 'end' (" + end + ')');
  294. checkArgument(start >= 0, "'start' (" + start + ") must be non-negative");
  295. if (styled) {
  296. return Styliser.getStyledText(text, start, end);
  297. } else {
  298. return text.substring(start, end);
  299. }
  300. }
  301. /**
  302. * Returns the selected range.
  303. *
  304. * @return selected range
  305. */
  306. public LinePosition getSelectedRange() {
  307. return canvas.getSelectedRange();
  308. }
  309. /**
  310. * Returns whether there is a selected range.
  311. *
  312. * @return true iif there is a selected range
  313. */
  314. public boolean hasSelectedRange() {
  315. final LinePosition selectedRange = canvas.getSelectedRange();
  316. return !(selectedRange.getStartLine() == selectedRange.getEndLine()
  317. && selectedRange.getStartPos() == selectedRange.getEndPos());
  318. }
  319. /**
  320. * Selects the specified region of text.
  321. *
  322. * @param position Line position
  323. */
  324. public void setSelectedText(final LinePosition position) {
  325. canvas.setSelectedRange(position);
  326. }
  327. /**
  328. * Returns the type of text this click represents.
  329. *
  330. * @param lineInfo Line info of click.
  331. *
  332. * @return Click type for specified position
  333. */
  334. public ClickTypeValue getClickType(final LineInfo lineInfo) {
  335. return canvas.getClickType(lineInfo);
  336. }
  337. /**
  338. * Returns the surrounding word at the specified position.
  339. *
  340. * @param lineNumber Line number to get word from
  341. * @param index Position to get surrounding word
  342. *
  343. * @return Surrounding word
  344. */
  345. public String getWordAtIndex(final int lineNumber, final int index) {
  346. if (lineNumber == -1) {
  347. return "";
  348. }
  349. final int[] indexes = StringUtils.indiciesOfWord(document.getLine(lineNumber).getText(),
  350. index);
  351. return document.getLine(lineNumber).getText().substring(indexes[0], indexes[1]);
  352. }
  353. /** Adds the selected text to the clipboard. */
  354. public void copy() {
  355. copy(false);
  356. }
  357. /**
  358. * Adds the selected text to the clipboard.
  359. *
  360. * @param copyControlCharacters Should we copy control codes, or strip them?
  361. */
  362. public void copy(final boolean copyControlCharacters) {
  363. if (getSelectedText(false) != null && !getSelectedText(false).isEmpty()) {
  364. clipboard.setContents(new StringSelection(getSelectedText(copyControlCharacters)), null);
  365. }
  366. }
  367. /** Clears the TextPane. */
  368. public void clear() {
  369. UIUtilities.invokeLater(document::clear);
  370. }
  371. /** Clears the selection. */
  372. public void clearSelection() {
  373. canvas.clearSelection();
  374. }
  375. /** Scrolls one page up in the TextPane. */
  376. public void pageDown() {
  377. scrollModel.setValue(scrollModel.getValue() + 10);
  378. }
  379. /** Scrolls one page down in the TextPane. */
  380. public void pageUp() {
  381. scrollModel.setValue(scrollModel.getValue() - 10);
  382. }
  383. /** Scrolls to the beginning of the TextPane. */
  384. public void goToHome() {
  385. scrollModel.setValue(0);
  386. }
  387. /** Scrolls to the end of the TextPane. */
  388. public void goToEnd() {
  389. scrollModel.setValue(scrollModel.getMaximum());
  390. }
  391. @Override
  392. public void trimmed(final int newSize, final int numTrimmed) {
  393. UIUtilities.invokeLater(() -> {
  394. lastSeenLine -= numTrimmed;
  395. final LinePosition selectedRange = getSelectedRange();
  396. selectedRange.setStartLine(selectedRange.getStartLine() - numTrimmed);
  397. selectedRange.setEndLine(selectedRange.getEndLine() - numTrimmed);
  398. if (selectedRange.getStartLine() < 0) {
  399. selectedRange.setStartLine(0);
  400. }
  401. if (selectedRange.getEndLine() < 0) {
  402. selectedRange.setEndLine(0);
  403. }
  404. setSelectedText(selectedRange);
  405. if (scrollModel.getValue() == scrollModel.getMaximum()) {
  406. setRangeProperties(newSize, newSize);
  407. } else {
  408. setRangeProperties(newSize, scrollModel.getValue() - numTrimmed);
  409. }
  410. });
  411. }
  412. @Override
  413. public void cleared() {
  414. UIUtilities.invokeLater(() -> {
  415. scrollModel.setMaximum(0);
  416. scrollModel.setValue(0);
  417. canvas.recalc();
  418. });
  419. }
  420. @Override
  421. public void linesAdded(final int line, final int length, final int size) {
  422. UIUtilities.invokeLater(() -> {
  423. if (scrollModel.getValue() == scrollModel.getMaximum()) {
  424. setRangeProperties(size, size);
  425. } else {
  426. setRangeProperties(size, scrollModel.getValue());
  427. if (showNotification) {
  428. newLineIndicator.setVisible(true);
  429. }
  430. }
  431. });
  432. }
  433. @Override
  434. public void repaintNeeded() {
  435. UIUtilities.invokeLater(canvas::recalc);
  436. }
  437. /**
  438. * Retrieves this TextPane's IRCDocument.
  439. *
  440. * @return This TextPane's IRC document
  441. */
  442. public IRCDocument getDocument() {
  443. return document;
  444. }
  445. /**
  446. * Retrieves the parent window for this TextPane.
  447. *
  448. * @return Parent window
  449. */
  450. public Window getWindow() {
  451. return frame;
  452. }
  453. /**
  454. * Adds a TextPane listener to this TextPane.
  455. *
  456. * @param listener Listener to add
  457. */
  458. public void addTextPaneListener(final TextPaneListener listener) {
  459. canvas.addTextPaneListener(listener);
  460. }
  461. /**
  462. * Removes a TextPane listener from this TextPane.
  463. *
  464. * @param listener Listener to remove
  465. */
  466. public void removeTextPaneListener(final TextPaneListener listener) {
  467. canvas.removeTextPaneListener(listener);
  468. }
  469. @Override
  470. public void configChanged(final String domain, final String key) {
  471. showNotification = frame.getContainer().getConfigManager()
  472. .getOptionBool(configDomain, "textpanelinenotification");
  473. if (!showNotification) {
  474. UIUtilities.invokeLater(() -> newLineIndicator.setVisible(false));
  475. }
  476. }
  477. /**
  478. * Called to close this TextPane and any associated resources.
  479. */
  480. public void close() {
  481. backgroundPainter.unbind();
  482. }
  483. }