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

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