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
) {
621 synchronized (getScreen()) {
622 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
623 attr
.setForeColor(attr
.getForeColor().invert());
624 attr
.setBackColor(attr
.getBackColor().invert());
625 getScreen().putAttrXY(x
, y
, attr
, false);
632 private void drawAll() {
634 System
.err
.printf("drawAll() enter\n");
638 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
639 // The only thing that has happened is the mouse moved.
640 // Clear the old position and draw the new position.
641 invertCell(oldMouseX
, oldMouseY
);
642 invertCell(mouseX
, mouseY
);
646 if (getScreen().isDirty()) {
647 backend
.flushScreen();
653 System
.err
.printf("drawAll() REDRAW\n");
656 // If true, the cursor is not visible
657 boolean cursor
= false;
659 // Start with a clean screen
662 // Draw the background
663 CellAttributes background
= theme
.getColor("tapplication.background");
664 getScreen().putAll(GraphicsChars
.HATCH
, background
);
666 // Draw each window in reverse Z order
667 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
668 Collections
.sort(sorted
);
669 Collections
.reverse(sorted
);
670 for (TWindow window
: sorted
) {
671 window
.drawChildren();
674 // Draw the blank menubar line - reset the screen clipping first so
675 // it won't trim it out.
676 getScreen().resetClipping();
677 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
678 theme
.getColor("tmenu"));
679 // Now draw the menus.
681 for (TMenu menu
: menus
) {
682 CellAttributes menuColor
;
683 CellAttributes menuMnemonicColor
;
684 if (menu
.isActive()) {
685 menuColor
= theme
.getColor("tmenu.highlighted");
686 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
688 menuColor
= theme
.getColor("tmenu");
689 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
691 // Draw the menu title
692 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
694 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
695 // Draw the highlight character
696 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
697 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
699 if (menu
.isActive()) {
701 // Reset the screen clipping so we can draw the next title.
702 getScreen().resetClipping();
704 x
+= menu
.getTitle().length() + 2;
707 for (TMenu menu
: subMenus
) {
708 // Reset the screen clipping so we can draw the next sub-menu.
709 getScreen().resetClipping();
713 // Draw the mouse pointer
714 invertCell(mouseX
, mouseY
);
716 // Place the cursor if it is visible
717 TWidget activeWidget
= null;
718 if (sorted
.size() > 0) {
719 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
720 if (activeWidget
.isCursorVisible()) {
721 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
722 activeWidget
.getCursorAbsoluteY());
729 getScreen().hideCursor();
732 // Flush the screen contents
733 backend
.flushScreen();
739 * Run this application until it exits.
743 // Timeout is in milliseconds, so default timeout after 1 second
747 // If I've got no updates to render, wait for something from the
748 // backend or a timer.
750 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
752 // Never sleep longer than 50 millis. We need time for
753 // windows with background tasks to update the display, and
754 // still flip buffers reasonably quickly in
755 // backend.flushPhysical().
756 timeout
= getSleepTime(50);
760 // As of now, I've got nothing to do: no I/O, nothing from
761 // the consumer threads, no timers that need to run ASAP. So
762 // wait until either the backend or the consumer threads have
765 synchronized (this) {
768 } catch (InterruptedException e
) {
769 // I'm awake and don't care why, let's see what's going
775 // Prevent stepping on the primary or secondary event handler.
778 // Pull any pending I/O events
779 backend
.getEvents(fillEventQueue
);
781 // Dispatch each event to the appropriate handler, one at a time.
783 TInputEvent event
= null;
784 if (fillEventQueue
.size() == 0) {
787 event
= fillEventQueue
.remove(0);
788 metaHandleEvent(event
);
791 // Wake a consumer thread if we have any pending events.
792 if (drainEventQueue
.size() > 0) {
796 // Process timers and call doIdle()'s
800 synchronized (getScreen()) {
804 // Let the event handlers run again.
805 startEventHandlers();
809 // Shutdown the event consumer threads
810 if (secondaryEventHandler
!= null) {
811 synchronized (secondaryEventHandler
) {
812 secondaryEventHandler
.notify();
815 if (primaryEventHandler
!= null) {
816 synchronized (primaryEventHandler
) {
817 primaryEventHandler
.notify();
821 // Shutdown the user I/O thread(s)
824 // Close all the windows. This gives them an opportunity to release
831 * Peek at certain application-level events, add to eventQueue, and wake
832 * up the consuming Thread.
834 * @param event the input event to consume
836 private void metaHandleEvent(final TInputEvent event
) {
839 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
840 event
)); System
.err
.flush();
844 // Do no more processing if the application is already trying
849 // Special application-wide events -------------------------------
852 if (event
instanceof TCommandEvent
) {
853 TCommandEvent command
= (TCommandEvent
) event
;
854 if (command
.getCmd().equals(cmAbort
)) {
861 if (event
instanceof TResizeEvent
) {
862 TResizeEvent resize
= (TResizeEvent
) event
;
863 synchronized (getScreen()) {
864 getScreen().setDimensions(resize
.getWidth(),
866 desktopBottom
= getScreen().getHeight() - 1;
875 // Peek at the mouse position
876 if (event
instanceof TMouseEvent
) {
877 TMouseEvent mouse
= (TMouseEvent
) event
;
878 synchronized (getScreen()) {
879 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
882 mouseX
= mouse
.getX();
883 mouseY
= mouse
.getY();
888 // Put into the main queue
889 drainEventQueue
.add(event
);
893 * Dispatch one event to the appropriate widget or application-level
894 * event handler. This is the primary event handler, it has the normal
895 * application-wide event handling.
897 * @param event the input event to consume
898 * @see #secondaryHandleEvent(TInputEvent event)
900 private void primaryHandleEvent(final TInputEvent event
) {
903 System
.err
.printf("Handle event: %s\n", event
);
906 // Special application-wide events -----------------------------------
908 // Peek at the mouse position
909 if (event
instanceof TMouseEvent
) {
910 // See if we need to switch focus to another window or the menu
911 checkSwitchFocus((TMouseEvent
) event
);
914 // Handle menu events
915 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
916 TMenu menu
= activeMenu
;
918 if (event
instanceof TMouseEvent
) {
919 TMouseEvent mouse
= (TMouseEvent
) event
;
921 while (subMenus
.size() > 0) {
922 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
923 if (subMenu
.mouseWouldHit(mouse
)) {
926 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
927 && (!mouse
.isMouse1())
928 && (!mouse
.isMouse2())
929 && (!mouse
.isMouse3())
930 && (!mouse
.isMouseWheelUp())
931 && (!mouse
.isMouseWheelDown())
935 // We navigated away from a sub-menu, so close it
939 // Convert the mouse relative x/y to menu coordinates
940 assert (mouse
.getX() == mouse
.getAbsoluteX());
941 assert (mouse
.getY() == mouse
.getAbsoluteY());
942 if (subMenus
.size() > 0) {
943 menu
= subMenus
.get(subMenus
.size() - 1);
945 mouse
.setX(mouse
.getX() - menu
.getX());
946 mouse
.setY(mouse
.getY() - menu
.getY());
948 menu
.handleEvent(event
);
952 if (event
instanceof TKeypressEvent
) {
953 TKeypressEvent keypress
= (TKeypressEvent
) event
;
955 // See if this key matches an accelerator, and if so dispatch the
957 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
958 TMenuItem item
= null;
959 synchronized (accelerators
) {
960 item
= accelerators
.get(keypressLowercase
);
963 if (item
.isEnabled()) {
964 // Let the menu item dispatch
969 // Handle the keypress
970 if (onKeypress(keypress
)) {
975 if (event
instanceof TCommandEvent
) {
976 if (onCommand((TCommandEvent
) event
)) {
981 if (event
instanceof TMenuEvent
) {
982 if (onMenu((TMenuEvent
) event
)) {
987 // Dispatch events to the active window -------------------------------
988 for (TWindow window
: windows
) {
989 if (window
.isActive()) {
990 if (event
instanceof TMouseEvent
) {
991 TMouseEvent mouse
= (TMouseEvent
) event
;
992 // Convert the mouse relative x/y to window coordinates
993 assert (mouse
.getX() == mouse
.getAbsoluteX());
994 assert (mouse
.getY() == mouse
.getAbsoluteY());
995 mouse
.setX(mouse
.getX() - window
.getX());
996 mouse
.setY(mouse
.getY() - window
.getY());
999 System
.err
.printf("TApplication dispatch event: %s\n",
1002 window
.handleEvent(event
);
1008 * Dispatch one event to the appropriate widget or application-level
1009 * event handler. This is the secondary event handler used by certain
1010 * special dialogs (currently TMessageBox and TFileOpenBox).
1012 * @param event the input event to consume
1013 * @see #primaryHandleEvent(TInputEvent event)
1015 private void secondaryHandleEvent(final TInputEvent event
) {
1016 secondaryEventReceiver
.handleEvent(event
);
1020 * Enable a widget to override the primary event thread.
1022 * @param widget widget that will receive events
1024 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1025 assert (secondaryEventReceiver
== null);
1026 assert (secondaryEventHandler
== null);
1027 assert ((widget
instanceof TMessageBox
)
1028 || (widget
instanceof TFileOpenBox
));
1029 secondaryEventReceiver
= widget
;
1030 secondaryEventHandler
= new WidgetEventHandler(this, false);
1031 (new Thread(secondaryEventHandler
)).start();
1035 * Yield to the secondary thread.
1037 public final void yield() {
1038 assert (secondaryEventReceiver
!= null);
1039 // This is where we handoff the event handler lock from the primary
1040 // to secondary thread. We unlock here, and in a future loop the
1041 // secondary thread locks again. When it gives up, we have the
1042 // single lock back.
1043 boolean oldLock
= unlockHandleEvent();
1046 while (secondaryEventReceiver
!= null) {
1047 synchronized (primaryEventHandler
) {
1049 primaryEventHandler
.wait();
1050 } catch (InterruptedException e
) {
1058 * Do stuff when there is no user input.
1060 private void doIdle() {
1062 System
.err
.printf("doIdle()\n");
1065 // Now run any timers that have timed out
1066 Date now
= new Date();
1067 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1068 for (TTimer timer
: timers
) {
1069 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1071 if (timer
.recurring
) {
1072 keepTimers
.add(timer
);
1075 keepTimers
.add(timer
);
1078 timers
= keepTimers
;
1081 for (TWindow window
: windows
) {
1087 * Get the amount of time I can sleep before missing a Timer tick.
1089 * @param timeout = initial (maximum) timeout in millis
1090 * @return number of milliseconds between now and the next timer event
1092 private long getSleepTime(final long timeout
) {
1093 Date now
= new Date();
1094 long nowTime
= now
.getTime();
1095 long sleepTime
= timeout
;
1096 for (TTimer timer
: timers
) {
1097 long nextTickTime
= timer
.getNextTick().getTime();
1098 if (nextTickTime
< nowTime
) {
1102 long timeDifference
= nextTickTime
- nowTime
;
1103 if (timeDifference
< sleepTime
) {
1104 sleepTime
= timeDifference
;
1107 assert (sleepTime
>= 0);
1108 assert (sleepTime
<= timeout
);
1113 * Close window. Note that the window's destructor is NOT called by this
1114 * method, instead the GC is assumed to do the cleanup.
1116 * @param window the window to remove
1118 public final void closeWindow(final TWindow window
) {
1119 synchronized (windows
) {
1120 int z
= window
.getZ();
1123 Collections
.sort(windows
);
1125 TWindow activeWindow
= null;
1126 for (TWindow w
: windows
) {
1128 w
.setZ(w
.getZ() - 1);
1129 if (w
.getZ() == 0) {
1132 assert (activeWindow
== null);
1144 // Perform window cleanup
1147 // Check if we are closing a TMessageBox or similar
1148 if (secondaryEventReceiver
!= null) {
1149 assert (secondaryEventHandler
!= null);
1151 // Do not send events to the secondaryEventReceiver anymore, the
1152 // window is closed.
1153 secondaryEventReceiver
= null;
1155 // Wake the secondary thread, it will wake the primary as it
1157 synchronized (secondaryEventHandler
) {
1158 secondaryEventHandler
.notify();
1164 * Switch to the next window.
1166 * @param forward if true, then switch to the next window in the list,
1167 * otherwise switch to the previous window in the list
1169 public final void switchWindow(final boolean forward
) {
1170 // Only switch if there are multiple windows
1171 if (windows
.size() < 2) {
1175 synchronized (windows
) {
1177 // Swap z/active between active window and the next in the list
1178 int activeWindowI
= -1;
1179 for (int i
= 0; i
< windows
.size(); i
++) {
1180 if (windows
.get(i
).isActive()) {
1185 assert (activeWindowI
>= 0);
1187 // Do not switch if a window is modal
1188 if (windows
.get(activeWindowI
).isModal()) {
1194 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1196 if (activeWindowI
== 0) {
1197 nextWindowI
= windows
.size() - 1;
1199 nextWindowI
= activeWindowI
- 1;
1202 windows
.get(activeWindowI
).setActive(false);
1203 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1204 windows
.get(activeWindowI
).onUnfocus();
1205 windows
.get(nextWindowI
).setZ(0);
1206 windows
.get(nextWindowI
).setActive(true);
1207 windows
.get(nextWindowI
).onFocus();
1209 } // synchronized (windows)
1214 * Add a window to my window list and make it active.
1216 * @param window new window to add
1218 public final void addWindow(final TWindow window
) {
1219 synchronized (windows
) {
1220 // Do not allow a modal window to spawn a non-modal window
1221 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1222 assert (window
.isModal());
1224 for (TWindow w
: windows
) {
1229 w
.setZ(w
.getZ() + 1);
1231 windows
.add(window
);
1233 window
.setActive(true);
1239 * Check if there is a system-modal window on top.
1241 * @return true if the active window is modal
1243 private boolean modalWindowActive() {
1244 if (windows
.size() == 0) {
1247 return windows
.get(windows
.size() - 1).isModal();
1251 * Check if a mouse event would hit either the active menu or any open
1254 * @param mouse mouse event
1255 * @return true if the mouse would hit the active menu or an open
1258 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1259 assert (activeMenu
!= null);
1260 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1261 Collections
.reverse(menus
);
1262 for (TMenu menu
: menus
) {
1263 if (menu
.mouseWouldHit(mouse
)) {
1267 return activeMenu
.mouseWouldHit(mouse
);
1271 * See if we need to switch window or activate the menu based on
1274 * @param mouse mouse event
1276 private void checkSwitchFocus(final TMouseEvent mouse
) {
1278 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1279 && (activeMenu
!= null)
1280 && (mouse
.getAbsoluteY() != 0)
1281 && (!mouseOnMenu(mouse
))
1283 // They clicked outside the active menu, turn it off
1284 activeMenu
.setActive(false);
1286 for (TMenu menu
: subMenus
) {
1287 menu
.setActive(false);
1293 // See if they hit the menu bar
1294 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1295 && (mouse
.isMouse1())
1296 && (!modalWindowActive())
1297 && (mouse
.getAbsoluteY() == 0)
1300 for (TMenu menu
: subMenus
) {
1301 menu
.setActive(false);
1305 // They selected the menu, go activate it
1306 for (TMenu menu
: menus
) {
1307 if ((mouse
.getAbsoluteX() >= menu
.getX())
1308 && (mouse
.getAbsoluteX() < menu
.getX()
1309 + menu
.getTitle().length() + 2)
1311 menu
.setActive(true);
1314 menu
.setActive(false);
1320 // See if they hit the menu bar
1321 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1322 && (mouse
.isMouse1())
1323 && (activeMenu
!= null)
1324 && (mouse
.getAbsoluteY() == 0)
1327 TMenu oldMenu
= activeMenu
;
1328 for (TMenu menu
: subMenus
) {
1329 menu
.setActive(false);
1333 // See if we should switch menus
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);
1343 if (oldMenu
!= activeMenu
) {
1344 // They switched menus
1345 oldMenu
.setActive(false);
1350 // Only switch if there are multiple windows
1351 if (windows
.size() < 2) {
1355 // Switch on the upclick
1356 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1360 synchronized (windows
) {
1361 Collections
.sort(windows
);
1362 if (windows
.get(0).isModal()) {
1363 // Modal windows don't switch
1367 for (TWindow window
: windows
) {
1368 assert (!window
.isModal());
1369 if (window
.mouseWouldHit(mouse
)) {
1370 if (window
== windows
.get(0)) {
1371 // Clicked on the same window, nothing to do
1375 // We will be switching to another window
1376 assert (windows
.get(0).isActive());
1377 assert (!window
.isActive());
1378 windows
.get(0).onUnfocus();
1379 windows
.get(0).setActive(false);
1380 windows
.get(0).setZ(window
.getZ());
1382 window
.setActive(true);
1389 // Clicked on the background, nothing to do
1394 * Turn off the menu.
1396 public final void closeMenu() {
1397 if (activeMenu
!= null) {
1398 activeMenu
.setActive(false);
1400 for (TMenu menu
: subMenus
) {
1401 menu
.setActive(false);
1408 * Turn off a sub-menu.
1410 public final void closeSubMenu() {
1411 assert (activeMenu
!= null);
1412 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1413 assert (item
!= null);
1414 item
.setActive(false);
1415 subMenus
.remove(subMenus
.size() - 1);
1419 * Switch to the next menu.
1421 * @param forward if true, then switch to the next menu in the list,
1422 * otherwise switch to the previous menu in the list
1424 public final void switchMenu(final boolean forward
) {
1425 assert (activeMenu
!= null);
1427 for (TMenu menu
: subMenus
) {
1428 menu
.setActive(false);
1432 for (int i
= 0; i
< menus
.size(); i
++) {
1433 if (activeMenu
== menus
.get(i
)) {
1435 if (i
< menus
.size() - 1) {
1443 activeMenu
.setActive(false);
1444 activeMenu
= menus
.get(i
);
1445 activeMenu
.setActive(true);
1452 * Method that TApplication subclasses can override to handle menu or
1453 * posted command events.
1455 * @param command command event
1456 * @return if true, this event was consumed
1458 protected boolean onCommand(final TCommandEvent command
) {
1459 // Default: handle cmExit
1460 if (command
.equals(cmExit
)) {
1461 if (messageBox("Confirmation", "Exit application?",
1462 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1468 if (command
.equals(cmShell
)) {
1469 openTerminal(0, 0, TWindow
.RESIZABLE
);
1473 if (command
.equals(cmTile
)) {
1477 if (command
.equals(cmCascade
)) {
1481 if (command
.equals(cmCloseAll
)) {
1490 * Method that TApplication subclasses can override to handle menu
1493 * @param menu menu event
1494 * @return if true, this event was consumed
1496 protected boolean onMenu(final TMenuEvent menu
) {
1498 // Default: handle MID_EXIT
1499 if (menu
.getId() == TMenu
.MID_EXIT
) {
1500 if (messageBox("Confirmation", "Exit application?",
1501 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1507 if (menu
.getId() == TMenu
.MID_SHELL
) {
1508 openTerminal(0, 0, TWindow
.RESIZABLE
);
1512 if (menu
.getId() == TMenu
.MID_TILE
) {
1516 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1520 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1528 * Method that TApplication subclasses can override to handle keystrokes.
1530 * @param keypress keystroke event
1531 * @return if true, this event was consumed
1533 protected boolean onKeypress(final TKeypressEvent keypress
) {
1534 // Default: only menu shortcuts
1536 // Process Alt-F, Alt-E, etc. menu shortcut keys
1537 if (!keypress
.getKey().isFnKey()
1538 && keypress
.getKey().isAlt()
1539 && !keypress
.getKey().isCtrl()
1540 && (activeMenu
== null)
1543 assert (subMenus
.size() == 0);
1545 for (TMenu menu
: menus
) {
1546 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1547 == Character
.toLowerCase(keypress
.getKey().getChar())
1550 menu
.setActive(true);
1560 * Add a menu item to the global list. If it has a keyboard accelerator,
1561 * that will be added the global hash.
1563 * @param item the menu item
1565 public final void addMenuItem(final TMenuItem item
) {
1566 menuItems
.add(item
);
1568 TKeypress key
= item
.getKey();
1570 synchronized (accelerators
) {
1571 assert (accelerators
.get(key
) == null);
1572 accelerators
.put(key
.toLowerCase(), item
);
1578 * Disable one menu item.
1580 * @param id the menu item ID
1582 public final void disableMenuItem(final int id
) {
1583 for (TMenuItem item
: menuItems
) {
1584 if (item
.getId() == id
) {
1585 item
.setEnabled(false);
1591 * Disable the range of menu items with ID's between lower and upper,
1594 * @param lower the lowest menu item ID
1595 * @param upper the highest menu item ID
1597 public final void disableMenuItems(final int lower
, final int upper
) {
1598 for (TMenuItem item
: menuItems
) {
1599 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1600 item
.setEnabled(false);
1606 * Enable one menu item.
1608 * @param id the menu item ID
1610 public final void enableMenuItem(final int id
) {
1611 for (TMenuItem item
: menuItems
) {
1612 if (item
.getId() == id
) {
1613 item
.setEnabled(true);
1619 * Enable 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 enableMenuItems(final int lower
, final int upper
) {
1626 for (TMenuItem item
: menuItems
) {
1627 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1628 item
.setEnabled(true);
1634 * Recompute menu x positions based on their title length.
1636 public final void recomputeMenuX() {
1638 for (TMenu menu
: menus
) {
1640 x
+= menu
.getTitle().length() + 2;
1645 * Post an event to process and turn off the menu.
1647 * @param event new event to add to the queue
1649 public final void addMenuEvent(final TInputEvent event
) {
1650 synchronized (fillEventQueue
) {
1651 fillEventQueue
.add(event
);
1657 * Add a sub-menu to the list of open sub-menus.
1659 * @param menu sub-menu
1661 public final void addSubMenu(final TMenu menu
) {
1666 * Convenience function to add a top-level menu.
1668 * @param title menu title
1669 * @return the new menu
1671 public final TMenu
addMenu(final String title
) {
1674 TMenu menu
= new TMenu(this, x
, y
, title
);
1681 * Convenience function to add a default "File" menu.
1683 * @return the new menu
1685 public final TMenu
addFileMenu() {
1686 TMenu fileMenu
= addMenu("&File");
1687 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1688 fileMenu
.addSeparator();
1689 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1690 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1695 * Convenience function to add a default "Edit" menu.
1697 * @return the new menu
1699 public final TMenu
addEditMenu() {
1700 TMenu editMenu
= addMenu("&Edit");
1701 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1702 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1703 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1704 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1709 * Convenience function to add a default "Window" menu.
1711 * @return the new menu
1713 public final TMenu
addWindowMenu() {
1714 TMenu windowMenu
= addMenu("&Window");
1715 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1716 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1717 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1718 windowMenu
.addSeparator();
1719 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1720 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1721 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1722 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1723 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1728 * Close all open windows.
1730 private void closeAllWindows() {
1731 // Don't do anything if we are in the menu
1732 if (activeMenu
!= null) {
1736 synchronized (windows
) {
1737 for (TWindow window
: windows
) {
1738 closeWindow(window
);
1744 * Re-layout the open windows as non-overlapping tiles. This produces
1745 * almost the same results as Turbo Pascal 7.0's IDE.
1747 private void tileWindows() {
1748 synchronized (windows
) {
1749 // Don't do anything if we are in the menu
1750 if (activeMenu
!= null) {
1753 int z
= windows
.size();
1759 a
= (int)(Math
.sqrt(z
));
1763 if (((a
* b
) + c
) == z
) {
1771 int newWidth
= (getScreen().getWidth() / a
);
1772 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1773 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1775 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1776 Collections
.sort(sorted
);
1777 Collections
.reverse(sorted
);
1778 for (int i
= 0; i
< sorted
.size(); i
++) {
1779 int logicalX
= i
/ b
;
1780 int logicalY
= i
% b
;
1781 if (i
>= ((a
- 1) * b
)) {
1783 logicalY
= i
- ((a
- 1) * b
);
1786 TWindow w
= sorted
.get(i
);
1787 w
.setX(logicalX
* newWidth
);
1788 w
.setWidth(newWidth
);
1789 if (i
>= ((a
- 1) * b
)) {
1790 w
.setY((logicalY
* newHeight2
) + 1);
1791 w
.setHeight(newHeight2
);
1793 w
.setY((logicalY
* newHeight1
) + 1);
1794 w
.setHeight(newHeight1
);
1801 * Re-layout the open windows as overlapping cascaded windows.
1803 private void cascadeWindows() {
1804 synchronized (windows
) {
1805 // Don't do anything if we are in the menu
1806 if (activeMenu
!= null) {
1811 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1812 Collections
.sort(sorted
);
1813 Collections
.reverse(sorted
);
1814 for (TWindow window
: sorted
) {
1819 if (x
> getScreen().getWidth()) {
1822 if (y
>= getScreen().getHeight()) {
1830 * Convenience function to add a timer.
1832 * @param duration number of milliseconds to wait between ticks
1833 * @param recurring if true, re-schedule this timer after every tick
1834 * @param action function to call when button is pressed
1837 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1838 final TAction action
) {
1840 TTimer timer
= new TTimer(duration
, recurring
, action
);
1841 synchronized (timers
) {
1848 * Convenience function to remove a timer.
1850 * @param timer timer to remove
1852 public final void removeTimer(final TTimer timer
) {
1853 synchronized (timers
) {
1854 timers
.remove(timer
);
1859 * Convenience function to spawn a message box.
1861 * @param title window title, will be centered along the top border
1862 * @param caption message to display. Use embedded newlines to get a
1864 * @return the new message box
1866 public final TMessageBox
messageBox(final String title
,
1867 final String caption
) {
1869 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1873 * Convenience function to spawn a message box.
1875 * @param title window title, will be centered along the top border
1876 * @param caption message to display. Use embedded newlines to get a
1878 * @param type one of the TMessageBox.Type constants. Default is
1880 * @return the new message box
1882 public final TMessageBox
messageBox(final String title
,
1883 final String caption
, final TMessageBox
.Type type
) {
1885 return new TMessageBox(this, title
, caption
, type
);
1889 * Convenience function to spawn an input box.
1891 * @param title window title, will be centered along the top border
1892 * @param caption message to display. Use embedded newlines to get a
1894 * @return the new input box
1896 public final TInputBox
inputBox(final String title
, final String caption
) {
1898 return new TInputBox(this, title
, caption
);
1902 * Convenience function to spawn an input box.
1904 * @param title window title, will be centered along the top border
1905 * @param caption message to display. Use embedded newlines to get a
1907 * @param text initial text to seed the field with
1908 * @return the new input box
1910 public final TInputBox
inputBox(final String title
, final String caption
,
1911 final String text
) {
1913 return new TInputBox(this, title
, caption
, text
);
1917 * Convenience function to open a terminal window.
1919 * @param x column relative to parent
1920 * @param y row relative to parent
1921 * @return the terminal new window
1923 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1924 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1928 * Convenience function to open a terminal window.
1930 * @param x column relative to parent
1931 * @param y row relative to parent
1932 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1933 * @return the terminal new window
1935 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1938 return new TTerminalWindow(this, x
, y
, flags
);
1942 * Convenience function to spawn an file open box.
1944 * @param path path of selected file
1945 * @return the result of the new file open box
1946 * @throws IOException if java.io operation throws
1948 public final String
fileOpenBox(final String path
) throws IOException
{
1950 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
1951 return box
.getFilename();
1955 * Convenience function to spawn an file open box.
1957 * @param path path of selected file
1958 * @param type one of the Type constants
1959 * @return the result of the new file open box
1960 * @throws IOException if java.io operation throws
1962 public final String
fileOpenBox(final String path
,
1963 final TFileOpenBox
.Type type
) throws IOException
{
1965 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
1966 return box
.getFilename();