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
.*;
60 import static jexer
.TKeypress
.*;
63 * TApplication sets up a full Text User Interface application.
65 public class TApplication
{
68 * WidgetEventHandler is the main event consumer loop. There are at most
69 * two such threads in existence: the primary for normal case and a
70 * secondary that is used for TMessageBox, TInputBox, and similar.
72 private class WidgetEventHandler
implements Runnable
{
74 * The main application.
76 private TApplication application
;
79 * Whether or not this WidgetEventHandler is the primary or secondary
82 private boolean primary
= true;
87 * @param application the main application
88 * @param primary if true, this is the primary event handler thread
90 public WidgetEventHandler(final TApplication application
,
91 final boolean primary
) {
93 this.application
= application
;
94 this.primary
= primary
;
103 while (!application
.quit
) {
105 // Wait until application notifies me
106 while (!application
.quit
) {
108 synchronized (application
.drainEventQueue
) {
109 if (application
.drainEventQueue
.size() > 0) {
113 synchronized (application
) {
116 && (application
.secondaryEventReceiver
== null)
118 // Secondary thread, time to exit
123 } catch (InterruptedException e
) {
128 // Pull all events off the queue
130 TInputEvent event
= null;
131 synchronized (application
.drainEventQueue
) {
132 if (application
.drainEventQueue
.size() == 0) {
135 event
= application
.drainEventQueue
.remove(0);
138 primaryHandleEvent(event
);
140 secondaryHandleEvent(event
);
143 && (application
.secondaryEventReceiver
== null)
145 // Secondary thread, time to exit
149 } // while (true) (main runnable loop)
154 * The primary event handler thread.
156 private WidgetEventHandler primaryEventHandler
;
159 * The secondary event handler thread.
161 private WidgetEventHandler secondaryEventHandler
;
164 * The widget receiving events from the secondary event handler thread.
166 private TWidget secondaryEventReceiver
;
169 * Access to the physical screen, keyboard, and mouse.
171 private Backend backend
;
178 public final Screen
getScreen() {
179 return backend
.getScreen();
183 * Actual mouse coordinate X.
188 * Actual mouse coordinate Y.
193 * Event queue that is filled by run().
195 private List
<TInputEvent
> fillEventQueue
;
198 * Event queue that will be drained by either primary or secondary
201 private List
<TInputEvent
> drainEventQueue
;
204 * Top-level menus in this application.
206 private List
<TMenu
> menus
;
209 * Stack of activated sub-menus in this application.
211 private List
<TMenu
> subMenus
;
214 * The currently acive menu.
216 private TMenu activeMenu
= null;
219 * Active keyboard accelerators.
221 private Map
<TKeypress
, TMenuItem
> accelerators
;
224 * Windows and widgets pull colors from this ColorTheme.
226 private ColorTheme theme
;
229 * Get the color theme.
233 public final ColorTheme
getTheme() {
238 * The top-level windows (but not menus).
240 private List
<TWindow
> windows
;
243 * Timers that are being ticked.
245 private List
<TTimer
> timers
;
248 * When true, exit the application.
250 private boolean quit
= false;
253 * When true, repaint the entire screen.
255 private boolean repaint
= true;
258 * Request full repaint on next screen refresh.
260 public final void setRepaint() {
265 * When true, just flush updates from the screen.
267 private boolean flush
= false;
270 * Y coordinate of the top edge of the desktop. For now this is a
271 * constant. Someday it would be nice to have a multi-line menu or
274 private static final int desktopTop
= 1;
277 * Get Y coordinate of the top edge of the desktop.
279 * @return Y coordinate of the top edge of the desktop
281 public final int getDesktopTop() {
286 * Y coordinate of the bottom edge of the desktop.
288 private int desktopBottom
;
291 * Get Y coordinate of the bottom edge of the desktop.
293 * @return Y coordinate of the bottom edge of the desktop
295 public final int getDesktopBottom() {
296 return desktopBottom
;
300 * Public constructor.
302 * @param input an InputStream connected to the remote user, or null for
303 * System.in. If System.in is used, then on non-Windows systems it will
304 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
305 * mode. input is always converted to a Reader with UTF-8 encoding.
306 * @param output an OutputStream connected to the remote user, or null
307 * for System.out. output is always converted to a Writer with UTF-8
309 * @throws UnsupportedEncodingException if an exception is thrown when
310 * creating the InputStreamReader
312 public TApplication(final InputStream input
,
313 final OutputStream output
) throws UnsupportedEncodingException
{
315 // AWT is the default backend on Windows unless explicitly overridden
317 boolean useAWT
= false;
318 if (System
.getProperty("os.name").startsWith("Windows")) {
321 if (System
.getProperty("jexer.AWT") != null) {
322 if (System
.getProperty("jexer.AWT", "false").equals("true")) {
331 backend
= new AWTBackend();
333 backend
= new ECMA48Backend(input
, output
);
335 theme
= new ColorTheme();
336 desktopBottom
= getScreen().getHeight() - 1;
337 fillEventQueue
= new ArrayList
<TInputEvent
>();
338 drainEventQueue
= new ArrayList
<TInputEvent
>();
339 windows
= new LinkedList
<TWindow
>();
340 menus
= new LinkedList
<TMenu
>();
341 subMenus
= new LinkedList
<TMenu
>();
342 timers
= new LinkedList
<TTimer
>();
343 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
345 // Setup the main consumer thread
346 primaryEventHandler
= new WidgetEventHandler(this, true);
347 (new Thread(primaryEventHandler
)).start();
351 * Invert the cell at the mouse pointer position.
353 private void drawMouse() {
354 CellAttributes attr
= getScreen().getAttrXY(mouseX
, mouseY
);
355 attr
.setForeColor(attr
.getForeColor().invert());
356 attr
.setBackColor(attr
.getBackColor().invert());
357 getScreen().putAttrXY(mouseX
, mouseY
, attr
, false);
360 if (windows
.size() == 0) {
368 public final void drawAll() {
369 if ((flush
) && (!repaint
)) {
370 backend
.flushScreen();
379 // If true, the cursor is not visible
380 boolean cursor
= false;
382 // Start with a clean screen
385 // Draw the background
386 CellAttributes background
= theme
.getColor("tapplication.background");
387 getScreen().putAll(GraphicsChars
.HATCH
, background
);
389 // Draw each window in reverse Z order
390 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
391 Collections
.sort(sorted
);
392 Collections
.reverse(sorted
);
393 for (TWindow window
: sorted
) {
394 window
.drawChildren();
397 // Draw the blank menubar line - reset the screen clipping first so
398 // it won't trim it out.
399 getScreen().resetClipping();
400 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
401 theme
.getColor("tmenu"));
402 // Now draw the menus.
404 for (TMenu menu
: menus
) {
405 CellAttributes menuColor
;
406 CellAttributes menuMnemonicColor
;
407 if (menu
.getActive()) {
408 menuColor
= theme
.getColor("tmenu.highlighted");
409 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
411 menuColor
= theme
.getColor("tmenu");
412 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
414 // Draw the menu title
415 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
417 getScreen().putStrXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
418 // Draw the highlight character
419 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
420 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
422 if (menu
.getActive()) {
424 // Reset the screen clipping so we can draw the next title.
425 getScreen().resetClipping();
427 x
+= menu
.getTitle().length() + 2;
430 for (TMenu menu
: subMenus
) {
431 // Reset the screen clipping so we can draw the next sub-menu.
432 getScreen().resetClipping();
436 // Draw the mouse pointer
439 // Place the cursor if it is visible
440 TWidget activeWidget
= null;
441 if (sorted
.size() > 0) {
442 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
443 if (activeWidget
.visibleCursor()) {
444 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
445 activeWidget
.getCursorAbsoluteY());
452 getScreen().hideCursor();
455 // Flush the screen contents
456 backend
.flushScreen();
463 * Run this application until it exits.
465 public final void run() {
467 // Timeout is in milliseconds, so default timeout after 1 second
469 int timeout
= getSleepTime(1000);
471 // See if there are any definitely events waiting to be processed
472 // or a screen redraw to do. If so, do not wait if there is no
474 synchronized (drainEventQueue
) {
475 if (drainEventQueue
.size() > 0) {
479 synchronized (fillEventQueue
) {
480 if (fillEventQueue
.size() > 0) {
485 // Pull any pending I/O events
486 backend
.getEvents(fillEventQueue
, timeout
);
488 // Dispatch each event to the appropriate handler, one at a time.
490 TInputEvent event
= null;
491 synchronized (fillEventQueue
) {
492 if (fillEventQueue
.size() == 0) {
495 event
= fillEventQueue
.remove(0);
497 metaHandleEvent(event
);
500 // Process timers and call doIdle()'s
504 synchronized (getScreen()) {
509 // Shutdown the consumer threads
510 synchronized (this) {
518 * Peek at certain application-level events, add to eventQueue, and wake
519 * up the consuming Thread.
521 * @param event the input event to consume
523 private void metaHandleEvent(final TInputEvent event
) {
526 System.err.printf(String.format("metaHandleEvents event: %s\n",
527 event)); System.err.flush();
531 // Do no more processing if the application is already trying
536 // Special application-wide events -------------------------------
539 if (event
instanceof TCommandEvent
) {
540 TCommandEvent command
= (TCommandEvent
) event
;
541 if (command
.getCmd().equals(cmAbort
)) {
548 if (event
instanceof TResizeEvent
) {
549 TResizeEvent resize
= (TResizeEvent
) event
;
550 getScreen().setDimensions(resize
.getWidth(),
552 desktopBottom
= getScreen().getHeight() - 1;
559 // Peek at the mouse position
560 if (event
instanceof TMouseEvent
) {
561 TMouseEvent mouse
= (TMouseEvent
) event
;
562 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
563 mouseX
= mouse
.getX();
564 mouseY
= mouse
.getY();
569 // Put into the main queue
570 synchronized (drainEventQueue
) {
571 drainEventQueue
.add(event
);
574 // Wake all threads: primary thread will either be consuming events
575 // again or waiting in yield(), and secondary thread will either not
576 // exist or consuming events.
577 synchronized (this) {
583 * Dispatch one event to the appropriate widget or application-level
584 * event handler. This is the primary event handler, it has the normal
585 * application-wide event handling.
587 * @param event the input event to consume
588 * @see #secondaryHandleEvent(TInputEvent event)
590 private void primaryHandleEvent(final TInputEvent event
) {
592 // System.err.printf("Handle event: %s\n", event);
594 // Special application-wide events -----------------------------------
596 // Peek at the mouse position
597 if (event
instanceof TMouseEvent
) {
598 // See if we need to switch focus to another window or the menu
599 checkSwitchFocus((TMouseEvent
) event
);
602 // Handle menu events
603 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
604 TMenu menu
= activeMenu
;
606 if (event
instanceof TMouseEvent
) {
607 TMouseEvent mouse
= (TMouseEvent
) event
;
609 while (subMenus
.size() > 0) {
610 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
611 if (subMenu
.mouseWouldHit(mouse
)) {
614 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
615 && (!mouse
.getMouse1())
616 && (!mouse
.getMouse2())
617 && (!mouse
.getMouse3())
618 && (!mouse
.getMouseWheelUp())
619 && (!mouse
.getMouseWheelDown())
623 // We navigated away from a sub-menu, so close it
627 // Convert the mouse relative x/y to menu coordinates
628 assert (mouse
.getX() == mouse
.getAbsoluteX());
629 assert (mouse
.getY() == mouse
.getAbsoluteY());
630 if (subMenus
.size() > 0) {
631 menu
= subMenus
.get(subMenus
.size() - 1);
633 mouse
.setX(mouse
.getX() - menu
.getX());
634 mouse
.setY(mouse
.getY() - menu
.getY());
636 menu
.handleEvent(event
);
640 if (event
instanceof TKeypressEvent
) {
641 TKeypressEvent keypress
= (TKeypressEvent
) event
;
643 // See if this key matches an accelerator, and if so dispatch the
645 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
646 TMenuItem item
= null;
647 synchronized (accelerators
) {
648 item
= accelerators
.get(keypressLowercase
);
651 // Let the menu item dispatch
655 // Handle the keypress
656 if (onKeypress(keypress
)) {
662 if (event
instanceof TCommandEvent
) {
663 if (onCommand((TCommandEvent
) event
)) {
668 if (event
instanceof TMenuEvent
) {
669 if (onMenu((TMenuEvent
) event
)) {
674 // Dispatch events to the active window -------------------------------
675 for (TWindow window
: windows
) {
676 if (window
.getActive()) {
677 if (event
instanceof TMouseEvent
) {
678 TMouseEvent mouse
= (TMouseEvent
) event
;
679 // Convert the mouse relative x/y to window coordinates
680 assert (mouse
.getX() == mouse
.getAbsoluteX());
681 assert (mouse
.getY() == mouse
.getAbsoluteY());
682 mouse
.setX(mouse
.getX() - window
.getX());
683 mouse
.setY(mouse
.getY() - window
.getY());
685 // System.err("TApplication dispatch event: %s\n", event);
686 window
.handleEvent(event
);
692 * Dispatch one event to the appropriate widget or application-level
693 * event handler. This is the secondary event handler used by certain
694 * special dialogs (currently TMessageBox and TFileOpenBox).
696 * @param event the input event to consume
697 * @see #primaryHandleEvent(TInputEvent event)
699 private void secondaryHandleEvent(final TInputEvent event
) {
700 secondaryEventReceiver
.handleEvent(event
);
704 * Enable a widget to override the primary event thread.
706 * @param widget widget that will receive events
708 public final void enableSecondaryEventReceiver(final TWidget widget
) {
709 assert (secondaryEventReceiver
== null);
710 assert (secondaryEventHandler
== null);
711 assert (widget
instanceof TMessageBox
);
712 secondaryEventReceiver
= widget
;
713 secondaryEventHandler
= new WidgetEventHandler(this, false);
714 (new Thread(secondaryEventHandler
)).start();
721 * Yield to the secondary thread.
723 public final void yield() {
724 assert (secondaryEventReceiver
!= null);
725 while (secondaryEventReceiver
!= null) {
726 synchronized (this) {
729 } catch (InterruptedException e
) {
737 * Do stuff when there is no user input.
739 private void doIdle() {
740 // Now run any timers that have timed out
741 Date now
= new Date();
742 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
743 for (TTimer timer
: timers
) {
744 if (timer
.getNextTick().getTime() < now
.getTime()) {
746 if (timer
.recurring
) {
747 keepTimers
.add(timer
);
750 keepTimers
.add(timer
);
756 for (TWindow window
: windows
) {
762 * Get the amount of time I can sleep before missing a Timer tick.
764 * @param timeout = initial (maximum) timeout
765 * @return number of milliseconds between now and the next timer event
767 protected int getSleepTime(final int timeout
) {
768 Date now
= new Date();
769 long sleepTime
= timeout
;
770 for (TTimer timer
: timers
) {
771 if (timer
.getNextTick().getTime() < now
.getTime()) {
774 if ((timer
.getNextTick().getTime() > now
.getTime())
775 && ((timer
.getNextTick().getTime() - now
.getTime()) < sleepTime
)
777 sleepTime
= timer
.getNextTick().getTime() - now
.getTime();
780 assert (sleepTime
>= 0);
781 return (int)sleepTime
;
785 * Close window. Note that the window's destructor is NOT called by this
786 * method, instead the GC is assumed to do the cleanup.
788 * @param window the window to remove
790 public final void closeWindow(final TWindow window
) {
791 int z
= window
.getZ();
793 Collections
.sort(windows
);
795 TWindow activeWindow
= null;
796 for (TWindow w
: windows
) {
798 w
.setZ(w
.getZ() - 1);
801 assert (activeWindow
== null);
809 // Perform window cleanup
815 // Check if we are closing a TMessageBox or similar
816 if (secondaryEventReceiver
!= null) {
817 assert (secondaryEventHandler
!= null);
819 // Do not send events to the secondaryEventReceiver anymore, the
821 secondaryEventReceiver
= null;
823 // Wake all threads: primary thread will be consuming events
824 // again, and secondary thread will exit.
825 synchronized (this) {
832 * Switch to the next window.
834 * @param forward if true, then switch to the next window in the list,
835 * otherwise switch to the previous window in the list
837 public final void switchWindow(final boolean forward
) {
838 // Only switch if there are multiple windows
839 if (windows
.size() < 2) {
843 // Swap z/active between active window and the next in the list
844 int activeWindowI
= -1;
845 for (int i
= 0; i
< windows
.size(); i
++) {
846 if (windows
.get(i
).getActive()) {
851 assert (activeWindowI
>= 0);
853 // Do not switch if a window is modal
854 if (windows
.get(activeWindowI
).isModal()) {
860 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
862 if (activeWindowI
== 0) {
863 nextWindowI
= windows
.size() - 1;
865 nextWindowI
= activeWindowI
- 1;
868 windows
.get(activeWindowI
).setActive(false);
869 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
870 windows
.get(nextWindowI
).setZ(0);
871 windows
.get(nextWindowI
).setActive(true);
878 * Add a window to my window list and make it active.
880 * @param window new window to add
882 public final void addWindow(final TWindow window
) {
883 // Do not allow a modal window to spawn a non-modal window
884 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
885 assert (window
.isModal());
887 for (TWindow w
: windows
) {
889 w
.setZ(w
.getZ() + 1);
892 window
.setActive(true);
897 * Check if there is a system-modal window on top.
899 * @return true if the active window is modal
901 private boolean modalWindowActive() {
902 if (windows
.size() == 0) {
905 return windows
.get(windows
.size() - 1).isModal();
909 * Check if a mouse event would hit either the active menu or any open
912 * @param mouse mouse event
913 * @return true if the mouse would hit the active menu or an open
916 private boolean mouseOnMenu(final TMouseEvent mouse
) {
917 assert (activeMenu
!= null);
918 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
919 Collections
.reverse(menus
);
920 for (TMenu menu
: menus
) {
921 if (menu
.mouseWouldHit(mouse
)) {
925 return activeMenu
.mouseWouldHit(mouse
);
929 * See if we need to switch window or activate the menu based on
932 * @param mouse mouse event
934 private void checkSwitchFocus(final TMouseEvent mouse
) {
936 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
937 && (activeMenu
!= null)
938 && (mouse
.getAbsoluteY() != 0)
939 && (!mouseOnMenu(mouse
))
941 // They clicked outside the active menu, turn it off
942 activeMenu
.setActive(false);
944 for (TMenu menu
: subMenus
) {
945 menu
.setActive(false);
951 // See if they hit the menu bar
952 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
953 && (mouse
.getMouse1())
954 && (!modalWindowActive())
955 && (mouse
.getAbsoluteY() == 0)
958 for (TMenu menu
: subMenus
) {
959 menu
.setActive(false);
963 // They selected the menu, go activate it
964 for (TMenu menu
: menus
) {
965 if ((mouse
.getAbsoluteX() >= menu
.getX())
966 && (mouse
.getAbsoluteX() < menu
.getX()
967 + menu
.getTitle().length() + 2)
969 menu
.setActive(true);
972 menu
.setActive(false);
979 // See if they hit the menu bar
980 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
981 && (mouse
.getMouse1())
982 && (activeMenu
!= null)
983 && (mouse
.getAbsoluteY() == 0)
986 TMenu oldMenu
= activeMenu
;
987 for (TMenu menu
: subMenus
) {
988 menu
.setActive(false);
992 // See if we should switch menus
993 for (TMenu menu
: menus
) {
994 if ((mouse
.getAbsoluteX() >= menu
.getX())
995 && (mouse
.getAbsoluteX() < menu
.getX()
996 + menu
.getTitle().length() + 2)
998 menu
.setActive(true);
1002 if (oldMenu
!= activeMenu
) {
1003 // They switched menus
1004 oldMenu
.setActive(false);
1010 // Only switch if there are multiple windows
1011 if (windows
.size() < 2) {
1015 // Switch on the upclick
1016 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1020 Collections
.sort(windows
);
1021 if (windows
.get(0).isModal()) {
1022 // Modal windows don't switch
1026 for (TWindow window
: windows
) {
1027 assert (!window
.isModal());
1028 if (window
.mouseWouldHit(mouse
)) {
1029 if (window
== windows
.get(0)) {
1030 // Clicked on the same window, nothing to do
1034 // We will be switching to another window
1035 assert (windows
.get(0).getActive());
1036 assert (!window
.getActive());
1037 windows
.get(0).setActive(false);
1038 windows
.get(0).setZ(window
.getZ());
1040 window
.setActive(true);
1046 // Clicked on the background, nothing to do
1051 * Turn off the menu.
1053 public final void closeMenu() {
1054 if (activeMenu
!= null) {
1055 activeMenu
.setActive(false);
1057 for (TMenu menu
: subMenus
) {
1058 menu
.setActive(false);
1066 * Turn off a sub-menu.
1068 public final void closeSubMenu() {
1069 assert (activeMenu
!= null);
1070 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1071 assert (item
!= null);
1072 item
.setActive(false);
1073 subMenus
.remove(subMenus
.size() - 1);
1078 * Switch to the next menu.
1080 * @param forward if true, then switch to the next menu in the list,
1081 * otherwise switch to the previous menu in the list
1083 public final void switchMenu(final boolean forward
) {
1084 assert (activeMenu
!= null);
1086 for (TMenu menu
: subMenus
) {
1087 menu
.setActive(false);
1091 for (int i
= 0; i
< menus
.size(); i
++) {
1092 if (activeMenu
== menus
.get(i
)) {
1094 if (i
< menus
.size() - 1) {
1102 activeMenu
.setActive(false);
1103 activeMenu
= menus
.get(i
);
1104 activeMenu
.setActive(true);
1112 * Method that TApplication subclasses can override to handle menu or
1113 * posted command events.
1115 * @param command command event
1116 * @return if true, this event was consumed
1118 protected boolean onCommand(final TCommandEvent command
) {
1119 // Default: handle cmExit
1120 if (command
.equals(cmExit
)) {
1121 if (messageBox("Confirmation", "Exit application?",
1122 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1131 if (command.equals(cmShell)) {
1132 openTerminal(0, 0, TWindow.Flag.RESIZABLE);
1138 if (command
.equals(cmTile
)) {
1143 if (command
.equals(cmCascade
)) {
1148 if (command
.equals(cmCloseAll
)) {
1158 * Method that TApplication subclasses can override to handle menu
1161 * @param menu menu event
1162 * @return if true, this event was consumed
1164 protected boolean onMenu(final TMenuEvent menu
) {
1166 // Default: handle MID_EXIT
1167 if (menu
.getId() == TMenu
.MID_EXIT
) {
1168 if (messageBox("Confirmation", "Exit application?",
1169 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1172 // System.err.printf("onMenu MID_EXIT result: quit = %s\n", quit);
1179 if (menu.id == TMenu.MID_SHELL) {
1180 openTerminal(0, 0, TWindow.Flag.RESIZABLE);
1186 if (menu
.getId() == TMenu
.MID_TILE
) {
1191 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1196 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1205 * Method that TApplication subclasses can override to handle keystrokes.
1207 * @param keypress keystroke event
1208 * @return if true, this event was consumed
1210 protected boolean onKeypress(final TKeypressEvent keypress
) {
1211 // Default: only menu shortcuts
1213 // Process Alt-F, Alt-E, etc. menu shortcut keys
1214 if (!keypress
.getKey().getIsKey()
1215 && keypress
.getKey().getAlt()
1216 && !keypress
.getKey().getCtrl()
1217 && (activeMenu
== null)
1220 assert (subMenus
.size() == 0);
1222 for (TMenu menu
: menus
) {
1223 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1224 == Character
.toLowerCase(keypress
.getKey().getCh())
1227 menu
.setActive(true);
1238 * Add a keyboard accelerator to the global hash.
1240 * @param item menu item this accelerator relates to
1241 * @param keypress keypress that will dispatch a TMenuEvent
1243 public final void addAccelerator(final TMenuItem item
,
1244 final TKeypress keypress
) {
1246 // System.err.printf("addAccelerator: key %s item %s\n", keypress, item);
1248 synchronized (accelerators
) {
1249 assert (accelerators
.get(keypress
) == null);
1250 accelerators
.put(keypress
, item
);
1255 * Recompute menu x positions based on their title length.
1257 public final void recomputeMenuX() {
1259 for (TMenu menu
: menus
) {
1261 x
+= menu
.getTitle().length() + 2;
1266 * Post an event to process and turn off the menu.
1268 * @param event new event to add to the queue
1270 public final void addMenuEvent(final TInputEvent event
) {
1271 synchronized (fillEventQueue
) {
1272 fillEventQueue
.add(event
);
1278 * Add a sub-menu to the list of open sub-menus.
1280 * @param menu sub-menu
1282 public final void addSubMenu(final TMenu menu
) {
1287 * Convenience function to add a top-level menu.
1289 * @param title menu title
1290 * @return the new menu
1292 public final TMenu
addMenu(final String title
) {
1295 TMenu menu
= new TMenu(this, x
, y
, title
);
1302 * Convenience function to add a default "File" menu.
1304 * @return the new menu
1306 public final TMenu
addFileMenu() {
1307 TMenu fileMenu
= addMenu("&File");
1308 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1309 fileMenu
.addSeparator();
1310 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1311 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1316 * Convenience function to add a default "Edit" menu.
1318 * @return the new menu
1320 public final TMenu
addEditMenu() {
1321 TMenu editMenu
= addMenu("&Edit");
1322 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1323 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1324 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1325 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1330 * Convenience function to add a default "Window" menu.
1332 * @return the new menu
1334 public final TMenu
addWindowMenu() {
1335 TMenu windowMenu
= addMenu("&Window");
1336 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1337 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1338 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1339 windowMenu
.addSeparator();
1340 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1341 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1342 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1343 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1344 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1349 * Close all open windows.
1351 private void closeAllWindows() {
1352 // Don't do anything if we are in the menu
1353 if (activeMenu
!= null) {
1356 for (TWindow window
: windows
) {
1357 closeWindow(window
);
1362 * Re-layout the open windows as non-overlapping tiles. This produces
1363 * almost the same results as Turbo Pascal 7.0's IDE.
1365 private void tileWindows() {
1366 // Don't do anything if we are in the menu
1367 if (activeMenu
!= null) {
1370 int z
= windows
.size();
1376 a
= (int)(Math
.sqrt(z
));
1380 if (((a
* b
) + c
) == z
) {
1388 int newWidth
= (getScreen().getWidth() / a
);
1389 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1390 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1391 // System.err.printf("Z %s a %s b %s c %s newWidth %s newHeight1 %s newHeight2 %s",
1392 // z, a, b, c, newWidth, newHeight1, newHeight2);
1394 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1395 Collections
.sort(sorted
);
1396 Collections
.reverse(sorted
);
1397 for (int i
= 0; i
< sorted
.size(); i
++) {
1398 int logicalX
= i
/ b
;
1399 int logicalY
= i
% b
;
1400 if (i
>= ((a
- 1) * b
)) {
1402 logicalY
= i
- ((a
- 1) * b
);
1405 TWindow w
= sorted
.get(i
);
1406 w
.setX(logicalX
* newWidth
);
1407 w
.setWidth(newWidth
);
1408 if (i
>= ((a
- 1) * b
)) {
1409 w
.setY((logicalY
* newHeight2
) + 1);
1410 w
.setHeight(newHeight2
);
1412 w
.setY((logicalY
* newHeight1
) + 1);
1413 w
.setHeight(newHeight1
);
1419 * Re-layout the open windows as overlapping cascaded windows.
1421 private void cascadeWindows() {
1422 // Don't do anything if we are in the menu
1423 if (activeMenu
!= null) {
1428 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1429 Collections
.sort(sorted
);
1430 Collections
.reverse(sorted
);
1431 for (TWindow window
: sorted
) {
1436 if (x
> getScreen().getWidth()) {
1439 if (y
>= getScreen().getHeight()) {
1446 * Convenience function to add a timer.
1448 * @param duration number of milliseconds to wait between ticks
1449 * @param recurring if true, re-schedule this timer after every tick
1450 * @param action function to call when button is pressed
1453 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1454 final TAction action
) {
1456 TTimer timer
= new TTimer(duration
, recurring
, action
);
1457 synchronized (timers
) {
1464 * Convenience function to remove a timer.
1466 * @param timer timer to remove
1468 public final void removeTimer(final TTimer timer
) {
1469 synchronized (timers
) {
1470 timers
.remove(timer
);
1475 * Convenience function to spawn a message box.
1477 * @param title window title, will be centered along the top border
1478 * @param caption message to display. Use embedded newlines to get a
1480 * @return the new message box
1482 public final TMessageBox
messageBox(final String title
,
1483 final String caption
) {
1485 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1489 * Convenience function to spawn a message box.
1491 * @param title window title, will be centered along the top border
1492 * @param caption message to display. Use embedded newlines to get a
1494 * @param type one of the TMessageBox.Type constants. Default is
1496 * @return the new message box
1498 public final TMessageBox
messageBox(final String title
,
1499 final String caption
, final TMessageBox
.Type type
) {
1501 return new TMessageBox(this, title
, caption
, type
);
1505 * Convenience function to spawn an input box.
1507 * @param title window title, will be centered along the top border
1508 * @param caption message to display. Use embedded newlines to get a
1510 * @return the new input box
1512 public final TInputBox
inputBox(final String title
, final String caption
) {
1514 return new TInputBox(this, title
, caption
);
1518 * Convenience function to spawn an input box.
1520 * @param title window title, will be centered along the top border
1521 * @param caption message to display. Use embedded newlines to get a
1523 * @param text initial text to seed the field with
1524 * @return the new input box
1526 public final TInputBox
inputBox(final String title
, final String caption
,
1527 final String text
) {
1529 return new TInputBox(this, title
, caption
, text
);