Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

LagDisplayManager.java 13KB

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