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
.AWTBackend
;
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
{
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 * WidgetEventHandler is the main event consumer loop. There are at most
78 * two such threads in existence: the primary for normal case and a
79 * secondary that is used for TMessageBox, TInputBox, and similar.
81 private class WidgetEventHandler
implements Runnable
{
83 * The main application.
85 private TApplication application
;
88 * Whether or not this WidgetEventHandler is the primary or secondary
91 private boolean primary
= true;
96 * @param application the main application
97 * @param primary if true, this is the primary event handler thread
99 public WidgetEventHandler(final TApplication application
,
100 final boolean primary
) {
102 this.application
= application
;
103 this.primary
= primary
;
112 while (!application
.quit
) {
114 // Wait until application notifies me
115 while (!application
.quit
) {
117 synchronized (application
.drainEventQueue
) {
118 if (application
.drainEventQueue
.size() > 0) {
123 synchronized (this) {
125 System
.err
.printf("%s %s sleep\n", this,
126 primary ?
"primary" : "secondary");
132 System
.err
.printf("%s %s AWAKE\n", this,
133 primary ?
"primary" : "secondary");
137 && (application
.secondaryEventReceiver
== null)
139 // Secondary thread, emergency exit. If we
140 // got here then something went wrong with
141 // the handoff between yield() and
143 synchronized (application
.primaryEventHandler
) {
144 application
.primaryEventHandler
.notify();
146 application
.secondaryEventHandler
= null;
147 throw new RuntimeException(
148 "secondary exited at wrong time");
152 } catch (InterruptedException e
) {
157 // Pull all events off the queue
159 TInputEvent event
= null;
160 synchronized (application
.drainEventQueue
) {
161 if (application
.drainEventQueue
.size() == 0) {
164 event
= application
.drainEventQueue
.remove(0);
166 // Wait for drawAll() or doIdle() to be done, then handle
168 boolean oldLock
= lockHandleEvent();
169 assert (oldLock
== false);
170 application
.repaint
= true;
172 primaryHandleEvent(event
);
174 secondaryHandleEvent(event
);
177 && (application
.secondaryEventReceiver
== null)
179 // Secondary thread, time to exit.
181 // DO NOT UNLOCK. Primary thread just came back from
182 // primaryHandleEvent() and will unlock in the else
183 // block below. Just wake it up.
184 synchronized (application
.primaryEventHandler
) {
185 application
.primaryEventHandler
.notify();
187 // Now eliminate my reference so that
188 // wakeEventHandler() resumes working on the primary.
189 application
.secondaryEventHandler
= null;
194 // Unlock. Either I am primary thread, or I am
195 // secondary thread and still running.
196 oldLock
= unlockHandleEvent();
197 assert (oldLock
== true);
201 // I have done some work of some kind. Tell the main run()
202 // loop to wake up now.
203 synchronized (application
) {
204 application
.notify();
207 } // while (true) (main runnable loop)
212 * The primary event handler thread.
214 private volatile WidgetEventHandler primaryEventHandler
;
217 * The secondary event handler thread.
219 private volatile WidgetEventHandler secondaryEventHandler
;
222 * The widget receiving events from the secondary event handler thread.
224 private volatile TWidget secondaryEventReceiver
;
227 * Spinlock for the primary and secondary event handlers.
228 * WidgetEventHandler.run() is responsible for setting this value.
230 private volatile boolean insideHandleEvent
= false;
233 * Wake the sleeping active event handler.
235 private void wakeEventHandler() {
236 if (secondaryEventHandler
!= null) {
237 synchronized (secondaryEventHandler
) {
238 secondaryEventHandler
.notify();
241 assert (primaryEventHandler
!= null);
242 synchronized (primaryEventHandler
) {
243 primaryEventHandler
.notify();
249 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
250 * spin indefinitely until unlockHandleEvent() is called.
252 * @return the old value of insideHandleEvent
254 private boolean lockHandleEvent() {
256 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
259 boolean oldValue
= true;
261 synchronized (this) {
262 // Wait for TApplication.run() to finish using the global state
263 // before allowing further event processing.
264 while (lockoutHandleEvent
== true) {}
266 oldValue
= insideHandleEvent
;
267 insideHandleEvent
= true;
271 System
.err
.printf(" ***\n");
277 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
278 * spin indefinitely until unlockHandleEvent() is called.
280 * @return the old value of insideHandleEvent
282 private boolean unlockHandleEvent() {
284 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
287 synchronized (this) {
288 boolean oldValue
= insideHandleEvent
;
289 insideHandleEvent
= false;
295 * Spinlock for the primary and secondary event handlers. When true, the
296 * event handlers will spinlock wait before calling handleEvent().
298 private volatile boolean lockoutHandleEvent
= false;
301 * TApplication.run() needs to be able rely on the global data structures
302 * being intact when calling doIdle() and drawAll(). Tell the event
303 * handlers to wait for an unlock before handling their events.
305 private void stopEventHandlers() {
307 System
.err
.printf(">> stopEventHandlers()");
310 lockoutHandleEvent
= true;
311 // Wait for the last event to finish processing before returning
312 // control to TApplication.run().
313 while (insideHandleEvent
== true) {}
316 System
.err
.printf(" XXX\n");
321 * TApplication.run() needs to be able rely on the global data structures
322 * being intact when calling doIdle() and drawAll(). Tell the event
323 * handlers that it is now OK to handle their events.
325 private void startEventHandlers() {
327 System
.err
.printf("<< startEventHandlers()\n");
329 lockoutHandleEvent
= false;
333 * Access to the physical screen, keyboard, and mouse.
335 private Backend backend
;
342 public final Screen
getScreen() {
343 return backend
.getScreen();
347 * Actual mouse coordinate X.
352 * Actual mouse coordinate Y.
357 * Old version of mouse coordinate X.
359 private int oldMouseX
;
362 * Old version mouse coordinate Y.
364 private int oldMouseY
;
367 * Event queue that is filled by run().
369 private List
<TInputEvent
> fillEventQueue
;
372 * Event queue that will be drained by either primary or secondary
375 private List
<TInputEvent
> drainEventQueue
;
378 * Top-level menus in this application.
380 private List
<TMenu
> menus
;
383 * Stack of activated sub-menus in this application.
385 private List
<TMenu
> subMenus
;
388 * The currently acive menu.
390 private TMenu activeMenu
= null;
393 * Active keyboard accelerators.
395 private Map
<TKeypress
, TMenuItem
> accelerators
;
398 * Windows and widgets pull colors from this ColorTheme.
400 private ColorTheme theme
;
403 * Get the color theme.
407 public final ColorTheme
getTheme() {
412 * The top-level windows (but not menus).
414 private List
<TWindow
> windows
;
417 * Timers that are being ticked.
419 private List
<TTimer
> timers
;
422 * When true, exit the application.
424 private volatile boolean quit
= false;
427 * When true, repaint the entire screen.
429 private volatile boolean repaint
= true;
432 * Y coordinate of the top edge of the desktop. For now this is a
433 * constant. Someday it would be nice to have a multi-line menu or
436 private static final int desktopTop
= 1;
439 * Get Y coordinate of the top edge of the desktop.
441 * @return Y coordinate of the top edge of the desktop
443 public final int getDesktopTop() {
448 * Y coordinate of the bottom edge of the desktop.
450 private int desktopBottom
;
453 * Get Y coordinate of the bottom edge of the desktop.
455 * @return Y coordinate of the bottom edge of the desktop
457 public final int getDesktopBottom() {
458 return desktopBottom
;
462 * Public constructor.
464 * @param input an InputStream connected to the remote user, or null for
465 * System.in. If System.in is used, then on non-Windows systems it will
466 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
467 * mode. input is always converted to a Reader with UTF-8 encoding.
468 * @param output an OutputStream connected to the remote user, or null
469 * for System.out. output is always converted to a Writer with UTF-8
471 * @throws UnsupportedEncodingException if an exception is thrown when
472 * creating the InputStreamReader
474 public TApplication(final InputStream input
,
475 final OutputStream output
) throws UnsupportedEncodingException
{
477 // AWT is the default backend on Windows unless explicitly overridden
479 boolean useAWT
= false;
480 if (System
.getProperty("os.name").startsWith("Windows")) {
483 if (System
.getProperty("jexer.AWT") != null) {
484 if (System
.getProperty("jexer.AWT", "false").equals("true")) {
493 backend
= new AWTBackend(this);
495 backend
= new ECMA48Backend(this, input
, output
);
497 theme
= new ColorTheme();
498 desktopBottom
= getScreen().getHeight() - 1;
499 fillEventQueue
= new ArrayList
<TInputEvent
>();
500 drainEventQueue
= new ArrayList
<TInputEvent
>();
501 windows
= new LinkedList
<TWindow
>();
502 menus
= new LinkedList
<TMenu
>();
503 subMenus
= new LinkedList
<TMenu
>();
504 timers
= new LinkedList
<TTimer
>();
505 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
507 // Setup the main consumer thread
508 primaryEventHandler
= new WidgetEventHandler(this, true);
509 (new Thread(primaryEventHandler
)).start();
513 * Invert the cell color at a position. This is used to track the mouse.
515 * @param x column position
516 * @param y row position
518 private void invertCell(final int x
, final int y
) {
519 synchronized (getScreen()) {
520 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
521 attr
.setForeColor(attr
.getForeColor().invert());
522 attr
.setBackColor(attr
.getBackColor().invert());
523 getScreen().putAttrXY(x
, y
, attr
, false);
530 public final void drawAll() {
532 System
.err
.printf("drawAll() enter\n");
536 synchronized (getScreen()) {
537 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
538 // The only thing that has happened is the mouse moved.
539 // Clear the old position and draw the new position.
540 invertCell(oldMouseX
, oldMouseY
);
541 invertCell(mouseX
, mouseY
);
546 if (getScreen().isDirty()) {
547 backend
.flushScreen();
553 System
.err
.printf("drawAll() REDRAW\n");
556 // If true, the cursor is not visible
557 boolean cursor
= false;
559 // Start with a clean screen
562 // Draw the background
563 CellAttributes background
= theme
.getColor("tapplication.background");
564 getScreen().putAll(GraphicsChars
.HATCH
, background
);
566 // Draw each window in reverse Z order
567 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
568 Collections
.sort(sorted
);
569 Collections
.reverse(sorted
);
570 for (TWindow window
: sorted
) {
571 window
.drawChildren();
574 // Draw the blank menubar line - reset the screen clipping first so
575 // it won't trim it out.
576 getScreen().resetClipping();
577 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
578 theme
.getColor("tmenu"));
579 // Now draw the menus.
581 for (TMenu menu
: menus
) {
582 CellAttributes menuColor
;
583 CellAttributes menuMnemonicColor
;
584 if (menu
.getActive()) {
585 menuColor
= theme
.getColor("tmenu.highlighted");
586 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
588 menuColor
= theme
.getColor("tmenu");
589 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
591 // Draw the menu title
592 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
594 getScreen().putStrXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
595 // Draw the highlight character
596 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
597 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
599 if (menu
.getActive()) {
601 // Reset the screen clipping so we can draw the next title.
602 getScreen().resetClipping();
604 x
+= menu
.getTitle().length() + 2;
607 for (TMenu menu
: subMenus
) {
608 // Reset the screen clipping so we can draw the next sub-menu.
609 getScreen().resetClipping();
613 // Draw the mouse pointer
614 invertCell(mouseX
, mouseY
);
616 // Place the cursor if it is visible
617 TWidget activeWidget
= null;
618 if (sorted
.size() > 0) {
619 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
620 if (activeWidget
.visibleCursor()) {
621 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
622 activeWidget
.getCursorAbsoluteY());
629 getScreen().hideCursor();
632 // Flush the screen contents
633 backend
.flushScreen();
639 * Run this application until it exits.
641 public final void run() {
643 // Timeout is in milliseconds, so default timeout after 1 second
647 // If I've got no updates to render, wait for something from the
648 // backend or a timer.
650 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
652 // Never sleep longer than 100 millis, to get windows with
653 // background tasks an opportunity to update the display.
654 timeout
= getSleepTime(100);
656 // See if there are any definitely events waiting to be
657 // processed. If so, do not wait -- either there is I/O
658 // coming in or the primary/secondary threads are still
660 synchronized (drainEventQueue
) {
661 if (drainEventQueue
.size() > 0) {
665 synchronized (fillEventQueue
) {
666 if (fillEventQueue
.size() > 0) {
673 // As of now, I've got nothing to do: no I/O, nothing from
674 // the consumer threads, no timers that need to run ASAP. So
675 // wait until either the backend or the consumer threads have
678 synchronized (this) {
681 } catch (InterruptedException e
) {
682 // I'm awake and don't care why, let's see what's going
688 // Pull any pending I/O events
689 backend
.getEvents(fillEventQueue
);
691 // Dispatch each event to the appropriate handler, one at a time.
693 TInputEvent event
= null;
694 synchronized (fillEventQueue
) {
695 if (fillEventQueue
.size() == 0) {
698 event
= fillEventQueue
.remove(0);
700 metaHandleEvent(event
);
703 // Wake a consumer thread if we have any pending events.
704 synchronized (drainEventQueue
) {
705 if (drainEventQueue
.size() > 0) {
710 // Prevent stepping on the primary or secondary event handler.
713 // Process timers and call doIdle()'s
717 synchronized (getScreen()) {
721 // Let the event handlers run again.
722 startEventHandlers();
726 // Shutdown the event consumer threads
727 if (secondaryEventHandler
!= null) {
728 synchronized (secondaryEventHandler
) {
729 secondaryEventHandler
.notify();
732 if (primaryEventHandler
!= null) {
733 synchronized (primaryEventHandler
) {
734 primaryEventHandler
.notify();
738 // Shutdown the user I/O thread(s)
741 // Close all the windows. This gives them an opportunity to release
748 * Peek at certain application-level events, add to eventQueue, and wake
749 * up the consuming Thread.
751 * @param event the input event to consume
753 private void metaHandleEvent(final TInputEvent event
) {
756 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
757 event
)); System
.err
.flush();
761 // Do no more processing if the application is already trying
766 // Special application-wide events -------------------------------
769 if (event
instanceof TCommandEvent
) {
770 TCommandEvent command
= (TCommandEvent
) event
;
771 if (command
.getCmd().equals(cmAbort
)) {
778 if (event
instanceof TResizeEvent
) {
779 TResizeEvent resize
= (TResizeEvent
) event
;
780 synchronized (getScreen()) {
781 getScreen().setDimensions(resize
.getWidth(),
783 desktopBottom
= getScreen().getHeight() - 1;
792 // Peek at the mouse position
793 if (event
instanceof TMouseEvent
) {
794 TMouseEvent mouse
= (TMouseEvent
) event
;
795 synchronized (getScreen()) {
796 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
799 mouseX
= mouse
.getX();
800 mouseY
= mouse
.getY();
805 // Put into the main queue
806 synchronized (drainEventQueue
) {
807 drainEventQueue
.add(event
);
812 * Dispatch one event to the appropriate widget or application-level
813 * event handler. This is the primary event handler, it has the normal
814 * application-wide event handling.
816 * @param event the input event to consume
817 * @see #secondaryHandleEvent(TInputEvent event)
819 private void primaryHandleEvent(final TInputEvent event
) {
822 System
.err
.printf("Handle event: %s\n", event
);
825 // Special application-wide events -----------------------------------
827 // Peek at the mouse position
828 if (event
instanceof TMouseEvent
) {
829 // See if we need to switch focus to another window or the menu
830 checkSwitchFocus((TMouseEvent
) event
);
833 // Handle menu events
834 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
835 TMenu menu
= activeMenu
;
837 if (event
instanceof TMouseEvent
) {
838 TMouseEvent mouse
= (TMouseEvent
) event
;
840 while (subMenus
.size() > 0) {
841 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
842 if (subMenu
.mouseWouldHit(mouse
)) {
845 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
846 && (!mouse
.getMouse1())
847 && (!mouse
.getMouse2())
848 && (!mouse
.getMouse3())
849 && (!mouse
.getMouseWheelUp())
850 && (!mouse
.getMouseWheelDown())
854 // We navigated away from a sub-menu, so close it
858 // Convert the mouse relative x/y to menu coordinates
859 assert (mouse
.getX() == mouse
.getAbsoluteX());
860 assert (mouse
.getY() == mouse
.getAbsoluteY());
861 if (subMenus
.size() > 0) {
862 menu
= subMenus
.get(subMenus
.size() - 1);
864 mouse
.setX(mouse
.getX() - menu
.getX());
865 mouse
.setY(mouse
.getY() - menu
.getY());
867 menu
.handleEvent(event
);
871 if (event
instanceof TKeypressEvent
) {
872 TKeypressEvent keypress
= (TKeypressEvent
) event
;
874 // See if this key matches an accelerator, and if so dispatch the
876 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
877 TMenuItem item
= null;
878 synchronized (accelerators
) {
879 item
= accelerators
.get(keypressLowercase
);
882 if (item
.getEnabled()) {
883 // Let the menu item dispatch
888 // Handle the keypress
889 if (onKeypress(keypress
)) {
894 if (event
instanceof TCommandEvent
) {
895 if (onCommand((TCommandEvent
) event
)) {
900 if (event
instanceof TMenuEvent
) {
901 if (onMenu((TMenuEvent
) event
)) {
906 // Dispatch events to the active window -------------------------------
907 for (TWindow window
: windows
) {
908 if (window
.getActive()) {
909 if (event
instanceof TMouseEvent
) {
910 TMouseEvent mouse
= (TMouseEvent
) event
;
911 // Convert the mouse relative x/y to window coordinates
912 assert (mouse
.getX() == mouse
.getAbsoluteX());
913 assert (mouse
.getY() == mouse
.getAbsoluteY());
914 mouse
.setX(mouse
.getX() - window
.getX());
915 mouse
.setY(mouse
.getY() - window
.getY());
918 System
.err
.printf("TApplication dispatch event: %s\n",
921 window
.handleEvent(event
);
927 * Dispatch one event to the appropriate widget or application-level
928 * event handler. This is the secondary event handler used by certain
929 * special dialogs (currently TMessageBox and TFileOpenBox).
931 * @param event the input event to consume
932 * @see #primaryHandleEvent(TInputEvent event)
934 private void secondaryHandleEvent(final TInputEvent event
) {
935 secondaryEventReceiver
.handleEvent(event
);
939 * Enable a widget to override the primary event thread.
941 * @param widget widget that will receive events
943 public final void enableSecondaryEventReceiver(final TWidget widget
) {
944 assert (secondaryEventReceiver
== null);
945 assert (secondaryEventHandler
== null);
946 assert (widget
instanceof TMessageBox
);
947 secondaryEventReceiver
= widget
;
948 secondaryEventHandler
= new WidgetEventHandler(this, false);
949 (new Thread(secondaryEventHandler
)).start();
953 * Yield to the secondary thread.
955 public final void yield() {
956 assert (secondaryEventReceiver
!= null);
957 // This is where we handoff the event handler lock from the primary
958 // to secondary thread. We unlock here, and in a future loop the
959 // secondary thread locks again. When it gives up, we have the
961 boolean oldLock
= unlockHandleEvent();
962 assert (oldLock
== true);
964 while (secondaryEventReceiver
!= null) {
965 synchronized (primaryEventHandler
) {
967 primaryEventHandler
.wait();
968 } catch (InterruptedException e
) {
976 * Do stuff when there is no user input.
978 private void doIdle() {
980 System
.err
.printf("doIdle()\n");
983 // Now run any timers that have timed out
984 Date now
= new Date();
985 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
986 for (TTimer timer
: timers
) {
987 if (timer
.getNextTick().getTime() <= now
.getTime()) {
989 if (timer
.recurring
) {
990 keepTimers
.add(timer
);
993 keepTimers
.add(timer
);
999 for (TWindow window
: windows
) {
1005 * Get the amount of time I can sleep before missing a Timer tick.
1007 * @param timeout = initial (maximum) timeout in millis
1008 * @return number of milliseconds between now and the next timer event
1010 private long getSleepTime(final long timeout
) {
1011 Date now
= new Date();
1012 long nowTime
= now
.getTime();
1013 long sleepTime
= timeout
;
1014 for (TTimer timer
: timers
) {
1015 long nextTickTime
= timer
.getNextTick().getTime();
1016 if (nextTickTime
< nowTime
) {
1020 long timeDifference
= nextTickTime
- nowTime
;
1021 if (timeDifference
< sleepTime
) {
1022 sleepTime
= timeDifference
;
1025 assert (sleepTime
>= 0);
1026 assert (sleepTime
<= timeout
);
1031 * Close window. Note that the window's destructor is NOT called by this
1032 * method, instead the GC is assumed to do the cleanup.
1034 * @param window the window to remove
1036 public final void closeWindow(final TWindow window
) {
1037 synchronized (windows
) {
1038 int z
= window
.getZ();
1040 Collections
.sort(windows
);
1042 TWindow activeWindow
= null;
1043 for (TWindow w
: windows
) {
1045 w
.setZ(w
.getZ() - 1);
1046 if (w
.getZ() == 0) {
1048 assert (activeWindow
== null);
1057 // Perform window cleanup
1060 // Check if we are closing a TMessageBox or similar
1061 if (secondaryEventReceiver
!= null) {
1062 assert (secondaryEventHandler
!= null);
1064 // Do not send events to the secondaryEventReceiver anymore, the
1065 // window is closed.
1066 secondaryEventReceiver
= null;
1068 // Wake the secondary thread, it will wake the primary as it
1070 synchronized (secondaryEventHandler
) {
1071 secondaryEventHandler
.notify();
1077 * Switch to the next window.
1079 * @param forward if true, then switch to the next window in the list,
1080 * otherwise switch to the previous window in the list
1082 public final void switchWindow(final boolean forward
) {
1083 // Only switch if there are multiple windows
1084 if (windows
.size() < 2) {
1088 synchronized (windows
) {
1090 // Swap z/active between active window and the next in the list
1091 int activeWindowI
= -1;
1092 for (int i
= 0; i
< windows
.size(); i
++) {
1093 if (windows
.get(i
).getActive()) {
1098 assert (activeWindowI
>= 0);
1100 // Do not switch if a window is modal
1101 if (windows
.get(activeWindowI
).isModal()) {
1107 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1109 if (activeWindowI
== 0) {
1110 nextWindowI
= windows
.size() - 1;
1112 nextWindowI
= activeWindowI
- 1;
1115 windows
.get(activeWindowI
).setActive(false);
1116 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1117 windows
.get(nextWindowI
).setZ(0);
1118 windows
.get(nextWindowI
).setActive(true);
1120 } // synchronized (windows)
1125 * Add a window to my window list and make it active.
1127 * @param window new window to add
1129 public final void addWindow(final TWindow window
) {
1130 synchronized (windows
) {
1131 // Do not allow a modal window to spawn a non-modal window
1132 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1133 assert (window
.isModal());
1135 for (TWindow w
: windows
) {
1137 w
.setZ(w
.getZ() + 1);
1139 windows
.add(window
);
1140 window
.setActive(true);
1146 * Check if there is a system-modal window on top.
1148 * @return true if the active window is modal
1150 private boolean modalWindowActive() {
1151 if (windows
.size() == 0) {
1154 return windows
.get(windows
.size() - 1).isModal();
1158 * Check if a mouse event would hit either the active menu or any open
1161 * @param mouse mouse event
1162 * @return true if the mouse would hit the active menu or an open
1165 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1166 assert (activeMenu
!= null);
1167 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1168 Collections
.reverse(menus
);
1169 for (TMenu menu
: menus
) {
1170 if (menu
.mouseWouldHit(mouse
)) {
1174 return activeMenu
.mouseWouldHit(mouse
);
1178 * See if we need to switch window or activate the menu based on
1181 * @param mouse mouse event
1183 private void checkSwitchFocus(final TMouseEvent mouse
) {
1185 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1186 && (activeMenu
!= null)
1187 && (mouse
.getAbsoluteY() != 0)
1188 && (!mouseOnMenu(mouse
))
1190 // They clicked outside the active menu, turn it off
1191 activeMenu
.setActive(false);
1193 for (TMenu menu
: subMenus
) {
1194 menu
.setActive(false);
1200 // See if they hit the menu bar
1201 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1202 && (mouse
.getMouse1())
1203 && (!modalWindowActive())
1204 && (mouse
.getAbsoluteY() == 0)
1207 for (TMenu menu
: subMenus
) {
1208 menu
.setActive(false);
1212 // They selected the menu, go activate it
1213 for (TMenu menu
: menus
) {
1214 if ((mouse
.getAbsoluteX() >= menu
.getX())
1215 && (mouse
.getAbsoluteX() < menu
.getX()
1216 + menu
.getTitle().length() + 2)
1218 menu
.setActive(true);
1221 menu
.setActive(false);
1227 // See if they hit the menu bar
1228 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1229 && (mouse
.getMouse1())
1230 && (activeMenu
!= null)
1231 && (mouse
.getAbsoluteY() == 0)
1234 TMenu oldMenu
= activeMenu
;
1235 for (TMenu menu
: subMenus
) {
1236 menu
.setActive(false);
1240 // See if we should switch menus
1241 for (TMenu menu
: menus
) {
1242 if ((mouse
.getAbsoluteX() >= menu
.getX())
1243 && (mouse
.getAbsoluteX() < menu
.getX()
1244 + menu
.getTitle().length() + 2)
1246 menu
.setActive(true);
1250 if (oldMenu
!= activeMenu
) {
1251 // They switched menus
1252 oldMenu
.setActive(false);
1257 // Only switch if there are multiple windows
1258 if (windows
.size() < 2) {
1262 // Switch on the upclick
1263 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1267 synchronized (windows
) {
1268 Collections
.sort(windows
);
1269 if (windows
.get(0).isModal()) {
1270 // Modal windows don't switch
1274 for (TWindow window
: windows
) {
1275 assert (!window
.isModal());
1276 if (window
.mouseWouldHit(mouse
)) {
1277 if (window
== windows
.get(0)) {
1278 // Clicked on the same window, nothing to do
1282 // We will be switching to another window
1283 assert (windows
.get(0).getActive());
1284 assert (!window
.getActive());
1285 windows
.get(0).setActive(false);
1286 windows
.get(0).setZ(window
.getZ());
1288 window
.setActive(true);
1294 // Clicked on the background, nothing to do
1299 * Turn off the menu.
1301 public final void closeMenu() {
1302 if (activeMenu
!= null) {
1303 activeMenu
.setActive(false);
1305 for (TMenu menu
: subMenus
) {
1306 menu
.setActive(false);
1313 * Turn off a sub-menu.
1315 public final void closeSubMenu() {
1316 assert (activeMenu
!= null);
1317 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1318 assert (item
!= null);
1319 item
.setActive(false);
1320 subMenus
.remove(subMenus
.size() - 1);
1324 * Switch to the next menu.
1326 * @param forward if true, then switch to the next menu in the list,
1327 * otherwise switch to the previous menu in the list
1329 public final void switchMenu(final boolean forward
) {
1330 assert (activeMenu
!= null);
1332 for (TMenu menu
: subMenus
) {
1333 menu
.setActive(false);
1337 for (int i
= 0; i
< menus
.size(); i
++) {
1338 if (activeMenu
== menus
.get(i
)) {
1340 if (i
< menus
.size() - 1) {
1348 activeMenu
.setActive(false);
1349 activeMenu
= menus
.get(i
);
1350 activeMenu
.setActive(true);
1357 * Method that TApplication subclasses can override to handle menu or
1358 * posted command events.
1360 * @param command command event
1361 * @return if true, this event was consumed
1363 protected boolean onCommand(final TCommandEvent command
) {
1364 // Default: handle cmExit
1365 if (command
.equals(cmExit
)) {
1366 if (messageBox("Confirmation", "Exit application?",
1367 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1373 if (command
.equals(cmShell
)) {
1374 openTerminal(0, 0, TWindow
.RESIZABLE
);
1378 if (command
.equals(cmTile
)) {
1382 if (command
.equals(cmCascade
)) {
1386 if (command
.equals(cmCloseAll
)) {
1395 * Method that TApplication subclasses can override to handle menu
1398 * @param menu menu event
1399 * @return if true, this event was consumed
1401 protected boolean onMenu(final TMenuEvent menu
) {
1403 // Default: handle MID_EXIT
1404 if (menu
.getId() == TMenu
.MID_EXIT
) {
1405 if (messageBox("Confirmation", "Exit application?",
1406 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1412 if (menu
.getId() == TMenu
.MID_SHELL
) {
1413 openTerminal(0, 0, TWindow
.RESIZABLE
);
1417 if (menu
.getId() == TMenu
.MID_TILE
) {
1421 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1425 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1433 * Method that TApplication subclasses can override to handle keystrokes.
1435 * @param keypress keystroke event
1436 * @return if true, this event was consumed
1438 protected boolean onKeypress(final TKeypressEvent keypress
) {
1439 // Default: only menu shortcuts
1441 // Process Alt-F, Alt-E, etc. menu shortcut keys
1442 if (!keypress
.getKey().getIsKey()
1443 && keypress
.getKey().getAlt()
1444 && !keypress
.getKey().getCtrl()
1445 && (activeMenu
== null)
1448 assert (subMenus
.size() == 0);
1450 for (TMenu menu
: menus
) {
1451 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1452 == Character
.toLowerCase(keypress
.getKey().getCh())
1455 menu
.setActive(true);
1465 * Add a keyboard accelerator to the global hash.
1467 * @param item menu item this accelerator relates to
1468 * @param keypress keypress that will dispatch a TMenuEvent
1470 public final void addAccelerator(final TMenuItem item
,
1471 final TKeypress keypress
) {
1473 synchronized (accelerators
) {
1474 assert (accelerators
.get(keypress
) == null);
1475 accelerators
.put(keypress
, item
);
1480 * Recompute menu x positions based on their title length.
1482 public final void recomputeMenuX() {
1484 for (TMenu menu
: menus
) {
1486 x
+= menu
.getTitle().length() + 2;
1491 * Post an event to process and turn off the menu.
1493 * @param event new event to add to the queue
1495 public final void addMenuEvent(final TInputEvent event
) {
1496 synchronized (fillEventQueue
) {
1497 fillEventQueue
.add(event
);
1503 * Add a sub-menu to the list of open sub-menus.
1505 * @param menu sub-menu
1507 public final void addSubMenu(final TMenu menu
) {
1512 * Convenience function to add a top-level menu.
1514 * @param title menu title
1515 * @return the new menu
1517 public final TMenu
addMenu(final String title
) {
1520 TMenu menu
= new TMenu(this, x
, y
, title
);
1527 * Convenience function to add a default "File" menu.
1529 * @return the new menu
1531 public final TMenu
addFileMenu() {
1532 TMenu fileMenu
= addMenu("&File");
1533 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1534 fileMenu
.addSeparator();
1535 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1536 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1541 * Convenience function to add a default "Edit" menu.
1543 * @return the new menu
1545 public final TMenu
addEditMenu() {
1546 TMenu editMenu
= addMenu("&Edit");
1547 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1548 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1549 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1550 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1555 * Convenience function to add a default "Window" menu.
1557 * @return the new menu
1559 public final TMenu
addWindowMenu() {
1560 TMenu windowMenu
= addMenu("&Window");
1561 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1562 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1563 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1564 windowMenu
.addSeparator();
1565 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1566 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1567 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1568 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1569 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1574 * Close all open windows.
1576 private void closeAllWindows() {
1577 // Don't do anything if we are in the menu
1578 if (activeMenu
!= null) {
1582 synchronized (windows
) {
1583 for (TWindow window
: windows
) {
1584 closeWindow(window
);
1590 * Re-layout the open windows as non-overlapping tiles. This produces
1591 * almost the same results as Turbo Pascal 7.0's IDE.
1593 private void tileWindows() {
1594 synchronized (windows
) {
1595 // Don't do anything if we are in the menu
1596 if (activeMenu
!= null) {
1599 int z
= windows
.size();
1605 a
= (int)(Math
.sqrt(z
));
1609 if (((a
* b
) + c
) == z
) {
1617 int newWidth
= (getScreen().getWidth() / a
);
1618 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1619 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1621 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1622 Collections
.sort(sorted
);
1623 Collections
.reverse(sorted
);
1624 for (int i
= 0; i
< sorted
.size(); i
++) {
1625 int logicalX
= i
/ b
;
1626 int logicalY
= i
% b
;
1627 if (i
>= ((a
- 1) * b
)) {
1629 logicalY
= i
- ((a
- 1) * b
);
1632 TWindow w
= sorted
.get(i
);
1633 w
.setX(logicalX
* newWidth
);
1634 w
.setWidth(newWidth
);
1635 if (i
>= ((a
- 1) * b
)) {
1636 w
.setY((logicalY
* newHeight2
) + 1);
1637 w
.setHeight(newHeight2
);
1639 w
.setY((logicalY
* newHeight1
) + 1);
1640 w
.setHeight(newHeight1
);
1647 * Re-layout the open windows as overlapping cascaded windows.
1649 private void cascadeWindows() {
1650 synchronized (windows
) {
1651 // Don't do anything if we are in the menu
1652 if (activeMenu
!= null) {
1657 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1658 Collections
.sort(sorted
);
1659 Collections
.reverse(sorted
);
1660 for (TWindow window
: sorted
) {
1665 if (x
> getScreen().getWidth()) {
1668 if (y
>= getScreen().getHeight()) {
1676 * Convenience function to add a timer.
1678 * @param duration number of milliseconds to wait between ticks
1679 * @param recurring if true, re-schedule this timer after every tick
1680 * @param action function to call when button is pressed
1683 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1684 final TAction action
) {
1686 TTimer timer
= new TTimer(duration
, recurring
, action
);
1687 synchronized (timers
) {
1694 * Convenience function to remove a timer.
1696 * @param timer timer to remove
1698 public final void removeTimer(final TTimer timer
) {
1699 synchronized (timers
) {
1700 timers
.remove(timer
);
1705 * Convenience function to spawn a message box.
1707 * @param title window title, will be centered along the top border
1708 * @param caption message to display. Use embedded newlines to get a
1710 * @return the new message box
1712 public final TMessageBox
messageBox(final String title
,
1713 final String caption
) {
1715 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1719 * Convenience function to spawn a message box.
1721 * @param title window title, will be centered along the top border
1722 * @param caption message to display. Use embedded newlines to get a
1724 * @param type one of the TMessageBox.Type constants. Default is
1726 * @return the new message box
1728 public final TMessageBox
messageBox(final String title
,
1729 final String caption
, final TMessageBox
.Type type
) {
1731 return new TMessageBox(this, title
, caption
, type
);
1735 * Convenience function to spawn an input box.
1737 * @param title window title, will be centered along the top border
1738 * @param caption message to display. Use embedded newlines to get a
1740 * @return the new input box
1742 public final TInputBox
inputBox(final String title
, final String caption
) {
1744 return new TInputBox(this, title
, caption
);
1748 * Convenience function to spawn an input box.
1750 * @param title window title, will be centered along the top border
1751 * @param caption message to display. Use embedded newlines to get a
1753 * @param text initial text to seed the field with
1754 * @return the new input box
1756 public final TInputBox
inputBox(final String title
, final String caption
,
1757 final String text
) {
1759 return new TInputBox(this, title
, caption
, text
);
1763 * Convenience function to open a terminal window.
1765 * @param x column relative to parent
1766 * @param y row relative to parent
1767 * @return the terminal new window
1769 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1770 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1774 * Convenience function to open a terminal window.
1776 * @param x column relative to parent
1777 * @param y row relative to parent
1778 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1779 * @return the terminal new window
1781 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1784 return new TTerminalWindow(this, x
, y
, flags
);