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

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