2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2016 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
31 import java
.io
.InputStream
;
32 import java
.io
.IOException
;
33 import java
.io
.OutputStream
;
34 import java
.io
.UnsupportedEncodingException
;
35 import java
.util
.Collections
;
36 import java
.util
.Date
;
37 import java
.util
.HashMap
;
38 import java
.util
.ArrayList
;
39 import java
.util
.LinkedList
;
40 import java
.util
.List
;
43 import jexer
.bits
.CellAttributes
;
44 import jexer
.bits
.ColorTheme
;
45 import jexer
.bits
.GraphicsChars
;
46 import jexer
.event
.TCommandEvent
;
47 import jexer
.event
.TInputEvent
;
48 import jexer
.event
.TKeypressEvent
;
49 import jexer
.event
.TMenuEvent
;
50 import jexer
.event
.TMouseEvent
;
51 import jexer
.event
.TResizeEvent
;
52 import jexer
.backend
.Backend
;
53 import jexer
.backend
.SwingBackend
;
54 import jexer
.backend
.ECMA48Backend
;
55 import jexer
.io
.Screen
;
56 import jexer
.menu
.TMenu
;
57 import jexer
.menu
.TMenuItem
;
58 import static jexer
.TCommand
.*;
61 * TApplication sets up a full Text User Interface application.
63 public class TApplication
implements Runnable
{
66 * If true, emit thread stuff to System.err.
68 private static final boolean debugThreads
= false;
71 * If true, emit events being processed to System.err.
73 private static final boolean debugEvents
= false;
76 * Two backend types are available.
78 public static enum BackendType
{
85 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
96 * WidgetEventHandler is the main event consumer loop. There are at most
97 * two such threads in existence: the primary for normal case and a
98 * secondary that is used for TMessageBox, TInputBox, and similar.
100 private class WidgetEventHandler
implements Runnable
{
102 * The main application.
104 private TApplication application
;
107 * Whether or not this WidgetEventHandler is the primary or secondary
110 private boolean primary
= true;
113 * Public constructor.
115 * @param application the main application
116 * @param primary if true, this is the primary event handler thread
118 public WidgetEventHandler(final TApplication application
,
119 final boolean primary
) {
121 this.application
= application
;
122 this.primary
= primary
;
131 while (!application
.quit
) {
133 // Wait until application notifies me
134 while (!application
.quit
) {
136 synchronized (application
.drainEventQueue
) {
137 if (application
.drainEventQueue
.size() > 0) {
142 synchronized (this) {
144 System
.err
.printf("%s %s sleep\n", this,
145 primary ?
"primary" : "secondary");
151 System
.err
.printf("%s %s AWAKE\n", this,
152 primary ?
"primary" : "secondary");
156 && (application
.secondaryEventReceiver
== null)
158 // Secondary thread, emergency exit. If we
159 // got here then something went wrong with
160 // the handoff between yield() and
162 synchronized (application
.primaryEventHandler
) {
163 application
.primaryEventHandler
.notify();
165 application
.secondaryEventHandler
= null;
166 throw new RuntimeException(
167 "secondary exited at wrong time");
171 } catch (InterruptedException e
) {
176 // Wait for drawAll() or doIdle() to be done, then handle the
178 boolean oldLock
= lockHandleEvent();
179 assert (oldLock
== false);
181 // Pull all events off the queue
183 TInputEvent event
= null;
184 synchronized (application
.drainEventQueue
) {
185 if (application
.drainEventQueue
.size() == 0) {
188 event
= application
.drainEventQueue
.remove(0);
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;
216 // Unlock. Either I am primary thread, or I am secondary
217 // thread and still running.
218 oldLock
= unlockHandleEvent();
219 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 // Backoff so that the backend can finish its work.
288 } catch (InterruptedException e
) {
293 oldValue
= insideHandleEvent
;
294 insideHandleEvent
= true;
298 System
.err
.printf(" ***\n");
304 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
305 * spin indefinitely until unlockHandleEvent() is called.
307 * @return the old value of insideHandleEvent
309 private boolean unlockHandleEvent() {
311 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
314 synchronized (this) {
315 boolean oldValue
= insideHandleEvent
;
316 insideHandleEvent
= false;
322 * Spinlock for the primary and secondary event handlers. When true, the
323 * event handlers will spinlock wait before calling handleEvent().
325 private volatile boolean lockoutHandleEvent
= false;
328 * TApplication.run() needs to be able rely on the global data structures
329 * being intact when calling doIdle() and drawAll(). Tell the event
330 * handlers to wait for an unlock before handling their events.
332 private void stopEventHandlers() {
334 System
.err
.printf(">> stopEventHandlers()");
337 lockoutHandleEvent
= true;
338 // Wait for the last event to finish processing before returning
339 // control to TApplication.run().
340 while (insideHandleEvent
== true) {
342 // Backoff so that the event handler can finish its work.
344 } catch (InterruptedException e
) {
350 System
.err
.printf(" XXX\n");
355 * TApplication.run() needs to be able rely on the global data structures
356 * being intact when calling doIdle() and drawAll(). Tell the event
357 * handlers that it is now OK to handle their events.
359 private void startEventHandlers() {
361 System
.err
.printf("<< startEventHandlers()\n");
363 lockoutHandleEvent
= false;
367 * Access to the physical screen, keyboard, and mouse.
369 private Backend backend
;
376 public final Screen
getScreen() {
377 return backend
.getScreen();
381 * Actual mouse coordinate X.
386 * Actual mouse coordinate Y.
391 * Old version of mouse coordinate X.
393 private int oldMouseX
;
396 * Old version mouse coordinate Y.
398 private int oldMouseY
;
401 * Event queue that is filled by run().
403 private List
<TInputEvent
> fillEventQueue
;
406 * Event queue that will be drained by either primary or secondary
409 private List
<TInputEvent
> drainEventQueue
;
412 * Top-level menus in this application.
414 private List
<TMenu
> menus
;
417 * Stack of activated sub-menus in this application.
419 private List
<TMenu
> subMenus
;
422 * The currently acive menu.
424 private TMenu activeMenu
= null;
427 * Active keyboard accelerators.
429 private Map
<TKeypress
, TMenuItem
> accelerators
;
434 private List
<TMenuItem
> menuItems
;
437 * Windows and widgets pull colors from this ColorTheme.
439 private ColorTheme theme
;
442 * Get the color theme.
446 public final ColorTheme
getTheme() {
451 * The top-level windows (but not menus).
453 private List
<TWindow
> windows
;
456 * Timers that are being ticked.
458 private List
<TTimer
> timers
;
461 * When true, exit the application.
463 private volatile boolean quit
= false;
466 * When true, repaint the entire screen.
468 private volatile boolean repaint
= true;
471 * Y coordinate of the top edge of the desktop. For now this is a
472 * constant. Someday it would be nice to have a multi-line menu or
475 private static final int desktopTop
= 1;
478 * Get Y coordinate of the top edge of the desktop.
480 * @return Y coordinate of the top edge of the desktop
482 public final int getDesktopTop() {
487 * Y coordinate of the bottom edge of the desktop.
489 private int desktopBottom
;
492 * Get Y coordinate of the bottom edge of the desktop.
494 * @return Y coordinate of the bottom edge of the desktop
496 public final int getDesktopBottom() {
497 return desktopBottom
;
501 * Public constructor.
503 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
505 * @throws UnsupportedEncodingException if an exception is thrown when
506 * creating the InputStreamReader
508 public TApplication(final BackendType backendType
)
509 throws UnsupportedEncodingException
{
511 switch (backendType
) {
513 backend
= new SwingBackend(this);
518 backend
= new ECMA48Backend(this, null, null);
521 throw new IllegalArgumentException("Invalid backend type: "
528 * Public constructor. The backend type will be BackendType.ECMA48.
530 * @param input an InputStream connected to the remote user, or null for
531 * System.in. If System.in is used, then on non-Windows systems it will
532 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
533 * mode. input is always converted to a Reader with UTF-8 encoding.
534 * @param output an OutputStream connected to the remote user, or null
535 * for System.out. output is always converted to a Writer with UTF-8
537 * @throws UnsupportedEncodingException if an exception is thrown when
538 * creating the InputStreamReader
540 public TApplication(final InputStream input
,
541 final OutputStream output
) throws UnsupportedEncodingException
{
543 backend
= new ECMA48Backend(this, input
, output
);
548 * Public constructor. This hook enables use with new non-Jexer
551 * @param backend a Backend that is already ready to go.
553 public TApplication(final Backend backend
) {
554 this.backend
= backend
;
559 * Finish construction once the backend is set.
561 private void TApplicationImpl() {
562 theme
= new ColorTheme();
563 desktopBottom
= getScreen().getHeight() - 1;
564 fillEventQueue
= new ArrayList
<TInputEvent
>();
565 drainEventQueue
= new ArrayList
<TInputEvent
>();
566 windows
= new LinkedList
<TWindow
>();
567 menus
= new LinkedList
<TMenu
>();
568 subMenus
= new LinkedList
<TMenu
>();
569 timers
= new LinkedList
<TTimer
>();
570 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
571 menuItems
= new ArrayList
<TMenuItem
>();
573 // Setup the main consumer thread
574 primaryEventHandler
= new WidgetEventHandler(this, true);
575 (new Thread(primaryEventHandler
)).start();
579 * Invert the cell color at a position. This is used to track the mouse.
581 * @param x column position
582 * @param y row position
584 private void invertCell(final int x
, final int y
) {
585 synchronized (getScreen()) {
586 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
587 attr
.setForeColor(attr
.getForeColor().invert());
588 attr
.setBackColor(attr
.getBackColor().invert());
589 getScreen().putAttrXY(x
, y
, attr
, false);
596 private void drawAll() {
598 System
.err
.printf("drawAll() enter\n");
602 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
603 // The only thing that has happened is the mouse moved.
604 // Clear the old position and draw the new position.
605 invertCell(oldMouseX
, oldMouseY
);
606 invertCell(mouseX
, mouseY
);
610 if (getScreen().isDirty()) {
611 backend
.flushScreen();
617 System
.err
.printf("drawAll() REDRAW\n");
620 // If true, the cursor is not visible
621 boolean cursor
= false;
623 // Start with a clean screen
626 // Draw the background
627 CellAttributes background
= theme
.getColor("tapplication.background");
628 getScreen().putAll(GraphicsChars
.HATCH
, background
);
630 // Draw each window in reverse Z order
631 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
632 Collections
.sort(sorted
);
633 Collections
.reverse(sorted
);
634 for (TWindow window
: sorted
) {
635 window
.drawChildren();
638 // Draw the blank menubar line - reset the screen clipping first so
639 // it won't trim it out.
640 getScreen().resetClipping();
641 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
642 theme
.getColor("tmenu"));
643 // Now draw the menus.
645 for (TMenu menu
: menus
) {
646 CellAttributes menuColor
;
647 CellAttributes menuMnemonicColor
;
648 if (menu
.isActive()) {
649 menuColor
= theme
.getColor("tmenu.highlighted");
650 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
652 menuColor
= theme
.getColor("tmenu");
653 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
655 // Draw the menu title
656 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
658 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
659 // Draw the highlight character
660 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
661 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
663 if (menu
.isActive()) {
665 // Reset the screen clipping so we can draw the next title.
666 getScreen().resetClipping();
668 x
+= menu
.getTitle().length() + 2;
671 for (TMenu menu
: subMenus
) {
672 // Reset the screen clipping so we can draw the next sub-menu.
673 getScreen().resetClipping();
677 // Draw the mouse pointer
678 invertCell(mouseX
, mouseY
);
680 // Place the cursor if it is visible
681 TWidget activeWidget
= null;
682 if (sorted
.size() > 0) {
683 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
684 if (activeWidget
.isCursorVisible()) {
685 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
686 activeWidget
.getCursorAbsoluteY());
693 getScreen().hideCursor();
696 // Flush the screen contents
697 backend
.flushScreen();
703 * Run this application until it exits.
707 // Timeout is in milliseconds, so default timeout after 1 second
711 // If I've got no updates to render, wait for something from the
712 // backend or a timer.
714 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
716 // Never sleep longer than 50 millis. We need time for
717 // windows with background tasks to update the display, and
718 // still flip buffers reasonably quickly in
719 // backend.flushPhysical().
720 timeout
= getSleepTime(50);
724 // As of now, I've got nothing to do: no I/O, nothing from
725 // the consumer threads, no timers that need to run ASAP. So
726 // wait until either the backend or the consumer threads have
729 synchronized (this) {
732 } catch (InterruptedException e
) {
733 // I'm awake and don't care why, let's see what's going
739 // Prevent stepping on the primary or secondary event handler.
742 // Pull any pending I/O events
743 backend
.getEvents(fillEventQueue
);
745 // Dispatch each event to the appropriate handler, one at a time.
747 TInputEvent event
= null;
748 if (fillEventQueue
.size() == 0) {
751 event
= fillEventQueue
.remove(0);
752 metaHandleEvent(event
);
755 // Wake a consumer thread if we have any pending events.
756 if (drainEventQueue
.size() > 0) {
760 // Process timers and call doIdle()'s
764 synchronized (getScreen()) {
768 // Let the event handlers run again.
769 startEventHandlers();
773 // Shutdown the event consumer threads
774 if (secondaryEventHandler
!= null) {
775 synchronized (secondaryEventHandler
) {
776 secondaryEventHandler
.notify();
779 if (primaryEventHandler
!= null) {
780 synchronized (primaryEventHandler
) {
781 primaryEventHandler
.notify();
785 // Shutdown the user I/O thread(s)
788 // Close all the windows. This gives them an opportunity to release
795 * Peek at certain application-level events, add to eventQueue, and wake
796 * up the consuming Thread.
798 * @param event the input event to consume
800 private void metaHandleEvent(final TInputEvent event
) {
803 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
804 event
)); System
.err
.flush();
808 // Do no more processing if the application is already trying
813 // Special application-wide events -------------------------------
816 if (event
instanceof TCommandEvent
) {
817 TCommandEvent command
= (TCommandEvent
) event
;
818 if (command
.getCmd().equals(cmAbort
)) {
825 if (event
instanceof TResizeEvent
) {
826 TResizeEvent resize
= (TResizeEvent
) event
;
827 synchronized (getScreen()) {
828 getScreen().setDimensions(resize
.getWidth(),
830 desktopBottom
= getScreen().getHeight() - 1;
839 // Peek at the mouse position
840 if (event
instanceof TMouseEvent
) {
841 TMouseEvent mouse
= (TMouseEvent
) event
;
842 synchronized (getScreen()) {
843 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
846 mouseX
= mouse
.getX();
847 mouseY
= mouse
.getY();
852 // Put into the main queue
853 drainEventQueue
.add(event
);
857 * Dispatch one event to the appropriate widget or application-level
858 * event handler. This is the primary event handler, it has the normal
859 * application-wide event handling.
861 * @param event the input event to consume
862 * @see #secondaryHandleEvent(TInputEvent event)
864 private void primaryHandleEvent(final TInputEvent event
) {
867 System
.err
.printf("Handle event: %s\n", event
);
870 // Special application-wide events -----------------------------------
872 // Peek at the mouse position
873 if (event
instanceof TMouseEvent
) {
874 // See if we need to switch focus to another window or the menu
875 checkSwitchFocus((TMouseEvent
) event
);
878 // Handle menu events
879 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
880 TMenu menu
= activeMenu
;
882 if (event
instanceof TMouseEvent
) {
883 TMouseEvent mouse
= (TMouseEvent
) event
;
885 while (subMenus
.size() > 0) {
886 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
887 if (subMenu
.mouseWouldHit(mouse
)) {
890 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
891 && (!mouse
.isMouse1())
892 && (!mouse
.isMouse2())
893 && (!mouse
.isMouse3())
894 && (!mouse
.isMouseWheelUp())
895 && (!mouse
.isMouseWheelDown())
899 // We navigated away from a sub-menu, so close it
903 // Convert the mouse relative x/y to menu coordinates
904 assert (mouse
.getX() == mouse
.getAbsoluteX());
905 assert (mouse
.getY() == mouse
.getAbsoluteY());
906 if (subMenus
.size() > 0) {
907 menu
= subMenus
.get(subMenus
.size() - 1);
909 mouse
.setX(mouse
.getX() - menu
.getX());
910 mouse
.setY(mouse
.getY() - menu
.getY());
912 menu
.handleEvent(event
);
916 if (event
instanceof TKeypressEvent
) {
917 TKeypressEvent keypress
= (TKeypressEvent
) event
;
919 // See if this key matches an accelerator, and if so dispatch the
921 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
922 TMenuItem item
= null;
923 synchronized (accelerators
) {
924 item
= accelerators
.get(keypressLowercase
);
927 if (item
.isEnabled()) {
928 // Let the menu item dispatch
933 // Handle the keypress
934 if (onKeypress(keypress
)) {
939 if (event
instanceof TCommandEvent
) {
940 if (onCommand((TCommandEvent
) event
)) {
945 if (event
instanceof TMenuEvent
) {
946 if (onMenu((TMenuEvent
) event
)) {
951 // Dispatch events to the active window -------------------------------
952 for (TWindow window
: windows
) {
953 if (window
.isActive()) {
954 if (event
instanceof TMouseEvent
) {
955 TMouseEvent mouse
= (TMouseEvent
) event
;
956 // Convert the mouse relative x/y to window coordinates
957 assert (mouse
.getX() == mouse
.getAbsoluteX());
958 assert (mouse
.getY() == mouse
.getAbsoluteY());
959 mouse
.setX(mouse
.getX() - window
.getX());
960 mouse
.setY(mouse
.getY() - window
.getY());
963 System
.err
.printf("TApplication dispatch event: %s\n",
966 window
.handleEvent(event
);
972 * Dispatch one event to the appropriate widget or application-level
973 * event handler. This is the secondary event handler used by certain
974 * special dialogs (currently TMessageBox and TFileOpenBox).
976 * @param event the input event to consume
977 * @see #primaryHandleEvent(TInputEvent event)
979 private void secondaryHandleEvent(final TInputEvent event
) {
980 secondaryEventReceiver
.handleEvent(event
);
984 * Enable a widget to override the primary event thread.
986 * @param widget widget that will receive events
988 public final void enableSecondaryEventReceiver(final TWidget widget
) {
989 assert (secondaryEventReceiver
== null);
990 assert (secondaryEventHandler
== null);
991 assert ((widget
instanceof TMessageBox
)
992 || (widget
instanceof TFileOpenBox
));
993 secondaryEventReceiver
= widget
;
994 secondaryEventHandler
= new WidgetEventHandler(this, false);
995 (new Thread(secondaryEventHandler
)).start();
999 * Yield to the secondary thread.
1001 public final void yield() {
1002 assert (secondaryEventReceiver
!= null);
1003 // This is where we handoff the event handler lock from the primary
1004 // to secondary thread. We unlock here, and in a future loop the
1005 // secondary thread locks again. When it gives up, we have the
1006 // single lock back.
1007 boolean oldLock
= unlockHandleEvent();
1010 while (secondaryEventReceiver
!= null) {
1011 synchronized (primaryEventHandler
) {
1013 primaryEventHandler
.wait();
1014 } catch (InterruptedException e
) {
1022 * Do stuff when there is no user input.
1024 private void doIdle() {
1026 System
.err
.printf("doIdle()\n");
1029 // Now run any timers that have timed out
1030 Date now
= new Date();
1031 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1032 for (TTimer timer
: timers
) {
1033 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1035 if (timer
.recurring
) {
1036 keepTimers
.add(timer
);
1039 keepTimers
.add(timer
);
1042 timers
= keepTimers
;
1045 for (TWindow window
: windows
) {
1051 * Get the amount of time I can sleep before missing a Timer tick.
1053 * @param timeout = initial (maximum) timeout in millis
1054 * @return number of milliseconds between now and the next timer event
1056 private long getSleepTime(final long timeout
) {
1057 Date now
= new Date();
1058 long nowTime
= now
.getTime();
1059 long sleepTime
= timeout
;
1060 for (TTimer timer
: timers
) {
1061 long nextTickTime
= timer
.getNextTick().getTime();
1062 if (nextTickTime
< nowTime
) {
1066 long timeDifference
= nextTickTime
- nowTime
;
1067 if (timeDifference
< sleepTime
) {
1068 sleepTime
= timeDifference
;
1071 assert (sleepTime
>= 0);
1072 assert (sleepTime
<= timeout
);
1077 * Close window. Note that the window's destructor is NOT called by this
1078 * method, instead the GC is assumed to do the cleanup.
1080 * @param window the window to remove
1082 public final void closeWindow(final TWindow window
) {
1083 synchronized (windows
) {
1084 int z
= window
.getZ();
1087 Collections
.sort(windows
);
1089 TWindow activeWindow
= null;
1090 for (TWindow w
: windows
) {
1092 w
.setZ(w
.getZ() - 1);
1093 if (w
.getZ() == 0) {
1096 assert (activeWindow
== null);
1108 // Perform window cleanup
1111 // Check if we are closing a TMessageBox or similar
1112 if (secondaryEventReceiver
!= null) {
1113 assert (secondaryEventHandler
!= null);
1115 // Do not send events to the secondaryEventReceiver anymore, the
1116 // window is closed.
1117 secondaryEventReceiver
= null;
1119 // Wake the secondary thread, it will wake the primary as it
1121 synchronized (secondaryEventHandler
) {
1122 secondaryEventHandler
.notify();
1128 * Switch to the next window.
1130 * @param forward if true, then switch to the next window in the list,
1131 * otherwise switch to the previous window in the list
1133 public final void switchWindow(final boolean forward
) {
1134 // Only switch if there are multiple windows
1135 if (windows
.size() < 2) {
1139 synchronized (windows
) {
1141 // Swap z/active between active window and the next in the list
1142 int activeWindowI
= -1;
1143 for (int i
= 0; i
< windows
.size(); i
++) {
1144 if (windows
.get(i
).isActive()) {
1149 assert (activeWindowI
>= 0);
1151 // Do not switch if a window is modal
1152 if (windows
.get(activeWindowI
).isModal()) {
1158 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1160 if (activeWindowI
== 0) {
1161 nextWindowI
= windows
.size() - 1;
1163 nextWindowI
= activeWindowI
- 1;
1166 windows
.get(activeWindowI
).setActive(false);
1167 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1168 windows
.get(activeWindowI
).onUnfocus();
1169 windows
.get(nextWindowI
).setZ(0);
1170 windows
.get(nextWindowI
).setActive(true);
1171 windows
.get(nextWindowI
).onFocus();
1173 } // synchronized (windows)
1178 * Add a window to my window list and make it active.
1180 * @param window new window to add
1182 public final void addWindow(final TWindow window
) {
1183 synchronized (windows
) {
1184 // Do not allow a modal window to spawn a non-modal window
1185 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1186 assert (window
.isModal());
1188 for (TWindow w
: windows
) {
1193 w
.setZ(w
.getZ() + 1);
1195 windows
.add(window
);
1197 window
.setActive(true);
1203 * Check if there is a system-modal window on top.
1205 * @return true if the active window is modal
1207 private boolean modalWindowActive() {
1208 if (windows
.size() == 0) {
1211 return windows
.get(windows
.size() - 1).isModal();
1215 * Check if a mouse event would hit either the active menu or any open
1218 * @param mouse mouse event
1219 * @return true if the mouse would hit the active menu or an open
1222 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1223 assert (activeMenu
!= null);
1224 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1225 Collections
.reverse(menus
);
1226 for (TMenu menu
: menus
) {
1227 if (menu
.mouseWouldHit(mouse
)) {
1231 return activeMenu
.mouseWouldHit(mouse
);
1235 * See if we need to switch window or activate the menu based on
1238 * @param mouse mouse event
1240 private void checkSwitchFocus(final TMouseEvent mouse
) {
1242 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1243 && (activeMenu
!= null)
1244 && (mouse
.getAbsoluteY() != 0)
1245 && (!mouseOnMenu(mouse
))
1247 // They clicked outside the active menu, turn it off
1248 activeMenu
.setActive(false);
1250 for (TMenu menu
: subMenus
) {
1251 menu
.setActive(false);
1257 // See if they hit the menu bar
1258 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1259 && (mouse
.isMouse1())
1260 && (!modalWindowActive())
1261 && (mouse
.getAbsoluteY() == 0)
1264 for (TMenu menu
: subMenus
) {
1265 menu
.setActive(false);
1269 // They selected the menu, go activate it
1270 for (TMenu menu
: menus
) {
1271 if ((mouse
.getAbsoluteX() >= menu
.getX())
1272 && (mouse
.getAbsoluteX() < menu
.getX()
1273 + menu
.getTitle().length() + 2)
1275 menu
.setActive(true);
1278 menu
.setActive(false);
1284 // See if they hit the menu bar
1285 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1286 && (mouse
.isMouse1())
1287 && (activeMenu
!= null)
1288 && (mouse
.getAbsoluteY() == 0)
1291 TMenu oldMenu
= activeMenu
;
1292 for (TMenu menu
: subMenus
) {
1293 menu
.setActive(false);
1297 // See if we should switch menus
1298 for (TMenu menu
: menus
) {
1299 if ((mouse
.getAbsoluteX() >= menu
.getX())
1300 && (mouse
.getAbsoluteX() < menu
.getX()
1301 + menu
.getTitle().length() + 2)
1303 menu
.setActive(true);
1307 if (oldMenu
!= activeMenu
) {
1308 // They switched menus
1309 oldMenu
.setActive(false);
1314 // Only switch if there are multiple windows
1315 if (windows
.size() < 2) {
1319 // Switch on the upclick
1320 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1324 synchronized (windows
) {
1325 Collections
.sort(windows
);
1326 if (windows
.get(0).isModal()) {
1327 // Modal windows don't switch
1331 for (TWindow window
: windows
) {
1332 assert (!window
.isModal());
1333 if (window
.mouseWouldHit(mouse
)) {
1334 if (window
== windows
.get(0)) {
1335 // Clicked on the same window, nothing to do
1339 // We will be switching to another window
1340 assert (windows
.get(0).isActive());
1341 assert (!window
.isActive());
1342 windows
.get(0).onUnfocus();
1343 windows
.get(0).setActive(false);
1344 windows
.get(0).setZ(window
.getZ());
1346 window
.setActive(true);
1353 // Clicked on the background, nothing to do
1358 * Turn off the menu.
1360 public final void closeMenu() {
1361 if (activeMenu
!= null) {
1362 activeMenu
.setActive(false);
1364 for (TMenu menu
: subMenus
) {
1365 menu
.setActive(false);
1372 * Turn off a sub-menu.
1374 public final void closeSubMenu() {
1375 assert (activeMenu
!= null);
1376 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1377 assert (item
!= null);
1378 item
.setActive(false);
1379 subMenus
.remove(subMenus
.size() - 1);
1383 * Switch to the next menu.
1385 * @param forward if true, then switch to the next menu in the list,
1386 * otherwise switch to the previous menu in the list
1388 public final void switchMenu(final boolean forward
) {
1389 assert (activeMenu
!= null);
1391 for (TMenu menu
: subMenus
) {
1392 menu
.setActive(false);
1396 for (int i
= 0; i
< menus
.size(); i
++) {
1397 if (activeMenu
== menus
.get(i
)) {
1399 if (i
< menus
.size() - 1) {
1407 activeMenu
.setActive(false);
1408 activeMenu
= menus
.get(i
);
1409 activeMenu
.setActive(true);
1416 * Method that TApplication subclasses can override to handle menu or
1417 * posted command events.
1419 * @param command command event
1420 * @return if true, this event was consumed
1422 protected boolean onCommand(final TCommandEvent command
) {
1423 // Default: handle cmExit
1424 if (command
.equals(cmExit
)) {
1425 if (messageBox("Confirmation", "Exit application?",
1426 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1432 if (command
.equals(cmShell
)) {
1433 openTerminal(0, 0, TWindow
.RESIZABLE
);
1437 if (command
.equals(cmTile
)) {
1441 if (command
.equals(cmCascade
)) {
1445 if (command
.equals(cmCloseAll
)) {
1454 * Method that TApplication subclasses can override to handle menu
1457 * @param menu menu event
1458 * @return if true, this event was consumed
1460 protected boolean onMenu(final TMenuEvent menu
) {
1462 // Default: handle MID_EXIT
1463 if (menu
.getId() == TMenu
.MID_EXIT
) {
1464 if (messageBox("Confirmation", "Exit application?",
1465 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1471 if (menu
.getId() == TMenu
.MID_SHELL
) {
1472 openTerminal(0, 0, TWindow
.RESIZABLE
);
1476 if (menu
.getId() == TMenu
.MID_TILE
) {
1480 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1484 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1492 * Method that TApplication subclasses can override to handle keystrokes.
1494 * @param keypress keystroke event
1495 * @return if true, this event was consumed
1497 protected boolean onKeypress(final TKeypressEvent keypress
) {
1498 // Default: only menu shortcuts
1500 // Process Alt-F, Alt-E, etc. menu shortcut keys
1501 if (!keypress
.getKey().isFnKey()
1502 && keypress
.getKey().isAlt()
1503 && !keypress
.getKey().isCtrl()
1504 && (activeMenu
== null)
1507 assert (subMenus
.size() == 0);
1509 for (TMenu menu
: menus
) {
1510 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1511 == Character
.toLowerCase(keypress
.getKey().getChar())
1514 menu
.setActive(true);
1524 * Add a menu item to the global list. If it has a keyboard accelerator,
1525 * that will be added the global hash.
1527 * @param item the menu item
1529 public final void addMenuItem(final TMenuItem item
) {
1530 menuItems
.add(item
);
1532 TKeypress key
= item
.getKey();
1534 synchronized (accelerators
) {
1535 assert (accelerators
.get(key
) == null);
1536 accelerators
.put(key
.toLowerCase(), item
);
1542 * Disable one menu item.
1544 * @param id the menu item ID
1546 public final void disableMenuItem(final int id
) {
1547 for (TMenuItem item
: menuItems
) {
1548 if (item
.getId() == id
) {
1549 item
.setEnabled(false);
1555 * Disable the range of menu items with ID's between lower and upper,
1558 * @param lower the lowest menu item ID
1559 * @param upper the highest menu item ID
1561 public final void disableMenuItems(final int lower
, final int upper
) {
1562 for (TMenuItem item
: menuItems
) {
1563 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1564 item
.setEnabled(false);
1570 * Enable one menu item.
1572 * @param id the menu item ID
1574 public final void enableMenuItem(final int id
) {
1575 for (TMenuItem item
: menuItems
) {
1576 if (item
.getId() == id
) {
1577 item
.setEnabled(true);
1583 * Enable the range of menu items with ID's between lower and upper,
1586 * @param lower the lowest menu item ID
1587 * @param upper the highest menu item ID
1589 public final void enableMenuItems(final int lower
, final int upper
) {
1590 for (TMenuItem item
: menuItems
) {
1591 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1592 item
.setEnabled(true);
1598 * Recompute menu x positions based on their title length.
1600 public final void recomputeMenuX() {
1602 for (TMenu menu
: menus
) {
1604 x
+= menu
.getTitle().length() + 2;
1609 * Post an event to process and turn off the menu.
1611 * @param event new event to add to the queue
1613 public final void addMenuEvent(final TInputEvent event
) {
1614 synchronized (fillEventQueue
) {
1615 fillEventQueue
.add(event
);
1621 * Add a sub-menu to the list of open sub-menus.
1623 * @param menu sub-menu
1625 public final void addSubMenu(final TMenu menu
) {
1630 * Convenience function to add a top-level menu.
1632 * @param title menu title
1633 * @return the new menu
1635 public final TMenu
addMenu(final String title
) {
1638 TMenu menu
= new TMenu(this, x
, y
, title
);
1645 * Convenience function to add a default "File" menu.
1647 * @return the new menu
1649 public final TMenu
addFileMenu() {
1650 TMenu fileMenu
= addMenu("&File");
1651 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1652 fileMenu
.addSeparator();
1653 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1654 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1659 * Convenience function to add a default "Edit" menu.
1661 * @return the new menu
1663 public final TMenu
addEditMenu() {
1664 TMenu editMenu
= addMenu("&Edit");
1665 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1666 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1667 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1668 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1673 * Convenience function to add a default "Window" menu.
1675 * @return the new menu
1677 public final TMenu
addWindowMenu() {
1678 TMenu windowMenu
= addMenu("&Window");
1679 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1680 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1681 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1682 windowMenu
.addSeparator();
1683 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1684 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1685 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1686 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1687 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1692 * Close all open windows.
1694 private void closeAllWindows() {
1695 // Don't do anything if we are in the menu
1696 if (activeMenu
!= null) {
1700 synchronized (windows
) {
1701 for (TWindow window
: windows
) {
1702 closeWindow(window
);
1708 * Re-layout the open windows as non-overlapping tiles. This produces
1709 * almost the same results as Turbo Pascal 7.0's IDE.
1711 private void tileWindows() {
1712 synchronized (windows
) {
1713 // Don't do anything if we are in the menu
1714 if (activeMenu
!= null) {
1717 int z
= windows
.size();
1723 a
= (int)(Math
.sqrt(z
));
1727 if (((a
* b
) + c
) == z
) {
1735 int newWidth
= (getScreen().getWidth() / a
);
1736 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1737 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1739 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1740 Collections
.sort(sorted
);
1741 Collections
.reverse(sorted
);
1742 for (int i
= 0; i
< sorted
.size(); i
++) {
1743 int logicalX
= i
/ b
;
1744 int logicalY
= i
% b
;
1745 if (i
>= ((a
- 1) * b
)) {
1747 logicalY
= i
- ((a
- 1) * b
);
1750 TWindow w
= sorted
.get(i
);
1751 w
.setX(logicalX
* newWidth
);
1752 w
.setWidth(newWidth
);
1753 if (i
>= ((a
- 1) * b
)) {
1754 w
.setY((logicalY
* newHeight2
) + 1);
1755 w
.setHeight(newHeight2
);
1757 w
.setY((logicalY
* newHeight1
) + 1);
1758 w
.setHeight(newHeight1
);
1765 * Re-layout the open windows as overlapping cascaded windows.
1767 private void cascadeWindows() {
1768 synchronized (windows
) {
1769 // Don't do anything if we are in the menu
1770 if (activeMenu
!= null) {
1775 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1776 Collections
.sort(sorted
);
1777 Collections
.reverse(sorted
);
1778 for (TWindow window
: sorted
) {
1783 if (x
> getScreen().getWidth()) {
1786 if (y
>= getScreen().getHeight()) {
1794 * Convenience function to add a timer.
1796 * @param duration number of milliseconds to wait between ticks
1797 * @param recurring if true, re-schedule this timer after every tick
1798 * @param action function to call when button is pressed
1801 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1802 final TAction action
) {
1804 TTimer timer
= new TTimer(duration
, recurring
, action
);
1805 synchronized (timers
) {
1812 * Convenience function to remove a timer.
1814 * @param timer timer to remove
1816 public final void removeTimer(final TTimer timer
) {
1817 synchronized (timers
) {
1818 timers
.remove(timer
);
1823 * Convenience function to spawn a message box.
1825 * @param title window title, will be centered along the top border
1826 * @param caption message to display. Use embedded newlines to get a
1828 * @return the new message box
1830 public final TMessageBox
messageBox(final String title
,
1831 final String caption
) {
1833 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1837 * Convenience function to spawn a message box.
1839 * @param title window title, will be centered along the top border
1840 * @param caption message to display. Use embedded newlines to get a
1842 * @param type one of the TMessageBox.Type constants. Default is
1844 * @return the new message box
1846 public final TMessageBox
messageBox(final String title
,
1847 final String caption
, final TMessageBox
.Type type
) {
1849 return new TMessageBox(this, title
, caption
, type
);
1853 * Convenience function to spawn an input box.
1855 * @param title window title, will be centered along the top border
1856 * @param caption message to display. Use embedded newlines to get a
1858 * @return the new input box
1860 public final TInputBox
inputBox(final String title
, final String caption
) {
1862 return new TInputBox(this, title
, caption
);
1866 * Convenience function to spawn an input box.
1868 * @param title window title, will be centered along the top border
1869 * @param caption message to display. Use embedded newlines to get a
1871 * @param text initial text to seed the field with
1872 * @return the new input box
1874 public final TInputBox
inputBox(final String title
, final String caption
,
1875 final String text
) {
1877 return new TInputBox(this, title
, caption
, text
);
1881 * Convenience function to open a terminal window.
1883 * @param x column relative to parent
1884 * @param y row relative to parent
1885 * @return the terminal new window
1887 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1888 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1892 * Convenience function to open a terminal window.
1894 * @param x column relative to parent
1895 * @param y row relative to parent
1896 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1897 * @return the terminal new window
1899 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1902 return new TTerminalWindow(this, x
, y
, flags
);
1906 * Convenience function to spawn an file open box.
1908 * @param path path of selected file
1909 * @return the result of the new file open box
1910 * @throws IOException if java.io operation throws
1912 public final String
fileOpenBox(final String path
) throws IOException
{
1914 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
1915 return box
.getFilename();
1919 * Convenience function to spawn an file open box.
1921 * @param path path of selected file
1922 * @param type one of the Type constants
1923 * @return the result of the new file open box
1924 * @throws IOException if java.io operation throws
1926 public final String
fileOpenBox(final String path
,
1927 final TFileOpenBox
.Type type
) throws IOException
{
1929 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
1930 return box
.getFilename();