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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /*
  2. * Copyright (c) 2006-2014 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.SwingController;
  24. import com.dmdirc.addons.ui_swing.UIUtilities;
  25. import com.dmdirc.addons.ui_swing.components.frames.TextFrame;
  26. import com.dmdirc.interfaces.config.ConfigChangeListener;
  27. import com.dmdirc.interfaces.ui.Window;
  28. import com.dmdirc.plugins.PluginDomain;
  29. import com.dmdirc.ui.messages.IRCDocument;
  30. import com.dmdirc.ui.messages.IRCDocumentListener;
  31. import com.dmdirc.ui.messages.LinePosition;
  32. import com.dmdirc.ui.messages.Styliser;
  33. import com.dmdirc.util.URLBuilder;
  34. import com.dmdirc.util.annotations.factory.Factory;
  35. import com.dmdirc.util.annotations.factory.Unbound;
  36. import java.awt.Color;
  37. import java.awt.Point;
  38. import java.awt.Toolkit;
  39. import java.awt.datatransfer.StringSelection;
  40. import java.awt.event.AdjustmentEvent;
  41. import java.awt.event.AdjustmentListener;
  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.JComponent;
  49. import javax.swing.JLabel;
  50. import javax.swing.JScrollBar;
  51. import javax.swing.SwingConstants;
  52. import net.miginfocom.swing.MigLayout;
  53. import org.jdesktop.jxlayer.JXLayer;
  54. /**
  55. * Styled, scrollable text pane.
  56. */
  57. @Factory(inject = true, singleton = true)
  58. public final class TextPane extends JComponent implements MouseWheelListener,
  59. AdjustmentListener, IRCDocumentListener, ConfigChangeListener {
  60. /**
  61. * A version number for this class. It should be changed whenever the class structure is changed
  62. * (or anything else that would prevent serialized objects being unserialized with the new
  63. * class).
  64. */
  65. private static final long serialVersionUID = 5;
  66. /** Scrollbar model. */
  67. private final BoundedRangeModel scrollModel;
  68. /** Canvas object, used to draw text. */
  69. private final TextPaneCanvas canvas;
  70. /** IRCDocument. */
  71. private final IRCDocument document;
  72. /** Parent Frame. */
  73. private final Window frame;
  74. /** Indicator to show whether new lines have been added. */
  75. private final JLabel newLineIndicator;
  76. /** Background painter. */
  77. private final BackgroundPainter backgroundPainter;
  78. /** The domain to read configuration from. */
  79. private final String configDomain;
  80. /** Last seen line. */
  81. private int lastSeenLine = 0;
  82. /** Show new line notifications. */
  83. private boolean showNotification;
  84. /**
  85. * Creates a new instance of TextPane.
  86. *
  87. * @param configDomain The domain to read configuration from.
  88. * @param urlBuilder The builder to use to construct URLs for resources.
  89. * @param frame Parent Frame
  90. */
  91. public TextPane(
  92. @SuppressWarnings("qualifiers") @PluginDomain(SwingController.class) final String configDomain,
  93. final URLBuilder urlBuilder,
  94. @Unbound final TextFrame frame) {
  95. super();
  96. this.frame = frame;
  97. this.configDomain = configDomain;
  98. setUI(new TextPaneUI());
  99. document = frame.getContainer().getDocument();
  100. newLineIndicator = new JLabel("", SwingConstants.CENTER);
  101. newLineIndicator.setBackground(Color.RED);
  102. newLineIndicator.setForeground(Color.WHITE);
  103. newLineIndicator.setOpaque(true);
  104. newLineIndicator.setVisible(false);
  105. setLayout(new MigLayout("fill, hidemode 3"));
  106. backgroundPainter = new BackgroundPainter(frame.getContainer().getConfigManager(),
  107. urlBuilder, configDomain, "textpanebackground", "textpanebackgroundoption");
  108. canvas = new TextPaneCanvas(this, document);
  109. final JXLayer<JComponent> layer = new JXLayer<JComponent>(canvas);
  110. layer.setUI(backgroundPainter);
  111. add(layer, "dock center");
  112. add(newLineIndicator, "dock south, center, grow");
  113. scrollModel = new TextPaneBoundedRangeModel();
  114. scrollModel.setExtent(0);
  115. final JScrollBar scrollBar = new JScrollBar(JScrollBar.VERTICAL);
  116. scrollBar.setModel(scrollModel);
  117. add(scrollBar, "dock east");
  118. scrollBar.addAdjustmentListener(this);
  119. scrollBar.addAdjustmentListener(canvas);
  120. frame.getContainer().getConfigManager().addChangeListener(configDomain,
  121. "textpanelinenotification", this);
  122. configChanged("", "textpanelinenotification");
  123. addMouseWheelListener(this);
  124. document.addIRCDocumentListener(this);
  125. setAutoscrolls(true);
  126. final MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
  127. /** {@inheritDoc} */
  128. @Override
  129. public void mouseDragged(final MouseEvent e) {
  130. if (e.getXOnScreen() > getLocationOnScreen().getX()
  131. && e.getXOnScreen() < (getLocationOnScreen().getX()
  132. + getWidth()) && e.getModifiersEx()
  133. == MouseEvent.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. /** {@inheritDoc} */
  162. @Override
  163. public void updateUI() {
  164. setUI(new TextPaneUI());
  165. }
  166. /**
  167. * Returns the last visible line in the textpane.
  168. *
  169. * @return Last visible line index
  170. */
  171. public int getLastVisibleLine() {
  172. return scrollModel.getValue();
  173. }
  174. /**
  175. * Sets the new position for the scrollbar and the associated position to render the text from.
  176. *
  177. * @param position new position of the scrollbar
  178. */
  179. public void setScrollBarPosition(final int position) {
  180. scrollModel.setValue(position);
  181. }
  182. /**
  183. * {@inheritDoc}
  184. *
  185. * @param e Mouse wheel event
  186. */
  187. @Override
  188. public void adjustmentValueChanged(final AdjustmentEvent e) {
  189. if (showNotification && e.getValue() >= scrollModel.getMaximum()) {
  190. newLineIndicator.setVisible(false);
  191. }
  192. lastSeenLine = Math.max(lastSeenLine, e.getValue());
  193. final int lines = scrollModel.getMaximum() - lastSeenLine;
  194. newLineIndicator.setText("↓ " + lines + " new line"
  195. + (lines == 1 ? "" : "s") + " ↓");
  196. }
  197. /**
  198. * {@inheritDoc}
  199. *
  200. * @param e Mouse wheel event
  201. */
  202. @Override
  203. public void mouseWheelMoved(final MouseWheelEvent e) {
  204. if (e.getWheelRotation() > 0) {
  205. scrollModel.setValue(scrollModel.getValue() + e.getScrollAmount());
  206. } else {
  207. scrollModel.setValue(scrollModel.getValue() - e.getScrollAmount());
  208. }
  209. }
  210. /**
  211. *
  212. * Returns the line information from a mouse click inside the textpane.
  213. *
  214. * @param point mouse position
  215. *
  216. * @return line number, line part, position in whole line
  217. */
  218. public LineInfo getClickPosition(final Point point) {
  219. return canvas.getClickPosition(point, true);
  220. }
  221. /**
  222. *
  223. * Returns the line information from a mouse click inside the textpane.
  224. *
  225. * @param point mouse position
  226. * @param selection Are we selecting text?
  227. *
  228. * @return line number, line part, position in whole line
  229. *
  230. * @since 0.6.3
  231. */
  232. public LineInfo getClickPosition(final Point point,
  233. final boolean selection) {
  234. return canvas.getClickPosition(point, selection);
  235. }
  236. /**
  237. * Returns the selected text.
  238. *
  239. * @return Selected text
  240. */
  241. public String getSelectedText() {
  242. return getSelectedText(false);
  243. }
  244. /**
  245. * Returns the selected text.
  246. *
  247. * @return Selected text
  248. */
  249. public String getStyledSelectedText() {
  250. return getSelectedText(true);
  251. }
  252. /**
  253. * Returns the selected text.
  254. *
  255. * @param styled Return styled text?
  256. *
  257. * @return Selected text
  258. */
  259. public String getSelectedText(final boolean styled) {
  260. final StringBuffer selectedText = new StringBuffer();
  261. final LinePosition selectedRange = canvas.getSelectedRange();
  262. if (selectedRange.getStartLine() == -1) {
  263. return null;
  264. }
  265. for (int i = selectedRange.getStartLine(); i
  266. <= selectedRange.getEndLine(); i++) {
  267. if (i != selectedRange.getStartLine()) {
  268. selectedText.append('\n');
  269. }
  270. if (scrollModel.getMaximum() < i) {
  271. return selectedText.toString();
  272. }
  273. final String line;
  274. if (styled) {
  275. line = document.getLine(i).getStyledText();
  276. } else {
  277. line = document.getLine(i).getText();
  278. }
  279. if (!line.isEmpty()) {
  280. if (selectedRange.getEndLine()
  281. == selectedRange.getStartLine()) {
  282. //loop through range
  283. if (selectedRange.getStartPos() != -1 && selectedRange.
  284. getEndPos() != -1) {
  285. selectedText.append(getText(line,
  286. selectedRange.getStartPos(),
  287. selectedRange.getEndPos(), styled));
  288. }
  289. } else if (i == selectedRange.getStartLine()) {
  290. //loop from start of range to the end
  291. if (selectedRange.getStartPos() != -1) {
  292. selectedText.append(getText(line,
  293. selectedRange.getStartPos(),
  294. Styliser.stipControlCodes(line).length(), styled));
  295. }
  296. } else if (i == selectedRange.getEndLine()) {
  297. //loop from start to end of range
  298. if (selectedRange.getEndPos() != -1) {
  299. selectedText.append(getText(line, 0, selectedRange
  300. .getEndPos(), styled));
  301. }
  302. } else {
  303. //loop the whole line
  304. selectedText.append(getText(line, 0, line.length(),
  305. styled));
  306. }
  307. }
  308. }
  309. return selectedText.toString();
  310. }
  311. /**
  312. * Gets a range of text (styled or unstyled) from the given text.
  313. *
  314. * @param text Text to extract text from
  315. * @param start Start index
  316. * @param end End index
  317. * @param styled Styled text?
  318. *
  319. * @return Requested text range as a String
  320. */
  321. private String getText(final String text, final int start, final int end,
  322. final boolean styled) {
  323. if (styled) {
  324. return Styliser.getStyledText(text, start, end);
  325. } else {
  326. return text.substring(start, end);
  327. }
  328. }
  329. /**
  330. * Returns the selected range.
  331. *
  332. * @return selected range
  333. */
  334. public LinePosition getSelectedRange() {
  335. return canvas.getSelectedRange();
  336. }
  337. /**
  338. * Returns whether there is a selected range.
  339. *
  340. * @return true iif there is a selected range
  341. */
  342. public boolean hasSelectedRange() {
  343. final LinePosition selectedRange = canvas.getSelectedRange();
  344. return !(selectedRange.getStartLine() == selectedRange.getEndLine()
  345. && selectedRange.getStartPos() == selectedRange.getEndPos());
  346. }
  347. /**
  348. * Selects the specified region of text.
  349. *
  350. * @param position Line position
  351. */
  352. public void setSelectedTexT(final LinePosition position) {
  353. canvas.setSelectedRange(position);
  354. }
  355. /**
  356. * Returns the type of text this click represents.
  357. *
  358. * @param lineInfo Line info of click.
  359. *
  360. * @return Click type for specified position
  361. */
  362. public ClickTypeValue getClickType(final LineInfo lineInfo) {
  363. return canvas.getClickType(lineInfo);
  364. }
  365. /**
  366. * Returns the surrouding word at the specified position.
  367. *
  368. * @param lineNumber Line number to get word from
  369. * @param index Position to get surrounding word
  370. *
  371. * @return Surrounding word
  372. */
  373. public String getWordAtIndex(final int lineNumber, final int index) {
  374. if (lineNumber == -1) {
  375. return "";
  376. }
  377. final int[] indexes = canvas.getSurroundingWordIndexes(document
  378. .getLine(lineNumber).getText(), index);
  379. return document.getLine(lineNumber).getText().substring(indexes[0],
  380. indexes[1]);
  381. }
  382. /** Adds the selected text to the clipboard. */
  383. public void copy() {
  384. copy(false);
  385. }
  386. /**
  387. * Adds the selected text to the clipboard.
  388. *
  389. * @param copyControlCharacters Should we copy control codes, or strip them?
  390. */
  391. public void copy(final boolean copyControlCharacters) {
  392. if (getSelectedText() != null && !getSelectedText().isEmpty()) {
  393. Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
  394. new StringSelection(getSelectedText(
  395. copyControlCharacters)), null);
  396. }
  397. }
  398. /** Clears the textpane. */
  399. public void clear() {
  400. UIUtilities.invokeLater(new Runnable() {
  401. /** {@inheritDoc}. */
  402. @Override
  403. public void run() {
  404. document.clear();
  405. }
  406. });
  407. }
  408. /** Clears the selection. */
  409. public void clearSelection() {
  410. canvas.clearSelection();
  411. }
  412. /** Scrolls one page up in the textpane. */
  413. public void pageDown() {
  414. scrollModel.setValue(scrollModel.getValue() + 10);
  415. }
  416. /** Scrolls one page down in the textpane. */
  417. public void pageUp() {
  418. scrollModel.setValue(scrollModel.getValue() - 10);
  419. }
  420. /** Scrolls to the beginning of the TextPane. */
  421. public void goToHome() {
  422. scrollModel.setValue(0);
  423. }
  424. /** Scrolls to the end of the TextPane. */
  425. public void goToEnd() {
  426. scrollModel.setValue(scrollModel.getMaximum());
  427. }
  428. /** {@inheritDoc}. */
  429. @Override
  430. public void trimmed(final int newSize, final int numTrimmed) {
  431. UIUtilities.invokeLater(new Runnable() {
  432. /** {@inheritDoc}. */
  433. @Override
  434. public void run() {
  435. lastSeenLine -= numTrimmed;
  436. final LinePosition selectedRange = getSelectedRange();
  437. selectedRange.setStartLine(selectedRange.getStartLine()
  438. - numTrimmed);
  439. selectedRange.setEndLine(selectedRange.getEndLine()
  440. - numTrimmed);
  441. if (selectedRange.getStartLine() < 0) {
  442. selectedRange.setStartLine(0);
  443. }
  444. if (selectedRange.getEndLine() < 0) {
  445. selectedRange.setEndLine(0);
  446. }
  447. setSelectedTexT(selectedRange);
  448. if (scrollModel.getValue() == scrollModel.getMaximum()) {
  449. setRangeProperties(newSize, newSize);
  450. } else {
  451. setRangeProperties(newSize, scrollModel.getValue()
  452. - numTrimmed);
  453. }
  454. }
  455. });
  456. }
  457. /** {@inheritDoc}. */
  458. @Override
  459. public void cleared() {
  460. UIUtilities.invokeLater(new Runnable() {
  461. /** {@inheritDoc}. */
  462. @Override
  463. public void run() {
  464. scrollModel.setMaximum(0);
  465. scrollModel.setValue(0);
  466. canvas.recalc();
  467. }
  468. });
  469. }
  470. /** {@inheritDoc}. */
  471. @Override
  472. public void linesAdded(final int line, final int length, final int size) {
  473. UIUtilities.invokeLater(new Runnable() {
  474. /** {@inheritDoc}. */
  475. @Override
  476. public void run() {
  477. if (scrollModel.getValue() == scrollModel.getMaximum()) {
  478. setRangeProperties(size, size);
  479. } else {
  480. setRangeProperties(size, scrollModel.getValue());
  481. if (showNotification) {
  482. newLineIndicator.setVisible(true);
  483. }
  484. }
  485. }
  486. });
  487. }
  488. /** {@inheritDoc}. */
  489. @Override
  490. public void repaintNeeded() {
  491. UIUtilities.invokeLater(new Runnable() {
  492. /** {@inheritDoc}. */
  493. @Override
  494. public void run() {
  495. canvas.recalc();
  496. }
  497. });
  498. }
  499. /**
  500. * Retrieves this textpane's IRCDocument.
  501. *
  502. * @return This textpane's IRC document
  503. */
  504. public IRCDocument getDocument() {
  505. return document;
  506. }
  507. /**
  508. * Retrives the parent window for this textpane.
  509. *
  510. * @return Parent window
  511. */
  512. public Window getWindow() {
  513. return frame;
  514. }
  515. /**
  516. * Adds a textpane listener to this textpane.
  517. *
  518. * @param listener Listener to add
  519. */
  520. public void addTextPaneListener(final TextPaneListener listener) {
  521. canvas.addTextPaneListener(listener);
  522. }
  523. /**
  524. * Removes a textpane listener from this textpane.
  525. *
  526. * @param listener Listener to remove
  527. */
  528. public void removeTextPaneListener(final TextPaneListener listener) {
  529. canvas.removeTextPaneListener(listener);
  530. }
  531. /** {@inheritDoc} */
  532. @Override
  533. public void configChanged(final String domain, final String key) {
  534. showNotification = frame.getContainer().getConfigManager()
  535. .getOptionBool(configDomain, "textpanelinenotification");
  536. if (!showNotification) {
  537. UIUtilities.invokeLater(new Runnable() {
  538. /** {@inheritDoc}. */
  539. @Override
  540. public void run() {
  541. newLineIndicator.setVisible(false);
  542. }
  543. });
  544. }
  545. }
  546. /**
  547. * Called to close this textpane and any associated resources.
  548. */
  549. public void close() {
  550. backgroundPainter.unbind();
  551. }
  552. }