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 acive 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 * Timers that are being ticked.
488 private List
<TTimer
> timers
;
491 * When true, exit the application.
493 private volatile boolean quit
= false;
496 * When true, repaint the entire screen.
498 private volatile boolean repaint
= true;
501 * Y coordinate of the top edge of the desktop. For now this is a
502 * constant. Someday it would be nice to have a multi-line menu or
505 private static final int desktopTop
= 1;
508 * Get Y coordinate of the top edge of the desktop.
510 * @return Y coordinate of the top edge of the desktop
512 public final int getDesktopTop() {
517 * Y coordinate of the bottom edge of the desktop.
519 private int desktopBottom
;
522 * Get Y coordinate of the bottom edge of the desktop.
524 * @return Y coordinate of the bottom edge of the desktop
526 public final int getDesktopBottom() {
527 return desktopBottom
;
531 * An optional TDesktop background window that is drawn underneath
534 private TDesktop desktop
;
537 * Set the TDesktop instance.
539 * @param desktop a TDesktop instance, or null to remove the one that is
542 public final void setDesktop(final TDesktop desktop
) {
543 if (this.desktop
!= null) {
544 this.desktop
.onClose();
546 this.desktop
= desktop
;
550 * Get the TDesktop instance.
552 * @return the desktop, or null if it is not set
554 public final TDesktop
getDesktop() {
558 // ------------------------------------------------------------------------
559 // General behavior -------------------------------------------------------
560 // ------------------------------------------------------------------------
563 * Display the about dialog.
565 protected void showAboutDialog() {
566 messageBox("About", "Jexer Version " +
567 this.getClass().getPackage().getImplementationVersion(),
568 TMessageBox
.Type
.OK
);
571 // ------------------------------------------------------------------------
572 // Constructors -----------------------------------------------------------
573 // ------------------------------------------------------------------------
576 * Public constructor.
578 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
580 * @throws UnsupportedEncodingException if an exception is thrown when
581 * creating the InputStreamReader
583 public TApplication(final BackendType backendType
)
584 throws UnsupportedEncodingException
{
586 switch (backendType
) {
588 backend
= new SwingBackend(this);
593 backend
= new ECMA48Backend(this, null, null);
596 throw new IllegalArgumentException("Invalid backend type: "
603 * Public constructor. The backend type will be BackendType.ECMA48.
605 * @param input an InputStream connected to the remote user, or null for
606 * System.in. If System.in is used, then on non-Windows systems it will
607 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
608 * mode. input is always converted to a Reader with UTF-8 encoding.
609 * @param output an OutputStream connected to the remote user, or null
610 * for System.out. output is always converted to a Writer with UTF-8
612 * @throws UnsupportedEncodingException if an exception is thrown when
613 * creating the InputStreamReader
615 public TApplication(final InputStream input
,
616 final OutputStream output
) throws UnsupportedEncodingException
{
618 backend
= new ECMA48Backend(this, input
, output
);
623 * Public constructor. The backend type will be BackendType.ECMA48.
625 * @param input the InputStream underlying 'reader'. Its available()
626 * method is used to determine if reader.read() will block or not.
627 * @param reader a Reader connected to the remote user.
628 * @param writer a PrintWriter connected to the remote user.
629 * @param setRawMode if true, set System.in into raw mode with stty.
630 * This should in general not be used. It is here solely for Demo3,
631 * which uses System.in.
632 * @throws IllegalArgumentException if input, reader, or writer are null.
634 public TApplication(final InputStream input
, final Reader reader
,
635 final PrintWriter writer
, final boolean setRawMode
) {
637 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
642 * Public constructor. The backend type will be BackendType.ECMA48.
644 * @param input the InputStream underlying 'reader'. Its available()
645 * method is used to determine if reader.read() will block or not.
646 * @param reader a Reader connected to the remote user.
647 * @param writer a PrintWriter connected to the remote user.
648 * @throws IllegalArgumentException if input, reader, or writer are null.
650 public TApplication(final InputStream input
, final Reader reader
,
651 final PrintWriter writer
) {
653 this(input
, reader
, writer
, false);
657 * Public constructor. This hook enables use with new non-Jexer
660 * @param backend a Backend that is already ready to go.
662 public TApplication(final Backend backend
) {
663 this.backend
= backend
;
668 * Finish construction once the backend is set.
670 private void TApplicationImpl() {
671 theme
= new ColorTheme();
672 desktopBottom
= getScreen().getHeight() - 1;
673 fillEventQueue
= new ArrayList
<TInputEvent
>();
674 drainEventQueue
= new ArrayList
<TInputEvent
>();
675 windows
= new LinkedList
<TWindow
>();
676 menus
= new LinkedList
<TMenu
>();
677 subMenus
= new LinkedList
<TMenu
>();
678 timers
= new LinkedList
<TTimer
>();
679 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
680 menuItems
= new ArrayList
<TMenuItem
>();
681 desktop
= new TDesktop(this);
683 // Setup the main consumer thread
684 primaryEventHandler
= new WidgetEventHandler(this, true);
685 (new Thread(primaryEventHandler
)).start();
688 // ------------------------------------------------------------------------
689 // Screen refresh loop ----------------------------------------------------
690 // ------------------------------------------------------------------------
693 * Invert the cell color at a position. This is used to track the mouse.
695 * @param x column position
696 * @param y row position
698 private void invertCell(final int x
, final int y
) {
700 System
.err
.printf("invertCell() %d %d\n", x
, y
);
702 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
703 attr
.setForeColor(attr
.getForeColor().invert());
704 attr
.setBackColor(attr
.getBackColor().invert());
705 getScreen().putAttrXY(x
, y
, attr
, false);
711 private void drawAll() {
713 System
.err
.printf("drawAll() enter\n");
718 System
.err
.printf("drawAll() !repaint\n");
720 synchronized (getScreen()) {
721 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
722 // The only thing that has happened is the mouse moved.
723 // Clear the old position and draw the new position.
724 invertCell(oldMouseX
, oldMouseY
);
725 invertCell(mouseX
, mouseY
);
729 if (getScreen().isDirty()) {
730 backend
.flushScreen();
737 System
.err
.printf("drawAll() REDRAW\n");
740 // If true, the cursor is not visible
741 boolean cursor
= false;
743 // Start with a clean screen
747 if (desktop
!= null) {
748 desktop
.drawChildren();
751 // Draw each window in reverse Z order
752 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
753 Collections
.sort(sorted
);
754 TWindow topLevel
= null;
755 if (sorted
.size() > 0) {
756 topLevel
= sorted
.get(0);
758 Collections
.reverse(sorted
);
759 for (TWindow window
: sorted
) {
760 window
.drawChildren();
763 // Draw the blank menubar line - reset the screen clipping first so
764 // it won't trim it out.
765 getScreen().resetClipping();
766 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
767 theme
.getColor("tmenu"));
768 // Now draw the menus.
770 for (TMenu menu
: menus
) {
771 CellAttributes menuColor
;
772 CellAttributes menuMnemonicColor
;
773 if (menu
.isActive()) {
774 menuColor
= theme
.getColor("tmenu.highlighted");
775 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
778 menuColor
= theme
.getColor("tmenu");
779 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
781 // Draw the menu title
782 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
784 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
785 // Draw the highlight character
786 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
787 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
789 if (menu
.isActive()) {
791 // Reset the screen clipping so we can draw the next title.
792 getScreen().resetClipping();
794 x
+= menu
.getTitle().length() + 2;
797 for (TMenu menu
: subMenus
) {
798 // Reset the screen clipping so we can draw the next sub-menu.
799 getScreen().resetClipping();
803 // Draw the status bar of the top-level window
804 TStatusBar statusBar
= null;
805 if (topLevel
!= null) {
806 statusBar
= topLevel
.getStatusBar();
808 if (statusBar
!= null) {
809 getScreen().resetClipping();
810 statusBar
.setWidth(getScreen().getWidth());
811 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
814 CellAttributes barColor
= new CellAttributes();
815 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
816 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
820 // Draw the mouse pointer
821 invertCell(mouseX
, mouseY
);
825 // Place the cursor if it is visible
826 TWidget activeWidget
= null;
827 if (sorted
.size() > 0) {
828 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
829 if (activeWidget
.isCursorVisible()) {
830 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
831 activeWidget
.getCursorAbsoluteY());
838 getScreen().hideCursor();
841 // Flush the screen contents
842 if (getScreen().isDirty()) {
843 backend
.flushScreen();
849 // ------------------------------------------------------------------------
850 // Main loop --------------------------------------------------------------
851 // ------------------------------------------------------------------------
854 * Run this application until it exits.
858 // Timeout is in milliseconds, so default timeout after 1 second
862 // If I've got no updates to render, wait for something from the
863 // backend or a timer.
865 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
867 // Never sleep longer than 50 millis. We need time for
868 // windows with background tasks to update the display, and
869 // still flip buffers reasonably quickly in
870 // backend.flushPhysical().
871 timeout
= getSleepTime(50);
875 // As of now, I've got nothing to do: no I/O, nothing from
876 // the consumer threads, no timers that need to run ASAP. So
877 // wait until either the backend or the consumer threads have
881 System
.err
.println("sleep " + timeout
+ " millis");
883 synchronized (this) {
886 } catch (InterruptedException e
) {
887 // I'm awake and don't care why, let's see what's going
893 // Prevent stepping on the primary or secondary event handler.
896 // Pull any pending I/O events
897 backend
.getEvents(fillEventQueue
);
899 // Dispatch each event to the appropriate handler, one at a time.
901 TInputEvent event
= null;
902 if (fillEventQueue
.size() == 0) {
905 event
= fillEventQueue
.remove(0);
906 metaHandleEvent(event
);
909 // Wake a consumer thread if we have any pending events.
910 if (drainEventQueue
.size() > 0) {
914 // Process timers and call doIdle()'s
918 synchronized (getScreen()) {
922 // Let the event handlers run again.
923 startEventHandlers();
927 // Shutdown the event consumer threads
928 if (secondaryEventHandler
!= null) {
929 synchronized (secondaryEventHandler
) {
930 secondaryEventHandler
.notify();
933 if (primaryEventHandler
!= null) {
934 synchronized (primaryEventHandler
) {
935 primaryEventHandler
.notify();
939 // Shutdown the user I/O thread(s)
942 // Close all the windows. This gives them an opportunity to release
949 * Peek at certain application-level events, add to eventQueue, and wake
950 * up the consuming Thread.
952 * @param event the input event to consume
954 private void metaHandleEvent(final TInputEvent event
) {
957 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
958 event
)); System
.err
.flush();
962 // Do no more processing if the application is already trying
967 // Special application-wide events -------------------------------
970 if (event
instanceof TCommandEvent
) {
971 TCommandEvent command
= (TCommandEvent
) event
;
972 if (command
.getCmd().equals(cmAbort
)) {
979 if (event
instanceof TResizeEvent
) {
980 TResizeEvent resize
= (TResizeEvent
) event
;
981 synchronized (getScreen()) {
982 getScreen().setDimensions(resize
.getWidth(),
984 desktopBottom
= getScreen().getHeight() - 1;
990 if (desktop
!= null) {
991 desktop
.setDimensions(0, 0, resize
.getWidth(),
992 resize
.getHeight() - 1);
997 // Peek at the mouse position
998 if (event
instanceof TMouseEvent
) {
999 TMouseEvent mouse
= (TMouseEvent
) event
;
1000 synchronized (getScreen()) {
1001 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1004 mouseX
= mouse
.getX();
1005 mouseY
= mouse
.getY();
1010 // Put into the main queue
1011 drainEventQueue
.add(event
);
1015 * Dispatch one event to the appropriate widget or application-level
1016 * event handler. This is the primary event handler, it has the normal
1017 * application-wide event handling.
1019 * @param event the input event to consume
1020 * @see #secondaryHandleEvent(TInputEvent event)
1022 private void primaryHandleEvent(final TInputEvent event
) {
1025 System
.err
.printf("Handle event: %s\n", event
);
1028 // Special application-wide events -----------------------------------
1030 // Peek at the mouse position
1031 if (event
instanceof TMouseEvent
) {
1032 // See if we need to switch focus to another window or the menu
1033 checkSwitchFocus((TMouseEvent
) event
);
1036 // Handle menu events
1037 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1038 TMenu menu
= activeMenu
;
1040 if (event
instanceof TMouseEvent
) {
1041 TMouseEvent mouse
= (TMouseEvent
) event
;
1043 while (subMenus
.size() > 0) {
1044 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1045 if (subMenu
.mouseWouldHit(mouse
)) {
1048 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1049 && (!mouse
.isMouse1())
1050 && (!mouse
.isMouse2())
1051 && (!mouse
.isMouse3())
1052 && (!mouse
.isMouseWheelUp())
1053 && (!mouse
.isMouseWheelDown())
1057 // We navigated away from a sub-menu, so close it
1061 // Convert the mouse relative x/y to menu coordinates
1062 assert (mouse
.getX() == mouse
.getAbsoluteX());
1063 assert (mouse
.getY() == mouse
.getAbsoluteY());
1064 if (subMenus
.size() > 0) {
1065 menu
= subMenus
.get(subMenus
.size() - 1);
1067 mouse
.setX(mouse
.getX() - menu
.getX());
1068 mouse
.setY(mouse
.getY() - menu
.getY());
1070 menu
.handleEvent(event
);
1074 if (event
instanceof TKeypressEvent
) {
1075 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1077 // See if this key matches an accelerator, and is not being
1078 // shortcutted by the active window, and if so dispatch the menu
1080 boolean windowWillShortcut
= false;
1081 for (TWindow window
: windows
) {
1082 if (window
.isActive()) {
1083 if (window
.isShortcutKeypress(keypress
.getKey())) {
1084 // We do not process this key, it will be passed to
1085 // the window instead.
1086 windowWillShortcut
= true;
1091 if (!windowWillShortcut
&& !modalWindowActive()) {
1092 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1093 TMenuItem item
= null;
1094 synchronized (accelerators
) {
1095 item
= accelerators
.get(keypressLowercase
);
1098 if (item
.isEnabled()) {
1099 // Let the menu item dispatch
1105 // Handle the keypress
1106 if (onKeypress(keypress
)) {
1112 if (event
instanceof TCommandEvent
) {
1113 if (onCommand((TCommandEvent
) event
)) {
1118 if (event
instanceof TMenuEvent
) {
1119 if (onMenu((TMenuEvent
) event
)) {
1124 // Dispatch events to the active window -------------------------------
1125 boolean dispatchToDesktop
= true;
1126 for (TWindow window
: windows
) {
1127 if (window
.isActive()) {
1128 if (event
instanceof TMouseEvent
) {
1129 TMouseEvent mouse
= (TMouseEvent
) event
;
1130 // Convert the mouse relative x/y to window coordinates
1131 assert (mouse
.getX() == mouse
.getAbsoluteX());
1132 assert (mouse
.getY() == mouse
.getAbsoluteY());
1133 mouse
.setX(mouse
.getX() - window
.getX());
1134 mouse
.setY(mouse
.getY() - window
.getY());
1136 if (window
.mouseWouldHit(mouse
)) {
1137 dispatchToDesktop
= false;
1139 } else if (event
instanceof TKeypressEvent
) {
1140 dispatchToDesktop
= false;
1144 System
.err
.printf("TApplication dispatch event: %s\n",
1147 window
.handleEvent(event
);
1151 if (dispatchToDesktop
) {
1152 // This event is fair game for the desktop to process.
1153 if (desktop
!= null) {
1154 desktop
.handleEvent(event
);
1160 * Dispatch one event to the appropriate widget or application-level
1161 * event handler. This is the secondary event handler used by certain
1162 * special dialogs (currently TMessageBox and TFileOpenBox).
1164 * @param event the input event to consume
1165 * @see #primaryHandleEvent(TInputEvent event)
1167 private void secondaryHandleEvent(final TInputEvent event
) {
1168 secondaryEventReceiver
.handleEvent(event
);
1172 * Enable a widget to override the primary event thread.
1174 * @param widget widget that will receive events
1176 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1177 assert (secondaryEventReceiver
== null);
1178 assert (secondaryEventHandler
== null);
1179 assert ((widget
instanceof TMessageBox
)
1180 || (widget
instanceof TFileOpenBox
));
1181 secondaryEventReceiver
= widget
;
1182 secondaryEventHandler
= new WidgetEventHandler(this, false);
1183 (new Thread(secondaryEventHandler
)).start();
1187 * Yield to the secondary thread.
1189 public final void yield() {
1190 assert (secondaryEventReceiver
!= null);
1191 // This is where we handoff the event handler lock from the primary
1192 // to secondary thread. We unlock here, and in a future loop the
1193 // secondary thread locks again. When it gives up, we have the
1194 // single lock back.
1195 boolean oldLock
= unlockHandleEvent();
1198 while (secondaryEventReceiver
!= null) {
1199 synchronized (primaryEventHandler
) {
1201 primaryEventHandler
.wait();
1202 } catch (InterruptedException e
) {
1210 * Do stuff when there is no user input.
1212 private void doIdle() {
1214 System
.err
.printf("doIdle()\n");
1217 // Now run any timers that have timed out
1218 Date now
= new Date();
1219 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1220 for (TTimer timer
: timers
) {
1221 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1223 if (timer
.recurring
) {
1224 keepTimers
.add(timer
);
1227 keepTimers
.add(timer
);
1230 timers
= keepTimers
;
1233 for (TWindow window
: windows
) {
1238 // ------------------------------------------------------------------------
1239 // TWindow management -----------------------------------------------------
1240 // ------------------------------------------------------------------------
1243 * Close window. Note that the window's destructor is NOT called by this
1244 * method, instead the GC is assumed to do the cleanup.
1246 * @param window the window to remove
1248 public final void closeWindow(final TWindow window
) {
1249 synchronized (windows
) {
1250 int z
= window
.getZ();
1253 Collections
.sort(windows
);
1255 TWindow activeWindow
= null;
1256 for (TWindow w
: windows
) {
1258 w
.setZ(w
.getZ() - 1);
1259 if (w
.getZ() == 0) {
1262 assert (activeWindow
== null);
1274 // Perform window cleanup
1277 // Check if we are closing a TMessageBox or similar
1278 if (secondaryEventReceiver
!= null) {
1279 assert (secondaryEventHandler
!= null);
1281 // Do not send events to the secondaryEventReceiver anymore, the
1282 // window is closed.
1283 secondaryEventReceiver
= null;
1285 // Wake the secondary thread, it will wake the primary as it
1287 synchronized (secondaryEventHandler
) {
1288 secondaryEventHandler
.notify();
1294 * Switch to the next window.
1296 * @param forward if true, then switch to the next window in the list,
1297 * otherwise switch to the previous window in the list
1299 public final void switchWindow(final boolean forward
) {
1300 // Only switch if there are multiple windows
1301 if (windows
.size() < 2) {
1305 synchronized (windows
) {
1307 // Swap z/active between active window and the next in the list
1308 int activeWindowI
= -1;
1309 for (int i
= 0; i
< windows
.size(); i
++) {
1310 if (windows
.get(i
).isActive()) {
1315 assert (activeWindowI
>= 0);
1317 // Do not switch if a window is modal
1318 if (windows
.get(activeWindowI
).isModal()) {
1324 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1326 if (activeWindowI
== 0) {
1327 nextWindowI
= windows
.size() - 1;
1329 nextWindowI
= activeWindowI
- 1;
1332 windows
.get(activeWindowI
).setActive(false);
1333 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1334 windows
.get(activeWindowI
).onUnfocus();
1335 windows
.get(nextWindowI
).setZ(0);
1336 windows
.get(nextWindowI
).setActive(true);
1337 windows
.get(nextWindowI
).onFocus();
1339 } // synchronized (windows)
1344 * Add a window to my window list and make it active.
1346 * @param window new window to add
1348 public final void addWindow(final TWindow window
) {
1350 // Do not add menu windows to the window list.
1351 if (window
instanceof TMenu
) {
1355 // Do not add the desktop to the window list.
1356 if (window
instanceof TDesktop
) {
1360 synchronized (windows
) {
1361 // Do not allow a modal window to spawn a non-modal window. If a
1362 // modal window is active, then this window will become modal
1364 if (modalWindowActive()) {
1365 window
.flags
|= TWindow
.MODAL
;
1366 window
.flags
|= TWindow
.CENTERED
;
1368 for (TWindow w
: windows
) {
1373 w
.setZ(w
.getZ() + 1);
1375 windows
.add(window
);
1377 window
.setActive(true);
1380 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1381 && smartWindowPlacement
) {
1383 doSmartPlacement(window
);
1389 * Check if there is a system-modal window on top.
1391 * @return true if the active window is modal
1393 private boolean modalWindowActive() {
1394 if (windows
.size() == 0) {
1398 for (TWindow w
: windows
) {
1408 * Close all open windows.
1410 private void closeAllWindows() {
1411 // Don't do anything if we are in the menu
1412 if (activeMenu
!= null) {
1415 while (windows
.size() > 0) {
1416 closeWindow(windows
.get(0));
1421 * Re-layout the open windows as non-overlapping tiles. This produces
1422 * almost the same results as Turbo Pascal 7.0's IDE.
1424 private void tileWindows() {
1425 synchronized (windows
) {
1426 // Don't do anything if we are in the menu
1427 if (activeMenu
!= null) {
1430 int z
= windows
.size();
1436 a
= (int)(Math
.sqrt(z
));
1440 if (((a
* b
) + c
) == z
) {
1448 int newWidth
= (getScreen().getWidth() / a
);
1449 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1450 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1452 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1453 Collections
.sort(sorted
);
1454 Collections
.reverse(sorted
);
1455 for (int i
= 0; i
< sorted
.size(); i
++) {
1456 int logicalX
= i
/ b
;
1457 int logicalY
= i
% b
;
1458 if (i
>= ((a
- 1) * b
)) {
1460 logicalY
= i
- ((a
- 1) * b
);
1463 TWindow w
= sorted
.get(i
);
1464 w
.setX(logicalX
* newWidth
);
1465 w
.setWidth(newWidth
);
1466 if (i
>= ((a
- 1) * b
)) {
1467 w
.setY((logicalY
* newHeight2
) + 1);
1468 w
.setHeight(newHeight2
);
1470 w
.setY((logicalY
* newHeight1
) + 1);
1471 w
.setHeight(newHeight1
);
1478 * Re-layout the open windows as overlapping cascaded windows.
1480 private void cascadeWindows() {
1481 synchronized (windows
) {
1482 // Don't do anything if we are in the menu
1483 if (activeMenu
!= null) {
1488 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1489 Collections
.sort(sorted
);
1490 Collections
.reverse(sorted
);
1491 for (TWindow window
: sorted
) {
1496 if (x
> getScreen().getWidth()) {
1499 if (y
>= getScreen().getHeight()) {
1507 * Place a window to minimize its overlap with other windows.
1509 * @param window the window to place
1511 public final void doSmartPlacement(final TWindow window
) {
1512 // This is a pretty dumb algorithm, but seems to work. The hardest
1513 // part is computing these "overlap" values seeking a minimum average
1516 int yMin
= desktopTop
;
1517 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1518 int yMax
= desktopBottom
- window
.getHeight() + 1;
1526 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1527 // No work to do, bail out.
1531 // Compute the overlap matrix without the new window.
1532 int width
= getScreen().getWidth();
1533 int height
= getScreen().getHeight();
1534 int overlapMatrix
[][] = new int[width
][height
];
1535 for (TWindow w
: windows
) {
1539 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1543 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1547 overlapMatrix
[x
][y
]++;
1552 long oldOverlapTotal
= 0;
1553 long oldOverlapN
= 0;
1554 for (int x
= 0; x
< width
; x
++) {
1555 for (int y
= 0; y
< height
; y
++) {
1556 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1557 if (overlapMatrix
[x
][y
] > 0) {
1564 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1565 boolean first
= true;
1566 int windowX
= window
.getX();
1567 int windowY
= window
.getY();
1569 // For each possible (x, y) position for the new window, compute a
1570 // new overlap matrix.
1571 for (int x
= xMin
; x
< xMax
; x
++) {
1572 for (int y
= yMin
; y
< yMax
; y
++) {
1574 // Start with the matrix minus this window.
1575 int newMatrix
[][] = new int[width
][height
];
1576 for (int mx
= 0; mx
< width
; mx
++) {
1577 for (int my
= 0; my
< height
; my
++) {
1578 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1582 // Add this window's values to the new overlap matrix.
1583 long newOverlapTotal
= 0;
1584 long newOverlapN
= 0;
1585 // Start by adding each new cell.
1586 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1590 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1594 newMatrix
[wx
][wy
]++;
1597 // Now figure out the new value for total coverage.
1598 for (int mx
= 0; mx
< width
; mx
++) {
1599 for (int my
= 0; my
< height
; my
++) {
1600 newOverlapTotal
+= newMatrix
[x
][y
];
1601 if (newMatrix
[mx
][my
] > 0) {
1606 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1609 // First time: just record what we got.
1610 oldOverlapAvg
= newOverlapAvg
;
1613 // All other times: pick a new best (x, y) and save the
1615 if (newOverlapAvg
< oldOverlapAvg
) {
1618 oldOverlapAvg
= newOverlapAvg
;
1622 } // for (int x = xMin; x < xMax; x++)
1624 } // for (int y = yMin; y < yMax; y++)
1626 // Finally, set the window's new coordinates.
1627 window
.setX(windowX
);
1628 window
.setY(windowY
);
1631 // ------------------------------------------------------------------------
1632 // TMenu management -------------------------------------------------------
1633 // ------------------------------------------------------------------------
1636 * Check if a mouse event would hit either the active menu or any open
1639 * @param mouse mouse event
1640 * @return true if the mouse would hit the active menu or an open
1643 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1644 assert (activeMenu
!= null);
1645 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1646 Collections
.reverse(menus
);
1647 for (TMenu menu
: menus
) {
1648 if (menu
.mouseWouldHit(mouse
)) {
1652 return activeMenu
.mouseWouldHit(mouse
);
1656 * See if we need to switch window or activate the menu based on
1659 * @param mouse mouse event
1661 private void checkSwitchFocus(final TMouseEvent mouse
) {
1663 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1664 && (activeMenu
!= null)
1665 && (mouse
.getAbsoluteY() != 0)
1666 && (!mouseOnMenu(mouse
))
1668 // They clicked outside the active menu, turn it off
1669 activeMenu
.setActive(false);
1671 for (TMenu menu
: subMenus
) {
1672 menu
.setActive(false);
1678 // See if they hit the menu bar
1679 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1680 && (mouse
.isMouse1())
1681 && (!modalWindowActive())
1682 && (mouse
.getAbsoluteY() == 0)
1685 for (TMenu menu
: subMenus
) {
1686 menu
.setActive(false);
1690 // They selected the menu, go activate it
1691 for (TMenu menu
: menus
) {
1692 if ((mouse
.getAbsoluteX() >= menu
.getX())
1693 && (mouse
.getAbsoluteX() < menu
.getX()
1694 + menu
.getTitle().length() + 2)
1696 menu
.setActive(true);
1699 menu
.setActive(false);
1705 // See if they hit the menu bar
1706 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1707 && (mouse
.isMouse1())
1708 && (activeMenu
!= null)
1709 && (mouse
.getAbsoluteY() == 0)
1712 TMenu oldMenu
= activeMenu
;
1713 for (TMenu menu
: subMenus
) {
1714 menu
.setActive(false);
1718 // See if we should switch menus
1719 for (TMenu menu
: menus
) {
1720 if ((mouse
.getAbsoluteX() >= menu
.getX())
1721 && (mouse
.getAbsoluteX() < menu
.getX()
1722 + menu
.getTitle().length() + 2)
1724 menu
.setActive(true);
1728 if (oldMenu
!= activeMenu
) {
1729 // They switched menus
1730 oldMenu
.setActive(false);
1735 // Only switch if there are multiple windows
1736 if (windows
.size() < 2) {
1740 // Switch on the upclick
1741 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1745 synchronized (windows
) {
1746 Collections
.sort(windows
);
1747 if (windows
.get(0).isModal()) {
1748 // Modal windows don't switch
1752 for (TWindow window
: windows
) {
1753 assert (!window
.isModal());
1754 if (window
.mouseWouldHit(mouse
)) {
1755 if (window
== windows
.get(0)) {
1756 // Clicked on the same window, nothing to do
1760 // We will be switching to another window
1761 assert (windows
.get(0).isActive());
1762 assert (!window
.isActive());
1763 windows
.get(0).onUnfocus();
1764 windows
.get(0).setActive(false);
1765 windows
.get(0).setZ(window
.getZ());
1767 window
.setActive(true);
1774 // Clicked on the background, nothing to do
1779 * Turn off the menu.
1781 public final void closeMenu() {
1782 if (activeMenu
!= null) {
1783 activeMenu
.setActive(false);
1785 for (TMenu menu
: subMenus
) {
1786 menu
.setActive(false);
1793 * Turn off a sub-menu.
1795 public final void closeSubMenu() {
1796 assert (activeMenu
!= null);
1797 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1798 assert (item
!= null);
1799 item
.setActive(false);
1800 subMenus
.remove(subMenus
.size() - 1);
1804 * Switch to the next menu.
1806 * @param forward if true, then switch to the next menu in the list,
1807 * otherwise switch to the previous menu in the list
1809 public final void switchMenu(final boolean forward
) {
1810 assert (activeMenu
!= null);
1812 for (TMenu menu
: subMenus
) {
1813 menu
.setActive(false);
1817 for (int i
= 0; i
< menus
.size(); i
++) {
1818 if (activeMenu
== menus
.get(i
)) {
1820 if (i
< menus
.size() - 1) {
1828 activeMenu
.setActive(false);
1829 activeMenu
= menus
.get(i
);
1830 activeMenu
.setActive(true);
1837 * Add a menu item to the global list. If it has a keyboard accelerator,
1838 * that will be added the global hash.
1840 * @param item the menu item
1842 public final void addMenuItem(final TMenuItem item
) {
1843 menuItems
.add(item
);
1845 TKeypress key
= item
.getKey();
1847 synchronized (accelerators
) {
1848 assert (accelerators
.get(key
) == null);
1849 accelerators
.put(key
.toLowerCase(), item
);
1855 * Disable one menu item.
1857 * @param id the menu item ID
1859 public final void disableMenuItem(final int id
) {
1860 for (TMenuItem item
: menuItems
) {
1861 if (item
.getId() == id
) {
1862 item
.setEnabled(false);
1868 * Disable the range of menu items with ID's between lower and upper,
1871 * @param lower the lowest menu item ID
1872 * @param upper the highest menu item ID
1874 public final void disableMenuItems(final int lower
, final int upper
) {
1875 for (TMenuItem item
: menuItems
) {
1876 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1877 item
.setEnabled(false);
1883 * Enable one menu item.
1885 * @param id the menu item ID
1887 public final void enableMenuItem(final int id
) {
1888 for (TMenuItem item
: menuItems
) {
1889 if (item
.getId() == id
) {
1890 item
.setEnabled(true);
1896 * Enable the range of menu items with ID's between lower and upper,
1899 * @param lower the lowest menu item ID
1900 * @param upper the highest menu item ID
1902 public final void enableMenuItems(final int lower
, final int upper
) {
1903 for (TMenuItem item
: menuItems
) {
1904 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1905 item
.setEnabled(true);
1911 * Recompute menu x positions based on their title length.
1913 public final void recomputeMenuX() {
1915 for (TMenu menu
: menus
) {
1917 x
+= menu
.getTitle().length() + 2;
1922 * Post an event to process and turn off the menu.
1924 * @param event new event to add to the queue
1926 public final void postMenuEvent(final TInputEvent event
) {
1927 synchronized (fillEventQueue
) {
1928 fillEventQueue
.add(event
);
1934 * Add a sub-menu to the list of open sub-menus.
1936 * @param menu sub-menu
1938 public final void addSubMenu(final TMenu menu
) {
1943 * Convenience function to add a top-level menu.
1945 * @param title menu title
1946 * @return the new menu
1948 public final TMenu
addMenu(final String title
) {
1951 TMenu menu
= new TMenu(this, x
, y
, title
);
1958 * Convenience function to add a default "File" menu.
1960 * @return the new menu
1962 public final TMenu
addFileMenu() {
1963 TMenu fileMenu
= addMenu("&File");
1964 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1965 fileMenu
.addSeparator();
1966 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1967 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1968 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
1969 "commands (Open, Save, Print, etc.)");
1970 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1975 * Convenience function to add a default "Edit" menu.
1977 * @return the new menu
1979 public final TMenu
addEditMenu() {
1980 TMenu editMenu
= addMenu("&Edit");
1981 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1982 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1983 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1984 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1985 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
1986 "undo, and Clipboard access");
1987 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1992 * Convenience function to add a default "Window" menu.
1994 * @return the new menu
1996 public final TMenu
addWindowMenu() {
1997 TMenu windowMenu
= addMenu("&Window");
1998 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1999 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2000 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2001 windowMenu
.addSeparator();
2002 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2003 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2004 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2005 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2006 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2007 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2009 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2014 * Convenience function to add a default "Help" menu.
2016 * @return the new menu
2018 public final TMenu
addHelpMenu() {
2019 TMenu helpMenu
= addMenu("&Help");
2020 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2021 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2022 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2023 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2024 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2025 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2026 helpMenu
.addSeparator();
2027 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2028 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2029 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2033 // ------------------------------------------------------------------------
2034 // Event handlers ---------------------------------------------------------
2035 // ------------------------------------------------------------------------
2038 * Method that TApplication subclasses can override to handle menu or
2039 * posted command events.
2041 * @param command command event
2042 * @return if true, this event was consumed
2044 protected boolean onCommand(final TCommandEvent command
) {
2045 // Default: handle cmExit
2046 if (command
.equals(cmExit
)) {
2047 if (messageBox("Confirmation", "Exit application?",
2048 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2054 if (command
.equals(cmShell
)) {
2055 openTerminal(0, 0, TWindow
.RESIZABLE
);
2059 if (command
.equals(cmTile
)) {
2063 if (command
.equals(cmCascade
)) {
2067 if (command
.equals(cmCloseAll
)) {
2076 * Method that TApplication subclasses can override to handle menu
2079 * @param menu menu event
2080 * @return if true, this event was consumed
2082 protected boolean onMenu(final TMenuEvent menu
) {
2084 // Default: handle MID_EXIT
2085 if (menu
.getId() == TMenu
.MID_EXIT
) {
2086 if (messageBox("Confirmation", "Exit application?",
2087 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2093 if (menu
.getId() == TMenu
.MID_SHELL
) {
2094 openTerminal(0, 0, TWindow
.RESIZABLE
);
2098 if (menu
.getId() == TMenu
.MID_TILE
) {
2102 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2106 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2110 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2118 * Method that TApplication subclasses can override to handle keystrokes.
2120 * @param keypress keystroke event
2121 * @return if true, this event was consumed
2123 protected boolean onKeypress(final TKeypressEvent keypress
) {
2124 // Default: only menu shortcuts
2126 // Process Alt-F, Alt-E, etc. menu shortcut keys
2127 if (!keypress
.getKey().isFnKey()
2128 && keypress
.getKey().isAlt()
2129 && !keypress
.getKey().isCtrl()
2130 && (activeMenu
== null)
2131 && !modalWindowActive()
2134 assert (subMenus
.size() == 0);
2136 for (TMenu menu
: menus
) {
2137 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2138 == Character
.toLowerCase(keypress
.getKey().getChar())
2141 menu
.setActive(true);
2150 // ------------------------------------------------------------------------
2151 // TTimer management ------------------------------------------------------
2152 // ------------------------------------------------------------------------
2155 * Get the amount of time I can sleep before missing a Timer tick.
2157 * @param timeout = initial (maximum) timeout in millis
2158 * @return number of milliseconds between now and the next timer event
2160 private long getSleepTime(final long timeout
) {
2161 Date now
= new Date();
2162 long nowTime
= now
.getTime();
2163 long sleepTime
= timeout
;
2164 for (TTimer timer
: timers
) {
2165 long nextTickTime
= timer
.getNextTick().getTime();
2166 if (nextTickTime
< nowTime
) {
2170 long timeDifference
= nextTickTime
- nowTime
;
2171 if (timeDifference
< sleepTime
) {
2172 sleepTime
= timeDifference
;
2175 assert (sleepTime
>= 0);
2176 assert (sleepTime
<= timeout
);
2181 * Convenience function to add a timer.
2183 * @param duration number of milliseconds to wait between ticks
2184 * @param recurring if true, re-schedule this timer after every tick
2185 * @param action function to call when button is pressed
2188 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2189 final TAction action
) {
2191 TTimer timer
= new TTimer(duration
, recurring
, action
);
2192 synchronized (timers
) {
2199 * Convenience function to remove a timer.
2201 * @param timer timer to remove
2203 public final void removeTimer(final TTimer timer
) {
2204 synchronized (timers
) {
2205 timers
.remove(timer
);
2209 // ------------------------------------------------------------------------
2210 // Other TWindow constructors ---------------------------------------------
2211 // ------------------------------------------------------------------------
2214 * Convenience function to spawn a message box.
2216 * @param title window title, will be centered along the top border
2217 * @param caption message to display. Use embedded newlines to get a
2219 * @return the new message box
2221 public final TMessageBox
messageBox(final String title
,
2222 final String caption
) {
2224 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2228 * Convenience function to spawn a message box.
2230 * @param title window title, will be centered along the top border
2231 * @param caption message to display. Use embedded newlines to get a
2233 * @param type one of the TMessageBox.Type constants. Default is
2235 * @return the new message box
2237 public final TMessageBox
messageBox(final String title
,
2238 final String caption
, final TMessageBox
.Type type
) {
2240 return new TMessageBox(this, title
, caption
, type
);
2244 * Convenience function to spawn an input box.
2246 * @param title window title, will be centered along the top border
2247 * @param caption message to display. Use embedded newlines to get a
2249 * @return the new input box
2251 public final TInputBox
inputBox(final String title
, final String caption
) {
2253 return new TInputBox(this, title
, caption
);
2257 * Convenience function to spawn an input box.
2259 * @param title window title, will be centered along the top border
2260 * @param caption message to display. Use embedded newlines to get a
2262 * @param text initial text to seed the field with
2263 * @return the new input box
2265 public final TInputBox
inputBox(final String title
, final String caption
,
2266 final String text
) {
2268 return new TInputBox(this, title
, caption
, text
);
2272 * Convenience function to open a terminal window.
2274 * @param x column relative to parent
2275 * @param y row relative to parent
2276 * @return the terminal new window
2278 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2279 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2283 * Convenience function to open a terminal window.
2285 * @param x column relative to parent
2286 * @param y row relative to parent
2287 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2288 * @return the terminal new window
2290 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2293 return new TTerminalWindow(this, x
, y
, flags
);
2297 * Convenience function to spawn an file open box.
2299 * @param path path of selected file
2300 * @return the result of the new file open box
2301 * @throws IOException if java.io operation throws
2303 public final String
fileOpenBox(final String path
) throws IOException
{
2305 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2306 return box
.getFilename();
2310 * Convenience function to spawn an file open box.
2312 * @param path path of selected file
2313 * @param type one of the Type constants
2314 * @return the result of the new file open box
2315 * @throws IOException if java.io operation throws
2317 public final String
fileOpenBox(final String path
,
2318 final TFileOpenBox
.Type type
) throws IOException
{
2320 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2321 return box
.getFilename();