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 synchronized (windows
) {
1023 int z
= window
.getZ();
1025 Collections
.sort(windows
);
1027 TWindow activeWindow
= null;
1028 for (TWindow w
: windows
) {
1030 w
.setZ(w
.getZ() - 1);
1031 if (w
.getZ() == 0) {
1033 assert (activeWindow
== null);
1042 // Perform window cleanup
1048 // Check if we are closing a TMessageBox or similar
1049 if (secondaryEventReceiver
!= null) {
1050 assert (secondaryEventHandler
!= null);
1052 // Do not send events to the secondaryEventReceiver anymore, the
1053 // window is closed.
1054 secondaryEventReceiver
= null;
1056 // Wake the secondary thread, it will wake the primary as it
1058 synchronized (secondaryEventHandler
) {
1059 secondaryEventHandler
.notify();
1065 * Switch to the next window.
1067 * @param forward if true, then switch to the next window in the list,
1068 * otherwise switch to the previous window in the list
1070 public final void switchWindow(final boolean forward
) {
1071 // Only switch if there are multiple windows
1072 if (windows
.size() < 2) {
1076 synchronized (windows
) {
1078 // Swap z/active between active window and the next in the list
1079 int activeWindowI
= -1;
1080 for (int i
= 0; i
< windows
.size(); i
++) {
1081 if (windows
.get(i
).getActive()) {
1086 assert (activeWindowI
>= 0);
1088 // Do not switch if a window is modal
1089 if (windows
.get(activeWindowI
).isModal()) {
1095 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1097 if (activeWindowI
== 0) {
1098 nextWindowI
= windows
.size() - 1;
1100 nextWindowI
= activeWindowI
- 1;
1103 windows
.get(activeWindowI
).setActive(false);
1104 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1105 windows
.get(nextWindowI
).setZ(0);
1106 windows
.get(nextWindowI
).setActive(true);
1108 } // synchronized (windows)
1115 * Add a window to my window list and make it active.
1117 * @param window new window to add
1119 public final void addWindow(final TWindow window
) {
1120 synchronized (windows
) {
1121 // Do not allow a modal window to spawn a non-modal window
1122 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1123 assert (window
.isModal());
1125 for (TWindow w
: windows
) {
1127 w
.setZ(w
.getZ() + 1);
1129 windows
.add(window
);
1130 window
.setActive(true);
1136 * Check if there is a system-modal window on top.
1138 * @return true if the active window is modal
1140 private boolean modalWindowActive() {
1141 if (windows
.size() == 0) {
1144 return windows
.get(windows
.size() - 1).isModal();
1148 * Check if a mouse event would hit either the active menu or any open
1151 * @param mouse mouse event
1152 * @return true if the mouse would hit the active menu or an open
1155 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1156 assert (activeMenu
!= null);
1157 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1158 Collections
.reverse(menus
);
1159 for (TMenu menu
: menus
) {
1160 if (menu
.mouseWouldHit(mouse
)) {
1164 return activeMenu
.mouseWouldHit(mouse
);
1168 * See if we need to switch window or activate the menu based on
1171 * @param mouse mouse event
1173 private void checkSwitchFocus(final TMouseEvent mouse
) {
1175 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1176 && (activeMenu
!= null)
1177 && (mouse
.getAbsoluteY() != 0)
1178 && (!mouseOnMenu(mouse
))
1180 // They clicked outside the active menu, turn it off
1181 activeMenu
.setActive(false);
1183 for (TMenu menu
: subMenus
) {
1184 menu
.setActive(false);
1190 // See if they hit the menu bar
1191 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1192 && (mouse
.getMouse1())
1193 && (!modalWindowActive())
1194 && (mouse
.getAbsoluteY() == 0)
1197 for (TMenu menu
: subMenus
) {
1198 menu
.setActive(false);
1202 // They selected the menu, go activate it
1203 for (TMenu menu
: menus
) {
1204 if ((mouse
.getAbsoluteX() >= menu
.getX())
1205 && (mouse
.getAbsoluteX() < menu
.getX()
1206 + menu
.getTitle().length() + 2)
1208 menu
.setActive(true);
1211 menu
.setActive(false);
1218 // See if they hit the menu bar
1219 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1220 && (mouse
.getMouse1())
1221 && (activeMenu
!= null)
1222 && (mouse
.getAbsoluteY() == 0)
1225 TMenu oldMenu
= activeMenu
;
1226 for (TMenu menu
: subMenus
) {
1227 menu
.setActive(false);
1231 // See if we should switch menus
1232 for (TMenu menu
: menus
) {
1233 if ((mouse
.getAbsoluteX() >= menu
.getX())
1234 && (mouse
.getAbsoluteX() < menu
.getX()
1235 + menu
.getTitle().length() + 2)
1237 menu
.setActive(true);
1241 if (oldMenu
!= activeMenu
) {
1242 // They switched menus
1243 oldMenu
.setActive(false);
1249 // Only switch if there are multiple windows
1250 if (windows
.size() < 2) {
1254 // Switch on the upclick
1255 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1259 synchronized (windows
) {
1260 Collections
.sort(windows
);
1261 if (windows
.get(0).isModal()) {
1262 // Modal windows don't switch
1266 for (TWindow window
: windows
) {
1267 assert (!window
.isModal());
1268 if (window
.mouseWouldHit(mouse
)) {
1269 if (window
== windows
.get(0)) {
1270 // Clicked on the same window, nothing to do
1274 // We will be switching to another window
1275 assert (windows
.get(0).getActive());
1276 assert (!window
.getActive());
1277 windows
.get(0).setActive(false);
1278 windows
.get(0).setZ(window
.getZ());
1280 window
.setActive(true);
1287 // Clicked on the background, nothing to do
1292 * Turn off the menu.
1294 public final void closeMenu() {
1295 if (activeMenu
!= null) {
1296 activeMenu
.setActive(false);
1298 for (TMenu menu
: subMenus
) {
1299 menu
.setActive(false);
1307 * Turn off a sub-menu.
1309 public final void closeSubMenu() {
1310 assert (activeMenu
!= null);
1311 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1312 assert (item
!= null);
1313 item
.setActive(false);
1314 subMenus
.remove(subMenus
.size() - 1);
1319 * Switch to the next menu.
1321 * @param forward if true, then switch to the next menu in the list,
1322 * otherwise switch to the previous menu in the list
1324 public final void switchMenu(final boolean forward
) {
1325 assert (activeMenu
!= null);
1327 for (TMenu menu
: subMenus
) {
1328 menu
.setActive(false);
1332 for (int i
= 0; i
< menus
.size(); i
++) {
1333 if (activeMenu
== menus
.get(i
)) {
1335 if (i
< menus
.size() - 1) {
1343 activeMenu
.setActive(false);
1344 activeMenu
= menus
.get(i
);
1345 activeMenu
.setActive(true);
1353 * Method that TApplication subclasses can override to handle menu or
1354 * posted command events.
1356 * @param command command event
1357 * @return if true, this event was consumed
1359 protected boolean onCommand(final TCommandEvent command
) {
1360 // Default: handle cmExit
1361 if (command
.equals(cmExit
)) {
1362 if (messageBox("Confirmation", "Exit application?",
1363 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1370 if (command
.equals(cmShell
)) {
1371 openTerminal(0, 0, TWindow
.RESIZABLE
);
1376 if (command
.equals(cmTile
)) {
1381 if (command
.equals(cmCascade
)) {
1386 if (command
.equals(cmCloseAll
)) {
1396 * Method that TApplication subclasses can override to handle menu
1399 * @param menu menu event
1400 * @return if true, this event was consumed
1402 protected boolean onMenu(final TMenuEvent menu
) {
1404 // Default: handle MID_EXIT
1405 if (menu
.getId() == TMenu
.MID_EXIT
) {
1406 if (messageBox("Confirmation", "Exit application?",
1407 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1410 // System.err.printf("onMenu MID_EXIT result: quit = %s\n", quit);
1415 if (menu
.getId() == TMenu
.MID_SHELL
) {
1416 openTerminal(0, 0, TWindow
.RESIZABLE
);
1421 if (menu
.getId() == TMenu
.MID_TILE
) {
1426 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1431 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1440 * Method that TApplication subclasses can override to handle keystrokes.
1442 * @param keypress keystroke event
1443 * @return if true, this event was consumed
1445 protected boolean onKeypress(final TKeypressEvent keypress
) {
1446 // Default: only menu shortcuts
1448 // Process Alt-F, Alt-E, etc. menu shortcut keys
1449 if (!keypress
.getKey().getIsKey()
1450 && keypress
.getKey().getAlt()
1451 && !keypress
.getKey().getCtrl()
1452 && (activeMenu
== null)
1455 assert (subMenus
.size() == 0);
1457 for (TMenu menu
: menus
) {
1458 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1459 == Character
.toLowerCase(keypress
.getKey().getCh())
1462 menu
.setActive(true);
1473 * Add a keyboard accelerator to the global hash.
1475 * @param item menu item this accelerator relates to
1476 * @param keypress keypress that will dispatch a TMenuEvent
1478 public final void addAccelerator(final TMenuItem item
,
1479 final TKeypress keypress
) {
1481 // System.err.printf("addAccelerator: key %s item %s\n", keypress, item);
1483 synchronized (accelerators
) {
1484 assert (accelerators
.get(keypress
) == null);
1485 accelerators
.put(keypress
, item
);
1490 * Recompute menu x positions based on their title length.
1492 public final void recomputeMenuX() {
1494 for (TMenu menu
: menus
) {
1496 x
+= menu
.getTitle().length() + 2;
1501 * Post an event to process and turn off the menu.
1503 * @param event new event to add to the queue
1505 public final void addMenuEvent(final TInputEvent event
) {
1506 synchronized (fillEventQueue
) {
1507 fillEventQueue
.add(event
);
1513 * Add a sub-menu to the list of open sub-menus.
1515 * @param menu sub-menu
1517 public final void addSubMenu(final TMenu menu
) {
1522 * Convenience function to add a top-level menu.
1524 * @param title menu title
1525 * @return the new menu
1527 public final TMenu
addMenu(final String title
) {
1530 TMenu menu
= new TMenu(this, x
, y
, title
);
1537 * Convenience function to add a default "File" menu.
1539 * @return the new menu
1541 public final TMenu
addFileMenu() {
1542 TMenu fileMenu
= addMenu("&File");
1543 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1544 fileMenu
.addSeparator();
1545 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1546 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1551 * Convenience function to add a default "Edit" menu.
1553 * @return the new menu
1555 public final TMenu
addEditMenu() {
1556 TMenu editMenu
= addMenu("&Edit");
1557 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1558 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1559 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1560 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1565 * Convenience function to add a default "Window" menu.
1567 * @return the new menu
1569 public final TMenu
addWindowMenu() {
1570 TMenu windowMenu
= addMenu("&Window");
1571 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1572 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1573 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1574 windowMenu
.addSeparator();
1575 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1576 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1577 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1578 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1579 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1584 * Close all open windows.
1586 private void closeAllWindows() {
1587 // Don't do anything if we are in the menu
1588 if (activeMenu
!= null) {
1592 synchronized (windows
) {
1593 for (TWindow window
: windows
) {
1594 closeWindow(window
);
1600 * Re-layout the open windows as non-overlapping tiles. This produces
1601 * almost the same results as Turbo Pascal 7.0's IDE.
1603 private void tileWindows() {
1604 synchronized (windows
) {
1605 // Don't do anything if we are in the menu
1606 if (activeMenu
!= null) {
1609 int z
= windows
.size();
1615 a
= (int)(Math
.sqrt(z
));
1619 if (((a
* b
) + c
) == z
) {
1627 int newWidth
= (getScreen().getWidth() / a
);
1628 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1629 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1631 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1632 Collections
.sort(sorted
);
1633 Collections
.reverse(sorted
);
1634 for (int i
= 0; i
< sorted
.size(); i
++) {
1635 int logicalX
= i
/ b
;
1636 int logicalY
= i
% b
;
1637 if (i
>= ((a
- 1) * b
)) {
1639 logicalY
= i
- ((a
- 1) * b
);
1642 TWindow w
= sorted
.get(i
);
1643 w
.setX(logicalX
* newWidth
);
1644 w
.setWidth(newWidth
);
1645 if (i
>= ((a
- 1) * b
)) {
1646 w
.setY((logicalY
* newHeight2
) + 1);
1647 w
.setHeight(newHeight2
);
1649 w
.setY((logicalY
* newHeight1
) + 1);
1650 w
.setHeight(newHeight1
);
1657 * Re-layout the open windows as overlapping cascaded windows.
1659 private void cascadeWindows() {
1660 synchronized (windows
) {
1661 // Don't do anything if we are in the menu
1662 if (activeMenu
!= null) {
1667 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1668 Collections
.sort(sorted
);
1669 Collections
.reverse(sorted
);
1670 for (TWindow window
: sorted
) {
1675 if (x
> getScreen().getWidth()) {
1678 if (y
>= getScreen().getHeight()) {
1686 * Convenience function to add a timer.
1688 * @param duration number of milliseconds to wait between ticks
1689 * @param recurring if true, re-schedule this timer after every tick
1690 * @param action function to call when button is pressed
1693 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1694 final TAction action
) {
1696 TTimer timer
= new TTimer(duration
, recurring
, action
);
1697 synchronized (timers
) {
1704 * Convenience function to remove a timer.
1706 * @param timer timer to remove
1708 public final void removeTimer(final TTimer timer
) {
1709 synchronized (timers
) {
1710 timers
.remove(timer
);
1715 * Convenience function to spawn a message box.
1717 * @param title window title, will be centered along the top border
1718 * @param caption message to display. Use embedded newlines to get a
1720 * @return the new message box
1722 public final TMessageBox
messageBox(final String title
,
1723 final String caption
) {
1725 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1729 * Convenience function to spawn a message box.
1731 * @param title window title, will be centered along the top border
1732 * @param caption message to display. Use embedded newlines to get a
1734 * @param type one of the TMessageBox.Type constants. Default is
1736 * @return the new message box
1738 public final TMessageBox
messageBox(final String title
,
1739 final String caption
, final TMessageBox
.Type type
) {
1741 return new TMessageBox(this, title
, caption
, type
);
1745 * Convenience function to spawn an input box.
1747 * @param title window title, will be centered along the top border
1748 * @param caption message to display. Use embedded newlines to get a
1750 * @return the new input box
1752 public final TInputBox
inputBox(final String title
, final String caption
) {
1754 return new TInputBox(this, title
, caption
);
1758 * Convenience function to spawn an input box.
1760 * @param title window title, will be centered along the top border
1761 * @param caption message to display. Use embedded newlines to get a
1763 * @param text initial text to seed the field with
1764 * @return the new input box
1766 public final TInputBox
inputBox(final String title
, final String caption
,
1767 final String text
) {
1769 return new TInputBox(this, title
, caption
, text
);
1773 * Convenience function to open a terminal window.
1775 * @param x column relative to parent
1776 * @param y row relative to parent
1777 * @return the terminal new window
1779 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1780 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1784 * Convenience function to open a terminal window.
1786 * @param x column relative to parent
1787 * @param y row relative to parent
1788 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1789 * @return the terminal new window
1791 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1794 return new TTerminalWindow(this, x
, y
, flags
);