2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2017 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
31 import java
.io
.InputStream
;
32 import java
.io
.IOException
;
33 import java
.io
.OutputStream
;
34 import java
.io
.PrintWriter
;
35 import java
.io
.Reader
;
36 import java
.io
.UnsupportedEncodingException
;
37 import java
.util
.Collections
;
38 import java
.util
.Date
;
39 import java
.util
.HashMap
;
40 import java
.util
.ArrayList
;
41 import java
.util
.LinkedList
;
42 import java
.util
.List
;
45 import jexer
.bits
.CellAttributes
;
46 import jexer
.bits
.ColorTheme
;
47 import jexer
.event
.TCommandEvent
;
48 import jexer
.event
.TInputEvent
;
49 import jexer
.event
.TKeypressEvent
;
50 import jexer
.event
.TMenuEvent
;
51 import jexer
.event
.TMouseEvent
;
52 import jexer
.event
.TResizeEvent
;
53 import jexer
.backend
.Backend
;
54 import jexer
.backend
.Screen
;
55 import jexer
.backend
.SwingBackend
;
56 import jexer
.backend
.ECMA48Backend
;
57 import jexer
.backend
.TWindowBackend
;
58 import jexer
.menu
.TMenu
;
59 import jexer
.menu
.TMenuItem
;
60 import static jexer
.TCommand
.*;
61 import static jexer
.TKeypress
.*;
64 * TApplication is the main driver class for a full Text User Interface
65 * application. It manages windows, provides a menu bar and status bar, and
66 * processes events received from the user.
68 public class TApplication
implements Runnable
{
70 // ------------------------------------------------------------------------
71 // Public constants -------------------------------------------------------
72 // ------------------------------------------------------------------------
75 * If true, emit thread stuff to System.err.
77 private static final boolean debugThreads
= false;
80 * If true, emit events being processed to System.err.
82 private static final boolean debugEvents
= false;
85 * If true, do "smart placement" on new windows that are not specified to
88 private static final boolean smartWindowPlacement
= true;
91 * Two backend types are available.
93 public static enum BackendType
{
100 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
105 * Synonym for ECMA48.
110 // ------------------------------------------------------------------------
111 // Primary/secondary event handlers ---------------------------------------
112 // ------------------------------------------------------------------------
115 * WidgetEventHandler is the main event consumer loop. There are at most
116 * two such threads in existence: the primary for normal case and a
117 * secondary that is used for TMessageBox, TInputBox, and similar.
119 private class WidgetEventHandler
implements Runnable
{
121 * The main application.
123 private TApplication application
;
126 * Whether or not this WidgetEventHandler is the primary or secondary
129 private boolean primary
= true;
132 * Public constructor.
134 * @param application the main application
135 * @param primary if true, this is the primary event handler thread
137 public WidgetEventHandler(final TApplication application
,
138 final boolean primary
) {
140 this.application
= application
;
141 this.primary
= primary
;
150 while (!application
.quit
) {
152 // Wait until application notifies me
153 while (!application
.quit
) {
155 synchronized (application
.drainEventQueue
) {
156 if (application
.drainEventQueue
.size() > 0) {
161 synchronized (this) {
163 System
.err
.printf("%s %s sleep\n", this,
164 primary ?
"primary" : "secondary");
170 System
.err
.printf("%s %s AWAKE\n", this,
171 primary ?
"primary" : "secondary");
175 && (application
.secondaryEventReceiver
== null)
177 // Secondary thread, emergency exit. If we
178 // got here then something went wrong with
179 // the handoff between yield() and
181 synchronized (application
.primaryEventHandler
) {
182 application
.primaryEventHandler
.notify();
184 application
.secondaryEventHandler
= null;
185 throw new RuntimeException(
186 "secondary exited at wrong time");
190 } catch (InterruptedException e
) {
195 // Wait for drawAll() or doIdle() to be done, then handle the
197 boolean oldLock
= lockHandleEvent();
198 assert (oldLock
== false);
200 // Pull all events off the queue
202 TInputEvent event
= null;
203 synchronized (application
.drainEventQueue
) {
204 if (application
.drainEventQueue
.size() == 0) {
207 event
= application
.drainEventQueue
.remove(0);
209 application
.repaint
= true;
211 primaryHandleEvent(event
);
213 secondaryHandleEvent(event
);
216 && (application
.secondaryEventReceiver
== null)
218 // Secondary thread, time to exit.
220 // DO NOT UNLOCK. Primary thread just came back from
221 // primaryHandleEvent() and will unlock in the else
222 // block below. Just wake it up.
223 synchronized (application
.primaryEventHandler
) {
224 application
.primaryEventHandler
.notify();
226 // Now eliminate my reference so that
227 // wakeEventHandler() resumes working on the primary.
228 application
.secondaryEventHandler
= null;
235 // Unlock. Either I am primary thread, or I am secondary
236 // thread and still running.
237 oldLock
= unlockHandleEvent();
238 assert (oldLock
== true);
240 // I have done some work of some kind. Tell the main run()
241 // loop to wake up now.
242 synchronized (application
) {
243 application
.notify();
246 } // while (true) (main runnable loop)
251 * The primary event handler thread.
253 private volatile WidgetEventHandler primaryEventHandler
;
256 * The secondary event handler thread.
258 private volatile WidgetEventHandler secondaryEventHandler
;
261 * The widget receiving events from the secondary event handler thread.
263 private volatile TWidget secondaryEventReceiver
;
266 * Spinlock for the primary and secondary event handlers.
267 * WidgetEventHandler.run() is responsible for setting this value.
269 private volatile boolean insideHandleEvent
= false;
272 * Wake the sleeping active event handler.
274 private void wakeEventHandler() {
275 if (secondaryEventHandler
!= null) {
276 synchronized (secondaryEventHandler
) {
277 secondaryEventHandler
.notify();
280 assert (primaryEventHandler
!= null);
281 synchronized (primaryEventHandler
) {
282 primaryEventHandler
.notify();
288 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
289 * spin indefinitely until unlockHandleEvent() is called.
291 * @return the old value of insideHandleEvent
293 private boolean lockHandleEvent() {
295 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
298 boolean oldValue
= true;
300 synchronized (this) {
301 // Wait for TApplication.run() to finish using the global state
302 // before allowing further event processing.
303 while (lockoutHandleEvent
== true) {
305 // Backoff so that the backend can finish its work.
307 } catch (InterruptedException e
) {
312 oldValue
= insideHandleEvent
;
313 insideHandleEvent
= true;
317 System
.err
.printf(" ***\n");
323 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
324 * spin indefinitely until unlockHandleEvent() is called.
326 * @return the old value of insideHandleEvent
328 private boolean unlockHandleEvent() {
330 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
333 synchronized (this) {
334 boolean oldValue
= insideHandleEvent
;
335 insideHandleEvent
= false;
341 * Spinlock for the primary and secondary event handlers. When true, the
342 * event handlers will spinlock wait before calling handleEvent().
344 private volatile boolean lockoutHandleEvent
= false;
347 * TApplication.run() needs to be able rely on the global data structures
348 * being intact when calling doIdle() and drawAll(). Tell the event
349 * handlers to wait for an unlock before handling their events.
351 private void stopEventHandlers() {
353 System
.err
.printf(">> stopEventHandlers()");
356 lockoutHandleEvent
= true;
357 // Wait for the last event to finish processing before returning
358 // control to TApplication.run().
359 while (insideHandleEvent
== true) {
361 // Backoff so that the event handler can finish its work.
363 } catch (InterruptedException e
) {
369 System
.err
.printf(" XXX\n");
374 * TApplication.run() needs to be able rely on the global data structures
375 * being intact when calling doIdle() and drawAll(). Tell the event
376 * handlers that it is now OK to handle their events.
378 private void startEventHandlers() {
380 System
.err
.printf("<< startEventHandlers()\n");
382 lockoutHandleEvent
= false;
385 // ------------------------------------------------------------------------
386 // TApplication attributes ------------------------------------------------
387 // ------------------------------------------------------------------------
390 * Access to the physical screen, keyboard, and mouse.
392 private Backend backend
;
397 * @return the Backend
399 public final Backend
getBackend() {
408 public final Screen
getScreen() {
409 if (backend
instanceof TWindowBackend
) {
410 // We are being rendered to a TWindow. We can't use its
411 // getScreen() method because that is how it is rendering to a
412 // hardware backend somewhere. Instead use its getOtherScreen()
414 return ((TWindowBackend
) backend
).getOtherScreen();
416 return backend
.getScreen();
421 * Actual mouse coordinate X.
426 * Actual mouse coordinate Y.
431 * Old version of mouse coordinate X.
433 private int oldMouseX
;
436 * Old version mouse coordinate Y.
438 private int oldMouseY
;
441 * Event queue that is filled by run().
443 private List
<TInputEvent
> fillEventQueue
;
446 * Event queue that will be drained by either primary or secondary
449 private List
<TInputEvent
> drainEventQueue
;
452 * Top-level menus in this application.
454 private List
<TMenu
> menus
;
457 * Stack of activated sub-menus in this application.
459 private List
<TMenu
> subMenus
;
462 * The currently active menu.
464 private TMenu activeMenu
= null;
467 * Active keyboard accelerators.
469 private Map
<TKeypress
, TMenuItem
> accelerators
;
474 private List
<TMenuItem
> menuItems
;
477 * Windows and widgets pull colors from this ColorTheme.
479 private ColorTheme theme
;
482 * Get the color theme.
486 public final ColorTheme
getTheme() {
491 * The top-level windows (but not menus).
493 private List
<TWindow
> windows
;
496 * The currently acive window.
498 private TWindow activeWindow
= null;
501 * Timers that are being ticked.
503 private List
<TTimer
> timers
;
506 * When true, exit the application.
508 private volatile boolean quit
= false;
511 * When true, repaint the entire screen.
513 private volatile boolean repaint
= true;
516 * Y coordinate of the top edge of the desktop. For now this is a
517 * constant. Someday it would be nice to have a multi-line menu or
520 private static final int desktopTop
= 1;
523 * Get Y coordinate of the top edge of the desktop.
525 * @return Y coordinate of the top edge of the desktop
527 public final int getDesktopTop() {
532 * Y coordinate of the bottom edge of the desktop.
534 private int desktopBottom
;
537 * Get Y coordinate of the bottom edge of the desktop.
539 * @return Y coordinate of the bottom edge of the desktop
541 public final int getDesktopBottom() {
542 return desktopBottom
;
546 * An optional TDesktop background window that is drawn underneath
549 private TDesktop desktop
;
552 * Set the TDesktop instance.
554 * @param desktop a TDesktop instance, or null to remove the one that is
557 public final void setDesktop(final TDesktop desktop
) {
558 if (this.desktop
!= null) {
559 this.desktop
.onClose();
561 this.desktop
= desktop
;
565 * Get the TDesktop instance.
567 * @return the desktop, or null if it is not set
569 public final TDesktop
getDesktop() {
574 * Get the current active window.
576 * @return the active window, or null if it is not set
578 public final TWindow
getActiveWindow() {
583 * Get a (shallow) copy of the window list.
585 * @return a copy of the list of windows for this application
587 public final List
<TWindow
> getAllWindows() {
588 List
<TWindow
> result
= new LinkedList
<TWindow
>();
589 result
.addAll(windows
);
594 * If true, focus follows mouse: windows automatically raised if the
595 * mouse passes over them.
597 private boolean focusFollowsMouse
= false;
600 * Get focusFollowsMouse flag.
602 * @return true if focus follows mouse: windows automatically raised if
603 * the mouse passes over them
605 public boolean getFocusFollowsMouse() {
606 return focusFollowsMouse
;
610 * Set focusFollowsMouse flag.
612 * @param focusFollowsMouse if true, focus follows mouse: windows
613 * automatically raised if the mouse passes over them
615 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
616 this.focusFollowsMouse
= focusFollowsMouse
;
619 // ------------------------------------------------------------------------
620 // General behavior -------------------------------------------------------
621 // ------------------------------------------------------------------------
624 * Display the about dialog.
626 protected void showAboutDialog() {
627 messageBox("About", "Jexer Version " +
628 this.getClass().getPackage().getImplementationVersion(),
629 TMessageBox
.Type
.OK
);
632 // ------------------------------------------------------------------------
633 // Constructors -----------------------------------------------------------
634 // ------------------------------------------------------------------------
637 * Public constructor.
639 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
641 * @throws UnsupportedEncodingException if an exception is thrown when
642 * creating the InputStreamReader
644 public TApplication(final BackendType backendType
)
645 throws UnsupportedEncodingException
{
647 switch (backendType
) {
649 // The default SwingBackend is 80x25, 20 pt font. If you want to
650 // change that, you can pass the extra arguments to the
651 // SwingBackend constructor here. For example, if you wanted
652 // 90x30, 16 pt font:
654 // backend = new SwingBackend(this, 90, 30, 16);
655 backend
= new SwingBackend(this);
660 backend
= new ECMA48Backend(this, null, null);
663 throw new IllegalArgumentException("Invalid backend type: "
670 * Public constructor. The backend type will be BackendType.ECMA48.
672 * @param input an InputStream connected to the remote user, or null for
673 * System.in. If System.in is used, then on non-Windows systems it will
674 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
675 * mode. input is always converted to a Reader with UTF-8 encoding.
676 * @param output an OutputStream connected to the remote user, or null
677 * for System.out. output is always converted to a Writer with UTF-8
679 * @throws UnsupportedEncodingException if an exception is thrown when
680 * creating the InputStreamReader
682 public TApplication(final InputStream input
,
683 final OutputStream output
) throws UnsupportedEncodingException
{
685 backend
= new ECMA48Backend(this, input
, output
);
690 * Public constructor. The backend type will be BackendType.ECMA48.
692 * @param input the InputStream underlying 'reader'. Its available()
693 * method is used to determine if reader.read() will block or not.
694 * @param reader a Reader connected to the remote user.
695 * @param writer a PrintWriter connected to the remote user.
696 * @param setRawMode if true, set System.in into raw mode with stty.
697 * This should in general not be used. It is here solely for Demo3,
698 * which uses System.in.
699 * @throws IllegalArgumentException if input, reader, or writer are null.
701 public TApplication(final InputStream input
, final Reader reader
,
702 final PrintWriter writer
, final boolean setRawMode
) {
704 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
709 * Public constructor. The backend type will be BackendType.ECMA48.
711 * @param input the InputStream underlying 'reader'. Its available()
712 * method is used to determine if reader.read() will block or not.
713 * @param reader a Reader connected to the remote user.
714 * @param writer a PrintWriter connected to the remote user.
715 * @throws IllegalArgumentException if input, reader, or writer are null.
717 public TApplication(final InputStream input
, final Reader reader
,
718 final PrintWriter writer
) {
720 this(input
, reader
, writer
, false);
724 * Public constructor. This hook enables use with new non-Jexer
727 * @param backend a Backend that is already ready to go.
729 public TApplication(final Backend backend
) {
730 this.backend
= backend
;
731 backend
.setListener(this);
736 * Finish construction once the backend is set.
738 private void TApplicationImpl() {
739 theme
= new ColorTheme();
740 desktopBottom
= getScreen().getHeight() - 1;
741 fillEventQueue
= new ArrayList
<TInputEvent
>();
742 drainEventQueue
= new ArrayList
<TInputEvent
>();
743 windows
= new LinkedList
<TWindow
>();
744 menus
= new LinkedList
<TMenu
>();
745 subMenus
= new LinkedList
<TMenu
>();
746 timers
= new LinkedList
<TTimer
>();
747 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
748 menuItems
= new ArrayList
<TMenuItem
>();
749 desktop
= new TDesktop(this);
751 // Setup the main consumer thread
752 primaryEventHandler
= new WidgetEventHandler(this, true);
753 (new Thread(primaryEventHandler
)).start();
756 // ------------------------------------------------------------------------
757 // Screen refresh loop ----------------------------------------------------
758 // ------------------------------------------------------------------------
761 * Invert the cell color at a position. This is used to track the mouse.
763 * @param x column position
764 * @param y row position
766 private void invertCell(final int x
, final int y
) {
768 System
.err
.printf("invertCell() %d %d\n", x
, y
);
770 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
771 attr
.setForeColor(attr
.getForeColor().invert());
772 attr
.setBackColor(attr
.getBackColor().invert());
773 getScreen().putAttrXY(x
, y
, attr
, false);
779 private void drawAll() {
781 System
.err
.printf("drawAll() enter\n");
786 System
.err
.printf("drawAll() !repaint\n");
788 synchronized (getScreen()) {
789 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
790 // The only thing that has happened is the mouse moved.
791 // Clear the old position and draw the new position.
792 invertCell(oldMouseX
, oldMouseY
);
793 invertCell(mouseX
, mouseY
);
797 if (getScreen().isDirty()) {
798 backend
.flushScreen();
805 System
.err
.printf("drawAll() REDRAW\n");
808 // If true, the cursor is not visible
809 boolean cursor
= false;
811 // Start with a clean screen
815 if (desktop
!= null) {
816 desktop
.drawChildren();
819 // Draw each window in reverse Z order
820 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
821 Collections
.sort(sorted
);
822 TWindow topLevel
= null;
823 if (sorted
.size() > 0) {
824 topLevel
= sorted
.get(0);
826 Collections
.reverse(sorted
);
827 for (TWindow window
: sorted
) {
828 if (window
.isShown()) {
829 window
.drawChildren();
833 // Draw the blank menubar line - reset the screen clipping first so
834 // it won't trim it out.
835 getScreen().resetClipping();
836 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
837 theme
.getColor("tmenu"));
838 // Now draw the menus.
840 for (TMenu menu
: menus
) {
841 CellAttributes menuColor
;
842 CellAttributes menuMnemonicColor
;
843 if (menu
.isActive()) {
844 menuColor
= theme
.getColor("tmenu.highlighted");
845 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
848 menuColor
= theme
.getColor("tmenu");
849 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
851 // Draw the menu title
852 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
854 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
855 // Draw the highlight character
856 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
857 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
859 if (menu
.isActive()) {
861 // Reset the screen clipping so we can draw the next title.
862 getScreen().resetClipping();
864 x
+= menu
.getTitle().length() + 2;
867 for (TMenu menu
: subMenus
) {
868 // Reset the screen clipping so we can draw the next sub-menu.
869 getScreen().resetClipping();
873 // Draw the status bar of the top-level window
874 TStatusBar statusBar
= null;
875 if (topLevel
!= null) {
876 statusBar
= topLevel
.getStatusBar();
878 if (statusBar
!= null) {
879 getScreen().resetClipping();
880 statusBar
.setWidth(getScreen().getWidth());
881 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
884 CellAttributes barColor
= new CellAttributes();
885 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
886 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
890 // Draw the mouse pointer
891 invertCell(mouseX
, mouseY
);
895 // Place the cursor if it is visible
896 TWidget activeWidget
= null;
897 if (sorted
.size() > 0) {
898 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
899 if (activeWidget
.isCursorVisible()) {
900 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
901 activeWidget
.getCursorAbsoluteY());
908 getScreen().hideCursor();
911 // Flush the screen contents
912 if (getScreen().isDirty()) {
913 backend
.flushScreen();
919 // ------------------------------------------------------------------------
920 // Main loop --------------------------------------------------------------
921 // ------------------------------------------------------------------------
924 * Force this application to exit.
931 * Run this application until it exits.
935 // Timeout is in milliseconds, so default timeout after 1 second
939 // If I've got no updates to render, wait for something from the
940 // backend or a timer.
942 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
944 // Never sleep longer than 50 millis. We need time for
945 // windows with background tasks to update the display, and
946 // still flip buffers reasonably quickly in
947 // backend.flushPhysical().
948 timeout
= getSleepTime(50);
952 // As of now, I've got nothing to do: no I/O, nothing from
953 // the consumer threads, no timers that need to run ASAP. So
954 // wait until either the backend or the consumer threads have
958 System
.err
.println("sleep " + timeout
+ " millis");
960 synchronized (this) {
963 } catch (InterruptedException e
) {
964 // I'm awake and don't care why, let's see what's going
970 // Prevent stepping on the primary or secondary event handler.
973 // Pull any pending I/O events
974 backend
.getEvents(fillEventQueue
);
976 // Dispatch each event to the appropriate handler, one at a time.
978 TInputEvent event
= null;
979 if (fillEventQueue
.size() == 0) {
982 event
= fillEventQueue
.remove(0);
983 metaHandleEvent(event
);
986 // Wake a consumer thread if we have any pending events.
987 if (drainEventQueue
.size() > 0) {
991 // Process timers and call doIdle()'s
995 synchronized (getScreen()) {
999 // Let the event handlers run again.
1000 startEventHandlers();
1004 // Shutdown the event consumer threads
1005 if (secondaryEventHandler
!= null) {
1006 synchronized (secondaryEventHandler
) {
1007 secondaryEventHandler
.notify();
1010 if (primaryEventHandler
!= null) {
1011 synchronized (primaryEventHandler
) {
1012 primaryEventHandler
.notify();
1016 // Shutdown the user I/O thread(s)
1019 // Close all the windows. This gives them an opportunity to release
1026 * Peek at certain application-level events, add to eventQueue, and wake
1027 * up the consuming Thread.
1029 * @param event the input event to consume
1031 private void metaHandleEvent(final TInputEvent event
) {
1034 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1035 event
)); System
.err
.flush();
1039 // Do no more processing if the application is already trying
1044 // Special application-wide events -------------------------------
1047 if (event
instanceof TCommandEvent
) {
1048 TCommandEvent command
= (TCommandEvent
) event
;
1049 if (command
.getCmd().equals(cmAbort
)) {
1056 if (event
instanceof TResizeEvent
) {
1057 TResizeEvent resize
= (TResizeEvent
) event
;
1058 synchronized (getScreen()) {
1059 getScreen().setDimensions(resize
.getWidth(),
1060 resize
.getHeight());
1061 desktopBottom
= getScreen().getHeight() - 1;
1067 if (desktop
!= null) {
1068 desktop
.setDimensions(0, 0, resize
.getWidth(),
1069 resize
.getHeight() - 1);
1074 // Put into the main queue
1075 drainEventQueue
.add(event
);
1079 * Dispatch one event to the appropriate widget or application-level
1080 * event handler. This is the primary event handler, it has the normal
1081 * application-wide event handling.
1083 * @param event the input event to consume
1084 * @see #secondaryHandleEvent(TInputEvent event)
1086 private void primaryHandleEvent(final TInputEvent event
) {
1089 System
.err
.printf("Handle event: %s\n", event
);
1092 // Special application-wide events -----------------------------------
1094 // Peek at the mouse position
1095 if (event
instanceof TMouseEvent
) {
1096 TMouseEvent mouse
= (TMouseEvent
) event
;
1097 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1100 mouseX
= mouse
.getX();
1101 mouseY
= mouse
.getY();
1104 // See if we need to switch focus to another window or the menu
1105 checkSwitchFocus((TMouseEvent
) event
);
1108 // Handle menu events
1109 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1110 TMenu menu
= activeMenu
;
1112 if (event
instanceof TMouseEvent
) {
1113 TMouseEvent mouse
= (TMouseEvent
) event
;
1115 while (subMenus
.size() > 0) {
1116 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1117 if (subMenu
.mouseWouldHit(mouse
)) {
1120 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1121 && (!mouse
.isMouse1())
1122 && (!mouse
.isMouse2())
1123 && (!mouse
.isMouse3())
1124 && (!mouse
.isMouseWheelUp())
1125 && (!mouse
.isMouseWheelDown())
1129 // We navigated away from a sub-menu, so close it
1133 // Convert the mouse relative x/y to menu coordinates
1134 assert (mouse
.getX() == mouse
.getAbsoluteX());
1135 assert (mouse
.getY() == mouse
.getAbsoluteY());
1136 if (subMenus
.size() > 0) {
1137 menu
= subMenus
.get(subMenus
.size() - 1);
1139 mouse
.setX(mouse
.getX() - menu
.getX());
1140 mouse
.setY(mouse
.getY() - menu
.getY());
1142 menu
.handleEvent(event
);
1146 if (event
instanceof TKeypressEvent
) {
1147 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1149 // See if this key matches an accelerator, and is not being
1150 // shortcutted by the active window, and if so dispatch the menu
1152 boolean windowWillShortcut
= false;
1153 if (activeWindow
!= null) {
1154 assert (activeWindow
.isShown());
1155 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1156 // We do not process this key, it will be passed to the
1158 windowWillShortcut
= true;
1162 if (!windowWillShortcut
&& !modalWindowActive()) {
1163 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1164 TMenuItem item
= null;
1165 synchronized (accelerators
) {
1166 item
= accelerators
.get(keypressLowercase
);
1169 if (item
.isEnabled()) {
1170 // Let the menu item dispatch
1176 // Handle the keypress
1177 if (onKeypress(keypress
)) {
1183 if (event
instanceof TCommandEvent
) {
1184 if (onCommand((TCommandEvent
) event
)) {
1189 if (event
instanceof TMenuEvent
) {
1190 if (onMenu((TMenuEvent
) event
)) {
1195 // Dispatch events to the active window -------------------------------
1196 boolean dispatchToDesktop
= true;
1197 TWindow window
= activeWindow
;
1198 if (window
!= null) {
1199 assert (window
.isActive());
1200 assert (window
.isShown());
1201 if (event
instanceof TMouseEvent
) {
1202 TMouseEvent mouse
= (TMouseEvent
) event
;
1203 // Convert the mouse relative x/y to window coordinates
1204 assert (mouse
.getX() == mouse
.getAbsoluteX());
1205 assert (mouse
.getY() == mouse
.getAbsoluteY());
1206 mouse
.setX(mouse
.getX() - window
.getX());
1207 mouse
.setY(mouse
.getY() - window
.getY());
1209 if (window
.mouseWouldHit(mouse
)) {
1210 dispatchToDesktop
= false;
1212 } else if (event
instanceof TKeypressEvent
) {
1213 dispatchToDesktop
= false;
1217 System
.err
.printf("TApplication dispatch event: %s\n",
1220 window
.handleEvent(event
);
1222 if (dispatchToDesktop
) {
1223 // This event is fair game for the desktop to process.
1224 if (desktop
!= null) {
1225 desktop
.handleEvent(event
);
1231 * Dispatch one event to the appropriate widget or application-level
1232 * event handler. This is the secondary event handler used by certain
1233 * special dialogs (currently TMessageBox and TFileOpenBox).
1235 * @param event the input event to consume
1236 * @see #primaryHandleEvent(TInputEvent event)
1238 private void secondaryHandleEvent(final TInputEvent event
) {
1239 // Peek at the mouse position
1240 if (event
instanceof TMouseEvent
) {
1241 TMouseEvent mouse
= (TMouseEvent
) event
;
1242 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1245 mouseX
= mouse
.getX();
1246 mouseY
= mouse
.getY();
1250 secondaryEventReceiver
.handleEvent(event
);
1254 * Enable a widget to override the primary event thread.
1256 * @param widget widget that will receive events
1258 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1259 assert (secondaryEventReceiver
== null);
1260 assert (secondaryEventHandler
== null);
1261 assert ((widget
instanceof TMessageBox
)
1262 || (widget
instanceof TFileOpenBox
));
1263 secondaryEventReceiver
= widget
;
1264 secondaryEventHandler
= new WidgetEventHandler(this, false);
1265 (new Thread(secondaryEventHandler
)).start();
1269 * Yield to the secondary thread.
1271 public final void yield() {
1272 assert (secondaryEventReceiver
!= null);
1273 // This is where we handoff the event handler lock from the primary
1274 // to secondary thread. We unlock here, and in a future loop the
1275 // secondary thread locks again. When it gives up, we have the
1276 // single lock back.
1277 boolean oldLock
= unlockHandleEvent();
1280 while (secondaryEventReceiver
!= null) {
1281 synchronized (primaryEventHandler
) {
1283 primaryEventHandler
.wait();
1284 } catch (InterruptedException e
) {
1292 * Do stuff when there is no user input.
1294 private void doIdle() {
1296 System
.err
.printf("doIdle()\n");
1299 // Now run any timers that have timed out
1300 Date now
= new Date();
1301 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1302 for (TTimer timer
: timers
) {
1303 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1305 if (timer
.recurring
) {
1306 keepTimers
.add(timer
);
1309 keepTimers
.add(timer
);
1312 timers
= keepTimers
;
1315 for (TWindow window
: windows
) {
1318 if (desktop
!= null) {
1323 // ------------------------------------------------------------------------
1324 // TWindow management -----------------------------------------------------
1325 // ------------------------------------------------------------------------
1328 * Return the total number of windows.
1330 * @return the total number of windows
1332 public final int windowCount() {
1333 return windows
.size();
1337 * Return the number of windows that are showing.
1339 * @return the number of windows that are showing on screen
1341 public final int shownWindowCount() {
1343 for (TWindow w
: windows
) {
1352 * Return the number of windows that are hidden.
1354 * @return the number of windows that are hidden
1356 public final int hiddenWindowCount() {
1358 for (TWindow w
: windows
) {
1367 * Check if a window instance is in this application's window list.
1369 * @param window window to look for
1370 * @return true if this window is in the list
1372 public final boolean hasWindow(final TWindow window
) {
1373 if (windows
.size() == 0) {
1376 for (TWindow w
: windows
) {
1378 assert (window
.getApplication() == this);
1386 * Activate a window: bring it to the top and have it receive events.
1388 * @param window the window to become the new active window
1390 public void activateWindow(final TWindow window
) {
1391 if (hasWindow(window
) == false) {
1393 * Someone has a handle to a window I don't have. Ignore this
1399 assert (windows
.size() > 0);
1401 if (window
.isHidden()) {
1402 // Unhiding will also activate.
1406 assert (window
.isShown());
1408 if (windows
.size() == 1) {
1409 assert (window
== windows
.get(0));
1410 if (activeWindow
== null) {
1411 activeWindow
= window
;
1413 activeWindow
.setActive(true);
1414 activeWindow
.onFocus();
1417 assert (window
.isActive());
1418 assert (activeWindow
== window
);
1422 if (activeWindow
== window
) {
1423 assert (window
.isActive());
1425 // Window is already active, do nothing.
1429 assert (!window
.isActive());
1430 if (activeWindow
!= null) {
1431 assert (activeWindow
.getZ() == 0);
1433 activeWindow
.onUnfocus();
1434 activeWindow
.setActive(false);
1435 activeWindow
.setZ(window
.getZ());
1437 activeWindow
= window
;
1438 activeWindow
.setZ(0);
1439 activeWindow
.setActive(true);
1440 activeWindow
.onFocus();
1447 * @param window the window to hide
1449 public void hideWindow(final TWindow window
) {
1450 if (hasWindow(window
) == false) {
1452 * Someone has a handle to a window I don't have. Ignore this
1458 assert (windows
.size() > 0);
1460 if (!window
.hidden
) {
1461 if (window
== activeWindow
) {
1462 if (shownWindowCount() > 1) {
1465 activeWindow
= null;
1466 window
.setActive(false);
1470 window
.hidden
= true;
1478 * @param window the window to show
1480 public void showWindow(final TWindow window
) {
1481 if (hasWindow(window
) == false) {
1483 * Someone has a handle to a window I don't have. Ignore this
1489 assert (windows
.size() > 0);
1491 if (window
.hidden
) {
1492 window
.hidden
= false;
1494 activateWindow(window
);
1499 * Close window. Note that the window's destructor is NOT called by this
1500 * method, instead the GC is assumed to do the cleanup.
1502 * @param window the window to remove
1504 public final void closeWindow(final TWindow window
) {
1505 if (hasWindow(window
) == false) {
1507 * Someone has a handle to a window I don't have. Ignore this
1513 synchronized (windows
) {
1514 int z
= window
.getZ();
1517 Collections
.sort(windows
);
1519 activeWindow
= null;
1520 for (TWindow w
: windows
) {
1522 w
.setZ(w
.getZ() - 1);
1523 if (w
.getZ() == 0) {
1526 assert (activeWindow
== null);
1538 // Perform window cleanup
1541 // Check if we are closing a TMessageBox or similar
1542 if (secondaryEventReceiver
!= null) {
1543 assert (secondaryEventHandler
!= null);
1545 // Do not send events to the secondaryEventReceiver anymore, the
1546 // window is closed.
1547 secondaryEventReceiver
= null;
1549 // Wake the secondary thread, it will wake the primary as it
1551 synchronized (secondaryEventHandler
) {
1552 secondaryEventHandler
.notify();
1556 // Permit desktop to be active if it is the only thing left.
1557 if (desktop
!= null) {
1558 if (windows
.size() == 0) {
1559 desktop
.setActive(true);
1565 * Switch to the next window.
1567 * @param forward if true, then switch to the next window in the list,
1568 * otherwise switch to the previous window in the list
1570 public final void switchWindow(final boolean forward
) {
1571 // Only switch if there are multiple visible windows
1572 if (shownWindowCount() < 2) {
1575 assert (activeWindow
!= null);
1577 synchronized (windows
) {
1579 // Swap z/active between active window and the next in the list
1580 int activeWindowI
= -1;
1581 for (int i
= 0; i
< windows
.size(); i
++) {
1582 if (windows
.get(i
) == activeWindow
) {
1583 assert (activeWindow
.isActive());
1587 assert (!windows
.get(0).isActive());
1590 assert (activeWindowI
>= 0);
1592 // Do not switch if a window is modal
1593 if (activeWindow
.isModal()) {
1597 int nextWindowI
= activeWindowI
;
1601 nextWindowI
%= windows
.size();
1604 if (nextWindowI
< 0) {
1605 nextWindowI
= windows
.size() - 1;
1609 if (windows
.get(nextWindowI
).isShown()) {
1610 activateWindow(windows
.get(nextWindowI
));
1614 } // synchronized (windows)
1619 * Add a window to my window list and make it active.
1621 * @param window new window to add
1623 public final void addWindow(final TWindow window
) {
1625 // Do not add menu windows to the window list.
1626 if (window
instanceof TMenu
) {
1630 // Do not add the desktop to the window list.
1631 if (window
instanceof TDesktop
) {
1635 synchronized (windows
) {
1636 // Do not allow a modal window to spawn a non-modal window. If a
1637 // modal window is active, then this window will become modal
1639 if (modalWindowActive()) {
1640 window
.flags
|= TWindow
.MODAL
;
1641 window
.flags
|= TWindow
.CENTERED
;
1642 window
.hidden
= false;
1644 if (window
.isShown()) {
1645 for (TWindow w
: windows
) {
1650 w
.setZ(w
.getZ() + 1);
1653 windows
.add(window
);
1654 if (window
.isShown()) {
1655 activeWindow
= window
;
1656 activeWindow
.setZ(0);
1657 activeWindow
.setActive(true);
1658 activeWindow
.onFocus();
1661 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1662 && smartWindowPlacement
) {
1664 doSmartPlacement(window
);
1668 // Desktop cannot be active over any other window.
1669 if (desktop
!= null) {
1670 desktop
.setActive(false);
1675 * Check if there is a system-modal window on top.
1677 * @return true if the active window is modal
1679 private boolean modalWindowActive() {
1680 if (windows
.size() == 0) {
1684 for (TWindow w
: windows
) {
1694 * Close all open windows.
1696 private void closeAllWindows() {
1697 // Don't do anything if we are in the menu
1698 if (activeMenu
!= null) {
1701 while (windows
.size() > 0) {
1702 closeWindow(windows
.get(0));
1707 * Re-layout the open windows as non-overlapping tiles. This produces
1708 * almost the same results as Turbo Pascal 7.0's IDE.
1710 private void tileWindows() {
1711 synchronized (windows
) {
1712 // Don't do anything if we are in the menu
1713 if (activeMenu
!= null) {
1716 int z
= windows
.size();
1722 a
= (int)(Math
.sqrt(z
));
1726 if (((a
* b
) + c
) == z
) {
1734 int newWidth
= (getScreen().getWidth() / a
);
1735 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1736 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1738 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1739 Collections
.sort(sorted
);
1740 Collections
.reverse(sorted
);
1741 for (int i
= 0; i
< sorted
.size(); i
++) {
1742 int logicalX
= i
/ b
;
1743 int logicalY
= i
% b
;
1744 if (i
>= ((a
- 1) * b
)) {
1746 logicalY
= i
- ((a
- 1) * b
);
1749 TWindow w
= sorted
.get(i
);
1750 w
.setX(logicalX
* newWidth
);
1751 w
.setWidth(newWidth
);
1752 if (i
>= ((a
- 1) * b
)) {
1753 w
.setY((logicalY
* newHeight2
) + 1);
1754 w
.setHeight(newHeight2
);
1756 w
.setY((logicalY
* newHeight1
) + 1);
1757 w
.setHeight(newHeight1
);
1764 * Re-layout the open windows as overlapping cascaded windows.
1766 private void cascadeWindows() {
1767 synchronized (windows
) {
1768 // Don't do anything if we are in the menu
1769 if (activeMenu
!= null) {
1774 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1775 Collections
.sort(sorted
);
1776 Collections
.reverse(sorted
);
1777 for (TWindow window
: sorted
) {
1782 if (x
> getScreen().getWidth()) {
1785 if (y
>= getScreen().getHeight()) {
1793 * Place a window to minimize its overlap with other windows.
1795 * @param window the window to place
1797 public final void doSmartPlacement(final TWindow window
) {
1798 // This is a pretty dumb algorithm, but seems to work. The hardest
1799 // part is computing these "overlap" values seeking a minimum average
1802 int yMin
= desktopTop
;
1803 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1804 int yMax
= desktopBottom
- window
.getHeight() + 1;
1812 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1813 // No work to do, bail out.
1817 // Compute the overlap matrix without the new window.
1818 int width
= getScreen().getWidth();
1819 int height
= getScreen().getHeight();
1820 int overlapMatrix
[][] = new int[width
][height
];
1821 for (TWindow w
: windows
) {
1825 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1829 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1833 overlapMatrix
[x
][y
]++;
1838 long oldOverlapTotal
= 0;
1839 long oldOverlapN
= 0;
1840 for (int x
= 0; x
< width
; x
++) {
1841 for (int y
= 0; y
< height
; y
++) {
1842 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1843 if (overlapMatrix
[x
][y
] > 0) {
1850 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1851 boolean first
= true;
1852 int windowX
= window
.getX();
1853 int windowY
= window
.getY();
1855 // For each possible (x, y) position for the new window, compute a
1856 // new overlap matrix.
1857 for (int x
= xMin
; x
< xMax
; x
++) {
1858 for (int y
= yMin
; y
< yMax
; y
++) {
1860 // Start with the matrix minus this window.
1861 int newMatrix
[][] = new int[width
][height
];
1862 for (int mx
= 0; mx
< width
; mx
++) {
1863 for (int my
= 0; my
< height
; my
++) {
1864 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1868 // Add this window's values to the new overlap matrix.
1869 long newOverlapTotal
= 0;
1870 long newOverlapN
= 0;
1871 // Start by adding each new cell.
1872 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1876 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1880 newMatrix
[wx
][wy
]++;
1883 // Now figure out the new value for total coverage.
1884 for (int mx
= 0; mx
< width
; mx
++) {
1885 for (int my
= 0; my
< height
; my
++) {
1886 newOverlapTotal
+= newMatrix
[x
][y
];
1887 if (newMatrix
[mx
][my
] > 0) {
1892 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1895 // First time: just record what we got.
1896 oldOverlapAvg
= newOverlapAvg
;
1899 // All other times: pick a new best (x, y) and save the
1901 if (newOverlapAvg
< oldOverlapAvg
) {
1904 oldOverlapAvg
= newOverlapAvg
;
1908 } // for (int x = xMin; x < xMax; x++)
1910 } // for (int y = yMin; y < yMax; y++)
1912 // Finally, set the window's new coordinates.
1913 window
.setX(windowX
);
1914 window
.setY(windowY
);
1917 // ------------------------------------------------------------------------
1918 // TMenu management -------------------------------------------------------
1919 // ------------------------------------------------------------------------
1922 * Check if a mouse event would hit either the active menu or any open
1925 * @param mouse mouse event
1926 * @return true if the mouse would hit the active menu or an open
1929 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1930 assert (activeMenu
!= null);
1931 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1932 Collections
.reverse(menus
);
1933 for (TMenu menu
: menus
) {
1934 if (menu
.mouseWouldHit(mouse
)) {
1938 return activeMenu
.mouseWouldHit(mouse
);
1942 * See if we need to switch window or activate the menu based on
1945 * @param mouse mouse event
1947 private void checkSwitchFocus(final TMouseEvent mouse
) {
1949 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1950 && (activeMenu
!= null)
1951 && (mouse
.getAbsoluteY() != 0)
1952 && (!mouseOnMenu(mouse
))
1954 // They clicked outside the active menu, turn it off
1955 activeMenu
.setActive(false);
1957 for (TMenu menu
: subMenus
) {
1958 menu
.setActive(false);
1964 // See if they hit the menu bar
1965 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1966 && (mouse
.isMouse1())
1967 && (!modalWindowActive())
1968 && (mouse
.getAbsoluteY() == 0)
1971 for (TMenu menu
: subMenus
) {
1972 menu
.setActive(false);
1976 // They selected the menu, go activate it
1977 for (TMenu menu
: menus
) {
1978 if ((mouse
.getAbsoluteX() >= menu
.getX())
1979 && (mouse
.getAbsoluteX() < menu
.getX()
1980 + menu
.getTitle().length() + 2)
1982 menu
.setActive(true);
1985 menu
.setActive(false);
1991 // See if they hit the menu bar
1992 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1993 && (mouse
.isMouse1())
1994 && (activeMenu
!= null)
1995 && (mouse
.getAbsoluteY() == 0)
1998 TMenu oldMenu
= activeMenu
;
1999 for (TMenu menu
: subMenus
) {
2000 menu
.setActive(false);
2004 // See if we should switch menus
2005 for (TMenu menu
: menus
) {
2006 if ((mouse
.getAbsoluteX() >= menu
.getX())
2007 && (mouse
.getAbsoluteX() < menu
.getX()
2008 + menu
.getTitle().length() + 2)
2010 menu
.setActive(true);
2014 if (oldMenu
!= activeMenu
) {
2015 // They switched menus
2016 oldMenu
.setActive(false);
2021 // If a menu is still active, don't switch windows
2022 if (activeMenu
!= null) {
2026 // Only switch if there are multiple windows
2027 if (windows
.size() < 2) {
2031 if (((focusFollowsMouse
== true)
2032 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2033 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2035 synchronized (windows
) {
2036 Collections
.sort(windows
);
2037 if (windows
.get(0).isModal()) {
2038 // Modal windows don't switch
2042 for (TWindow window
: windows
) {
2043 assert (!window
.isModal());
2045 if (window
.isHidden()) {
2046 assert (!window
.isActive());
2050 if (window
.mouseWouldHit(mouse
)) {
2051 if (window
== windows
.get(0)) {
2052 // Clicked on the same window, nothing to do
2053 assert (window
.isActive());
2057 // We will be switching to another window
2058 assert (windows
.get(0).isActive());
2059 assert (windows
.get(0) == activeWindow
);
2060 assert (!window
.isActive());
2061 activeWindow
.onUnfocus();
2062 activeWindow
.setActive(false);
2063 activeWindow
.setZ(window
.getZ());
2064 activeWindow
= window
;
2066 window
.setActive(true);
2073 // Clicked on the background, nothing to do
2077 // Nothing to do: this isn't a mouse up, or focus isn't following
2083 * Turn off the menu.
2085 public final void closeMenu() {
2086 if (activeMenu
!= null) {
2087 activeMenu
.setActive(false);
2089 for (TMenu menu
: subMenus
) {
2090 menu
.setActive(false);
2097 * Get a (shallow) copy of the menu list.
2099 * @return a copy of the menu list
2101 public final List
<TMenu
> getAllMenus() {
2102 return new LinkedList
<TMenu
>(menus
);
2106 * Add a top-level menu to the list.
2108 * @param menu the menu to add
2109 * @throws IllegalArgumentException if the menu is already used in
2110 * another TApplication
2112 public final void addMenu(final TMenu menu
) {
2113 if ((menu
.getApplication() != null)
2114 && (menu
.getApplication() != this)
2116 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2117 "part of application " + menu
.getApplication());
2125 * Remove a top-level menu from the list.
2127 * @param menu the menu to remove
2128 * @throws IllegalArgumentException if the menu is already used in
2129 * another TApplication
2131 public final void removeMenu(final TMenu menu
) {
2132 if ((menu
.getApplication() != null)
2133 && (menu
.getApplication() != this)
2135 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2136 "part of application " + menu
.getApplication());
2144 * Turn off a sub-menu.
2146 public final void closeSubMenu() {
2147 assert (activeMenu
!= null);
2148 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2149 assert (item
!= null);
2150 item
.setActive(false);
2151 subMenus
.remove(subMenus
.size() - 1);
2155 * Switch to the next menu.
2157 * @param forward if true, then switch to the next menu in the list,
2158 * otherwise switch to the previous menu in the list
2160 public final void switchMenu(final boolean forward
) {
2161 assert (activeMenu
!= null);
2163 for (TMenu menu
: subMenus
) {
2164 menu
.setActive(false);
2168 for (int i
= 0; i
< menus
.size(); i
++) {
2169 if (activeMenu
== menus
.get(i
)) {
2171 if (i
< menus
.size() - 1) {
2179 activeMenu
.setActive(false);
2180 activeMenu
= menus
.get(i
);
2181 activeMenu
.setActive(true);
2188 * Add a menu item to the global list. If it has a keyboard accelerator,
2189 * that will be added the global hash.
2191 * @param item the menu item
2193 public final void addMenuItem(final TMenuItem item
) {
2194 menuItems
.add(item
);
2196 TKeypress key
= item
.getKey();
2198 synchronized (accelerators
) {
2199 assert (accelerators
.get(key
) == null);
2200 accelerators
.put(key
.toLowerCase(), item
);
2206 * Disable one menu item.
2208 * @param id the menu item ID
2210 public final void disableMenuItem(final int id
) {
2211 for (TMenuItem item
: menuItems
) {
2212 if (item
.getId() == id
) {
2213 item
.setEnabled(false);
2219 * Disable the range of menu items with ID's between lower and upper,
2222 * @param lower the lowest menu item ID
2223 * @param upper the highest menu item ID
2225 public final void disableMenuItems(final int lower
, final int upper
) {
2226 for (TMenuItem item
: menuItems
) {
2227 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2228 item
.setEnabled(false);
2234 * Enable one menu item.
2236 * @param id the menu item ID
2238 public final void enableMenuItem(final int id
) {
2239 for (TMenuItem item
: menuItems
) {
2240 if (item
.getId() == id
) {
2241 item
.setEnabled(true);
2247 * Enable the range of menu items with ID's between lower and upper,
2250 * @param lower the lowest menu item ID
2251 * @param upper the highest menu item ID
2253 public final void enableMenuItems(final int lower
, final int upper
) {
2254 for (TMenuItem item
: menuItems
) {
2255 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2256 item
.setEnabled(true);
2262 * Recompute menu x positions based on their title length.
2264 public final void recomputeMenuX() {
2266 for (TMenu menu
: menus
) {
2268 x
+= menu
.getTitle().length() + 2;
2273 * Post an event to process and turn off the menu.
2275 * @param event new event to add to the queue
2277 public final void postMenuEvent(final TInputEvent event
) {
2278 synchronized (fillEventQueue
) {
2279 fillEventQueue
.add(event
);
2285 * Add a sub-menu to the list of open sub-menus.
2287 * @param menu sub-menu
2289 public final void addSubMenu(final TMenu menu
) {
2294 * Convenience function to add a top-level menu.
2296 * @param title menu title
2297 * @return the new menu
2299 public final TMenu
addMenu(final String title
) {
2302 TMenu menu
= new TMenu(this, x
, y
, title
);
2309 * Convenience function to add a default "File" menu.
2311 * @return the new menu
2313 public final TMenu
addFileMenu() {
2314 TMenu fileMenu
= addMenu("&File");
2315 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2316 fileMenu
.addSeparator();
2317 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2318 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2319 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2320 "commands (Open, Save, Print, etc.)");
2321 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2326 * Convenience function to add a default "Edit" menu.
2328 * @return the new menu
2330 public final TMenu
addEditMenu() {
2331 TMenu editMenu
= addMenu("&Edit");
2332 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2333 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2334 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2335 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2336 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2337 "undo, and Clipboard access");
2338 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2343 * Convenience function to add a default "Window" menu.
2345 * @return the new menu
2347 public final TMenu
addWindowMenu() {
2348 TMenu windowMenu
= addMenu("&Window");
2349 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2350 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2351 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2352 windowMenu
.addSeparator();
2353 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2354 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2355 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2356 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2357 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2358 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2360 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2365 * Convenience function to add a default "Help" menu.
2367 * @return the new menu
2369 public final TMenu
addHelpMenu() {
2370 TMenu helpMenu
= addMenu("&Help");
2371 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2372 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2373 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2374 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2375 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2376 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2377 helpMenu
.addSeparator();
2378 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2379 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2380 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2384 // ------------------------------------------------------------------------
2385 // Event handlers ---------------------------------------------------------
2386 // ------------------------------------------------------------------------
2389 * Method that TApplication subclasses can override to handle menu or
2390 * posted command events.
2392 * @param command command event
2393 * @return if true, this event was consumed
2395 protected boolean onCommand(final TCommandEvent command
) {
2396 // Default: handle cmExit
2397 if (command
.equals(cmExit
)) {
2398 if (messageBox("Confirmation", "Exit application?",
2399 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2405 if (command
.equals(cmShell
)) {
2406 openTerminal(0, 0, TWindow
.RESIZABLE
);
2410 if (command
.equals(cmTile
)) {
2414 if (command
.equals(cmCascade
)) {
2418 if (command
.equals(cmCloseAll
)) {
2423 if (command
.equals(cmMenu
)) {
2424 if (!modalWindowActive() && (activeMenu
== null)) {
2425 if (menus
.size() > 0) {
2426 menus
.get(0).setActive(true);
2427 activeMenu
= menus
.get(0);
2437 * Method that TApplication subclasses can override to handle menu
2440 * @param menu menu event
2441 * @return if true, this event was consumed
2443 protected boolean onMenu(final TMenuEvent menu
) {
2445 // Default: handle MID_EXIT
2446 if (menu
.getId() == TMenu
.MID_EXIT
) {
2447 if (messageBox("Confirmation", "Exit application?",
2448 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2454 if (menu
.getId() == TMenu
.MID_SHELL
) {
2455 openTerminal(0, 0, TWindow
.RESIZABLE
);
2459 if (menu
.getId() == TMenu
.MID_TILE
) {
2463 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2467 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2471 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2479 * Method that TApplication subclasses can override to handle keystrokes.
2481 * @param keypress keystroke event
2482 * @return if true, this event was consumed
2484 protected boolean onKeypress(final TKeypressEvent keypress
) {
2485 // Default: only menu shortcuts
2487 // Process Alt-F, Alt-E, etc. menu shortcut keys
2488 if (!keypress
.getKey().isFnKey()
2489 && keypress
.getKey().isAlt()
2490 && !keypress
.getKey().isCtrl()
2491 && (activeMenu
== null)
2492 && !modalWindowActive()
2495 assert (subMenus
.size() == 0);
2497 for (TMenu menu
: menus
) {
2498 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2499 == Character
.toLowerCase(keypress
.getKey().getChar())
2502 menu
.setActive(true);
2511 // ------------------------------------------------------------------------
2512 // TTimer management ------------------------------------------------------
2513 // ------------------------------------------------------------------------
2516 * Get the amount of time I can sleep before missing a Timer tick.
2518 * @param timeout = initial (maximum) timeout in millis
2519 * @return number of milliseconds between now and the next timer event
2521 private long getSleepTime(final long timeout
) {
2522 Date now
= new Date();
2523 long nowTime
= now
.getTime();
2524 long sleepTime
= timeout
;
2525 for (TTimer timer
: timers
) {
2526 long nextTickTime
= timer
.getNextTick().getTime();
2527 if (nextTickTime
< nowTime
) {
2531 long timeDifference
= nextTickTime
- nowTime
;
2532 if (timeDifference
< sleepTime
) {
2533 sleepTime
= timeDifference
;
2536 assert (sleepTime
>= 0);
2537 assert (sleepTime
<= timeout
);
2542 * Convenience function to add a timer.
2544 * @param duration number of milliseconds to wait between ticks
2545 * @param recurring if true, re-schedule this timer after every tick
2546 * @param action function to call when button is pressed
2549 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2550 final TAction action
) {
2552 TTimer timer
= new TTimer(duration
, recurring
, action
);
2553 synchronized (timers
) {
2560 * Convenience function to remove a timer.
2562 * @param timer timer to remove
2564 public final void removeTimer(final TTimer timer
) {
2565 synchronized (timers
) {
2566 timers
.remove(timer
);
2570 // ------------------------------------------------------------------------
2571 // Other TWindow constructors ---------------------------------------------
2572 // ------------------------------------------------------------------------
2575 * Convenience function to spawn a message box.
2577 * @param title window title, will be centered along the top border
2578 * @param caption message to display. Use embedded newlines to get a
2580 * @return the new message box
2582 public final TMessageBox
messageBox(final String title
,
2583 final String caption
) {
2585 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2589 * Convenience function to spawn a message box.
2591 * @param title window title, will be centered along the top border
2592 * @param caption message to display. Use embedded newlines to get a
2594 * @param type one of the TMessageBox.Type constants. Default is
2596 * @return the new message box
2598 public final TMessageBox
messageBox(final String title
,
2599 final String caption
, final TMessageBox
.Type type
) {
2601 return new TMessageBox(this, title
, caption
, type
);
2605 * Convenience function to spawn an input box.
2607 * @param title window title, will be centered along the top border
2608 * @param caption message to display. Use embedded newlines to get a
2610 * @return the new input box
2612 public final TInputBox
inputBox(final String title
, final String caption
) {
2614 return new TInputBox(this, title
, caption
);
2618 * Convenience function to spawn an input box.
2620 * @param title window title, will be centered along the top border
2621 * @param caption message to display. Use embedded newlines to get a
2623 * @param text initial text to seed the field with
2624 * @return the new input box
2626 public final TInputBox
inputBox(final String title
, final String caption
,
2627 final String text
) {
2629 return new TInputBox(this, title
, caption
, text
);
2633 * Convenience function to open a terminal window.
2635 * @param x column relative to parent
2636 * @param y row relative to parent
2637 * @return the terminal new window
2639 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2640 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2644 * Convenience function to open a terminal window.
2646 * @param x column relative to parent
2647 * @param y row relative to parent
2648 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2649 * @return the terminal new window
2651 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2654 return new TTerminalWindow(this, x
, y
, flags
);
2658 * Convenience function to spawn an file open box.
2660 * @param path path of selected file
2661 * @return the result of the new file open box
2662 * @throws IOException if java.io operation throws
2664 public final String
fileOpenBox(final String path
) throws IOException
{
2666 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2667 return box
.getFilename();
2671 * Convenience function to spawn an file open box.
2673 * @param path path of selected file
2674 * @param type one of the Type constants
2675 * @return the result of the new file open box
2676 * @throws IOException if java.io operation throws
2678 public final String
fileOpenBox(final String path
,
2679 final TFileOpenBox
.Type type
) throws IOException
{
2681 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2682 return box
.getFilename();
2686 * Convenience function to create a new window and make it active.
2687 * Window will be located at (0, 0).
2689 * @param title window title, will be centered along the top border
2690 * @param width width of window
2691 * @param height height of window
2693 public final TWindow
addWindow(final String title
, final int width
,
2696 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2700 * Convenience function to create a new window and make it active.
2701 * Window will be located at (0, 0).
2703 * @param title window title, will be centered along the top border
2704 * @param width width of window
2705 * @param height height of window
2706 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2708 public final TWindow
addWindow(final String title
,
2709 final int width
, final int height
, final int flags
) {
2711 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2716 * Convenience function to create a new window and make it active.
2718 * @param title window title, will be centered along the top border
2719 * @param x column relative to parent
2720 * @param y row relative to parent
2721 * @param width width of window
2722 * @param height height of window
2724 public final TWindow
addWindow(final String title
,
2725 final int x
, final int y
, final int width
, final int height
) {
2727 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2732 * Convenience function to create a new window and make it active.
2734 * @param title window title, will be centered along the top border
2735 * @param x column relative to parent
2736 * @param y row relative to parent
2737 * @param width width of window
2738 * @param height height of window
2739 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2741 public final TWindow
addWindow(final String title
,
2742 final int x
, final int y
, final int width
, final int height
,
2745 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);