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.

LagDisplayManager.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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.lagdisplay;
  23. import com.dmdirc.ClientModule.GlobalConfig;
  24. import com.dmdirc.DMDircMBassador;
  25. import com.dmdirc.FrameContainer;
  26. import com.dmdirc.ServerState;
  27. import com.dmdirc.addons.ui_swing.EdtHandlerInvocation;
  28. import com.dmdirc.addons.ui_swing.components.frames.TextFrame;
  29. import com.dmdirc.addons.ui_swing.events.SwingEventBus;
  30. import com.dmdirc.addons.ui_swing.events.SwingWindowSelectedEvent;
  31. import com.dmdirc.addons.ui_swing.interfaces.ActiveFrameManager;
  32. import com.dmdirc.events.ServerDisconnectedEvent;
  33. import com.dmdirc.events.ServerGotpingEvent;
  34. import com.dmdirc.events.ServerNopingEvent;
  35. import com.dmdirc.events.ServerNumericEvent;
  36. import com.dmdirc.events.ServerPingsentEvent;
  37. import com.dmdirc.events.StatusBarComponentAddedEvent;
  38. import com.dmdirc.events.StatusBarComponentRemovedEvent;
  39. import com.dmdirc.interfaces.Connection;
  40. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  41. import com.dmdirc.interfaces.config.ConfigChangeListener;
  42. import com.dmdirc.plugins.PluginDomain;
  43. import com.dmdirc.util.collections.RollingList;
  44. import java.util.Date;
  45. import java.util.HashMap;
  46. import java.util.Map;
  47. import java.util.Optional;
  48. import java.util.WeakHashMap;
  49. import javax.inject.Inject;
  50. import javax.inject.Provider;
  51. import javax.inject.Singleton;
  52. import net.engio.mbassy.listener.Handler;
  53. import net.engio.mbassy.listener.Invoke;
  54. /**
  55. * Manages the lifecycle of the lag display plugin.
  56. */
  57. @Singleton
  58. public class LagDisplayManager implements ConfigChangeListener {
  59. /** Event bus to receive events on. */
  60. private final DMDircMBassador eventBus;
  61. /** Swing event bus to receive events from. */
  62. private final SwingEventBus swingEventBus;
  63. /** Active frame manager. */
  64. private final ActiveFrameManager activeFrameManager;
  65. private final Provider<LagDisplayPanel> panelProvider;
  66. /** The settings domain to use. */
  67. private final String domain;
  68. /** Config to read global settings from. */
  69. private final AggregateConfigProvider globalConfig;
  70. /** A cache of ping times. */
  71. private final Map<Connection, String> pings = new WeakHashMap<>();
  72. /** Ping history. */
  73. private final Map<Connection, RollingList<Long>> history = new HashMap<>();
  74. /** Whether or not to show a graph in the info popup. */
  75. private boolean showGraph = true;
  76. /** Whether or not to show labels on that graph. */
  77. private boolean showLabels = true;
  78. /** The length of history to keep per-server. */
  79. private int historySize = 100;
  80. /** The panel currently in use. Null before {@link #load()} or after {@link #unload()}. */
  81. private LagDisplayPanel panel;
  82. @Inject
  83. public LagDisplayManager(final DMDircMBassador eventBus,
  84. final SwingEventBus swingEventBus,
  85. final ActiveFrameManager activeFrameManager,
  86. final Provider<LagDisplayPanel> panelProvider,
  87. @PluginDomain(LagDisplayPlugin.class) final String domain,
  88. @GlobalConfig final AggregateConfigProvider globalConfig) {
  89. this.eventBus = eventBus;
  90. this.swingEventBus = swingEventBus;
  91. this.activeFrameManager = activeFrameManager;
  92. this.panelProvider = panelProvider;
  93. this.domain = domain;
  94. this.globalConfig = globalConfig;
  95. }
  96. public void load() {
  97. panel = panelProvider.get();
  98. eventBus.publishAsync(new StatusBarComponentAddedEvent(panel));
  99. globalConfig.addChangeListener(domain, this);
  100. readConfig();
  101. swingEventBus.subscribe(this);
  102. eventBus.subscribe(this);
  103. }
  104. public void unload() {
  105. eventBus.publishAsync(new StatusBarComponentRemovedEvent(panel));
  106. globalConfig.removeListener(this);
  107. swingEventBus.unsubscribe(this);
  108. eventBus.unsubscribe(this);
  109. panel = null;
  110. }
  111. /** Reads the plugin's global configuration settings. */
  112. private void readConfig() {
  113. showGraph = globalConfig.getOptionBool(domain, "graph");
  114. showLabels = globalConfig.getOptionBool(domain, "labels");
  115. historySize = globalConfig.getOptionInt(domain, "history");
  116. }
  117. /**
  118. * Retrieves the history of the specified server. If there is no history, a new list is added to
  119. * the history map and returned.
  120. *
  121. * @param connection The connection whose history is being requested
  122. *
  123. * @return The history for the specified server
  124. */
  125. protected RollingList<Long> getHistory(final Connection connection) {
  126. if (!history.containsKey(connection)) {
  127. history.put(connection, new RollingList<>(historySize));
  128. }
  129. return history.get(connection);
  130. }
  131. /**
  132. * Determines if the {@link ServerInfoDialog} should show a graph of the ping time for the
  133. * current server.
  134. *
  135. * @return True if a graph should be shown, false otherwise
  136. */
  137. public boolean shouldShowGraph() {
  138. return showGraph;
  139. }
  140. /**
  141. * Determines if the {@link PingHistoryPanel} should show labels on selected points.
  142. *
  143. * @return True if labels should be shown, false otherwise
  144. */
  145. public boolean shouldShowLabels() {
  146. return showLabels;
  147. }
  148. @Handler(invocation = EdtHandlerInvocation.class, delivery = Invoke.Asynchronously)
  149. public void selectionChanged(final SwingWindowSelectedEvent event) {
  150. if (event.getWindow().isPresent()) {
  151. final Optional<Connection> connection = event.getWindow().get().getContainer()
  152. .getOptionalConnection();
  153. if (connection.isPresent() && connection.get().getState() != ServerState.CONNECTED) {
  154. panel.getComponent().setText("Not connected");
  155. } else {
  156. panel.getComponent().setText(getTime(connection.get()));
  157. }
  158. } else {
  159. panel.getComponent().setText("Unknown");
  160. }
  161. panel.refreshDialog();
  162. }
  163. @Handler
  164. public void handleServerNumeric(final ServerNumericEvent event) {
  165. if (event.getNumeric() != 421) {
  166. return;
  167. }
  168. final boolean useAlternate = ((FrameContainer) event.getConnection()).getConfigManager()
  169. .getOptionBool(domain, "usealternate");
  170. final boolean isActive = isActiveWindow(event.getConnection());
  171. final String[] args = event.getArgs();
  172. if (useAlternate && args[3].startsWith("LAGCHECK_")) {
  173. try {
  174. final long sent = Long.parseLong(args[3].substring(9));
  175. final Long duration = new Date().getTime() - sent;
  176. final String value = formatTime(duration);
  177. pings.put(event.getConnection(), value);
  178. getHistory(event.getConnection()).add(duration);
  179. if (isActive) {
  180. panel.getComponent().setText(value);
  181. }
  182. } catch (NumberFormatException ex) {
  183. pings.remove(event.getConnection());
  184. }
  185. event.setDisplayFormat("");
  186. panel.refreshDialog();
  187. }
  188. }
  189. @Handler
  190. public void handleServerDisconnected(final ServerDisconnectedEvent event) {
  191. final boolean isActive = isActiveWindow(event.getConnection());
  192. if (isActive) {
  193. panel.getComponent().setText("Not connected");
  194. pings.remove(event.getConnection());
  195. }
  196. panel.refreshDialog();
  197. }
  198. @Handler
  199. public void handleServerGotPing(final ServerGotpingEvent event) {
  200. if (event.getConnection().getWindowModel().getConfigManager().
  201. getOptionBool(domain, "usealternate")) {
  202. return;
  203. }
  204. final boolean isActive = isActiveWindow(event.getConnection());
  205. final String value = formatTime(event.getPing());
  206. getHistory(event.getConnection()).add(event.getPing());
  207. pings.put(event.getConnection(), value);
  208. if (isActive) {
  209. panel.getComponent().setText(value);
  210. }
  211. panel.refreshDialog();
  212. }
  213. @Handler
  214. public void handleServerNoPing(final ServerNopingEvent event) {
  215. if (event.getConnection().getWindowModel().getConfigManager().
  216. getOptionBool(domain, "usealternate")) {
  217. return;
  218. }
  219. final boolean isActive = isActiveWindow(event.getConnection());
  220. final String value = formatTime(event.getPing()) + '+';
  221. pings.put(event.getConnection(), value);
  222. if (isActive) {
  223. panel.getComponent().setText(value);
  224. }
  225. panel.refreshDialog();
  226. }
  227. @Handler
  228. public void handleServerPingSent(final ServerPingsentEvent event) {
  229. if (!event.getConnection().getWindowModel().getConfigManager().
  230. getOptionBool(domain, "usealternate")) {
  231. return;
  232. }
  233. event.getConnection().getParser().sendRawMessage("LAGCHECK_" + new Date().getTime());
  234. }
  235. /**
  236. * Retrieves the ping time for the specified connection.
  237. *
  238. * @param connection The connection whose ping time is being requested
  239. *
  240. * @return A String representation of the current lag, or "Unknown"
  241. */
  242. public String getTime(final Connection connection) {
  243. return pings.get(connection) == null ? "Unknown" : pings.get(connection);
  244. }
  245. /**
  246. * Formats the specified time so it's a nice size to display in the label.
  247. *
  248. * @param object An uncast Long representing the time to be formatted
  249. *
  250. * @return Formatted time string
  251. */
  252. protected String formatTime(final Object object) {
  253. final Long time = (Long) object;
  254. if (time >= 10000) {
  255. return Math.round(time / 1000.0) + "s";
  256. } else {
  257. return time + "ms";
  258. }
  259. }
  260. @Override
  261. public void configChanged(final String domain, final String key) {
  262. readConfig();
  263. }
  264. private boolean isActiveWindow(final Connection connection) {
  265. return activeFrameManager.getActiveFrame().map(TextFrame::getContainer)
  266. .flatMap(FrameContainer::getOptionalConnection)
  267. .filter(connection::equals).isPresent();
  268. }
  269. }