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

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