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
.ECMA48Backend
;
55 import jexer
.io
.Screen
;
56 import jexer
.menu
.TMenu
;
57 import jexer
.menu
.TMenuItem
;
58 import static jexer
.TCommand
.*;
59 import static jexer
.TKeypress
.*;
62 * TApplication sets up a full Text User Interface application.
64 public class TApplication
{
67 * WidgetEventHandler is the main event consumer loop. There are at most
68 * two such threads in existence: the primary for normal case and a
69 * secondary that is used for TMessageBox, TInputBox, and similar.
71 private class WidgetEventHandler
implements Runnable
{
73 * The main application.
75 private TApplication application
;
78 * Whether or not this WidgetEventHandler is the primary or secondary
81 private boolean primary
= true;
86 * @param application the main application
87 * @param primary if true, this is the primary event handler thread
89 public WidgetEventHandler(final TApplication application
,
90 final boolean primary
) {
92 this.application
= application
;
93 this.primary
= primary
;
102 while (!application
.quit
) {
104 // Wait until application notifies me
105 while (!application
.quit
) {
107 synchronized (application
.drainEventQueue
) {
108 if (application
.drainEventQueue
.size() > 0) {
112 synchronized (application
) {
115 && (application
.secondaryEventReceiver
== null)
117 // Secondary thread, time to exit
122 } catch (InterruptedException e
) {
127 // Pull all events off the queue
129 TInputEvent event
= null;
130 synchronized (application
.drainEventQueue
) {
131 if (application
.drainEventQueue
.size() == 0) {
134 event
= application
.drainEventQueue
.remove(0);
137 primaryHandleEvent(event
);
139 secondaryHandleEvent(event
);
142 && (application
.secondaryEventReceiver
== null)
144 // Secondary thread, time to exit
148 } // while (true) (main runnable loop)
153 * The primary event handler thread.
155 private WidgetEventHandler primaryEventHandler
;
158 * The secondary event handler thread.
160 private WidgetEventHandler secondaryEventHandler
;
163 * The widget receiving events from the secondary event handler thread.
165 private TWidget secondaryEventReceiver
;
168 * Access to the physical screen, keyboard, and mouse.
170 private Backend backend
;
177 public final Screen
getScreen() {
178 return backend
.getScreen();
182 * Actual mouse coordinate X.
187 * Actual mouse coordinate Y.
192 * Event queue that is filled by run().
194 private List
<TInputEvent
> fillEventQueue
;
197 * Event queue that will be drained by either primary or secondary
200 private List
<TInputEvent
> drainEventQueue
;
203 * Top-level menus in this application.
205 private List
<TMenu
> menus
;
208 * Stack of activated sub-menus in this application.
210 private List
<TMenu
> subMenus
;
213 * The currently acive menu.
215 private TMenu activeMenu
= null;
218 * Active keyboard accelerators.
220 private Map
<TKeypress
, TMenuItem
> accelerators
;
223 * Windows and widgets pull colors from this ColorTheme.
225 private ColorTheme theme
;
228 * Get the color theme.
232 public final ColorTheme
getTheme() {
237 * The top-level windows (but not menus).
239 private List
<TWindow
> windows
;
242 * Timers that are being ticked.
244 private List
<TTimer
> timers
;
247 * When true, exit the application.
249 private boolean quit
= false;
252 * When true, repaint the entire screen.
254 private boolean repaint
= true;
257 * Request full repaint on next screen refresh.
259 public final void setRepaint() {
264 * When true, just flush updates from the screen.
266 private boolean flush
= false;
269 * Y coordinate of the top edge of the desktop. For now this is a
270 * constant. Someday it would be nice to have a multi-line menu or
273 private static final int desktopTop
= 1;
276 * Get Y coordinate of the top edge of the desktop.
278 * @return Y coordinate of the top edge of the desktop
280 public final int getDesktopTop() {
285 * Y coordinate of the bottom edge of the desktop.
287 private int desktopBottom
;
290 * Get Y coordinate of the bottom edge of the desktop.
292 * @return Y coordinate of the bottom edge of the desktop
294 public final int getDesktopBottom() {
295 return desktopBottom
;
299 * Public constructor.
301 * @param input an InputStream connected to the remote user, or null for
302 * System.in. If System.in is used, then on non-Windows systems it will
303 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
304 * mode. input is always converted to a Reader with UTF-8 encoding.
305 * @param output an OutputStream connected to the remote user, or null
306 * for System.out. output is always converted to a Writer with UTF-8
308 * @throws UnsupportedEncodingException if an exception is thrown when
309 * creating the InputStreamReader
311 public TApplication(final InputStream input
,
312 final OutputStream output
) throws UnsupportedEncodingException
{
314 backend
= new ECMA48Backend(input
, output
);
315 theme
= new ColorTheme();
316 desktopBottom
= getScreen().getHeight() - 1;
317 fillEventQueue
= new ArrayList
<TInputEvent
>();
318 drainEventQueue
= new ArrayList
<TInputEvent
>();
319 windows
= new LinkedList
<TWindow
>();
320 menus
= new LinkedList
<TMenu
>();
321 subMenus
= new LinkedList
<TMenu
>();
322 timers
= new LinkedList
<TTimer
>();
323 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
325 // Setup the main consumer thread
326 primaryEventHandler
= new WidgetEventHandler(this, true);
327 (new Thread(primaryEventHandler
)).start();
331 * Invert the cell at the mouse pointer position.
333 private void drawMouse() {
334 CellAttributes attr
= getScreen().getAttrXY(mouseX
, mouseY
);
335 attr
.setForeColor(attr
.getForeColor().invert());
336 attr
.setBackColor(attr
.getBackColor().invert());
337 getScreen().putAttrXY(mouseX
, mouseY
, attr
, false);
340 if (windows
.size() == 0) {
348 public final void drawAll() {
349 if ((flush
) && (!repaint
)) {
350 backend
.flushScreen();
359 // If true, the cursor is not visible
360 boolean cursor
= false;
362 // Start with a clean screen
365 // Draw the background
366 CellAttributes background
= theme
.getColor("tapplication.background");
367 getScreen().putAll(GraphicsChars
.HATCH
, background
);
369 // Draw each window in reverse Z order
370 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
371 Collections
.sort(sorted
);
372 Collections
.reverse(sorted
);
373 for (TWindow window
: sorted
) {
374 window
.drawChildren();
377 // Draw the blank menubar line - reset the screen clipping first so
378 // it won't trim it out.
379 getScreen().resetClipping();
380 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
381 theme
.getColor("tmenu"));
382 // Now draw the menus.
384 for (TMenu menu
: menus
) {
385 CellAttributes menuColor
;
386 CellAttributes menuMnemonicColor
;
387 if (menu
.getActive()) {
388 menuColor
= theme
.getColor("tmenu.highlighted");
389 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
391 menuColor
= theme
.getColor("tmenu");
392 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
394 // Draw the menu title
395 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
397 getScreen().putStrXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
398 // Draw the highlight character
399 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
400 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
402 if (menu
.getActive()) {
404 // Reset the screen clipping so we can draw the next title.
405 getScreen().resetClipping();
407 x
+= menu
.getTitle().length() + 2;
410 for (TMenu menu
: subMenus
) {
411 // Reset the screen clipping so we can draw the next sub-menu.
412 getScreen().resetClipping();
416 // Draw the mouse pointer
419 // Place the cursor if it is visible
420 TWidget activeWidget
= null;
421 if (sorted
.size() > 0) {
422 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
423 if (activeWidget
.visibleCursor()) {
424 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
425 activeWidget
.getCursorAbsoluteY());
432 getScreen().hideCursor();
435 // Flush the screen contents
436 backend
.flushScreen();
443 * Run this application until it exits.
445 public final void run() {
447 // Timeout is in milliseconds, so default timeout after 1 second
449 int timeout
= getSleepTime(1000);
451 // See if there are any definitely events waiting to be processed
452 // or a screen redraw to do. If so, do not wait if there is no
454 synchronized (drainEventQueue
) {
455 if (drainEventQueue
.size() > 0) {
459 synchronized (fillEventQueue
) {
460 if (fillEventQueue
.size() > 0) {
465 // Pull any pending I/O events
466 backend
.getEvents(fillEventQueue
, timeout
);
468 // Dispatch each event to the appropriate handler, one at a time.
470 TInputEvent event
= null;
471 synchronized (fillEventQueue
) {
472 if (fillEventQueue
.size() == 0) {
475 event
= fillEventQueue
.remove(0);
477 metaHandleEvent(event
);
480 // Process timers and call doIdle()'s
487 // Shutdown the consumer threads
488 synchronized (this) {
496 * Peek at certain application-level events, add to eventQueue, and wake
497 * up the consuming Thread.
499 * @param event the input event to consume
501 private void metaHandleEvent(final TInputEvent event
) {
504 System.err.printf(String.format("metaHandleEvents event: %s\n",
505 event)); System.err.flush();
509 // Do no more processing if the application is already trying
514 // Special application-wide events -------------------------------
517 if (event
instanceof TCommandEvent
) {
518 TCommandEvent command
= (TCommandEvent
) event
;
519 if (command
.getCmd().equals(cmAbort
)) {
526 if (event
instanceof TResizeEvent
) {
527 TResizeEvent resize
= (TResizeEvent
) event
;
528 getScreen().setDimensions(resize
.getWidth(),
530 desktopBottom
= getScreen().getHeight() - 1;
537 // Peek at the mouse position
538 if (event
instanceof TMouseEvent
) {
539 TMouseEvent mouse
= (TMouseEvent
) event
;
540 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
541 mouseX
= mouse
.getX();
542 mouseY
= mouse
.getY();
547 // Put into the main queue
548 synchronized (drainEventQueue
) {
549 drainEventQueue
.add(event
);
552 // Wake all threads: primary thread will either be consuming events
553 // again or waiting in yield(), and secondary thread will either not
554 // exist or consuming events.
555 synchronized (this) {
561 * Dispatch one event to the appropriate widget or application-level
562 * event handler. This is the primary event handler, it has the normal
563 * application-wide event handling.
565 * @param event the input event to consume
566 * @see #secondaryHandleEvent(TInputEvent event)
568 private void primaryHandleEvent(final TInputEvent event
) {
570 // System.err.printf("Handle event: %s\n", event);
572 // Special application-wide events -----------------------------------
574 // Peek at the mouse position
575 if (event
instanceof TMouseEvent
) {
576 // See if we need to switch focus to another window or the menu
577 checkSwitchFocus((TMouseEvent
) event
);
580 // Handle menu events
581 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
582 TMenu menu
= activeMenu
;
584 if (event
instanceof TMouseEvent
) {
585 TMouseEvent mouse
= (TMouseEvent
) event
;
587 while (subMenus
.size() > 0) {
588 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
589 if (subMenu
.mouseWouldHit(mouse
)) {
592 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
593 && (!mouse
.getMouse1())
594 && (!mouse
.getMouse2())
595 && (!mouse
.getMouse3())
596 && (!mouse
.getMouseWheelUp())
597 && (!mouse
.getMouseWheelDown())
601 // We navigated away from a sub-menu, so close it
605 // Convert the mouse relative x/y to menu coordinates
606 assert (mouse
.getX() == mouse
.getAbsoluteX());
607 assert (mouse
.getY() == mouse
.getAbsoluteY());
608 if (subMenus
.size() > 0) {
609 menu
= subMenus
.get(subMenus
.size() - 1);
611 mouse
.setX(mouse
.getX() - menu
.getX());
612 mouse
.setY(mouse
.getY() - menu
.getY());
614 menu
.handleEvent(event
);
618 if (event
instanceof TKeypressEvent
) {
619 TKeypressEvent keypress
= (TKeypressEvent
) event
;
621 // See if this key matches an accelerator, and if so dispatch the
623 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
624 TMenuItem item
= null;
625 synchronized (accelerators
) {
626 item
= accelerators
.get(keypressLowercase
);
629 // Let the menu item dispatch
633 // Handle the keypress
634 if (onKeypress(keypress
)) {
640 if (event
instanceof TCommandEvent
) {
641 if (onCommand((TCommandEvent
) event
)) {
646 if (event
instanceof TMenuEvent
) {
647 if (onMenu((TMenuEvent
) event
)) {
652 // Dispatch events to the active window -------------------------------
653 for (TWindow window
: windows
) {
654 if (window
.getActive()) {
655 if (event
instanceof TMouseEvent
) {
656 TMouseEvent mouse
= (TMouseEvent
) event
;
657 // Convert the mouse relative x/y to window coordinates
658 assert (mouse
.getX() == mouse
.getAbsoluteX());
659 assert (mouse
.getY() == mouse
.getAbsoluteY());
660 mouse
.setX(mouse
.getX() - window
.getX());
661 mouse
.setY(mouse
.getY() - window
.getY());
663 // System.err("TApplication dispatch event: %s\n", event);
664 window
.handleEvent(event
);
670 * Dispatch one event to the appropriate widget or application-level
671 * event handler. This is the secondary event handler used by certain
672 * special dialogs (currently TMessageBox and TFileOpenBox).
674 * @param event the input event to consume
675 * @see #primaryHandleEvent(TInputEvent event)
677 private void secondaryHandleEvent(final TInputEvent event
) {
678 secondaryEventReceiver
.handleEvent(event
);
682 * Enable a widget to override the primary event thread.
684 * @param widget widget that will receive events
686 public final void enableSecondaryEventReceiver(final TWidget widget
) {
687 assert (secondaryEventReceiver
== null);
688 assert (secondaryEventHandler
== null);
689 assert (widget
instanceof TMessageBox
);
690 secondaryEventReceiver
= widget
;
691 secondaryEventHandler
= new WidgetEventHandler(this, false);
692 (new Thread(secondaryEventHandler
)).start();
699 * Yield to the secondary thread.
701 public final void yield() {
702 assert (secondaryEventReceiver
!= null);
703 while (secondaryEventReceiver
!= null) {
704 synchronized (this) {
707 } catch (InterruptedException e
) {
715 * Do stuff when there is no user input.
717 private void doIdle() {
718 // Now run any timers that have timed out
719 Date now
= new Date();
720 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
721 for (TTimer timer
: timers
) {
722 if (timer
.getNextTick().getTime() < now
.getTime()) {
724 if (timer
.recurring
) {
725 keepTimers
.add(timer
);
728 keepTimers
.add(timer
);
734 for (TWindow window
: windows
) {
740 * Get the amount of time I can sleep before missing a Timer tick.
742 * @param timeout = initial (maximum) timeout
743 * @return number of milliseconds between now and the next timer event
745 protected int getSleepTime(final int timeout
) {
746 Date now
= new Date();
747 long sleepTime
= timeout
;
748 for (TTimer timer
: timers
) {
749 if (timer
.getNextTick().getTime() < now
.getTime()) {
752 if ((timer
.getNextTick().getTime() > now
.getTime())
753 && ((timer
.getNextTick().getTime() - now
.getTime()) < sleepTime
)
755 sleepTime
= timer
.getNextTick().getTime() - now
.getTime();
758 assert (sleepTime
>= 0);
759 return (int)sleepTime
;
763 * Close window. Note that the window's destructor is NOT called by this
764 * method, instead the GC is assumed to do the cleanup.
766 * @param window the window to remove
768 public final void closeWindow(final TWindow window
) {
769 int z
= window
.getZ();
771 Collections
.sort(windows
);
773 TWindow activeWindow
= null;
774 for (TWindow w
: windows
) {
776 w
.setZ(w
.getZ() - 1);
779 assert (activeWindow
== null);
787 // Perform window cleanup
793 // Check if we are closing a TMessageBox or similar
794 if (secondaryEventReceiver
!= null) {
795 assert (secondaryEventHandler
!= null);
797 // Do not send events to the secondaryEventReceiver anymore, the
799 secondaryEventReceiver
= null;
801 // Wake all threads: primary thread will be consuming events
802 // again, and secondary thread will exit.
803 synchronized (this) {
810 * Switch to the next window.
812 * @param forward if true, then switch to the next window in the list,
813 * otherwise switch to the previous window in the list
815 public final void switchWindow(final boolean forward
) {
816 // Only switch if there are multiple windows
817 if (windows
.size() < 2) {
821 // Swap z/active between active window and the next in the list
822 int activeWindowI
= -1;
823 for (int i
= 0; i
< windows
.size(); i
++) {
824 if (windows
.get(i
).getActive()) {
829 assert (activeWindowI
>= 0);
831 // Do not switch if a window is modal
832 if (windows
.get(activeWindowI
).isModal()) {
838 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
840 if (activeWindowI
== 0) {
841 nextWindowI
= windows
.size() - 1;
843 nextWindowI
= activeWindowI
- 1;
846 windows
.get(activeWindowI
).setActive(false);
847 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
848 windows
.get(nextWindowI
).setZ(0);
849 windows
.get(nextWindowI
).setActive(true);
856 * Add a window to my window list and make it active.
858 * @param window new window to add
860 public final void addWindow(final TWindow window
) {
861 // Do not allow a modal window to spawn a non-modal window
862 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
863 assert (window
.isModal());
865 for (TWindow w
: windows
) {
867 w
.setZ(w
.getZ() + 1);
870 window
.setActive(true);
875 * Check if there is a system-modal window on top.
877 * @return true if the active window is modal
879 private boolean modalWindowActive() {
880 if (windows
.size() == 0) {
883 return windows
.get(windows
.size() - 1).isModal();
887 * Check if a mouse event would hit either the active menu or any open
890 * @param mouse mouse event
891 * @return true if the mouse would hit the active menu or an open
894 private boolean mouseOnMenu(final TMouseEvent mouse
) {
895 assert (activeMenu
!= null);
896 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
897 Collections
.reverse(menus
);
898 for (TMenu menu
: menus
) {
899 if (menu
.mouseWouldHit(mouse
)) {
903 return activeMenu
.mouseWouldHit(mouse
);
907 * See if we need to switch window or activate the menu based on
910 * @param mouse mouse event
912 private void checkSwitchFocus(final TMouseEvent mouse
) {
914 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
915 && (activeMenu
!= null)
916 && (mouse
.getAbsoluteY() != 0)
917 && (!mouseOnMenu(mouse
))
919 // They clicked outside the active menu, turn it off
920 activeMenu
.setActive(false);
922 for (TMenu menu
: subMenus
) {
923 menu
.setActive(false);
929 // See if they hit the menu bar
930 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
931 && (mouse
.getMouse1())
932 && (!modalWindowActive())
933 && (mouse
.getAbsoluteY() == 0)
936 for (TMenu menu
: subMenus
) {
937 menu
.setActive(false);
941 // They selected the menu, go activate it
942 for (TMenu menu
: menus
) {
943 if ((mouse
.getAbsoluteX() >= menu
.getX())
944 && (mouse
.getAbsoluteX() < menu
.getX()
945 + menu
.getTitle().length() + 2)
947 menu
.setActive(true);
950 menu
.setActive(false);
957 // See if they hit the menu bar
958 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
959 && (mouse
.getMouse1())
960 && (activeMenu
!= null)
961 && (mouse
.getAbsoluteY() == 0)
964 TMenu oldMenu
= activeMenu
;
965 for (TMenu menu
: subMenus
) {
966 menu
.setActive(false);
970 // See if we should switch menus
971 for (TMenu menu
: menus
) {
972 if ((mouse
.getAbsoluteX() >= menu
.getX())
973 && (mouse
.getAbsoluteX() < menu
.getX()
974 + menu
.getTitle().length() + 2)
976 menu
.setActive(true);
980 if (oldMenu
!= activeMenu
) {
981 // They switched menus
982 oldMenu
.setActive(false);
988 // Only switch if there are multiple windows
989 if (windows
.size() < 2) {
993 // Switch on the upclick
994 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
998 Collections
.sort(windows
);
999 if (windows
.get(0).isModal()) {
1000 // Modal windows don't switch
1004 for (TWindow window
: windows
) {
1005 assert (!window
.isModal());
1006 if (window
.mouseWouldHit(mouse
)) {
1007 if (window
== windows
.get(0)) {
1008 // Clicked on the same window, nothing to do
1012 // We will be switching to another window
1013 assert (windows
.get(0).getActive());
1014 assert (!window
.getActive());
1015 windows
.get(0).setActive(false);
1016 windows
.get(0).setZ(window
.getZ());
1018 window
.setActive(true);
1024 // Clicked on the background, nothing to do
1029 * Turn off the menu.
1031 public final void closeMenu() {
1032 if (activeMenu
!= null) {
1033 activeMenu
.setActive(false);
1035 for (TMenu menu
: subMenus
) {
1036 menu
.setActive(false);
1044 * Turn off a sub-menu.
1046 public final void closeSubMenu() {
1047 assert (activeMenu
!= null);
1048 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1049 assert (item
!= null);
1050 item
.setActive(false);
1051 subMenus
.remove(subMenus
.size() - 1);
1056 * Switch to the next menu.
1058 * @param forward if true, then switch to the next menu in the list,
1059 * otherwise switch to the previous menu in the list
1061 public final void switchMenu(final boolean forward
) {
1062 assert (activeMenu
!= null);
1064 for (TMenu menu
: subMenus
) {
1065 menu
.setActive(false);
1069 for (int i
= 0; i
< menus
.size(); i
++) {
1070 if (activeMenu
== menus
.get(i
)) {
1072 if (i
< menus
.size() - 1) {
1080 activeMenu
.setActive(false);
1081 activeMenu
= menus
.get(i
);
1082 activeMenu
.setActive(true);
1090 * Method that TApplication subclasses can override to handle menu or
1091 * posted command events.
1093 * @param command command event
1094 * @return if true, this event was consumed
1096 protected boolean onCommand(final TCommandEvent command
) {
1097 // Default: handle cmExit
1098 if (command
.equals(cmExit
)) {
1099 if (messageBox("Confirmation", "Exit application?",
1100 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1109 if (command.equals(cmShell)) {
1110 openTerminal(0, 0, TWindow.Flag.RESIZABLE);
1116 if (command
.equals(cmTile
)) {
1121 if (command
.equals(cmCascade
)) {
1126 if (command
.equals(cmCloseAll
)) {
1136 * Method that TApplication subclasses can override to handle menu
1139 * @param menu menu event
1140 * @return if true, this event was consumed
1142 protected boolean onMenu(final TMenuEvent menu
) {
1144 // Default: handle MID_EXIT
1145 if (menu
.getId() == TMenu
.MID_EXIT
) {
1146 if (messageBox("Confirmation", "Exit application?",
1147 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1150 // System.err.printf("onMenu MID_EXIT result: quit = %s\n", quit);
1157 if (menu.id == TMenu.MID_SHELL) {
1158 openTerminal(0, 0, TWindow.Flag.RESIZABLE);
1164 if (menu
.getId() == TMenu
.MID_TILE
) {
1169 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1174 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1183 * Method that TApplication subclasses can override to handle keystrokes.
1185 * @param keypress keystroke event
1186 * @return if true, this event was consumed
1188 protected boolean onKeypress(final TKeypressEvent keypress
) {
1189 // Default: only menu shortcuts
1191 // Process Alt-F, Alt-E, etc. menu shortcut keys
1192 if (!keypress
.getKey().getIsKey()
1193 && keypress
.getKey().getAlt()
1194 && !keypress
.getKey().getCtrl()
1195 && (activeMenu
== null)
1198 assert (subMenus
.size() == 0);
1200 for (TMenu menu
: menus
) {
1201 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1202 == Character
.toLowerCase(keypress
.getKey().getCh())
1205 menu
.setActive(true);
1216 * Add a keyboard accelerator to the global hash.
1218 * @param item menu item this accelerator relates to
1219 * @param keypress keypress that will dispatch a TMenuEvent
1221 public final void addAccelerator(final TMenuItem item
,
1222 final TKeypress keypress
) {
1224 // System.err.printf("addAccelerator: key %s item %s\n", keypress, item);
1226 synchronized (accelerators
) {
1227 assert (accelerators
.get(keypress
) == null);
1228 accelerators
.put(keypress
, item
);
1233 * Recompute menu x positions based on their title length.
1235 public final void recomputeMenuX() {
1237 for (TMenu menu
: menus
) {
1239 x
+= menu
.getTitle().length() + 2;
1244 * Post an event to process and turn off the menu.
1246 * @param event new event to add to the queue
1248 public final void addMenuEvent(final TInputEvent event
) {
1249 synchronized (fillEventQueue
) {
1250 fillEventQueue
.add(event
);
1256 * Add a sub-menu to the list of open sub-menus.
1258 * @param menu sub-menu
1260 public final void addSubMenu(final TMenu menu
) {
1265 * Convenience function to add a top-level menu.
1267 * @param title menu title
1268 * @return the new menu
1270 public final TMenu
addMenu(String title
) {
1273 TMenu menu
= new TMenu(this, x
, y
, title
);
1280 * Convenience function to add a default "File" menu.
1282 * @return the new menu
1284 public final TMenu
addFileMenu() {
1285 TMenu fileMenu
= addMenu("&File");
1286 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1287 fileMenu
.addSeparator();
1288 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1289 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1294 * Convenience function to add a default "Edit" menu.
1296 * @return the new menu
1298 public final TMenu
addEditMenu() {
1299 TMenu editMenu
= addMenu("&Edit");
1300 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1301 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1302 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1303 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1308 * Convenience function to add a default "Window" menu.
1310 * @return the new menu
1312 public final TMenu
addWindowMenu() {
1313 TMenu windowMenu
= addMenu("&Window");
1314 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1315 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1316 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1317 windowMenu
.addSeparator();
1318 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1319 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1320 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1321 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1322 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1327 * Close all open windows.
1329 private void closeAllWindows() {
1330 // Don't do anything if we are in the menu
1331 if (activeMenu
!= null) {
1334 for (TWindow window
: windows
) {
1335 closeWindow(window
);
1340 * Re-layout the open windows as non-overlapping tiles. This produces
1341 * almost the same results as Turbo Pascal 7.0's IDE.
1343 private void tileWindows() {
1344 // Don't do anything if we are in the menu
1345 if (activeMenu
!= null) {
1348 int z
= windows
.size();
1354 a
= (int)(Math
.sqrt(z
));
1358 if (((a
* b
) + c
) == z
) {
1366 int newWidth
= (getScreen().getWidth() / a
);
1367 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1368 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1369 // System.err.printf("Z %s a %s b %s c %s newWidth %s newHeight1 %s newHeight2 %s",
1370 // z, a, b, c, newWidth, newHeight1, newHeight2);
1372 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1373 Collections
.sort(sorted
);
1374 Collections
.reverse(sorted
);
1375 for (int i
= 0; i
< sorted
.size(); i
++) {
1376 int logicalX
= i
/ b
;
1377 int logicalY
= i
% b
;
1378 if (i
>= ((a
- 1) * b
)) {
1380 logicalY
= i
- ((a
- 1) * b
);
1383 TWindow w
= sorted
.get(i
);
1384 w
.setX(logicalX
* newWidth
);
1385 w
.setWidth(newWidth
);
1386 if (i
>= ((a
- 1) * b
)) {
1387 w
.setY((logicalY
* newHeight2
) + 1);
1388 w
.setHeight(newHeight2
);
1390 w
.setY((logicalY
* newHeight1
) + 1);
1391 w
.setHeight(newHeight1
);
1397 * Re-layout the open windows as overlapping cascaded windows.
1399 private void cascadeWindows() {
1400 // Don't do anything if we are in the menu
1401 if (activeMenu
!= null) {
1406 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1407 Collections
.sort(sorted
);
1408 Collections
.reverse(sorted
);
1409 for (TWindow window
: sorted
) {
1414 if (x
> getScreen().getWidth()) {
1417 if (y
>= getScreen().getHeight()) {
1424 * Convenience function to add a timer.
1426 * @param duration number of milliseconds to wait between ticks
1427 * @param recurring if true, re-schedule this timer after every tick
1428 * @param action function to call when button is pressed
1431 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1432 final TAction action
) {
1434 TTimer timer
= new TTimer(duration
, recurring
, action
);
1435 synchronized (timers
) {
1442 * Convenience function to remove a timer.
1444 * @param timer timer to remove
1446 public final void removeTimer(final TTimer timer
) {
1447 synchronized (timers
) {
1448 timers
.remove(timer
);
1453 * Convenience function to spawn a message box.
1455 * @param title window title, will be centered along the top border
1456 * @param caption message to display. Use embedded newlines to get a
1458 * @return the new message box
1460 public final TMessageBox
messageBox(final String title
,
1461 final String caption
) {
1463 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1467 * Convenience function to spawn a message box.
1469 * @param title window title, will be centered along the top border
1470 * @param caption message to display. Use embedded newlines to get a
1472 * @param type one of the TMessageBox.Type constants. Default is
1474 * @return the new message box
1476 public final TMessageBox
messageBox(final String title
,
1477 final String caption
, final TMessageBox
.Type type
) {
1479 return new TMessageBox(this, title
, caption
, type
);
1483 * Convenience function to spawn an input box.
1485 * @param title window title, will be centered along the top border
1486 * @param caption message to display. Use embedded newlines to get a
1488 * @return the new input box
1490 public final TInputBox
inputBox(final String title
, final String caption
) {
1492 return new TInputBox(this, title
, caption
);
1496 * Convenience function to spawn an input box.
1498 * @param title window title, will be centered along the top border
1499 * @param caption message to display. Use embedded newlines to get a
1501 * @param text initial text to seed the field with
1502 * @return the new input box
1504 public final TInputBox
inputBox(final String title
, final String caption
,
1505 final String text
) {
1507 return new TInputBox(this, title
, caption
, text
);