Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TextPane.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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.DMDircMBassador;
  24. import com.dmdirc.addons.ui_swing.UIUtilities;
  25. import com.dmdirc.interfaces.config.ConfigChangeListener;
  26. import com.dmdirc.interfaces.ui.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 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.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. public final class TextPane extends JComponent implements MouseWheelListener,
  58. AdjustmentListener, IRCDocumentListener, ConfigChangeListener {
  59. /** A version number for this class. */
  60. private static final long serialVersionUID = 5;
  61. /** Scrollbar model. */
  62. private final BoundedRangeModel scrollModel;
  63. /** Canvas object, used to draw text. */
  64. private final TextPaneCanvas canvas;
  65. /** IRCDocument. */
  66. private final IRCDocument document;
  67. /** Parent Frame. */
  68. private final Window frame;
  69. /** Indicator to show whether new lines have been added. */
  70. private final JLabel newLineIndicator;
  71. /** Background painter. */
  72. private final BackgroundPainter backgroundPainter;
  73. /** The domain to read configuration from. */
  74. private final String configDomain;
  75. /** Clipboard to handle copy and paste cations. */
  76. private final Clipboard clipboard;
  77. /** Last seen line. */
  78. private int lastSeenLine;
  79. /** Show new line notifications. */
  80. private boolean showNotification;
  81. /**
  82. * Creates a new instance of TextPane.
  83. *
  84. * @param eventBus The event bus to post errors to.
  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 DMDircMBassador eventBus,
  92. final String configDomain,
  93. final URLBuilder urlBuilder, final Clipboard clipboard,
  94. final Window frame) {
  95. this.frame = frame;
  96. this.configDomain = configDomain;
  97. this.clipboard = clipboard;
  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, eventBus, configDomain, "textpanebackground",
  108. "textpanebackgroundoption");
  109. canvas = new TextPaneCanvas(this, document);
  110. final JXLayer<JComponent> layer = new JXLayer<JComponent>(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. if (selectedRange.getStartPos() != -1) {
  262. selectedText.append(getText(line, selectedRange.getStartPos(),
  263. Styliser.stipControlCodes(line).length(), styled));
  264. }
  265. } else if (i == selectedRange.getEndLine()) {
  266. //loop from start to end of range
  267. if (selectedRange.getEndPos() != -1) {
  268. selectedText.append(getText(line, 0, selectedRange .getEndPos(), styled));
  269. }
  270. } else {
  271. //loop the whole line
  272. selectedText.append(getText(line, 0, line.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. if (styled) {
  291. return Styliser.getStyledText(text, start, end);
  292. } else {
  293. return text.substring(start, end);
  294. }
  295. }
  296. /**
  297. * Returns the selected range.
  298. *
  299. * @return selected range
  300. */
  301. public LinePosition getSelectedRange() {
  302. return canvas.getSelectedRange();
  303. }
  304. /**
  305. * Returns whether there is a selected range.
  306. *
  307. * @return true iif there is a selected range
  308. */
  309. public boolean hasSelectedRange() {
  310. final LinePosition selectedRange = canvas.getSelectedRange();
  311. return !(selectedRange.getStartLine() == selectedRange.getEndLine()
  312. && selectedRange.getStartPos() == selectedRange.getEndPos());
  313. }
  314. /**
  315. * Selects the specified region of text.
  316. *
  317. * @param position Line position
  318. */
  319. public void setSelectedText(final LinePosition position) {
  320. canvas.setSelectedRange(position);
  321. }
  322. /**
  323. * Returns the type of text this click represents.
  324. *
  325. * @param lineInfo Line info of click.
  326. *
  327. * @return Click type for specified position
  328. */
  329. public ClickTypeValue getClickType(final LineInfo lineInfo) {
  330. return canvas.getClickType(lineInfo);
  331. }
  332. /**
  333. * Returns the surrounding word at the specified position.
  334. *
  335. * @param lineNumber Line number to get word from
  336. * @param index Position to get surrounding word
  337. *
  338. * @return Surrounding word
  339. */
  340. public String getWordAtIndex(final int lineNumber, final int index) {
  341. if (lineNumber == -1) {
  342. return "";
  343. }
  344. final int[] indexes = StringUtils.indiciesOfWord(document.getLine(lineNumber).getText(),
  345. index);
  346. return document.getLine(lineNumber).getText().substring(indexes[0], indexes[1]);
  347. }
  348. /** Adds the selected text to the clipboard. */
  349. public void copy() {
  350. copy(false);
  351. }
  352. /**
  353. * Adds the selected text to the clipboard.
  354. *
  355. * @param copyControlCharacters Should we copy control codes, or strip them?
  356. */
  357. public void copy(final boolean copyControlCharacters) {
  358. if (getSelectedText(false) != null && !getSelectedText(false).isEmpty()) {
  359. clipboard.setContents(new StringSelection(getSelectedText(copyControlCharacters)), null);
  360. }
  361. }
  362. /** Clears the TextPane. */
  363. public void clear() {
  364. UIUtilities.invokeLater(document::clear);
  365. }
  366. /** Clears the selection. */
  367. public void clearSelection() {
  368. canvas.clearSelection();
  369. }
  370. /** Scrolls one page up in the TextPane. */
  371. public void pageDown() {
  372. scrollModel.setValue(scrollModel.getValue() + 10);
  373. }
  374. /** Scrolls one page down in the TextPane. */
  375. public void pageUp() {
  376. scrollModel.setValue(scrollModel.getValue() - 10);
  377. }
  378. /** Scrolls to the beginning of the TextPane. */
  379. public void goToHome() {
  380. scrollModel.setValue(0);
  381. }
  382. /** Scrolls to the end of the TextPane. */
  383. public void goToEnd() {
  384. scrollModel.setValue(scrollModel.getMaximum());
  385. }
  386. @Override
  387. public void trimmed(final int newSize, final int numTrimmed) {
  388. UIUtilities.invokeLater(() -> {
  389. lastSeenLine -= numTrimmed;
  390. final LinePosition selectedRange = getSelectedRange();
  391. selectedRange.setStartLine(selectedRange.getStartLine() - numTrimmed);
  392. selectedRange.setEndLine(selectedRange.getEndLine() - numTrimmed);
  393. if (selectedRange.getStartLine() < 0) {
  394. selectedRange.setStartLine(0);
  395. }
  396. if (selectedRange.getEndLine() < 0) {
  397. selectedRange.setEndLine(0);
  398. }
  399. setSelectedText(selectedRange);
  400. if (scrollModel.getValue() == scrollModel.getMaximum()) {
  401. setRangeProperties(newSize, newSize);
  402. } else {
  403. setRangeProperties(newSize, scrollModel.getValue() - numTrimmed);
  404. }
  405. });
  406. }
  407. @Override
  408. public void cleared() {
  409. UIUtilities.invokeLater(() -> {
  410. scrollModel.setMaximum(0);
  411. scrollModel.setValue(0);
  412. canvas.recalc();
  413. });
  414. }
  415. @Override
  416. public void linesAdded(final int line, final int length, final int size) {
  417. UIUtilities.invokeLater(() -> {
  418. if (scrollModel.getValue() == scrollModel.getMaximum()) {
  419. setRangeProperties(size, size);
  420. } else {
  421. setRangeProperties(size, scrollModel.getValue());
  422. if (showNotification) {
  423. newLineIndicator.setVisible(true);
  424. }
  425. }
  426. });
  427. }
  428. @Override
  429. public void repaintNeeded() {
  430. UIUtilities.invokeLater(canvas::recalc);
  431. }
  432. /**
  433. * Retrieves this TextPane's IRCDocument.
  434. *
  435. * @return This TextPane's IRC document
  436. */
  437. public IRCDocument getDocument() {
  438. return document;
  439. }
  440. /**
  441. * Retrieves the parent window for this TextPane.
  442. *
  443. * @return Parent window
  444. */
  445. public Window getWindow() {
  446. return frame;
  447. }
  448. /**
  449. * Adds a TextPane listener to this TextPane.
  450. *
  451. * @param listener Listener to add
  452. */
  453. public void addTextPaneListener(final TextPaneListener listener) {
  454. canvas.addTextPaneListener(listener);
  455. }
  456. /**
  457. * Removes a TextPane listener from this TextPane.
  458. *
  459. * @param listener Listener to remove
  460. */
  461. public void removeTextPaneListener(final TextPaneListener listener) {
  462. canvas.removeTextPaneListener(listener);
  463. }
  464. @Override
  465. public void configChanged(final String domain, final String key) {
  466. showNotification = frame.getContainer().getConfigManager()
  467. .getOptionBool(configDomain, "textpanelinenotification");
  468. if (!showNotification) {
  469. UIUtilities.invokeLater(() -> newLineIndicator.setVisible(false));
  470. }
  471. }
  472. /**
  473. * Called to close this TextPane and any associated resources.
  474. */
  475. public void close() {
  476. backgroundPainter.unbind();
  477. }
  478. }