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 * If true, emit thread stuff to System.err.
70 private static final boolean debugThreads
= false;
73 * If true, emit events being processed to System.err.
75 private static final boolean debugEvents
= false;
78 * WidgetEventHandler is the main event consumer loop. There are at most
79 * two such threads in existence: the primary for normal case and a
80 * secondary that is used for TMessageBox, TInputBox, and similar.
82 private class WidgetEventHandler
implements Runnable
{
84 * The main application.
86 private TApplication application
;
89 * Whether or not this WidgetEventHandler is the primary or secondary
92 private boolean primary
= true;
97 * @param application the main application
98 * @param primary if true, this is the primary event handler thread
100 public WidgetEventHandler(final TApplication application
,
101 final boolean primary
) {
103 this.application
= application
;
104 this.primary
= primary
;
113 while (!application
.quit
) {
115 // Wait until application notifies me
116 while (!application
.quit
) {
118 synchronized (application
.drainEventQueue
) {
119 if (application
.drainEventQueue
.size() > 0) {
123 synchronized (application
) {
126 && (application
.secondaryEventReceiver
== null)
128 // Secondary thread, time to exit
133 } catch (InterruptedException e
) {
138 // Pull all events off the queue
140 TInputEvent event
= null;
141 synchronized (application
.drainEventQueue
) {
142 if (application
.drainEventQueue
.size() == 0) {
145 event
= application
.drainEventQueue
.remove(0);
147 // Wait for drawAll() or doIdle() to be done, then handle
149 boolean oldLock
= lockHandleEvent();
150 assert (oldLock
== false);
152 primaryHandleEvent(event
);
154 secondaryHandleEvent(event
);
157 && (application
.secondaryEventReceiver
== null)
159 // Secondary thread, time to exit.
161 // DO NOT UNLOCK. Primary thread just came back from
162 // primaryHandleEvent() and will unlock in the else
166 // Unlock. Either I am primary thread, or I am
167 // secondary thread and still running.
168 oldLock
= unlockHandleEvent();
169 assert (oldLock
== true);
172 } // while (true) (main runnable loop)
177 * The primary event handler thread.
179 private WidgetEventHandler primaryEventHandler
;
182 * The secondary event handler thread.
184 private WidgetEventHandler secondaryEventHandler
;
187 * The widget receiving events from the secondary event handler thread.
189 private TWidget secondaryEventReceiver
;
192 * Spinlock for the primary and secondary event handlers.
193 * WidgetEventHandler.run() is responsible for setting this value.
195 private volatile boolean insideHandleEvent
= false;
198 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
199 * spin indefinitely until unlockHandleEvent() is called.
201 * @return the old value of insideHandleEvent
203 private boolean lockHandleEvent() {
205 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
208 boolean oldValue
= true;
210 synchronized (this) {
211 // Wait for TApplication.run() to finish using the global state
212 // before allowing further event processing.
213 while (lockoutHandleEvent
== true);
215 oldValue
= insideHandleEvent
;
216 insideHandleEvent
= true;
220 System
.err
.printf(" ***\n");
226 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
227 * spin indefinitely until unlockHandleEvent() is called.
229 * @return the old value of insideHandleEvent
231 private boolean unlockHandleEvent() {
233 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
236 synchronized (this) {
237 boolean oldValue
= insideHandleEvent
;
238 insideHandleEvent
= false;
244 * Spinlock for the primary and secondary event handlers. When true, the
245 * event handlers will spinlock wait before calling handleEvent().
247 private volatile boolean lockoutHandleEvent
= false;
250 * TApplication.run() needs to be able rely on the global data structures
251 * being intact when calling doIdle() and drawAll(). Tell the event
252 * handlers to wait for an unlock before handling their events.
254 private void stopEventHandlers() {
256 System
.err
.printf(">> stopEventHandlers()");
259 lockoutHandleEvent
= true;
260 // Wait for the last event to finish processing before returning
261 // control to TApplication.run().
262 while (insideHandleEvent
== true);
265 System
.err
.printf(" XXX\n");
270 * TApplication.run() needs to be able rely on the global data structures
271 * being intact when calling doIdle() and drawAll(). Tell the event
272 * handlers that it is now OK to handle their events.
274 private void startEventHandlers() {
276 System
.err
.printf("<< startEventHandlers()\n");
278 lockoutHandleEvent
= false;
282 * Access to the physical screen, keyboard, and mouse.
284 private Backend backend
;
291 public final Screen
getScreen() {
292 return backend
.getScreen();
296 * Actual mouse coordinate X.
301 * Actual mouse coordinate Y.
306 * Event queue that is filled by run().
308 private List
<TInputEvent
> fillEventQueue
;
311 * Event queue that will be drained by either primary or secondary
314 private List
<TInputEvent
> drainEventQueue
;
317 * Top-level menus in this application.
319 private List
<TMenu
> menus
;
322 * Stack of activated sub-menus in this application.
324 private List
<TMenu
> subMenus
;
327 * The currently acive menu.
329 private TMenu activeMenu
= null;
332 * Active keyboard accelerators.
334 private Map
<TKeypress
, TMenuItem
> accelerators
;
337 * Windows and widgets pull colors from this ColorTheme.
339 private ColorTheme theme
;
342 * Get the color theme.
346 public final ColorTheme
getTheme() {
351 * The top-level windows (but not menus).
353 private List
<TWindow
> windows
;
356 * Timers that are being ticked.
358 private List
<TTimer
> timers
;
361 * When true, exit the application.
363 private boolean quit
= false;
366 * When true, repaint the entire screen.
368 private boolean repaint
= true;
371 * Request full repaint on next screen refresh.
373 public final void setRepaint() {
378 * When true, just flush updates from the screen.
380 private boolean flush
= false;
383 * Y coordinate of the top edge of the desktop. For now this is a
384 * constant. Someday it would be nice to have a multi-line menu or
387 private static final int desktopTop
= 1;
390 * Get Y coordinate of the top edge of the desktop.
392 * @return Y coordinate of the top edge of the desktop
394 public final int getDesktopTop() {
399 * Y coordinate of the bottom edge of the desktop.
401 private int desktopBottom
;
404 * Get Y coordinate of the bottom edge of the desktop.
406 * @return Y coordinate of the bottom edge of the desktop
408 public final int getDesktopBottom() {
409 return desktopBottom
;
413 * Public constructor.
415 * @param input an InputStream connected to the remote user, or null for
416 * System.in. If System.in is used, then on non-Windows systems it will
417 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
418 * mode. input is always converted to a Reader with UTF-8 encoding.
419 * @param output an OutputStream connected to the remote user, or null
420 * for System.out. output is always converted to a Writer with UTF-8
422 * @throws UnsupportedEncodingException if an exception is thrown when
423 * creating the InputStreamReader
425 public TApplication(final InputStream input
,
426 final OutputStream output
) throws UnsupportedEncodingException
{
428 // AWT is the default backend on Windows unless explicitly overridden
430 boolean useAWT
= false;
431 if (System
.getProperty("os.name").startsWith("Windows")) {
434 if (System
.getProperty("jexer.AWT") != null) {
435 if (System
.getProperty("jexer.AWT", "false").equals("true")) {
444 backend
= new AWTBackend();
446 backend
= new ECMA48Backend(input
, output
);
448 theme
= new ColorTheme();
449 desktopBottom
= getScreen().getHeight() - 1;
450 fillEventQueue
= new ArrayList
<TInputEvent
>();
451 drainEventQueue
= new ArrayList
<TInputEvent
>();
452 windows
= new LinkedList
<TWindow
>();
453 menus
= new LinkedList
<TMenu
>();
454 subMenus
= new LinkedList
<TMenu
>();
455 timers
= new LinkedList
<TTimer
>();
456 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
458 // Setup the main consumer thread
459 primaryEventHandler
= new WidgetEventHandler(this, true);
460 (new Thread(primaryEventHandler
)).start();
464 * Invert the cell at the mouse pointer position.
466 private void drawMouse() {
467 CellAttributes attr
= getScreen().getAttrXY(mouseX
, mouseY
);
468 attr
.setForeColor(attr
.getForeColor().invert());
469 attr
.setBackColor(attr
.getBackColor().invert());
470 getScreen().putAttrXY(mouseX
, mouseY
, attr
, false);
473 if (windows
.size() == 0) {
481 public final void drawAll() {
483 System
.err
.printf("drawAll() enter\n");
486 if ((flush
) && (!repaint
)) {
487 backend
.flushScreen();
497 System
.err
.printf("drawAll() REDRAW\n");
500 // If true, the cursor is not visible
501 boolean cursor
= false;
503 // Start with a clean screen
506 // Draw the background
507 CellAttributes background
= theme
.getColor("tapplication.background");
508 getScreen().putAll(GraphicsChars
.HATCH
, background
);
510 // Draw each window in reverse Z order
511 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
512 Collections
.sort(sorted
);
513 Collections
.reverse(sorted
);
514 for (TWindow window
: sorted
) {
515 window
.drawChildren();
518 // Draw the blank menubar line - reset the screen clipping first so
519 // it won't trim it out.
520 getScreen().resetClipping();
521 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
522 theme
.getColor("tmenu"));
523 // Now draw the menus.
525 for (TMenu menu
: menus
) {
526 CellAttributes menuColor
;
527 CellAttributes menuMnemonicColor
;
528 if (menu
.getActive()) {
529 menuColor
= theme
.getColor("tmenu.highlighted");
530 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
532 menuColor
= theme
.getColor("tmenu");
533 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
535 // Draw the menu title
536 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
538 getScreen().putStrXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
539 // Draw the highlight character
540 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
541 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
543 if (menu
.getActive()) {
545 // Reset the screen clipping so we can draw the next title.
546 getScreen().resetClipping();
548 x
+= menu
.getTitle().length() + 2;
551 for (TMenu menu
: subMenus
) {
552 // Reset the screen clipping so we can draw the next sub-menu.
553 getScreen().resetClipping();
557 // Draw the mouse pointer
560 // Place the cursor if it is visible
561 TWidget activeWidget
= null;
562 if (sorted
.size() > 0) {
563 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
564 if (activeWidget
.visibleCursor()) {
565 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
566 activeWidget
.getCursorAbsoluteY());
573 getScreen().hideCursor();
576 // Flush the screen contents
577 backend
.flushScreen();
584 * Run this application until it exits.
586 public final void run() {
588 // Timeout is in milliseconds, so default timeout after 1 second
590 int timeout
= getSleepTime(1000);
592 // See if there are any definitely events waiting to be processed
593 // or a screen redraw to do. If so, do not wait if there is no
595 synchronized (drainEventQueue
) {
596 if (drainEventQueue
.size() > 0) {
600 synchronized (fillEventQueue
) {
601 if (fillEventQueue
.size() > 0) {
606 // Pull any pending I/O events
607 backend
.getEvents(fillEventQueue
, timeout
);
609 // Dispatch each event to the appropriate handler, one at a time.
611 TInputEvent event
= null;
612 synchronized (fillEventQueue
) {
613 if (fillEventQueue
.size() == 0) {
616 event
= fillEventQueue
.remove(0);
618 metaHandleEvent(event
);
621 // Prevent stepping on the primary or secondary event handler.
624 // Process timers and call doIdle()'s
628 synchronized (getScreen()) {
632 // Let the event handlers run again.
633 startEventHandlers();
636 // Shutdown the consumer threads
637 synchronized (this) {
645 * Peek at certain application-level events, add to eventQueue, and wake
646 * up the consuming Thread.
648 * @param event the input event to consume
650 private void metaHandleEvent(final TInputEvent event
) {
653 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
654 event
)); System
.err
.flush();
658 // Do no more processing if the application is already trying
663 // Special application-wide events -------------------------------
666 if (event
instanceof TCommandEvent
) {
667 TCommandEvent command
= (TCommandEvent
) event
;
668 if (command
.getCmd().equals(cmAbort
)) {
675 if (event
instanceof TResizeEvent
) {
676 TResizeEvent resize
= (TResizeEvent
) event
;
677 getScreen().setDimensions(resize
.getWidth(),
679 desktopBottom
= getScreen().getHeight() - 1;
686 // Peek at the mouse position
687 if (event
instanceof TMouseEvent
) {
688 TMouseEvent mouse
= (TMouseEvent
) event
;
689 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
690 mouseX
= mouse
.getX();
691 mouseY
= mouse
.getY();
696 // Put into the main queue
697 synchronized (drainEventQueue
) {
698 drainEventQueue
.add(event
);
701 // Wake all threads: primary thread will either be consuming events
702 // again or waiting in yield(), and secondary thread will either not
703 // exist or consuming events.
704 synchronized (this) {
710 * Dispatch one event to the appropriate widget or application-level
711 * event handler. This is the primary event handler, it has the normal
712 * application-wide event handling.
714 * @param event the input event to consume
715 * @see #secondaryHandleEvent(TInputEvent event)
717 private void primaryHandleEvent(final TInputEvent event
) {
720 System
.err
.printf("Handle event: %s\n", event
);
723 // Special application-wide events -----------------------------------
725 // Peek at the mouse position
726 if (event
instanceof TMouseEvent
) {
727 // See if we need to switch focus to another window or the menu
728 checkSwitchFocus((TMouseEvent
) event
);
731 // Handle menu events
732 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
733 TMenu menu
= activeMenu
;
735 if (event
instanceof TMouseEvent
) {
736 TMouseEvent mouse
= (TMouseEvent
) event
;
738 while (subMenus
.size() > 0) {
739 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
740 if (subMenu
.mouseWouldHit(mouse
)) {
743 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
744 && (!mouse
.getMouse1())
745 && (!mouse
.getMouse2())
746 && (!mouse
.getMouse3())
747 && (!mouse
.getMouseWheelUp())
748 && (!mouse
.getMouseWheelDown())
752 // We navigated away from a sub-menu, so close it
756 // Convert the mouse relative x/y to menu coordinates
757 assert (mouse
.getX() == mouse
.getAbsoluteX());
758 assert (mouse
.getY() == mouse
.getAbsoluteY());
759 if (subMenus
.size() > 0) {
760 menu
= subMenus
.get(subMenus
.size() - 1);
762 mouse
.setX(mouse
.getX() - menu
.getX());
763 mouse
.setY(mouse
.getY() - menu
.getY());
765 menu
.handleEvent(event
);
769 if (event
instanceof TKeypressEvent
) {
770 TKeypressEvent keypress
= (TKeypressEvent
) event
;
772 // See if this key matches an accelerator, and if so dispatch the
774 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
775 TMenuItem item
= null;
776 synchronized (accelerators
) {
777 item
= accelerators
.get(keypressLowercase
);
780 // Let the menu item dispatch
784 // Handle the keypress
785 if (onKeypress(keypress
)) {
791 if (event
instanceof TCommandEvent
) {
792 if (onCommand((TCommandEvent
) event
)) {
797 if (event
instanceof TMenuEvent
) {
798 if (onMenu((TMenuEvent
) event
)) {
803 // Dispatch events to the active window -------------------------------
804 for (TWindow window
: windows
) {
805 if (window
.getActive()) {
806 if (event
instanceof TMouseEvent
) {
807 TMouseEvent mouse
= (TMouseEvent
) event
;
808 // Convert the mouse relative x/y to window coordinates
809 assert (mouse
.getX() == mouse
.getAbsoluteX());
810 assert (mouse
.getY() == mouse
.getAbsoluteY());
811 mouse
.setX(mouse
.getX() - window
.getX());
812 mouse
.setY(mouse
.getY() - window
.getY());
815 System
.err
.printf("TApplication dispatch event: %s\n",
818 window
.handleEvent(event
);
824 * Dispatch one event to the appropriate widget or application-level
825 * event handler. This is the secondary event handler used by certain
826 * special dialogs (currently TMessageBox and TFileOpenBox).
828 * @param event the input event to consume
829 * @see #primaryHandleEvent(TInputEvent event)
831 private void secondaryHandleEvent(final TInputEvent event
) {
832 secondaryEventReceiver
.handleEvent(event
);
836 * Enable a widget to override the primary event thread.
838 * @param widget widget that will receive events
840 public final void enableSecondaryEventReceiver(final TWidget widget
) {
841 assert (secondaryEventReceiver
== null);
842 assert (secondaryEventHandler
== null);
843 assert (widget
instanceof TMessageBox
);
844 secondaryEventReceiver
= widget
;
845 secondaryEventHandler
= new WidgetEventHandler(this, false);
846 (new Thread(secondaryEventHandler
)).start();
853 * Yield to the secondary thread.
855 public final void yield() {
856 assert (secondaryEventReceiver
!= null);
857 // This is where we handoff the event handler lock from the primary
858 // to secondary thread. We unlock here, and in a future loop the
859 // secondary thread locks again. When it gives up, we have the
861 boolean oldLock
= unlockHandleEvent();
862 assert (oldLock
== true);
864 while (secondaryEventReceiver
!= null) {
865 synchronized (this) {
868 } catch (InterruptedException e
) {
876 * Do stuff when there is no user input.
878 private void doIdle() {
880 System
.err
.printf("doIdle()\n");
883 // Now run any timers that have timed out
884 Date now
= new Date();
885 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
886 for (TTimer timer
: timers
) {
887 if (timer
.getNextTick().getTime() < now
.getTime()) {
889 if (timer
.recurring
) {
890 keepTimers
.add(timer
);
893 keepTimers
.add(timer
);
899 for (TWindow window
: windows
) {
905 * Get the amount of time I can sleep before missing a Timer tick.
907 * @param timeout = initial (maximum) timeout
908 * @return number of milliseconds between now and the next timer event
910 protected int getSleepTime(final int timeout
) {
911 Date now
= new Date();
912 long sleepTime
= timeout
;
913 for (TTimer timer
: timers
) {
914 if (timer
.getNextTick().getTime() < now
.getTime()) {
917 if ((timer
.getNextTick().getTime() > now
.getTime())
918 && ((timer
.getNextTick().getTime() - now
.getTime()) < sleepTime
)
920 sleepTime
= timer
.getNextTick().getTime() - now
.getTime();
923 assert (sleepTime
>= 0);
924 return (int)sleepTime
;
928 * Close window. Note that the window's destructor is NOT called by this
929 * method, instead the GC is assumed to do the cleanup.
931 * @param window the window to remove
933 public final void closeWindow(final TWindow window
) {
934 int z
= window
.getZ();
936 Collections
.sort(windows
);
938 TWindow activeWindow
= null;
939 for (TWindow w
: windows
) {
941 w
.setZ(w
.getZ() - 1);
944 assert (activeWindow
== null);
952 // Perform window cleanup
958 // Check if we are closing a TMessageBox or similar
959 if (secondaryEventReceiver
!= null) {
960 assert (secondaryEventHandler
!= null);
962 // Do not send events to the secondaryEventReceiver anymore, the
964 secondaryEventReceiver
= null;
966 // Wake all threads: primary thread will be consuming events
967 // again, and secondary thread will exit.
968 synchronized (this) {
975 * Switch to the next window.
977 * @param forward if true, then switch to the next window in the list,
978 * otherwise switch to the previous window in the list
980 public final void switchWindow(final boolean forward
) {
981 // Only switch if there are multiple windows
982 if (windows
.size() < 2) {
986 // Swap z/active between active window and the next in the list
987 int activeWindowI
= -1;
988 for (int i
= 0; i
< windows
.size(); i
++) {
989 if (windows
.get(i
).getActive()) {
994 assert (activeWindowI
>= 0);
996 // Do not switch if a window is modal
997 if (windows
.get(activeWindowI
).isModal()) {
1003 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1005 if (activeWindowI
== 0) {
1006 nextWindowI
= windows
.size() - 1;
1008 nextWindowI
= activeWindowI
- 1;
1011 windows
.get(activeWindowI
).setActive(false);
1012 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1013 windows
.get(nextWindowI
).setZ(0);
1014 windows
.get(nextWindowI
).setActive(true);
1021 * Add a window to my window list and make it active.
1023 * @param window new window to add
1025 public final void addWindow(final TWindow window
) {
1026 // Do not allow a modal window to spawn a non-modal window
1027 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1028 assert (window
.isModal());
1030 for (TWindow w
: windows
) {
1032 w
.setZ(w
.getZ() + 1);
1034 windows
.add(window
);
1035 window
.setActive(true);
1040 * Check if there is a system-modal window on top.
1042 * @return true if the active window is modal
1044 private boolean modalWindowActive() {
1045 if (windows
.size() == 0) {
1048 return windows
.get(windows
.size() - 1).isModal();
1052 * Check if a mouse event would hit either the active menu or any open
1055 * @param mouse mouse event
1056 * @return true if the mouse would hit the active menu or an open
1059 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1060 assert (activeMenu
!= null);
1061 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1062 Collections
.reverse(menus
);
1063 for (TMenu menu
: menus
) {
1064 if (menu
.mouseWouldHit(mouse
)) {
1068 return activeMenu
.mouseWouldHit(mouse
);
1072 * See if we need to switch window or activate the menu based on
1075 * @param mouse mouse event
1077 private void checkSwitchFocus(final TMouseEvent mouse
) {
1079 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1080 && (activeMenu
!= null)
1081 && (mouse
.getAbsoluteY() != 0)
1082 && (!mouseOnMenu(mouse
))
1084 // They clicked outside the active menu, turn it off
1085 activeMenu
.setActive(false);
1087 for (TMenu menu
: subMenus
) {
1088 menu
.setActive(false);
1094 // See if they hit the menu bar
1095 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1096 && (mouse
.getMouse1())
1097 && (!modalWindowActive())
1098 && (mouse
.getAbsoluteY() == 0)
1101 for (TMenu menu
: subMenus
) {
1102 menu
.setActive(false);
1106 // They selected the menu, go activate it
1107 for (TMenu menu
: menus
) {
1108 if ((mouse
.getAbsoluteX() >= menu
.getX())
1109 && (mouse
.getAbsoluteX() < menu
.getX()
1110 + menu
.getTitle().length() + 2)
1112 menu
.setActive(true);
1115 menu
.setActive(false);
1122 // See if they hit the menu bar
1123 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1124 && (mouse
.getMouse1())
1125 && (activeMenu
!= null)
1126 && (mouse
.getAbsoluteY() == 0)
1129 TMenu oldMenu
= activeMenu
;
1130 for (TMenu menu
: subMenus
) {
1131 menu
.setActive(false);
1135 // See if we should switch menus
1136 for (TMenu menu
: menus
) {
1137 if ((mouse
.getAbsoluteX() >= menu
.getX())
1138 && (mouse
.getAbsoluteX() < menu
.getX()
1139 + menu
.getTitle().length() + 2)
1141 menu
.setActive(true);
1145 if (oldMenu
!= activeMenu
) {
1146 // They switched menus
1147 oldMenu
.setActive(false);
1153 // Only switch if there are multiple windows
1154 if (windows
.size() < 2) {
1158 // Switch on the upclick
1159 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1163 Collections
.sort(windows
);
1164 if (windows
.get(0).isModal()) {
1165 // Modal windows don't switch
1169 for (TWindow window
: windows
) {
1170 assert (!window
.isModal());
1171 if (window
.mouseWouldHit(mouse
)) {
1172 if (window
== windows
.get(0)) {
1173 // Clicked on the same window, nothing to do
1177 // We will be switching to another window
1178 assert (windows
.get(0).getActive());
1179 assert (!window
.getActive());
1180 windows
.get(0).setActive(false);
1181 windows
.get(0).setZ(window
.getZ());
1183 window
.setActive(true);
1189 // Clicked on the background, nothing to do
1194 * Turn off the menu.
1196 public final void closeMenu() {
1197 if (activeMenu
!= null) {
1198 activeMenu
.setActive(false);
1200 for (TMenu menu
: subMenus
) {
1201 menu
.setActive(false);
1209 * Turn off a sub-menu.
1211 public final void closeSubMenu() {
1212 assert (activeMenu
!= null);
1213 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1214 assert (item
!= null);
1215 item
.setActive(false);
1216 subMenus
.remove(subMenus
.size() - 1);
1221 * Switch to the next menu.
1223 * @param forward if true, then switch to the next menu in the list,
1224 * otherwise switch to the previous menu in the list
1226 public final void switchMenu(final boolean forward
) {
1227 assert (activeMenu
!= null);
1229 for (TMenu menu
: subMenus
) {
1230 menu
.setActive(false);
1234 for (int i
= 0; i
< menus
.size(); i
++) {
1235 if (activeMenu
== menus
.get(i
)) {
1237 if (i
< menus
.size() - 1) {
1245 activeMenu
.setActive(false);
1246 activeMenu
= menus
.get(i
);
1247 activeMenu
.setActive(true);
1255 * Method that TApplication subclasses can override to handle menu or
1256 * posted command events.
1258 * @param command command event
1259 * @return if true, this event was consumed
1261 protected boolean onCommand(final TCommandEvent command
) {
1262 // Default: handle cmExit
1263 if (command
.equals(cmExit
)) {
1264 if (messageBox("Confirmation", "Exit application?",
1265 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1272 if (command
.equals(cmShell
)) {
1273 openTerminal(0, 0, TWindow
.RESIZABLE
);
1278 if (command
.equals(cmTile
)) {
1283 if (command
.equals(cmCascade
)) {
1288 if (command
.equals(cmCloseAll
)) {
1298 * Method that TApplication subclasses can override to handle menu
1301 * @param menu menu event
1302 * @return if true, this event was consumed
1304 protected boolean onMenu(final TMenuEvent menu
) {
1306 // Default: handle MID_EXIT
1307 if (menu
.getId() == TMenu
.MID_EXIT
) {
1308 if (messageBox("Confirmation", "Exit application?",
1309 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1312 // System.err.printf("onMenu MID_EXIT result: quit = %s\n", quit);
1317 if (menu
.getId() == TMenu
.MID_SHELL
) {
1318 openTerminal(0, 0, TWindow
.RESIZABLE
);
1323 if (menu
.getId() == TMenu
.MID_TILE
) {
1328 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1333 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1342 * Method that TApplication subclasses can override to handle keystrokes.
1344 * @param keypress keystroke event
1345 * @return if true, this event was consumed
1347 protected boolean onKeypress(final TKeypressEvent keypress
) {
1348 // Default: only menu shortcuts
1350 // Process Alt-F, Alt-E, etc. menu shortcut keys
1351 if (!keypress
.getKey().getIsKey()
1352 && keypress
.getKey().getAlt()
1353 && !keypress
.getKey().getCtrl()
1354 && (activeMenu
== null)
1357 assert (subMenus
.size() == 0);
1359 for (TMenu menu
: menus
) {
1360 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1361 == Character
.toLowerCase(keypress
.getKey().getCh())
1364 menu
.setActive(true);
1375 * Add a keyboard accelerator to the global hash.
1377 * @param item menu item this accelerator relates to
1378 * @param keypress keypress that will dispatch a TMenuEvent
1380 public final void addAccelerator(final TMenuItem item
,
1381 final TKeypress keypress
) {
1383 // System.err.printf("addAccelerator: key %s item %s\n", keypress, item);
1385 synchronized (accelerators
) {
1386 assert (accelerators
.get(keypress
) == null);
1387 accelerators
.put(keypress
, item
);
1392 * Recompute menu x positions based on their title length.
1394 public final void recomputeMenuX() {
1396 for (TMenu menu
: menus
) {
1398 x
+= menu
.getTitle().length() + 2;
1403 * Post an event to process and turn off the menu.
1405 * @param event new event to add to the queue
1407 public final void addMenuEvent(final TInputEvent event
) {
1408 synchronized (fillEventQueue
) {
1409 fillEventQueue
.add(event
);
1415 * Add a sub-menu to the list of open sub-menus.
1417 * @param menu sub-menu
1419 public final void addSubMenu(final TMenu menu
) {
1424 * Convenience function to add a top-level menu.
1426 * @param title menu title
1427 * @return the new menu
1429 public final TMenu
addMenu(final String title
) {
1432 TMenu menu
= new TMenu(this, x
, y
, title
);
1439 * Convenience function to add a default "File" menu.
1441 * @return the new menu
1443 public final TMenu
addFileMenu() {
1444 TMenu fileMenu
= addMenu("&File");
1445 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1446 fileMenu
.addSeparator();
1447 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1448 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1453 * Convenience function to add a default "Edit" menu.
1455 * @return the new menu
1457 public final TMenu
addEditMenu() {
1458 TMenu editMenu
= addMenu("&Edit");
1459 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1460 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1461 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1462 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1467 * Convenience function to add a default "Window" menu.
1469 * @return the new menu
1471 public final TMenu
addWindowMenu() {
1472 TMenu windowMenu
= addMenu("&Window");
1473 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1474 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1475 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1476 windowMenu
.addSeparator();
1477 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1478 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1479 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1480 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1481 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1486 * Close all open windows.
1488 private void closeAllWindows() {
1489 // Don't do anything if we are in the menu
1490 if (activeMenu
!= null) {
1493 for (TWindow window
: windows
) {
1494 closeWindow(window
);
1499 * Re-layout the open windows as non-overlapping tiles. This produces
1500 * almost the same results as Turbo Pascal 7.0's IDE.
1502 private void tileWindows() {
1503 // Don't do anything if we are in the menu
1504 if (activeMenu
!= null) {
1507 int z
= windows
.size();
1513 a
= (int)(Math
.sqrt(z
));
1517 if (((a
* b
) + c
) == z
) {
1525 int newWidth
= (getScreen().getWidth() / a
);
1526 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1527 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1529 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1530 Collections
.sort(sorted
);
1531 Collections
.reverse(sorted
);
1532 for (int i
= 0; i
< sorted
.size(); i
++) {
1533 int logicalX
= i
/ b
;
1534 int logicalY
= i
% b
;
1535 if (i
>= ((a
- 1) * b
)) {
1537 logicalY
= i
- ((a
- 1) * b
);
1540 TWindow w
= sorted
.get(i
);
1541 w
.setX(logicalX
* newWidth
);
1542 w
.setWidth(newWidth
);
1543 if (i
>= ((a
- 1) * b
)) {
1544 w
.setY((logicalY
* newHeight2
) + 1);
1545 w
.setHeight(newHeight2
);
1547 w
.setY((logicalY
* newHeight1
) + 1);
1548 w
.setHeight(newHeight1
);
1554 * Re-layout the open windows as overlapping cascaded windows.
1556 private void cascadeWindows() {
1557 // Don't do anything if we are in the menu
1558 if (activeMenu
!= null) {
1563 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1564 Collections
.sort(sorted
);
1565 Collections
.reverse(sorted
);
1566 for (TWindow window
: sorted
) {
1571 if (x
> getScreen().getWidth()) {
1574 if (y
>= getScreen().getHeight()) {
1581 * Convenience function to add a timer.
1583 * @param duration number of milliseconds to wait between ticks
1584 * @param recurring if true, re-schedule this timer after every tick
1585 * @param action function to call when button is pressed
1588 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1589 final TAction action
) {
1591 TTimer timer
= new TTimer(duration
, recurring
, action
);
1592 synchronized (timers
) {
1599 * Convenience function to remove a timer.
1601 * @param timer timer to remove
1603 public final void removeTimer(final TTimer timer
) {
1604 synchronized (timers
) {
1605 timers
.remove(timer
);
1610 * Convenience function to spawn a message box.
1612 * @param title window title, will be centered along the top border
1613 * @param caption message to display. Use embedded newlines to get a
1615 * @return the new message box
1617 public final TMessageBox
messageBox(final String title
,
1618 final String caption
) {
1620 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1624 * Convenience function to spawn a message box.
1626 * @param title window title, will be centered along the top border
1627 * @param caption message to display. Use embedded newlines to get a
1629 * @param type one of the TMessageBox.Type constants. Default is
1631 * @return the new message box
1633 public final TMessageBox
messageBox(final String title
,
1634 final String caption
, final TMessageBox
.Type type
) {
1636 return new TMessageBox(this, title
, caption
, type
);
1640 * Convenience function to spawn an input box.
1642 * @param title window title, will be centered along the top border
1643 * @param caption message to display. Use embedded newlines to get a
1645 * @return the new input box
1647 public final TInputBox
inputBox(final String title
, final String caption
) {
1649 return new TInputBox(this, title
, caption
);
1653 * Convenience function to spawn an input box.
1655 * @param title window title, will be centered along the top border
1656 * @param caption message to display. Use embedded newlines to get a
1658 * @param text initial text to seed the field with
1659 * @return the new input box
1661 public final TInputBox
inputBox(final String title
, final String caption
,
1662 final String text
) {
1664 return new TInputBox(this, title
, caption
, text
);
1668 * Convenience function to open a terminal window.
1670 * @param x column relative to parent
1671 * @param y row relative to parent
1672 * @return the terminal new window
1674 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1675 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1679 * Convenience function to open a terminal window.
1681 * @param x column relative to parent
1682 * @param y row relative to parent
1683 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1684 * @return the terminal new window
1686 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1689 return new TTerminalWindow(this, x
, y
, flags
);