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.

TopicBar.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc.addons.ui_swing.components;
  18. import com.dmdirc.Topic;
  19. import com.dmdirc.addons.ui_swing.EdtHandlerInvocation;
  20. import com.dmdirc.addons.ui_swing.UIUtilities;
  21. import com.dmdirc.addons.ui_swing.actions.ReplacePasteAction;
  22. import com.dmdirc.addons.ui_swing.components.frames.ChannelFrame;
  23. import com.dmdirc.addons.ui_swing.components.inputfields.SwingInputHandler;
  24. import com.dmdirc.addons.ui_swing.components.inputfields.TextPaneInputField;
  25. import com.dmdirc.addons.ui_swing.components.text.WrapEditorKit;
  26. import com.dmdirc.addons.ui_swing.textpane.StyledDocumentMaker;
  27. import com.dmdirc.events.ChannelTopicChangeEvent;
  28. import com.dmdirc.events.ChannelTopicUnsetEvent;
  29. import com.dmdirc.interfaces.CommandController;
  30. import com.dmdirc.interfaces.GroupChat;
  31. import com.dmdirc.config.provider.AggregateConfigProvider;
  32. import com.dmdirc.config.provider.ConfigChangeListener;
  33. import com.dmdirc.plugins.ServiceManager;
  34. import com.dmdirc.ui.input.TabCompleterUtils;
  35. import com.dmdirc.ui.messages.ColourManager;
  36. import com.dmdirc.ui.messages.IRCControlCodes;
  37. import java.awt.Color;
  38. import java.awt.Window;
  39. import java.awt.datatransfer.Clipboard;
  40. import java.awt.event.ActionEvent;
  41. import java.awt.event.ActionListener;
  42. import java.awt.event.MouseEvent;
  43. import java.awt.event.MouseListener;
  44. import java.util.Optional;
  45. import javax.swing.AbstractAction;
  46. import javax.swing.JButton;
  47. import javax.swing.JComponent;
  48. import javax.swing.JLabel;
  49. import javax.swing.JScrollPane;
  50. import javax.swing.KeyStroke;
  51. import javax.swing.ScrollPaneConstants;
  52. import javax.swing.SwingUtilities;
  53. import javax.swing.event.DocumentEvent;
  54. import javax.swing.event.DocumentListener;
  55. import javax.swing.text.AbstractDocument;
  56. import javax.swing.text.SimpleAttributeSet;
  57. import javax.swing.text.StyleConstants;
  58. import javax.swing.text.StyledDocument;
  59. import net.miginfocom.swing.MigLayout;
  60. import net.engio.mbassy.listener.Handler;
  61. /**
  62. * Component to show and edit topics for a channel.
  63. */
  64. public class TopicBar extends JComponent implements ActionListener, ConfigChangeListener,
  65. MouseListener, DocumentListener {
  66. /** Serial version UID. */
  67. private static final long serialVersionUID = 1;
  68. /** Topic text. */
  69. private final TextPaneInputField topicText;
  70. /** Edit button. */
  71. private final JButton topicEdit;
  72. /** Cancel button. */
  73. private final JButton topicCancel;
  74. /** Manager to use to resolve colours. */
  75. private final ColourManager colourManager;
  76. /** The window this topic bar is for. */
  77. private final ChannelFrame window;
  78. /** Associated channel. */
  79. private final GroupChat channel;
  80. /** the maximum length allowed for a topic. */
  81. private final int topicLengthMax;
  82. /** The config domain to read settings from. */
  83. private final String domain;
  84. /** Empty Attribute set. */
  85. private SimpleAttributeSet as;
  86. /** Foreground Colour. */
  87. private Color foregroundColour;
  88. /** Background Colour. */
  89. private Color backgroundColour;
  90. /** Error icon. */
  91. private final JLabel errorIcon;
  92. /** Show the topic bar? */
  93. private boolean showBar;
  94. /** Show the full topic, or truncate? */
  95. private boolean showFull;
  96. /** Hide topic bar when topic is empty? */
  97. private boolean hideEmpty;
  98. /**
  99. * Creates a new instance of {@link TopicBar}.
  100. *
  101. * @param parentWindow The window that ultimately contains this topic bar.
  102. * @param globalConfig The config provider to read settings from.
  103. * @param domain The domain that settings are stored in.
  104. * @param colourManager The colour manager to use for colour input.
  105. * @param serviceManager The service manager to use for plugin information.
  106. * @param clipboard The clipboard to copy and paste from
  107. * @param commandController The controller to use for command information.
  108. * @param channel The channel that this topic bar is for.
  109. * @param window The window this topic bar is for.
  110. * @param iconManager The icon manager to use for this bar's icons.
  111. */
  112. public TopicBar(
  113. final Window parentWindow,
  114. final AggregateConfigProvider globalConfig,
  115. final String domain,
  116. final ColourManager colourManager,
  117. final ServiceManager serviceManager,
  118. final Clipboard clipboard,
  119. final CommandController commandController,
  120. final GroupChat channel,
  121. final ChannelFrame window,
  122. final IconManager iconManager,
  123. final TabCompleterUtils tabCompleterUtils) {
  124. this.channel = channel;
  125. this.domain = domain;
  126. this.colourManager = colourManager;
  127. this.window = window;
  128. topicText = new TextPaneInputField(parentWindow, globalConfig, colourManager, iconManager);
  129. topicLengthMax = channel.getMaxTopicLength();
  130. updateOptions();
  131. errorIcon = new JLabel(iconManager.getIcon("input-error"));
  132. topicText.setEditorKit(new WrapEditorKit(showFull, channel.getEventBus(), window.getContainer()));
  133. ((AbstractDocument) topicText.getDocument()).setDocumentFilter(
  134. new NewlinesDocumentFilter());
  135. topicText.getActionMap().put("paste-from-clipboard",
  136. new ReplacePasteAction(clipboard, "(\r\n|\n|\r)", " "));
  137. topicEdit = new ImageButton<>("edit",
  138. iconManager.getIcon("edit-inactive"),
  139. iconManager.getIcon("edit"));
  140. topicCancel = new ImageButton<>("cancel",
  141. iconManager.getIcon("close"),
  142. iconManager.getIcon("close-active"));
  143. final SwingInputHandler handler = new SwingInputHandler(
  144. serviceManager, topicText, commandController,
  145. channel.getWindowModel().getInputModel().get().getCommandParser(),
  146. channel.getWindowModel(),
  147. tabCompleterUtils, channel.getEventBus());
  148. handler.setTypes(true, false, true, false);
  149. handler.setTabCompleter(channel.getWindowModel().getInputModel().get().getTabCompleter());
  150. final JScrollPane sp = new JScrollPane(topicText);
  151. sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
  152. sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
  153. setLayout(new MigLayout("fillx, ins 0, hidemode 3"));
  154. add(sp, "growx, pushx");
  155. add(errorIcon, "");
  156. add(topicCancel, "");
  157. add(topicEdit, "");
  158. //Fix broken layout manager
  159. invalidate();
  160. validate();
  161. invalidate();
  162. channel.getEventBus().subscribe(this);
  163. topicText.addActionListener(this);
  164. topicEdit.addActionListener(this);
  165. topicCancel.addActionListener(this);
  166. topicText.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enterButton");
  167. topicText.getActionMap().put("enterButton", new AbstractAction("enterButton") {
  168. /** A version number for this class. */
  169. private static final long serialVersionUID = 1;
  170. @Override
  171. public void actionPerformed(final ActionEvent e) {
  172. commitTopicEdit();
  173. }
  174. });
  175. topicText.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "escapeButton");
  176. topicText.getActionMap().put("escapeButton", new AbstractAction("escapeButton") {
  177. /** A version number for this class. */
  178. private static final long serialVersionUID = 1;
  179. @Override
  180. public void actionPerformed(final ActionEvent e) {
  181. cancelTopicEdit();
  182. }
  183. });
  184. topicText.addMouseListener(this);
  185. topicText.getDocument().addDocumentListener(this);
  186. globalConfig.addChangeListener("ui", "backgroundcolour", this);
  187. globalConfig.addChangeListener("ui", "foregroundcolour", this);
  188. globalConfig.addChangeListener("ui", "inputbackgroundcolour", this);
  189. globalConfig.addChangeListener("ui", "inputforegroundcolour", this);
  190. globalConfig.addChangeListener(domain, "showfulltopic", this);
  191. globalConfig.addChangeListener(domain, "hideEmptyTopicBar", this);
  192. globalConfig.addChangeListener(domain, "showtopicbar", this);
  193. setVisible(true);
  194. topicText.setFocusable(false);
  195. topicText.setEditable(false);
  196. topicCancel.setVisible(false);
  197. setColours();
  198. validateTopic();
  199. final Optional<Topic> topic = channel.getCurrentTopic();
  200. topic.ifPresent(topic1 -> topicChanged(channel, topic1));
  201. }
  202. @Handler(invocation = EdtHandlerInvocation.class)
  203. public void handleTopicChanged(final ChannelTopicChangeEvent event) {
  204. if (event.getChannel().equals(channel)) {
  205. topicChanged(event.getChannel(), event.getTopic());
  206. }
  207. }
  208. @Handler(invocation = EdtHandlerInvocation.class)
  209. public void handleTopicUnset(final ChannelTopicUnsetEvent event) {
  210. if (event.getChannel().equals(channel)) {
  211. topicChanged(event.getChannel(), null);
  212. }
  213. }
  214. private void topicChanged(final GroupChat channel, final Topic topic) {
  215. if (topicText.isEditable()) {
  216. return;
  217. }
  218. topicText.setText("");
  219. if (topic != null) {
  220. channel.getWindowModel().getBackBuffer().getStyliser().addStyledString(
  221. new StyledDocumentMaker((StyledDocument) topicText.getDocument(), as),
  222. IRCControlCodes.COLOUR_HEX
  223. + UIUtilities.getHex(foregroundColour)
  224. + topic.getTopic());
  225. }
  226. topicText.setCaretPosition(0);
  227. validateTopic();
  228. setVisible(false);
  229. setVisible(true);
  230. }
  231. @Override
  232. public void setVisible(final boolean visibility) {
  233. if (!showBar || !visibility) {
  234. super.setVisible(false);
  235. return;
  236. }
  237. if (hideEmpty) {
  238. super.setVisible(topicText.getDocument().getLength() != 0);
  239. return;
  240. }
  241. super.setVisible(true);
  242. }
  243. @Override
  244. public void actionPerformed(final ActionEvent e) {
  245. if (!channel.isOnChannel()) {
  246. return;
  247. }
  248. if (e.getSource() == topicEdit) {
  249. if (topicText.isEditable()) {
  250. commitTopicEdit();
  251. } else {
  252. setupTopicEdit();
  253. }
  254. } else if (e.getSource() == topicCancel) {
  255. cancelTopicEdit();
  256. }
  257. }
  258. /**
  259. * Commits a topic edit to the parent channel.
  260. */
  261. private void commitTopicEdit() {
  262. final Optional<Topic> oldTopic = channel.getCurrentTopic();
  263. if ((!oldTopic.isPresent() && !topicText.getText().isEmpty())
  264. || (oldTopic.isPresent() && !oldTopic.get().getTopic().equals(topicText.getText()))) {
  265. channel.setTopic(topicText.getText());
  266. }
  267. final Optional<Topic> newTopic = channel.getCurrentTopic();
  268. window.getInputField().requestFocusInWindow();
  269. if (newTopic.isPresent()) {
  270. topicText.setText(newTopic.get().getTopic());
  271. } else {
  272. topicText.setText("");
  273. }
  274. topicText.setFocusable(false);
  275. topicText.setEditable(false);
  276. topicCancel.setVisible(false);
  277. }
  278. /**
  279. * Sets the topic ready to be edited, changing attributes and focus.
  280. */
  281. private void setupTopicEdit() {
  282. topicText.setVisible(false);
  283. topicText.setText("");
  284. final Optional<Topic> topic = channel.getCurrentTopic();
  285. topic.ifPresent(topic1 -> topicText.setText(topic1.getTopic()));
  286. applyAttributes();
  287. topicText.setCaretPosition(0);
  288. topicText.setFocusable(true);
  289. topicText.setEditable(true);
  290. topicText.setVisible(true);
  291. topicText.requestFocusInWindow();
  292. topicCancel.setVisible(true);
  293. }
  294. /**
  295. * Cancels a topic edit, resetting focus and button states.
  296. */
  297. private void cancelTopicEdit() {
  298. topicText.setFocusable(false);
  299. topicText.setEditable(false);
  300. topicCancel.setVisible(false);
  301. window.getInputField().requestFocusInWindow();
  302. topicChanged(channel, null);
  303. }
  304. /**
  305. * Load and set colours.
  306. */
  307. private void setColours() {
  308. backgroundColour = UIUtilities.convertColour(
  309. colourManager.getColourFromString(channel.getWindowModel().getConfigManager()
  310. .getOptionString("ui", "inputbackgroundcolour", "ui",
  311. "backgroundcolour"), null));
  312. foregroundColour = UIUtilities.convertColour(
  313. colourManager.getColourFromString(
  314. channel.getWindowModel().getConfigManager().getOptionString(
  315. "ui", "inputforegroundcolour",
  316. "ui", "foregroundcolour"), null));
  317. setBackground(backgroundColour);
  318. setForeground(foregroundColour);
  319. setDisabledTextColour(foregroundColour);
  320. setCaretColor(foregroundColour);
  321. setAttributes();
  322. }
  323. /**
  324. * Sets sensible attributes.
  325. */
  326. private void setAttributes() {
  327. as = new SimpleAttributeSet();
  328. StyleConstants.setFontFamily(as, topicText.getFont().getFamily());
  329. StyleConstants.setFontSize(as, topicText.getFont().getSize());
  330. StyleConstants.setBackground(as, backgroundColour);
  331. StyleConstants.setForeground(as, foregroundColour);
  332. StyleConstants.setUnderline(as, false);
  333. StyleConstants.setBold(as, false);
  334. StyleConstants.setItalic(as, false);
  335. }
  336. /**
  337. * Applies predefined attributes to the topic bar.
  338. */
  339. private void applyAttributes() {
  340. setAttributes();
  341. ((StyledDocument) topicText.getDocument())
  342. .setCharacterAttributes(0, Integer.MAX_VALUE, as, true);
  343. }
  344. /**
  345. * Sets the caret position in this topic bar.
  346. *
  347. * @param position New position
  348. */
  349. public void setCaretPosition(final int position) {
  350. UIUtilities.invokeLater(() -> topicText.setCaretPosition(position));
  351. }
  352. /**
  353. * Sets the caret colour to the specified colour.
  354. *
  355. * @param optionColour Colour for the caret
  356. */
  357. public void setCaretColor(final Color optionColour) {
  358. UIUtilities.invokeLater(() -> topicText.setCaretColor(optionColour));
  359. }
  360. @Override
  361. public void setForeground(final Color optionColour) {
  362. UIUtilities.invokeLater(() -> topicText.setForeground(optionColour));
  363. }
  364. /**
  365. * Sets the disabled text colour to the specified colour.
  366. *
  367. * @param optionColour Colour for the disabled text
  368. */
  369. public void setDisabledTextColour(final Color optionColour) {
  370. UIUtilities.invokeLater(() -> topicText.setDisabledTextColor(optionColour));
  371. }
  372. @Override
  373. public void setBackground(final Color optionColour) {
  374. UIUtilities.invokeLater(() -> topicText.setBackground(optionColour));
  375. }
  376. @Override
  377. public void configChanged(final String domain, final String key) {
  378. updateOptions();
  379. setVisible(showBar);
  380. cancelTopicEdit();
  381. if ("showfulltopic".equals(key)) {
  382. topicText.setEditorKit(new WrapEditorKit(showFull, channel.getEventBus(), window.getContainer()));
  383. ((AbstractDocument) topicText.getDocument()).setDocumentFilter(
  384. new NewlinesDocumentFilter());
  385. topicChanged(channel, null);
  386. }
  387. setColours();
  388. }
  389. private void updateOptions() {
  390. showFull = channel.getWindowModel().getConfigManager()
  391. .getOptionBool(domain, "showfulltopic");
  392. hideEmpty = channel.getWindowModel().getConfigManager()
  393. .getOptionBool(domain, "hideEmptyTopicBar");
  394. showBar = channel.getWindowModel().getConfigManager()
  395. .getOptionBool(domain, "showtopicbar");
  396. }
  397. /**
  398. * Closes this topic bar.
  399. */
  400. public void close() {
  401. channel.getEventBus().unsubscribe(this);
  402. }
  403. /**
  404. * Validates the topic text and shows errors as appropriate.
  405. */
  406. public void validateTopic() {
  407. UIUtilities.invokeLater(() -> {
  408. if (topicText.isEditable()) {
  409. final int charsLeft = topicLengthMax - topicText.getText().
  410. length();
  411. if (charsLeft < 0) {
  412. errorIcon.setVisible(true);
  413. errorIcon.setToolTipText("Topic too long: " + topicText.
  414. getText().length() + " of " + topicLengthMax);
  415. } else {
  416. errorIcon.setVisible(false);
  417. errorIcon.setToolTipText(null);
  418. }
  419. } else {
  420. errorIcon.setVisible(false);
  421. }
  422. });
  423. }
  424. @Override
  425. public void mouseClicked(final MouseEvent e) {
  426. if (e.getClickCount() == 2 && !topicText.isEditable()) {
  427. topicEdit.doClick();
  428. }
  429. }
  430. @Override
  431. public void mousePressed(final MouseEvent e) {
  432. //Ignore
  433. }
  434. @Override
  435. public void mouseReleased(final MouseEvent e) {
  436. //Ignore
  437. }
  438. @Override
  439. public void mouseEntered(final MouseEvent e) {
  440. //Ignore
  441. }
  442. @Override
  443. public void mouseExited(final MouseEvent e) {
  444. //Ignore
  445. }
  446. @Override
  447. public void insertUpdate(final DocumentEvent e) {
  448. validateTopic();
  449. if (topicText.isEditable()) {
  450. SwingUtilities.invokeLater(this::applyAttributes);
  451. }
  452. }
  453. @Override
  454. public void removeUpdate(final DocumentEvent e) {
  455. validateTopic();
  456. }
  457. @Override
  458. public void changedUpdate(final DocumentEvent e) {
  459. validateTopic();
  460. }
  461. }