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) {
124 synchronized (this) {
126 System.err.printf("%s %s sleep\n", this, primary ?
127 "primary" : "secondary");
133 System.err.printf("%s %s AWAKE\n", this, primary ?
134 "primary" : "secondary");
138 && (application
.secondaryEventReceiver
== null)
140 // Secondary thread, emergency exit. If we
141 // got here then something went wrong with
142 // the handoff between yield() and
145 System
.err
.printf("secondary exiting at wrong time, why?\n");
146 synchronized (application
.primaryEventHandler
) {
147 application
.primaryEventHandler
.notify();
149 application
.secondaryEventHandler
= null;
154 } catch (InterruptedException e
) {
159 // Pull all events off the queue
161 TInputEvent event
= null;
162 synchronized (application
.drainEventQueue
) {
163 if (application
.drainEventQueue
.size() == 0) {
166 event
= application
.drainEventQueue
.remove(0);
168 // Wait for drawAll() or doIdle() to be done, then handle
170 boolean oldLock
= lockHandleEvent();
171 assert (oldLock
== false);
173 primaryHandleEvent(event
);
175 secondaryHandleEvent(event
);
177 application
.repaint
= true;
179 && (application
.secondaryEventReceiver
== null)
181 // Secondary thread, time to exit.
183 // DO NOT UNLOCK. Primary thread just came back from
184 // primaryHandleEvent() and will unlock in the else
185 // block below. Just wake it up.
186 synchronized (application
.primaryEventHandler
) {
187 application
.primaryEventHandler
.notify();
189 // Now eliminate my reference so that
190 // wakeEventHandler() resumes working on the primary.
191 application
.secondaryEventHandler
= null;
196 // Unlock. Either I am primary thread, or I am
197 // secondary thread and still running.
198 oldLock
= unlockHandleEvent();
199 assert (oldLock
== true);
203 // I have done some work of some kind. Tell the main run()
204 // loop to wake up now.
205 synchronized (application
) {
206 application
.notify();
209 } // while (true) (main runnable loop)
214 * The primary event handler thread.
216 private volatile WidgetEventHandler primaryEventHandler
;
219 * The secondary event handler thread.
221 private volatile WidgetEventHandler secondaryEventHandler
;
224 * The widget receiving events from the secondary event handler thread.
226 private volatile TWidget secondaryEventReceiver
;
229 * Spinlock for the primary and secondary event handlers.
230 * WidgetEventHandler.run() is responsible for setting this value.
232 private volatile boolean insideHandleEvent
= false;
235 * Wake the sleeping active event handler.
237 private void wakeEventHandler() {
238 if (secondaryEventHandler
!= null) {
239 synchronized (secondaryEventHandler
) {
240 secondaryEventHandler
.notify();
243 assert (primaryEventHandler
!= null);
244 synchronized (primaryEventHandler
) {
245 primaryEventHandler
.notify();
251 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
252 * spin indefinitely until unlockHandleEvent() is called.
254 * @return the old value of insideHandleEvent
256 private boolean lockHandleEvent() {
258 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
261 boolean oldValue
= true;
263 synchronized (this) {
264 // Wait for TApplication.run() to finish using the global state
265 // before allowing further event processing.
266 while (lockoutHandleEvent
== true);
268 oldValue
= insideHandleEvent
;
269 insideHandleEvent
= true;
273 System
.err
.printf(" ***\n");
279 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
280 * spin indefinitely until unlockHandleEvent() is called.
282 * @return the old value of insideHandleEvent
284 private boolean unlockHandleEvent() {
286 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
289 synchronized (this) {
290 boolean oldValue
= insideHandleEvent
;
291 insideHandleEvent
= false;
297 * Spinlock for the primary and secondary event handlers. When true, the
298 * event handlers will spinlock wait before calling handleEvent().
300 private volatile boolean lockoutHandleEvent
= false;
303 * TApplication.run() needs to be able rely on the global data structures
304 * being intact when calling doIdle() and drawAll(). Tell the event
305 * handlers to wait for an unlock before handling their events.
307 private void stopEventHandlers() {
309 System
.err
.printf(">> stopEventHandlers()");
312 lockoutHandleEvent
= true;
313 // Wait for the last event to finish processing before returning
314 // control to TApplication.run().
315 while (insideHandleEvent
== true);
318 System
.err
.printf(" XXX\n");
323 * TApplication.run() needs to be able rely on the global data structures
324 * being intact when calling doIdle() and drawAll(). Tell the event
325 * handlers that it is now OK to handle their events.
327 private void startEventHandlers() {
329 System
.err
.printf("<< startEventHandlers()\n");
331 lockoutHandleEvent
= false;
335 * Access to the physical screen, keyboard, and mouse.
337 private Backend backend
;
344 public final Screen
getScreen() {
345 return backend
.getScreen();
349 * Actual mouse coordinate X.
354 * Actual mouse coordinate Y.
359 * Event queue that is filled by run().
361 private List
<TInputEvent
> fillEventQueue
;
364 * Event queue that will be drained by either primary or secondary
367 private List
<TInputEvent
> drainEventQueue
;
370 * Top-level menus in this application.
372 private List
<TMenu
> menus
;
375 * Stack of activated sub-menus in this application.
377 private List
<TMenu
> subMenus
;
380 * The currently acive menu.
382 private TMenu activeMenu
= null;
385 * Active keyboard accelerators.
387 private Map
<TKeypress
, TMenuItem
> accelerators
;
390 * Windows and widgets pull colors from this ColorTheme.
392 private ColorTheme theme
;
395 * Get the color theme.
399 public final ColorTheme
getTheme() {
404 * The top-level windows (but not menus).
406 private List
<TWindow
> windows
;
409 * Timers that are being ticked.
411 private List
<TTimer
> timers
;
414 * When true, exit the application.
416 private volatile boolean quit
= false;
419 * When true, repaint the entire screen.
421 private volatile boolean repaint
= true;
424 * When true, just flush updates from the screen. This is only used to
425 * minimize physical writes for the mouse cursor.
427 private boolean flush
= false;
430 * Y coordinate of the top edge of the desktop. For now this is a
431 * constant. Someday it would be nice to have a multi-line menu or
434 private static final int desktopTop
= 1;
437 * Get Y coordinate of the top edge of the desktop.
439 * @return Y coordinate of the top edge of the desktop
441 public final int getDesktopTop() {
446 * Y coordinate of the bottom edge of the desktop.
448 private int desktopBottom
;
451 * Get Y coordinate of the bottom edge of the desktop.
453 * @return Y coordinate of the bottom edge of the desktop
455 public final int getDesktopBottom() {
456 return desktopBottom
;
460 * Public constructor.
462 * @param input an InputStream connected to the remote user, or null for
463 * System.in. If System.in is used, then on non-Windows systems it will
464 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
465 * mode. input is always converted to a Reader with UTF-8 encoding.
466 * @param output an OutputStream connected to the remote user, or null
467 * for System.out. output is always converted to a Writer with UTF-8
469 * @throws UnsupportedEncodingException if an exception is thrown when
470 * creating the InputStreamReader
472 public TApplication(final InputStream input
,
473 final OutputStream output
) throws UnsupportedEncodingException
{
475 // AWT is the default backend on Windows unless explicitly overridden
477 boolean useAWT
= false;
478 if (System
.getProperty("os.name").startsWith("Windows")) {
481 if (System
.getProperty("jexer.AWT") != null) {
482 if (System
.getProperty("jexer.AWT", "false").equals("true")) {
491 backend
= new AWTBackend(this);
493 backend
= new ECMA48Backend(this, input
, output
);
495 theme
= new ColorTheme();
496 desktopBottom
= getScreen().getHeight() - 1;
497 fillEventQueue
= new ArrayList
<TInputEvent
>();
498 drainEventQueue
= new ArrayList
<TInputEvent
>();
499 windows
= new LinkedList
<TWindow
>();
500 menus
= new LinkedList
<TMenu
>();
501 subMenus
= new LinkedList
<TMenu
>();
502 timers
= new LinkedList
<TTimer
>();
503 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
505 // Setup the main consumer thread
506 primaryEventHandler
= new WidgetEventHandler(this, true);
507 (new Thread(primaryEventHandler
)).start();
511 * Invert the cell at the mouse pointer position.
513 private void drawMouse() {
514 CellAttributes attr
= getScreen().getAttrXY(mouseX
, mouseY
);
515 attr
.setForeColor(attr
.getForeColor().invert());
516 attr
.setBackColor(attr
.getBackColor().invert());
517 getScreen().putAttrXY(mouseX
, mouseY
, attr
, false);
520 if (windows
.size() == 0) {
528 public final void drawAll() {
530 System
.err
.printf("drawAll() enter\n");
533 if ((flush
) && (!repaint
)) {
534 backend
.flushScreen();
540 System
.err
.printf("drawAll() REDRAW\n");
543 // If true, the cursor is not visible
544 boolean cursor
= false;
546 // Start with a clean screen
549 // Draw the background
550 CellAttributes background
= theme
.getColor("tapplication.background");
551 getScreen().putAll(GraphicsChars
.HATCH
, background
);
553 // Draw each window in reverse Z order
554 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
555 Collections
.sort(sorted
);
556 Collections
.reverse(sorted
);
557 for (TWindow window
: sorted
) {
558 window
.drawChildren();
561 // Draw the blank menubar line - reset the screen clipping first so
562 // it won't trim it out.
563 getScreen().resetClipping();
564 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
565 theme
.getColor("tmenu"));
566 // Now draw the menus.
568 for (TMenu menu
: menus
) {
569 CellAttributes menuColor
;
570 CellAttributes menuMnemonicColor
;
571 if (menu
.getActive()) {
572 menuColor
= theme
.getColor("tmenu.highlighted");
573 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
575 menuColor
= theme
.getColor("tmenu");
576 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
578 // Draw the menu title
579 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
581 getScreen().putStrXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
582 // Draw the highlight character
583 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
584 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
586 if (menu
.getActive()) {
588 // Reset the screen clipping so we can draw the next title.
589 getScreen().resetClipping();
591 x
+= menu
.getTitle().length() + 2;
594 for (TMenu menu
: subMenus
) {
595 // Reset the screen clipping so we can draw the next sub-menu.
596 getScreen().resetClipping();
600 // Draw the mouse pointer
603 // Place the cursor if it is visible
604 TWidget activeWidget
= null;
605 if (sorted
.size() > 0) {
606 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
607 if (activeWidget
.visibleCursor()) {
608 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
609 activeWidget
.getCursorAbsoluteY());
616 getScreen().hideCursor();
619 // Flush the screen contents
620 backend
.flushScreen();
627 * Run this application until it exits.
629 public final void run() {
631 // Timeout is in milliseconds, so default timeout after 1 second
635 // If I've got no updates to render, wait for something from the
636 // backend or a timer.
637 if (!repaint
&& !flush
) {
638 // Never sleep longer than 100 millis, to get windows with
639 // background tasks an opportunity to update the display.
640 timeout
= getSleepTime(100);
642 // See if there are any definitely events waiting to be
643 // processed. If so, do not wait -- either there is I/O
644 // coming in or the primary/secondary threads are still
646 synchronized (drainEventQueue
) {
647 if (drainEventQueue
.size() > 0) {
651 synchronized (fillEventQueue
) {
652 if (fillEventQueue
.size() > 0) {
659 // As of now, I've got nothing to do: no I/O, nothing from
660 // the consumer threads, no timers that need to run ASAP. So
661 // wait until either the backend or the consumer threads have
664 synchronized (this) {
667 } catch (InterruptedException e
) {
668 // I'm awake and don't care why, let's see what's going
673 // Pull any pending I/O events
674 backend
.getEvents(fillEventQueue
);
676 // Dispatch each event to the appropriate handler, one at a time.
678 TInputEvent event
= null;
679 synchronized (fillEventQueue
) {
680 if (fillEventQueue
.size() == 0) {
683 event
= fillEventQueue
.remove(0);
685 metaHandleEvent(event
);
688 // Wake a consumer thread if we have any pending events.
689 synchronized (drainEventQueue
) {
690 if (drainEventQueue
.size() > 0) {
695 // Prevent stepping on the primary or secondary event handler.
698 // Process timers and call doIdle()'s
702 synchronized (getScreen()) {
706 // Let the event handlers run again.
707 startEventHandlers();
711 // Shutdown the event consumer threads
712 if (secondaryEventHandler
!= null) {
713 synchronized (secondaryEventHandler
) {
714 secondaryEventHandler
.notify();
717 if (primaryEventHandler
!= null) {
718 synchronized (primaryEventHandler
) {
719 primaryEventHandler
.notify();
723 // Shutdown the user I/O thread(s)
726 // Close all the windows. This gives them an opportunity to release
733 * Peek at certain application-level events, add to eventQueue, and wake
734 * up the consuming Thread.
736 * @param event the input event to consume
738 private void metaHandleEvent(final TInputEvent event
) {
741 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
742 event
)); System
.err
.flush();
746 // Do no more processing if the application is already trying
751 // Special application-wide events -------------------------------
754 if (event
instanceof TCommandEvent
) {
755 TCommandEvent command
= (TCommandEvent
) event
;
756 if (command
.getCmd().equals(cmAbort
)) {
763 if (event
instanceof TResizeEvent
) {
764 TResizeEvent resize
= (TResizeEvent
) event
;
765 getScreen().setDimensions(resize
.getWidth(),
767 desktopBottom
= getScreen().getHeight() - 1;
774 // Peek at the mouse position
775 if (event
instanceof TMouseEvent
) {
776 TMouseEvent mouse
= (TMouseEvent
) event
;
777 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
778 mouseX
= mouse
.getX();
779 mouseY
= mouse
.getY();
784 // Put into the main queue
785 synchronized (drainEventQueue
) {
786 drainEventQueue
.add(event
);
791 * Dispatch one event to the appropriate widget or application-level
792 * event handler. This is the primary event handler, it has the normal
793 * application-wide event handling.
795 * @param event the input event to consume
796 * @see #secondaryHandleEvent(TInputEvent event)
798 private void primaryHandleEvent(final TInputEvent event
) {
801 System
.err
.printf("Handle event: %s\n", event
);
804 // Special application-wide events -----------------------------------
806 // Peek at the mouse position
807 if (event
instanceof TMouseEvent
) {
808 // See if we need to switch focus to another window or the menu
809 checkSwitchFocus((TMouseEvent
) event
);
812 // Handle menu events
813 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
814 TMenu menu
= activeMenu
;
816 if (event
instanceof TMouseEvent
) {
817 TMouseEvent mouse
= (TMouseEvent
) event
;
819 while (subMenus
.size() > 0) {
820 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
821 if (subMenu
.mouseWouldHit(mouse
)) {
824 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
825 && (!mouse
.getMouse1())
826 && (!mouse
.getMouse2())
827 && (!mouse
.getMouse3())
828 && (!mouse
.getMouseWheelUp())
829 && (!mouse
.getMouseWheelDown())
833 // We navigated away from a sub-menu, so close it
837 // Convert the mouse relative x/y to menu coordinates
838 assert (mouse
.getX() == mouse
.getAbsoluteX());
839 assert (mouse
.getY() == mouse
.getAbsoluteY());
840 if (subMenus
.size() > 0) {
841 menu
= subMenus
.get(subMenus
.size() - 1);
843 mouse
.setX(mouse
.getX() - menu
.getX());
844 mouse
.setY(mouse
.getY() - menu
.getY());
846 menu
.handleEvent(event
);
850 if (event
instanceof TKeypressEvent
) {
851 TKeypressEvent keypress
= (TKeypressEvent
) event
;
853 // See if this key matches an accelerator, and if so dispatch the
855 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
856 TMenuItem item
= null;
857 synchronized (accelerators
) {
858 item
= accelerators
.get(keypressLowercase
);
861 // Let the menu item dispatch
865 // Handle the keypress
866 if (onKeypress(keypress
)) {
872 if (event
instanceof TCommandEvent
) {
873 if (onCommand((TCommandEvent
) event
)) {
878 if (event
instanceof TMenuEvent
) {
879 if (onMenu((TMenuEvent
) event
)) {
884 // Dispatch events to the active window -------------------------------
885 for (TWindow window
: windows
) {
886 if (window
.getActive()) {
887 if (event
instanceof TMouseEvent
) {
888 TMouseEvent mouse
= (TMouseEvent
) event
;
889 // Convert the mouse relative x/y to window coordinates
890 assert (mouse
.getX() == mouse
.getAbsoluteX());
891 assert (mouse
.getY() == mouse
.getAbsoluteY());
892 mouse
.setX(mouse
.getX() - window
.getX());
893 mouse
.setY(mouse
.getY() - window
.getY());
896 System
.err
.printf("TApplication dispatch event: %s\n",
899 window
.handleEvent(event
);
905 * Dispatch one event to the appropriate widget or application-level
906 * event handler. This is the secondary event handler used by certain
907 * special dialogs (currently TMessageBox and TFileOpenBox).
909 * @param event the input event to consume
910 * @see #primaryHandleEvent(TInputEvent event)
912 private void secondaryHandleEvent(final TInputEvent event
) {
913 secondaryEventReceiver
.handleEvent(event
);
917 * Enable a widget to override the primary event thread.
919 * @param widget widget that will receive events
921 public final void enableSecondaryEventReceiver(final TWidget widget
) {
922 assert (secondaryEventReceiver
== null);
923 assert (secondaryEventHandler
== null);
924 assert (widget
instanceof TMessageBox
);
925 secondaryEventReceiver
= widget
;
926 secondaryEventHandler
= new WidgetEventHandler(this, false);
927 (new Thread(secondaryEventHandler
)).start();
934 * Yield to the secondary thread.
936 public final void yield() {
937 assert (secondaryEventReceiver
!= null);
938 // This is where we handoff the event handler lock from the primary
939 // to secondary thread. We unlock here, and in a future loop the
940 // secondary thread locks again. When it gives up, we have the
942 boolean oldLock
= unlockHandleEvent();
943 assert (oldLock
== true);
945 // System.err.printf("YIELD\n");
947 while (secondaryEventReceiver
!= null) {
948 synchronized (primaryEventHandler
) {
950 primaryEventHandler
.wait();
951 } catch (InterruptedException e
) {
957 // System.err.printf("EXIT YIELD\n");
961 * Do stuff when there is no user input.
963 private void doIdle() {
965 System
.err
.printf("doIdle()\n");
968 // Now run any timers that have timed out
969 Date now
= new Date();
970 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
971 for (TTimer timer
: timers
) {
972 if (timer
.getNextTick().getTime() <= now
.getTime()) {
974 if (timer
.recurring
) {
975 keepTimers
.add(timer
);
978 keepTimers
.add(timer
);
984 for (TWindow window
: windows
) {
990 * Get the amount of time I can sleep before missing a Timer tick.
992 * @param timeout = initial (maximum) timeout in millis
993 * @return number of milliseconds between now and the next timer event
995 protected long getSleepTime(final long timeout
) {
996 Date now
= new Date();
997 long nowTime
= now
.getTime();
998 long sleepTime
= timeout
;
999 for (TTimer timer
: timers
) {
1000 long nextTickTime
= timer
.getNextTick().getTime();
1001 if (nextTickTime
< nowTime
) {
1005 long timeDifference
= nextTickTime
- nowTime
;
1006 if (timeDifference
< sleepTime
) {
1007 sleepTime
= timeDifference
;
1010 assert (sleepTime
>= 0);
1011 assert (sleepTime
<= timeout
);
1016 * Close window. Note that the window's destructor is NOT called by this
1017 * method, instead the GC is assumed to do the cleanup.
1019 * @param window the window to remove
1021 public final void closeWindow(final TWindow window
) {
1022 int z
= window
.getZ();
1024 Collections
.sort(windows
);
1026 TWindow activeWindow
= null;
1027 for (TWindow w
: windows
) {
1029 w
.setZ(w
.getZ() - 1);
1030 if (w
.getZ() == 0) {
1032 assert (activeWindow
== null);
1040 // Perform window cleanup
1046 // Check if we are closing a TMessageBox or similar
1047 if (secondaryEventReceiver
!= null) {
1048 assert (secondaryEventHandler
!= null);
1050 // Do not send events to the secondaryEventReceiver anymore, the
1051 // window is closed.
1052 secondaryEventReceiver
= null;
1054 // Wake the secondary thread, it will wake the primary as it
1056 synchronized (secondaryEventHandler
) {
1057 secondaryEventHandler
.notify();
1063 * Switch to the next window.
1065 * @param forward if true, then switch to the next window in the list,
1066 * otherwise switch to the previous window in the list
1068 public final void switchWindow(final boolean forward
) {
1069 // Only switch if there are multiple windows
1070 if (windows
.size() < 2) {
1074 // Swap z/active between active window and the next in the list
1075 int activeWindowI
= -1;
1076 for (int i
= 0; i
< windows
.size(); i
++) {
1077 if (windows
.get(i
).getActive()) {
1082 assert (activeWindowI
>= 0);
1084 // Do not switch if a window is modal
1085 if (windows
.get(activeWindowI
).isModal()) {
1091 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1093 if (activeWindowI
== 0) {
1094 nextWindowI
= windows
.size() - 1;
1096 nextWindowI
= activeWindowI
- 1;
1099 windows
.get(activeWindowI
).setActive(false);
1100 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1101 windows
.get(nextWindowI
).setZ(0);
1102 windows
.get(nextWindowI
).setActive(true);
1109 * Add a window to my window list and make it active.
1111 * @param window new window to add
1113 public final void addWindow(final TWindow window
) {
1114 // Do not allow a modal window to spawn a non-modal window
1115 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1116 assert (window
.isModal());
1118 for (TWindow w
: windows
) {
1120 w
.setZ(w
.getZ() + 1);
1122 windows
.add(window
);
1123 window
.setActive(true);
1128 * Check if there is a system-modal window on top.
1130 * @return true if the active window is modal
1132 private boolean modalWindowActive() {
1133 if (windows
.size() == 0) {
1136 return windows
.get(windows
.size() - 1).isModal();
1140 * Check if a mouse event would hit either the active menu or any open
1143 * @param mouse mouse event
1144 * @return true if the mouse would hit the active menu or an open
1147 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1148 assert (activeMenu
!= null);
1149 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1150 Collections
.reverse(menus
);
1151 for (TMenu menu
: menus
) {
1152 if (menu
.mouseWouldHit(mouse
)) {
1156 return activeMenu
.mouseWouldHit(mouse
);
1160 * See if we need to switch window or activate the menu based on
1163 * @param mouse mouse event
1165 private void checkSwitchFocus(final TMouseEvent mouse
) {
1167 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1168 && (activeMenu
!= null)
1169 && (mouse
.getAbsoluteY() != 0)
1170 && (!mouseOnMenu(mouse
))
1172 // They clicked outside the active menu, turn it off
1173 activeMenu
.setActive(false);
1175 for (TMenu menu
: subMenus
) {
1176 menu
.setActive(false);
1182 // See if they hit the menu bar
1183 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1184 && (mouse
.getMouse1())
1185 && (!modalWindowActive())
1186 && (mouse
.getAbsoluteY() == 0)
1189 for (TMenu menu
: subMenus
) {
1190 menu
.setActive(false);
1194 // They selected the menu, go activate it
1195 for (TMenu menu
: menus
) {
1196 if ((mouse
.getAbsoluteX() >= menu
.getX())
1197 && (mouse
.getAbsoluteX() < menu
.getX()
1198 + menu
.getTitle().length() + 2)
1200 menu
.setActive(true);
1203 menu
.setActive(false);
1210 // See if they hit the menu bar
1211 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1212 && (mouse
.getMouse1())
1213 && (activeMenu
!= null)
1214 && (mouse
.getAbsoluteY() == 0)
1217 TMenu oldMenu
= activeMenu
;
1218 for (TMenu menu
: subMenus
) {
1219 menu
.setActive(false);
1223 // See if we should switch menus
1224 for (TMenu menu
: menus
) {
1225 if ((mouse
.getAbsoluteX() >= menu
.getX())
1226 && (mouse
.getAbsoluteX() < menu
.getX()
1227 + menu
.getTitle().length() + 2)
1229 menu
.setActive(true);
1233 if (oldMenu
!= activeMenu
) {
1234 // They switched menus
1235 oldMenu
.setActive(false);
1241 // Only switch if there are multiple windows
1242 if (windows
.size() < 2) {
1246 // Switch on the upclick
1247 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1251 Collections
.sort(windows
);
1252 if (windows
.get(0).isModal()) {
1253 // Modal windows don't switch
1257 for (TWindow window
: windows
) {
1258 assert (!window
.isModal());
1259 if (window
.mouseWouldHit(mouse
)) {
1260 if (window
== windows
.get(0)) {
1261 // Clicked on the same window, nothing to do
1265 // We will be switching to another window
1266 assert (windows
.get(0).getActive());
1267 assert (!window
.getActive());
1268 windows
.get(0).setActive(false);
1269 windows
.get(0).setZ(window
.getZ());
1271 window
.setActive(true);
1277 // Clicked on the background, nothing to do
1282 * Turn off the menu.
1284 public final void closeMenu() {
1285 if (activeMenu
!= null) {
1286 activeMenu
.setActive(false);
1288 for (TMenu menu
: subMenus
) {
1289 menu
.setActive(false);
1297 * Turn off a sub-menu.
1299 public final void closeSubMenu() {
1300 assert (activeMenu
!= null);
1301 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1302 assert (item
!= null);
1303 item
.setActive(false);
1304 subMenus
.remove(subMenus
.size() - 1);
1309 * Switch to the next menu.
1311 * @param forward if true, then switch to the next menu in the list,
1312 * otherwise switch to the previous menu in the list
1314 public final void switchMenu(final boolean forward
) {
1315 assert (activeMenu
!= null);
1317 for (TMenu menu
: subMenus
) {
1318 menu
.setActive(false);
1322 for (int i
= 0; i
< menus
.size(); i
++) {
1323 if (activeMenu
== menus
.get(i
)) {
1325 if (i
< menus
.size() - 1) {
1333 activeMenu
.setActive(false);
1334 activeMenu
= menus
.get(i
);
1335 activeMenu
.setActive(true);
1343 * Method that TApplication subclasses can override to handle menu or
1344 * posted command events.
1346 * @param command command event
1347 * @return if true, this event was consumed
1349 protected boolean onCommand(final TCommandEvent command
) {
1350 // Default: handle cmExit
1351 if (command
.equals(cmExit
)) {
1352 if (messageBox("Confirmation", "Exit application?",
1353 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1360 if (command
.equals(cmShell
)) {
1361 openTerminal(0, 0, TWindow
.RESIZABLE
);
1366 if (command
.equals(cmTile
)) {
1371 if (command
.equals(cmCascade
)) {
1376 if (command
.equals(cmCloseAll
)) {
1386 * Method that TApplication subclasses can override to handle menu
1389 * @param menu menu event
1390 * @return if true, this event was consumed
1392 protected boolean onMenu(final TMenuEvent menu
) {
1394 // Default: handle MID_EXIT
1395 if (menu
.getId() == TMenu
.MID_EXIT
) {
1396 if (messageBox("Confirmation", "Exit application?",
1397 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1400 // System.err.printf("onMenu MID_EXIT result: quit = %s\n", quit);
1405 if (menu
.getId() == TMenu
.MID_SHELL
) {
1406 openTerminal(0, 0, TWindow
.RESIZABLE
);
1411 if (menu
.getId() == TMenu
.MID_TILE
) {
1416 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1421 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1430 * Method that TApplication subclasses can override to handle keystrokes.
1432 * @param keypress keystroke event
1433 * @return if true, this event was consumed
1435 protected boolean onKeypress(final TKeypressEvent keypress
) {
1436 // Default: only menu shortcuts
1438 // Process Alt-F, Alt-E, etc. menu shortcut keys
1439 if (!keypress
.getKey().getIsKey()
1440 && keypress
.getKey().getAlt()
1441 && !keypress
.getKey().getCtrl()
1442 && (activeMenu
== null)
1445 assert (subMenus
.size() == 0);
1447 for (TMenu menu
: menus
) {
1448 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1449 == Character
.toLowerCase(keypress
.getKey().getCh())
1452 menu
.setActive(true);
1463 * Add a keyboard accelerator to the global hash.
1465 * @param item menu item this accelerator relates to
1466 * @param keypress keypress that will dispatch a TMenuEvent
1468 public final void addAccelerator(final TMenuItem item
,
1469 final TKeypress keypress
) {
1471 // System.err.printf("addAccelerator: key %s item %s\n", keypress, item);
1473 synchronized (accelerators
) {
1474 assert (accelerators
.get(keypress
) == null);
1475 accelerators
.put(keypress
, item
);
1480 * Recompute menu x positions based on their title length.
1482 public final void recomputeMenuX() {
1484 for (TMenu menu
: menus
) {
1486 x
+= menu
.getTitle().length() + 2;
1491 * Post an event to process and turn off the menu.
1493 * @param event new event to add to the queue
1495 public final void addMenuEvent(final TInputEvent event
) {
1496 synchronized (fillEventQueue
) {
1497 fillEventQueue
.add(event
);
1503 * Add a sub-menu to the list of open sub-menus.
1505 * @param menu sub-menu
1507 public final void addSubMenu(final TMenu menu
) {
1512 * Convenience function to add a top-level menu.
1514 * @param title menu title
1515 * @return the new menu
1517 public final TMenu
addMenu(final String title
) {
1520 TMenu menu
= new TMenu(this, x
, y
, title
);
1527 * Convenience function to add a default "File" menu.
1529 * @return the new menu
1531 public final TMenu
addFileMenu() {
1532 TMenu fileMenu
= addMenu("&File");
1533 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1534 fileMenu
.addSeparator();
1535 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1536 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1541 * Convenience function to add a default "Edit" menu.
1543 * @return the new menu
1545 public final TMenu
addEditMenu() {
1546 TMenu editMenu
= addMenu("&Edit");
1547 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1548 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1549 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1550 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1555 * Convenience function to add a default "Window" menu.
1557 * @return the new menu
1559 public final TMenu
addWindowMenu() {
1560 TMenu windowMenu
= addMenu("&Window");
1561 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1562 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1563 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1564 windowMenu
.addSeparator();
1565 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1566 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1567 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1568 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1569 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1574 * Close all open windows.
1576 private void closeAllWindows() {
1577 // Don't do anything if we are in the menu
1578 if (activeMenu
!= null) {
1581 for (TWindow window
: windows
) {
1582 closeWindow(window
);
1587 * Re-layout the open windows as non-overlapping tiles. This produces
1588 * almost the same results as Turbo Pascal 7.0's IDE.
1590 private void tileWindows() {
1591 // Don't do anything if we are in the menu
1592 if (activeMenu
!= null) {
1595 int z
= windows
.size();
1601 a
= (int)(Math
.sqrt(z
));
1605 if (((a
* b
) + c
) == z
) {
1613 int newWidth
= (getScreen().getWidth() / a
);
1614 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1615 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1617 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1618 Collections
.sort(sorted
);
1619 Collections
.reverse(sorted
);
1620 for (int i
= 0; i
< sorted
.size(); i
++) {
1621 int logicalX
= i
/ b
;
1622 int logicalY
= i
% b
;
1623 if (i
>= ((a
- 1) * b
)) {
1625 logicalY
= i
- ((a
- 1) * b
);
1628 TWindow w
= sorted
.get(i
);
1629 w
.setX(logicalX
* newWidth
);
1630 w
.setWidth(newWidth
);
1631 if (i
>= ((a
- 1) * b
)) {
1632 w
.setY((logicalY
* newHeight2
) + 1);
1633 w
.setHeight(newHeight2
);
1635 w
.setY((logicalY
* newHeight1
) + 1);
1636 w
.setHeight(newHeight1
);
1642 * Re-layout the open windows as overlapping cascaded windows.
1644 private void cascadeWindows() {
1645 // Don't do anything if we are in the menu
1646 if (activeMenu
!= null) {
1651 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1652 Collections
.sort(sorted
);
1653 Collections
.reverse(sorted
);
1654 for (TWindow window
: sorted
) {
1659 if (x
> getScreen().getWidth()) {
1662 if (y
>= getScreen().getHeight()) {
1669 * Convenience function to add a timer.
1671 * @param duration number of milliseconds to wait between ticks
1672 * @param recurring if true, re-schedule this timer after every tick
1673 * @param action function to call when button is pressed
1676 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1677 final TAction action
) {
1679 TTimer timer
= new TTimer(duration
, recurring
, action
);
1680 synchronized (timers
) {
1687 * Convenience function to remove a timer.
1689 * @param timer timer to remove
1691 public final void removeTimer(final TTimer timer
) {
1692 synchronized (timers
) {
1693 timers
.remove(timer
);
1698 * Convenience function to spawn a message box.
1700 * @param title window title, will be centered along the top border
1701 * @param caption message to display. Use embedded newlines to get a
1703 * @return the new message box
1705 public final TMessageBox
messageBox(final String title
,
1706 final String caption
) {
1708 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1712 * Convenience function to spawn a message box.
1714 * @param title window title, will be centered along the top border
1715 * @param caption message to display. Use embedded newlines to get a
1717 * @param type one of the TMessageBox.Type constants. Default is
1719 * @return the new message box
1721 public final TMessageBox
messageBox(final String title
,
1722 final String caption
, final TMessageBox
.Type type
) {
1724 return new TMessageBox(this, title
, caption
, type
);
1728 * Convenience function to spawn an input box.
1730 * @param title window title, will be centered along the top border
1731 * @param caption message to display. Use embedded newlines to get a
1733 * @return the new input box
1735 public final TInputBox
inputBox(final String title
, final String caption
) {
1737 return new TInputBox(this, title
, caption
);
1741 * Convenience function to spawn an input box.
1743 * @param title window title, will be centered along the top border
1744 * @param caption message to display. Use embedded newlines to get a
1746 * @param text initial text to seed the field with
1747 * @return the new input box
1749 public final TInputBox
inputBox(final String title
, final String caption
,
1750 final String text
) {
1752 return new TInputBox(this, title
, caption
, text
);
1756 * Convenience function to open a terminal window.
1758 * @param x column relative to parent
1759 * @param y row relative to parent
1760 * @return the terminal new window
1762 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1763 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1767 * Convenience function to open a terminal window.
1769 * @param x column relative to parent
1770 * @param y row relative to parent
1771 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1772 * @return the terminal new window
1774 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1777 return new TTerminalWindow(this, x
, y
, flags
);