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

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