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
.IOException
;
35 import java
.io
.OutputStream
;
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
.*;
63 * TApplication sets up a full Text User Interface application.
65 public class TApplication
implements Runnable
{
68 * If true, emit thread stuff to System.err.
70 private static final boolean debugThreads
= false;
73 * If true, emit events being processed to System.err.
75 private static final boolean debugEvents
= false;
78 * Two backend types are available.
80 public static enum BackendType
{
87 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
98 * WidgetEventHandler is the main event consumer loop. There are at most
99 * two such threads in existence: the primary for normal case and a
100 * secondary that is used for TMessageBox, TInputBox, and similar.
102 private class WidgetEventHandler
implements Runnable
{
104 * The main application.
106 private TApplication application
;
109 * Whether or not this WidgetEventHandler is the primary or secondary
112 private boolean primary
= true;
115 * Public constructor.
117 * @param application the main application
118 * @param primary if true, this is the primary event handler thread
120 public WidgetEventHandler(final TApplication application
,
121 final boolean primary
) {
123 this.application
= application
;
124 this.primary
= primary
;
133 while (!application
.quit
) {
135 // Wait until application notifies me
136 while (!application
.quit
) {
138 synchronized (application
.drainEventQueue
) {
139 if (application
.drainEventQueue
.size() > 0) {
144 synchronized (this) {
146 System
.err
.printf("%s %s sleep\n", this,
147 primary ?
"primary" : "secondary");
153 System
.err
.printf("%s %s AWAKE\n", this,
154 primary ?
"primary" : "secondary");
158 && (application
.secondaryEventReceiver
== null)
160 // Secondary thread, emergency exit. If we
161 // got here then something went wrong with
162 // the handoff between yield() and
164 synchronized (application
.primaryEventHandler
) {
165 application
.primaryEventHandler
.notify();
167 application
.secondaryEventHandler
= null;
168 throw new RuntimeException(
169 "secondary exited at wrong time");
173 } catch (InterruptedException e
) {
178 // Wait for drawAll() or doIdle() to be done, then handle the
180 boolean oldLock
= lockHandleEvent();
181 assert (oldLock
== false);
183 // Pull all events off the queue
185 TInputEvent event
= null;
186 synchronized (application
.drainEventQueue
) {
187 if (application
.drainEventQueue
.size() == 0) {
190 event
= application
.drainEventQueue
.remove(0);
192 application
.repaint
= true;
194 primaryHandleEvent(event
);
196 secondaryHandleEvent(event
);
199 && (application
.secondaryEventReceiver
== null)
201 // Secondary thread, time to exit.
203 // DO NOT UNLOCK. Primary thread just came back from
204 // primaryHandleEvent() and will unlock in the else
205 // block below. Just wake it up.
206 synchronized (application
.primaryEventHandler
) {
207 application
.primaryEventHandler
.notify();
209 // Now eliminate my reference so that
210 // wakeEventHandler() resumes working on the primary.
211 application
.secondaryEventHandler
= null;
218 // Unlock. Either I am primary thread, or I am secondary
219 // thread and still running.
220 oldLock
= unlockHandleEvent();
221 assert (oldLock
== true);
223 // I have done some work of some kind. Tell the main run()
224 // loop to wake up now.
225 synchronized (application
) {
226 application
.notify();
229 } // while (true) (main runnable loop)
234 * The primary event handler thread.
236 private volatile WidgetEventHandler primaryEventHandler
;
239 * The secondary event handler thread.
241 private volatile WidgetEventHandler secondaryEventHandler
;
244 * The widget receiving events from the secondary event handler thread.
246 private volatile TWidget secondaryEventReceiver
;
249 * Spinlock for the primary and secondary event handlers.
250 * WidgetEventHandler.run() is responsible for setting this value.
252 private volatile boolean insideHandleEvent
= false;
255 * Wake the sleeping active event handler.
257 private void wakeEventHandler() {
258 if (secondaryEventHandler
!= null) {
259 synchronized (secondaryEventHandler
) {
260 secondaryEventHandler
.notify();
263 assert (primaryEventHandler
!= null);
264 synchronized (primaryEventHandler
) {
265 primaryEventHandler
.notify();
271 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
272 * spin indefinitely until unlockHandleEvent() is called.
274 * @return the old value of insideHandleEvent
276 private boolean lockHandleEvent() {
278 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
281 boolean oldValue
= true;
283 synchronized (this) {
284 // Wait for TApplication.run() to finish using the global state
285 // before allowing further event processing.
286 while (lockoutHandleEvent
== true) {
288 // Backoff so that the backend can finish its work.
290 } catch (InterruptedException e
) {
295 oldValue
= insideHandleEvent
;
296 insideHandleEvent
= true;
300 System
.err
.printf(" ***\n");
306 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
307 * spin indefinitely until unlockHandleEvent() is called.
309 * @return the old value of insideHandleEvent
311 private boolean unlockHandleEvent() {
313 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
316 synchronized (this) {
317 boolean oldValue
= insideHandleEvent
;
318 insideHandleEvent
= false;
324 * Spinlock for the primary and secondary event handlers. When true, the
325 * event handlers will spinlock wait before calling handleEvent().
327 private volatile boolean lockoutHandleEvent
= false;
330 * TApplication.run() needs to be able rely on the global data structures
331 * being intact when calling doIdle() and drawAll(). Tell the event
332 * handlers to wait for an unlock before handling their events.
334 private void stopEventHandlers() {
336 System
.err
.printf(">> stopEventHandlers()");
339 lockoutHandleEvent
= true;
340 // Wait for the last event to finish processing before returning
341 // control to TApplication.run().
342 while (insideHandleEvent
== true) {
344 // Backoff so that the event handler can finish its work.
346 } catch (InterruptedException e
) {
352 System
.err
.printf(" XXX\n");
357 * TApplication.run() needs to be able rely on the global data structures
358 * being intact when calling doIdle() and drawAll(). Tell the event
359 * handlers that it is now OK to handle their events.
361 private void startEventHandlers() {
363 System
.err
.printf("<< startEventHandlers()\n");
365 lockoutHandleEvent
= false;
369 * Access to the physical screen, keyboard, and mouse.
371 private Backend backend
;
378 public final Screen
getScreen() {
379 return backend
.getScreen();
383 * Actual mouse coordinate X.
388 * Actual mouse coordinate Y.
393 * Old version of mouse coordinate X.
395 private int oldMouseX
;
398 * Old version mouse coordinate Y.
400 private int oldMouseY
;
403 * Event queue that is filled by run().
405 private List
<TInputEvent
> fillEventQueue
;
408 * Event queue that will be drained by either primary or secondary
411 private List
<TInputEvent
> drainEventQueue
;
414 * Top-level menus in this application.
416 private List
<TMenu
> menus
;
419 * Stack of activated sub-menus in this application.
421 private List
<TMenu
> subMenus
;
424 * The currently acive menu.
426 private TMenu activeMenu
= null;
429 * Active keyboard accelerators.
431 private Map
<TKeypress
, TMenuItem
> accelerators
;
436 private List
<TMenuItem
> menuItems
;
439 * Windows and widgets pull colors from this ColorTheme.
441 private ColorTheme theme
;
444 * Get the color theme.
448 public final ColorTheme
getTheme() {
453 * The top-level windows (but not menus).
455 private List
<TWindow
> windows
;
458 * Timers that are being ticked.
460 private List
<TTimer
> timers
;
463 * When true, exit the application.
465 private volatile boolean quit
= false;
468 * When true, repaint the entire screen.
470 private volatile boolean repaint
= true;
473 * Y coordinate of the top edge of the desktop. For now this is a
474 * constant. Someday it would be nice to have a multi-line menu or
477 private static final int desktopTop
= 1;
480 * Get Y coordinate of the top edge of the desktop.
482 * @return Y coordinate of the top edge of the desktop
484 public final int getDesktopTop() {
489 * Y coordinate of the bottom edge of the desktop.
491 private int desktopBottom
;
494 * Get Y coordinate of the bottom edge of the desktop.
496 * @return Y coordinate of the bottom edge of the desktop
498 public final int getDesktopBottom() {
499 return desktopBottom
;
503 * Public constructor.
505 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
507 * @throws UnsupportedEncodingException if an exception is thrown when
508 * creating the InputStreamReader
510 public TApplication(final BackendType backendType
)
511 throws UnsupportedEncodingException
{
513 switch (backendType
) {
515 backend
= new SwingBackend(this);
520 backend
= new ECMA48Backend(this, null, null);
523 throw new IllegalArgumentException("Invalid backend type: "
530 * Public constructor. The backend type will be BackendType.ECMA48.
532 * @param input an InputStream connected to the remote user, or null for
533 * System.in. If System.in is used, then on non-Windows systems it will
534 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
535 * mode. input is always converted to a Reader with UTF-8 encoding.
536 * @param output an OutputStream connected to the remote user, or null
537 * for System.out. output is always converted to a Writer with UTF-8
539 * @throws UnsupportedEncodingException if an exception is thrown when
540 * creating the InputStreamReader
542 public TApplication(final InputStream input
,
543 final OutputStream output
) throws UnsupportedEncodingException
{
545 backend
= new ECMA48Backend(this, input
, output
);
550 * Public constructor. This hook enables use with new non-Jexer
553 * @param backend a Backend that is already ready to go.
555 public TApplication(final Backend backend
) {
556 this.backend
= backend
;
561 * Finish construction once the backend is set.
563 private void TApplicationImpl() {
564 theme
= new ColorTheme();
565 desktopBottom
= getScreen().getHeight() - 1;
566 fillEventQueue
= new ArrayList
<TInputEvent
>();
567 drainEventQueue
= new ArrayList
<TInputEvent
>();
568 windows
= new LinkedList
<TWindow
>();
569 menus
= new LinkedList
<TMenu
>();
570 subMenus
= new LinkedList
<TMenu
>();
571 timers
= new LinkedList
<TTimer
>();
572 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
573 menuItems
= new ArrayList
<TMenuItem
>();
575 // Setup the main consumer thread
576 primaryEventHandler
= new WidgetEventHandler(this, true);
577 (new Thread(primaryEventHandler
)).start();
581 * Invert the cell color at a position. This is used to track the mouse.
583 * @param x column position
584 * @param y row position
586 private void invertCell(final int x
, final int y
) {
587 synchronized (getScreen()) {
588 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
589 attr
.setForeColor(attr
.getForeColor().invert());
590 attr
.setBackColor(attr
.getBackColor().invert());
591 getScreen().putAttrXY(x
, y
, attr
, false);
598 private void drawAll() {
600 System
.err
.printf("drawAll() enter\n");
604 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
605 // The only thing that has happened is the mouse moved.
606 // Clear the old position and draw the new position.
607 invertCell(oldMouseX
, oldMouseY
);
608 invertCell(mouseX
, mouseY
);
612 if (getScreen().isDirty()) {
613 backend
.flushScreen();
619 System
.err
.printf("drawAll() REDRAW\n");
622 // If true, the cursor is not visible
623 boolean cursor
= false;
625 // Start with a clean screen
628 // Draw the background
629 CellAttributes background
= theme
.getColor("tapplication.background");
630 getScreen().putAll(GraphicsChars
.HATCH
, background
);
632 // Draw each window in reverse Z order
633 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
634 Collections
.sort(sorted
);
635 Collections
.reverse(sorted
);
636 for (TWindow window
: sorted
) {
637 window
.drawChildren();
640 // Draw the blank menubar line - reset the screen clipping first so
641 // it won't trim it out.
642 getScreen().resetClipping();
643 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
644 theme
.getColor("tmenu"));
645 // Now draw the menus.
647 for (TMenu menu
: menus
) {
648 CellAttributes menuColor
;
649 CellAttributes menuMnemonicColor
;
650 if (menu
.isActive()) {
651 menuColor
= theme
.getColor("tmenu.highlighted");
652 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
654 menuColor
= theme
.getColor("tmenu");
655 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
657 // Draw the menu title
658 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
660 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
661 // Draw the highlight character
662 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
663 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
665 if (menu
.isActive()) {
667 // Reset the screen clipping so we can draw the next title.
668 getScreen().resetClipping();
670 x
+= menu
.getTitle().length() + 2;
673 for (TMenu menu
: subMenus
) {
674 // Reset the screen clipping so we can draw the next sub-menu.
675 getScreen().resetClipping();
679 // Draw the mouse pointer
680 invertCell(mouseX
, mouseY
);
682 // Place the cursor if it is visible
683 TWidget activeWidget
= null;
684 if (sorted
.size() > 0) {
685 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
686 if (activeWidget
.isCursorVisible()) {
687 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
688 activeWidget
.getCursorAbsoluteY());
695 getScreen().hideCursor();
698 // Flush the screen contents
699 backend
.flushScreen();
705 * Run this application until it exits.
709 // Timeout is in milliseconds, so default timeout after 1 second
713 // If I've got no updates to render, wait for something from the
714 // backend or a timer.
716 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
718 // Never sleep longer than 50 millis. We need time for
719 // windows with background tasks to update the display, and
720 // still flip buffers reasonably quickly in
721 // backend.flushPhysical().
722 timeout
= getSleepTime(50);
726 // As of now, I've got nothing to do: no I/O, nothing from
727 // the consumer threads, no timers that need to run ASAP. So
728 // wait until either the backend or the consumer threads have
731 synchronized (this) {
734 } catch (InterruptedException e
) {
735 // I'm awake and don't care why, let's see what's going
741 // Prevent stepping on the primary or secondary event handler.
744 // Pull any pending I/O events
745 backend
.getEvents(fillEventQueue
);
747 // Dispatch each event to the appropriate handler, one at a time.
749 TInputEvent event
= null;
750 if (fillEventQueue
.size() == 0) {
753 event
= fillEventQueue
.remove(0);
754 metaHandleEvent(event
);
757 // Wake a consumer thread if we have any pending events.
758 if (drainEventQueue
.size() > 0) {
762 // Process timers and call doIdle()'s
766 synchronized (getScreen()) {
770 // Let the event handlers run again.
771 startEventHandlers();
775 // Shutdown the event consumer threads
776 if (secondaryEventHandler
!= null) {
777 synchronized (secondaryEventHandler
) {
778 secondaryEventHandler
.notify();
781 if (primaryEventHandler
!= null) {
782 synchronized (primaryEventHandler
) {
783 primaryEventHandler
.notify();
787 // Shutdown the user I/O thread(s)
790 // Close all the windows. This gives them an opportunity to release
797 * Peek at certain application-level events, add to eventQueue, and wake
798 * up the consuming Thread.
800 * @param event the input event to consume
802 private void metaHandleEvent(final TInputEvent event
) {
805 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
806 event
)); System
.err
.flush();
810 // Do no more processing if the application is already trying
815 // Special application-wide events -------------------------------
818 if (event
instanceof TCommandEvent
) {
819 TCommandEvent command
= (TCommandEvent
) event
;
820 if (command
.getCmd().equals(cmAbort
)) {
827 if (event
instanceof TResizeEvent
) {
828 TResizeEvent resize
= (TResizeEvent
) event
;
829 synchronized (getScreen()) {
830 getScreen().setDimensions(resize
.getWidth(),
832 desktopBottom
= getScreen().getHeight() - 1;
841 // Peek at the mouse position
842 if (event
instanceof TMouseEvent
) {
843 TMouseEvent mouse
= (TMouseEvent
) event
;
844 synchronized (getScreen()) {
845 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
848 mouseX
= mouse
.getX();
849 mouseY
= mouse
.getY();
854 // Put into the main queue
855 drainEventQueue
.add(event
);
859 * Dispatch one event to the appropriate widget or application-level
860 * event handler. This is the primary event handler, it has the normal
861 * application-wide event handling.
863 * @param event the input event to consume
864 * @see #secondaryHandleEvent(TInputEvent event)
866 private void primaryHandleEvent(final TInputEvent event
) {
869 System
.err
.printf("Handle event: %s\n", event
);
872 // Special application-wide events -----------------------------------
874 // Peek at the mouse position
875 if (event
instanceof TMouseEvent
) {
876 // See if we need to switch focus to another window or the menu
877 checkSwitchFocus((TMouseEvent
) event
);
880 // Handle menu events
881 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
882 TMenu menu
= activeMenu
;
884 if (event
instanceof TMouseEvent
) {
885 TMouseEvent mouse
= (TMouseEvent
) event
;
887 while (subMenus
.size() > 0) {
888 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
889 if (subMenu
.mouseWouldHit(mouse
)) {
892 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
893 && (!mouse
.isMouse1())
894 && (!mouse
.isMouse2())
895 && (!mouse
.isMouse3())
896 && (!mouse
.isMouseWheelUp())
897 && (!mouse
.isMouseWheelDown())
901 // We navigated away from a sub-menu, so close it
905 // Convert the mouse relative x/y to menu coordinates
906 assert (mouse
.getX() == mouse
.getAbsoluteX());
907 assert (mouse
.getY() == mouse
.getAbsoluteY());
908 if (subMenus
.size() > 0) {
909 menu
= subMenus
.get(subMenus
.size() - 1);
911 mouse
.setX(mouse
.getX() - menu
.getX());
912 mouse
.setY(mouse
.getY() - menu
.getY());
914 menu
.handleEvent(event
);
918 if (event
instanceof TKeypressEvent
) {
919 TKeypressEvent keypress
= (TKeypressEvent
) event
;
921 // See if this key matches an accelerator, and if so dispatch the
923 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
924 TMenuItem item
= null;
925 synchronized (accelerators
) {
926 item
= accelerators
.get(keypressLowercase
);
929 if (item
.isEnabled()) {
930 // Let the menu item dispatch
935 // Handle the keypress
936 if (onKeypress(keypress
)) {
941 if (event
instanceof TCommandEvent
) {
942 if (onCommand((TCommandEvent
) event
)) {
947 if (event
instanceof TMenuEvent
) {
948 if (onMenu((TMenuEvent
) event
)) {
953 // Dispatch events to the active window -------------------------------
954 for (TWindow window
: windows
) {
955 if (window
.isActive()) {
956 if (event
instanceof TMouseEvent
) {
957 TMouseEvent mouse
= (TMouseEvent
) event
;
958 // Convert the mouse relative x/y to window coordinates
959 assert (mouse
.getX() == mouse
.getAbsoluteX());
960 assert (mouse
.getY() == mouse
.getAbsoluteY());
961 mouse
.setX(mouse
.getX() - window
.getX());
962 mouse
.setY(mouse
.getY() - window
.getY());
965 System
.err
.printf("TApplication dispatch event: %s\n",
968 window
.handleEvent(event
);
974 * Dispatch one event to the appropriate widget or application-level
975 * event handler. This is the secondary event handler used by certain
976 * special dialogs (currently TMessageBox and TFileOpenBox).
978 * @param event the input event to consume
979 * @see #primaryHandleEvent(TInputEvent event)
981 private void secondaryHandleEvent(final TInputEvent event
) {
982 secondaryEventReceiver
.handleEvent(event
);
986 * Enable a widget to override the primary event thread.
988 * @param widget widget that will receive events
990 public final void enableSecondaryEventReceiver(final TWidget widget
) {
991 assert (secondaryEventReceiver
== null);
992 assert (secondaryEventHandler
== null);
993 assert ((widget
instanceof TMessageBox
)
994 || (widget
instanceof TFileOpenBox
));
995 secondaryEventReceiver
= widget
;
996 secondaryEventHandler
= new WidgetEventHandler(this, false);
997 (new Thread(secondaryEventHandler
)).start();
1001 * Yield to the secondary thread.
1003 public final void yield() {
1004 assert (secondaryEventReceiver
!= null);
1005 // This is where we handoff the event handler lock from the primary
1006 // to secondary thread. We unlock here, and in a future loop the
1007 // secondary thread locks again. When it gives up, we have the
1008 // single lock back.
1009 boolean oldLock
= unlockHandleEvent();
1012 while (secondaryEventReceiver
!= null) {
1013 synchronized (primaryEventHandler
) {
1015 primaryEventHandler
.wait();
1016 } catch (InterruptedException e
) {
1024 * Do stuff when there is no user input.
1026 private void doIdle() {
1028 System
.err
.printf("doIdle()\n");
1031 // Now run any timers that have timed out
1032 Date now
= new Date();
1033 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1034 for (TTimer timer
: timers
) {
1035 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1037 if (timer
.recurring
) {
1038 keepTimers
.add(timer
);
1041 keepTimers
.add(timer
);
1044 timers
= keepTimers
;
1047 for (TWindow window
: windows
) {
1053 * Get the amount of time I can sleep before missing a Timer tick.
1055 * @param timeout = initial (maximum) timeout in millis
1056 * @return number of milliseconds between now and the next timer event
1058 private long getSleepTime(final long timeout
) {
1059 Date now
= new Date();
1060 long nowTime
= now
.getTime();
1061 long sleepTime
= timeout
;
1062 for (TTimer timer
: timers
) {
1063 long nextTickTime
= timer
.getNextTick().getTime();
1064 if (nextTickTime
< nowTime
) {
1068 long timeDifference
= nextTickTime
- nowTime
;
1069 if (timeDifference
< sleepTime
) {
1070 sleepTime
= timeDifference
;
1073 assert (sleepTime
>= 0);
1074 assert (sleepTime
<= timeout
);
1079 * Close window. Note that the window's destructor is NOT called by this
1080 * method, instead the GC is assumed to do the cleanup.
1082 * @param window the window to remove
1084 public final void closeWindow(final TWindow window
) {
1085 synchronized (windows
) {
1086 int z
= window
.getZ();
1089 Collections
.sort(windows
);
1091 TWindow activeWindow
= null;
1092 for (TWindow w
: windows
) {
1094 w
.setZ(w
.getZ() - 1);
1095 if (w
.getZ() == 0) {
1098 assert (activeWindow
== null);
1110 // Perform window cleanup
1113 // Check if we are closing a TMessageBox or similar
1114 if (secondaryEventReceiver
!= null) {
1115 assert (secondaryEventHandler
!= null);
1117 // Do not send events to the secondaryEventReceiver anymore, the
1118 // window is closed.
1119 secondaryEventReceiver
= null;
1121 // Wake the secondary thread, it will wake the primary as it
1123 synchronized (secondaryEventHandler
) {
1124 secondaryEventHandler
.notify();
1130 * Switch to the next window.
1132 * @param forward if true, then switch to the next window in the list,
1133 * otherwise switch to the previous window in the list
1135 public final void switchWindow(final boolean forward
) {
1136 // Only switch if there are multiple windows
1137 if (windows
.size() < 2) {
1141 synchronized (windows
) {
1143 // Swap z/active between active window and the next in the list
1144 int activeWindowI
= -1;
1145 for (int i
= 0; i
< windows
.size(); i
++) {
1146 if (windows
.get(i
).isActive()) {
1151 assert (activeWindowI
>= 0);
1153 // Do not switch if a window is modal
1154 if (windows
.get(activeWindowI
).isModal()) {
1160 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1162 if (activeWindowI
== 0) {
1163 nextWindowI
= windows
.size() - 1;
1165 nextWindowI
= activeWindowI
- 1;
1168 windows
.get(activeWindowI
).setActive(false);
1169 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1170 windows
.get(activeWindowI
).onUnfocus();
1171 windows
.get(nextWindowI
).setZ(0);
1172 windows
.get(nextWindowI
).setActive(true);
1173 windows
.get(nextWindowI
).onFocus();
1175 } // synchronized (windows)
1180 * Add a window to my window list and make it active.
1182 * @param window new window to add
1184 public final void addWindow(final TWindow window
) {
1185 synchronized (windows
) {
1186 // Do not allow a modal window to spawn a non-modal window
1187 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1188 assert (window
.isModal());
1190 for (TWindow w
: windows
) {
1195 w
.setZ(w
.getZ() + 1);
1197 windows
.add(window
);
1199 window
.setActive(true);
1205 * Check if there is a system-modal window on top.
1207 * @return true if the active window is modal
1209 private boolean modalWindowActive() {
1210 if (windows
.size() == 0) {
1213 return windows
.get(windows
.size() - 1).isModal();
1217 * Check if a mouse event would hit either the active menu or any open
1220 * @param mouse mouse event
1221 * @return true if the mouse would hit the active menu or an open
1224 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1225 assert (activeMenu
!= null);
1226 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1227 Collections
.reverse(menus
);
1228 for (TMenu menu
: menus
) {
1229 if (menu
.mouseWouldHit(mouse
)) {
1233 return activeMenu
.mouseWouldHit(mouse
);
1237 * See if we need to switch window or activate the menu based on
1240 * @param mouse mouse event
1242 private void checkSwitchFocus(final TMouseEvent mouse
) {
1244 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1245 && (activeMenu
!= null)
1246 && (mouse
.getAbsoluteY() != 0)
1247 && (!mouseOnMenu(mouse
))
1249 // They clicked outside the active menu, turn it off
1250 activeMenu
.setActive(false);
1252 for (TMenu menu
: subMenus
) {
1253 menu
.setActive(false);
1259 // See if they hit the menu bar
1260 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1261 && (mouse
.isMouse1())
1262 && (!modalWindowActive())
1263 && (mouse
.getAbsoluteY() == 0)
1266 for (TMenu menu
: subMenus
) {
1267 menu
.setActive(false);
1271 // They selected the menu, go activate it
1272 for (TMenu menu
: menus
) {
1273 if ((mouse
.getAbsoluteX() >= menu
.getX())
1274 && (mouse
.getAbsoluteX() < menu
.getX()
1275 + menu
.getTitle().length() + 2)
1277 menu
.setActive(true);
1280 menu
.setActive(false);
1286 // See if they hit the menu bar
1287 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1288 && (mouse
.isMouse1())
1289 && (activeMenu
!= null)
1290 && (mouse
.getAbsoluteY() == 0)
1293 TMenu oldMenu
= activeMenu
;
1294 for (TMenu menu
: subMenus
) {
1295 menu
.setActive(false);
1299 // See if we should switch menus
1300 for (TMenu menu
: menus
) {
1301 if ((mouse
.getAbsoluteX() >= menu
.getX())
1302 && (mouse
.getAbsoluteX() < menu
.getX()
1303 + menu
.getTitle().length() + 2)
1305 menu
.setActive(true);
1309 if (oldMenu
!= activeMenu
) {
1310 // They switched menus
1311 oldMenu
.setActive(false);
1316 // Only switch if there are multiple windows
1317 if (windows
.size() < 2) {
1321 // Switch on the upclick
1322 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1326 synchronized (windows
) {
1327 Collections
.sort(windows
);
1328 if (windows
.get(0).isModal()) {
1329 // Modal windows don't switch
1333 for (TWindow window
: windows
) {
1334 assert (!window
.isModal());
1335 if (window
.mouseWouldHit(mouse
)) {
1336 if (window
== windows
.get(0)) {
1337 // Clicked on the same window, nothing to do
1341 // We will be switching to another window
1342 assert (windows
.get(0).isActive());
1343 assert (!window
.isActive());
1344 windows
.get(0).onUnfocus();
1345 windows
.get(0).setActive(false);
1346 windows
.get(0).setZ(window
.getZ());
1348 window
.setActive(true);
1355 // Clicked on the background, nothing to do
1360 * Turn off the menu.
1362 public final void closeMenu() {
1363 if (activeMenu
!= null) {
1364 activeMenu
.setActive(false);
1366 for (TMenu menu
: subMenus
) {
1367 menu
.setActive(false);
1374 * Turn off a sub-menu.
1376 public final void closeSubMenu() {
1377 assert (activeMenu
!= null);
1378 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1379 assert (item
!= null);
1380 item
.setActive(false);
1381 subMenus
.remove(subMenus
.size() - 1);
1385 * Switch to the next menu.
1387 * @param forward if true, then switch to the next menu in the list,
1388 * otherwise switch to the previous menu in the list
1390 public final void switchMenu(final boolean forward
) {
1391 assert (activeMenu
!= null);
1393 for (TMenu menu
: subMenus
) {
1394 menu
.setActive(false);
1398 for (int i
= 0; i
< menus
.size(); i
++) {
1399 if (activeMenu
== menus
.get(i
)) {
1401 if (i
< menus
.size() - 1) {
1409 activeMenu
.setActive(false);
1410 activeMenu
= menus
.get(i
);
1411 activeMenu
.setActive(true);
1418 * Method that TApplication subclasses can override to handle menu or
1419 * posted command events.
1421 * @param command command event
1422 * @return if true, this event was consumed
1424 protected boolean onCommand(final TCommandEvent command
) {
1425 // Default: handle cmExit
1426 if (command
.equals(cmExit
)) {
1427 if (messageBox("Confirmation", "Exit application?",
1428 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1434 if (command
.equals(cmShell
)) {
1435 openTerminal(0, 0, TWindow
.RESIZABLE
);
1439 if (command
.equals(cmTile
)) {
1443 if (command
.equals(cmCascade
)) {
1447 if (command
.equals(cmCloseAll
)) {
1456 * Method that TApplication subclasses can override to handle menu
1459 * @param menu menu event
1460 * @return if true, this event was consumed
1462 protected boolean onMenu(final TMenuEvent menu
) {
1464 // Default: handle MID_EXIT
1465 if (menu
.getId() == TMenu
.MID_EXIT
) {
1466 if (messageBox("Confirmation", "Exit application?",
1467 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1473 if (menu
.getId() == TMenu
.MID_SHELL
) {
1474 openTerminal(0, 0, TWindow
.RESIZABLE
);
1478 if (menu
.getId() == TMenu
.MID_TILE
) {
1482 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1486 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1494 * Method that TApplication subclasses can override to handle keystrokes.
1496 * @param keypress keystroke event
1497 * @return if true, this event was consumed
1499 protected boolean onKeypress(final TKeypressEvent keypress
) {
1500 // Default: only menu shortcuts
1502 // Process Alt-F, Alt-E, etc. menu shortcut keys
1503 if (!keypress
.getKey().isFnKey()
1504 && keypress
.getKey().isAlt()
1505 && !keypress
.getKey().isCtrl()
1506 && (activeMenu
== null)
1509 assert (subMenus
.size() == 0);
1511 for (TMenu menu
: menus
) {
1512 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1513 == Character
.toLowerCase(keypress
.getKey().getChar())
1516 menu
.setActive(true);
1526 * Add a menu item to the global list. If it has a keyboard accelerator,
1527 * that will be added the global hash.
1529 * @param item the menu item
1531 public final void addMenuItem(final TMenuItem item
) {
1532 menuItems
.add(item
);
1534 TKeypress key
= item
.getKey();
1536 synchronized (accelerators
) {
1537 assert (accelerators
.get(key
) == null);
1538 accelerators
.put(key
.toLowerCase(), item
);
1544 * Disable one menu item.
1546 * @param id the menu item ID
1548 public final void disableMenuItem(final int id
) {
1549 for (TMenuItem item
: menuItems
) {
1550 if (item
.getId() == id
) {
1551 item
.setEnabled(false);
1557 * Disable the range of menu items with ID's between lower and upper,
1560 * @param lower the lowest menu item ID
1561 * @param upper the highest menu item ID
1563 public final void disableMenuItems(final int lower
, final int upper
) {
1564 for (TMenuItem item
: menuItems
) {
1565 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1566 item
.setEnabled(false);
1572 * Enable one menu item.
1574 * @param id the menu item ID
1576 public final void enableMenuItem(final int id
) {
1577 for (TMenuItem item
: menuItems
) {
1578 if (item
.getId() == id
) {
1579 item
.setEnabled(true);
1585 * Enable the range of menu items with ID's between lower and upper,
1588 * @param lower the lowest menu item ID
1589 * @param upper the highest menu item ID
1591 public final void enableMenuItems(final int lower
, final int upper
) {
1592 for (TMenuItem item
: menuItems
) {
1593 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1594 item
.setEnabled(true);
1600 * Recompute menu x positions based on their title length.
1602 public final void recomputeMenuX() {
1604 for (TMenu menu
: menus
) {
1606 x
+= menu
.getTitle().length() + 2;
1611 * Post an event to process and turn off the menu.
1613 * @param event new event to add to the queue
1615 public final void addMenuEvent(final TInputEvent event
) {
1616 synchronized (fillEventQueue
) {
1617 fillEventQueue
.add(event
);
1623 * Add a sub-menu to the list of open sub-menus.
1625 * @param menu sub-menu
1627 public final void addSubMenu(final TMenu menu
) {
1632 * Convenience function to add a top-level menu.
1634 * @param title menu title
1635 * @return the new menu
1637 public final TMenu
addMenu(final String title
) {
1640 TMenu menu
= new TMenu(this, x
, y
, title
);
1647 * Convenience function to add a default "File" menu.
1649 * @return the new menu
1651 public final TMenu
addFileMenu() {
1652 TMenu fileMenu
= addMenu("&File");
1653 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1654 fileMenu
.addSeparator();
1655 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1656 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1661 * Convenience function to add a default "Edit" menu.
1663 * @return the new menu
1665 public final TMenu
addEditMenu() {
1666 TMenu editMenu
= addMenu("&Edit");
1667 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1668 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1669 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1670 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1675 * Convenience function to add a default "Window" menu.
1677 * @return the new menu
1679 public final TMenu
addWindowMenu() {
1680 TMenu windowMenu
= addMenu("&Window");
1681 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1682 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1683 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1684 windowMenu
.addSeparator();
1685 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1686 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1687 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1688 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1689 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1694 * Close all open windows.
1696 private void closeAllWindows() {
1697 // Don't do anything if we are in the menu
1698 if (activeMenu
!= null) {
1702 synchronized (windows
) {
1703 for (TWindow window
: windows
) {
1704 closeWindow(window
);
1710 * Re-layout the open windows as non-overlapping tiles. This produces
1711 * almost the same results as Turbo Pascal 7.0's IDE.
1713 private void tileWindows() {
1714 synchronized (windows
) {
1715 // Don't do anything if we are in the menu
1716 if (activeMenu
!= null) {
1719 int z
= windows
.size();
1725 a
= (int)(Math
.sqrt(z
));
1729 if (((a
* b
) + c
) == z
) {
1737 int newWidth
= (getScreen().getWidth() / a
);
1738 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1739 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1741 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1742 Collections
.sort(sorted
);
1743 Collections
.reverse(sorted
);
1744 for (int i
= 0; i
< sorted
.size(); i
++) {
1745 int logicalX
= i
/ b
;
1746 int logicalY
= i
% b
;
1747 if (i
>= ((a
- 1) * b
)) {
1749 logicalY
= i
- ((a
- 1) * b
);
1752 TWindow w
= sorted
.get(i
);
1753 w
.setX(logicalX
* newWidth
);
1754 w
.setWidth(newWidth
);
1755 if (i
>= ((a
- 1) * b
)) {
1756 w
.setY((logicalY
* newHeight2
) + 1);
1757 w
.setHeight(newHeight2
);
1759 w
.setY((logicalY
* newHeight1
) + 1);
1760 w
.setHeight(newHeight1
);
1767 * Re-layout the open windows as overlapping cascaded windows.
1769 private void cascadeWindows() {
1770 synchronized (windows
) {
1771 // Don't do anything if we are in the menu
1772 if (activeMenu
!= null) {
1777 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1778 Collections
.sort(sorted
);
1779 Collections
.reverse(sorted
);
1780 for (TWindow window
: sorted
) {
1785 if (x
> getScreen().getWidth()) {
1788 if (y
>= getScreen().getHeight()) {
1796 * Convenience function to add a timer.
1798 * @param duration number of milliseconds to wait between ticks
1799 * @param recurring if true, re-schedule this timer after every tick
1800 * @param action function to call when button is pressed
1803 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1804 final TAction action
) {
1806 TTimer timer
= new TTimer(duration
, recurring
, action
);
1807 synchronized (timers
) {
1814 * Convenience function to remove a timer.
1816 * @param timer timer to remove
1818 public final void removeTimer(final TTimer timer
) {
1819 synchronized (timers
) {
1820 timers
.remove(timer
);
1825 * Convenience function to spawn a message box.
1827 * @param title window title, will be centered along the top border
1828 * @param caption message to display. Use embedded newlines to get a
1830 * @return the new message box
1832 public final TMessageBox
messageBox(final String title
,
1833 final String caption
) {
1835 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1839 * Convenience function to spawn a message box.
1841 * @param title window title, will be centered along the top border
1842 * @param caption message to display. Use embedded newlines to get a
1844 * @param type one of the TMessageBox.Type constants. Default is
1846 * @return the new message box
1848 public final TMessageBox
messageBox(final String title
,
1849 final String caption
, final TMessageBox
.Type type
) {
1851 return new TMessageBox(this, title
, caption
, type
);
1855 * Convenience function to spawn an input box.
1857 * @param title window title, will be centered along the top border
1858 * @param caption message to display. Use embedded newlines to get a
1860 * @return the new input box
1862 public final TInputBox
inputBox(final String title
, final String caption
) {
1864 return new TInputBox(this, title
, caption
);
1868 * Convenience function to spawn an input box.
1870 * @param title window title, will be centered along the top border
1871 * @param caption message to display. Use embedded newlines to get a
1873 * @param text initial text to seed the field with
1874 * @return the new input box
1876 public final TInputBox
inputBox(final String title
, final String caption
,
1877 final String text
) {
1879 return new TInputBox(this, title
, caption
, text
);
1883 * Convenience function to open a terminal window.
1885 * @param x column relative to parent
1886 * @param y row relative to parent
1887 * @return the terminal new window
1889 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1890 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1894 * Convenience function to open a terminal window.
1896 * @param x column relative to parent
1897 * @param y row relative to parent
1898 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1899 * @return the terminal new window
1901 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1904 return new TTerminalWindow(this, x
, y
, flags
);
1908 * Convenience function to spawn an file open box.
1910 * @param path path of selected file
1911 * @return the result of the new file open box
1912 * @throws IOException if java.io operation throws
1914 public final String
fileOpenBox(final String path
) throws IOException
{
1916 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
1917 return box
.getFilename();
1921 * Convenience function to spawn an file open box.
1923 * @param path path of selected file
1924 * @param type one of the Type constants
1925 * @return the result of the new file open box
1926 * @throws IOException if java.io operation throws
1928 public final String
fileOpenBox(final String path
,
1929 final TFileOpenBox
.Type type
) throws IOException
{
1931 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
1932 return box
.getFilename();