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
.bits
.GraphicsChars
;
48 import jexer
.event
.TCommandEvent
;
49 import jexer
.event
.TInputEvent
;
50 import jexer
.event
.TKeypressEvent
;
51 import jexer
.event
.TMenuEvent
;
52 import jexer
.event
.TMouseEvent
;
53 import jexer
.event
.TResizeEvent
;
54 import jexer
.backend
.Backend
;
55 import jexer
.backend
.SwingBackend
;
56 import jexer
.backend
.ECMA48Backend
;
57 import jexer
.io
.Screen
;
58 import jexer
.menu
.TMenu
;
59 import jexer
.menu
.TMenuItem
;
60 import static jexer
.TCommand
.*;
61 import static jexer
.TKeypress
.*;
64 * TApplication sets up a full Text User Interface application.
66 public class TApplication
implements Runnable
{
68 // ------------------------------------------------------------------------
69 // Public constants -------------------------------------------------------
70 // ------------------------------------------------------------------------
73 * If true, emit thread stuff to System.err.
75 private static final boolean debugThreads
= false;
78 * If true, emit events being processed to System.err.
80 private static final boolean debugEvents
= false;
83 * If true, do "smart placement" on new windows that are not specified to
86 private static final boolean smartWindowPlacement
= true;
89 * Two backend types are available.
91 public static enum BackendType
{
98 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
103 * Synonym for ECMA48.
108 // ------------------------------------------------------------------------
109 // Primary/secondary event handlers ---------------------------------------
110 // ------------------------------------------------------------------------
113 * WidgetEventHandler is the main event consumer loop. There are at most
114 * two such threads in existence: the primary for normal case and a
115 * secondary that is used for TMessageBox, TInputBox, and similar.
117 private class WidgetEventHandler
implements Runnable
{
119 * The main application.
121 private TApplication application
;
124 * Whether or not this WidgetEventHandler is the primary or secondary
127 private boolean primary
= true;
130 * Public constructor.
132 * @param application the main application
133 * @param primary if true, this is the primary event handler thread
135 public WidgetEventHandler(final TApplication application
,
136 final boolean primary
) {
138 this.application
= application
;
139 this.primary
= primary
;
148 while (!application
.quit
) {
150 // Wait until application notifies me
151 while (!application
.quit
) {
153 synchronized (application
.drainEventQueue
) {
154 if (application
.drainEventQueue
.size() > 0) {
159 synchronized (this) {
161 System
.err
.printf("%s %s sleep\n", this,
162 primary ?
"primary" : "secondary");
168 System
.err
.printf("%s %s AWAKE\n", this,
169 primary ?
"primary" : "secondary");
173 && (application
.secondaryEventReceiver
== null)
175 // Secondary thread, emergency exit. If we
176 // got here then something went wrong with
177 // the handoff between yield() and
179 synchronized (application
.primaryEventHandler
) {
180 application
.primaryEventHandler
.notify();
182 application
.secondaryEventHandler
= null;
183 throw new RuntimeException(
184 "secondary exited at wrong time");
188 } catch (InterruptedException e
) {
193 // Wait for drawAll() or doIdle() to be done, then handle the
195 boolean oldLock
= lockHandleEvent();
196 assert (oldLock
== false);
198 // Pull all events off the queue
200 TInputEvent event
= null;
201 synchronized (application
.drainEventQueue
) {
202 if (application
.drainEventQueue
.size() == 0) {
205 event
= application
.drainEventQueue
.remove(0);
207 application
.repaint
= true;
209 primaryHandleEvent(event
);
211 secondaryHandleEvent(event
);
214 && (application
.secondaryEventReceiver
== null)
216 // Secondary thread, time to exit.
218 // DO NOT UNLOCK. Primary thread just came back from
219 // primaryHandleEvent() and will unlock in the else
220 // block below. Just wake it up.
221 synchronized (application
.primaryEventHandler
) {
222 application
.primaryEventHandler
.notify();
224 // Now eliminate my reference so that
225 // wakeEventHandler() resumes working on the primary.
226 application
.secondaryEventHandler
= null;
233 // Unlock. Either I am primary thread, or I am secondary
234 // thread and still running.
235 oldLock
= unlockHandleEvent();
236 assert (oldLock
== true);
238 // I have done some work of some kind. Tell the main run()
239 // loop to wake up now.
240 synchronized (application
) {
241 application
.notify();
244 } // while (true) (main runnable loop)
249 * The primary event handler thread.
251 private volatile WidgetEventHandler primaryEventHandler
;
254 * The secondary event handler thread.
256 private volatile WidgetEventHandler secondaryEventHandler
;
259 * The widget receiving events from the secondary event handler thread.
261 private volatile TWidget secondaryEventReceiver
;
264 * Spinlock for the primary and secondary event handlers.
265 * WidgetEventHandler.run() is responsible for setting this value.
267 private volatile boolean insideHandleEvent
= false;
270 * Wake the sleeping active event handler.
272 private void wakeEventHandler() {
273 if (secondaryEventHandler
!= null) {
274 synchronized (secondaryEventHandler
) {
275 secondaryEventHandler
.notify();
278 assert (primaryEventHandler
!= null);
279 synchronized (primaryEventHandler
) {
280 primaryEventHandler
.notify();
286 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
287 * spin indefinitely until unlockHandleEvent() is called.
289 * @return the old value of insideHandleEvent
291 private boolean lockHandleEvent() {
293 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
296 boolean oldValue
= true;
298 synchronized (this) {
299 // Wait for TApplication.run() to finish using the global state
300 // before allowing further event processing.
301 while (lockoutHandleEvent
== true) {
303 // Backoff so that the backend can finish its work.
305 } catch (InterruptedException e
) {
310 oldValue
= insideHandleEvent
;
311 insideHandleEvent
= true;
315 System
.err
.printf(" ***\n");
321 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
322 * spin indefinitely until unlockHandleEvent() is called.
324 * @return the old value of insideHandleEvent
326 private boolean unlockHandleEvent() {
328 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
331 synchronized (this) {
332 boolean oldValue
= insideHandleEvent
;
333 insideHandleEvent
= false;
339 * Spinlock for the primary and secondary event handlers. When true, the
340 * event handlers will spinlock wait before calling handleEvent().
342 private volatile boolean lockoutHandleEvent
= false;
345 * TApplication.run() needs to be able rely on the global data structures
346 * being intact when calling doIdle() and drawAll(). Tell the event
347 * handlers to wait for an unlock before handling their events.
349 private void stopEventHandlers() {
351 System
.err
.printf(">> stopEventHandlers()");
354 lockoutHandleEvent
= true;
355 // Wait for the last event to finish processing before returning
356 // control to TApplication.run().
357 while (insideHandleEvent
== true) {
359 // Backoff so that the event handler can finish its work.
361 } catch (InterruptedException e
) {
367 System
.err
.printf(" XXX\n");
372 * TApplication.run() needs to be able rely on the global data structures
373 * being intact when calling doIdle() and drawAll(). Tell the event
374 * handlers that it is now OK to handle their events.
376 private void startEventHandlers() {
378 System
.err
.printf("<< startEventHandlers()\n");
380 lockoutHandleEvent
= false;
383 // ------------------------------------------------------------------------
384 // TApplication attributes ------------------------------------------------
385 // ------------------------------------------------------------------------
388 * Access to the physical screen, keyboard, and mouse.
390 private Backend backend
;
395 * @return the Backend
397 public final Backend
getBackend() {
406 public final Screen
getScreen() {
407 return backend
.getScreen();
411 * Actual mouse coordinate X.
416 * Actual mouse coordinate Y.
421 * Old version of mouse coordinate X.
423 private int oldMouseX
;
426 * Old version mouse coordinate Y.
428 private int oldMouseY
;
431 * Event queue that is filled by run().
433 private List
<TInputEvent
> fillEventQueue
;
436 * Event queue that will be drained by either primary or secondary
439 private List
<TInputEvent
> drainEventQueue
;
442 * Top-level menus in this application.
444 private List
<TMenu
> menus
;
447 * Stack of activated sub-menus in this application.
449 private List
<TMenu
> subMenus
;
452 * The currently active menu.
454 private TMenu activeMenu
= null;
457 * Active keyboard accelerators.
459 private Map
<TKeypress
, TMenuItem
> accelerators
;
464 private List
<TMenuItem
> menuItems
;
467 * Windows and widgets pull colors from this ColorTheme.
469 private ColorTheme theme
;
472 * Get the color theme.
476 public final ColorTheme
getTheme() {
481 * The top-level windows (but not menus).
483 private List
<TWindow
> windows
;
486 * The currently acive window.
488 private TWindow activeWindow
= null;
491 * Timers that are being ticked.
493 private List
<TTimer
> timers
;
496 * When true, exit the application.
498 private volatile boolean quit
= false;
501 * When true, repaint the entire screen.
503 private volatile boolean repaint
= true;
506 * Y coordinate of the top edge of the desktop. For now this is a
507 * constant. Someday it would be nice to have a multi-line menu or
510 private static final int desktopTop
= 1;
513 * Get Y coordinate of the top edge of the desktop.
515 * @return Y coordinate of the top edge of the desktop
517 public final int getDesktopTop() {
522 * Y coordinate of the bottom edge of the desktop.
524 private int desktopBottom
;
527 * Get Y coordinate of the bottom edge of the desktop.
529 * @return Y coordinate of the bottom edge of the desktop
531 public final int getDesktopBottom() {
532 return desktopBottom
;
536 * An optional TDesktop background window that is drawn underneath
539 private TDesktop desktop
;
542 * Set the TDesktop instance.
544 * @param desktop a TDesktop instance, or null to remove the one that is
547 public final void setDesktop(final TDesktop desktop
) {
548 if (this.desktop
!= null) {
549 this.desktop
.onClose();
551 this.desktop
= desktop
;
555 * Get the TDesktop instance.
557 * @return the desktop, or null if it is not set
559 public final TDesktop
getDesktop() {
564 * Get the current active window.
566 * @return the active window, or null if it is not set
568 public final TWindow
getActiveWindow() {
573 * Get the list of windows.
575 * @return a copy of the list of windows for this application
577 public final List
<TWindow
> getAllWindows() {
578 List
<TWindow
> result
= new LinkedList
<TWindow
>();
579 result
.addAll(windows
);
583 // ------------------------------------------------------------------------
584 // General behavior -------------------------------------------------------
585 // ------------------------------------------------------------------------
588 * Display the about dialog.
590 protected void showAboutDialog() {
591 messageBox("About", "Jexer Version " +
592 this.getClass().getPackage().getImplementationVersion(),
593 TMessageBox
.Type
.OK
);
596 // ------------------------------------------------------------------------
597 // Constructors -----------------------------------------------------------
598 // ------------------------------------------------------------------------
601 * Public constructor.
603 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
605 * @throws UnsupportedEncodingException if an exception is thrown when
606 * creating the InputStreamReader
608 public TApplication(final BackendType backendType
)
609 throws UnsupportedEncodingException
{
611 switch (backendType
) {
613 backend
= new SwingBackend(this);
618 backend
= new ECMA48Backend(this, null, null);
621 throw new IllegalArgumentException("Invalid backend type: "
628 * Public constructor. The backend type will be BackendType.ECMA48.
630 * @param input an InputStream connected to the remote user, or null for
631 * System.in. If System.in is used, then on non-Windows systems it will
632 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
633 * mode. input is always converted to a Reader with UTF-8 encoding.
634 * @param output an OutputStream connected to the remote user, or null
635 * for System.out. output is always converted to a Writer with UTF-8
637 * @throws UnsupportedEncodingException if an exception is thrown when
638 * creating the InputStreamReader
640 public TApplication(final InputStream input
,
641 final OutputStream output
) throws UnsupportedEncodingException
{
643 backend
= new ECMA48Backend(this, input
, output
);
648 * Public constructor. The backend type will be BackendType.ECMA48.
650 * @param input the InputStream underlying 'reader'. Its available()
651 * method is used to determine if reader.read() will block or not.
652 * @param reader a Reader connected to the remote user.
653 * @param writer a PrintWriter connected to the remote user.
654 * @param setRawMode if true, set System.in into raw mode with stty.
655 * This should in general not be used. It is here solely for Demo3,
656 * which uses System.in.
657 * @throws IllegalArgumentException if input, reader, or writer are null.
659 public TApplication(final InputStream input
, final Reader reader
,
660 final PrintWriter writer
, final boolean setRawMode
) {
662 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
667 * Public constructor. The backend type will be BackendType.ECMA48.
669 * @param input the InputStream underlying 'reader'. Its available()
670 * method is used to determine if reader.read() will block or not.
671 * @param reader a Reader connected to the remote user.
672 * @param writer a PrintWriter connected to the remote user.
673 * @throws IllegalArgumentException if input, reader, or writer are null.
675 public TApplication(final InputStream input
, final Reader reader
,
676 final PrintWriter writer
) {
678 this(input
, reader
, writer
, false);
682 * Public constructor. This hook enables use with new non-Jexer
685 * @param backend a Backend that is already ready to go.
687 public TApplication(final Backend backend
) {
688 this.backend
= backend
;
693 * Finish construction once the backend is set.
695 private void TApplicationImpl() {
696 theme
= new ColorTheme();
697 desktopBottom
= getScreen().getHeight() - 1;
698 fillEventQueue
= new ArrayList
<TInputEvent
>();
699 drainEventQueue
= new ArrayList
<TInputEvent
>();
700 windows
= new LinkedList
<TWindow
>();
701 menus
= new LinkedList
<TMenu
>();
702 subMenus
= new LinkedList
<TMenu
>();
703 timers
= new LinkedList
<TTimer
>();
704 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
705 menuItems
= new ArrayList
<TMenuItem
>();
706 desktop
= new TDesktop(this);
708 // Setup the main consumer thread
709 primaryEventHandler
= new WidgetEventHandler(this, true);
710 (new Thread(primaryEventHandler
)).start();
713 // ------------------------------------------------------------------------
714 // Screen refresh loop ----------------------------------------------------
715 // ------------------------------------------------------------------------
718 * Invert the cell color at a position. This is used to track the mouse.
720 * @param x column position
721 * @param y row position
723 private void invertCell(final int x
, final int y
) {
725 System
.err
.printf("invertCell() %d %d\n", x
, y
);
727 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
728 attr
.setForeColor(attr
.getForeColor().invert());
729 attr
.setBackColor(attr
.getBackColor().invert());
730 getScreen().putAttrXY(x
, y
, attr
, false);
736 private void drawAll() {
738 System
.err
.printf("drawAll() enter\n");
743 System
.err
.printf("drawAll() !repaint\n");
745 synchronized (getScreen()) {
746 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
747 // The only thing that has happened is the mouse moved.
748 // Clear the old position and draw the new position.
749 invertCell(oldMouseX
, oldMouseY
);
750 invertCell(mouseX
, mouseY
);
754 if (getScreen().isDirty()) {
755 backend
.flushScreen();
762 System
.err
.printf("drawAll() REDRAW\n");
765 // If true, the cursor is not visible
766 boolean cursor
= false;
768 // Start with a clean screen
772 if (desktop
!= null) {
773 desktop
.drawChildren();
776 // Draw each window in reverse Z order
777 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
778 Collections
.sort(sorted
);
779 TWindow topLevel
= null;
780 if (sorted
.size() > 0) {
781 topLevel
= sorted
.get(0);
783 Collections
.reverse(sorted
);
784 for (TWindow window
: sorted
) {
785 if (window
.isShown()) {
786 window
.drawChildren();
790 // Draw the blank menubar line - reset the screen clipping first so
791 // it won't trim it out.
792 getScreen().resetClipping();
793 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
794 theme
.getColor("tmenu"));
795 // Now draw the menus.
797 for (TMenu menu
: menus
) {
798 CellAttributes menuColor
;
799 CellAttributes menuMnemonicColor
;
800 if (menu
.isActive()) {
801 menuColor
= theme
.getColor("tmenu.highlighted");
802 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
805 menuColor
= theme
.getColor("tmenu");
806 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
808 // Draw the menu title
809 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
811 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
812 // Draw the highlight character
813 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
814 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
816 if (menu
.isActive()) {
818 // Reset the screen clipping so we can draw the next title.
819 getScreen().resetClipping();
821 x
+= menu
.getTitle().length() + 2;
824 for (TMenu menu
: subMenus
) {
825 // Reset the screen clipping so we can draw the next sub-menu.
826 getScreen().resetClipping();
830 // Draw the status bar of the top-level window
831 TStatusBar statusBar
= null;
832 if (topLevel
!= null) {
833 statusBar
= topLevel
.getStatusBar();
835 if (statusBar
!= null) {
836 getScreen().resetClipping();
837 statusBar
.setWidth(getScreen().getWidth());
838 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
841 CellAttributes barColor
= new CellAttributes();
842 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
843 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
847 // Draw the mouse pointer
848 invertCell(mouseX
, mouseY
);
852 // Place the cursor if it is visible
853 TWidget activeWidget
= null;
854 if (sorted
.size() > 0) {
855 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
856 if (activeWidget
.isCursorVisible()) {
857 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
858 activeWidget
.getCursorAbsoluteY());
865 getScreen().hideCursor();
868 // Flush the screen contents
869 if (getScreen().isDirty()) {
870 backend
.flushScreen();
876 // ------------------------------------------------------------------------
877 // Main loop --------------------------------------------------------------
878 // ------------------------------------------------------------------------
881 * Run this application until it exits.
885 // Timeout is in milliseconds, so default timeout after 1 second
889 // If I've got no updates to render, wait for something from the
890 // backend or a timer.
892 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
894 // Never sleep longer than 50 millis. We need time for
895 // windows with background tasks to update the display, and
896 // still flip buffers reasonably quickly in
897 // backend.flushPhysical().
898 timeout
= getSleepTime(50);
902 // As of now, I've got nothing to do: no I/O, nothing from
903 // the consumer threads, no timers that need to run ASAP. So
904 // wait until either the backend or the consumer threads have
908 System
.err
.println("sleep " + timeout
+ " millis");
910 synchronized (this) {
913 } catch (InterruptedException e
) {
914 // I'm awake and don't care why, let's see what's going
920 // Prevent stepping on the primary or secondary event handler.
923 // Pull any pending I/O events
924 backend
.getEvents(fillEventQueue
);
926 // Dispatch each event to the appropriate handler, one at a time.
928 TInputEvent event
= null;
929 if (fillEventQueue
.size() == 0) {
932 event
= fillEventQueue
.remove(0);
933 metaHandleEvent(event
);
936 // Wake a consumer thread if we have any pending events.
937 if (drainEventQueue
.size() > 0) {
941 // Process timers and call doIdle()'s
945 synchronized (getScreen()) {
949 // Let the event handlers run again.
950 startEventHandlers();
954 // Shutdown the event consumer threads
955 if (secondaryEventHandler
!= null) {
956 synchronized (secondaryEventHandler
) {
957 secondaryEventHandler
.notify();
960 if (primaryEventHandler
!= null) {
961 synchronized (primaryEventHandler
) {
962 primaryEventHandler
.notify();
966 // Shutdown the user I/O thread(s)
969 // Close all the windows. This gives them an opportunity to release
976 * Peek at certain application-level events, add to eventQueue, and wake
977 * up the consuming Thread.
979 * @param event the input event to consume
981 private void metaHandleEvent(final TInputEvent event
) {
984 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
985 event
)); System
.err
.flush();
989 // Do no more processing if the application is already trying
994 // Special application-wide events -------------------------------
997 if (event
instanceof TCommandEvent
) {
998 TCommandEvent command
= (TCommandEvent
) event
;
999 if (command
.getCmd().equals(cmAbort
)) {
1006 if (event
instanceof TResizeEvent
) {
1007 TResizeEvent resize
= (TResizeEvent
) event
;
1008 synchronized (getScreen()) {
1009 getScreen().setDimensions(resize
.getWidth(),
1010 resize
.getHeight());
1011 desktopBottom
= getScreen().getHeight() - 1;
1017 if (desktop
!= null) {
1018 desktop
.setDimensions(0, 0, resize
.getWidth(),
1019 resize
.getHeight() - 1);
1024 // Peek at the mouse position
1025 if (event
instanceof TMouseEvent
) {
1026 TMouseEvent mouse
= (TMouseEvent
) event
;
1027 synchronized (getScreen()) {
1028 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1031 mouseX
= mouse
.getX();
1032 mouseY
= mouse
.getY();
1037 // Put into the main queue
1038 drainEventQueue
.add(event
);
1042 * Dispatch one event to the appropriate widget or application-level
1043 * event handler. This is the primary event handler, it has the normal
1044 * application-wide event handling.
1046 * @param event the input event to consume
1047 * @see #secondaryHandleEvent(TInputEvent event)
1049 private void primaryHandleEvent(final TInputEvent event
) {
1052 System
.err
.printf("Handle event: %s\n", event
);
1055 // Special application-wide events -----------------------------------
1057 // Peek at the mouse position
1058 if (event
instanceof TMouseEvent
) {
1059 // See if we need to switch focus to another window or the menu
1060 checkSwitchFocus((TMouseEvent
) event
);
1063 // Handle menu events
1064 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1065 TMenu menu
= activeMenu
;
1067 if (event
instanceof TMouseEvent
) {
1068 TMouseEvent mouse
= (TMouseEvent
) event
;
1070 while (subMenus
.size() > 0) {
1071 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1072 if (subMenu
.mouseWouldHit(mouse
)) {
1075 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1076 && (!mouse
.isMouse1())
1077 && (!mouse
.isMouse2())
1078 && (!mouse
.isMouse3())
1079 && (!mouse
.isMouseWheelUp())
1080 && (!mouse
.isMouseWheelDown())
1084 // We navigated away from a sub-menu, so close it
1088 // Convert the mouse relative x/y to menu coordinates
1089 assert (mouse
.getX() == mouse
.getAbsoluteX());
1090 assert (mouse
.getY() == mouse
.getAbsoluteY());
1091 if (subMenus
.size() > 0) {
1092 menu
= subMenus
.get(subMenus
.size() - 1);
1094 mouse
.setX(mouse
.getX() - menu
.getX());
1095 mouse
.setY(mouse
.getY() - menu
.getY());
1097 menu
.handleEvent(event
);
1101 if (event
instanceof TKeypressEvent
) {
1102 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1104 // See if this key matches an accelerator, and is not being
1105 // shortcutted by the active window, and if so dispatch the menu
1107 boolean windowWillShortcut
= false;
1108 if (activeWindow
!= null) {
1109 assert (activeWindow
.isShown());
1110 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1111 // We do not process this key, it will be passed to the
1113 windowWillShortcut
= true;
1117 if (!windowWillShortcut
&& !modalWindowActive()) {
1118 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1119 TMenuItem item
= null;
1120 synchronized (accelerators
) {
1121 item
= accelerators
.get(keypressLowercase
);
1124 if (item
.isEnabled()) {
1125 // Let the menu item dispatch
1131 // Handle the keypress
1132 if (onKeypress(keypress
)) {
1138 if (event
instanceof TCommandEvent
) {
1139 if (onCommand((TCommandEvent
) event
)) {
1144 if (event
instanceof TMenuEvent
) {
1145 if (onMenu((TMenuEvent
) event
)) {
1150 // Dispatch events to the active window -------------------------------
1151 boolean dispatchToDesktop
= true;
1152 TWindow window
= activeWindow
;
1153 if (window
!= null) {
1154 assert (window
.isActive());
1155 assert (window
.isShown());
1156 if (event
instanceof TMouseEvent
) {
1157 TMouseEvent mouse
= (TMouseEvent
) event
;
1158 // Convert the mouse relative x/y to window coordinates
1159 assert (mouse
.getX() == mouse
.getAbsoluteX());
1160 assert (mouse
.getY() == mouse
.getAbsoluteY());
1161 mouse
.setX(mouse
.getX() - window
.getX());
1162 mouse
.setY(mouse
.getY() - window
.getY());
1164 if (window
.mouseWouldHit(mouse
)) {
1165 dispatchToDesktop
= false;
1167 } else if (event
instanceof TKeypressEvent
) {
1168 dispatchToDesktop
= false;
1172 System
.err
.printf("TApplication dispatch event: %s\n",
1175 window
.handleEvent(event
);
1177 if (dispatchToDesktop
) {
1178 // This event is fair game for the desktop to process.
1179 if (desktop
!= null) {
1180 desktop
.handleEvent(event
);
1186 * Dispatch one event to the appropriate widget or application-level
1187 * event handler. This is the secondary event handler used by certain
1188 * special dialogs (currently TMessageBox and TFileOpenBox).
1190 * @param event the input event to consume
1191 * @see #primaryHandleEvent(TInputEvent event)
1193 private void secondaryHandleEvent(final TInputEvent event
) {
1194 secondaryEventReceiver
.handleEvent(event
);
1198 * Enable a widget to override the primary event thread.
1200 * @param widget widget that will receive events
1202 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1203 assert (secondaryEventReceiver
== null);
1204 assert (secondaryEventHandler
== null);
1205 assert ((widget
instanceof TMessageBox
)
1206 || (widget
instanceof TFileOpenBox
));
1207 secondaryEventReceiver
= widget
;
1208 secondaryEventHandler
= new WidgetEventHandler(this, false);
1209 (new Thread(secondaryEventHandler
)).start();
1213 * Yield to the secondary thread.
1215 public final void yield() {
1216 assert (secondaryEventReceiver
!= null);
1217 // This is where we handoff the event handler lock from the primary
1218 // to secondary thread. We unlock here, and in a future loop the
1219 // secondary thread locks again. When it gives up, we have the
1220 // single lock back.
1221 boolean oldLock
= unlockHandleEvent();
1224 while (secondaryEventReceiver
!= null) {
1225 synchronized (primaryEventHandler
) {
1227 primaryEventHandler
.wait();
1228 } catch (InterruptedException e
) {
1236 * Do stuff when there is no user input.
1238 private void doIdle() {
1240 System
.err
.printf("doIdle()\n");
1243 // Now run any timers that have timed out
1244 Date now
= new Date();
1245 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1246 for (TTimer timer
: timers
) {
1247 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1249 if (timer
.recurring
) {
1250 keepTimers
.add(timer
);
1253 keepTimers
.add(timer
);
1256 timers
= keepTimers
;
1259 for (TWindow window
: windows
) {
1262 if (desktop
!= null) {
1267 // ------------------------------------------------------------------------
1268 // TWindow management -----------------------------------------------------
1269 // ------------------------------------------------------------------------
1272 * Return the total number of windows.
1274 * @return the total number of windows
1276 public final int windowCount() {
1277 return windows
.size();
1281 * Return the number of windows that are visible.
1283 * @return the number of windows that are visible
1285 public final int shownWindowCount() {
1287 for (TWindow w
: windows
) {
1296 * Check if a window instance is in this application's window list.
1298 * @param window window to look for
1299 * @return true if this window is in the list
1301 public final boolean hasWindow(final TWindow window
) {
1302 if (windows
.size() == 0) {
1305 for (TWindow w
: windows
) {
1314 * Activate a window: bring it to the top and have it receive events.
1316 * @param window the window to become the new active window
1318 public void activateWindow(final TWindow window
) {
1319 if (hasWindow(window
) == false) {
1321 * Someone has a handle to a window I don't have. Ignore this
1327 assert (windows
.size() > 0);
1329 if (window
.isHidden()) {
1330 // Unhiding will also activate.
1334 assert (window
.isShown());
1336 if (windows
.size() == 1) {
1337 assert (window
== windows
.get(0));
1338 if (activeWindow
== null) {
1339 activeWindow
= window
;
1341 activeWindow
.setActive(true);
1342 activeWindow
.onFocus();
1345 assert (window
.isActive());
1346 assert (activeWindow
== window
);
1350 if (activeWindow
== window
) {
1351 assert (window
.isActive());
1353 // Window is already active, do nothing.
1357 assert (!window
.isActive());
1358 if (activeWindow
!= null) {
1359 assert (activeWindow
.getZ() == 0);
1361 activeWindow
.onUnfocus();
1362 activeWindow
.setActive(false);
1363 activeWindow
.setZ(window
.getZ());
1365 activeWindow
= window
;
1366 activeWindow
.setZ(0);
1367 activeWindow
.setActive(true);
1368 activeWindow
.onFocus();
1375 * @param window the window to hide
1377 public void hideWindow(final TWindow window
) {
1378 if (hasWindow(window
) == false) {
1380 * Someone has a handle to a window I don't have. Ignore this
1386 assert (windows
.size() > 0);
1388 if (!window
.hidden
) {
1389 if (window
== activeWindow
) {
1390 if (shownWindowCount() > 1) {
1393 activeWindow
= null;
1394 window
.setActive(false);
1398 window
.hidden
= true;
1406 * @param window the window to show
1408 public void showWindow(final TWindow window
) {
1409 if (hasWindow(window
) == false) {
1411 * Someone has a handle to a window I don't have. Ignore this
1417 assert (windows
.size() > 0);
1419 if (window
.hidden
) {
1420 window
.hidden
= false;
1422 activateWindow(window
);
1427 * Close window. Note that the window's destructor is NOT called by this
1428 * method, instead the GC is assumed to do the cleanup.
1430 * @param window the window to remove
1432 public final void closeWindow(final TWindow window
) {
1433 if (hasWindow(window
) == false) {
1435 * Someone has a handle to a window I don't have. Ignore this
1441 synchronized (windows
) {
1442 int z
= window
.getZ();
1445 Collections
.sort(windows
);
1447 activeWindow
= null;
1448 for (TWindow w
: windows
) {
1450 w
.setZ(w
.getZ() - 1);
1451 if (w
.getZ() == 0) {
1454 assert (activeWindow
== null);
1466 // Perform window cleanup
1469 // Check if we are closing a TMessageBox or similar
1470 if (secondaryEventReceiver
!= null) {
1471 assert (secondaryEventHandler
!= null);
1473 // Do not send events to the secondaryEventReceiver anymore, the
1474 // window is closed.
1475 secondaryEventReceiver
= null;
1477 // Wake the secondary thread, it will wake the primary as it
1479 synchronized (secondaryEventHandler
) {
1480 secondaryEventHandler
.notify();
1484 // Permit desktop to be active if it is the only thing left.
1485 if (desktop
!= null) {
1486 if (windows
.size() == 0) {
1487 desktop
.setActive(true);
1493 * Switch to the next window.
1495 * @param forward if true, then switch to the next window in the list,
1496 * otherwise switch to the previous window in the list
1498 public final void switchWindow(final boolean forward
) {
1499 // Only switch if there are multiple windows
1500 if (windows
.size() < 2) {
1503 assert (activeWindow
!= null);
1505 synchronized (windows
) {
1507 // Swap z/active between active window and the next in the list
1508 int activeWindowI
= -1;
1509 for (int i
= 0; i
< windows
.size(); i
++) {
1510 if (windows
.get(i
) == activeWindow
) {
1511 assert (activeWindow
.isActive());
1515 assert (!windows
.get(0).isActive());
1518 assert (activeWindowI
>= 0);
1520 // Do not switch if a window is modal
1521 if (activeWindow
.isModal()) {
1527 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1529 if (activeWindowI
== 0) {
1530 nextWindowI
= windows
.size() - 1;
1532 nextWindowI
= activeWindowI
- 1;
1536 activateWindow(windows
.get(nextWindowI
));
1537 } // synchronized (windows)
1542 * Add a window to my window list and make it active.
1544 * @param window new window to add
1546 public final void addWindow(final TWindow window
) {
1548 // Do not add menu windows to the window list.
1549 if (window
instanceof TMenu
) {
1553 // Do not add the desktop to the window list.
1554 if (window
instanceof TDesktop
) {
1558 synchronized (windows
) {
1559 // Do not allow a modal window to spawn a non-modal window. If a
1560 // modal window is active, then this window will become modal
1562 if (modalWindowActive()) {
1563 window
.flags
|= TWindow
.MODAL
;
1564 window
.flags
|= TWindow
.CENTERED
;
1565 window
.hidden
= false;
1567 if (window
.isShown()) {
1568 for (TWindow w
: windows
) {
1573 w
.setZ(w
.getZ() + 1);
1576 windows
.add(window
);
1577 if (window
.isShown()) {
1578 activeWindow
= window
;
1579 activeWindow
.setZ(0);
1580 activeWindow
.setActive(true);
1581 activeWindow
.onFocus();
1584 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1585 && smartWindowPlacement
) {
1587 doSmartPlacement(window
);
1591 // Desktop cannot be active over any other window.
1592 if (desktop
!= null) {
1593 desktop
.setActive(false);
1598 * Check if there is a system-modal window on top.
1600 * @return true if the active window is modal
1602 private boolean modalWindowActive() {
1603 if (windows
.size() == 0) {
1607 for (TWindow w
: windows
) {
1617 * Close all open windows.
1619 private void closeAllWindows() {
1620 // Don't do anything if we are in the menu
1621 if (activeMenu
!= null) {
1624 while (windows
.size() > 0) {
1625 closeWindow(windows
.get(0));
1630 * Re-layout the open windows as non-overlapping tiles. This produces
1631 * almost the same results as Turbo Pascal 7.0's IDE.
1633 private void tileWindows() {
1634 synchronized (windows
) {
1635 // Don't do anything if we are in the menu
1636 if (activeMenu
!= null) {
1639 int z
= windows
.size();
1645 a
= (int)(Math
.sqrt(z
));
1649 if (((a
* b
) + c
) == z
) {
1657 int newWidth
= (getScreen().getWidth() / a
);
1658 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1659 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1661 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1662 Collections
.sort(sorted
);
1663 Collections
.reverse(sorted
);
1664 for (int i
= 0; i
< sorted
.size(); i
++) {
1665 int logicalX
= i
/ b
;
1666 int logicalY
= i
% b
;
1667 if (i
>= ((a
- 1) * b
)) {
1669 logicalY
= i
- ((a
- 1) * b
);
1672 TWindow w
= sorted
.get(i
);
1673 w
.setX(logicalX
* newWidth
);
1674 w
.setWidth(newWidth
);
1675 if (i
>= ((a
- 1) * b
)) {
1676 w
.setY((logicalY
* newHeight2
) + 1);
1677 w
.setHeight(newHeight2
);
1679 w
.setY((logicalY
* newHeight1
) + 1);
1680 w
.setHeight(newHeight1
);
1687 * Re-layout the open windows as overlapping cascaded windows.
1689 private void cascadeWindows() {
1690 synchronized (windows
) {
1691 // Don't do anything if we are in the menu
1692 if (activeMenu
!= null) {
1697 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1698 Collections
.sort(sorted
);
1699 Collections
.reverse(sorted
);
1700 for (TWindow window
: sorted
) {
1705 if (x
> getScreen().getWidth()) {
1708 if (y
>= getScreen().getHeight()) {
1716 * Place a window to minimize its overlap with other windows.
1718 * @param window the window to place
1720 public final void doSmartPlacement(final TWindow window
) {
1721 // This is a pretty dumb algorithm, but seems to work. The hardest
1722 // part is computing these "overlap" values seeking a minimum average
1725 int yMin
= desktopTop
;
1726 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1727 int yMax
= desktopBottom
- window
.getHeight() + 1;
1735 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1736 // No work to do, bail out.
1740 // Compute the overlap matrix without the new window.
1741 int width
= getScreen().getWidth();
1742 int height
= getScreen().getHeight();
1743 int overlapMatrix
[][] = new int[width
][height
];
1744 for (TWindow w
: windows
) {
1748 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1752 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1756 overlapMatrix
[x
][y
]++;
1761 long oldOverlapTotal
= 0;
1762 long oldOverlapN
= 0;
1763 for (int x
= 0; x
< width
; x
++) {
1764 for (int y
= 0; y
< height
; y
++) {
1765 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1766 if (overlapMatrix
[x
][y
] > 0) {
1773 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1774 boolean first
= true;
1775 int windowX
= window
.getX();
1776 int windowY
= window
.getY();
1778 // For each possible (x, y) position for the new window, compute a
1779 // new overlap matrix.
1780 for (int x
= xMin
; x
< xMax
; x
++) {
1781 for (int y
= yMin
; y
< yMax
; y
++) {
1783 // Start with the matrix minus this window.
1784 int newMatrix
[][] = new int[width
][height
];
1785 for (int mx
= 0; mx
< width
; mx
++) {
1786 for (int my
= 0; my
< height
; my
++) {
1787 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1791 // Add this window's values to the new overlap matrix.
1792 long newOverlapTotal
= 0;
1793 long newOverlapN
= 0;
1794 // Start by adding each new cell.
1795 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1799 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1803 newMatrix
[wx
][wy
]++;
1806 // Now figure out the new value for total coverage.
1807 for (int mx
= 0; mx
< width
; mx
++) {
1808 for (int my
= 0; my
< height
; my
++) {
1809 newOverlapTotal
+= newMatrix
[x
][y
];
1810 if (newMatrix
[mx
][my
] > 0) {
1815 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1818 // First time: just record what we got.
1819 oldOverlapAvg
= newOverlapAvg
;
1822 // All other times: pick a new best (x, y) and save the
1824 if (newOverlapAvg
< oldOverlapAvg
) {
1827 oldOverlapAvg
= newOverlapAvg
;
1831 } // for (int x = xMin; x < xMax; x++)
1833 } // for (int y = yMin; y < yMax; y++)
1835 // Finally, set the window's new coordinates.
1836 window
.setX(windowX
);
1837 window
.setY(windowY
);
1840 // ------------------------------------------------------------------------
1841 // TMenu management -------------------------------------------------------
1842 // ------------------------------------------------------------------------
1845 * Check if a mouse event would hit either the active menu or any open
1848 * @param mouse mouse event
1849 * @return true if the mouse would hit the active menu or an open
1852 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1853 assert (activeMenu
!= null);
1854 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1855 Collections
.reverse(menus
);
1856 for (TMenu menu
: menus
) {
1857 if (menu
.mouseWouldHit(mouse
)) {
1861 return activeMenu
.mouseWouldHit(mouse
);
1865 * See if we need to switch window or activate the menu based on
1868 * @param mouse mouse event
1870 private void checkSwitchFocus(final TMouseEvent mouse
) {
1872 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1873 && (activeMenu
!= null)
1874 && (mouse
.getAbsoluteY() != 0)
1875 && (!mouseOnMenu(mouse
))
1877 // They clicked outside the active menu, turn it off
1878 activeMenu
.setActive(false);
1880 for (TMenu menu
: subMenus
) {
1881 menu
.setActive(false);
1887 // See if they hit the menu bar
1888 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1889 && (mouse
.isMouse1())
1890 && (!modalWindowActive())
1891 && (mouse
.getAbsoluteY() == 0)
1894 for (TMenu menu
: subMenus
) {
1895 menu
.setActive(false);
1899 // They selected the menu, go activate it
1900 for (TMenu menu
: menus
) {
1901 if ((mouse
.getAbsoluteX() >= menu
.getX())
1902 && (mouse
.getAbsoluteX() < menu
.getX()
1903 + menu
.getTitle().length() + 2)
1905 menu
.setActive(true);
1908 menu
.setActive(false);
1914 // See if they hit the menu bar
1915 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1916 && (mouse
.isMouse1())
1917 && (activeMenu
!= null)
1918 && (mouse
.getAbsoluteY() == 0)
1921 TMenu oldMenu
= activeMenu
;
1922 for (TMenu menu
: subMenus
) {
1923 menu
.setActive(false);
1927 // See if we should switch menus
1928 for (TMenu menu
: menus
) {
1929 if ((mouse
.getAbsoluteX() >= menu
.getX())
1930 && (mouse
.getAbsoluteX() < menu
.getX()
1931 + menu
.getTitle().length() + 2)
1933 menu
.setActive(true);
1937 if (oldMenu
!= activeMenu
) {
1938 // They switched menus
1939 oldMenu
.setActive(false);
1944 // Only switch if there are multiple windows
1945 if (windows
.size() < 2) {
1949 // Switch on the upclick
1950 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1954 synchronized (windows
) {
1955 Collections
.sort(windows
);
1956 if (windows
.get(0).isModal()) {
1957 // Modal windows don't switch
1961 for (TWindow window
: windows
) {
1962 assert (!window
.isModal());
1964 if (window
.isHidden()) {
1965 assert (!window
.isActive());
1969 if (window
.mouseWouldHit(mouse
)) {
1970 if (window
== windows
.get(0)) {
1971 // Clicked on the same window, nothing to do
1972 assert (window
.isActive());
1976 // We will be switching to another window
1977 assert (windows
.get(0).isActive());
1978 assert (windows
.get(0) == activeWindow
);
1979 assert (!window
.isActive());
1980 activeWindow
.onUnfocus();
1981 activeWindow
.setActive(false);
1982 activeWindow
.setZ(window
.getZ());
1983 activeWindow
= window
;
1985 window
.setActive(true);
1992 // Clicked on the background, nothing to do
1997 * Turn off the menu.
1999 public final void closeMenu() {
2000 if (activeMenu
!= null) {
2001 activeMenu
.setActive(false);
2003 for (TMenu menu
: subMenus
) {
2004 menu
.setActive(false);
2011 * Turn off a sub-menu.
2013 public final void closeSubMenu() {
2014 assert (activeMenu
!= null);
2015 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2016 assert (item
!= null);
2017 item
.setActive(false);
2018 subMenus
.remove(subMenus
.size() - 1);
2022 * Switch to the next menu.
2024 * @param forward if true, then switch to the next menu in the list,
2025 * otherwise switch to the previous menu in the list
2027 public final void switchMenu(final boolean forward
) {
2028 assert (activeMenu
!= null);
2030 for (TMenu menu
: subMenus
) {
2031 menu
.setActive(false);
2035 for (int i
= 0; i
< menus
.size(); i
++) {
2036 if (activeMenu
== menus
.get(i
)) {
2038 if (i
< menus
.size() - 1) {
2046 activeMenu
.setActive(false);
2047 activeMenu
= menus
.get(i
);
2048 activeMenu
.setActive(true);
2055 * Add a menu item to the global list. If it has a keyboard accelerator,
2056 * that will be added the global hash.
2058 * @param item the menu item
2060 public final void addMenuItem(final TMenuItem item
) {
2061 menuItems
.add(item
);
2063 TKeypress key
= item
.getKey();
2065 synchronized (accelerators
) {
2066 assert (accelerators
.get(key
) == null);
2067 accelerators
.put(key
.toLowerCase(), item
);
2073 * Disable one menu item.
2075 * @param id the menu item ID
2077 public final void disableMenuItem(final int id
) {
2078 for (TMenuItem item
: menuItems
) {
2079 if (item
.getId() == id
) {
2080 item
.setEnabled(false);
2086 * Disable the range of menu items with ID's between lower and upper,
2089 * @param lower the lowest menu item ID
2090 * @param upper the highest menu item ID
2092 public final void disableMenuItems(final int lower
, final int upper
) {
2093 for (TMenuItem item
: menuItems
) {
2094 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2095 item
.setEnabled(false);
2101 * Enable one menu item.
2103 * @param id the menu item ID
2105 public final void enableMenuItem(final int id
) {
2106 for (TMenuItem item
: menuItems
) {
2107 if (item
.getId() == id
) {
2108 item
.setEnabled(true);
2114 * Enable the range of menu items with ID's between lower and upper,
2117 * @param lower the lowest menu item ID
2118 * @param upper the highest menu item ID
2120 public final void enableMenuItems(final int lower
, final int upper
) {
2121 for (TMenuItem item
: menuItems
) {
2122 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2123 item
.setEnabled(true);
2129 * Recompute menu x positions based on their title length.
2131 public final void recomputeMenuX() {
2133 for (TMenu menu
: menus
) {
2135 x
+= menu
.getTitle().length() + 2;
2140 * Post an event to process and turn off the menu.
2142 * @param event new event to add to the queue
2144 public final void postMenuEvent(final TInputEvent event
) {
2145 synchronized (fillEventQueue
) {
2146 fillEventQueue
.add(event
);
2152 * Add a sub-menu to the list of open sub-menus.
2154 * @param menu sub-menu
2156 public final void addSubMenu(final TMenu menu
) {
2161 * Convenience function to add a top-level menu.
2163 * @param title menu title
2164 * @return the new menu
2166 public final TMenu
addMenu(final String title
) {
2169 TMenu menu
= new TMenu(this, x
, y
, title
);
2176 * Convenience function to add a default "File" menu.
2178 * @return the new menu
2180 public final TMenu
addFileMenu() {
2181 TMenu fileMenu
= addMenu("&File");
2182 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2183 fileMenu
.addSeparator();
2184 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2185 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2186 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2187 "commands (Open, Save, Print, etc.)");
2188 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2193 * Convenience function to add a default "Edit" menu.
2195 * @return the new menu
2197 public final TMenu
addEditMenu() {
2198 TMenu editMenu
= addMenu("&Edit");
2199 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2200 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2201 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2202 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2203 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2204 "undo, and Clipboard access");
2205 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2210 * Convenience function to add a default "Window" menu.
2212 * @return the new menu
2214 public final TMenu
addWindowMenu() {
2215 TMenu windowMenu
= addMenu("&Window");
2216 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2217 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2218 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2219 windowMenu
.addSeparator();
2220 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2221 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2222 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2223 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2224 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2225 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2227 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2232 * Convenience function to add a default "Help" menu.
2234 * @return the new menu
2236 public final TMenu
addHelpMenu() {
2237 TMenu helpMenu
= addMenu("&Help");
2238 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2239 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2240 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2241 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2242 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2243 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2244 helpMenu
.addSeparator();
2245 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2246 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2247 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2251 // ------------------------------------------------------------------------
2252 // Event handlers ---------------------------------------------------------
2253 // ------------------------------------------------------------------------
2256 * Method that TApplication subclasses can override to handle menu or
2257 * posted command events.
2259 * @param command command event
2260 * @return if true, this event was consumed
2262 protected boolean onCommand(final TCommandEvent command
) {
2263 // Default: handle cmExit
2264 if (command
.equals(cmExit
)) {
2265 if (messageBox("Confirmation", "Exit application?",
2266 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2272 if (command
.equals(cmShell
)) {
2273 openTerminal(0, 0, TWindow
.RESIZABLE
);
2277 if (command
.equals(cmTile
)) {
2281 if (command
.equals(cmCascade
)) {
2285 if (command
.equals(cmCloseAll
)) {
2294 * Method that TApplication subclasses can override to handle menu
2297 * @param menu menu event
2298 * @return if true, this event was consumed
2300 protected boolean onMenu(final TMenuEvent menu
) {
2302 // Default: handle MID_EXIT
2303 if (menu
.getId() == TMenu
.MID_EXIT
) {
2304 if (messageBox("Confirmation", "Exit application?",
2305 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2311 if (menu
.getId() == TMenu
.MID_SHELL
) {
2312 openTerminal(0, 0, TWindow
.RESIZABLE
);
2316 if (menu
.getId() == TMenu
.MID_TILE
) {
2320 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2324 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2328 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2336 * Method that TApplication subclasses can override to handle keystrokes.
2338 * @param keypress keystroke event
2339 * @return if true, this event was consumed
2341 protected boolean onKeypress(final TKeypressEvent keypress
) {
2342 // Default: only menu shortcuts
2344 // Process Alt-F, Alt-E, etc. menu shortcut keys
2345 if (!keypress
.getKey().isFnKey()
2346 && keypress
.getKey().isAlt()
2347 && !keypress
.getKey().isCtrl()
2348 && (activeMenu
== null)
2349 && !modalWindowActive()
2352 assert (subMenus
.size() == 0);
2354 for (TMenu menu
: menus
) {
2355 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2356 == Character
.toLowerCase(keypress
.getKey().getChar())
2359 menu
.setActive(true);
2368 // ------------------------------------------------------------------------
2369 // TTimer management ------------------------------------------------------
2370 // ------------------------------------------------------------------------
2373 * Get the amount of time I can sleep before missing a Timer tick.
2375 * @param timeout = initial (maximum) timeout in millis
2376 * @return number of milliseconds between now and the next timer event
2378 private long getSleepTime(final long timeout
) {
2379 Date now
= new Date();
2380 long nowTime
= now
.getTime();
2381 long sleepTime
= timeout
;
2382 for (TTimer timer
: timers
) {
2383 long nextTickTime
= timer
.getNextTick().getTime();
2384 if (nextTickTime
< nowTime
) {
2388 long timeDifference
= nextTickTime
- nowTime
;
2389 if (timeDifference
< sleepTime
) {
2390 sleepTime
= timeDifference
;
2393 assert (sleepTime
>= 0);
2394 assert (sleepTime
<= timeout
);
2399 * Convenience function to add a timer.
2401 * @param duration number of milliseconds to wait between ticks
2402 * @param recurring if true, re-schedule this timer after every tick
2403 * @param action function to call when button is pressed
2406 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2407 final TAction action
) {
2409 TTimer timer
= new TTimer(duration
, recurring
, action
);
2410 synchronized (timers
) {
2417 * Convenience function to remove a timer.
2419 * @param timer timer to remove
2421 public final void removeTimer(final TTimer timer
) {
2422 synchronized (timers
) {
2423 timers
.remove(timer
);
2427 // ------------------------------------------------------------------------
2428 // Other TWindow constructors ---------------------------------------------
2429 // ------------------------------------------------------------------------
2432 * Convenience function to spawn a message box.
2434 * @param title window title, will be centered along the top border
2435 * @param caption message to display. Use embedded newlines to get a
2437 * @return the new message box
2439 public final TMessageBox
messageBox(final String title
,
2440 final String caption
) {
2442 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2446 * Convenience function to spawn a message box.
2448 * @param title window title, will be centered along the top border
2449 * @param caption message to display. Use embedded newlines to get a
2451 * @param type one of the TMessageBox.Type constants. Default is
2453 * @return the new message box
2455 public final TMessageBox
messageBox(final String title
,
2456 final String caption
, final TMessageBox
.Type type
) {
2458 return new TMessageBox(this, title
, caption
, type
);
2462 * Convenience function to spawn an input box.
2464 * @param title window title, will be centered along the top border
2465 * @param caption message to display. Use embedded newlines to get a
2467 * @return the new input box
2469 public final TInputBox
inputBox(final String title
, final String caption
) {
2471 return new TInputBox(this, title
, caption
);
2475 * Convenience function to spawn an input box.
2477 * @param title window title, will be centered along the top border
2478 * @param caption message to display. Use embedded newlines to get a
2480 * @param text initial text to seed the field with
2481 * @return the new input box
2483 public final TInputBox
inputBox(final String title
, final String caption
,
2484 final String text
) {
2486 return new TInputBox(this, title
, caption
, text
);
2490 * Convenience function to open a terminal window.
2492 * @param x column relative to parent
2493 * @param y row relative to parent
2494 * @return the terminal new window
2496 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2497 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2501 * Convenience function to open a terminal window.
2503 * @param x column relative to parent
2504 * @param y row relative to parent
2505 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2506 * @return the terminal new window
2508 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2511 return new TTerminalWindow(this, x
, y
, flags
);
2515 * Convenience function to spawn an file open box.
2517 * @param path path of selected file
2518 * @return the result of the new file open box
2519 * @throws IOException if java.io operation throws
2521 public final String
fileOpenBox(final String path
) throws IOException
{
2523 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2524 return box
.getFilename();
2528 * Convenience function to spawn an file open box.
2530 * @param path path of selected file
2531 * @param type one of the Type constants
2532 * @return the result of the new file open box
2533 * @throws IOException if java.io operation throws
2535 public final String
fileOpenBox(final String path
,
2536 final TFileOpenBox
.Type type
) throws IOException
{
2538 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2539 return box
.getFilename();
2543 * Convenience function to create a new window and make it active.
2544 * Window will be located at (0, 0).
2546 * @param title window title, will be centered along the top border
2547 * @param width width of window
2548 * @param height height of window
2550 public final TWindow
addWindow(final String title
, final int width
,
2553 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2557 * Convenience function to create a new window and make it active.
2558 * Window will be located at (0, 0).
2560 * @param title window title, will be centered along the top border
2561 * @param width width of window
2562 * @param height height of window
2563 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2565 public final TWindow
addWindow(final String title
,
2566 final int width
, final int height
, final int flags
) {
2568 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2573 * Convenience function to create a new window and make it active.
2575 * @param title window title, will be centered along the top border
2576 * @param x column relative to parent
2577 * @param y row relative to parent
2578 * @param width width of window
2579 * @param height height of window
2581 public final TWindow
addWindow(final String title
,
2582 final int x
, final int y
, final int width
, final int height
) {
2584 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2589 * Convenience function to create a new window and make it active.
2591 * @param application TApplication that manages this window
2592 * @param title window title, will be centered along the top border
2593 * @param x column relative to parent
2594 * @param y row relative to parent
2595 * @param width width of window
2596 * @param height height of window
2597 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2599 public final TWindow
addWindow(final String title
,
2600 final int x
, final int y
, final int width
, final int height
,
2603 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);