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 50 millis. We need time for
695 // windows with background tasks to update the display, and
696 // still flip buffers reasonably quickly in
697 // backend.flushPhysical().
698 timeout
= getSleepTime(50);
700 // See if there are any definitely events waiting to be
701 // processed. If so, do not wait -- either there is I/O
702 // coming in or the primary/secondary threads are still
704 synchronized (drainEventQueue
) {
705 if (drainEventQueue
.size() > 0) {
709 synchronized (fillEventQueue
) {
710 if (fillEventQueue
.size() > 0) {
717 // As of now, I've got nothing to do: no I/O, nothing from
718 // the consumer threads, no timers that need to run ASAP. So
719 // wait until either the backend or the consumer threads have
722 synchronized (this) {
725 } catch (InterruptedException e
) {
726 // I'm awake and don't care why, let's see what's going
732 // Pull any pending I/O events
733 backend
.getEvents(fillEventQueue
);
735 // Dispatch each event to the appropriate handler, one at a time.
737 TInputEvent event
= null;
738 synchronized (fillEventQueue
) {
739 if (fillEventQueue
.size() == 0) {
742 event
= fillEventQueue
.remove(0);
744 metaHandleEvent(event
);
747 // Wake a consumer thread if we have any pending events.
748 synchronized (drainEventQueue
) {
749 if (drainEventQueue
.size() > 0) {
754 // Prevent stepping on the primary or secondary event handler.
757 // Process timers and call doIdle()'s
761 synchronized (getScreen()) {
765 // Let the event handlers run again.
766 startEventHandlers();
770 // Shutdown the event consumer threads
771 if (secondaryEventHandler
!= null) {
772 synchronized (secondaryEventHandler
) {
773 secondaryEventHandler
.notify();
776 if (primaryEventHandler
!= null) {
777 synchronized (primaryEventHandler
) {
778 primaryEventHandler
.notify();
782 // Shutdown the user I/O thread(s)
785 // Close all the windows. This gives them an opportunity to release
792 * Peek at certain application-level events, add to eventQueue, and wake
793 * up the consuming Thread.
795 * @param event the input event to consume
797 private void metaHandleEvent(final TInputEvent event
) {
800 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
801 event
)); System
.err
.flush();
805 // Do no more processing if the application is already trying
810 // Special application-wide events -------------------------------
813 if (event
instanceof TCommandEvent
) {
814 TCommandEvent command
= (TCommandEvent
) event
;
815 if (command
.getCmd().equals(cmAbort
)) {
822 if (event
instanceof TResizeEvent
) {
823 TResizeEvent resize
= (TResizeEvent
) event
;
824 synchronized (getScreen()) {
825 getScreen().setDimensions(resize
.getWidth(),
827 desktopBottom
= getScreen().getHeight() - 1;
836 // Peek at the mouse position
837 if (event
instanceof TMouseEvent
) {
838 TMouseEvent mouse
= (TMouseEvent
) event
;
839 synchronized (getScreen()) {
840 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
843 mouseX
= mouse
.getX();
844 mouseY
= mouse
.getY();
849 // Put into the main queue
850 synchronized (drainEventQueue
) {
851 drainEventQueue
.add(event
);
856 * Dispatch one event to the appropriate widget or application-level
857 * event handler. This is the primary event handler, it has the normal
858 * application-wide event handling.
860 * @param event the input event to consume
861 * @see #secondaryHandleEvent(TInputEvent event)
863 private void primaryHandleEvent(final TInputEvent event
) {
866 System
.err
.printf("Handle event: %s\n", event
);
869 // Special application-wide events -----------------------------------
871 // Peek at the mouse position
872 if (event
instanceof TMouseEvent
) {
873 // See if we need to switch focus to another window or the menu
874 checkSwitchFocus((TMouseEvent
) event
);
877 // Handle menu events
878 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
879 TMenu menu
= activeMenu
;
881 if (event
instanceof TMouseEvent
) {
882 TMouseEvent mouse
= (TMouseEvent
) event
;
884 while (subMenus
.size() > 0) {
885 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
886 if (subMenu
.mouseWouldHit(mouse
)) {
889 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
890 && (!mouse
.isMouse1())
891 && (!mouse
.isMouse2())
892 && (!mouse
.isMouse3())
893 && (!mouse
.isMouseWheelUp())
894 && (!mouse
.isMouseWheelDown())
898 // We navigated away from a sub-menu, so close it
902 // Convert the mouse relative x/y to menu coordinates
903 assert (mouse
.getX() == mouse
.getAbsoluteX());
904 assert (mouse
.getY() == mouse
.getAbsoluteY());
905 if (subMenus
.size() > 0) {
906 menu
= subMenus
.get(subMenus
.size() - 1);
908 mouse
.setX(mouse
.getX() - menu
.getX());
909 mouse
.setY(mouse
.getY() - menu
.getY());
911 menu
.handleEvent(event
);
915 if (event
instanceof TKeypressEvent
) {
916 TKeypressEvent keypress
= (TKeypressEvent
) event
;
918 // See if this key matches an accelerator, and if so dispatch the
920 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
921 TMenuItem item
= null;
922 synchronized (accelerators
) {
923 item
= accelerators
.get(keypressLowercase
);
926 if (item
.isEnabled()) {
927 // Let the menu item dispatch
932 // Handle the keypress
933 if (onKeypress(keypress
)) {
938 if (event
instanceof TCommandEvent
) {
939 if (onCommand((TCommandEvent
) event
)) {
944 if (event
instanceof TMenuEvent
) {
945 if (onMenu((TMenuEvent
) event
)) {
950 // Dispatch events to the active window -------------------------------
951 for (TWindow window
: windows
) {
952 if (window
.isActive()) {
953 if (event
instanceof TMouseEvent
) {
954 TMouseEvent mouse
= (TMouseEvent
) event
;
955 // Convert the mouse relative x/y to window coordinates
956 assert (mouse
.getX() == mouse
.getAbsoluteX());
957 assert (mouse
.getY() == mouse
.getAbsoluteY());
958 mouse
.setX(mouse
.getX() - window
.getX());
959 mouse
.setY(mouse
.getY() - window
.getY());
962 System
.err
.printf("TApplication dispatch event: %s\n",
965 window
.handleEvent(event
);
971 * Dispatch one event to the appropriate widget or application-level
972 * event handler. This is the secondary event handler used by certain
973 * special dialogs (currently TMessageBox and TFileOpenBox).
975 * @param event the input event to consume
976 * @see #primaryHandleEvent(TInputEvent event)
978 private void secondaryHandleEvent(final TInputEvent event
) {
979 secondaryEventReceiver
.handleEvent(event
);
983 * Enable a widget to override the primary event thread.
985 * @param widget widget that will receive events
987 public final void enableSecondaryEventReceiver(final TWidget widget
) {
988 assert (secondaryEventReceiver
== null);
989 assert (secondaryEventHandler
== null);
990 assert (widget
instanceof TMessageBox
);
991 secondaryEventReceiver
= widget
;
992 secondaryEventHandler
= new WidgetEventHandler(this, false);
993 (new Thread(secondaryEventHandler
)).start();
997 * Yield to the secondary thread.
999 public final void yield() {
1000 assert (secondaryEventReceiver
!= null);
1001 // This is where we handoff the event handler lock from the primary
1002 // to secondary thread. We unlock here, and in a future loop the
1003 // secondary thread locks again. When it gives up, we have the
1004 // single lock back.
1005 boolean oldLock
= unlockHandleEvent();
1006 assert (oldLock
== true);
1008 while (secondaryEventReceiver
!= null) {
1009 synchronized (primaryEventHandler
) {
1011 primaryEventHandler
.wait();
1012 } catch (InterruptedException e
) {
1020 * Do stuff when there is no user input.
1022 private void doIdle() {
1024 System
.err
.printf("doIdle()\n");
1027 // Now run any timers that have timed out
1028 Date now
= new Date();
1029 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1030 for (TTimer timer
: timers
) {
1031 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1033 if (timer
.recurring
) {
1034 keepTimers
.add(timer
);
1037 keepTimers
.add(timer
);
1040 timers
= keepTimers
;
1043 for (TWindow window
: windows
) {
1049 * Get the amount of time I can sleep before missing a Timer tick.
1051 * @param timeout = initial (maximum) timeout in millis
1052 * @return number of milliseconds between now and the next timer event
1054 private long getSleepTime(final long timeout
) {
1055 Date now
= new Date();
1056 long nowTime
= now
.getTime();
1057 long sleepTime
= timeout
;
1058 for (TTimer timer
: timers
) {
1059 long nextTickTime
= timer
.getNextTick().getTime();
1060 if (nextTickTime
< nowTime
) {
1064 long timeDifference
= nextTickTime
- nowTime
;
1065 if (timeDifference
< sleepTime
) {
1066 sleepTime
= timeDifference
;
1069 assert (sleepTime
>= 0);
1070 assert (sleepTime
<= timeout
);
1075 * Close window. Note that the window's destructor is NOT called by this
1076 * method, instead the GC is assumed to do the cleanup.
1078 * @param window the window to remove
1080 public final void closeWindow(final TWindow window
) {
1081 synchronized (windows
) {
1082 int z
= window
.getZ();
1084 Collections
.sort(windows
);
1086 TWindow activeWindow
= null;
1087 for (TWindow w
: windows
) {
1089 w
.setZ(w
.getZ() - 1);
1090 if (w
.getZ() == 0) {
1092 assert (activeWindow
== null);
1101 // Perform window cleanup
1104 // Check if we are closing a TMessageBox or similar
1105 if (secondaryEventReceiver
!= null) {
1106 assert (secondaryEventHandler
!= null);
1108 // Do not send events to the secondaryEventReceiver anymore, the
1109 // window is closed.
1110 secondaryEventReceiver
= null;
1112 // Wake the secondary thread, it will wake the primary as it
1114 synchronized (secondaryEventHandler
) {
1115 secondaryEventHandler
.notify();
1121 * Switch to the next window.
1123 * @param forward if true, then switch to the next window in the list,
1124 * otherwise switch to the previous window in the list
1126 public final void switchWindow(final boolean forward
) {
1127 // Only switch if there are multiple windows
1128 if (windows
.size() < 2) {
1132 synchronized (windows
) {
1134 // Swap z/active between active window and the next in the list
1135 int activeWindowI
= -1;
1136 for (int i
= 0; i
< windows
.size(); i
++) {
1137 if (windows
.get(i
).isActive()) {
1142 assert (activeWindowI
>= 0);
1144 // Do not switch if a window is modal
1145 if (windows
.get(activeWindowI
).isModal()) {
1151 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1153 if (activeWindowI
== 0) {
1154 nextWindowI
= windows
.size() - 1;
1156 nextWindowI
= activeWindowI
- 1;
1159 windows
.get(activeWindowI
).setActive(false);
1160 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1161 windows
.get(nextWindowI
).setZ(0);
1162 windows
.get(nextWindowI
).setActive(true);
1164 } // synchronized (windows)
1169 * Add a window to my window list and make it active.
1171 * @param window new window to add
1173 public final void addWindow(final TWindow window
) {
1174 synchronized (windows
) {
1175 // Do not allow a modal window to spawn a non-modal window
1176 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1177 assert (window
.isModal());
1179 for (TWindow w
: windows
) {
1181 w
.setZ(w
.getZ() + 1);
1183 windows
.add(window
);
1184 window
.setActive(true);
1190 * Check if there is a system-modal window on top.
1192 * @return true if the active window is modal
1194 private boolean modalWindowActive() {
1195 if (windows
.size() == 0) {
1198 return windows
.get(windows
.size() - 1).isModal();
1202 * Check if a mouse event would hit either the active menu or any open
1205 * @param mouse mouse event
1206 * @return true if the mouse would hit the active menu or an open
1209 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1210 assert (activeMenu
!= null);
1211 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1212 Collections
.reverse(menus
);
1213 for (TMenu menu
: menus
) {
1214 if (menu
.mouseWouldHit(mouse
)) {
1218 return activeMenu
.mouseWouldHit(mouse
);
1222 * See if we need to switch window or activate the menu based on
1225 * @param mouse mouse event
1227 private void checkSwitchFocus(final TMouseEvent mouse
) {
1229 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1230 && (activeMenu
!= null)
1231 && (mouse
.getAbsoluteY() != 0)
1232 && (!mouseOnMenu(mouse
))
1234 // They clicked outside the active menu, turn it off
1235 activeMenu
.setActive(false);
1237 for (TMenu menu
: subMenus
) {
1238 menu
.setActive(false);
1244 // See if they hit the menu bar
1245 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1246 && (mouse
.isMouse1())
1247 && (!modalWindowActive())
1248 && (mouse
.getAbsoluteY() == 0)
1251 for (TMenu menu
: subMenus
) {
1252 menu
.setActive(false);
1256 // They selected the menu, go activate it
1257 for (TMenu menu
: menus
) {
1258 if ((mouse
.getAbsoluteX() >= menu
.getX())
1259 && (mouse
.getAbsoluteX() < menu
.getX()
1260 + menu
.getTitle().length() + 2)
1262 menu
.setActive(true);
1265 menu
.setActive(false);
1271 // See if they hit the menu bar
1272 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1273 && (mouse
.isMouse1())
1274 && (activeMenu
!= null)
1275 && (mouse
.getAbsoluteY() == 0)
1278 TMenu oldMenu
= activeMenu
;
1279 for (TMenu menu
: subMenus
) {
1280 menu
.setActive(false);
1284 // See if we should switch menus
1285 for (TMenu menu
: menus
) {
1286 if ((mouse
.getAbsoluteX() >= menu
.getX())
1287 && (mouse
.getAbsoluteX() < menu
.getX()
1288 + menu
.getTitle().length() + 2)
1290 menu
.setActive(true);
1294 if (oldMenu
!= activeMenu
) {
1295 // They switched menus
1296 oldMenu
.setActive(false);
1301 // Only switch if there are multiple windows
1302 if (windows
.size() < 2) {
1306 // Switch on the upclick
1307 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1311 synchronized (windows
) {
1312 Collections
.sort(windows
);
1313 if (windows
.get(0).isModal()) {
1314 // Modal windows don't switch
1318 for (TWindow window
: windows
) {
1319 assert (!window
.isModal());
1320 if (window
.mouseWouldHit(mouse
)) {
1321 if (window
== windows
.get(0)) {
1322 // Clicked on the same window, nothing to do
1326 // We will be switching to another window
1327 assert (windows
.get(0).isActive());
1328 assert (!window
.isActive());
1329 windows
.get(0).setActive(false);
1330 windows
.get(0).setZ(window
.getZ());
1332 window
.setActive(true);
1338 // Clicked on the background, nothing to do
1343 * Turn off the menu.
1345 public final void closeMenu() {
1346 if (activeMenu
!= null) {
1347 activeMenu
.setActive(false);
1349 for (TMenu menu
: subMenus
) {
1350 menu
.setActive(false);
1357 * Turn off a sub-menu.
1359 public final void closeSubMenu() {
1360 assert (activeMenu
!= null);
1361 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1362 assert (item
!= null);
1363 item
.setActive(false);
1364 subMenus
.remove(subMenus
.size() - 1);
1368 * Switch to the next menu.
1370 * @param forward if true, then switch to the next menu in the list,
1371 * otherwise switch to the previous menu in the list
1373 public final void switchMenu(final boolean forward
) {
1374 assert (activeMenu
!= null);
1376 for (TMenu menu
: subMenus
) {
1377 menu
.setActive(false);
1381 for (int i
= 0; i
< menus
.size(); i
++) {
1382 if (activeMenu
== menus
.get(i
)) {
1384 if (i
< menus
.size() - 1) {
1392 activeMenu
.setActive(false);
1393 activeMenu
= menus
.get(i
);
1394 activeMenu
.setActive(true);
1401 * Method that TApplication subclasses can override to handle menu or
1402 * posted command events.
1404 * @param command command event
1405 * @return if true, this event was consumed
1407 protected boolean onCommand(final TCommandEvent command
) {
1408 // Default: handle cmExit
1409 if (command
.equals(cmExit
)) {
1410 if (messageBox("Confirmation", "Exit application?",
1411 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1417 if (command
.equals(cmShell
)) {
1418 openTerminal(0, 0, TWindow
.RESIZABLE
);
1422 if (command
.equals(cmTile
)) {
1426 if (command
.equals(cmCascade
)) {
1430 if (command
.equals(cmCloseAll
)) {
1439 * Method that TApplication subclasses can override to handle menu
1442 * @param menu menu event
1443 * @return if true, this event was consumed
1445 protected boolean onMenu(final TMenuEvent menu
) {
1447 // Default: handle MID_EXIT
1448 if (menu
.getId() == TMenu
.MID_EXIT
) {
1449 if (messageBox("Confirmation", "Exit application?",
1450 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1456 if (menu
.getId() == TMenu
.MID_SHELL
) {
1457 openTerminal(0, 0, TWindow
.RESIZABLE
);
1461 if (menu
.getId() == TMenu
.MID_TILE
) {
1465 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1469 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1477 * Method that TApplication subclasses can override to handle keystrokes.
1479 * @param keypress keystroke event
1480 * @return if true, this event was consumed
1482 protected boolean onKeypress(final TKeypressEvent keypress
) {
1483 // Default: only menu shortcuts
1485 // Process Alt-F, Alt-E, etc. menu shortcut keys
1486 if (!keypress
.getKey().isFnKey()
1487 && keypress
.getKey().isAlt()
1488 && !keypress
.getKey().isCtrl()
1489 && (activeMenu
== null)
1492 assert (subMenus
.size() == 0);
1494 for (TMenu menu
: menus
) {
1495 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1496 == Character
.toLowerCase(keypress
.getKey().getChar())
1499 menu
.setActive(true);
1509 * Add a keyboard accelerator to the global hash.
1511 * @param item menu item this accelerator relates to
1512 * @param keypress keypress that will dispatch a TMenuEvent
1514 public final void addAccelerator(final TMenuItem item
,
1515 final TKeypress keypress
) {
1517 synchronized (accelerators
) {
1518 assert (accelerators
.get(keypress
) == null);
1519 accelerators
.put(keypress
, item
);
1524 * Recompute menu x positions based on their title length.
1526 public final void recomputeMenuX() {
1528 for (TMenu menu
: menus
) {
1530 x
+= menu
.getTitle().length() + 2;
1535 * Post an event to process and turn off the menu.
1537 * @param event new event to add to the queue
1539 public final void addMenuEvent(final TInputEvent event
) {
1540 synchronized (fillEventQueue
) {
1541 fillEventQueue
.add(event
);
1547 * Add a sub-menu to the list of open sub-menus.
1549 * @param menu sub-menu
1551 public final void addSubMenu(final TMenu menu
) {
1556 * Convenience function to add a top-level menu.
1558 * @param title menu title
1559 * @return the new menu
1561 public final TMenu
addMenu(final String title
) {
1564 TMenu menu
= new TMenu(this, x
, y
, title
);
1571 * Convenience function to add a default "File" menu.
1573 * @return the new menu
1575 public final TMenu
addFileMenu() {
1576 TMenu fileMenu
= addMenu("&File");
1577 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1578 fileMenu
.addSeparator();
1579 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1580 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1585 * Convenience function to add a default "Edit" menu.
1587 * @return the new menu
1589 public final TMenu
addEditMenu() {
1590 TMenu editMenu
= addMenu("&Edit");
1591 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1592 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1593 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1594 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1599 * Convenience function to add a default "Window" menu.
1601 * @return the new menu
1603 public final TMenu
addWindowMenu() {
1604 TMenu windowMenu
= addMenu("&Window");
1605 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1606 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1607 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1608 windowMenu
.addSeparator();
1609 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1610 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1611 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1612 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1613 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1618 * Close all open windows.
1620 private void closeAllWindows() {
1621 // Don't do anything if we are in the menu
1622 if (activeMenu
!= null) {
1626 synchronized (windows
) {
1627 for (TWindow window
: windows
) {
1628 closeWindow(window
);
1634 * Re-layout the open windows as non-overlapping tiles. This produces
1635 * almost the same results as Turbo Pascal 7.0's IDE.
1637 private void tileWindows() {
1638 synchronized (windows
) {
1639 // Don't do anything if we are in the menu
1640 if (activeMenu
!= null) {
1643 int z
= windows
.size();
1649 a
= (int)(Math
.sqrt(z
));
1653 if (((a
* b
) + c
) == z
) {
1661 int newWidth
= (getScreen().getWidth() / a
);
1662 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1663 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1665 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1666 Collections
.sort(sorted
);
1667 Collections
.reverse(sorted
);
1668 for (int i
= 0; i
< sorted
.size(); i
++) {
1669 int logicalX
= i
/ b
;
1670 int logicalY
= i
% b
;
1671 if (i
>= ((a
- 1) * b
)) {
1673 logicalY
= i
- ((a
- 1) * b
);
1676 TWindow w
= sorted
.get(i
);
1677 w
.setX(logicalX
* newWidth
);
1678 w
.setWidth(newWidth
);
1679 if (i
>= ((a
- 1) * b
)) {
1680 w
.setY((logicalY
* newHeight2
) + 1);
1681 w
.setHeight(newHeight2
);
1683 w
.setY((logicalY
* newHeight1
) + 1);
1684 w
.setHeight(newHeight1
);
1691 * Re-layout the open windows as overlapping cascaded windows.
1693 private void cascadeWindows() {
1694 synchronized (windows
) {
1695 // Don't do anything if we are in the menu
1696 if (activeMenu
!= null) {
1701 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1702 Collections
.sort(sorted
);
1703 Collections
.reverse(sorted
);
1704 for (TWindow window
: sorted
) {
1709 if (x
> getScreen().getWidth()) {
1712 if (y
>= getScreen().getHeight()) {
1720 * Convenience function to add a timer.
1722 * @param duration number of milliseconds to wait between ticks
1723 * @param recurring if true, re-schedule this timer after every tick
1724 * @param action function to call when button is pressed
1727 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1728 final TAction action
) {
1730 TTimer timer
= new TTimer(duration
, recurring
, action
);
1731 synchronized (timers
) {
1738 * Convenience function to remove a timer.
1740 * @param timer timer to remove
1742 public final void removeTimer(final TTimer timer
) {
1743 synchronized (timers
) {
1744 timers
.remove(timer
);
1749 * Convenience function to spawn a message box.
1751 * @param title window title, will be centered along the top border
1752 * @param caption message to display. Use embedded newlines to get a
1754 * @return the new message box
1756 public final TMessageBox
messageBox(final String title
,
1757 final String caption
) {
1759 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1763 * Convenience function to spawn a message box.
1765 * @param title window title, will be centered along the top border
1766 * @param caption message to display. Use embedded newlines to get a
1768 * @param type one of the TMessageBox.Type constants. Default is
1770 * @return the new message box
1772 public final TMessageBox
messageBox(final String title
,
1773 final String caption
, final TMessageBox
.Type type
) {
1775 return new TMessageBox(this, title
, caption
, type
);
1779 * Convenience function to spawn an input box.
1781 * @param title window title, will be centered along the top border
1782 * @param caption message to display. Use embedded newlines to get a
1784 * @return the new input box
1786 public final TInputBox
inputBox(final String title
, final String caption
) {
1788 return new TInputBox(this, title
, caption
);
1792 * Convenience function to spawn an input box.
1794 * @param title window title, will be centered along the top border
1795 * @param caption message to display. Use embedded newlines to get a
1797 * @param text initial text to seed the field with
1798 * @return the new input box
1800 public final TInputBox
inputBox(final String title
, final String caption
,
1801 final String text
) {
1803 return new TInputBox(this, title
, caption
, text
);
1807 * Convenience function to open a terminal window.
1809 * @param x column relative to parent
1810 * @param y row relative to parent
1811 * @return the terminal new window
1813 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1814 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1818 * Convenience function to open a terminal window.
1820 * @param x column relative to parent
1821 * @param y row relative to parent
1822 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1823 * @return the terminal new window
1825 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1828 return new TTerminalWindow(this, x
, y
, flags
);