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 // Wait for drawAll() or doIdle() to be done, then handle the
179 boolean oldLock
= lockHandleEvent();
180 assert (oldLock
== false);
182 // Pull all events off the queue
184 TInputEvent event
= null;
185 synchronized (application
.drainEventQueue
) {
186 if (application
.drainEventQueue
.size() == 0) {
189 event
= application
.drainEventQueue
.remove(0);
191 application
.repaint
= true;
193 primaryHandleEvent(event
);
195 secondaryHandleEvent(event
);
198 && (application
.secondaryEventReceiver
== null)
200 // Secondary thread, time to exit.
202 // DO NOT UNLOCK. Primary thread just came back from
203 // primaryHandleEvent() and will unlock in the else
204 // block below. Just wake it up.
205 synchronized (application
.primaryEventHandler
) {
206 application
.primaryEventHandler
.notify();
208 // Now eliminate my reference so that
209 // wakeEventHandler() resumes working on the primary.
210 application
.secondaryEventHandler
= null;
217 // Unlock. Either I am primary thread, or I am secondary
218 // thread and still running.
219 oldLock
= unlockHandleEvent();
220 assert (oldLock
== true);
222 // I have done some work of some kind. Tell the main run()
223 // loop to wake up now.
224 synchronized (application
) {
225 application
.notify();
228 } // while (true) (main runnable loop)
233 * The primary event handler thread.
235 private volatile WidgetEventHandler primaryEventHandler
;
238 * The secondary event handler thread.
240 private volatile WidgetEventHandler secondaryEventHandler
;
243 * The widget receiving events from the secondary event handler thread.
245 private volatile TWidget secondaryEventReceiver
;
248 * Spinlock for the primary and secondary event handlers.
249 * WidgetEventHandler.run() is responsible for setting this value.
251 private volatile boolean insideHandleEvent
= false;
254 * Wake the sleeping active event handler.
256 private void wakeEventHandler() {
257 if (secondaryEventHandler
!= null) {
258 synchronized (secondaryEventHandler
) {
259 secondaryEventHandler
.notify();
262 assert (primaryEventHandler
!= null);
263 synchronized (primaryEventHandler
) {
264 primaryEventHandler
.notify();
270 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
271 * spin indefinitely until unlockHandleEvent() is called.
273 * @return the old value of insideHandleEvent
275 private boolean lockHandleEvent() {
277 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
280 boolean oldValue
= true;
282 synchronized (this) {
283 // Wait for TApplication.run() to finish using the global state
284 // before allowing further event processing.
285 while (lockoutHandleEvent
== true) {
287 // Backoff so that the backend can finish its work.
289 } catch (InterruptedException e
) {
294 oldValue
= insideHandleEvent
;
295 insideHandleEvent
= true;
299 System
.err
.printf(" ***\n");
305 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
306 * spin indefinitely until unlockHandleEvent() is called.
308 * @return the old value of insideHandleEvent
310 private boolean unlockHandleEvent() {
312 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
315 synchronized (this) {
316 boolean oldValue
= insideHandleEvent
;
317 insideHandleEvent
= false;
323 * Spinlock for the primary and secondary event handlers. When true, the
324 * event handlers will spinlock wait before calling handleEvent().
326 private volatile boolean lockoutHandleEvent
= false;
329 * TApplication.run() needs to be able rely on the global data structures
330 * being intact when calling doIdle() and drawAll(). Tell the event
331 * handlers to wait for an unlock before handling their events.
333 private void stopEventHandlers() {
335 System
.err
.printf(">> stopEventHandlers()");
338 lockoutHandleEvent
= true;
339 // Wait for the last event to finish processing before returning
340 // control to TApplication.run().
341 while (insideHandleEvent
== true) {
343 // Backoff so that the event handler can finish its work.
345 } catch (InterruptedException e
) {
351 System
.err
.printf(" XXX\n");
356 * TApplication.run() needs to be able rely on the global data structures
357 * being intact when calling doIdle() and drawAll(). Tell the event
358 * handlers that it is now OK to handle their events.
360 private void startEventHandlers() {
362 System
.err
.printf("<< startEventHandlers()\n");
364 lockoutHandleEvent
= false;
368 * Access to the physical screen, keyboard, and mouse.
370 private Backend backend
;
377 public final Screen
getScreen() {
378 return backend
.getScreen();
382 * Actual mouse coordinate X.
387 * Actual mouse coordinate Y.
392 * Old version of mouse coordinate X.
394 private int oldMouseX
;
397 * Old version mouse coordinate Y.
399 private int oldMouseY
;
402 * Event queue that is filled by run().
404 private List
<TInputEvent
> fillEventQueue
;
407 * Event queue that will be drained by either primary or secondary
410 private List
<TInputEvent
> drainEventQueue
;
413 * Top-level menus in this application.
415 private List
<TMenu
> menus
;
418 * Stack of activated sub-menus in this application.
420 private List
<TMenu
> subMenus
;
423 * The currently acive menu.
425 private TMenu activeMenu
= null;
428 * Active keyboard accelerators.
430 private Map
<TKeypress
, TMenuItem
> accelerators
;
433 * Windows and widgets pull colors from this ColorTheme.
435 private ColorTheme theme
;
438 * Get the color theme.
442 public final ColorTheme
getTheme() {
447 * The top-level windows (but not menus).
449 private List
<TWindow
> windows
;
452 * Timers that are being ticked.
454 private List
<TTimer
> timers
;
457 * When true, exit the application.
459 private volatile boolean quit
= false;
462 * When true, repaint the entire screen.
464 private volatile boolean repaint
= true;
467 * Y coordinate of the top edge of the desktop. For now this is a
468 * constant. Someday it would be nice to have a multi-line menu or
471 private static final int desktopTop
= 1;
474 * Get Y coordinate of the top edge of the desktop.
476 * @return Y coordinate of the top edge of the desktop
478 public final int getDesktopTop() {
483 * Y coordinate of the bottom edge of the desktop.
485 private int desktopBottom
;
488 * Get Y coordinate of the bottom edge of the desktop.
490 * @return Y coordinate of the bottom edge of the desktop
492 public final int getDesktopBottom() {
493 return desktopBottom
;
497 * Public constructor.
499 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
501 * @throws UnsupportedEncodingException if an exception is thrown when
502 * creating the InputStreamReader
504 public TApplication(final BackendType backendType
)
505 throws UnsupportedEncodingException
{
507 switch (backendType
) {
509 backend
= new SwingBackend(this);
514 backend
= new ECMA48Backend(this, null, null);
520 * Public constructor. The backend type will be BackendType.ECMA48.
522 * @param input an InputStream connected to the remote user, or null for
523 * System.in. If System.in is used, then on non-Windows systems it will
524 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
525 * mode. input is always converted to a Reader with UTF-8 encoding.
526 * @param output an OutputStream connected to the remote user, or null
527 * for System.out. output is always converted to a Writer with UTF-8
529 * @throws UnsupportedEncodingException if an exception is thrown when
530 * creating the InputStreamReader
532 public TApplication(final InputStream input
,
533 final OutputStream output
) throws UnsupportedEncodingException
{
535 backend
= new ECMA48Backend(this, input
, output
);
540 * Public constructor. This hook enables use with new non-Jexer
543 * @param backend a Backend that is already ready to go.
545 public TApplication(final Backend backend
) {
546 this.backend
= backend
;
551 * Finish construction once the backend is set.
553 private void TApplicationImpl() {
554 theme
= new ColorTheme();
555 desktopBottom
= getScreen().getHeight() - 1;
556 fillEventQueue
= new ArrayList
<TInputEvent
>();
557 drainEventQueue
= new ArrayList
<TInputEvent
>();
558 windows
= new LinkedList
<TWindow
>();
559 menus
= new LinkedList
<TMenu
>();
560 subMenus
= new LinkedList
<TMenu
>();
561 timers
= new LinkedList
<TTimer
>();
562 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
564 // Setup the main consumer thread
565 primaryEventHandler
= new WidgetEventHandler(this, true);
566 (new Thread(primaryEventHandler
)).start();
570 * Invert the cell color at a position. This is used to track the mouse.
572 * @param x column position
573 * @param y row position
575 private void invertCell(final int x
, final int y
) {
576 synchronized (getScreen()) {
577 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
578 attr
.setForeColor(attr
.getForeColor().invert());
579 attr
.setBackColor(attr
.getBackColor().invert());
580 getScreen().putAttrXY(x
, y
, attr
, false);
587 private void drawAll() {
589 System
.err
.printf("drawAll() enter\n");
593 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
594 // The only thing that has happened is the mouse moved.
595 // Clear the old position and draw the new position.
596 invertCell(oldMouseX
, oldMouseY
);
597 invertCell(mouseX
, mouseY
);
601 if (getScreen().isDirty()) {
602 backend
.flushScreen();
608 System
.err
.printf("drawAll() REDRAW\n");
611 // If true, the cursor is not visible
612 boolean cursor
= false;
614 // Start with a clean screen
617 // Draw the background
618 CellAttributes background
= theme
.getColor("tapplication.background");
619 getScreen().putAll(GraphicsChars
.HATCH
, background
);
621 // Draw each window in reverse Z order
622 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
623 Collections
.sort(sorted
);
624 Collections
.reverse(sorted
);
625 for (TWindow window
: sorted
) {
626 window
.drawChildren();
629 // Draw the blank menubar line - reset the screen clipping first so
630 // it won't trim it out.
631 getScreen().resetClipping();
632 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
633 theme
.getColor("tmenu"));
634 // Now draw the menus.
636 for (TMenu menu
: menus
) {
637 CellAttributes menuColor
;
638 CellAttributes menuMnemonicColor
;
639 if (menu
.isActive()) {
640 menuColor
= theme
.getColor("tmenu.highlighted");
641 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
643 menuColor
= theme
.getColor("tmenu");
644 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
646 // Draw the menu title
647 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
649 getScreen().putStrXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
650 // Draw the highlight character
651 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
652 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
654 if (menu
.isActive()) {
656 // Reset the screen clipping so we can draw the next title.
657 getScreen().resetClipping();
659 x
+= menu
.getTitle().length() + 2;
662 for (TMenu menu
: subMenus
) {
663 // Reset the screen clipping so we can draw the next sub-menu.
664 getScreen().resetClipping();
668 // Draw the mouse pointer
669 invertCell(mouseX
, mouseY
);
671 // Place the cursor if it is visible
672 TWidget activeWidget
= null;
673 if (sorted
.size() > 0) {
674 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
675 if (activeWidget
.isCursorVisible()) {
676 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
677 activeWidget
.getCursorAbsoluteY());
684 getScreen().hideCursor();
687 // Flush the screen contents
688 backend
.flushScreen();
694 * Run this application until it exits.
698 // Timeout is in milliseconds, so default timeout after 1 second
702 // If I've got no updates to render, wait for something from the
703 // backend or a timer.
705 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
707 // Never sleep longer than 50 millis. We need time for
708 // windows with background tasks to update the display, and
709 // still flip buffers reasonably quickly in
710 // backend.flushPhysical().
711 timeout
= getSleepTime(50);
715 // As of now, I've got nothing to do: no I/O, nothing from
716 // the consumer threads, no timers that need to run ASAP. So
717 // wait until either the backend or the consumer threads have
720 synchronized (this) {
723 } catch (InterruptedException e
) {
724 // I'm awake and don't care why, let's see what's going
730 // Prevent stepping on the primary or secondary event handler.
733 // Pull any pending I/O events
734 backend
.getEvents(fillEventQueue
);
736 // Dispatch each event to the appropriate handler, one at a time.
738 TInputEvent event
= null;
739 if (fillEventQueue
.size() == 0) {
742 event
= fillEventQueue
.remove(0);
743 metaHandleEvent(event
);
746 // Wake a consumer thread if we have any pending events.
747 if (drainEventQueue
.size() > 0) {
751 // Process timers and call doIdle()'s
755 synchronized (getScreen()) {
759 // Let the event handlers run again.
760 startEventHandlers();
764 // Shutdown the event consumer threads
765 if (secondaryEventHandler
!= null) {
766 synchronized (secondaryEventHandler
) {
767 secondaryEventHandler
.notify();
770 if (primaryEventHandler
!= null) {
771 synchronized (primaryEventHandler
) {
772 primaryEventHandler
.notify();
776 // Shutdown the user I/O thread(s)
779 // Close all the windows. This gives them an opportunity to release
786 * Peek at certain application-level events, add to eventQueue, and wake
787 * up the consuming Thread.
789 * @param event the input event to consume
791 private void metaHandleEvent(final TInputEvent event
) {
794 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
795 event
)); System
.err
.flush();
799 // Do no more processing if the application is already trying
804 // Special application-wide events -------------------------------
807 if (event
instanceof TCommandEvent
) {
808 TCommandEvent command
= (TCommandEvent
) event
;
809 if (command
.getCmd().equals(cmAbort
)) {
816 if (event
instanceof TResizeEvent
) {
817 TResizeEvent resize
= (TResizeEvent
) event
;
818 synchronized (getScreen()) {
819 getScreen().setDimensions(resize
.getWidth(),
821 desktopBottom
= getScreen().getHeight() - 1;
830 // Peek at the mouse position
831 if (event
instanceof TMouseEvent
) {
832 TMouseEvent mouse
= (TMouseEvent
) event
;
833 synchronized (getScreen()) {
834 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
837 mouseX
= mouse
.getX();
838 mouseY
= mouse
.getY();
843 // Put into the main queue
844 drainEventQueue
.add(event
);
848 * Dispatch one event to the appropriate widget or application-level
849 * event handler. This is the primary event handler, it has the normal
850 * application-wide event handling.
852 * @param event the input event to consume
853 * @see #secondaryHandleEvent(TInputEvent event)
855 private void primaryHandleEvent(final TInputEvent event
) {
858 System
.err
.printf("Handle event: %s\n", event
);
861 // Special application-wide events -----------------------------------
863 // Peek at the mouse position
864 if (event
instanceof TMouseEvent
) {
865 // See if we need to switch focus to another window or the menu
866 checkSwitchFocus((TMouseEvent
) event
);
869 // Handle menu events
870 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
871 TMenu menu
= activeMenu
;
873 if (event
instanceof TMouseEvent
) {
874 TMouseEvent mouse
= (TMouseEvent
) event
;
876 while (subMenus
.size() > 0) {
877 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
878 if (subMenu
.mouseWouldHit(mouse
)) {
881 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
882 && (!mouse
.isMouse1())
883 && (!mouse
.isMouse2())
884 && (!mouse
.isMouse3())
885 && (!mouse
.isMouseWheelUp())
886 && (!mouse
.isMouseWheelDown())
890 // We navigated away from a sub-menu, so close it
894 // Convert the mouse relative x/y to menu coordinates
895 assert (mouse
.getX() == mouse
.getAbsoluteX());
896 assert (mouse
.getY() == mouse
.getAbsoluteY());
897 if (subMenus
.size() > 0) {
898 menu
= subMenus
.get(subMenus
.size() - 1);
900 mouse
.setX(mouse
.getX() - menu
.getX());
901 mouse
.setY(mouse
.getY() - menu
.getY());
903 menu
.handleEvent(event
);
907 if (event
instanceof TKeypressEvent
) {
908 TKeypressEvent keypress
= (TKeypressEvent
) event
;
910 // See if this key matches an accelerator, and if so dispatch the
912 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
913 TMenuItem item
= null;
914 synchronized (accelerators
) {
915 item
= accelerators
.get(keypressLowercase
);
918 if (item
.isEnabled()) {
919 // Let the menu item dispatch
924 // Handle the keypress
925 if (onKeypress(keypress
)) {
930 if (event
instanceof TCommandEvent
) {
931 if (onCommand((TCommandEvent
) event
)) {
936 if (event
instanceof TMenuEvent
) {
937 if (onMenu((TMenuEvent
) event
)) {
942 // Dispatch events to the active window -------------------------------
943 for (TWindow window
: windows
) {
944 if (window
.isActive()) {
945 if (event
instanceof TMouseEvent
) {
946 TMouseEvent mouse
= (TMouseEvent
) event
;
947 // Convert the mouse relative x/y to window coordinates
948 assert (mouse
.getX() == mouse
.getAbsoluteX());
949 assert (mouse
.getY() == mouse
.getAbsoluteY());
950 mouse
.setX(mouse
.getX() - window
.getX());
951 mouse
.setY(mouse
.getY() - window
.getY());
954 System
.err
.printf("TApplication dispatch event: %s\n",
957 window
.handleEvent(event
);
963 * Dispatch one event to the appropriate widget or application-level
964 * event handler. This is the secondary event handler used by certain
965 * special dialogs (currently TMessageBox and TFileOpenBox).
967 * @param event the input event to consume
968 * @see #primaryHandleEvent(TInputEvent event)
970 private void secondaryHandleEvent(final TInputEvent event
) {
971 secondaryEventReceiver
.handleEvent(event
);
975 * Enable a widget to override the primary event thread.
977 * @param widget widget that will receive events
979 public final void enableSecondaryEventReceiver(final TWidget widget
) {
980 assert (secondaryEventReceiver
== null);
981 assert (secondaryEventHandler
== null);
982 assert (widget
instanceof TMessageBox
);
983 secondaryEventReceiver
= widget
;
984 secondaryEventHandler
= new WidgetEventHandler(this, false);
985 (new Thread(secondaryEventHandler
)).start();
989 * Yield to the secondary thread.
991 public final void yield() {
992 assert (secondaryEventReceiver
!= null);
993 // This is where we handoff the event handler lock from the primary
994 // to secondary thread. We unlock here, and in a future loop the
995 // secondary thread locks again. When it gives up, we have the
997 boolean oldLock
= unlockHandleEvent();
998 assert (oldLock
== true);
1000 while (secondaryEventReceiver
!= null) {
1001 synchronized (primaryEventHandler
) {
1003 primaryEventHandler
.wait();
1004 } catch (InterruptedException e
) {
1012 * Do stuff when there is no user input.
1014 private void doIdle() {
1016 System
.err
.printf("doIdle()\n");
1019 // Now run any timers that have timed out
1020 Date now
= new Date();
1021 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1022 for (TTimer timer
: timers
) {
1023 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1025 if (timer
.recurring
) {
1026 keepTimers
.add(timer
);
1029 keepTimers
.add(timer
);
1032 timers
= keepTimers
;
1035 for (TWindow window
: windows
) {
1041 * Get the amount of time I can sleep before missing a Timer tick.
1043 * @param timeout = initial (maximum) timeout in millis
1044 * @return number of milliseconds between now and the next timer event
1046 private long getSleepTime(final long timeout
) {
1047 Date now
= new Date();
1048 long nowTime
= now
.getTime();
1049 long sleepTime
= timeout
;
1050 for (TTimer timer
: timers
) {
1051 long nextTickTime
= timer
.getNextTick().getTime();
1052 if (nextTickTime
< nowTime
) {
1056 long timeDifference
= nextTickTime
- nowTime
;
1057 if (timeDifference
< sleepTime
) {
1058 sleepTime
= timeDifference
;
1061 assert (sleepTime
>= 0);
1062 assert (sleepTime
<= timeout
);
1067 * Close window. Note that the window's destructor is NOT called by this
1068 * method, instead the GC is assumed to do the cleanup.
1070 * @param window the window to remove
1072 public final void closeWindow(final TWindow window
) {
1073 synchronized (windows
) {
1074 int z
= window
.getZ();
1076 Collections
.sort(windows
);
1078 TWindow activeWindow
= null;
1079 for (TWindow w
: windows
) {
1081 w
.setZ(w
.getZ() - 1);
1082 if (w
.getZ() == 0) {
1084 assert (activeWindow
== null);
1093 // Perform window cleanup
1096 // Check if we are closing a TMessageBox or similar
1097 if (secondaryEventReceiver
!= null) {
1098 assert (secondaryEventHandler
!= null);
1100 // Do not send events to the secondaryEventReceiver anymore, the
1101 // window is closed.
1102 secondaryEventReceiver
= null;
1104 // Wake the secondary thread, it will wake the primary as it
1106 synchronized (secondaryEventHandler
) {
1107 secondaryEventHandler
.notify();
1113 * Switch to the next window.
1115 * @param forward if true, then switch to the next window in the list,
1116 * otherwise switch to the previous window in the list
1118 public final void switchWindow(final boolean forward
) {
1119 // Only switch if there are multiple windows
1120 if (windows
.size() < 2) {
1124 synchronized (windows
) {
1126 // Swap z/active between active window and the next in the list
1127 int activeWindowI
= -1;
1128 for (int i
= 0; i
< windows
.size(); i
++) {
1129 if (windows
.get(i
).isActive()) {
1134 assert (activeWindowI
>= 0);
1136 // Do not switch if a window is modal
1137 if (windows
.get(activeWindowI
).isModal()) {
1143 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1145 if (activeWindowI
== 0) {
1146 nextWindowI
= windows
.size() - 1;
1148 nextWindowI
= activeWindowI
- 1;
1151 windows
.get(activeWindowI
).setActive(false);
1152 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1153 windows
.get(nextWindowI
).setZ(0);
1154 windows
.get(nextWindowI
).setActive(true);
1156 } // synchronized (windows)
1161 * Add a window to my window list and make it active.
1163 * @param window new window to add
1165 public final void addWindow(final TWindow window
) {
1166 synchronized (windows
) {
1167 // Do not allow a modal window to spawn a non-modal window
1168 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1169 assert (window
.isModal());
1171 for (TWindow w
: windows
) {
1173 w
.setZ(w
.getZ() + 1);
1175 windows
.add(window
);
1176 window
.setActive(true);
1182 * Check if there is a system-modal window on top.
1184 * @return true if the active window is modal
1186 private boolean modalWindowActive() {
1187 if (windows
.size() == 0) {
1190 return windows
.get(windows
.size() - 1).isModal();
1194 * Check if a mouse event would hit either the active menu or any open
1197 * @param mouse mouse event
1198 * @return true if the mouse would hit the active menu or an open
1201 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1202 assert (activeMenu
!= null);
1203 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1204 Collections
.reverse(menus
);
1205 for (TMenu menu
: menus
) {
1206 if (menu
.mouseWouldHit(mouse
)) {
1210 return activeMenu
.mouseWouldHit(mouse
);
1214 * See if we need to switch window or activate the menu based on
1217 * @param mouse mouse event
1219 private void checkSwitchFocus(final TMouseEvent mouse
) {
1221 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1222 && (activeMenu
!= null)
1223 && (mouse
.getAbsoluteY() != 0)
1224 && (!mouseOnMenu(mouse
))
1226 // They clicked outside the active menu, turn it off
1227 activeMenu
.setActive(false);
1229 for (TMenu menu
: subMenus
) {
1230 menu
.setActive(false);
1236 // See if they hit the menu bar
1237 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1238 && (mouse
.isMouse1())
1239 && (!modalWindowActive())
1240 && (mouse
.getAbsoluteY() == 0)
1243 for (TMenu menu
: subMenus
) {
1244 menu
.setActive(false);
1248 // They selected the menu, go activate it
1249 for (TMenu menu
: menus
) {
1250 if ((mouse
.getAbsoluteX() >= menu
.getX())
1251 && (mouse
.getAbsoluteX() < menu
.getX()
1252 + menu
.getTitle().length() + 2)
1254 menu
.setActive(true);
1257 menu
.setActive(false);
1263 // See if they hit the menu bar
1264 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1265 && (mouse
.isMouse1())
1266 && (activeMenu
!= null)
1267 && (mouse
.getAbsoluteY() == 0)
1270 TMenu oldMenu
= activeMenu
;
1271 for (TMenu menu
: subMenus
) {
1272 menu
.setActive(false);
1276 // See if we should switch menus
1277 for (TMenu menu
: menus
) {
1278 if ((mouse
.getAbsoluteX() >= menu
.getX())
1279 && (mouse
.getAbsoluteX() < menu
.getX()
1280 + menu
.getTitle().length() + 2)
1282 menu
.setActive(true);
1286 if (oldMenu
!= activeMenu
) {
1287 // They switched menus
1288 oldMenu
.setActive(false);
1293 // Only switch if there are multiple windows
1294 if (windows
.size() < 2) {
1298 // Switch on the upclick
1299 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1303 synchronized (windows
) {
1304 Collections
.sort(windows
);
1305 if (windows
.get(0).isModal()) {
1306 // Modal windows don't switch
1310 for (TWindow window
: windows
) {
1311 assert (!window
.isModal());
1312 if (window
.mouseWouldHit(mouse
)) {
1313 if (window
== windows
.get(0)) {
1314 // Clicked on the same window, nothing to do
1318 // We will be switching to another window
1319 assert (windows
.get(0).isActive());
1320 assert (!window
.isActive());
1321 windows
.get(0).setActive(false);
1322 windows
.get(0).setZ(window
.getZ());
1324 window
.setActive(true);
1330 // Clicked on the background, nothing to do
1335 * Turn off the menu.
1337 public final void closeMenu() {
1338 if (activeMenu
!= null) {
1339 activeMenu
.setActive(false);
1341 for (TMenu menu
: subMenus
) {
1342 menu
.setActive(false);
1349 * Turn off a sub-menu.
1351 public final void closeSubMenu() {
1352 assert (activeMenu
!= null);
1353 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1354 assert (item
!= null);
1355 item
.setActive(false);
1356 subMenus
.remove(subMenus
.size() - 1);
1360 * Switch to the next menu.
1362 * @param forward if true, then switch to the next menu in the list,
1363 * otherwise switch to the previous menu in the list
1365 public final void switchMenu(final boolean forward
) {
1366 assert (activeMenu
!= null);
1368 for (TMenu menu
: subMenus
) {
1369 menu
.setActive(false);
1373 for (int i
= 0; i
< menus
.size(); i
++) {
1374 if (activeMenu
== menus
.get(i
)) {
1376 if (i
< menus
.size() - 1) {
1384 activeMenu
.setActive(false);
1385 activeMenu
= menus
.get(i
);
1386 activeMenu
.setActive(true);
1393 * Method that TApplication subclasses can override to handle menu or
1394 * posted command events.
1396 * @param command command event
1397 * @return if true, this event was consumed
1399 protected boolean onCommand(final TCommandEvent command
) {
1400 // Default: handle cmExit
1401 if (command
.equals(cmExit
)) {
1402 if (messageBox("Confirmation", "Exit application?",
1403 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1409 if (command
.equals(cmShell
)) {
1410 openTerminal(0, 0, TWindow
.RESIZABLE
);
1414 if (command
.equals(cmTile
)) {
1418 if (command
.equals(cmCascade
)) {
1422 if (command
.equals(cmCloseAll
)) {
1431 * Method that TApplication subclasses can override to handle menu
1434 * @param menu menu event
1435 * @return if true, this event was consumed
1437 protected boolean onMenu(final TMenuEvent menu
) {
1439 // Default: handle MID_EXIT
1440 if (menu
.getId() == TMenu
.MID_EXIT
) {
1441 if (messageBox("Confirmation", "Exit application?",
1442 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1448 if (menu
.getId() == TMenu
.MID_SHELL
) {
1449 openTerminal(0, 0, TWindow
.RESIZABLE
);
1453 if (menu
.getId() == TMenu
.MID_TILE
) {
1457 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1461 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1469 * Method that TApplication subclasses can override to handle keystrokes.
1471 * @param keypress keystroke event
1472 * @return if true, this event was consumed
1474 protected boolean onKeypress(final TKeypressEvent keypress
) {
1475 // Default: only menu shortcuts
1477 // Process Alt-F, Alt-E, etc. menu shortcut keys
1478 if (!keypress
.getKey().isFnKey()
1479 && keypress
.getKey().isAlt()
1480 && !keypress
.getKey().isCtrl()
1481 && (activeMenu
== null)
1484 assert (subMenus
.size() == 0);
1486 for (TMenu menu
: menus
) {
1487 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1488 == Character
.toLowerCase(keypress
.getKey().getChar())
1491 menu
.setActive(true);
1501 * Add a keyboard accelerator to the global hash.
1503 * @param item menu item this accelerator relates to
1504 * @param keypress keypress that will dispatch a TMenuEvent
1506 public final void addAccelerator(final TMenuItem item
,
1507 final TKeypress keypress
) {
1509 synchronized (accelerators
) {
1510 assert (accelerators
.get(keypress
) == null);
1511 accelerators
.put(keypress
, item
);
1516 * Recompute menu x positions based on their title length.
1518 public final void recomputeMenuX() {
1520 for (TMenu menu
: menus
) {
1522 x
+= menu
.getTitle().length() + 2;
1527 * Post an event to process and turn off the menu.
1529 * @param event new event to add to the queue
1531 public final void addMenuEvent(final TInputEvent event
) {
1532 synchronized (fillEventQueue
) {
1533 fillEventQueue
.add(event
);
1539 * Add a sub-menu to the list of open sub-menus.
1541 * @param menu sub-menu
1543 public final void addSubMenu(final TMenu menu
) {
1548 * Convenience function to add a top-level menu.
1550 * @param title menu title
1551 * @return the new menu
1553 public final TMenu
addMenu(final String title
) {
1556 TMenu menu
= new TMenu(this, x
, y
, title
);
1563 * Convenience function to add a default "File" menu.
1565 * @return the new menu
1567 public final TMenu
addFileMenu() {
1568 TMenu fileMenu
= addMenu("&File");
1569 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1570 fileMenu
.addSeparator();
1571 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1572 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1577 * Convenience function to add a default "Edit" menu.
1579 * @return the new menu
1581 public final TMenu
addEditMenu() {
1582 TMenu editMenu
= addMenu("&Edit");
1583 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1584 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1585 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1586 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1591 * Convenience function to add a default "Window" menu.
1593 * @return the new menu
1595 public final TMenu
addWindowMenu() {
1596 TMenu windowMenu
= addMenu("&Window");
1597 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1598 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1599 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1600 windowMenu
.addSeparator();
1601 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1602 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1603 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1604 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1605 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1610 * Close all open windows.
1612 private void closeAllWindows() {
1613 // Don't do anything if we are in the menu
1614 if (activeMenu
!= null) {
1618 synchronized (windows
) {
1619 for (TWindow window
: windows
) {
1620 closeWindow(window
);
1626 * Re-layout the open windows as non-overlapping tiles. This produces
1627 * almost the same results as Turbo Pascal 7.0's IDE.
1629 private void tileWindows() {
1630 synchronized (windows
) {
1631 // Don't do anything if we are in the menu
1632 if (activeMenu
!= null) {
1635 int z
= windows
.size();
1641 a
= (int)(Math
.sqrt(z
));
1645 if (((a
* b
) + c
) == z
) {
1653 int newWidth
= (getScreen().getWidth() / a
);
1654 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1655 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1657 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1658 Collections
.sort(sorted
);
1659 Collections
.reverse(sorted
);
1660 for (int i
= 0; i
< sorted
.size(); i
++) {
1661 int logicalX
= i
/ b
;
1662 int logicalY
= i
% b
;
1663 if (i
>= ((a
- 1) * b
)) {
1665 logicalY
= i
- ((a
- 1) * b
);
1668 TWindow w
= sorted
.get(i
);
1669 w
.setX(logicalX
* newWidth
);
1670 w
.setWidth(newWidth
);
1671 if (i
>= ((a
- 1) * b
)) {
1672 w
.setY((logicalY
* newHeight2
) + 1);
1673 w
.setHeight(newHeight2
);
1675 w
.setY((logicalY
* newHeight1
) + 1);
1676 w
.setHeight(newHeight1
);
1683 * Re-layout the open windows as overlapping cascaded windows.
1685 private void cascadeWindows() {
1686 synchronized (windows
) {
1687 // Don't do anything if we are in the menu
1688 if (activeMenu
!= null) {
1693 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1694 Collections
.sort(sorted
);
1695 Collections
.reverse(sorted
);
1696 for (TWindow window
: sorted
) {
1701 if (x
> getScreen().getWidth()) {
1704 if (y
>= getScreen().getHeight()) {
1712 * Convenience function to add a timer.
1714 * @param duration number of milliseconds to wait between ticks
1715 * @param recurring if true, re-schedule this timer after every tick
1716 * @param action function to call when button is pressed
1719 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1720 final TAction action
) {
1722 TTimer timer
= new TTimer(duration
, recurring
, action
);
1723 synchronized (timers
) {
1730 * Convenience function to remove a timer.
1732 * @param timer timer to remove
1734 public final void removeTimer(final TTimer timer
) {
1735 synchronized (timers
) {
1736 timers
.remove(timer
);
1741 * Convenience function to spawn a message box.
1743 * @param title window title, will be centered along the top border
1744 * @param caption message to display. Use embedded newlines to get a
1746 * @return the new message box
1748 public final TMessageBox
messageBox(final String title
,
1749 final String caption
) {
1751 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1755 * Convenience function to spawn a message box.
1757 * @param title window title, will be centered along the top border
1758 * @param caption message to display. Use embedded newlines to get a
1760 * @param type one of the TMessageBox.Type constants. Default is
1762 * @return the new message box
1764 public final TMessageBox
messageBox(final String title
,
1765 final String caption
, final TMessageBox
.Type type
) {
1767 return new TMessageBox(this, title
, caption
, type
);
1771 * Convenience function to spawn an input box.
1773 * @param title window title, will be centered along the top border
1774 * @param caption message to display. Use embedded newlines to get a
1776 * @return the new input box
1778 public final TInputBox
inputBox(final String title
, final String caption
) {
1780 return new TInputBox(this, title
, caption
);
1784 * Convenience function to spawn an input box.
1786 * @param title window title, will be centered along the top border
1787 * @param caption message to display. Use embedded newlines to get a
1789 * @param text initial text to seed the field with
1790 * @return the new input box
1792 public final TInputBox
inputBox(final String title
, final String caption
,
1793 final String text
) {
1795 return new TInputBox(this, title
, caption
, text
);
1799 * Convenience function to open a terminal window.
1801 * @param x column relative to parent
1802 * @param y row relative to parent
1803 * @return the terminal new window
1805 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1806 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1810 * Convenience function to open a terminal window.
1812 * @param x column relative to parent
1813 * @param y row relative to parent
1814 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1815 * @return the terminal new window
1817 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1820 return new TTerminalWindow(this, x
, y
, flags
);