Debian Codegraph @

src/java/org/astrogrid/samp/gui/SendActionManager.java

raw
1 package org.astrogrid.samp.gui;
2
3 import java.awt.Toolkit;
4 import java.awt.event.ActionEvent;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.Iterator;
8 import java.util.List;
9 import java.util.logging.Logger;
10 import javax.swing.AbstractAction;
11 import javax.swing.AbstractListModel;
12 import javax.swing.Action;
13 import javax.swing.ComboBoxModel;
14 import javax.swing.Icon;
15 import javax.swing.ImageIcon;
16 import javax.swing.JMenu;
17 import javax.swing.event.ChangeEvent;
18 import javax.swing.event.ChangeListener;
19 import javax.swing.event.ListDataEvent;
20 import javax.swing.event.ListDataListener;
21 import javax.swing.ListModel;
22 import javax.swing.SwingUtilities;
23 import org.astrogrid.samp.Client;
24
25 /**
26 * Manages actions to send SAMP messages to one or all recipients.
27 * The main useful trick that this class can do is to maintain one or
28 * more menus for sending messages to suitable recipients.
29 * The contents of these menus are updated automatically depending on
30 * the subscriptions of all the currently registered SAMP clients.
31 *
32 * <p>Note: concrete subclasses must call {@link #updateState} before use
33 * (in the constructor).
34 *
35 * @author Mark Taylor
36 * @since 2 Sep 2008
37 */
38 public abstract class SendActionManager {
39
40 private final GuiHubConnector connector_;
41 final ListModel subscribedClientModel_;
42 private final List menuList_;
43 private final ListDataListener subscriptionListener_;
44 private final ChangeListener connectionListener_;
45 private boolean enabled_;
46 private Action broadcastAct_;
47 private boolean broadcastActCreated_;
48 private Action[] sendActs_;
49 private static Icon SEND_ICON;
50 private static Icon BROADCAST_ICON;
51 private static final Logger logger_ =
52 Logger.getLogger( SendActionManager.class.getName() );
53
54 /** ComboBox element indicating broadcast to all clients. */
55 public static final String BROADCAST_TARGET = "All Clients";
56
57 /**
58 * Constructor.
59 *
60 * @param connector hub connector
61 * @param clientListModel list model containing only those
62 * clients which are suitable recipients;
63 * all elements must be {@link org.astrogrid.samp.Client}s
64 */
65 protected SendActionManager( GuiHubConnector connector,
66 ListModel clientListModel ) {
67 connector_ = connector;
68 subscribedClientModel_ = clientListModel;
69 subscriptionListener_ = new ListDataListener() {
70 public void intervalAdded( ListDataEvent evt ) {
71 updateState();
72 }
73 public void intervalRemoved( ListDataEvent evt ) {
74 updateState();
75 }
76 public void contentsChanged( ListDataEvent evt ) {
77 updateState();
78 }
79 };
80 subscribedClientModel_.addListDataListener( subscriptionListener_ );
81
82 // Ensure that changes to the connection status are reflected.
83 connectionListener_ = new ChangeListener() {
84 public void stateChanged( ChangeEvent evt ) {
85 updateEnabledness();
86 }
87 };
88 connector.addConnectionListener( connectionListener_ );
89
90 // Initialise other state.
91 enabled_ = true;
92 menuList_ = new ArrayList();
93 }
94
95 /**
96 * Returns a new action for broadcast associated with this object.
97 * The enabled status of the action will be managed by this object.
98 *
99 * @return broadcast action; may be null if broadcast is not required
100 */
101 protected abstract Action createBroadcastAction();
102
103 /**
104 * Returns an action which can perform a single-client send associated
105 * with this object. If it implements <code>equals</code>
106 * (and <code>hashCode</code>) intelligently there will be efficiency
107 * advantages.
108 * The enabled status of such actions will be managed by this object.
109 *
110 * @param client recipient client
111 * @return action which sends to the given client
112 */
113 protected abstract Action getSendAction( Client client );
114
115 /**
116 * Sets the enabled status of this object. This acts as a restriction
117 * (AND) on the enabled status of the menus and actions controlled by
118 * this object. If there are no suitable recipient applications
119 * registered they will be disabled anyway.
120 *
121 * @param enabled false to ensure that the actions are disabled,
122 * true means they may be enabled
123 */
124 public void setEnabled( boolean enabled ) {
125 enabled_ = enabled;
126 updateEnabledness();
127 }
128
129 /**
130 * Returns an action which will broadcast a message
131 * to all suitable registered applications.
132 *
133 * <p>This action is currently not disabled when there are no suitable
134 * listeners, mainly for debugging purposes (so you can see if a
135 * message is getting sent and what it looks like even in absence of
136 * suitable listeners).
137 *
138 * @return broadcast action
139 */
140 public Action getBroadcastAction() {
141 if ( ! broadcastActCreated_ ) {
142 broadcastAct_ = createBroadcastAction();
143 broadcastActCreated_ = true;
144 updateEnabledness();
145 }
146 return broadcastAct_;
147 }
148
149 /**
150 * Returns a new menu which provides options to send a message to
151 * one of the registered listeners at a time. This menu will be
152 * disabled when no suitable listeners are registered.
153 *
154 * @param name menu title
155 * @return new message send menu
156 */
157 public JMenu createSendMenu( String name ) {
158 JMenu menu = new JMenu( name );
159 for ( int is = 0; is < sendActs_.length; is++ ) {
160 menu.add( sendActs_[ is ] );
161 }
162 menuList_.add( menu );
163 updateEnabledness();
164 return menu;
165 }
166
167 /**
168 * Releases any resources associated with a menu previously created
169 * using {@link #createSendMenu}. Don't use the menu again.
170 *
171 * @param menu previously created send menu
172 */
173 public void disposeSendMenu( JMenu menu ) {
174 menuList_.remove( menu );
175 }
176
177 /**
178 * Releases any resources associated with this object.
179 */
180 public void dispose() {
181 subscribedClientModel_.removeListDataListener( subscriptionListener_ );
182 if ( subscribedClientModel_ instanceof SubscribedClientListModel ) {
183 ((SubscribedClientListModel) subscribedClientModel_).dispose();
184 }
185 connector_.removeConnectionListener( connectionListener_ );
186 }
187
188 /**
189 * Updates the state of actions managed by this object when the
190 * list of registered listeners has changed.
191 */
192 public void updateState() {
193
194 // Get a list of actions for the currently subscribed clients.
195 int nsub = subscribedClientModel_.getSize();
196 Action[] sendActs = new Action[ nsub ];
197 for ( int ia = 0; ia < nsub; ia++ ) {
198 sendActs[ ia ] =
199 getSendAction( (Client)
200 subscribedClientModel_.getElementAt( ia ) );
201 }
202
203 // Update menus if required.
204 if ( ! Arrays.equals( sendActs, sendActs_ ) ) {
205 sendActs_ = sendActs;
206 for ( Iterator menuIt = menuList_.iterator(); menuIt.hasNext(); ) {
207 JMenu menu = (JMenu) menuIt.next();
208 menu.removeAll();
209 for ( int is = 0; is < sendActs.length; is++ ) {
210 menu.add( sendActs[ is ] );
211 }
212 }
213 updateEnabledness();
214 }
215 }
216
217 /**
218 * Returns the client list to which this manager will offer sends.
219 *
220 * @return listmodel whose elements are suitably subscribed {@link Client}s
221 */
222 public ListModel getClientListModel() {
223 return subscribedClientModel_;
224 }
225
226 /**
227 * Returns a new ComboBoxModel containing selections for each suitable
228 * client and an additional selection for broadcast to all clients.
229 * Elements are {@link org.astrogrid.samp.Client} objects, or
230 * {@link #BROADCAST_TARGET} to indicate broadcast.
231 * The result of this is suitable for use with {@link #createTargetAction}.
232 *
233 * @return new client combo box model
234 */
235 public ComboBoxModel createTargetSelector() {
236 return new TargetComboBoxModel( subscribedClientModel_ );
237 }
238
239 /**
240 * Returns an action suitable for sending the message represented by
241 * this manager to a target selected by a supplied ComboBoxModel.
242 * This model is typically the result of calling
243 * {@link #createTargetSelector}.
244 *
245 * @param targetSelector combo box model in which the elements are
246 * {@link org.astrogrid.samp.Client} objects,
247 * or {@link #BROADCAST_TARGET} null to indicate broadcast
248 */
249 public Action createTargetAction( final ComboBoxModel targetSelector ) {
250 return new AbstractAction( "Send to selected target" ) {
251 public void actionPerformed( ActionEvent evt ) {
252 Object target = targetSelector.getSelectedItem();
253 if ( target instanceof Client ) {
254 getSendAction( (Client) target ).actionPerformed( evt );
255 }
256 else if ( BROADCAST_TARGET.equals( target ) ) {
257 getBroadcastAction().actionPerformed( evt );
258 }
259 else {
260 Toolkit.getDefaultToolkit().beep();
261 logger_.warning( "Unknown send target: " + target
262 + " - no action" );
263 }
264 }
265 };
266 }
267
268 /**
269 * Returns this manager's hub connector.
270 *
271 * @return connector
272 */
273 public GuiHubConnector getConnector() {
274 return connector_;
275 }
276
277 /**
278 * Updates the enabled status of controlled actions in accordance with
279 * this object's current state.
280 */
281 private void updateEnabledness() {
282 boolean active = enabled_
283 && connector_.isConnected()
284 && sendActs_.length > 0;
285 if ( broadcastAct_ != null ) {
286 broadcastAct_.setEnabled( active );
287 }
288 for ( Iterator it = menuList_.iterator(); it.hasNext(); ) {
289 ((JMenu) it.next()).setEnabled( active );
290 }
291 }
292
293 /**
294 * Returns an icon suitable for depicting a general targetted send.
295 *
296 * @return send icon
297 */
298 public static Icon getSendIcon() {
299 if ( SEND_ICON == null ) {
300 SEND_ICON = IconStore.createResourceIcon( "phone2.gif" );
301 }
302 return SEND_ICON;
303 }
304
305 /**
306 * Returns an icon suitable for depicting a general broadcast send.
307 *
308 * @return broadcast icon
309 */
310 public static Icon getBroadcastIcon() {
311 if ( BROADCAST_ICON == null ) {
312 BROADCAST_ICON = IconStore.createResourceIcon( "tx3.gif" );
313 }
314 return BROADCAST_ICON;
315 }
316
317 /**
318 * ComboBoxModel implementation used for selecting a target client.
319 * It essentiall mirrors an existing client model but prepends a
320 * broadcast option.
321 */
322 private static class TargetComboBoxModel extends AbstractListModel
323 implements ComboBoxModel {
324 private final ListModel clientListModel_;
325 private Object selectedItem_ = BROADCAST_TARGET;
326
327 /**
328 * Constructor.
329 *
330 * @param clientListModel list model containing suitable
331 * {@link org.astrogrid.samp.Client}s
332 */
333 TargetComboBoxModel( ListModel clientListModel ) {
334 clientListModel_ = clientListModel;
335
336 /* Watch the underlying client model for changes and
337 * update this one accordingly. */
338 clientListModel_.addListDataListener( new ListDataListener() {
339 public void contentsChanged( ListDataEvent evt ) {
340 fireContentsChanged( evt.getSource(),
341 adjustIndex( evt.getIndex0() ),
342 adjustIndex( evt.getIndex1() ) );
343 }
344 public void intervalAdded( ListDataEvent evt ) {
345 fireIntervalAdded( evt.getSource(),
346 adjustIndex( evt.getIndex0() ),
347 adjustIndex( evt.getIndex1() ) );
348 }
349 public void intervalRemoved( ListDataEvent evt ) {
350 fireIntervalRemoved( evt.getSource(),
351 adjustIndex( evt.getIndex0() ),
352 adjustIndex( evt.getIndex1() ) );
353 }
354 private int adjustIndex( int index ) {
355 return index >= 0 ? index + 1
356 : index;
357 }
358 } );
359 }
360
361 public int getSize() {
362 return clientListModel_.getSize() + 1;
363 }
364
365 public Object getElementAt( int index ) {
366 return index == 0 ? BROADCAST_TARGET
367 : clientListModel_.getElementAt( index - 1 );
368 }
369
370 public Object getSelectedItem() {
371 return selectedItem_;
372 }
373
374 public void setSelectedItem( Object item ) {
375 selectedItem_ = item;
376 }
377 }
378 }