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

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