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.

Channel.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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;
  23. import com.dmdirc.commandparser.CommandType;
  24. import com.dmdirc.commandparser.parsers.ChannelCommandParser;
  25. import com.dmdirc.config.ConfigBinding;
  26. import com.dmdirc.events.ChannelClosedEvent;
  27. import com.dmdirc.events.ChannelSelfActionEvent;
  28. import com.dmdirc.events.ChannelSelfMessageEvent;
  29. import com.dmdirc.interfaces.CommandController;
  30. import com.dmdirc.interfaces.Connection;
  31. import com.dmdirc.interfaces.GroupChat;
  32. import com.dmdirc.interfaces.NicklistListener;
  33. import com.dmdirc.interfaces.TopicChangeListener;
  34. import com.dmdirc.interfaces.config.ConfigProviderMigrator;
  35. import com.dmdirc.parser.interfaces.ChannelClientInfo;
  36. import com.dmdirc.parser.interfaces.ChannelInfo;
  37. import com.dmdirc.parser.interfaces.ClientInfo;
  38. import com.dmdirc.parser.interfaces.Parser;
  39. import com.dmdirc.ui.messages.BackBufferFactory;
  40. import com.dmdirc.ui.core.components.WindowComponent;
  41. import com.dmdirc.ui.input.TabCompleterFactory;
  42. import com.dmdirc.ui.input.TabCompletionType;
  43. import com.dmdirc.ui.messages.Styliser;
  44. import com.dmdirc.ui.messages.sink.MessageSinkManager;
  45. import com.dmdirc.util.EventUtils;
  46. import com.dmdirc.util.URLBuilder;
  47. import com.dmdirc.util.collections.ListenerList;
  48. import com.dmdirc.util.collections.RollingList;
  49. import com.dmdirc.util.colours.Colour;
  50. import com.dmdirc.util.colours.ColourUtils;
  51. import java.util.ArrayList;
  52. import java.util.Arrays;
  53. import java.util.Collection;
  54. import java.util.Collections;
  55. import java.util.List;
  56. import java.util.Map;
  57. import java.util.Optional;
  58. import java.util.stream.Collectors;
  59. /**
  60. * The Channel class represents the client's view of the channel. It handles callbacks for channel
  61. * events from the parser, maintains the corresponding ChannelWindow, and handles user input for the
  62. * channel.
  63. */
  64. public class Channel extends MessageTarget implements GroupChat {
  65. /** List of registered listeners. */
  66. private final ListenerList listenerList = new ListenerList();
  67. /** The parser's pChannel class. */
  68. private ChannelInfo channelInfo;
  69. /** The server this channel is on. */
  70. private final Server server;
  71. /** A list of previous topics we've seen. */
  72. private final RollingList<Topic> topics;
  73. /** Our event handler. */
  74. private final ChannelEventHandler eventHandler;
  75. /** The migrator to use to migrate our config provider. */
  76. private final ConfigProviderMigrator configMigrator;
  77. /** Whether we're in this channel or not. */
  78. private boolean isOnChannel;
  79. /** Whether we should send WHO requests for this channel. */
  80. @ConfigBinding(domain = "channel", key = "sendwho")
  81. private volatile boolean sendWho;
  82. /** Whether we should show mode prefixes in text. */
  83. @ConfigBinding(domain = "channel", key = "showmodeprefix")
  84. private volatile boolean showModePrefix;
  85. /** Whether we should show colours in nicks. */
  86. @ConfigBinding(domain = "ui", key = "shownickcoloursintext")
  87. private volatile boolean showColours;
  88. /**
  89. * Creates a new instance of Channel.
  90. *
  91. * @param newServer The server object that this channel belongs to
  92. * @param newChannelInfo The parser's channel object that corresponds to this channel
  93. * @param configMigrator The config migrator which provides the config for this channel.
  94. * @param tabCompleterFactory The factory to use to create tab completers.
  95. * @param commandController The controller to load commands from.
  96. * @param messageSinkManager The sink manager to use to despatch messages.
  97. * @param urlBuilder The URL builder to use when finding icons.
  98. * @param eventBus The bus to despatch events onto.
  99. */
  100. public Channel(
  101. final Server newServer,
  102. final ChannelInfo newChannelInfo,
  103. final ConfigProviderMigrator configMigrator,
  104. final TabCompleterFactory tabCompleterFactory,
  105. final CommandController commandController,
  106. final MessageSinkManager messageSinkManager,
  107. final URLBuilder urlBuilder,
  108. final DMDircMBassador eventBus,
  109. final BackBufferFactory backBufferFactory) {
  110. super(newServer, "channel-inactive", newChannelInfo.getName(),
  111. Styliser.stipControlCodes(newChannelInfo.getName()),
  112. configMigrator.getConfigProvider(),
  113. backBufferFactory,
  114. new ChannelCommandParser(newServer, commandController, eventBus),
  115. tabCompleterFactory.getTabCompleter(newServer.getTabCompleter(),
  116. configMigrator.getConfigProvider(), CommandType.TYPE_CHANNEL,
  117. CommandType.TYPE_CHAT),
  118. messageSinkManager,
  119. urlBuilder,
  120. newServer.getEventBus(),
  121. Arrays.asList(WindowComponent.TEXTAREA.getIdentifier(),
  122. WindowComponent.INPUTFIELD.getIdentifier(),
  123. WindowComponent.TOPICBAR.getIdentifier(),
  124. WindowComponent.USERLIST.getIdentifier()));
  125. this.configMigrator = configMigrator;
  126. this.channelInfo = newChannelInfo;
  127. this.server = newServer;
  128. getConfigManager().getBinder().bind(this, Channel.class);
  129. topics = new RollingList<>(getConfigManager().getOptionInt("channel", "topichistorysize"));
  130. eventHandler = new ChannelEventHandler(this, getEventBus());
  131. registerCallbacks();
  132. updateTitle();
  133. selfJoin();
  134. }
  135. public ChannelInfo getChannelInfo() {
  136. return channelInfo;
  137. }
  138. @Override
  139. public boolean isOnChannel() {
  140. return isOnChannel;
  141. }
  142. /**
  143. * Registers callbacks with the parser for this channel.
  144. */
  145. private void registerCallbacks() {
  146. eventHandler.registerCallbacks();
  147. configMigrator.migrate(server.getProtocol(), server.getIrcd(),
  148. server.getNetwork(), server.getAddress(), channelInfo.getName());
  149. }
  150. @Override
  151. public void sendLine(final String line) {
  152. if (server.getState() != ServerState.CONNECTED
  153. || server.getParser().get().getChannel(channelInfo.getName()) == null) {
  154. // We're not in the channel/connected to the server
  155. return;
  156. }
  157. final ClientInfo me = server.getParser().get().getLocalClient();
  158. final String[] details = getDetails(channelInfo.getChannelClient(me));
  159. splitLine(line).stream().filter(part -> !part.isEmpty()).forEach(part -> {
  160. final ChannelSelfMessageEvent event =
  161. new ChannelSelfMessageEvent(this, channelInfo.getChannelClient(me), part);
  162. final String format =
  163. EventUtils.postDisplayable(getEventBus(), event, "channelSelfMessage");
  164. addLine(format, details[0], details[1], details[2], details[3], part, channelInfo);
  165. channelInfo.sendMessage(part);
  166. });
  167. }
  168. @Override
  169. public int getMaxLineLength() {
  170. return server.getState() == ServerState.CONNECTED
  171. ? server.getParser().get().getMaxLength("PRIVMSG", getChannelInfo().getName())
  172. : -1;
  173. }
  174. @Override
  175. public void sendAction(final String action) {
  176. if (server.getState() != ServerState.CONNECTED
  177. || server.getParser().get().getChannel(channelInfo.getName()) == null) {
  178. // We're not on the server/channel
  179. return;
  180. }
  181. final ClientInfo me = server.getParser().get().getLocalClient();
  182. final String[] details = getDetails(channelInfo.getChannelClient(me));
  183. if (server.getParser().get().getMaxLength("PRIVMSG", getChannelInfo().getName())
  184. <= action.length()) {
  185. addLine("actionTooLong", action.length());
  186. } else {
  187. final ChannelSelfActionEvent event = new ChannelSelfActionEvent(this,
  188. channelInfo.getChannelClient(me), action);
  189. final String format = EventUtils.postDisplayable(getEventBus(), event,
  190. "channelSelfAction");
  191. addLine(format, details[0], details[1], details[2], details[3], action, channelInfo);
  192. channelInfo.sendAction(action);
  193. }
  194. }
  195. /**
  196. * Sets this object's ChannelInfo reference to the one supplied. This only needs to be done if
  197. * the channel window (and hence this channel object) has stayed open while the user has been
  198. * out of the channel.
  199. *
  200. * @param newChannelInfo The new ChannelInfo object
  201. */
  202. public void setChannelInfo(final ChannelInfo newChannelInfo) {
  203. channelInfo = newChannelInfo;
  204. registerCallbacks();
  205. }
  206. /**
  207. * Called when we join this channel. Just needs to output a message.
  208. */
  209. public void selfJoin() {
  210. isOnChannel = true;
  211. final ClientInfo me = server.getParser().get().getLocalClient();
  212. addLine("channelSelfJoin", "", me.getNickname(), me.getUsername(),
  213. me.getHostname(), channelInfo.getName());
  214. checkWho();
  215. setIcon("channel");
  216. server.removeInvites(channelInfo.getName());
  217. }
  218. /**
  219. * Updates the title of the channel window, and of the main window if appropriate.
  220. */
  221. private void updateTitle() {
  222. String temp = Styliser.stipControlCodes(channelInfo.getName());
  223. if (!channelInfo.getTopic().isEmpty()) {
  224. temp += " - " + Styliser.stipControlCodes(channelInfo.getTopic());
  225. }
  226. setTitle(temp);
  227. }
  228. @Override
  229. public void join() {
  230. server.getParser().get().joinChannel(channelInfo.getName());
  231. }
  232. @Override
  233. public void part(final String reason) {
  234. channelInfo.part(reason);
  235. resetWindow();
  236. }
  237. @Override
  238. public void retrieveListModes() {
  239. channelInfo.requestListModes();
  240. }
  241. /**
  242. * Resets the window state after the client has left a channel.
  243. */
  244. public void resetWindow() {
  245. isOnChannel = false;
  246. setIcon("channel-inactive");
  247. listenerList.getCallable(NicklistListener.class)
  248. .clientListUpdated(Collections.<ChannelClientInfo>emptyList());
  249. }
  250. @Override
  251. public void close() {
  252. super.close();
  253. // Remove any callbacks or listeners
  254. eventHandler.unregisterCallbacks();
  255. getConfigManager().getBinder().unbind(this);
  256. server.getParser().map(Parser::getCallbackManager)
  257. .ifPresent(cm -> cm.delAllCallback(eventHandler));
  258. // Trigger any actions neccessary
  259. if (isOnChannel && server.getState() != ServerState.CLOSING) {
  260. part(getConfigManager().getOption("general", "partmessage"));
  261. }
  262. // Trigger action for the window closing
  263. getEventBus().publish(new ChannelClosedEvent(this));
  264. // Inform any parents that the window is closing
  265. server.delChannel(channelInfo.getName());
  266. }
  267. /**
  268. * Called every {general.whotime} seconds to check if the channel needs to send a who request.
  269. */
  270. public void checkWho() {
  271. if (isOnChannel && sendWho) {
  272. channelInfo.sendWho();
  273. }
  274. }
  275. /**
  276. * Adds a ChannelClient to this Channel.
  277. *
  278. * @param client The client to be added
  279. */
  280. public void addClient(final ChannelClientInfo client) {
  281. listenerList.getCallable(NicklistListener.class).clientAdded(client);
  282. getTabCompleter().addEntry(TabCompletionType.CHANNEL_NICK,
  283. client.getClient().getNickname());
  284. }
  285. /**
  286. * Removes the specified ChannelClient from this channel.
  287. *
  288. * @param client The client to be removed
  289. */
  290. public void removeClient(final ChannelClientInfo client) {
  291. listenerList.getCallable(NicklistListener.class).clientRemoved(client);
  292. getTabCompleter().removeEntry(TabCompletionType.CHANNEL_NICK,
  293. client.getClient().getNickname());
  294. if (client.getClient().equals(server.getParser().get().getLocalClient())) {
  295. resetWindow();
  296. }
  297. }
  298. /**
  299. * Replaces the list of known clients on this channel with the specified one.
  300. *
  301. * @param clients The list of clients to use
  302. */
  303. public void setClients(final Collection<ChannelClientInfo> clients) {
  304. listenerList.getCallable(NicklistListener.class).clientListUpdated(clients);
  305. getTabCompleter().clear(TabCompletionType.CHANNEL_NICK);
  306. getTabCompleter().addEntries(TabCompletionType.CHANNEL_NICK,
  307. clients.stream().map(c -> c.getClient().getNickname()).collect(Collectors.toList()));
  308. }
  309. /**
  310. * Renames a client that is in this channel.
  311. *
  312. * @param oldName The old nickname of the client
  313. * @param newName The new nickname of the client
  314. */
  315. public void renameClient(final String oldName, final String newName) {
  316. getTabCompleter().removeEntry(TabCompletionType.CHANNEL_NICK, oldName);
  317. getTabCompleter().addEntry(TabCompletionType.CHANNEL_NICK, newName);
  318. refreshClients();
  319. }
  320. /**
  321. * Refreshes the list of clients stored by this channel. Should be called when (visible) user
  322. * modes or nicknames change.
  323. */
  324. public void refreshClients() {
  325. if (!isOnChannel) {
  326. return;
  327. }
  328. listenerList.getCallable(NicklistListener.class).clientListUpdated();
  329. }
  330. /**
  331. * Returns a string containing the most important mode for the specified client.
  332. *
  333. * @param channelClient The channel client to check.
  334. *
  335. * @return A string containing the most important mode, or an empty string if there are no
  336. * (known) modes.
  337. */
  338. private String getModes(final ChannelClientInfo channelClient) {
  339. if (channelClient == null || !showModePrefix) {
  340. return "";
  341. } else {
  342. return channelClient.getImportantModePrefix();
  343. }
  344. }
  345. /**
  346. * Returns a string[] containing the nickname/ident/host of a channel client.
  347. *
  348. * @param client The channel client to check
  349. *
  350. * @return A string[] containing displayable components
  351. */
  352. private String[] getDetails(final ChannelClientInfo client) {
  353. if (client == null) {
  354. // WTF?
  355. throw new UnsupportedOperationException("getDetails called with"
  356. + " null ChannelClientInfo");
  357. }
  358. final String[] res = {
  359. getModes(client),
  360. Styliser.CODE_NICKNAME + client.getClient().getNickname() + Styliser.CODE_NICKNAME,
  361. client.getClient().getUsername(),
  362. client.getClient().getHostname(),};
  363. if (showColours) {
  364. final Map<?, ?> map = client.getMap();
  365. if (map.containsKey(ChannelClientProperty.TEXT_FOREGROUND)) {
  366. final String prefix;
  367. if (map.containsKey(ChannelClientProperty.TEXT_BACKGROUND)) {
  368. prefix = ',' + ColourUtils.getHex((Colour) map.get(
  369. ChannelClientProperty.TEXT_BACKGROUND));
  370. } else {
  371. prefix = Styliser.CODE_HEXCOLOUR + ColourUtils.getHex((Colour) map.get(
  372. ChannelClientProperty.TEXT_FOREGROUND));
  373. }
  374. res[1] = prefix + res[1] + Styliser.CODE_HEXCOLOUR;
  375. }
  376. }
  377. return res;
  378. }
  379. @Override
  380. protected boolean processNotificationArg(final Object arg, final List<Object> args) {
  381. if (arg instanceof ClientInfo) {
  382. // Format ClientInfos
  383. final ClientInfo clientInfo = (ClientInfo) arg;
  384. args.add(clientInfo.getNickname());
  385. args.add(clientInfo.getUsername());
  386. args.add(clientInfo.getHostname());
  387. return true;
  388. } else if (arg instanceof ChannelClientInfo) {
  389. // Format ChannelClientInfos
  390. final ChannelClientInfo clientInfo = (ChannelClientInfo) arg;
  391. args.addAll(Arrays.asList(getDetails(clientInfo)));
  392. return true;
  393. } else if (arg instanceof Topic) {
  394. // Format topics
  395. final Topic topic = (Topic) arg;
  396. args.add("");
  397. args.add(topic.getClient().getNickname());
  398. args.add(topic.getClient().getUsername().orElse(""));
  399. args.add(topic.getClient().getHostname().orElse(""));
  400. args.add(topic.getTopic());
  401. args.add(topic.getTime() * 1000);
  402. return true;
  403. } else {
  404. // Everything else - default formatting
  405. return super.processNotificationArg(arg, args);
  406. }
  407. }
  408. @Override
  409. protected void modifyNotificationArgs(final List<Object> actionArgs,
  410. final List<Object> messageArgs) {
  411. messageArgs.add(channelInfo.getName());
  412. }
  413. // ---------------------------------------------------- TOPIC HANDLING -----
  414. /**
  415. * Adds the specified topic to this channel's topic list.
  416. *
  417. * @param topic The topic to be added.
  418. */
  419. public void addTopic(final Topic topic) {
  420. synchronized (topics) {
  421. topics.add(topic);
  422. }
  423. updateTitle();
  424. new Thread(
  425. () -> listenerList.getCallable(TopicChangeListener.class).topicChanged(this, topic),
  426. "Topic change listener runner").start();
  427. }
  428. @Override
  429. public List<Topic> getTopics() {
  430. synchronized (topics) {
  431. return new ArrayList<>(topics.getList());
  432. }
  433. }
  434. @Override
  435. public Optional<Topic> getCurrentTopic() {
  436. synchronized (topics) {
  437. if (topics.getList().isEmpty()) {
  438. return Optional.empty();
  439. } else {
  440. return Optional.of(topics.get(topics.getList().size() - 1));
  441. }
  442. }
  443. }
  444. // ------------------------------------------ PARSER METHOD DELEGATION -----
  445. @Override
  446. public void setTopic(final String topic) {
  447. channelInfo.setTopic(topic);
  448. }
  449. @Override
  450. public int getMaxTopicLength() {
  451. return server.getParser().get().getMaxTopicLength();
  452. }
  453. @Override
  454. public void addNicklistListener(final NicklistListener listener) {
  455. listenerList.add(NicklistListener.class, listener);
  456. }
  457. @Override
  458. public void removeNicklistListener(final NicklistListener listener) {
  459. listenerList.remove(NicklistListener.class, listener);
  460. }
  461. @Override
  462. public void addTopicChangeListener(final TopicChangeListener listener) {
  463. listenerList.add(TopicChangeListener.class, listener);
  464. }
  465. @Override
  466. public void removeTopicChangeListener(final TopicChangeListener listener) {
  467. listenerList.remove(TopicChangeListener.class, listener);
  468. }
  469. @Override
  470. public Optional<Connection> getConnection() {
  471. return Optional.of(server);
  472. }
  473. }