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 12KB

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