2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2016 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
31 import java
.io
.InputStream
;
32 import java
.io
.IOException
;
33 import java
.io
.OutputStream
;
34 import java
.io
.PrintWriter
;
35 import java
.io
.Reader
;
36 import java
.io
.UnsupportedEncodingException
;
37 import java
.util
.Collections
;
38 import java
.util
.Date
;
39 import java
.util
.HashMap
;
40 import java
.util
.ArrayList
;
41 import java
.util
.LinkedList
;
42 import java
.util
.List
;
45 import jexer
.bits
.CellAttributes
;
46 import jexer
.bits
.ColorTheme
;
47 import jexer
.bits
.GraphicsChars
;
48 import jexer
.event
.TCommandEvent
;
49 import jexer
.event
.TInputEvent
;
50 import jexer
.event
.TKeypressEvent
;
51 import jexer
.event
.TMenuEvent
;
52 import jexer
.event
.TMouseEvent
;
53 import jexer
.event
.TResizeEvent
;
54 import jexer
.backend
.Backend
;
55 import jexer
.backend
.SwingBackend
;
56 import jexer
.backend
.ECMA48Backend
;
57 import jexer
.io
.Screen
;
58 import jexer
.menu
.TMenu
;
59 import jexer
.menu
.TMenuItem
;
60 import static jexer
.TCommand
.*;
63 * TApplication sets up a full Text User Interface application.
65 public class TApplication
implements Runnable
{
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 * Two backend types are available.
80 public static enum BackendType
{
87 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
98 * WidgetEventHandler is the main event consumer loop. There are at most
99 * two such threads in existence: the primary for normal case and a
100 * secondary that is used for TMessageBox, TInputBox, and similar.
102 private class WidgetEventHandler
implements Runnable
{
104 * The main application.
106 private TApplication application
;
109 * Whether or not this WidgetEventHandler is the primary or secondary
112 private boolean primary
= true;
115 * Public constructor.
117 * @param application the main application
118 * @param primary if true, this is the primary event handler thread
120 public WidgetEventHandler(final TApplication application
,
121 final boolean primary
) {
123 this.application
= application
;
124 this.primary
= primary
;
133 while (!application
.quit
) {
135 // Wait until application notifies me
136 while (!application
.quit
) {
138 synchronized (application
.drainEventQueue
) {
139 if (application
.drainEventQueue
.size() > 0) {
144 synchronized (this) {
146 System
.err
.printf("%s %s sleep\n", this,
147 primary ?
"primary" : "secondary");
153 System
.err
.printf("%s %s AWAKE\n", this,
154 primary ?
"primary" : "secondary");
158 && (application
.secondaryEventReceiver
== null)
160 // Secondary thread, emergency exit. If we
161 // got here then something went wrong with
162 // the handoff between yield() and
164 synchronized (application
.primaryEventHandler
) {
165 application
.primaryEventHandler
.notify();
167 application
.secondaryEventHandler
= null;
168 throw new RuntimeException(
169 "secondary exited at wrong time");
173 } catch (InterruptedException e
) {
178 // Wait for drawAll() or doIdle() to be done, then handle the
180 boolean oldLock
= lockHandleEvent();
181 assert (oldLock
== false);
183 // Pull all events off the queue
185 TInputEvent event
= null;
186 synchronized (application
.drainEventQueue
) {
187 if (application
.drainEventQueue
.size() == 0) {
190 event
= application
.drainEventQueue
.remove(0);
192 application
.repaint
= true;
194 primaryHandleEvent(event
);
196 secondaryHandleEvent(event
);
199 && (application
.secondaryEventReceiver
== null)
201 // Secondary thread, time to exit.
203 // DO NOT UNLOCK. Primary thread just came back from
204 // primaryHandleEvent() and will unlock in the else
205 // block below. Just wake it up.
206 synchronized (application
.primaryEventHandler
) {
207 application
.primaryEventHandler
.notify();
209 // Now eliminate my reference so that
210 // wakeEventHandler() resumes working on the primary.
211 application
.secondaryEventHandler
= null;
218 // Unlock. Either I am primary thread, or I am secondary
219 // thread and still running.
220 oldLock
= unlockHandleEvent();
221 assert (oldLock
== true);
223 // I have done some work of some kind. Tell the main run()
224 // loop to wake up now.
225 synchronized (application
) {
226 application
.notify();
229 } // while (true) (main runnable loop)
234 * The primary event handler thread.
236 private volatile WidgetEventHandler primaryEventHandler
;
239 * The secondary event handler thread.
241 private volatile WidgetEventHandler secondaryEventHandler
;
244 * The widget receiving events from the secondary event handler thread.
246 private volatile TWidget secondaryEventReceiver
;
249 * Spinlock for the primary and secondary event handlers.
250 * WidgetEventHandler.run() is responsible for setting this value.
252 private volatile boolean insideHandleEvent
= false;
255 * Wake the sleeping active event handler.
257 private void wakeEventHandler() {
258 if (secondaryEventHandler
!= null) {
259 synchronized (secondaryEventHandler
) {
260 secondaryEventHandler
.notify();
263 assert (primaryEventHandler
!= null);
264 synchronized (primaryEventHandler
) {
265 primaryEventHandler
.notify();
271 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
272 * spin indefinitely until unlockHandleEvent() is called.
274 * @return the old value of insideHandleEvent
276 private boolean lockHandleEvent() {
278 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
281 boolean oldValue
= true;
283 synchronized (this) {
284 // Wait for TApplication.run() to finish using the global state
285 // before allowing further event processing.
286 while (lockoutHandleEvent
== true) {
288 // Backoff so that the backend can finish its work.
290 } catch (InterruptedException e
) {
295 oldValue
= insideHandleEvent
;
296 insideHandleEvent
= true;
300 System
.err
.printf(" ***\n");
306 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
307 * spin indefinitely until unlockHandleEvent() is called.
309 * @return the old value of insideHandleEvent
311 private boolean unlockHandleEvent() {
313 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
316 synchronized (this) {
317 boolean oldValue
= insideHandleEvent
;
318 insideHandleEvent
= false;
324 * Spinlock for the primary and secondary event handlers. When true, the
325 * event handlers will spinlock wait before calling handleEvent().
327 private volatile boolean lockoutHandleEvent
= false;
330 * TApplication.run() needs to be able rely on the global data structures
331 * being intact when calling doIdle() and drawAll(). Tell the event
332 * handlers to wait for an unlock before handling their events.
334 private void stopEventHandlers() {
336 System
.err
.printf(">> stopEventHandlers()");
339 lockoutHandleEvent
= true;
340 // Wait for the last event to finish processing before returning
341 // control to TApplication.run().
342 while (insideHandleEvent
== true) {
344 // Backoff so that the event handler can finish its work.
346 } catch (InterruptedException e
) {
352 System
.err
.printf(" XXX\n");
357 * TApplication.run() needs to be able rely on the global data structures
358 * being intact when calling doIdle() and drawAll(). Tell the event
359 * handlers that it is now OK to handle their events.
361 private void startEventHandlers() {
363 System
.err
.printf("<< startEventHandlers()\n");
365 lockoutHandleEvent
= false;
369 * Access to the physical screen, keyboard, and mouse.
371 private Backend backend
;
378 public final Screen
getScreen() {
379 return backend
.getScreen();
383 * Actual mouse coordinate X.
388 * Actual mouse coordinate Y.
393 * Old version of mouse coordinate X.
395 private int oldMouseX
;
398 * Old version mouse coordinate Y.
400 private int oldMouseY
;
403 * Event queue that is filled by run().
405 private List
<TInputEvent
> fillEventQueue
;
408 * Event queue that will be drained by either primary or secondary
411 private List
<TInputEvent
> drainEventQueue
;
414 * Top-level menus in this application.
416 private List
<TMenu
> menus
;
419 * Stack of activated sub-menus in this application.
421 private List
<TMenu
> subMenus
;
424 * The currently acive menu.
426 private TMenu activeMenu
= null;
429 * Active keyboard accelerators.
431 private Map
<TKeypress
, TMenuItem
> accelerators
;
436 private List
<TMenuItem
> menuItems
;
439 * Windows and widgets pull colors from this ColorTheme.
441 private ColorTheme theme
;
444 * Get the color theme.
448 public final ColorTheme
getTheme() {
453 * The top-level windows (but not menus).
455 private List
<TWindow
> windows
;
458 * Timers that are being ticked.
460 private List
<TTimer
> timers
;
463 * When true, exit the application.
465 private volatile boolean quit
= false;
468 * When true, repaint the entire screen.
470 private volatile boolean repaint
= true;
473 * Y coordinate of the top edge of the desktop. For now this is a
474 * constant. Someday it would be nice to have a multi-line menu or
477 private static final int desktopTop
= 1;
480 * Get Y coordinate of the top edge of the desktop.
482 * @return Y coordinate of the top edge of the desktop
484 public final int getDesktopTop() {
489 * Y coordinate of the bottom edge of the desktop.
491 private int desktopBottom
;
494 * Get Y coordinate of the bottom edge of the desktop.
496 * @return Y coordinate of the bottom edge of the desktop
498 public final int getDesktopBottom() {
499 return desktopBottom
;
503 * Public constructor.
505 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
507 * @throws UnsupportedEncodingException if an exception is thrown when
508 * creating the InputStreamReader
510 public TApplication(final BackendType backendType
)
511 throws UnsupportedEncodingException
{
513 switch (backendType
) {
515 backend
= new SwingBackend(this);
520 backend
= new ECMA48Backend(this, null, null);
523 throw new IllegalArgumentException("Invalid backend type: "
530 * Public constructor. The backend type will be BackendType.ECMA48.
532 * @param input an InputStream connected to the remote user, or null for
533 * System.in. If System.in is used, then on non-Windows systems it will
534 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
535 * mode. input is always converted to a Reader with UTF-8 encoding.
536 * @param output an OutputStream connected to the remote user, or null
537 * for System.out. output is always converted to a Writer with UTF-8
539 * @throws UnsupportedEncodingException if an exception is thrown when
540 * creating the InputStreamReader
542 public TApplication(final InputStream input
,
543 final OutputStream output
) throws UnsupportedEncodingException
{
545 backend
= new ECMA48Backend(this, input
, output
);
550 * Public constructor. The backend type will be BackendType.ECMA48.
552 * @param input the InputStream underlying 'reader'. Its available()
553 * method is used to determine if reader.read() will block or not.
554 * @param reader a Reader connected to the remote user.
555 * @param writer a PrintWriter connected to the remote user.
556 * @param setRawMode if true, set System.in into raw mode with stty.
557 * This should in general not be used. It is here solely for Demo3,
558 * which uses System.in.
559 * @throws IllegalArgumentException if input, reader, or writer are null.
561 public TApplication(final InputStream input
, final Reader reader
,
562 final PrintWriter writer
, final boolean setRawMode
) {
564 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
569 * Public constructor. The backend type will be BackendType.ECMA48.
571 * @param input the InputStream underlying 'reader'. Its available()
572 * method is used to determine if reader.read() will block or not.
573 * @param reader a Reader connected to the remote user.
574 * @param writer a PrintWriter connected to the remote user.
575 * @throws IllegalArgumentException if input, reader, or writer are null.
577 public TApplication(final InputStream input
, final Reader reader
,
578 final PrintWriter writer
) {
580 this(input
, reader
, writer
, false);
584 * Public constructor. This hook enables use with new non-Jexer
587 * @param backend a Backend that is already ready to go.
589 public TApplication(final Backend backend
) {
590 this.backend
= backend
;
595 * Finish construction once the backend is set.
597 private void TApplicationImpl() {
598 theme
= new ColorTheme();
599 desktopBottom
= getScreen().getHeight() - 1;
600 fillEventQueue
= new ArrayList
<TInputEvent
>();
601 drainEventQueue
= new ArrayList
<TInputEvent
>();
602 windows
= new LinkedList
<TWindow
>();
603 menus
= new LinkedList
<TMenu
>();
604 subMenus
= new LinkedList
<TMenu
>();
605 timers
= new LinkedList
<TTimer
>();
606 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
607 menuItems
= new ArrayList
<TMenuItem
>();
609 // Setup the main consumer thread
610 primaryEventHandler
= new WidgetEventHandler(this, true);
611 (new Thread(primaryEventHandler
)).start();
615 * Invert the cell color at a position. This is used to track the mouse.
617 * @param x column position
618 * @param y row position
620 private void invertCell(final int x
, final int y
) {
622 System
.err
.printf("invertCell() %d %d\n", x
, y
);
624 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
625 attr
.setForeColor(attr
.getForeColor().invert());
626 attr
.setBackColor(attr
.getBackColor().invert());
627 getScreen().putAttrXY(x
, y
, attr
, false);
633 private void drawAll() {
635 System
.err
.printf("drawAll() enter\n");
640 System
.err
.printf("drawAll() !repaint\n");
642 synchronized (getScreen()) {
643 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
644 // The only thing that has happened is the mouse moved.
645 // Clear the old position and draw the new position.
646 invertCell(oldMouseX
, oldMouseY
);
647 invertCell(mouseX
, mouseY
);
651 if (getScreen().isDirty()) {
652 backend
.flushScreen();
659 System
.err
.printf("drawAll() REDRAW\n");
662 // If true, the cursor is not visible
663 boolean cursor
= false;
665 // Start with a clean screen
668 // Draw the background
669 CellAttributes background
= theme
.getColor("tapplication.background");
670 getScreen().putAll(GraphicsChars
.HATCH
, background
);
672 // Draw each window in reverse Z order
673 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
674 Collections
.sort(sorted
);
675 Collections
.reverse(sorted
);
676 for (TWindow window
: sorted
) {
677 window
.drawChildren();
680 // Draw the blank menubar line - reset the screen clipping first so
681 // it won't trim it out.
682 getScreen().resetClipping();
683 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
684 theme
.getColor("tmenu"));
685 // Now draw the menus.
687 for (TMenu menu
: menus
) {
688 CellAttributes menuColor
;
689 CellAttributes menuMnemonicColor
;
690 if (menu
.isActive()) {
691 menuColor
= theme
.getColor("tmenu.highlighted");
692 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
694 menuColor
= theme
.getColor("tmenu");
695 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
697 // Draw the menu title
698 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
700 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
701 // Draw the highlight character
702 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
703 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
705 if (menu
.isActive()) {
707 // Reset the screen clipping so we can draw the next title.
708 getScreen().resetClipping();
710 x
+= menu
.getTitle().length() + 2;
713 for (TMenu menu
: subMenus
) {
714 // Reset the screen clipping so we can draw the next sub-menu.
715 getScreen().resetClipping();
719 // Draw the mouse pointer
720 invertCell(mouseX
, mouseY
);
724 // Place the cursor if it is visible
725 TWidget activeWidget
= null;
726 if (sorted
.size() > 0) {
727 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
728 if (activeWidget
.isCursorVisible()) {
729 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
730 activeWidget
.getCursorAbsoluteY());
737 getScreen().hideCursor();
740 // Flush the screen contents
741 if (getScreen().isDirty()) {
742 backend
.flushScreen();
749 * Run this application until it exits.
753 // Timeout is in milliseconds, so default timeout after 1 second
757 // If I've got no updates to render, wait for something from the
758 // backend or a timer.
760 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
762 // Never sleep longer than 50 millis. We need time for
763 // windows with background tasks to update the display, and
764 // still flip buffers reasonably quickly in
765 // backend.flushPhysical().
766 timeout
= getSleepTime(50);
770 // As of now, I've got nothing to do: no I/O, nothing from
771 // the consumer threads, no timers that need to run ASAP. So
772 // wait until either the backend or the consumer threads have
776 System
.err
.println("sleep " + timeout
+ " millis");
778 synchronized (this) {
781 } catch (InterruptedException e
) {
782 // I'm awake and don't care why, let's see what's going
788 // Prevent stepping on the primary or secondary event handler.
791 // Pull any pending I/O events
792 backend
.getEvents(fillEventQueue
);
794 // Dispatch each event to the appropriate handler, one at a time.
796 TInputEvent event
= null;
797 if (fillEventQueue
.size() == 0) {
800 event
= fillEventQueue
.remove(0);
801 metaHandleEvent(event
);
804 // Wake a consumer thread if we have any pending events.
805 if (drainEventQueue
.size() > 0) {
809 // Process timers and call doIdle()'s
813 synchronized (getScreen()) {
817 // Let the event handlers run again.
818 startEventHandlers();
822 // Shutdown the event consumer threads
823 if (secondaryEventHandler
!= null) {
824 synchronized (secondaryEventHandler
) {
825 secondaryEventHandler
.notify();
828 if (primaryEventHandler
!= null) {
829 synchronized (primaryEventHandler
) {
830 primaryEventHandler
.notify();
834 // Shutdown the user I/O thread(s)
837 // Close all the windows. This gives them an opportunity to release
844 * Peek at certain application-level events, add to eventQueue, and wake
845 * up the consuming Thread.
847 * @param event the input event to consume
849 private void metaHandleEvent(final TInputEvent event
) {
852 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
853 event
)); System
.err
.flush();
857 // Do no more processing if the application is already trying
862 // Special application-wide events -------------------------------
865 if (event
instanceof TCommandEvent
) {
866 TCommandEvent command
= (TCommandEvent
) event
;
867 if (command
.getCmd().equals(cmAbort
)) {
874 if (event
instanceof TResizeEvent
) {
875 TResizeEvent resize
= (TResizeEvent
) event
;
876 synchronized (getScreen()) {
877 getScreen().setDimensions(resize
.getWidth(),
879 desktopBottom
= getScreen().getHeight() - 1;
888 // Peek at the mouse position
889 if (event
instanceof TMouseEvent
) {
890 TMouseEvent mouse
= (TMouseEvent
) event
;
891 synchronized (getScreen()) {
892 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
895 mouseX
= mouse
.getX();
896 mouseY
= mouse
.getY();
901 // Put into the main queue
902 drainEventQueue
.add(event
);
906 * Dispatch one event to the appropriate widget or application-level
907 * event handler. This is the primary event handler, it has the normal
908 * application-wide event handling.
910 * @param event the input event to consume
911 * @see #secondaryHandleEvent(TInputEvent event)
913 private void primaryHandleEvent(final TInputEvent event
) {
916 System
.err
.printf("Handle event: %s\n", event
);
919 // Special application-wide events -----------------------------------
921 // Peek at the mouse position
922 if (event
instanceof TMouseEvent
) {
923 // See if we need to switch focus to another window or the menu
924 checkSwitchFocus((TMouseEvent
) event
);
927 // Handle menu events
928 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
929 TMenu menu
= activeMenu
;
931 if (event
instanceof TMouseEvent
) {
932 TMouseEvent mouse
= (TMouseEvent
) event
;
934 while (subMenus
.size() > 0) {
935 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
936 if (subMenu
.mouseWouldHit(mouse
)) {
939 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
940 && (!mouse
.isMouse1())
941 && (!mouse
.isMouse2())
942 && (!mouse
.isMouse3())
943 && (!mouse
.isMouseWheelUp())
944 && (!mouse
.isMouseWheelDown())
948 // We navigated away from a sub-menu, so close it
952 // Convert the mouse relative x/y to menu coordinates
953 assert (mouse
.getX() == mouse
.getAbsoluteX());
954 assert (mouse
.getY() == mouse
.getAbsoluteY());
955 if (subMenus
.size() > 0) {
956 menu
= subMenus
.get(subMenus
.size() - 1);
958 mouse
.setX(mouse
.getX() - menu
.getX());
959 mouse
.setY(mouse
.getY() - menu
.getY());
961 menu
.handleEvent(event
);
965 if (event
instanceof TKeypressEvent
) {
966 TKeypressEvent keypress
= (TKeypressEvent
) event
;
968 // See if this key matches an accelerator, and is not being
969 // shortcutted by the active window, and if so dispatch the menu
971 boolean windowWillShortcut
= false;
972 for (TWindow window
: windows
) {
973 if (window
.isActive()) {
974 if (window
.isShortcutKeypress(keypress
.getKey())) {
975 // We do not process this key, it will be passed to
976 // the window instead.
977 windowWillShortcut
= true;
982 if (!windowWillShortcut
) {
983 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
984 TMenuItem item
= null;
985 synchronized (accelerators
) {
986 item
= accelerators
.get(keypressLowercase
);
989 if (item
.isEnabled()) {
990 // Let the menu item dispatch
997 // Handle the keypress
998 if (onKeypress(keypress
)) {
1003 if (event
instanceof TCommandEvent
) {
1004 if (onCommand((TCommandEvent
) event
)) {
1009 if (event
instanceof TMenuEvent
) {
1010 if (onMenu((TMenuEvent
) event
)) {
1015 // Dispatch events to the active window -------------------------------
1016 for (TWindow window
: windows
) {
1017 if (window
.isActive()) {
1018 if (event
instanceof TMouseEvent
) {
1019 TMouseEvent mouse
= (TMouseEvent
) event
;
1020 // Convert the mouse relative x/y to window coordinates
1021 assert (mouse
.getX() == mouse
.getAbsoluteX());
1022 assert (mouse
.getY() == mouse
.getAbsoluteY());
1023 mouse
.setX(mouse
.getX() - window
.getX());
1024 mouse
.setY(mouse
.getY() - window
.getY());
1027 System
.err
.printf("TApplication dispatch event: %s\n",
1030 window
.handleEvent(event
);
1036 * Dispatch one event to the appropriate widget or application-level
1037 * event handler. This is the secondary event handler used by certain
1038 * special dialogs (currently TMessageBox and TFileOpenBox).
1040 * @param event the input event to consume
1041 * @see #primaryHandleEvent(TInputEvent event)
1043 private void secondaryHandleEvent(final TInputEvent event
) {
1044 secondaryEventReceiver
.handleEvent(event
);
1048 * Enable a widget to override the primary event thread.
1050 * @param widget widget that will receive events
1052 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1053 assert (secondaryEventReceiver
== null);
1054 assert (secondaryEventHandler
== null);
1055 assert ((widget
instanceof TMessageBox
)
1056 || (widget
instanceof TFileOpenBox
));
1057 secondaryEventReceiver
= widget
;
1058 secondaryEventHandler
= new WidgetEventHandler(this, false);
1059 (new Thread(secondaryEventHandler
)).start();
1063 * Yield to the secondary thread.
1065 public final void yield() {
1066 assert (secondaryEventReceiver
!= null);
1067 // This is where we handoff the event handler lock from the primary
1068 // to secondary thread. We unlock here, and in a future loop the
1069 // secondary thread locks again. When it gives up, we have the
1070 // single lock back.
1071 boolean oldLock
= unlockHandleEvent();
1074 while (secondaryEventReceiver
!= null) {
1075 synchronized (primaryEventHandler
) {
1077 primaryEventHandler
.wait();
1078 } catch (InterruptedException e
) {
1086 * Do stuff when there is no user input.
1088 private void doIdle() {
1090 System
.err
.printf("doIdle()\n");
1093 // Now run any timers that have timed out
1094 Date now
= new Date();
1095 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1096 for (TTimer timer
: timers
) {
1097 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1099 if (timer
.recurring
) {
1100 keepTimers
.add(timer
);
1103 keepTimers
.add(timer
);
1106 timers
= keepTimers
;
1109 for (TWindow window
: windows
) {
1115 * Get the amount of time I can sleep before missing a Timer tick.
1117 * @param timeout = initial (maximum) timeout in millis
1118 * @return number of milliseconds between now and the next timer event
1120 private long getSleepTime(final long timeout
) {
1121 Date now
= new Date();
1122 long nowTime
= now
.getTime();
1123 long sleepTime
= timeout
;
1124 for (TTimer timer
: timers
) {
1125 long nextTickTime
= timer
.getNextTick().getTime();
1126 if (nextTickTime
< nowTime
) {
1130 long timeDifference
= nextTickTime
- nowTime
;
1131 if (timeDifference
< sleepTime
) {
1132 sleepTime
= timeDifference
;
1135 assert (sleepTime
>= 0);
1136 assert (sleepTime
<= timeout
);
1141 * Close window. Note that the window's destructor is NOT called by this
1142 * method, instead the GC is assumed to do the cleanup.
1144 * @param window the window to remove
1146 public final void closeWindow(final TWindow window
) {
1147 synchronized (windows
) {
1148 int z
= window
.getZ();
1151 Collections
.sort(windows
);
1153 TWindow activeWindow
= null;
1154 for (TWindow w
: windows
) {
1156 w
.setZ(w
.getZ() - 1);
1157 if (w
.getZ() == 0) {
1160 assert (activeWindow
== null);
1172 // Perform window cleanup
1175 // Check if we are closing a TMessageBox or similar
1176 if (secondaryEventReceiver
!= null) {
1177 assert (secondaryEventHandler
!= null);
1179 // Do not send events to the secondaryEventReceiver anymore, the
1180 // window is closed.
1181 secondaryEventReceiver
= null;
1183 // Wake the secondary thread, it will wake the primary as it
1185 synchronized (secondaryEventHandler
) {
1186 secondaryEventHandler
.notify();
1192 * Switch to the next window.
1194 * @param forward if true, then switch to the next window in the list,
1195 * otherwise switch to the previous window in the list
1197 public final void switchWindow(final boolean forward
) {
1198 // Only switch if there are multiple windows
1199 if (windows
.size() < 2) {
1203 synchronized (windows
) {
1205 // Swap z/active between active window and the next in the list
1206 int activeWindowI
= -1;
1207 for (int i
= 0; i
< windows
.size(); i
++) {
1208 if (windows
.get(i
).isActive()) {
1213 assert (activeWindowI
>= 0);
1215 // Do not switch if a window is modal
1216 if (windows
.get(activeWindowI
).isModal()) {
1222 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1224 if (activeWindowI
== 0) {
1225 nextWindowI
= windows
.size() - 1;
1227 nextWindowI
= activeWindowI
- 1;
1230 windows
.get(activeWindowI
).setActive(false);
1231 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1232 windows
.get(activeWindowI
).onUnfocus();
1233 windows
.get(nextWindowI
).setZ(0);
1234 windows
.get(nextWindowI
).setActive(true);
1235 windows
.get(nextWindowI
).onFocus();
1237 } // synchronized (windows)
1242 * Add a window to my window list and make it active.
1244 * @param window new window to add
1246 public final void addWindow(final TWindow window
) {
1247 synchronized (windows
) {
1248 // Do not allow a modal window to spawn a non-modal window
1249 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1250 assert (window
.isModal());
1252 for (TWindow w
: windows
) {
1257 w
.setZ(w
.getZ() + 1);
1259 windows
.add(window
);
1261 window
.setActive(true);
1267 * Check if there is a system-modal window on top.
1269 * @return true if the active window is modal
1271 private boolean modalWindowActive() {
1272 if (windows
.size() == 0) {
1275 return windows
.get(windows
.size() - 1).isModal();
1279 * Check if a mouse event would hit either the active menu or any open
1282 * @param mouse mouse event
1283 * @return true if the mouse would hit the active menu or an open
1286 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1287 assert (activeMenu
!= null);
1288 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1289 Collections
.reverse(menus
);
1290 for (TMenu menu
: menus
) {
1291 if (menu
.mouseWouldHit(mouse
)) {
1295 return activeMenu
.mouseWouldHit(mouse
);
1299 * See if we need to switch window or activate the menu based on
1302 * @param mouse mouse event
1304 private void checkSwitchFocus(final TMouseEvent mouse
) {
1306 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1307 && (activeMenu
!= null)
1308 && (mouse
.getAbsoluteY() != 0)
1309 && (!mouseOnMenu(mouse
))
1311 // They clicked outside the active menu, turn it off
1312 activeMenu
.setActive(false);
1314 for (TMenu menu
: subMenus
) {
1315 menu
.setActive(false);
1321 // See if they hit the menu bar
1322 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1323 && (mouse
.isMouse1())
1324 && (!modalWindowActive())
1325 && (mouse
.getAbsoluteY() == 0)
1328 for (TMenu menu
: subMenus
) {
1329 menu
.setActive(false);
1333 // They selected the menu, go activate it
1334 for (TMenu menu
: menus
) {
1335 if ((mouse
.getAbsoluteX() >= menu
.getX())
1336 && (mouse
.getAbsoluteX() < menu
.getX()
1337 + menu
.getTitle().length() + 2)
1339 menu
.setActive(true);
1342 menu
.setActive(false);
1348 // See if they hit the menu bar
1349 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1350 && (mouse
.isMouse1())
1351 && (activeMenu
!= null)
1352 && (mouse
.getAbsoluteY() == 0)
1355 TMenu oldMenu
= activeMenu
;
1356 for (TMenu menu
: subMenus
) {
1357 menu
.setActive(false);
1361 // See if we should switch menus
1362 for (TMenu menu
: menus
) {
1363 if ((mouse
.getAbsoluteX() >= menu
.getX())
1364 && (mouse
.getAbsoluteX() < menu
.getX()
1365 + menu
.getTitle().length() + 2)
1367 menu
.setActive(true);
1371 if (oldMenu
!= activeMenu
) {
1372 // They switched menus
1373 oldMenu
.setActive(false);
1378 // Only switch if there are multiple windows
1379 if (windows
.size() < 2) {
1383 // Switch on the upclick
1384 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1388 synchronized (windows
) {
1389 Collections
.sort(windows
);
1390 if (windows
.get(0).isModal()) {
1391 // Modal windows don't switch
1395 for (TWindow window
: windows
) {
1396 assert (!window
.isModal());
1397 if (window
.mouseWouldHit(mouse
)) {
1398 if (window
== windows
.get(0)) {
1399 // Clicked on the same window, nothing to do
1403 // We will be switching to another window
1404 assert (windows
.get(0).isActive());
1405 assert (!window
.isActive());
1406 windows
.get(0).onUnfocus();
1407 windows
.get(0).setActive(false);
1408 windows
.get(0).setZ(window
.getZ());
1410 window
.setActive(true);
1417 // Clicked on the background, nothing to do
1422 * Turn off the menu.
1424 public final void closeMenu() {
1425 if (activeMenu
!= null) {
1426 activeMenu
.setActive(false);
1428 for (TMenu menu
: subMenus
) {
1429 menu
.setActive(false);
1436 * Turn off a sub-menu.
1438 public final void closeSubMenu() {
1439 assert (activeMenu
!= null);
1440 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1441 assert (item
!= null);
1442 item
.setActive(false);
1443 subMenus
.remove(subMenus
.size() - 1);
1447 * Switch to the next menu.
1449 * @param forward if true, then switch to the next menu in the list,
1450 * otherwise switch to the previous menu in the list
1452 public final void switchMenu(final boolean forward
) {
1453 assert (activeMenu
!= null);
1455 for (TMenu menu
: subMenus
) {
1456 menu
.setActive(false);
1460 for (int i
= 0; i
< menus
.size(); i
++) {
1461 if (activeMenu
== menus
.get(i
)) {
1463 if (i
< menus
.size() - 1) {
1471 activeMenu
.setActive(false);
1472 activeMenu
= menus
.get(i
);
1473 activeMenu
.setActive(true);
1480 * Method that TApplication subclasses can override to handle menu or
1481 * posted command events.
1483 * @param command command event
1484 * @return if true, this event was consumed
1486 protected boolean onCommand(final TCommandEvent command
) {
1487 // Default: handle cmExit
1488 if (command
.equals(cmExit
)) {
1489 if (messageBox("Confirmation", "Exit application?",
1490 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1496 if (command
.equals(cmShell
)) {
1497 openTerminal(0, 0, TWindow
.RESIZABLE
);
1501 if (command
.equals(cmTile
)) {
1505 if (command
.equals(cmCascade
)) {
1509 if (command
.equals(cmCloseAll
)) {
1518 * Method that TApplication subclasses can override to handle menu
1521 * @param menu menu event
1522 * @return if true, this event was consumed
1524 protected boolean onMenu(final TMenuEvent menu
) {
1526 // Default: handle MID_EXIT
1527 if (menu
.getId() == TMenu
.MID_EXIT
) {
1528 if (messageBox("Confirmation", "Exit application?",
1529 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1535 if (menu
.getId() == TMenu
.MID_SHELL
) {
1536 openTerminal(0, 0, TWindow
.RESIZABLE
);
1540 if (menu
.getId() == TMenu
.MID_TILE
) {
1544 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1548 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1556 * Method that TApplication subclasses can override to handle keystrokes.
1558 * @param keypress keystroke event
1559 * @return if true, this event was consumed
1561 protected boolean onKeypress(final TKeypressEvent keypress
) {
1562 // Default: only menu shortcuts
1564 // Process Alt-F, Alt-E, etc. menu shortcut keys
1565 if (!keypress
.getKey().isFnKey()
1566 && keypress
.getKey().isAlt()
1567 && !keypress
.getKey().isCtrl()
1568 && (activeMenu
== null)
1571 assert (subMenus
.size() == 0);
1573 for (TMenu menu
: menus
) {
1574 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1575 == Character
.toLowerCase(keypress
.getKey().getChar())
1578 menu
.setActive(true);
1588 * Add a menu item to the global list. If it has a keyboard accelerator,
1589 * that will be added the global hash.
1591 * @param item the menu item
1593 public final void addMenuItem(final TMenuItem item
) {
1594 menuItems
.add(item
);
1596 TKeypress key
= item
.getKey();
1598 synchronized (accelerators
) {
1599 assert (accelerators
.get(key
) == null);
1600 accelerators
.put(key
.toLowerCase(), item
);
1606 * Disable one menu item.
1608 * @param id the menu item ID
1610 public final void disableMenuItem(final int id
) {
1611 for (TMenuItem item
: menuItems
) {
1612 if (item
.getId() == id
) {
1613 item
.setEnabled(false);
1619 * Disable the range of menu items with ID's between lower and upper,
1622 * @param lower the lowest menu item ID
1623 * @param upper the highest menu item ID
1625 public final void disableMenuItems(final int lower
, final int upper
) {
1626 for (TMenuItem item
: menuItems
) {
1627 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1628 item
.setEnabled(false);
1634 * Enable one menu item.
1636 * @param id the menu item ID
1638 public final void enableMenuItem(final int id
) {
1639 for (TMenuItem item
: menuItems
) {
1640 if (item
.getId() == id
) {
1641 item
.setEnabled(true);
1647 * Enable the range of menu items with ID's between lower and upper,
1650 * @param lower the lowest menu item ID
1651 * @param upper the highest menu item ID
1653 public final void enableMenuItems(final int lower
, final int upper
) {
1654 for (TMenuItem item
: menuItems
) {
1655 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1656 item
.setEnabled(true);
1662 * Recompute menu x positions based on their title length.
1664 public final void recomputeMenuX() {
1666 for (TMenu menu
: menus
) {
1668 x
+= menu
.getTitle().length() + 2;
1673 * Post an event to process and turn off the menu.
1675 * @param event new event to add to the queue
1677 public final void postMenuEvent(final TInputEvent event
) {
1678 synchronized (fillEventQueue
) {
1679 fillEventQueue
.add(event
);
1685 * Add a sub-menu to the list of open sub-menus.
1687 * @param menu sub-menu
1689 public final void addSubMenu(final TMenu menu
) {
1694 * Convenience function to add a top-level menu.
1696 * @param title menu title
1697 * @return the new menu
1699 public final TMenu
addMenu(final String title
) {
1702 TMenu menu
= new TMenu(this, x
, y
, title
);
1709 * Convenience function to add a default "File" menu.
1711 * @return the new menu
1713 public final TMenu
addFileMenu() {
1714 TMenu fileMenu
= addMenu("&File");
1715 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1716 fileMenu
.addSeparator();
1717 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1718 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1723 * Convenience function to add a default "Edit" menu.
1725 * @return the new menu
1727 public final TMenu
addEditMenu() {
1728 TMenu editMenu
= addMenu("&Edit");
1729 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1730 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1731 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1732 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1737 * Convenience function to add a default "Window" menu.
1739 * @return the new menu
1741 public final TMenu
addWindowMenu() {
1742 TMenu windowMenu
= addMenu("&Window");
1743 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1744 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1745 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1746 windowMenu
.addSeparator();
1747 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1748 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1749 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1750 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1751 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1756 * Close all open windows.
1758 private void closeAllWindows() {
1759 // Don't do anything if we are in the menu
1760 if (activeMenu
!= null) {
1763 while (windows
.size() > 0) {
1764 closeWindow(windows
.get(0));
1769 * Re-layout the open windows as non-overlapping tiles. This produces
1770 * almost the same results as Turbo Pascal 7.0's IDE.
1772 private void tileWindows() {
1773 synchronized (windows
) {
1774 // Don't do anything if we are in the menu
1775 if (activeMenu
!= null) {
1778 int z
= windows
.size();
1784 a
= (int)(Math
.sqrt(z
));
1788 if (((a
* b
) + c
) == z
) {
1796 int newWidth
= (getScreen().getWidth() / a
);
1797 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1798 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1800 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1801 Collections
.sort(sorted
);
1802 Collections
.reverse(sorted
);
1803 for (int i
= 0; i
< sorted
.size(); i
++) {
1804 int logicalX
= i
/ b
;
1805 int logicalY
= i
% b
;
1806 if (i
>= ((a
- 1) * b
)) {
1808 logicalY
= i
- ((a
- 1) * b
);
1811 TWindow w
= sorted
.get(i
);
1812 w
.setX(logicalX
* newWidth
);
1813 w
.setWidth(newWidth
);
1814 if (i
>= ((a
- 1) * b
)) {
1815 w
.setY((logicalY
* newHeight2
) + 1);
1816 w
.setHeight(newHeight2
);
1818 w
.setY((logicalY
* newHeight1
) + 1);
1819 w
.setHeight(newHeight1
);
1826 * Re-layout the open windows as overlapping cascaded windows.
1828 private void cascadeWindows() {
1829 synchronized (windows
) {
1830 // Don't do anything if we are in the menu
1831 if (activeMenu
!= null) {
1836 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1837 Collections
.sort(sorted
);
1838 Collections
.reverse(sorted
);
1839 for (TWindow window
: sorted
) {
1844 if (x
> getScreen().getWidth()) {
1847 if (y
>= getScreen().getHeight()) {
1855 * Convenience function to add a timer.
1857 * @param duration number of milliseconds to wait between ticks
1858 * @param recurring if true, re-schedule this timer after every tick
1859 * @param action function to call when button is pressed
1862 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1863 final TAction action
) {
1865 TTimer timer
= new TTimer(duration
, recurring
, action
);
1866 synchronized (timers
) {
1873 * Convenience function to remove a timer.
1875 * @param timer timer to remove
1877 public final void removeTimer(final TTimer timer
) {
1878 synchronized (timers
) {
1879 timers
.remove(timer
);
1884 * Convenience function to spawn a message box.
1886 * @param title window title, will be centered along the top border
1887 * @param caption message to display. Use embedded newlines to get a
1889 * @return the new message box
1891 public final TMessageBox
messageBox(final String title
,
1892 final String caption
) {
1894 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1898 * Convenience function to spawn a message box.
1900 * @param title window title, will be centered along the top border
1901 * @param caption message to display. Use embedded newlines to get a
1903 * @param type one of the TMessageBox.Type constants. Default is
1905 * @return the new message box
1907 public final TMessageBox
messageBox(final String title
,
1908 final String caption
, final TMessageBox
.Type type
) {
1910 return new TMessageBox(this, title
, caption
, type
);
1914 * Convenience function to spawn an input box.
1916 * @param title window title, will be centered along the top border
1917 * @param caption message to display. Use embedded newlines to get a
1919 * @return the new input box
1921 public final TInputBox
inputBox(final String title
, final String caption
) {
1923 return new TInputBox(this, title
, caption
);
1927 * Convenience function to spawn an input box.
1929 * @param title window title, will be centered along the top border
1930 * @param caption message to display. Use embedded newlines to get a
1932 * @param text initial text to seed the field with
1933 * @return the new input box
1935 public final TInputBox
inputBox(final String title
, final String caption
,
1936 final String text
) {
1938 return new TInputBox(this, title
, caption
, text
);
1942 * Convenience function to open a terminal window.
1944 * @param x column relative to parent
1945 * @param y row relative to parent
1946 * @return the terminal new window
1948 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1949 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1953 * Convenience function to open a terminal window.
1955 * @param x column relative to parent
1956 * @param y row relative to parent
1957 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1958 * @return the terminal new window
1960 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1963 return new TTerminalWindow(this, x
, y
, flags
);
1967 * Convenience function to spawn an file open box.
1969 * @param path path of selected file
1970 * @return the result of the new file open box
1971 * @throws IOException if java.io operation throws
1973 public final String
fileOpenBox(final String path
) throws IOException
{
1975 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
1976 return box
.getFilename();
1980 * Convenience function to spawn an file open box.
1982 * @param path path of selected file
1983 * @param type one of the Type constants
1984 * @return the result of the new file open box
1985 * @throws IOException if java.io operation throws
1987 public final String
fileOpenBox(final String path
,
1988 final TFileOpenBox
.Type type
) throws IOException
{
1990 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
1991 return box
.getFilename();