2 * Jexer - Java Text User Interface
4 * License: LGPLv3 or later
6 * This module is licensed under the GNU Lesser General Public License
7 * Version 3. Please see the file "COPYING" in this directory for more
8 * information about the GNU Lesser General Public License Version 3.
10 * Copyright (C) 2015 Kevin Lamonte
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 3 of
15 * the License, or (at your option) any later version.
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this program; if not, see
24 * http://www.gnu.org/licenses/, or write to the Free Software
25 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
28 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
33 import java
.io
.InputStream
;
34 import java
.io
.OutputStream
;
35 import java
.io
.UnsupportedEncodingException
;
36 import java
.util
.Collections
;
37 import java
.util
.Date
;
38 import java
.util
.HashMap
;
39 import java
.util
.ArrayList
;
40 import java
.util
.LinkedList
;
41 import java
.util
.List
;
44 import jexer
.bits
.CellAttributes
;
45 import jexer
.bits
.ColorTheme
;
46 import jexer
.bits
.GraphicsChars
;
47 import jexer
.event
.TCommandEvent
;
48 import jexer
.event
.TInputEvent
;
49 import jexer
.event
.TKeypressEvent
;
50 import jexer
.event
.TMenuEvent
;
51 import jexer
.event
.TMouseEvent
;
52 import jexer
.event
.TResizeEvent
;
53 import jexer
.backend
.Backend
;
54 import jexer
.backend
.SwingBackend
;
55 import jexer
.backend
.ECMA48Backend
;
56 import jexer
.io
.Screen
;
57 import jexer
.menu
.TMenu
;
58 import jexer
.menu
.TMenuItem
;
59 import static jexer
.TCommand
.*;
62 * TApplication sets up a full Text User Interface application.
64 public class TApplication
implements Runnable
{
67 * If true, emit thread stuff to System.err.
69 private static final boolean debugThreads
= false;
72 * If true, emit events being processed to System.err.
74 private static final boolean debugEvents
= false;
77 * Two backend types are available.
79 public static enum BackendType
{
86 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
97 * WidgetEventHandler is the main event consumer loop. There are at most
98 * two such threads in existence: the primary for normal case and a
99 * secondary that is used for TMessageBox, TInputBox, and similar.
101 private class WidgetEventHandler
implements Runnable
{
103 * The main application.
105 private TApplication application
;
108 * Whether or not this WidgetEventHandler is the primary or secondary
111 private boolean primary
= true;
114 * Public constructor.
116 * @param application the main application
117 * @param primary if true, this is the primary event handler thread
119 public WidgetEventHandler(final TApplication application
,
120 final boolean primary
) {
122 this.application
= application
;
123 this.primary
= primary
;
132 while (!application
.quit
) {
134 // Wait until application notifies me
135 while (!application
.quit
) {
137 synchronized (application
.drainEventQueue
) {
138 if (application
.drainEventQueue
.size() > 0) {
143 synchronized (this) {
145 System
.err
.printf("%s %s sleep\n", this,
146 primary ?
"primary" : "secondary");
152 System
.err
.printf("%s %s AWAKE\n", this,
153 primary ?
"primary" : "secondary");
157 && (application
.secondaryEventReceiver
== null)
159 // Secondary thread, emergency exit. If we
160 // got here then something went wrong with
161 // the handoff between yield() and
163 synchronized (application
.primaryEventHandler
) {
164 application
.primaryEventHandler
.notify();
166 application
.secondaryEventHandler
= null;
167 throw new RuntimeException(
168 "secondary exited at wrong time");
172 } catch (InterruptedException e
) {
177 // Pull all events off the queue
179 TInputEvent event
= null;
180 synchronized (application
.drainEventQueue
) {
181 if (application
.drainEventQueue
.size() == 0) {
184 event
= application
.drainEventQueue
.remove(0);
186 // Wait for drawAll() or doIdle() to be done, then handle
188 boolean oldLock
= lockHandleEvent();
189 assert (oldLock
== false);
190 application
.repaint
= true;
192 primaryHandleEvent(event
);
194 secondaryHandleEvent(event
);
197 && (application
.secondaryEventReceiver
== null)
199 // Secondary thread, time to exit.
201 // DO NOT UNLOCK. Primary thread just came back from
202 // primaryHandleEvent() and will unlock in the else
203 // block below. Just wake it up.
204 synchronized (application
.primaryEventHandler
) {
205 application
.primaryEventHandler
.notify();
207 // Now eliminate my reference so that
208 // wakeEventHandler() resumes working on the primary.
209 application
.secondaryEventHandler
= null;
214 // Unlock. Either I am primary thread, or I am
215 // secondary thread and still running.
216 oldLock
= unlockHandleEvent();
217 assert (oldLock
== true);
221 // I have done some work of some kind. Tell the main run()
222 // loop to wake up now.
223 synchronized (application
) {
224 application
.notify();
227 } // while (true) (main runnable loop)
232 * The primary event handler thread.
234 private volatile WidgetEventHandler primaryEventHandler
;
237 * The secondary event handler thread.
239 private volatile WidgetEventHandler secondaryEventHandler
;
242 * The widget receiving events from the secondary event handler thread.
244 private volatile TWidget secondaryEventReceiver
;
247 * Spinlock for the primary and secondary event handlers.
248 * WidgetEventHandler.run() is responsible for setting this value.
250 private volatile boolean insideHandleEvent
= false;
253 * Wake the sleeping active event handler.
255 private void wakeEventHandler() {
256 if (secondaryEventHandler
!= null) {
257 synchronized (secondaryEventHandler
) {
258 secondaryEventHandler
.notify();
261 assert (primaryEventHandler
!= null);
262 synchronized (primaryEventHandler
) {
263 primaryEventHandler
.notify();
269 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
270 * spin indefinitely until unlockHandleEvent() is called.
272 * @return the old value of insideHandleEvent
274 private boolean lockHandleEvent() {
276 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
279 boolean oldValue
= true;
281 synchronized (this) {
282 // Wait for TApplication.run() to finish using the global state
283 // before allowing further event processing.
284 while (lockoutHandleEvent
== true) {}
286 oldValue
= insideHandleEvent
;
287 insideHandleEvent
= true;
291 System
.err
.printf(" ***\n");
297 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
298 * spin indefinitely until unlockHandleEvent() is called.
300 * @return the old value of insideHandleEvent
302 private boolean unlockHandleEvent() {
304 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
307 synchronized (this) {
308 boolean oldValue
= insideHandleEvent
;
309 insideHandleEvent
= false;
315 * Spinlock for the primary and secondary event handlers. When true, the
316 * event handlers will spinlock wait before calling handleEvent().
318 private volatile boolean lockoutHandleEvent
= false;
321 * TApplication.run() needs to be able rely on the global data structures
322 * being intact when calling doIdle() and drawAll(). Tell the event
323 * handlers to wait for an unlock before handling their events.
325 private void stopEventHandlers() {
327 System
.err
.printf(">> stopEventHandlers()");
330 lockoutHandleEvent
= true;
331 // Wait for the last event to finish processing before returning
332 // control to TApplication.run().
333 while (insideHandleEvent
== true) {}
336 System
.err
.printf(" XXX\n");
341 * TApplication.run() needs to be able rely on the global data structures
342 * being intact when calling doIdle() and drawAll(). Tell the event
343 * handlers that it is now OK to handle their events.
345 private void startEventHandlers() {
347 System
.err
.printf("<< startEventHandlers()\n");
349 lockoutHandleEvent
= false;
353 * Access to the physical screen, keyboard, and mouse.
355 private Backend backend
;
362 public final Screen
getScreen() {
363 return backend
.getScreen();
367 * Actual mouse coordinate X.
372 * Actual mouse coordinate Y.
377 * Old version of mouse coordinate X.
379 private int oldMouseX
;
382 * Old version mouse coordinate Y.
384 private int oldMouseY
;
387 * Event queue that is filled by run().
389 private List
<TInputEvent
> fillEventQueue
;
392 * Event queue that will be drained by either primary or secondary
395 private List
<TInputEvent
> drainEventQueue
;
398 * Top-level menus in this application.
400 private List
<TMenu
> menus
;
403 * Stack of activated sub-menus in this application.
405 private List
<TMenu
> subMenus
;
408 * The currently acive menu.
410 private TMenu activeMenu
= null;
413 * Active keyboard accelerators.
415 private Map
<TKeypress
, TMenuItem
> accelerators
;
418 * Windows and widgets pull colors from this ColorTheme.
420 private ColorTheme theme
;
423 * Get the color theme.
427 public final ColorTheme
getTheme() {
432 * The top-level windows (but not menus).
434 private List
<TWindow
> windows
;
437 * Timers that are being ticked.
439 private List
<TTimer
> timers
;
442 * When true, exit the application.
444 private volatile boolean quit
= false;
447 * When true, repaint the entire screen.
449 private volatile boolean repaint
= true;
452 * Y coordinate of the top edge of the desktop. For now this is a
453 * constant. Someday it would be nice to have a multi-line menu or
456 private static final int desktopTop
= 1;
459 * Get Y coordinate of the top edge of the desktop.
461 * @return Y coordinate of the top edge of the desktop
463 public final int getDesktopTop() {
468 * Y coordinate of the bottom edge of the desktop.
470 private int desktopBottom
;
473 * Get Y coordinate of the bottom edge of the desktop.
475 * @return Y coordinate of the bottom edge of the desktop
477 public final int getDesktopBottom() {
478 return desktopBottom
;
482 * Public constructor.
484 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
486 * @throws UnsupportedEncodingException if an exception is thrown when
487 * creating the InputStreamReader
489 public TApplication(final BackendType backendType
)
490 throws UnsupportedEncodingException
{
492 switch (backendType
) {
494 backend
= new SwingBackend(this);
499 backend
= new ECMA48Backend(this, null, null);
505 * Public constructor. The backend type will be BackendType.ECMA48.
507 * @param input an InputStream connected to the remote user, or null for
508 * System.in. If System.in is used, then on non-Windows systems it will
509 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
510 * mode. input is always converted to a Reader with UTF-8 encoding.
511 * @param output an OutputStream connected to the remote user, or null
512 * for System.out. output is always converted to a Writer with UTF-8
514 * @throws UnsupportedEncodingException if an exception is thrown when
515 * creating the InputStreamReader
517 public TApplication(final InputStream input
,
518 final OutputStream output
) throws UnsupportedEncodingException
{
520 backend
= new ECMA48Backend(this, input
, output
);
525 * Public constructor. This hook enables use with new non-Jexer
528 * @param backend a Backend that is already ready to go.
530 public TApplication(final Backend backend
) {
531 this.backend
= backend
;
536 * Finish construction once the backend is set.
538 private void TApplicationImpl() {
539 theme
= new ColorTheme();
540 desktopBottom
= getScreen().getHeight() - 1;
541 fillEventQueue
= new ArrayList
<TInputEvent
>();
542 drainEventQueue
= new ArrayList
<TInputEvent
>();
543 windows
= new LinkedList
<TWindow
>();
544 menus
= new LinkedList
<TMenu
>();
545 subMenus
= new LinkedList
<TMenu
>();
546 timers
= new LinkedList
<TTimer
>();
547 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
549 // Setup the main consumer thread
550 primaryEventHandler
= new WidgetEventHandler(this, true);
551 (new Thread(primaryEventHandler
)).start();
555 * Invert the cell color at a position. This is used to track the mouse.
557 * @param x column position
558 * @param y row position
560 private void invertCell(final int x
, final int y
) {
561 synchronized (getScreen()) {
562 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
563 attr
.setForeColor(attr
.getForeColor().invert());
564 attr
.setBackColor(attr
.getBackColor().invert());
565 getScreen().putAttrXY(x
, y
, attr
, false);
572 private void drawAll() {
574 System
.err
.printf("drawAll() enter\n");
578 synchronized (getScreen()) {
579 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
580 // The only thing that has happened is the mouse moved.
581 // Clear the old position and draw the new position.
582 invertCell(oldMouseX
, oldMouseY
);
583 invertCell(mouseX
, mouseY
);
588 if (getScreen().isDirty()) {
589 backend
.flushScreen();
595 System
.err
.printf("drawAll() REDRAW\n");
598 // If true, the cursor is not visible
599 boolean cursor
= false;
601 // Start with a clean screen
604 // Draw the background
605 CellAttributes background
= theme
.getColor("tapplication.background");
606 getScreen().putAll(GraphicsChars
.HATCH
, background
);
608 // Draw each window in reverse Z order
609 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
610 Collections
.sort(sorted
);
611 Collections
.reverse(sorted
);
612 for (TWindow window
: sorted
) {
613 window
.drawChildren();
616 // Draw the blank menubar line - reset the screen clipping first so
617 // it won't trim it out.
618 getScreen().resetClipping();
619 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
620 theme
.getColor("tmenu"));
621 // Now draw the menus.
623 for (TMenu menu
: menus
) {
624 CellAttributes menuColor
;
625 CellAttributes menuMnemonicColor
;
626 if (menu
.isActive()) {
627 menuColor
= theme
.getColor("tmenu.highlighted");
628 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
630 menuColor
= theme
.getColor("tmenu");
631 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
633 // Draw the menu title
634 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
636 getScreen().putStrXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
637 // Draw the highlight character
638 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
639 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
641 if (menu
.isActive()) {
643 // Reset the screen clipping so we can draw the next title.
644 getScreen().resetClipping();
646 x
+= menu
.getTitle().length() + 2;
649 for (TMenu menu
: subMenus
) {
650 // Reset the screen clipping so we can draw the next sub-menu.
651 getScreen().resetClipping();
655 // Draw the mouse pointer
656 invertCell(mouseX
, mouseY
);
658 // Place the cursor if it is visible
659 TWidget activeWidget
= null;
660 if (sorted
.size() > 0) {
661 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
662 if (activeWidget
.isCursorVisible()) {
663 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
664 activeWidget
.getCursorAbsoluteY());
671 getScreen().hideCursor();
674 // Flush the screen contents
675 backend
.flushScreen();
681 * Run this application until it exits.
685 // Timeout is in milliseconds, so default timeout after 1 second
689 // If I've got no updates to render, wait for something from the
690 // backend or a timer.
692 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
694 // Never sleep longer than 100 millis, to get windows with
695 // background tasks an opportunity to update the display.
696 timeout
= getSleepTime(100);
698 // See if there are any definitely events waiting to be
699 // processed. If so, do not wait -- either there is I/O
700 // coming in or the primary/secondary threads are still
702 synchronized (drainEventQueue
) {
703 if (drainEventQueue
.size() > 0) {
707 synchronized (fillEventQueue
) {
708 if (fillEventQueue
.size() > 0) {
715 // As of now, I've got nothing to do: no I/O, nothing from
716 // the consumer threads, no timers that need to run ASAP. So
717 // wait until either the backend or the consumer threads have
720 synchronized (this) {
723 } catch (InterruptedException e
) {
724 // I'm awake and don't care why, let's see what's going
730 // Pull any pending I/O events
731 backend
.getEvents(fillEventQueue
);
733 // Dispatch each event to the appropriate handler, one at a time.
735 TInputEvent event
= null;
736 synchronized (fillEventQueue
) {
737 if (fillEventQueue
.size() == 0) {
740 event
= fillEventQueue
.remove(0);
742 metaHandleEvent(event
);
745 // Wake a consumer thread if we have any pending events.
746 synchronized (drainEventQueue
) {
747 if (drainEventQueue
.size() > 0) {
752 // Prevent stepping on the primary or secondary event handler.
755 // Process timers and call doIdle()'s
759 synchronized (getScreen()) {
763 // Let the event handlers run again.
764 startEventHandlers();
768 // Shutdown the event consumer threads
769 if (secondaryEventHandler
!= null) {
770 synchronized (secondaryEventHandler
) {
771 secondaryEventHandler
.notify();
774 if (primaryEventHandler
!= null) {
775 synchronized (primaryEventHandler
) {
776 primaryEventHandler
.notify();
780 // Shutdown the user I/O thread(s)
783 // Close all the windows. This gives them an opportunity to release
790 * Peek at certain application-level events, add to eventQueue, and wake
791 * up the consuming Thread.
793 * @param event the input event to consume
795 private void metaHandleEvent(final TInputEvent event
) {
798 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
799 event
)); System
.err
.flush();
803 // Do no more processing if the application is already trying
808 // Special application-wide events -------------------------------
811 if (event
instanceof TCommandEvent
) {
812 TCommandEvent command
= (TCommandEvent
) event
;
813 if (command
.getCmd().equals(cmAbort
)) {
820 if (event
instanceof TResizeEvent
) {
821 TResizeEvent resize
= (TResizeEvent
) event
;
822 synchronized (getScreen()) {
823 getScreen().setDimensions(resize
.getWidth(),
825 desktopBottom
= getScreen().getHeight() - 1;
834 // Peek at the mouse position
835 if (event
instanceof TMouseEvent
) {
836 TMouseEvent mouse
= (TMouseEvent
) event
;
837 synchronized (getScreen()) {
838 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
841 mouseX
= mouse
.getX();
842 mouseY
= mouse
.getY();
847 // Put into the main queue
848 synchronized (drainEventQueue
) {
849 drainEventQueue
.add(event
);
854 * Dispatch one event to the appropriate widget or application-level
855 * event handler. This is the primary event handler, it has the normal
856 * application-wide event handling.
858 * @param event the input event to consume
859 * @see #secondaryHandleEvent(TInputEvent event)
861 private void primaryHandleEvent(final TInputEvent event
) {
864 System
.err
.printf("Handle event: %s\n", event
);
867 // Special application-wide events -----------------------------------
869 // Peek at the mouse position
870 if (event
instanceof TMouseEvent
) {
871 // See if we need to switch focus to another window or the menu
872 checkSwitchFocus((TMouseEvent
) event
);
875 // Handle menu events
876 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
877 TMenu menu
= activeMenu
;
879 if (event
instanceof TMouseEvent
) {
880 TMouseEvent mouse
= (TMouseEvent
) event
;
882 while (subMenus
.size() > 0) {
883 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
884 if (subMenu
.mouseWouldHit(mouse
)) {
887 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
888 && (!mouse
.isMouse1())
889 && (!mouse
.isMouse2())
890 && (!mouse
.isMouse3())
891 && (!mouse
.isMouseWheelUp())
892 && (!mouse
.isMouseWheelDown())
896 // We navigated away from a sub-menu, so close it
900 // Convert the mouse relative x/y to menu coordinates
901 assert (mouse
.getX() == mouse
.getAbsoluteX());
902 assert (mouse
.getY() == mouse
.getAbsoluteY());
903 if (subMenus
.size() > 0) {
904 menu
= subMenus
.get(subMenus
.size() - 1);
906 mouse
.setX(mouse
.getX() - menu
.getX());
907 mouse
.setY(mouse
.getY() - menu
.getY());
909 menu
.handleEvent(event
);
913 if (event
instanceof TKeypressEvent
) {
914 TKeypressEvent keypress
= (TKeypressEvent
) event
;
916 // See if this key matches an accelerator, and if so dispatch the
918 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
919 TMenuItem item
= null;
920 synchronized (accelerators
) {
921 item
= accelerators
.get(keypressLowercase
);
924 if (item
.isEnabled()) {
925 // Let the menu item dispatch
930 // Handle the keypress
931 if (onKeypress(keypress
)) {
936 if (event
instanceof TCommandEvent
) {
937 if (onCommand((TCommandEvent
) event
)) {
942 if (event
instanceof TMenuEvent
) {
943 if (onMenu((TMenuEvent
) event
)) {
948 // Dispatch events to the active window -------------------------------
949 for (TWindow window
: windows
) {
950 if (window
.isActive()) {
951 if (event
instanceof TMouseEvent
) {
952 TMouseEvent mouse
= (TMouseEvent
) event
;
953 // Convert the mouse relative x/y to window coordinates
954 assert (mouse
.getX() == mouse
.getAbsoluteX());
955 assert (mouse
.getY() == mouse
.getAbsoluteY());
956 mouse
.setX(mouse
.getX() - window
.getX());
957 mouse
.setY(mouse
.getY() - window
.getY());
960 System
.err
.printf("TApplication dispatch event: %s\n",
963 window
.handleEvent(event
);
969 * Dispatch one event to the appropriate widget or application-level
970 * event handler. This is the secondary event handler used by certain
971 * special dialogs (currently TMessageBox and TFileOpenBox).
973 * @param event the input event to consume
974 * @see #primaryHandleEvent(TInputEvent event)
976 private void secondaryHandleEvent(final TInputEvent event
) {
977 secondaryEventReceiver
.handleEvent(event
);
981 * Enable a widget to override the primary event thread.
983 * @param widget widget that will receive events
985 public final void enableSecondaryEventReceiver(final TWidget widget
) {
986 assert (secondaryEventReceiver
== null);
987 assert (secondaryEventHandler
== null);
988 assert (widget
instanceof TMessageBox
);
989 secondaryEventReceiver
= widget
;
990 secondaryEventHandler
= new WidgetEventHandler(this, false);
991 (new Thread(secondaryEventHandler
)).start();
995 * Yield to the secondary thread.
997 public final void yield() {
998 assert (secondaryEventReceiver
!= null);
999 // This is where we handoff the event handler lock from the primary
1000 // to secondary thread. We unlock here, and in a future loop the
1001 // secondary thread locks again. When it gives up, we have the
1002 // single lock back.
1003 boolean oldLock
= unlockHandleEvent();
1004 assert (oldLock
== true);
1006 while (secondaryEventReceiver
!= null) {
1007 synchronized (primaryEventHandler
) {
1009 primaryEventHandler
.wait();
1010 } catch (InterruptedException e
) {
1018 * Do stuff when there is no user input.
1020 private void doIdle() {
1022 System
.err
.printf("doIdle()\n");
1025 // Now run any timers that have timed out
1026 Date now
= new Date();
1027 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1028 for (TTimer timer
: timers
) {
1029 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1031 if (timer
.recurring
) {
1032 keepTimers
.add(timer
);
1035 keepTimers
.add(timer
);
1038 timers
= keepTimers
;
1041 for (TWindow window
: windows
) {
1047 * Get the amount of time I can sleep before missing a Timer tick.
1049 * @param timeout = initial (maximum) timeout in millis
1050 * @return number of milliseconds between now and the next timer event
1052 private long getSleepTime(final long timeout
) {
1053 Date now
= new Date();
1054 long nowTime
= now
.getTime();
1055 long sleepTime
= timeout
;
1056 for (TTimer timer
: timers
) {
1057 long nextTickTime
= timer
.getNextTick().getTime();
1058 if (nextTickTime
< nowTime
) {
1062 long timeDifference
= nextTickTime
- nowTime
;
1063 if (timeDifference
< sleepTime
) {
1064 sleepTime
= timeDifference
;
1067 assert (sleepTime
>= 0);
1068 assert (sleepTime
<= timeout
);
1073 * Close window. Note that the window's destructor is NOT called by this
1074 * method, instead the GC is assumed to do the cleanup.
1076 * @param window the window to remove
1078 public final void closeWindow(final TWindow window
) {
1079 synchronized (windows
) {
1080 int z
= window
.getZ();
1082 Collections
.sort(windows
);
1084 TWindow activeWindow
= null;
1085 for (TWindow w
: windows
) {
1087 w
.setZ(w
.getZ() - 1);
1088 if (w
.getZ() == 0) {
1090 assert (activeWindow
== null);
1099 // Perform window cleanup
1102 // Check if we are closing a TMessageBox or similar
1103 if (secondaryEventReceiver
!= null) {
1104 assert (secondaryEventHandler
!= null);
1106 // Do not send events to the secondaryEventReceiver anymore, the
1107 // window is closed.
1108 secondaryEventReceiver
= null;
1110 // Wake the secondary thread, it will wake the primary as it
1112 synchronized (secondaryEventHandler
) {
1113 secondaryEventHandler
.notify();
1119 * Switch to the next window.
1121 * @param forward if true, then switch to the next window in the list,
1122 * otherwise switch to the previous window in the list
1124 public final void switchWindow(final boolean forward
) {
1125 // Only switch if there are multiple windows
1126 if (windows
.size() < 2) {
1130 synchronized (windows
) {
1132 // Swap z/active between active window and the next in the list
1133 int activeWindowI
= -1;
1134 for (int i
= 0; i
< windows
.size(); i
++) {
1135 if (windows
.get(i
).isActive()) {
1140 assert (activeWindowI
>= 0);
1142 // Do not switch if a window is modal
1143 if (windows
.get(activeWindowI
).isModal()) {
1149 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1151 if (activeWindowI
== 0) {
1152 nextWindowI
= windows
.size() - 1;
1154 nextWindowI
= activeWindowI
- 1;
1157 windows
.get(activeWindowI
).setActive(false);
1158 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1159 windows
.get(nextWindowI
).setZ(0);
1160 windows
.get(nextWindowI
).setActive(true);
1162 } // synchronized (windows)
1167 * Add a window to my window list and make it active.
1169 * @param window new window to add
1171 public final void addWindow(final TWindow window
) {
1172 synchronized (windows
) {
1173 // Do not allow a modal window to spawn a non-modal window
1174 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1175 assert (window
.isModal());
1177 for (TWindow w
: windows
) {
1179 w
.setZ(w
.getZ() + 1);
1181 windows
.add(window
);
1182 window
.setActive(true);
1188 * Check if there is a system-modal window on top.
1190 * @return true if the active window is modal
1192 private boolean modalWindowActive() {
1193 if (windows
.size() == 0) {
1196 return windows
.get(windows
.size() - 1).isModal();
1200 * Check if a mouse event would hit either the active menu or any open
1203 * @param mouse mouse event
1204 * @return true if the mouse would hit the active menu or an open
1207 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1208 assert (activeMenu
!= null);
1209 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1210 Collections
.reverse(menus
);
1211 for (TMenu menu
: menus
) {
1212 if (menu
.mouseWouldHit(mouse
)) {
1216 return activeMenu
.mouseWouldHit(mouse
);
1220 * See if we need to switch window or activate the menu based on
1223 * @param mouse mouse event
1225 private void checkSwitchFocus(final TMouseEvent mouse
) {
1227 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1228 && (activeMenu
!= null)
1229 && (mouse
.getAbsoluteY() != 0)
1230 && (!mouseOnMenu(mouse
))
1232 // They clicked outside the active menu, turn it off
1233 activeMenu
.setActive(false);
1235 for (TMenu menu
: subMenus
) {
1236 menu
.setActive(false);
1242 // See if they hit the menu bar
1243 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1244 && (mouse
.isMouse1())
1245 && (!modalWindowActive())
1246 && (mouse
.getAbsoluteY() == 0)
1249 for (TMenu menu
: subMenus
) {
1250 menu
.setActive(false);
1254 // They selected the menu, go activate it
1255 for (TMenu menu
: menus
) {
1256 if ((mouse
.getAbsoluteX() >= menu
.getX())
1257 && (mouse
.getAbsoluteX() < menu
.getX()
1258 + menu
.getTitle().length() + 2)
1260 menu
.setActive(true);
1263 menu
.setActive(false);
1269 // See if they hit the menu bar
1270 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1271 && (mouse
.isMouse1())
1272 && (activeMenu
!= null)
1273 && (mouse
.getAbsoluteY() == 0)
1276 TMenu oldMenu
= activeMenu
;
1277 for (TMenu menu
: subMenus
) {
1278 menu
.setActive(false);
1282 // See if we should switch menus
1283 for (TMenu menu
: menus
) {
1284 if ((mouse
.getAbsoluteX() >= menu
.getX())
1285 && (mouse
.getAbsoluteX() < menu
.getX()
1286 + menu
.getTitle().length() + 2)
1288 menu
.setActive(true);
1292 if (oldMenu
!= activeMenu
) {
1293 // They switched menus
1294 oldMenu
.setActive(false);
1299 // Only switch if there are multiple windows
1300 if (windows
.size() < 2) {
1304 // Switch on the upclick
1305 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1309 synchronized (windows
) {
1310 Collections
.sort(windows
);
1311 if (windows
.get(0).isModal()) {
1312 // Modal windows don't switch
1316 for (TWindow window
: windows
) {
1317 assert (!window
.isModal());
1318 if (window
.mouseWouldHit(mouse
)) {
1319 if (window
== windows
.get(0)) {
1320 // Clicked on the same window, nothing to do
1324 // We will be switching to another window
1325 assert (windows
.get(0).isActive());
1326 assert (!window
.isActive());
1327 windows
.get(0).setActive(false);
1328 windows
.get(0).setZ(window
.getZ());
1330 window
.setActive(true);
1336 // Clicked on the background, nothing to do
1341 * Turn off the menu.
1343 public final void closeMenu() {
1344 if (activeMenu
!= null) {
1345 activeMenu
.setActive(false);
1347 for (TMenu menu
: subMenus
) {
1348 menu
.setActive(false);
1355 * Turn off a sub-menu.
1357 public final void closeSubMenu() {
1358 assert (activeMenu
!= null);
1359 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1360 assert (item
!= null);
1361 item
.setActive(false);
1362 subMenus
.remove(subMenus
.size() - 1);
1366 * Switch to the next menu.
1368 * @param forward if true, then switch to the next menu in the list,
1369 * otherwise switch to the previous menu in the list
1371 public final void switchMenu(final boolean forward
) {
1372 assert (activeMenu
!= null);
1374 for (TMenu menu
: subMenus
) {
1375 menu
.setActive(false);
1379 for (int i
= 0; i
< menus
.size(); i
++) {
1380 if (activeMenu
== menus
.get(i
)) {
1382 if (i
< menus
.size() - 1) {
1390 activeMenu
.setActive(false);
1391 activeMenu
= menus
.get(i
);
1392 activeMenu
.setActive(true);
1399 * Method that TApplication subclasses can override to handle menu or
1400 * posted command events.
1402 * @param command command event
1403 * @return if true, this event was consumed
1405 protected boolean onCommand(final TCommandEvent command
) {
1406 // Default: handle cmExit
1407 if (command
.equals(cmExit
)) {
1408 if (messageBox("Confirmation", "Exit application?",
1409 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1415 if (command
.equals(cmShell
)) {
1416 openTerminal(0, 0, TWindow
.RESIZABLE
);
1420 if (command
.equals(cmTile
)) {
1424 if (command
.equals(cmCascade
)) {
1428 if (command
.equals(cmCloseAll
)) {
1437 * Method that TApplication subclasses can override to handle menu
1440 * @param menu menu event
1441 * @return if true, this event was consumed
1443 protected boolean onMenu(final TMenuEvent menu
) {
1445 // Default: handle MID_EXIT
1446 if (menu
.getId() == TMenu
.MID_EXIT
) {
1447 if (messageBox("Confirmation", "Exit application?",
1448 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1454 if (menu
.getId() == TMenu
.MID_SHELL
) {
1455 openTerminal(0, 0, TWindow
.RESIZABLE
);
1459 if (menu
.getId() == TMenu
.MID_TILE
) {
1463 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1467 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1475 * Method that TApplication subclasses can override to handle keystrokes.
1477 * @param keypress keystroke event
1478 * @return if true, this event was consumed
1480 protected boolean onKeypress(final TKeypressEvent keypress
) {
1481 // Default: only menu shortcuts
1483 // Process Alt-F, Alt-E, etc. menu shortcut keys
1484 if (!keypress
.getKey().isFnKey()
1485 && keypress
.getKey().isAlt()
1486 && !keypress
.getKey().isCtrl()
1487 && (activeMenu
== null)
1490 assert (subMenus
.size() == 0);
1492 for (TMenu menu
: menus
) {
1493 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1494 == Character
.toLowerCase(keypress
.getKey().getChar())
1497 menu
.setActive(true);
1507 * Add a keyboard accelerator to the global hash.
1509 * @param item menu item this accelerator relates to
1510 * @param keypress keypress that will dispatch a TMenuEvent
1512 public final void addAccelerator(final TMenuItem item
,
1513 final TKeypress keypress
) {
1515 synchronized (accelerators
) {
1516 assert (accelerators
.get(keypress
) == null);
1517 accelerators
.put(keypress
, item
);
1522 * Recompute menu x positions based on their title length.
1524 public final void recomputeMenuX() {
1526 for (TMenu menu
: menus
) {
1528 x
+= menu
.getTitle().length() + 2;
1533 * Post an event to process and turn off the menu.
1535 * @param event new event to add to the queue
1537 public final void addMenuEvent(final TInputEvent event
) {
1538 synchronized (fillEventQueue
) {
1539 fillEventQueue
.add(event
);
1545 * Add a sub-menu to the list of open sub-menus.
1547 * @param menu sub-menu
1549 public final void addSubMenu(final TMenu menu
) {
1554 * Convenience function to add a top-level menu.
1556 * @param title menu title
1557 * @return the new menu
1559 public final TMenu
addMenu(final String title
) {
1562 TMenu menu
= new TMenu(this, x
, y
, title
);
1569 * Convenience function to add a default "File" menu.
1571 * @return the new menu
1573 public final TMenu
addFileMenu() {
1574 TMenu fileMenu
= addMenu("&File");
1575 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1576 fileMenu
.addSeparator();
1577 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1578 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1583 * Convenience function to add a default "Edit" menu.
1585 * @return the new menu
1587 public final TMenu
addEditMenu() {
1588 TMenu editMenu
= addMenu("&Edit");
1589 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1590 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1591 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1592 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1597 * Convenience function to add a default "Window" menu.
1599 * @return the new menu
1601 public final TMenu
addWindowMenu() {
1602 TMenu windowMenu
= addMenu("&Window");
1603 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1604 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1605 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1606 windowMenu
.addSeparator();
1607 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1608 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1609 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1610 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1611 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1616 * Close all open windows.
1618 private void closeAllWindows() {
1619 // Don't do anything if we are in the menu
1620 if (activeMenu
!= null) {
1624 synchronized (windows
) {
1625 for (TWindow window
: windows
) {
1626 closeWindow(window
);
1632 * Re-layout the open windows as non-overlapping tiles. This produces
1633 * almost the same results as Turbo Pascal 7.0's IDE.
1635 private void tileWindows() {
1636 synchronized (windows
) {
1637 // Don't do anything if we are in the menu
1638 if (activeMenu
!= null) {
1641 int z
= windows
.size();
1647 a
= (int)(Math
.sqrt(z
));
1651 if (((a
* b
) + c
) == z
) {
1659 int newWidth
= (getScreen().getWidth() / a
);
1660 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1661 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1663 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1664 Collections
.sort(sorted
);
1665 Collections
.reverse(sorted
);
1666 for (int i
= 0; i
< sorted
.size(); i
++) {
1667 int logicalX
= i
/ b
;
1668 int logicalY
= i
% b
;
1669 if (i
>= ((a
- 1) * b
)) {
1671 logicalY
= i
- ((a
- 1) * b
);
1674 TWindow w
= sorted
.get(i
);
1675 w
.setX(logicalX
* newWidth
);
1676 w
.setWidth(newWidth
);
1677 if (i
>= ((a
- 1) * b
)) {
1678 w
.setY((logicalY
* newHeight2
) + 1);
1679 w
.setHeight(newHeight2
);
1681 w
.setY((logicalY
* newHeight1
) + 1);
1682 w
.setHeight(newHeight1
);
1689 * Re-layout the open windows as overlapping cascaded windows.
1691 private void cascadeWindows() {
1692 synchronized (windows
) {
1693 // Don't do anything if we are in the menu
1694 if (activeMenu
!= null) {
1699 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1700 Collections
.sort(sorted
);
1701 Collections
.reverse(sorted
);
1702 for (TWindow window
: sorted
) {
1707 if (x
> getScreen().getWidth()) {
1710 if (y
>= getScreen().getHeight()) {
1718 * Convenience function to add a timer.
1720 * @param duration number of milliseconds to wait between ticks
1721 * @param recurring if true, re-schedule this timer after every tick
1722 * @param action function to call when button is pressed
1725 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1726 final TAction action
) {
1728 TTimer timer
= new TTimer(duration
, recurring
, action
);
1729 synchronized (timers
) {
1736 * Convenience function to remove a timer.
1738 * @param timer timer to remove
1740 public final void removeTimer(final TTimer timer
) {
1741 synchronized (timers
) {
1742 timers
.remove(timer
);
1747 * Convenience function to spawn a message box.
1749 * @param title window title, will be centered along the top border
1750 * @param caption message to display. Use embedded newlines to get a
1752 * @return the new message box
1754 public final TMessageBox
messageBox(final String title
,
1755 final String caption
) {
1757 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1761 * Convenience function to spawn a message box.
1763 * @param title window title, will be centered along the top border
1764 * @param caption message to display. Use embedded newlines to get a
1766 * @param type one of the TMessageBox.Type constants. Default is
1768 * @return the new message box
1770 public final TMessageBox
messageBox(final String title
,
1771 final String caption
, final TMessageBox
.Type type
) {
1773 return new TMessageBox(this, title
, caption
, type
);
1777 * Convenience function to spawn an input box.
1779 * @param title window title, will be centered along the top border
1780 * @param caption message to display. Use embedded newlines to get a
1782 * @return the new input box
1784 public final TInputBox
inputBox(final String title
, final String caption
) {
1786 return new TInputBox(this, title
, caption
);
1790 * Convenience function to spawn an input box.
1792 * @param title window title, will be centered along the top border
1793 * @param caption message to display. Use embedded newlines to get a
1795 * @param text initial text to seed the field with
1796 * @return the new input box
1798 public final TInputBox
inputBox(final String title
, final String caption
,
1799 final String text
) {
1801 return new TInputBox(this, title
, caption
, text
);
1805 * Convenience function to open a terminal window.
1807 * @param x column relative to parent
1808 * @param y row relative to parent
1809 * @return the terminal new window
1811 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1812 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1816 * Convenience function to open a terminal window.
1818 * @param x column relative to parent
1819 * @param y row relative to parent
1820 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1821 * @return the terminal new window
1823 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1826 return new TTerminalWindow(this, x
, y
, flags
);