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 showing.
1283 * @return the number of windows that are showing on screen
1285 public final int shownWindowCount() {
1287 for (TWindow w
: windows
) {
1296 * Return the number of windows that are hidden.
1298 * @return the number of windows that are hidden
1300 public final int hiddenWindowCount() {
1302 for (TWindow w
: windows
) {
1311 * Check if a window instance is in this application's window list.
1313 * @param window window to look for
1314 * @return true if this window is in the list
1316 public final boolean hasWindow(final TWindow window
) {
1317 if (windows
.size() == 0) {
1320 for (TWindow w
: windows
) {
1322 assert (window
.getApplication() == this);
1330 * Activate a window: bring it to the top and have it receive events.
1332 * @param window the window to become the new active window
1334 public void activateWindow(final TWindow window
) {
1335 if (hasWindow(window
) == false) {
1337 * Someone has a handle to a window I don't have. Ignore this
1343 assert (windows
.size() > 0);
1345 if (window
.isHidden()) {
1346 // Unhiding will also activate.
1350 assert (window
.isShown());
1352 if (windows
.size() == 1) {
1353 assert (window
== windows
.get(0));
1354 if (activeWindow
== null) {
1355 activeWindow
= window
;
1357 activeWindow
.setActive(true);
1358 activeWindow
.onFocus();
1361 assert (window
.isActive());
1362 assert (activeWindow
== window
);
1366 if (activeWindow
== window
) {
1367 assert (window
.isActive());
1369 // Window is already active, do nothing.
1373 assert (!window
.isActive());
1374 if (activeWindow
!= null) {
1375 assert (activeWindow
.getZ() == 0);
1377 activeWindow
.onUnfocus();
1378 activeWindow
.setActive(false);
1379 activeWindow
.setZ(window
.getZ());
1381 activeWindow
= window
;
1382 activeWindow
.setZ(0);
1383 activeWindow
.setActive(true);
1384 activeWindow
.onFocus();
1391 * @param window the window to hide
1393 public void hideWindow(final TWindow window
) {
1394 if (hasWindow(window
) == false) {
1396 * Someone has a handle to a window I don't have. Ignore this
1402 assert (windows
.size() > 0);
1404 if (!window
.hidden
) {
1405 if (window
== activeWindow
) {
1406 if (shownWindowCount() > 1) {
1409 activeWindow
= null;
1410 window
.setActive(false);
1414 window
.hidden
= true;
1422 * @param window the window to show
1424 public void showWindow(final TWindow window
) {
1425 if (hasWindow(window
) == false) {
1427 * Someone has a handle to a window I don't have. Ignore this
1433 assert (windows
.size() > 0);
1435 if (window
.hidden
) {
1436 window
.hidden
= false;
1438 activateWindow(window
);
1443 * Close window. Note that the window's destructor is NOT called by this
1444 * method, instead the GC is assumed to do the cleanup.
1446 * @param window the window to remove
1448 public final void closeWindow(final TWindow window
) {
1449 if (hasWindow(window
) == false) {
1451 * Someone has a handle to a window I don't have. Ignore this
1457 synchronized (windows
) {
1458 int z
= window
.getZ();
1461 Collections
.sort(windows
);
1463 activeWindow
= null;
1464 for (TWindow w
: windows
) {
1466 w
.setZ(w
.getZ() - 1);
1467 if (w
.getZ() == 0) {
1470 assert (activeWindow
== null);
1482 // Perform window cleanup
1485 // Check if we are closing a TMessageBox or similar
1486 if (secondaryEventReceiver
!= null) {
1487 assert (secondaryEventHandler
!= null);
1489 // Do not send events to the secondaryEventReceiver anymore, the
1490 // window is closed.
1491 secondaryEventReceiver
= null;
1493 // Wake the secondary thread, it will wake the primary as it
1495 synchronized (secondaryEventHandler
) {
1496 secondaryEventHandler
.notify();
1500 // Permit desktop to be active if it is the only thing left.
1501 if (desktop
!= null) {
1502 if (windows
.size() == 0) {
1503 desktop
.setActive(true);
1509 * Switch to the next window.
1511 * @param forward if true, then switch to the next window in the list,
1512 * otherwise switch to the previous window in the list
1514 public final void switchWindow(final boolean forward
) {
1515 // Only switch if there are multiple visible windows
1516 if (shownWindowCount() < 2) {
1519 assert (activeWindow
!= null);
1521 synchronized (windows
) {
1523 // Swap z/active between active window and the next in the list
1524 int activeWindowI
= -1;
1525 for (int i
= 0; i
< windows
.size(); i
++) {
1526 if (windows
.get(i
) == activeWindow
) {
1527 assert (activeWindow
.isActive());
1531 assert (!windows
.get(0).isActive());
1534 assert (activeWindowI
>= 0);
1536 // Do not switch if a window is modal
1537 if (activeWindow
.isModal()) {
1541 int nextWindowI
= activeWindowI
;
1545 nextWindowI
%= windows
.size();
1548 if (nextWindowI
< 0) {
1549 nextWindowI
= windows
.size() - 1;
1553 if (windows
.get(nextWindowI
).isShown()) {
1554 activateWindow(windows
.get(nextWindowI
));
1558 } // synchronized (windows)
1563 * Add a window to my window list and make it active.
1565 * @param window new window to add
1567 public final void addWindow(final TWindow window
) {
1569 // Do not add menu windows to the window list.
1570 if (window
instanceof TMenu
) {
1574 // Do not add the desktop to the window list.
1575 if (window
instanceof TDesktop
) {
1579 synchronized (windows
) {
1580 // Do not allow a modal window to spawn a non-modal window. If a
1581 // modal window is active, then this window will become modal
1583 if (modalWindowActive()) {
1584 window
.flags
|= TWindow
.MODAL
;
1585 window
.flags
|= TWindow
.CENTERED
;
1586 window
.hidden
= false;
1588 if (window
.isShown()) {
1589 for (TWindow w
: windows
) {
1594 w
.setZ(w
.getZ() + 1);
1597 windows
.add(window
);
1598 if (window
.isShown()) {
1599 activeWindow
= window
;
1600 activeWindow
.setZ(0);
1601 activeWindow
.setActive(true);
1602 activeWindow
.onFocus();
1605 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1606 && smartWindowPlacement
) {
1608 doSmartPlacement(window
);
1612 // Desktop cannot be active over any other window.
1613 if (desktop
!= null) {
1614 desktop
.setActive(false);
1619 * Check if there is a system-modal window on top.
1621 * @return true if the active window is modal
1623 private boolean modalWindowActive() {
1624 if (windows
.size() == 0) {
1628 for (TWindow w
: windows
) {
1638 * Close all open windows.
1640 private void closeAllWindows() {
1641 // Don't do anything if we are in the menu
1642 if (activeMenu
!= null) {
1645 while (windows
.size() > 0) {
1646 closeWindow(windows
.get(0));
1651 * Re-layout the open windows as non-overlapping tiles. This produces
1652 * almost the same results as Turbo Pascal 7.0's IDE.
1654 private void tileWindows() {
1655 synchronized (windows
) {
1656 // Don't do anything if we are in the menu
1657 if (activeMenu
!= null) {
1660 int z
= windows
.size();
1666 a
= (int)(Math
.sqrt(z
));
1670 if (((a
* b
) + c
) == z
) {
1678 int newWidth
= (getScreen().getWidth() / a
);
1679 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1680 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1682 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1683 Collections
.sort(sorted
);
1684 Collections
.reverse(sorted
);
1685 for (int i
= 0; i
< sorted
.size(); i
++) {
1686 int logicalX
= i
/ b
;
1687 int logicalY
= i
% b
;
1688 if (i
>= ((a
- 1) * b
)) {
1690 logicalY
= i
- ((a
- 1) * b
);
1693 TWindow w
= sorted
.get(i
);
1694 w
.setX(logicalX
* newWidth
);
1695 w
.setWidth(newWidth
);
1696 if (i
>= ((a
- 1) * b
)) {
1697 w
.setY((logicalY
* newHeight2
) + 1);
1698 w
.setHeight(newHeight2
);
1700 w
.setY((logicalY
* newHeight1
) + 1);
1701 w
.setHeight(newHeight1
);
1708 * Re-layout the open windows as overlapping cascaded windows.
1710 private void cascadeWindows() {
1711 synchronized (windows
) {
1712 // Don't do anything if we are in the menu
1713 if (activeMenu
!= null) {
1718 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1719 Collections
.sort(sorted
);
1720 Collections
.reverse(sorted
);
1721 for (TWindow window
: sorted
) {
1726 if (x
> getScreen().getWidth()) {
1729 if (y
>= getScreen().getHeight()) {
1737 * Place a window to minimize its overlap with other windows.
1739 * @param window the window to place
1741 public final void doSmartPlacement(final TWindow window
) {
1742 // This is a pretty dumb algorithm, but seems to work. The hardest
1743 // part is computing these "overlap" values seeking a minimum average
1746 int yMin
= desktopTop
;
1747 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1748 int yMax
= desktopBottom
- window
.getHeight() + 1;
1756 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1757 // No work to do, bail out.
1761 // Compute the overlap matrix without the new window.
1762 int width
= getScreen().getWidth();
1763 int height
= getScreen().getHeight();
1764 int overlapMatrix
[][] = new int[width
][height
];
1765 for (TWindow w
: windows
) {
1769 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1773 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1777 overlapMatrix
[x
][y
]++;
1782 long oldOverlapTotal
= 0;
1783 long oldOverlapN
= 0;
1784 for (int x
= 0; x
< width
; x
++) {
1785 for (int y
= 0; y
< height
; y
++) {
1786 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1787 if (overlapMatrix
[x
][y
] > 0) {
1794 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1795 boolean first
= true;
1796 int windowX
= window
.getX();
1797 int windowY
= window
.getY();
1799 // For each possible (x, y) position for the new window, compute a
1800 // new overlap matrix.
1801 for (int x
= xMin
; x
< xMax
; x
++) {
1802 for (int y
= yMin
; y
< yMax
; y
++) {
1804 // Start with the matrix minus this window.
1805 int newMatrix
[][] = new int[width
][height
];
1806 for (int mx
= 0; mx
< width
; mx
++) {
1807 for (int my
= 0; my
< height
; my
++) {
1808 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1812 // Add this window's values to the new overlap matrix.
1813 long newOverlapTotal
= 0;
1814 long newOverlapN
= 0;
1815 // Start by adding each new cell.
1816 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1820 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1824 newMatrix
[wx
][wy
]++;
1827 // Now figure out the new value for total coverage.
1828 for (int mx
= 0; mx
< width
; mx
++) {
1829 for (int my
= 0; my
< height
; my
++) {
1830 newOverlapTotal
+= newMatrix
[x
][y
];
1831 if (newMatrix
[mx
][my
] > 0) {
1836 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1839 // First time: just record what we got.
1840 oldOverlapAvg
= newOverlapAvg
;
1843 // All other times: pick a new best (x, y) and save the
1845 if (newOverlapAvg
< oldOverlapAvg
) {
1848 oldOverlapAvg
= newOverlapAvg
;
1852 } // for (int x = xMin; x < xMax; x++)
1854 } // for (int y = yMin; y < yMax; y++)
1856 // Finally, set the window's new coordinates.
1857 window
.setX(windowX
);
1858 window
.setY(windowY
);
1861 // ------------------------------------------------------------------------
1862 // TMenu management -------------------------------------------------------
1863 // ------------------------------------------------------------------------
1866 * Check if a mouse event would hit either the active menu or any open
1869 * @param mouse mouse event
1870 * @return true if the mouse would hit the active menu or an open
1873 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1874 assert (activeMenu
!= null);
1875 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1876 Collections
.reverse(menus
);
1877 for (TMenu menu
: menus
) {
1878 if (menu
.mouseWouldHit(mouse
)) {
1882 return activeMenu
.mouseWouldHit(mouse
);
1886 * See if we need to switch window or activate the menu based on
1889 * @param mouse mouse event
1891 private void checkSwitchFocus(final TMouseEvent mouse
) {
1893 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1894 && (activeMenu
!= null)
1895 && (mouse
.getAbsoluteY() != 0)
1896 && (!mouseOnMenu(mouse
))
1898 // They clicked outside the active menu, turn it off
1899 activeMenu
.setActive(false);
1901 for (TMenu menu
: subMenus
) {
1902 menu
.setActive(false);
1908 // See if they hit the menu bar
1909 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1910 && (mouse
.isMouse1())
1911 && (!modalWindowActive())
1912 && (mouse
.getAbsoluteY() == 0)
1915 for (TMenu menu
: subMenus
) {
1916 menu
.setActive(false);
1920 // They selected the menu, go activate it
1921 for (TMenu menu
: menus
) {
1922 if ((mouse
.getAbsoluteX() >= menu
.getX())
1923 && (mouse
.getAbsoluteX() < menu
.getX()
1924 + menu
.getTitle().length() + 2)
1926 menu
.setActive(true);
1929 menu
.setActive(false);
1935 // See if they hit the menu bar
1936 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1937 && (mouse
.isMouse1())
1938 && (activeMenu
!= null)
1939 && (mouse
.getAbsoluteY() == 0)
1942 TMenu oldMenu
= activeMenu
;
1943 for (TMenu menu
: subMenus
) {
1944 menu
.setActive(false);
1948 // See if we should switch menus
1949 for (TMenu menu
: menus
) {
1950 if ((mouse
.getAbsoluteX() >= menu
.getX())
1951 && (mouse
.getAbsoluteX() < menu
.getX()
1952 + menu
.getTitle().length() + 2)
1954 menu
.setActive(true);
1958 if (oldMenu
!= activeMenu
) {
1959 // They switched menus
1960 oldMenu
.setActive(false);
1965 // Only switch if there are multiple windows
1966 if (windows
.size() < 2) {
1970 // Switch on the upclick
1971 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1975 synchronized (windows
) {
1976 Collections
.sort(windows
);
1977 if (windows
.get(0).isModal()) {
1978 // Modal windows don't switch
1982 for (TWindow window
: windows
) {
1983 assert (!window
.isModal());
1985 if (window
.isHidden()) {
1986 assert (!window
.isActive());
1990 if (window
.mouseWouldHit(mouse
)) {
1991 if (window
== windows
.get(0)) {
1992 // Clicked on the same window, nothing to do
1993 assert (window
.isActive());
1997 // We will be switching to another window
1998 assert (windows
.get(0).isActive());
1999 assert (windows
.get(0) == activeWindow
);
2000 assert (!window
.isActive());
2001 activeWindow
.onUnfocus();
2002 activeWindow
.setActive(false);
2003 activeWindow
.setZ(window
.getZ());
2004 activeWindow
= window
;
2006 window
.setActive(true);
2013 // Clicked on the background, nothing to do
2018 * Turn off the menu.
2020 public final void closeMenu() {
2021 if (activeMenu
!= null) {
2022 activeMenu
.setActive(false);
2024 for (TMenu menu
: subMenus
) {
2025 menu
.setActive(false);
2032 * Turn off a sub-menu.
2034 public final void closeSubMenu() {
2035 assert (activeMenu
!= null);
2036 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2037 assert (item
!= null);
2038 item
.setActive(false);
2039 subMenus
.remove(subMenus
.size() - 1);
2043 * Switch to the next menu.
2045 * @param forward if true, then switch to the next menu in the list,
2046 * otherwise switch to the previous menu in the list
2048 public final void switchMenu(final boolean forward
) {
2049 assert (activeMenu
!= null);
2051 for (TMenu menu
: subMenus
) {
2052 menu
.setActive(false);
2056 for (int i
= 0; i
< menus
.size(); i
++) {
2057 if (activeMenu
== menus
.get(i
)) {
2059 if (i
< menus
.size() - 1) {
2067 activeMenu
.setActive(false);
2068 activeMenu
= menus
.get(i
);
2069 activeMenu
.setActive(true);
2076 * Add a menu item to the global list. If it has a keyboard accelerator,
2077 * that will be added the global hash.
2079 * @param item the menu item
2081 public final void addMenuItem(final TMenuItem item
) {
2082 menuItems
.add(item
);
2084 TKeypress key
= item
.getKey();
2086 synchronized (accelerators
) {
2087 assert (accelerators
.get(key
) == null);
2088 accelerators
.put(key
.toLowerCase(), item
);
2094 * Disable one menu item.
2096 * @param id the menu item ID
2098 public final void disableMenuItem(final int id
) {
2099 for (TMenuItem item
: menuItems
) {
2100 if (item
.getId() == id
) {
2101 item
.setEnabled(false);
2107 * Disable the range of menu items with ID's between lower and upper,
2110 * @param lower the lowest menu item ID
2111 * @param upper the highest menu item ID
2113 public final void disableMenuItems(final int lower
, final int upper
) {
2114 for (TMenuItem item
: menuItems
) {
2115 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2116 item
.setEnabled(false);
2122 * Enable one menu item.
2124 * @param id the menu item ID
2126 public final void enableMenuItem(final int id
) {
2127 for (TMenuItem item
: menuItems
) {
2128 if (item
.getId() == id
) {
2129 item
.setEnabled(true);
2135 * Enable the range of menu items with ID's between lower and upper,
2138 * @param lower the lowest menu item ID
2139 * @param upper the highest menu item ID
2141 public final void enableMenuItems(final int lower
, final int upper
) {
2142 for (TMenuItem item
: menuItems
) {
2143 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2144 item
.setEnabled(true);
2150 * Recompute menu x positions based on their title length.
2152 public final void recomputeMenuX() {
2154 for (TMenu menu
: menus
) {
2156 x
+= menu
.getTitle().length() + 2;
2161 * Post an event to process and turn off the menu.
2163 * @param event new event to add to the queue
2165 public final void postMenuEvent(final TInputEvent event
) {
2166 synchronized (fillEventQueue
) {
2167 fillEventQueue
.add(event
);
2173 * Add a sub-menu to the list of open sub-menus.
2175 * @param menu sub-menu
2177 public final void addSubMenu(final TMenu menu
) {
2182 * Convenience function to add a top-level menu.
2184 * @param title menu title
2185 * @return the new menu
2187 public final TMenu
addMenu(final String title
) {
2190 TMenu menu
= new TMenu(this, x
, y
, title
);
2197 * Convenience function to add a default "File" menu.
2199 * @return the new menu
2201 public final TMenu
addFileMenu() {
2202 TMenu fileMenu
= addMenu("&File");
2203 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2204 fileMenu
.addSeparator();
2205 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2206 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2207 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2208 "commands (Open, Save, Print, etc.)");
2209 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2214 * Convenience function to add a default "Edit" menu.
2216 * @return the new menu
2218 public final TMenu
addEditMenu() {
2219 TMenu editMenu
= addMenu("&Edit");
2220 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2221 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2222 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2223 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2224 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2225 "undo, and Clipboard access");
2226 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2231 * Convenience function to add a default "Window" menu.
2233 * @return the new menu
2235 public final TMenu
addWindowMenu() {
2236 TMenu windowMenu
= addMenu("&Window");
2237 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2238 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2239 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2240 windowMenu
.addSeparator();
2241 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2242 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2243 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2244 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2245 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2246 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2248 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2253 * Convenience function to add a default "Help" menu.
2255 * @return the new menu
2257 public final TMenu
addHelpMenu() {
2258 TMenu helpMenu
= addMenu("&Help");
2259 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2260 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2261 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2262 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2263 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2264 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2265 helpMenu
.addSeparator();
2266 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2267 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2268 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2272 // ------------------------------------------------------------------------
2273 // Event handlers ---------------------------------------------------------
2274 // ------------------------------------------------------------------------
2277 * Method that TApplication subclasses can override to handle menu or
2278 * posted command events.
2280 * @param command command event
2281 * @return if true, this event was consumed
2283 protected boolean onCommand(final TCommandEvent command
) {
2284 // Default: handle cmExit
2285 if (command
.equals(cmExit
)) {
2286 if (messageBox("Confirmation", "Exit application?",
2287 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2293 if (command
.equals(cmShell
)) {
2294 openTerminal(0, 0, TWindow
.RESIZABLE
);
2298 if (command
.equals(cmTile
)) {
2302 if (command
.equals(cmCascade
)) {
2306 if (command
.equals(cmCloseAll
)) {
2315 * Method that TApplication subclasses can override to handle menu
2318 * @param menu menu event
2319 * @return if true, this event was consumed
2321 protected boolean onMenu(final TMenuEvent menu
) {
2323 // Default: handle MID_EXIT
2324 if (menu
.getId() == TMenu
.MID_EXIT
) {
2325 if (messageBox("Confirmation", "Exit application?",
2326 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2332 if (menu
.getId() == TMenu
.MID_SHELL
) {
2333 openTerminal(0, 0, TWindow
.RESIZABLE
);
2337 if (menu
.getId() == TMenu
.MID_TILE
) {
2341 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2345 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2349 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2357 * Method that TApplication subclasses can override to handle keystrokes.
2359 * @param keypress keystroke event
2360 * @return if true, this event was consumed
2362 protected boolean onKeypress(final TKeypressEvent keypress
) {
2363 // Default: only menu shortcuts
2365 // Process Alt-F, Alt-E, etc. menu shortcut keys
2366 if (!keypress
.getKey().isFnKey()
2367 && keypress
.getKey().isAlt()
2368 && !keypress
.getKey().isCtrl()
2369 && (activeMenu
== null)
2370 && !modalWindowActive()
2373 assert (subMenus
.size() == 0);
2375 for (TMenu menu
: menus
) {
2376 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2377 == Character
.toLowerCase(keypress
.getKey().getChar())
2380 menu
.setActive(true);
2389 // ------------------------------------------------------------------------
2390 // TTimer management ------------------------------------------------------
2391 // ------------------------------------------------------------------------
2394 * Get the amount of time I can sleep before missing a Timer tick.
2396 * @param timeout = initial (maximum) timeout in millis
2397 * @return number of milliseconds between now and the next timer event
2399 private long getSleepTime(final long timeout
) {
2400 Date now
= new Date();
2401 long nowTime
= now
.getTime();
2402 long sleepTime
= timeout
;
2403 for (TTimer timer
: timers
) {
2404 long nextTickTime
= timer
.getNextTick().getTime();
2405 if (nextTickTime
< nowTime
) {
2409 long timeDifference
= nextTickTime
- nowTime
;
2410 if (timeDifference
< sleepTime
) {
2411 sleepTime
= timeDifference
;
2414 assert (sleepTime
>= 0);
2415 assert (sleepTime
<= timeout
);
2420 * Convenience function to add a timer.
2422 * @param duration number of milliseconds to wait between ticks
2423 * @param recurring if true, re-schedule this timer after every tick
2424 * @param action function to call when button is pressed
2427 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2428 final TAction action
) {
2430 TTimer timer
= new TTimer(duration
, recurring
, action
);
2431 synchronized (timers
) {
2438 * Convenience function to remove a timer.
2440 * @param timer timer to remove
2442 public final void removeTimer(final TTimer timer
) {
2443 synchronized (timers
) {
2444 timers
.remove(timer
);
2448 // ------------------------------------------------------------------------
2449 // Other TWindow constructors ---------------------------------------------
2450 // ------------------------------------------------------------------------
2453 * Convenience function to spawn a message box.
2455 * @param title window title, will be centered along the top border
2456 * @param caption message to display. Use embedded newlines to get a
2458 * @return the new message box
2460 public final TMessageBox
messageBox(final String title
,
2461 final String caption
) {
2463 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2467 * Convenience function to spawn a message box.
2469 * @param title window title, will be centered along the top border
2470 * @param caption message to display. Use embedded newlines to get a
2472 * @param type one of the TMessageBox.Type constants. Default is
2474 * @return the new message box
2476 public final TMessageBox
messageBox(final String title
,
2477 final String caption
, final TMessageBox
.Type type
) {
2479 return new TMessageBox(this, title
, caption
, type
);
2483 * Convenience function to spawn an input box.
2485 * @param title window title, will be centered along the top border
2486 * @param caption message to display. Use embedded newlines to get a
2488 * @return the new input box
2490 public final TInputBox
inputBox(final String title
, final String caption
) {
2492 return new TInputBox(this, title
, caption
);
2496 * Convenience function to spawn an input box.
2498 * @param title window title, will be centered along the top border
2499 * @param caption message to display. Use embedded newlines to get a
2501 * @param text initial text to seed the field with
2502 * @return the new input box
2504 public final TInputBox
inputBox(final String title
, final String caption
,
2505 final String text
) {
2507 return new TInputBox(this, title
, caption
, text
);
2511 * Convenience function to open a terminal window.
2513 * @param x column relative to parent
2514 * @param y row relative to parent
2515 * @return the terminal new window
2517 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2518 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2522 * Convenience function to open a terminal window.
2524 * @param x column relative to parent
2525 * @param y row relative to parent
2526 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2527 * @return the terminal new window
2529 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2532 return new TTerminalWindow(this, x
, y
, flags
);
2536 * Convenience function to spawn an file open box.
2538 * @param path path of selected file
2539 * @return the result of the new file open box
2540 * @throws IOException if java.io operation throws
2542 public final String
fileOpenBox(final String path
) throws IOException
{
2544 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2545 return box
.getFilename();
2549 * Convenience function to spawn an file open box.
2551 * @param path path of selected file
2552 * @param type one of the Type constants
2553 * @return the result of the new file open box
2554 * @throws IOException if java.io operation throws
2556 public final String
fileOpenBox(final String path
,
2557 final TFileOpenBox
.Type type
) throws IOException
{
2559 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2560 return box
.getFilename();
2564 * Convenience function to create a new window and make it active.
2565 * Window will be located at (0, 0).
2567 * @param title window title, will be centered along the top border
2568 * @param width width of window
2569 * @param height height of window
2571 public final TWindow
addWindow(final String title
, final int width
,
2574 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2578 * Convenience function to create a new window and make it active.
2579 * Window will be located at (0, 0).
2581 * @param title window title, will be centered along the top border
2582 * @param width width of window
2583 * @param height height of window
2584 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2586 public final TWindow
addWindow(final String title
,
2587 final int width
, final int height
, final int flags
) {
2589 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2594 * Convenience function to create a new window and make it active.
2596 * @param title window title, will be centered along the top border
2597 * @param x column relative to parent
2598 * @param y row relative to parent
2599 * @param width width of window
2600 * @param height height of window
2602 public final TWindow
addWindow(final String title
,
2603 final int x
, final int y
, final int width
, final int height
) {
2605 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2610 * Convenience function to create a new window and make it active.
2612 * @param title window title, will be centered along the top border
2613 * @param x column relative to parent
2614 * @param y row relative to parent
2615 * @param width width of window
2616 * @param height height of window
2617 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2619 public final TWindow
addWindow(final String title
,
2620 final int x
, final int y
, final int width
, final int height
,
2623 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);