您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TopicBar.java 18KB

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