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 if (System
.getProperty("jexer.AWT", "false").equals("true")) {
316 backend
= new AWTBackend();
318 backend
= new ECMA48Backend(input
, output
);
321 theme
= new ColorTheme();
322 desktopBottom
= getScreen().getHeight() - 1;
323 fillEventQueue
= new ArrayList
<TInputEvent
>();
324 drainEventQueue
= new ArrayList
<TInputEvent
>();
325 windows
= new LinkedList
<TWindow
>();
326 menus
= new LinkedList
<TMenu
>();
327 subMenus
= new LinkedList
<TMenu
>();
328 timers
= new LinkedList
<TTimer
>();
329 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
331 // Setup the main consumer thread
332 primaryEventHandler
= new WidgetEventHandler(this, true);
333 (new Thread(primaryEventHandler
)).start();
337 * Invert the cell at the mouse pointer position.
339 private void drawMouse() {
340 CellAttributes attr
= getScreen().getAttrXY(mouseX
, mouseY
);
341 attr
.setForeColor(attr
.getForeColor().invert());
342 attr
.setBackColor(attr
.getBackColor().invert());
343 getScreen().putAttrXY(mouseX
, mouseY
, attr
, false);
346 if (windows
.size() == 0) {
354 public final void drawAll() {
355 if ((flush
) && (!repaint
)) {
356 backend
.flushScreen();
365 // If true, the cursor is not visible
366 boolean cursor
= false;
368 // Start with a clean screen
371 // Draw the background
372 CellAttributes background
= theme
.getColor("tapplication.background");
373 getScreen().putAll(GraphicsChars
.HATCH
, background
);
375 // Draw each window in reverse Z order
376 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
377 Collections
.sort(sorted
);
378 Collections
.reverse(sorted
);
379 for (TWindow window
: sorted
) {
380 window
.drawChildren();
383 // Draw the blank menubar line - reset the screen clipping first so
384 // it won't trim it out.
385 getScreen().resetClipping();
386 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
387 theme
.getColor("tmenu"));
388 // Now draw the menus.
390 for (TMenu menu
: menus
) {
391 CellAttributes menuColor
;
392 CellAttributes menuMnemonicColor
;
393 if (menu
.getActive()) {
394 menuColor
= theme
.getColor("tmenu.highlighted");
395 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
397 menuColor
= theme
.getColor("tmenu");
398 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
400 // Draw the menu title
401 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
403 getScreen().putStrXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
404 // Draw the highlight character
405 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
406 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
408 if (menu
.getActive()) {
410 // Reset the screen clipping so we can draw the next title.
411 getScreen().resetClipping();
413 x
+= menu
.getTitle().length() + 2;
416 for (TMenu menu
: subMenus
) {
417 // Reset the screen clipping so we can draw the next sub-menu.
418 getScreen().resetClipping();
422 // Draw the mouse pointer
425 // Place the cursor if it is visible
426 TWidget activeWidget
= null;
427 if (sorted
.size() > 0) {
428 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
429 if (activeWidget
.visibleCursor()) {
430 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
431 activeWidget
.getCursorAbsoluteY());
438 getScreen().hideCursor();
441 // Flush the screen contents
442 backend
.flushScreen();
449 * Run this application until it exits.
451 public final void run() {
453 // Timeout is in milliseconds, so default timeout after 1 second
455 int timeout
= getSleepTime(1000);
457 // See if there are any definitely events waiting to be processed
458 // or a screen redraw to do. If so, do not wait if there is no
460 synchronized (drainEventQueue
) {
461 if (drainEventQueue
.size() > 0) {
465 synchronized (fillEventQueue
) {
466 if (fillEventQueue
.size() > 0) {
471 // Pull any pending I/O events
472 backend
.getEvents(fillEventQueue
, timeout
);
474 // Dispatch each event to the appropriate handler, one at a time.
476 TInputEvent event
= null;
477 synchronized (fillEventQueue
) {
478 if (fillEventQueue
.size() == 0) {
481 event
= fillEventQueue
.remove(0);
483 metaHandleEvent(event
);
486 // Process timers and call doIdle()'s
493 // Shutdown the consumer threads
494 synchronized (this) {
502 * Peek at certain application-level events, add to eventQueue, and wake
503 * up the consuming Thread.
505 * @param event the input event to consume
507 private void metaHandleEvent(final TInputEvent event
) {
510 System.err.printf(String.format("metaHandleEvents event: %s\n",
511 event)); System.err.flush();
515 // Do no more processing if the application is already trying
520 // Special application-wide events -------------------------------
523 if (event
instanceof TCommandEvent
) {
524 TCommandEvent command
= (TCommandEvent
) event
;
525 if (command
.getCmd().equals(cmAbort
)) {
532 if (event
instanceof TResizeEvent
) {
533 TResizeEvent resize
= (TResizeEvent
) event
;
534 getScreen().setDimensions(resize
.getWidth(),
536 desktopBottom
= getScreen().getHeight() - 1;
543 // Peek at the mouse position
544 if (event
instanceof TMouseEvent
) {
545 TMouseEvent mouse
= (TMouseEvent
) event
;
546 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
547 mouseX
= mouse
.getX();
548 mouseY
= mouse
.getY();
553 // Put into the main queue
554 synchronized (drainEventQueue
) {
555 drainEventQueue
.add(event
);
558 // Wake all threads: primary thread will either be consuming events
559 // again or waiting in yield(), and secondary thread will either not
560 // exist or consuming events.
561 synchronized (this) {
567 * Dispatch one event to the appropriate widget or application-level
568 * event handler. This is the primary event handler, it has the normal
569 * application-wide event handling.
571 * @param event the input event to consume
572 * @see #secondaryHandleEvent(TInputEvent event)
574 private void primaryHandleEvent(final TInputEvent event
) {
576 // System.err.printf("Handle event: %s\n", event);
578 // Special application-wide events -----------------------------------
580 // Peek at the mouse position
581 if (event
instanceof TMouseEvent
) {
582 // See if we need to switch focus to another window or the menu
583 checkSwitchFocus((TMouseEvent
) event
);
586 // Handle menu events
587 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
588 TMenu menu
= activeMenu
;
590 if (event
instanceof TMouseEvent
) {
591 TMouseEvent mouse
= (TMouseEvent
) event
;
593 while (subMenus
.size() > 0) {
594 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
595 if (subMenu
.mouseWouldHit(mouse
)) {
598 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
599 && (!mouse
.getMouse1())
600 && (!mouse
.getMouse2())
601 && (!mouse
.getMouse3())
602 && (!mouse
.getMouseWheelUp())
603 && (!mouse
.getMouseWheelDown())
607 // We navigated away from a sub-menu, so close it
611 // Convert the mouse relative x/y to menu coordinates
612 assert (mouse
.getX() == mouse
.getAbsoluteX());
613 assert (mouse
.getY() == mouse
.getAbsoluteY());
614 if (subMenus
.size() > 0) {
615 menu
= subMenus
.get(subMenus
.size() - 1);
617 mouse
.setX(mouse
.getX() - menu
.getX());
618 mouse
.setY(mouse
.getY() - menu
.getY());
620 menu
.handleEvent(event
);
624 if (event
instanceof TKeypressEvent
) {
625 TKeypressEvent keypress
= (TKeypressEvent
) event
;
627 // See if this key matches an accelerator, and if so dispatch the
629 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
630 TMenuItem item
= null;
631 synchronized (accelerators
) {
632 item
= accelerators
.get(keypressLowercase
);
635 // Let the menu item dispatch
639 // Handle the keypress
640 if (onKeypress(keypress
)) {
646 if (event
instanceof TCommandEvent
) {
647 if (onCommand((TCommandEvent
) event
)) {
652 if (event
instanceof TMenuEvent
) {
653 if (onMenu((TMenuEvent
) event
)) {
658 // Dispatch events to the active window -------------------------------
659 for (TWindow window
: windows
) {
660 if (window
.getActive()) {
661 if (event
instanceof TMouseEvent
) {
662 TMouseEvent mouse
= (TMouseEvent
) event
;
663 // Convert the mouse relative x/y to window coordinates
664 assert (mouse
.getX() == mouse
.getAbsoluteX());
665 assert (mouse
.getY() == mouse
.getAbsoluteY());
666 mouse
.setX(mouse
.getX() - window
.getX());
667 mouse
.setY(mouse
.getY() - window
.getY());
669 // System.err("TApplication dispatch event: %s\n", event);
670 window
.handleEvent(event
);
676 * Dispatch one event to the appropriate widget or application-level
677 * event handler. This is the secondary event handler used by certain
678 * special dialogs (currently TMessageBox and TFileOpenBox).
680 * @param event the input event to consume
681 * @see #primaryHandleEvent(TInputEvent event)
683 private void secondaryHandleEvent(final TInputEvent event
) {
684 secondaryEventReceiver
.handleEvent(event
);
688 * Enable a widget to override the primary event thread.
690 * @param widget widget that will receive events
692 public final void enableSecondaryEventReceiver(final TWidget widget
) {
693 assert (secondaryEventReceiver
== null);
694 assert (secondaryEventHandler
== null);
695 assert (widget
instanceof TMessageBox
);
696 secondaryEventReceiver
= widget
;
697 secondaryEventHandler
= new WidgetEventHandler(this, false);
698 (new Thread(secondaryEventHandler
)).start();
705 * Yield to the secondary thread.
707 public final void yield() {
708 assert (secondaryEventReceiver
!= null);
709 while (secondaryEventReceiver
!= null) {
710 synchronized (this) {
713 } catch (InterruptedException e
) {
721 * Do stuff when there is no user input.
723 private void doIdle() {
724 // Now run any timers that have timed out
725 Date now
= new Date();
726 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
727 for (TTimer timer
: timers
) {
728 if (timer
.getNextTick().getTime() < now
.getTime()) {
730 if (timer
.recurring
) {
731 keepTimers
.add(timer
);
734 keepTimers
.add(timer
);
740 for (TWindow window
: windows
) {
746 * Get the amount of time I can sleep before missing a Timer tick.
748 * @param timeout = initial (maximum) timeout
749 * @return number of milliseconds between now and the next timer event
751 protected int getSleepTime(final int timeout
) {
752 Date now
= new Date();
753 long sleepTime
= timeout
;
754 for (TTimer timer
: timers
) {
755 if (timer
.getNextTick().getTime() < now
.getTime()) {
758 if ((timer
.getNextTick().getTime() > now
.getTime())
759 && ((timer
.getNextTick().getTime() - now
.getTime()) < sleepTime
)
761 sleepTime
= timer
.getNextTick().getTime() - now
.getTime();
764 assert (sleepTime
>= 0);
765 return (int)sleepTime
;
769 * Close window. Note that the window's destructor is NOT called by this
770 * method, instead the GC is assumed to do the cleanup.
772 * @param window the window to remove
774 public final void closeWindow(final TWindow window
) {
775 int z
= window
.getZ();
777 Collections
.sort(windows
);
779 TWindow activeWindow
= null;
780 for (TWindow w
: windows
) {
782 w
.setZ(w
.getZ() - 1);
785 assert (activeWindow
== null);
793 // Perform window cleanup
799 // Check if we are closing a TMessageBox or similar
800 if (secondaryEventReceiver
!= null) {
801 assert (secondaryEventHandler
!= null);
803 // Do not send events to the secondaryEventReceiver anymore, the
805 secondaryEventReceiver
= null;
807 // Wake all threads: primary thread will be consuming events
808 // again, and secondary thread will exit.
809 synchronized (this) {
816 * Switch to the next window.
818 * @param forward if true, then switch to the next window in the list,
819 * otherwise switch to the previous window in the list
821 public final void switchWindow(final boolean forward
) {
822 // Only switch if there are multiple windows
823 if (windows
.size() < 2) {
827 // Swap z/active between active window and the next in the list
828 int activeWindowI
= -1;
829 for (int i
= 0; i
< windows
.size(); i
++) {
830 if (windows
.get(i
).getActive()) {
835 assert (activeWindowI
>= 0);
837 // Do not switch if a window is modal
838 if (windows
.get(activeWindowI
).isModal()) {
844 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
846 if (activeWindowI
== 0) {
847 nextWindowI
= windows
.size() - 1;
849 nextWindowI
= activeWindowI
- 1;
852 windows
.get(activeWindowI
).setActive(false);
853 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
854 windows
.get(nextWindowI
).setZ(0);
855 windows
.get(nextWindowI
).setActive(true);
862 * Add a window to my window list and make it active.
864 * @param window new window to add
866 public final void addWindow(final TWindow window
) {
867 // Do not allow a modal window to spawn a non-modal window
868 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
869 assert (window
.isModal());
871 for (TWindow w
: windows
) {
873 w
.setZ(w
.getZ() + 1);
876 window
.setActive(true);
881 * Check if there is a system-modal window on top.
883 * @return true if the active window is modal
885 private boolean modalWindowActive() {
886 if (windows
.size() == 0) {
889 return windows
.get(windows
.size() - 1).isModal();
893 * Check if a mouse event would hit either the active menu or any open
896 * @param mouse mouse event
897 * @return true if the mouse would hit the active menu or an open
900 private boolean mouseOnMenu(final TMouseEvent mouse
) {
901 assert (activeMenu
!= null);
902 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
903 Collections
.reverse(menus
);
904 for (TMenu menu
: menus
) {
905 if (menu
.mouseWouldHit(mouse
)) {
909 return activeMenu
.mouseWouldHit(mouse
);
913 * See if we need to switch window or activate the menu based on
916 * @param mouse mouse event
918 private void checkSwitchFocus(final TMouseEvent mouse
) {
920 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
921 && (activeMenu
!= null)
922 && (mouse
.getAbsoluteY() != 0)
923 && (!mouseOnMenu(mouse
))
925 // They clicked outside the active menu, turn it off
926 activeMenu
.setActive(false);
928 for (TMenu menu
: subMenus
) {
929 menu
.setActive(false);
935 // See if they hit the menu bar
936 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
937 && (mouse
.getMouse1())
938 && (!modalWindowActive())
939 && (mouse
.getAbsoluteY() == 0)
942 for (TMenu menu
: subMenus
) {
943 menu
.setActive(false);
947 // They selected the menu, go activate it
948 for (TMenu menu
: menus
) {
949 if ((mouse
.getAbsoluteX() >= menu
.getX())
950 && (mouse
.getAbsoluteX() < menu
.getX()
951 + menu
.getTitle().length() + 2)
953 menu
.setActive(true);
956 menu
.setActive(false);
963 // See if they hit the menu bar
964 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
965 && (mouse
.getMouse1())
966 && (activeMenu
!= null)
967 && (mouse
.getAbsoluteY() == 0)
970 TMenu oldMenu
= activeMenu
;
971 for (TMenu menu
: subMenus
) {
972 menu
.setActive(false);
976 // See if we should switch menus
977 for (TMenu menu
: menus
) {
978 if ((mouse
.getAbsoluteX() >= menu
.getX())
979 && (mouse
.getAbsoluteX() < menu
.getX()
980 + menu
.getTitle().length() + 2)
982 menu
.setActive(true);
986 if (oldMenu
!= activeMenu
) {
987 // They switched menus
988 oldMenu
.setActive(false);
994 // Only switch if there are multiple windows
995 if (windows
.size() < 2) {
999 // Switch on the upclick
1000 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1004 Collections
.sort(windows
);
1005 if (windows
.get(0).isModal()) {
1006 // Modal windows don't switch
1010 for (TWindow window
: windows
) {
1011 assert (!window
.isModal());
1012 if (window
.mouseWouldHit(mouse
)) {
1013 if (window
== windows
.get(0)) {
1014 // Clicked on the same window, nothing to do
1018 // We will be switching to another window
1019 assert (windows
.get(0).getActive());
1020 assert (!window
.getActive());
1021 windows
.get(0).setActive(false);
1022 windows
.get(0).setZ(window
.getZ());
1024 window
.setActive(true);
1030 // Clicked on the background, nothing to do
1035 * Turn off the menu.
1037 public final void closeMenu() {
1038 if (activeMenu
!= null) {
1039 activeMenu
.setActive(false);
1041 for (TMenu menu
: subMenus
) {
1042 menu
.setActive(false);
1050 * Turn off a sub-menu.
1052 public final void closeSubMenu() {
1053 assert (activeMenu
!= null);
1054 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1055 assert (item
!= null);
1056 item
.setActive(false);
1057 subMenus
.remove(subMenus
.size() - 1);
1062 * Switch to the next menu.
1064 * @param forward if true, then switch to the next menu in the list,
1065 * otherwise switch to the previous menu in the list
1067 public final void switchMenu(final boolean forward
) {
1068 assert (activeMenu
!= null);
1070 for (TMenu menu
: subMenus
) {
1071 menu
.setActive(false);
1075 for (int i
= 0; i
< menus
.size(); i
++) {
1076 if (activeMenu
== menus
.get(i
)) {
1078 if (i
< menus
.size() - 1) {
1086 activeMenu
.setActive(false);
1087 activeMenu
= menus
.get(i
);
1088 activeMenu
.setActive(true);
1096 * Method that TApplication subclasses can override to handle menu or
1097 * posted command events.
1099 * @param command command event
1100 * @return if true, this event was consumed
1102 protected boolean onCommand(final TCommandEvent command
) {
1103 // Default: handle cmExit
1104 if (command
.equals(cmExit
)) {
1105 if (messageBox("Confirmation", "Exit application?",
1106 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1115 if (command.equals(cmShell)) {
1116 openTerminal(0, 0, TWindow.Flag.RESIZABLE);
1122 if (command
.equals(cmTile
)) {
1127 if (command
.equals(cmCascade
)) {
1132 if (command
.equals(cmCloseAll
)) {
1142 * Method that TApplication subclasses can override to handle menu
1145 * @param menu menu event
1146 * @return if true, this event was consumed
1148 protected boolean onMenu(final TMenuEvent menu
) {
1150 // Default: handle MID_EXIT
1151 if (menu
.getId() == TMenu
.MID_EXIT
) {
1152 if (messageBox("Confirmation", "Exit application?",
1153 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1156 // System.err.printf("onMenu MID_EXIT result: quit = %s\n", quit);
1163 if (menu.id == TMenu.MID_SHELL) {
1164 openTerminal(0, 0, TWindow.Flag.RESIZABLE);
1170 if (menu
.getId() == TMenu
.MID_TILE
) {
1175 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1180 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1189 * Method that TApplication subclasses can override to handle keystrokes.
1191 * @param keypress keystroke event
1192 * @return if true, this event was consumed
1194 protected boolean onKeypress(final TKeypressEvent keypress
) {
1195 // Default: only menu shortcuts
1197 // Process Alt-F, Alt-E, etc. menu shortcut keys
1198 if (!keypress
.getKey().getIsKey()
1199 && keypress
.getKey().getAlt()
1200 && !keypress
.getKey().getCtrl()
1201 && (activeMenu
== null)
1204 assert (subMenus
.size() == 0);
1206 for (TMenu menu
: menus
) {
1207 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1208 == Character
.toLowerCase(keypress
.getKey().getCh())
1211 menu
.setActive(true);
1222 * Add a keyboard accelerator to the global hash.
1224 * @param item menu item this accelerator relates to
1225 * @param keypress keypress that will dispatch a TMenuEvent
1227 public final void addAccelerator(final TMenuItem item
,
1228 final TKeypress keypress
) {
1230 // System.err.printf("addAccelerator: key %s item %s\n", keypress, item);
1232 synchronized (accelerators
) {
1233 assert (accelerators
.get(keypress
) == null);
1234 accelerators
.put(keypress
, item
);
1239 * Recompute menu x positions based on their title length.
1241 public final void recomputeMenuX() {
1243 for (TMenu menu
: menus
) {
1245 x
+= menu
.getTitle().length() + 2;
1250 * Post an event to process and turn off the menu.
1252 * @param event new event to add to the queue
1254 public final void addMenuEvent(final TInputEvent event
) {
1255 synchronized (fillEventQueue
) {
1256 fillEventQueue
.add(event
);
1262 * Add a sub-menu to the list of open sub-menus.
1264 * @param menu sub-menu
1266 public final void addSubMenu(final TMenu menu
) {
1271 * Convenience function to add a top-level menu.
1273 * @param title menu title
1274 * @return the new menu
1276 public final TMenu
addMenu(String title
) {
1279 TMenu menu
= new TMenu(this, x
, y
, title
);
1286 * Convenience function to add a default "File" menu.
1288 * @return the new menu
1290 public final TMenu
addFileMenu() {
1291 TMenu fileMenu
= addMenu("&File");
1292 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1293 fileMenu
.addSeparator();
1294 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1295 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1300 * Convenience function to add a default "Edit" menu.
1302 * @return the new menu
1304 public final TMenu
addEditMenu() {
1305 TMenu editMenu
= addMenu("&Edit");
1306 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1307 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1308 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1309 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1314 * Convenience function to add a default "Window" menu.
1316 * @return the new menu
1318 public final TMenu
addWindowMenu() {
1319 TMenu windowMenu
= addMenu("&Window");
1320 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1321 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1322 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1323 windowMenu
.addSeparator();
1324 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1325 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1326 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1327 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1328 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1333 * Close all open windows.
1335 private void closeAllWindows() {
1336 // Don't do anything if we are in the menu
1337 if (activeMenu
!= null) {
1340 for (TWindow window
: windows
) {
1341 closeWindow(window
);
1346 * Re-layout the open windows as non-overlapping tiles. This produces
1347 * almost the same results as Turbo Pascal 7.0's IDE.
1349 private void tileWindows() {
1350 // Don't do anything if we are in the menu
1351 if (activeMenu
!= null) {
1354 int z
= windows
.size();
1360 a
= (int)(Math
.sqrt(z
));
1364 if (((a
* b
) + c
) == z
) {
1372 int newWidth
= (getScreen().getWidth() / a
);
1373 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1374 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1375 // System.err.printf("Z %s a %s b %s c %s newWidth %s newHeight1 %s newHeight2 %s",
1376 // z, a, b, c, newWidth, newHeight1, newHeight2);
1378 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1379 Collections
.sort(sorted
);
1380 Collections
.reverse(sorted
);
1381 for (int i
= 0; i
< sorted
.size(); i
++) {
1382 int logicalX
= i
/ b
;
1383 int logicalY
= i
% b
;
1384 if (i
>= ((a
- 1) * b
)) {
1386 logicalY
= i
- ((a
- 1) * b
);
1389 TWindow w
= sorted
.get(i
);
1390 w
.setX(logicalX
* newWidth
);
1391 w
.setWidth(newWidth
);
1392 if (i
>= ((a
- 1) * b
)) {
1393 w
.setY((logicalY
* newHeight2
) + 1);
1394 w
.setHeight(newHeight2
);
1396 w
.setY((logicalY
* newHeight1
) + 1);
1397 w
.setHeight(newHeight1
);
1403 * Re-layout the open windows as overlapping cascaded windows.
1405 private void cascadeWindows() {
1406 // Don't do anything if we are in the menu
1407 if (activeMenu
!= null) {
1412 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1413 Collections
.sort(sorted
);
1414 Collections
.reverse(sorted
);
1415 for (TWindow window
: sorted
) {
1420 if (x
> getScreen().getWidth()) {
1423 if (y
>= getScreen().getHeight()) {
1430 * Convenience function to add a timer.
1432 * @param duration number of milliseconds to wait between ticks
1433 * @param recurring if true, re-schedule this timer after every tick
1434 * @param action function to call when button is pressed
1437 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1438 final TAction action
) {
1440 TTimer timer
= new TTimer(duration
, recurring
, action
);
1441 synchronized (timers
) {
1448 * Convenience function to remove a timer.
1450 * @param timer timer to remove
1452 public final void removeTimer(final TTimer timer
) {
1453 synchronized (timers
) {
1454 timers
.remove(timer
);
1459 * Convenience function to spawn a message box.
1461 * @param title window title, will be centered along the top border
1462 * @param caption message to display. Use embedded newlines to get a
1464 * @return the new message box
1466 public final TMessageBox
messageBox(final String title
,
1467 final String caption
) {
1469 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1473 * Convenience function to spawn a message box.
1475 * @param title window title, will be centered along the top border
1476 * @param caption message to display. Use embedded newlines to get a
1478 * @param type one of the TMessageBox.Type constants. Default is
1480 * @return the new message box
1482 public final TMessageBox
messageBox(final String title
,
1483 final String caption
, final TMessageBox
.Type type
) {
1485 return new TMessageBox(this, title
, caption
, type
);
1489 * Convenience function to spawn an input 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 * @return the new input box
1496 public final TInputBox
inputBox(final String title
, final String caption
) {
1498 return new TInputBox(this, title
, caption
);
1502 * Convenience function to spawn an input box.
1504 * @param title window title, will be centered along the top border
1505 * @param caption message to display. Use embedded newlines to get a
1507 * @param text initial text to seed the field with
1508 * @return the new input box
1510 public final TInputBox
inputBox(final String title
, final String caption
,
1511 final String text
) {
1513 return new TInputBox(this, title
, caption
, text
);