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

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