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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc.addons.lagdisplay;
  18. import com.dmdirc.ServerState;
  19. import com.dmdirc.addons.ui_swing.EdtHandlerInvocation;
  20. import com.dmdirc.addons.ui_swing.components.frames.TextFrame;
  21. import com.dmdirc.addons.ui_swing.events.SwingEventBus;
  22. import com.dmdirc.addons.ui_swing.events.SwingWindowSelectedEvent;
  23. import com.dmdirc.addons.ui_swing.interfaces.ActiveFrameManager;
  24. import com.dmdirc.config.GlobalConfig;
  25. import com.dmdirc.config.prefs.PluginPreferencesCategory;
  26. import com.dmdirc.config.prefs.PreferencesCategory;
  27. import com.dmdirc.config.prefs.PreferencesDialogModel;
  28. import com.dmdirc.config.prefs.PreferencesSetting;
  29. import com.dmdirc.config.prefs.PreferencesType;
  30. import com.dmdirc.events.ClientPrefsOpenedEvent;
  31. import com.dmdirc.events.DisplayProperty;
  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.events.eventbus.EventBus;
  41. import com.dmdirc.interfaces.WindowModel;
  42. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  43. import com.dmdirc.interfaces.config.ConfigChangeListener;
  44. import com.dmdirc.plugins.PluginDomain;
  45. import com.dmdirc.plugins.PluginInfo;
  46. import com.dmdirc.util.collections.RollingList;
  47. import java.util.Date;
  48. import java.util.HashMap;
  49. import java.util.Map;
  50. import java.util.Optional;
  51. import java.util.WeakHashMap;
  52. import javax.inject.Inject;
  53. import javax.inject.Provider;
  54. import javax.inject.Singleton;
  55. import net.engio.mbassy.listener.Handler;
  56. /**
  57. * Manages the lifecycle of the lag display plugin.
  58. */
  59. @Singleton
  60. public class LagDisplayManager implements ConfigChangeListener {
  61. /** Event bus to receive events on. */
  62. private final EventBus eventBus;
  63. /** Swing event bus to receive events from. */
  64. private final SwingEventBus swingEventBus;
  65. /** Active frame manager. */
  66. private final ActiveFrameManager activeFrameManager;
  67. private final Provider<LagDisplayPanel> panelProvider;
  68. /** The settings domain to use. */
  69. private final String domain;
  70. private final PluginInfo pluginInfo;
  71. /** Config to read global settings from. */
  72. private final AggregateConfigProvider globalConfig;
  73. /** A cache of ping times. */
  74. private final Map<Connection, String> pings = new WeakHashMap<>();
  75. /** Ping history. */
  76. private final Map<Connection, RollingList<Long>> history = new HashMap<>();
  77. /** Whether or not to show a graph in the info popup. */
  78. private boolean showGraph = true;
  79. /** Whether or not to show labels on that graph. */
  80. private boolean showLabels = true;
  81. /** The length of history to keep per-server. */
  82. private int historySize = 100;
  83. /** The panel currently in use. Null before {@link #load()} or after {@link #unload()}. */
  84. private LagDisplayPanel panel;
  85. @Inject
  86. public LagDisplayManager(final EventBus eventBus,
  87. final SwingEventBus swingEventBus,
  88. final ActiveFrameManager activeFrameManager,
  89. final Provider<LagDisplayPanel> panelProvider,
  90. @PluginDomain(LagDisplayPlugin.class) final String domain,
  91. @PluginDomain(LagDisplayPlugin.class) final PluginInfo pluginInfo,
  92. @GlobalConfig final AggregateConfigProvider globalConfig) {
  93. this.eventBus = eventBus;
  94. this.swingEventBus = swingEventBus;
  95. this.activeFrameManager = activeFrameManager;
  96. this.panelProvider = panelProvider;
  97. this.domain = domain;
  98. this.pluginInfo = pluginInfo;
  99. this.globalConfig = globalConfig;
  100. }
  101. public void load() {
  102. panel = panelProvider.get();
  103. eventBus.publishAsync(new StatusBarComponentAddedEvent(panel));
  104. globalConfig.addChangeListener(domain, this);
  105. readConfig();
  106. swingEventBus.subscribe(this);
  107. eventBus.subscribe(this);
  108. }
  109. public void unload() {
  110. eventBus.publishAsync(new StatusBarComponentRemovedEvent(panel));
  111. globalConfig.removeListener(this);
  112. swingEventBus.unsubscribe(this);
  113. eventBus.unsubscribe(this);
  114. panel = null;
  115. }
  116. /** Reads the plugin's global configuration settings. */
  117. private void readConfig() {
  118. showGraph = globalConfig.getOptionBool(domain, "graph");
  119. showLabels = globalConfig.getOptionBool(domain, "labels");
  120. historySize = globalConfig.getOptionInt(domain, "history");
  121. }
  122. /**
  123. * Retrieves the history of the specified server. If there is no history, a new list is added to
  124. * the history map and returned.
  125. *
  126. * @param connection The connection whose history is being requested
  127. *
  128. * @return The history for the specified server
  129. */
  130. protected RollingList<Long> getHistory(final Connection connection) {
  131. if (!history.containsKey(connection)) {
  132. history.put(connection, new RollingList<>(historySize));
  133. }
  134. return history.get(connection);
  135. }
  136. /**
  137. * Determines if the {@link ServerInfoDialog} should show a graph of the ping time for the
  138. * current server.
  139. *
  140. * @return True if a graph should be shown, false otherwise
  141. */
  142. public boolean shouldShowGraph() {
  143. return showGraph;
  144. }
  145. /**
  146. * Determines if the {@link PingHistoryPanel} should show labels on selected points.
  147. *
  148. * @return True if labels should be shown, false otherwise
  149. */
  150. public boolean shouldShowLabels() {
  151. return showLabels;
  152. }
  153. @Handler(invocation = EdtHandlerInvocation.class)
  154. public void selectionChanged(final SwingWindowSelectedEvent event) {
  155. if (event.getWindow().isPresent()) {
  156. final Optional<Connection> connection = event.getWindow().get().getContainer()
  157. .getConnection();
  158. if (connection.isPresent() && connection.get().getState() != ServerState.CONNECTED) {
  159. panel.getComponent().setText("Not connected");
  160. } else {
  161. panel.getComponent().setText(getTime(connection.get()));
  162. }
  163. } else {
  164. panel.getComponent().setText("Unknown");
  165. }
  166. panel.refreshDialog();
  167. }
  168. @Handler
  169. public void handleServerNumeric(final ServerNumericEvent event) {
  170. if (event.getNumeric() != 421) {
  171. return;
  172. }
  173. final boolean useAlternate = event.getConnection().getWindowModel().getConfigManager()
  174. .getOptionBool(domain, "usealternate");
  175. final boolean isActive = isActiveWindow(event.getConnection());
  176. final String[] args = event.getArgs();
  177. if (useAlternate && args[3].startsWith("LAGCHECK_")) {
  178. try {
  179. final long sent = Long.parseLong(args[3].substring(9));
  180. final Long duration = new Date().getTime() - sent;
  181. final String value = formatTime(duration);
  182. pings.put(event.getConnection(), value);
  183. getHistory(event.getConnection()).add(duration);
  184. if (isActive) {
  185. panel.getComponent().setText(value);
  186. }
  187. } catch (NumberFormatException ex) {
  188. pings.remove(event.getConnection());
  189. }
  190. event.setDisplayProperty(DisplayProperty.DO_NOT_DISPLAY, true);
  191. panel.refreshDialog();
  192. }
  193. }
  194. @Handler
  195. public void handleServerDisconnected(final ServerDisconnectedEvent event) {
  196. final boolean isActive = isActiveWindow(event.getConnection());
  197. if (isActive) {
  198. panel.getComponent().setText("Not connected");
  199. pings.remove(event.getConnection());
  200. }
  201. panel.refreshDialog();
  202. }
  203. @Handler
  204. public void handleServerGotPing(final ServerGotPingEvent event) {
  205. if (event.getConnection().getWindowModel().getConfigManager().
  206. getOptionBool(domain, "usealternate")) {
  207. return;
  208. }
  209. final boolean isActive = isActiveWindow(event.getConnection());
  210. final String value = formatTime(event.getPing());
  211. getHistory(event.getConnection()).add(event.getPing());
  212. pings.put(event.getConnection(), value);
  213. if (isActive) {
  214. panel.getComponent().setText(value);
  215. }
  216. panel.refreshDialog();
  217. }
  218. @Handler
  219. public void handleServerNoPing(final ServerNoPingEvent event) {
  220. if (event.getConnection().getWindowModel().getConfigManager().
  221. getOptionBool(domain, "usealternate")) {
  222. return;
  223. }
  224. final boolean isActive = isActiveWindow(event.getConnection());
  225. final String value = formatTime(event.getPing()) + '+';
  226. pings.put(event.getConnection(), value);
  227. if (isActive) {
  228. panel.getComponent().setText(value);
  229. }
  230. panel.refreshDialog();
  231. }
  232. @Handler
  233. public void handleServerPingSent(final ServerPingSentEvent event) {
  234. if (!event.getConnection().getWindowModel().getConfigManager().
  235. getOptionBool(domain, "usealternate")) {
  236. return;
  237. }
  238. event.getConnection().getParser().get().sendRawMessage("LAGCHECK_" + new Date().getTime());
  239. }
  240. /**
  241. * Retrieves the ping time for the specified connection.
  242. *
  243. * @param connection The connection whose ping time is being requested
  244. *
  245. * @return A String representation of the current lag, or "Unknown"
  246. */
  247. public String getTime(final Connection connection) {
  248. return pings.get(connection) == null ? "Unknown" : pings.get(connection);
  249. }
  250. /**
  251. * Formats the specified time so it's a nice size to display in the label.
  252. *
  253. * @param object An uncast Long representing the time to be formatted
  254. *
  255. * @return Formatted time string
  256. */
  257. protected String formatTime(final Object object) {
  258. final Long time = (Long) object;
  259. if (time >= 10000) {
  260. return Math.round(time / 1000.0) + "s";
  261. } else {
  262. return time + "ms";
  263. }
  264. }
  265. @Override
  266. public void configChanged(final String domain, final String key) {
  267. readConfig();
  268. }
  269. private boolean isActiveWindow(final Connection connection) {
  270. return activeFrameManager.getActiveFrame().map(TextFrame::getContainer)
  271. .flatMap(WindowModel::getConnection)
  272. .filter(connection::equals).isPresent();
  273. }
  274. @Handler
  275. public void showConfig(final ClientPrefsOpenedEvent event) {
  276. final PreferencesDialogModel manager = event.getModel();
  277. final PreferencesCategory cat = new PluginPreferencesCategory(
  278. pluginInfo, "Lag display plugin", "");
  279. cat.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  280. pluginInfo.getDomain(), "usealternate",
  281. "Alternate method", "Use an alternate method of determining "
  282. + "lag which bypasses bouncers or proxies that may reply?",
  283. manager.getConfigManager(), manager.getIdentity()));
  284. cat.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  285. pluginInfo.getDomain(), "graph", "Show graph", "Show a graph of ping times "
  286. + "for the current server in the information popup?",
  287. manager.getConfigManager(), manager.getIdentity()));
  288. cat.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
  289. pluginInfo.getDomain(), "labels", "Show labels", "Show labels on selected "
  290. + "points on the ping graph?",
  291. manager.getConfigManager(), manager.getIdentity()));
  292. cat.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
  293. pluginInfo.getDomain(), "history", "Graph points", "Number of data points "
  294. + "to plot on the graph, if enabled.",
  295. manager.getConfigManager(), manager.getIdentity()));
  296. manager.getCategory("Plugins").addSubCategory(cat);
  297. }
  298. }