Debian Codegraph @

src/java/org/astrogrid/samp/hub/HubServiceMode.java

raw
1 package org.astrogrid.samp.hub;
2
3 import java.awt.AWTException;
4 import java.awt.CheckboxMenuItem;
5 import java.awt.Image;
6 import java.awt.Menu;
7 import java.awt.MenuItem;
8 import java.awt.PopupMenu;
9 import java.awt.Toolkit;
10 import java.awt.event.ActionEvent;
11 import java.awt.event.ActionListener;
12 import java.awt.event.ItemEvent;
13 import java.awt.event.ItemListener;
14 import java.awt.event.KeyEvent;
15 import java.awt.event.WindowAdapter;
16 import java.awt.event.WindowEvent;
17 import java.io.IOException;
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Random;
22 import java.util.logging.Logger;
23 import javax.swing.AbstractAction;
24 import javax.swing.Action;
25 import javax.swing.JCheckBoxMenuItem;
26 import javax.swing.JMenu;
27 import javax.swing.JMenuBar;
28 import javax.swing.JMenuItem;
29 import javax.swing.JFrame;
30 import javax.swing.JToggleButton;
31 import javax.swing.SwingUtilities;
32 import javax.swing.event.ChangeEvent;
33 import javax.swing.event.ChangeListener;
34 import org.astrogrid.samp.Client;
35 import org.astrogrid.samp.client.DefaultClientProfile;
36 import org.astrogrid.samp.client.SampException;
37 import org.astrogrid.samp.gui.ErrorDialog;
38 import org.astrogrid.samp.gui.GuiHubService;
39 import org.astrogrid.samp.gui.MessageTrackerHubService;
40 import org.astrogrid.samp.gui.SysTray;
41
42 /**
43 * Specifies a particular hub implementation for use with {@link Hub}.
44 *
45 * @author Mark Taylor
46 * @since 20 Nov 2008
47 */
48 public abstract class HubServiceMode {
49 // This class looks like an enumeration-type class to external users.
50 // It is actually a HubService factory.
51
52 private final String name_;
53 private final boolean isDaemon_;
54 private static final Logger logger_ =
55 Logger.getLogger( HubServiceMode.class.getName() );
56
57 /** Hub mode with no GUI representation of hub operations. */
58 public static final HubServiceMode NO_GUI;
59
60 /** Hub mode with a GUI representation of connected clients. */
61 public static final HubServiceMode CLIENT_GUI;
62
63 /** Hub mode with a GUI representation of clients and messages. */
64 public static HubServiceMode MESSAGE_GUI;
65
66 /** Hub Mode which piggy-backs on an existing hub using
67 * the default client profile. */
68 public static HubServiceMode FACADE;
69
70 /** Array of available hub modes. */
71 private static final HubServiceMode[] KNOWN_MODES = new HubServiceMode[] {
72 NO_GUI = createBasicHubMode( "no-gui" ),
73 CLIENT_GUI = createGuiHubMode( "client-gui" ),
74 MESSAGE_GUI = createMessageTrackerHubMode( "msg-gui" ),
75 FACADE = createFacadeHubMode( "facade" ),
76 };
77
78 /**
79 * Constructor.
80 *
81 * @param name mode name
82 * @param isDaemon true if the hub will start only daemon threads
83 */
84 HubServiceMode( String name, boolean isDaemon ) {
85 name_ = name;
86 isDaemon_ = isDaemon;
87 }
88
89 /**
90 * Creates and returns a new hub service object.
91 *
92 * @param random random number generator
93 * @param profiles hub profiles
94 * @param runners 1-element array of Hubs - this should be
95 * populated with the runner once it has been constructed
96 * @return object containing the hub service and possibly a window
97 */
98 abstract ServiceGui createHubService( Random random, HubProfile[] profiles,
99 Hub[] runners );
100
101 /**
102 * Indicates whether the hub service will start only daemon threads.
103 * If it returns true, the caller may need to make sure that the
104 * JVM doesn't stop too early.
105 *
106 * @return true iff no non-daemon threads will be started by the service
107 */
108 boolean isDaemon() {
109 return isDaemon_;
110 }
111
112 /**
113 * Returns this mode's name.
114 *
115 * @return mode name
116 */
117 String getName() {
118 return name_;
119 }
120
121 public String toString() {
122 return name_;
123 }
124
125 /**
126 * Returns one of the known modes which has a name as given.
127 *
128 * @param name mode name (case-insensitive)
129 * @return mode with given name, or null if none known
130 */
131 public static HubServiceMode getModeFromName( String name ) {
132 HubServiceMode[] modes = KNOWN_MODES;
133 for ( int im = 0; im < modes.length; im++ ) {
134 HubServiceMode mode = modes[ im ];
135 if ( mode.name_.equalsIgnoreCase( name ) ) {
136 return mode;
137 }
138 }
139 return null;
140 }
141
142 /**
143 * Returns an array of the hub modes which can actually be used.
144 *
145 * @return available mode list
146 */
147 public static HubServiceMode[] getAvailableModes() {
148 List modeList = new ArrayList();
149 for ( int i = 0; i < KNOWN_MODES.length; i++ ) {
150 HubServiceMode mode = KNOWN_MODES[ i ];
151 if ( ! ( mode instanceof BrokenHubMode ) ) {
152 modeList.add( mode );
153 }
154 }
155 return (HubServiceMode[]) modeList.toArray( new HubServiceMode[ 0 ] );
156 }
157
158 /**
159 * Used to perform common configuration of hub display windows
160 * for GUI-type hub modes.
161 *
162 * @param frame hub window
163 * @param profiles profiles to run for hub
164 * @param runners 1-element array which will contain an associated
165 * hub runner object if one exists
166 * @param hubService object providing hub services
167 * @return object which should be shutdown when the hub stops running
168 */
169 private static Tidier configureHubWindow( JFrame frame,
170 HubProfile[] profiles,
171 Hub[] runners,
172 GuiHubService hubService ) {
173 SysTray sysTray = SysTray.getInstance();
174 if ( sysTray.isSupported() ) {
175 try {
176 SysTrayWindowConfig winConfig =
177 new SysTrayWindowConfig( frame, profiles, runners,
178 hubService, sysTray );
179 winConfig.configureWindow();
180 winConfig.configureSysTray();
181 logger_.info( "Hub started in system tray" );
182 return winConfig;
183 }
184 catch ( AWTException e ) {
185 logger_.warning( "Failed to install in system tray: " + e );
186 BasicWindowConfig winConfig =
187 new BasicWindowConfig( frame, profiles, runners,
188 hubService );
189 winConfig.configureWindow();
190 return winConfig;
191 }
192 }
193 else {
194 logger_.info( "System tray not supported: displaying hub window" );
195 BasicWindowConfig winConfig =
196 new BasicWindowConfig( frame, profiles, runners, hubService );
197 winConfig.configureWindow();
198 return winConfig;
199 }
200 }
201
202 /**
203 * Constructs a mode for BasicHubService.
204 *
205 * @param name mode name
206 * @return non-gui mode
207 */
208 private static HubServiceMode createBasicHubMode( String name ) {
209 try {
210 return new HubServiceMode( name, true ) {
211 ServiceGui createHubService( Random random,
212 HubProfile[] profiles,
213 Hub[] runners ) {
214 ServiceGui serviceGui = new ServiceGui();
215 serviceGui.service_ = new BasicHubService( random );
216 return serviceGui;
217 }
218 };
219 }
220 catch ( Throwable e ) {
221 return new BrokenHubMode( name, e );
222 }
223 }
224
225 /**
226 * Constructs a mode for GuiHubService.
227 *
228 * @return mode without message tracking
229 */
230 private static HubServiceMode createGuiHubMode( String name ) {
231 try {
232
233 /* Check GuiHubService class is present; if GUI classes are
234 * missing in a stripped-down installation find out now
235 * (mode creation time) rather than service creation time. */
236 GuiHubService.class.getName();
237
238 /* Create and return the service. */
239 return new HubServiceMode( name, false ) {
240 ServiceGui createHubService( Random random,
241 final HubProfile[] profiles,
242 final Hub[] runners ) {
243 final ServiceGui serviceGui = new ServiceGui();
244 serviceGui.service_ = new GuiHubService( random ) {
245 volatile Runnable tidierCallback;
246 public void start() {
247 final GuiHubService service = this;
248 super.start();
249 SwingUtilities.invokeLater( new Runnable() {
250 public void run() {
251 JFrame window = createHubWindow();
252 final Tidier tidier =
253 configureHubWindow( window, profiles,
254 runners, service );
255 tidierCallback = new Runnable() {
256 public void run() {
257 tidier.tidyGui();
258 }
259 };
260 serviceGui.window_ = window;
261 }
262 } );
263 }
264 public void shutdown() {
265 super.shutdown();
266
267 /* It is (apparently) necessary under some
268 * circumstances to call an existing Runnable here
269 * rather than creating a new one because of
270 * weird (buggy?) shutdown behaviour
271 * in the JNLP class loader (fails with
272 * IllegalStateException: zip file closed).
273 * Report and fix provided by Laurent Bourges. */
274 if ( tidierCallback != null ) {
275 SwingUtilities.invokeLater( tidierCallback );
276 };
277 }
278 };
279 return serviceGui;
280 }
281 };
282 }
283 catch ( Throwable e ) {
284 return new BrokenHubMode( name, e );
285 }
286 }
287
288 /**
289 * Constructs a mode for MessageTrackerHubService.
290 *
291 * @return mode with message tracking
292 */
293 private static HubServiceMode createMessageTrackerHubMode( String name ) {
294 try {
295 MessageTrackerHubService.class.getName();
296 return new HubServiceMode( name, false ) {
297 ServiceGui createHubService( Random random,
298 final HubProfile[] profiles,
299 final Hub[] runners ) {
300 final ServiceGui serviceGui = new ServiceGui();
301 serviceGui.service_ =
302 new MessageTrackerHubService( random ) {
303 Tidier tidier;
304 public void start() {
305 super.start();
306 final MessageTrackerHubService service = this;
307 SwingUtilities.invokeLater( new Runnable() {
308 public void run() {
309 JFrame window = createHubWindow();
310 tidier = configureHubWindow( window,
311 profiles,
312 runners,
313 service );
314 serviceGui.window_ = window;
315 }
316 } );
317 }
318 public void shutdown() {
319 super.shutdown();
320 SwingUtilities.invokeLater( new Runnable() {
321 public void run() {
322 if ( tidier != null ) {
323 tidier.tidyGui();
324 }
325 }
326 } );
327 }
328 };
329 return serviceGui;
330 }
331 };
332 }
333 catch ( Throwable e ) {
334 return new BrokenHubMode( name, e );
335 }
336 }
337
338 /**
339 * Constructs a mode for FacadeHubService.
340 *
341 * @return mode based on the default client profile
342 */
343 private static HubServiceMode createFacadeHubMode( String name ) {
344 return new HubServiceMode( name, true ) {
345 ServiceGui createHubService( Random random, HubProfile[] profiles,
346 final Hub[] runners ) {
347 ServiceGui serviceGui = new ServiceGui();
348 serviceGui.service_ =
349 new FacadeHubService( DefaultClientProfile.getProfile() );
350 return serviceGui;
351 }
352 };
353 }
354
355 /**
356 * HubServiceMode implementation for modes which cannot be used because they
357 * rely on classes unavailable at runtime.
358 */
359 private static class BrokenHubMode extends HubServiceMode {
360 private final Throwable error_;
361
362 /**
363 * Constructor.
364 *
365 * @param name mode name
366 * @param error error explaining why mode is unavailable for use
367 */
368 BrokenHubMode( String name, Throwable error ) {
369 super( name, false );
370 error_ = error;
371 }
372 ServiceGui createHubService( Random random, HubProfile[] profiles,
373 Hub[] runners ) {
374 throw new RuntimeException( "Hub mode " + getName()
375 + " unavailable", error_ );
376 }
377 }
378
379 /**
380 * Utility abstract class to define an object which can be tidied up
381 * on hub shutdown.
382 */
383 private interface Tidier {
384
385 /**
386 * Performs any required tidying operations.
387 * May be assumed to be called on the AWT Event Dispatch Thread.
388 */
389 void tidyGui();
390 }
391
392 /**
393 * Aggregates a HubService and an associated monitor/control window.
394 */
395 static class ServiceGui {
396 private volatile HubService service_;
397 private JFrame window_;
398
399 /**
400 * Returns the hub service.
401 *
402 * @return hub service object
403 */
404 public HubService getHubService() {
405 return service_;
406 }
407
408 /**
409 * Returns a monitor/control window for this service, if available.
410 *
411 * @return window, or null
412 */
413 public JFrame getWindow() {
414 return window_;
415 }
416 }
417
418 /**
419 * Class to configure a window for use as a hub control.
420 */
421 private static class BasicWindowConfig implements Tidier {
422 final JFrame frame_;
423 final Hub[] runners_;
424 final GuiHubService hubService_;
425 final ProfileToggler[] profileTogglers_;
426 final ConfigHubProfile[] configProfiles_;
427 final Action exitAct_;
428
429 /**
430 * Constructor.
431 *
432 * @param frame hub window
433 * @param profiles hub profiles to run
434 * @param runners 1-element array which will contain an associated
435 * hub runner object if one exists
436 * @param hubService object providing hub services
437 */
438 BasicWindowConfig( JFrame frame, HubProfile[] profiles,
439 final Hub[] runners, GuiHubService hubService ) {
440 frame_ = frame;
441 runners_ = runners;
442 hubService_ = hubService;
443 profileTogglers_ = new ProfileToggler[ profiles.length ];
444 List configProfileList = new ArrayList();
445 for ( int ip = 0; ip < profiles.length; ip++ ) {
446 HubProfile profile = profiles[ ip ];
447 profileTogglers_[ ip ] = new ProfileToggler( profile, runners );
448 if ( profile instanceof ConfigHubProfile ) {
449 configProfileList.add( (ConfigHubProfile) profile );
450 }
451 }
452 configProfiles_ =
453 (ConfigHubProfile[])
454 configProfileList.toArray( new ConfigHubProfile[ 0 ] );
455 exitAct_ = new AbstractAction( "Stop Hub" ) {
456 public void actionPerformed( ActionEvent evt ) {
457 if ( runners[ 0 ] != null ) {
458 runners[ 0 ].shutdown();
459 }
460 tidyGui();
461 }
462 };
463 exitAct_.putValue( Action.SHORT_DESCRIPTION,
464 "Shut down SAMP hub" );
465 exitAct_.putValue( Action.MNEMONIC_KEY,
466 Integer.valueOf( KeyEvent.VK_T ) );
467 }
468
469 /**
470 * Perform configuration of window.
471 */
472 public void configureWindow() {
473 configureMenus();
474 frame_.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
475 frame_.setVisible( true );
476 frame_.addWindowListener( new WindowAdapter() {
477 public void windowClosed( WindowEvent evt ) {
478 Hub runner = runners_[ 0 ];
479 if ( runner != null ) {
480 runner.shutdown();
481 }
482 }
483 } );
484 }
485
486 /**
487 * Configures menus on the window. Invoked by configureWindow.
488 */
489 protected void configureMenus() {
490 JMenuBar mbar = new JMenuBar();
491 JMenu fileMenu = new JMenu( "File" );
492 fileMenu.setMnemonic( KeyEvent.VK_F );
493 fileMenu.add( new JMenuItem( exitAct_ ) );
494 mbar.add( fileMenu );
495 JMenu[] serviceMenus = hubService_.createMenus();
496 for ( int im = 0; im < serviceMenus.length; im++ ) {
497 mbar.add( serviceMenus[ im ] );
498 }
499 JMenu profileMenu = new JMenu( "Profiles" );
500 profileMenu.setMnemonic( KeyEvent.VK_P );
501 for ( int ip = 0; ip < profileTogglers_.length; ip++ ) {
502 profileMenu.add( profileTogglers_[ ip ].createJMenuItem() );
503 }
504
505 // Add configuration menus - somewhat hacky, only really intended
506 // for Web Profile at present.
507 for ( int ic = 0; ic < configProfiles_.length; ic++ ) {
508 ConfigHubProfile configProfile = configProfiles_[ ic ];
509 JToggleButton.ToggleButtonModel[] configModels =
510 configProfile.getConfigModels();
511 JMenu configMenu =
512 new JMenu( configProfile.getProfileName()
513 + " Profile Configuration" );
514 for ( int im = 0; im < configModels.length; im++ ) {
515 JToggleButton.ToggleButtonModel model = configModels[ im ];
516 JCheckBoxMenuItem menuItem =
517 new JCheckBoxMenuItem( model.toString() );
518 menuItem.setModel( model );
519 configMenu.add( menuItem );
520 }
521 profileMenu.add( configMenu );
522 }
523 mbar.add( profileMenu );
524 frame_.setJMenuBar( mbar );
525 }
526
527 public void tidyGui() {
528 if ( frame_.isDisplayable() ) {
529 frame_.dispose();
530 }
531 }
532 }
533
534 /**
535 * Takes care of hub display window configuration with system tray
536 * functionality.
537 */
538 private static class SysTrayWindowConfig extends BasicWindowConfig {
539 private final SysTray sysTray_;
540 private final Action showAct_;
541 private final Action hideAct_;
542 private final MenuItem showItem_;
543 private final MenuItem hideItem_;
544 private final MenuItem exitItem_;
545 private final ActionListener iconListener_;
546 private Object trayIcon_;
547
548 /**
549 * Constructor.
550 *
551 * @param frame hub window
552 * @param profiles hub profiles to run
553 * @param runners 1-element array which will contain an associated
554 * hub runner object if one exists
555 * @param hubService object providing hub services
556 * @param sysTray system tray facade object
557 */
558 SysTrayWindowConfig( JFrame frame, HubProfile[] profiles, Hub[] runners,
559 GuiHubService hubService, SysTray sysTray ) {
560 super( frame, profiles, runners, hubService );
561 sysTray_ = sysTray;
562 showAct_ = new AbstractAction( "Show Hub Window" ) {
563 public void actionPerformed( ActionEvent evt ) {
564 setWindowVisible( true );
565 }
566 };
567 hideAct_ = new AbstractAction( "Hide Hub Window" ) {
568 public void actionPerformed( ActionEvent evt ) {
569 setWindowVisible( false );
570 }
571 };
572 showItem_ = toMenuItem( showAct_ );
573 hideItem_ = toMenuItem( hideAct_ );
574 exitItem_ = toMenuItem( exitAct_ );
575 iconListener_ = showAct_;
576 }
577
578 protected void configureMenus() {
579 super.configureMenus();
580 frame_.getJMenuBar().getMenu( 0 ).add( new JMenuItem( hideAct_ ) );
581 }
582
583 public void configureWindow() {
584 configureMenus();
585 frame_.setDefaultCloseOperation( JFrame.HIDE_ON_CLOSE );
586
587 // Arrange that a manual window close will set the action states
588 // correctly.
589 frame_.addWindowListener( new WindowAdapter() {
590 public void windowClosing( WindowEvent evt ) {
591 showAct_.setEnabled( true );
592 hideAct_.setEnabled( false );
593 }
594 } );
595 hideAct_.actionPerformed( null );
596 }
597
598 /**
599 * Performs configuration.
600 */
601 public void configureSysTray() throws AWTException {
602 Image im = Toolkit.getDefaultToolkit()
603 .createImage( Client.class
604 .getResource( "images/hub.png" ) );
605 String tooltip = "SAMP Hub";
606 PopupMenu popup = new PopupMenu();
607 Menu profileMenu = new Menu( "Profiles" );
608 for ( int ip = 0; ip < profileTogglers_.length; ip++ ) {
609 profileMenu.add( profileTogglers_[ ip ].createMenuItem() );
610 }
611 popup.add( profileMenu );
612 popup.add( showItem_ );
613 popup.add( hideItem_ );
614 popup.add( exitItem_ );
615 trayIcon_ = sysTray_.addIcon( im, tooltip, popup, iconListener_ );
616 }
617
618 public void tidyGui() {
619 super.tidyGui();
620 try {
621 sysTray_.removeIcon( trayIcon_ );
622 }
623 catch ( AWTException e ) {
624 logger_.warning( "Can't remove hub system tray icon: " + e );
625 }
626 }
627
628 /**
629 * Sets visibility for the hub control window, adjusting actions
630 * as appropriate.
631 *
632 * @param isVis true for visible, false for invisible
633 */
634 private void setWindowVisible( boolean isVis ) {
635 frame_.setVisible( isVis );
636 showAct_.setEnabled( ! isVis );
637 hideAct_.setEnabled( isVis );
638 showItem_.setEnabled( ! isVis );
639 hideItem_.setEnabled( isVis );
640 }
641
642 /**
643 * Turns an action into an AWT menu item.
644 *
645 * @param act action
646 * @return MenuItem facade
647 */
648 private MenuItem toMenuItem( Action act ) {
649 MenuItem item =
650 new MenuItem( (String) act.getValue( Action.NAME ) );
651 item.addActionListener( act );
652 return item;
653 }
654 }
655
656 /**
657 * Manages a toggle button for starting/stopping profiles.
658 * This object can supply both Swing JMenuItems and AWT MenuItems
659 * with effectively the same model (which is quite hard work).
660 */
661 private static class ProfileToggler {
662 final HubProfile profile_;
663 final Hub[] runners_;
664 final String title_;
665 final JToggleButton.ToggleButtonModel toggleModel_;
666 final List menuItemList_;
667
668 /**
669 * Constructor.
670 *
671 * @param profile profile to operate on
672 * @param runners one-element array containing hub
673 */
674 ProfileToggler( HubProfile profile, Hub[] runners ) {
675 profile_ = profile;
676 runners_ = runners;
677 title_ = profile.getProfileName() + " Profile";
678 menuItemList_ = new ArrayList();
679 toggleModel_ = new JToggleButton.ToggleButtonModel() {
680 public boolean isSelected() {
681 return profile_.isRunning();
682 }
683 public void setSelected( boolean on ) {
684 Hub hub = runners_[ 0 ];
685 if ( hub != null ) {
686 if ( on && ! profile_.isRunning() ) {
687 try {
688 hub.startProfile( profile_ );
689 super.setSelected( on );
690 }
691 catch ( IOException e ) {
692 ErrorDialog
693 .showError( null, title_ + " Start Error",
694 "Error starting " + title_, e );
695 return;
696 }
697 }
698 else if ( ! on && profile_.isRunning() ) {
699 hub.stopProfile( profile_ );
700 }
701 }
702 super.setSelected( on );
703 }
704 };
705 toggleModel_.addChangeListener( new ChangeListener() {
706 public void stateChanged( ChangeEvent evt ) {
707 updateMenuItems();
708 }
709 } );
710 }
711
712 /**
713 * Returns a new Swing JMenuItem for start/stop toggle.
714 *
715 * @return menu item
716 */
717 public JMenuItem createJMenuItem() {
718 JCheckBoxMenuItem item = new JCheckBoxMenuItem( title_ );
719 item.setToolTipText( "Start or stop the " + title_ );
720 char chr = Character
721 .toUpperCase( profile_.getProfileName().charAt( 0 ) );
722 if ( chr >= 'A' && chr <= 'Z' ) {
723 item.setMnemonic( (int) chr );
724 }
725 item.setModel( toggleModel_ );
726 return item;
727 }
728
729 /**
730 * Returns a new AWT MenuItem for start/stop toggle.
731 *
732 * @return menu item
733 */
734 public MenuItem createMenuItem() {
735 final CheckboxMenuItem item = new CheckboxMenuItem( title_ );
736 item.addItemListener( new ItemListener() {
737 public void itemStateChanged( ItemEvent evt ) {
738 boolean on = item.getState();
739 toggleModel_.setSelected( on );
740 if ( toggleModel_.isSelected() != on ) {
741 item.setState( toggleModel_.isSelected() );
742 }
743 }
744 } );
745 item.setState( toggleModel_.isSelected() );
746 menuItemList_.add( item );
747 return item;
748 }
749
750 /**
751 * Updates all dispatched menu items to the current state.
752 */
753 private void updateMenuItems() {
754 for ( Iterator it = menuItemList_.iterator(); it.hasNext(); ) {
755 CheckboxMenuItem item = (CheckboxMenuItem) it.next();
756 boolean on = toggleModel_.isSelected();
757 if ( item.getState() != on ) {
758 item.setState( on );
759 }
760 }
761 }
762 }
763 }