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
;
376 * @return the Backend
378 public final Backend
getBackend() {
387 public final Screen
getScreen() {
388 return backend
.getScreen();
392 * Actual mouse coordinate X.
397 * Actual mouse coordinate Y.
402 * Old version of mouse coordinate X.
404 private int oldMouseX
;
407 * Old version mouse coordinate Y.
409 private int oldMouseY
;
412 * Event queue that is filled by run().
414 private List
<TInputEvent
> fillEventQueue
;
417 * Event queue that will be drained by either primary or secondary
420 private List
<TInputEvent
> drainEventQueue
;
423 * Top-level menus in this application.
425 private List
<TMenu
> menus
;
428 * Stack of activated sub-menus in this application.
430 private List
<TMenu
> subMenus
;
433 * The currently acive menu.
435 private TMenu activeMenu
= null;
438 * Active keyboard accelerators.
440 private Map
<TKeypress
, TMenuItem
> accelerators
;
445 private List
<TMenuItem
> menuItems
;
448 * Windows and widgets pull colors from this ColorTheme.
450 private ColorTheme theme
;
453 * Get the color theme.
457 public final ColorTheme
getTheme() {
462 * The top-level windows (but not menus).
464 private List
<TWindow
> windows
;
467 * Timers that are being ticked.
469 private List
<TTimer
> timers
;
472 * When true, exit the application.
474 private volatile boolean quit
= false;
477 * When true, repaint the entire screen.
479 private volatile boolean repaint
= true;
482 * Y coordinate of the top edge of the desktop. For now this is a
483 * constant. Someday it would be nice to have a multi-line menu or
486 private static final int desktopTop
= 1;
489 * Get Y coordinate of the top edge of the desktop.
491 * @return Y coordinate of the top edge of the desktop
493 public final int getDesktopTop() {
498 * Y coordinate of the bottom edge of the desktop.
500 private int desktopBottom
;
503 * Get Y coordinate of the bottom edge of the desktop.
505 * @return Y coordinate of the bottom edge of the desktop
507 public final int getDesktopBottom() {
508 return desktopBottom
;
512 * Public constructor.
514 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
516 * @throws UnsupportedEncodingException if an exception is thrown when
517 * creating the InputStreamReader
519 public TApplication(final BackendType backendType
)
520 throws UnsupportedEncodingException
{
522 switch (backendType
) {
524 backend
= new SwingBackend(this);
529 backend
= new ECMA48Backend(this, null, null);
532 throw new IllegalArgumentException("Invalid backend type: "
539 * Public constructor. The backend type will be BackendType.ECMA48.
541 * @param input an InputStream connected to the remote user, or null for
542 * System.in. If System.in is used, then on non-Windows systems it will
543 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
544 * mode. input is always converted to a Reader with UTF-8 encoding.
545 * @param output an OutputStream connected to the remote user, or null
546 * for System.out. output is always converted to a Writer with UTF-8
548 * @throws UnsupportedEncodingException if an exception is thrown when
549 * creating the InputStreamReader
551 public TApplication(final InputStream input
,
552 final OutputStream output
) throws UnsupportedEncodingException
{
554 backend
= new ECMA48Backend(this, input
, output
);
559 * Public constructor. The backend type will be BackendType.ECMA48.
561 * @param input the InputStream underlying 'reader'. Its available()
562 * method is used to determine if reader.read() will block or not.
563 * @param reader a Reader connected to the remote user.
564 * @param writer a PrintWriter connected to the remote user.
565 * @param setRawMode if true, set System.in into raw mode with stty.
566 * This should in general not be used. It is here solely for Demo3,
567 * which uses System.in.
568 * @throws IllegalArgumentException if input, reader, or writer are null.
570 public TApplication(final InputStream input
, final Reader reader
,
571 final PrintWriter writer
, final boolean setRawMode
) {
573 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
578 * Public constructor. The backend type will be BackendType.ECMA48.
580 * @param input the InputStream underlying 'reader'. Its available()
581 * method is used to determine if reader.read() will block or not.
582 * @param reader a Reader connected to the remote user.
583 * @param writer a PrintWriter connected to the remote user.
584 * @throws IllegalArgumentException if input, reader, or writer are null.
586 public TApplication(final InputStream input
, final Reader reader
,
587 final PrintWriter writer
) {
589 this(input
, reader
, writer
, false);
593 * Public constructor. This hook enables use with new non-Jexer
596 * @param backend a Backend that is already ready to go.
598 public TApplication(final Backend backend
) {
599 this.backend
= backend
;
604 * Finish construction once the backend is set.
606 private void TApplicationImpl() {
607 theme
= new ColorTheme();
608 desktopBottom
= getScreen().getHeight() - 1;
609 fillEventQueue
= new ArrayList
<TInputEvent
>();
610 drainEventQueue
= new ArrayList
<TInputEvent
>();
611 windows
= new LinkedList
<TWindow
>();
612 menus
= new LinkedList
<TMenu
>();
613 subMenus
= new LinkedList
<TMenu
>();
614 timers
= new LinkedList
<TTimer
>();
615 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
616 menuItems
= new ArrayList
<TMenuItem
>();
618 // Setup the main consumer thread
619 primaryEventHandler
= new WidgetEventHandler(this, true);
620 (new Thread(primaryEventHandler
)).start();
624 * Invert the cell color at a position. This is used to track the mouse.
626 * @param x column position
627 * @param y row position
629 private void invertCell(final int x
, final int y
) {
631 System
.err
.printf("invertCell() %d %d\n", x
, y
);
633 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
634 attr
.setForeColor(attr
.getForeColor().invert());
635 attr
.setBackColor(attr
.getBackColor().invert());
636 getScreen().putAttrXY(x
, y
, attr
, false);
642 private void drawAll() {
644 System
.err
.printf("drawAll() enter\n");
649 System
.err
.printf("drawAll() !repaint\n");
651 synchronized (getScreen()) {
652 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
653 // The only thing that has happened is the mouse moved.
654 // Clear the old position and draw the new position.
655 invertCell(oldMouseX
, oldMouseY
);
656 invertCell(mouseX
, mouseY
);
660 if (getScreen().isDirty()) {
661 backend
.flushScreen();
668 System
.err
.printf("drawAll() REDRAW\n");
671 // If true, the cursor is not visible
672 boolean cursor
= false;
674 // Start with a clean screen
677 // Draw the background
678 CellAttributes background
= theme
.getColor("tapplication.background");
679 getScreen().putAll(GraphicsChars
.HATCH
, background
);
681 // Draw each window in reverse Z order
682 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
683 Collections
.sort(sorted
);
684 Collections
.reverse(sorted
);
685 for (TWindow window
: sorted
) {
686 window
.drawChildren();
689 // Draw the blank menubar line - reset the screen clipping first so
690 // it won't trim it out.
691 getScreen().resetClipping();
692 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
693 theme
.getColor("tmenu"));
694 // Now draw the menus.
696 for (TMenu menu
: menus
) {
697 CellAttributes menuColor
;
698 CellAttributes menuMnemonicColor
;
699 if (menu
.isActive()) {
700 menuColor
= theme
.getColor("tmenu.highlighted");
701 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
703 menuColor
= theme
.getColor("tmenu");
704 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
706 // Draw the menu title
707 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
709 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
710 // Draw the highlight character
711 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
712 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
714 if (menu
.isActive()) {
716 // Reset the screen clipping so we can draw the next title.
717 getScreen().resetClipping();
719 x
+= menu
.getTitle().length() + 2;
722 for (TMenu menu
: subMenus
) {
723 // Reset the screen clipping so we can draw the next sub-menu.
724 getScreen().resetClipping();
728 // Draw the mouse pointer
729 invertCell(mouseX
, mouseY
);
733 // Place the cursor if it is visible
734 TWidget activeWidget
= null;
735 if (sorted
.size() > 0) {
736 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
737 if (activeWidget
.isCursorVisible()) {
738 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
739 activeWidget
.getCursorAbsoluteY());
746 getScreen().hideCursor();
749 // Flush the screen contents
750 if (getScreen().isDirty()) {
751 backend
.flushScreen();
758 * Run this application until it exits.
762 // Timeout is in milliseconds, so default timeout after 1 second
766 // If I've got no updates to render, wait for something from the
767 // backend or a timer.
769 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
771 // Never sleep longer than 50 millis. We need time for
772 // windows with background tasks to update the display, and
773 // still flip buffers reasonably quickly in
774 // backend.flushPhysical().
775 timeout
= getSleepTime(50);
779 // As of now, I've got nothing to do: no I/O, nothing from
780 // the consumer threads, no timers that need to run ASAP. So
781 // wait until either the backend or the consumer threads have
785 System
.err
.println("sleep " + timeout
+ " millis");
787 synchronized (this) {
790 } catch (InterruptedException e
) {
791 // I'm awake and don't care why, let's see what's going
797 // Prevent stepping on the primary or secondary event handler.
800 // Pull any pending I/O events
801 backend
.getEvents(fillEventQueue
);
803 // Dispatch each event to the appropriate handler, one at a time.
805 TInputEvent event
= null;
806 if (fillEventQueue
.size() == 0) {
809 event
= fillEventQueue
.remove(0);
810 metaHandleEvent(event
);
813 // Wake a consumer thread if we have any pending events.
814 if (drainEventQueue
.size() > 0) {
818 // Process timers and call doIdle()'s
822 synchronized (getScreen()) {
826 // Let the event handlers run again.
827 startEventHandlers();
831 // Shutdown the event consumer threads
832 if (secondaryEventHandler
!= null) {
833 synchronized (secondaryEventHandler
) {
834 secondaryEventHandler
.notify();
837 if (primaryEventHandler
!= null) {
838 synchronized (primaryEventHandler
) {
839 primaryEventHandler
.notify();
843 // Shutdown the user I/O thread(s)
846 // Close all the windows. This gives them an opportunity to release
853 * Peek at certain application-level events, add to eventQueue, and wake
854 * up the consuming Thread.
856 * @param event the input event to consume
858 private void metaHandleEvent(final TInputEvent event
) {
861 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
862 event
)); System
.err
.flush();
866 // Do no more processing if the application is already trying
871 // Special application-wide events -------------------------------
874 if (event
instanceof TCommandEvent
) {
875 TCommandEvent command
= (TCommandEvent
) event
;
876 if (command
.getCmd().equals(cmAbort
)) {
883 if (event
instanceof TResizeEvent
) {
884 TResizeEvent resize
= (TResizeEvent
) event
;
885 synchronized (getScreen()) {
886 getScreen().setDimensions(resize
.getWidth(),
888 desktopBottom
= getScreen().getHeight() - 1;
897 // Peek at the mouse position
898 if (event
instanceof TMouseEvent
) {
899 TMouseEvent mouse
= (TMouseEvent
) event
;
900 synchronized (getScreen()) {
901 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
904 mouseX
= mouse
.getX();
905 mouseY
= mouse
.getY();
910 // Put into the main queue
911 drainEventQueue
.add(event
);
915 * Dispatch one event to the appropriate widget or application-level
916 * event handler. This is the primary event handler, it has the normal
917 * application-wide event handling.
919 * @param event the input event to consume
920 * @see #secondaryHandleEvent(TInputEvent event)
922 private void primaryHandleEvent(final TInputEvent event
) {
925 System
.err
.printf("Handle event: %s\n", event
);
928 // Special application-wide events -----------------------------------
930 // Peek at the mouse position
931 if (event
instanceof TMouseEvent
) {
932 // See if we need to switch focus to another window or the menu
933 checkSwitchFocus((TMouseEvent
) event
);
936 // Handle menu events
937 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
938 TMenu menu
= activeMenu
;
940 if (event
instanceof TMouseEvent
) {
941 TMouseEvent mouse
= (TMouseEvent
) event
;
943 while (subMenus
.size() > 0) {
944 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
945 if (subMenu
.mouseWouldHit(mouse
)) {
948 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
949 && (!mouse
.isMouse1())
950 && (!mouse
.isMouse2())
951 && (!mouse
.isMouse3())
952 && (!mouse
.isMouseWheelUp())
953 && (!mouse
.isMouseWheelDown())
957 // We navigated away from a sub-menu, so close it
961 // Convert the mouse relative x/y to menu coordinates
962 assert (mouse
.getX() == mouse
.getAbsoluteX());
963 assert (mouse
.getY() == mouse
.getAbsoluteY());
964 if (subMenus
.size() > 0) {
965 menu
= subMenus
.get(subMenus
.size() - 1);
967 mouse
.setX(mouse
.getX() - menu
.getX());
968 mouse
.setY(mouse
.getY() - menu
.getY());
970 menu
.handleEvent(event
);
974 if (event
instanceof TKeypressEvent
) {
975 TKeypressEvent keypress
= (TKeypressEvent
) event
;
977 // See if this key matches an accelerator, and is not being
978 // shortcutted by the active window, and if so dispatch the menu
980 boolean windowWillShortcut
= false;
981 for (TWindow window
: windows
) {
982 if (window
.isActive()) {
983 if (window
.isShortcutKeypress(keypress
.getKey())) {
984 // We do not process this key, it will be passed to
985 // the window instead.
986 windowWillShortcut
= true;
991 if (!windowWillShortcut
) {
992 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
993 TMenuItem item
= null;
994 synchronized (accelerators
) {
995 item
= accelerators
.get(keypressLowercase
);
998 if (item
.isEnabled()) {
999 // Let the menu item dispatch
1006 // Handle the keypress
1007 if (onKeypress(keypress
)) {
1012 if (event
instanceof TCommandEvent
) {
1013 if (onCommand((TCommandEvent
) event
)) {
1018 if (event
instanceof TMenuEvent
) {
1019 if (onMenu((TMenuEvent
) event
)) {
1024 // Dispatch events to the active window -------------------------------
1025 for (TWindow window
: windows
) {
1026 if (window
.isActive()) {
1027 if (event
instanceof TMouseEvent
) {
1028 TMouseEvent mouse
= (TMouseEvent
) event
;
1029 // Convert the mouse relative x/y to window coordinates
1030 assert (mouse
.getX() == mouse
.getAbsoluteX());
1031 assert (mouse
.getY() == mouse
.getAbsoluteY());
1032 mouse
.setX(mouse
.getX() - window
.getX());
1033 mouse
.setY(mouse
.getY() - window
.getY());
1036 System
.err
.printf("TApplication dispatch event: %s\n",
1039 window
.handleEvent(event
);
1045 * Dispatch one event to the appropriate widget or application-level
1046 * event handler. This is the secondary event handler used by certain
1047 * special dialogs (currently TMessageBox and TFileOpenBox).
1049 * @param event the input event to consume
1050 * @see #primaryHandleEvent(TInputEvent event)
1052 private void secondaryHandleEvent(final TInputEvent event
) {
1053 secondaryEventReceiver
.handleEvent(event
);
1057 * Enable a widget to override the primary event thread.
1059 * @param widget widget that will receive events
1061 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1062 assert (secondaryEventReceiver
== null);
1063 assert (secondaryEventHandler
== null);
1064 assert ((widget
instanceof TMessageBox
)
1065 || (widget
instanceof TFileOpenBox
));
1066 secondaryEventReceiver
= widget
;
1067 secondaryEventHandler
= new WidgetEventHandler(this, false);
1068 (new Thread(secondaryEventHandler
)).start();
1072 * Yield to the secondary thread.
1074 public final void yield() {
1075 assert (secondaryEventReceiver
!= null);
1076 // This is where we handoff the event handler lock from the primary
1077 // to secondary thread. We unlock here, and in a future loop the
1078 // secondary thread locks again. When it gives up, we have the
1079 // single lock back.
1080 boolean oldLock
= unlockHandleEvent();
1083 while (secondaryEventReceiver
!= null) {
1084 synchronized (primaryEventHandler
) {
1086 primaryEventHandler
.wait();
1087 } catch (InterruptedException e
) {
1095 * Do stuff when there is no user input.
1097 private void doIdle() {
1099 System
.err
.printf("doIdle()\n");
1102 // Now run any timers that have timed out
1103 Date now
= new Date();
1104 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1105 for (TTimer timer
: timers
) {
1106 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1108 if (timer
.recurring
) {
1109 keepTimers
.add(timer
);
1112 keepTimers
.add(timer
);
1115 timers
= keepTimers
;
1118 for (TWindow window
: windows
) {
1124 * Get the amount of time I can sleep before missing a Timer tick.
1126 * @param timeout = initial (maximum) timeout in millis
1127 * @return number of milliseconds between now and the next timer event
1129 private long getSleepTime(final long timeout
) {
1130 Date now
= new Date();
1131 long nowTime
= now
.getTime();
1132 long sleepTime
= timeout
;
1133 for (TTimer timer
: timers
) {
1134 long nextTickTime
= timer
.getNextTick().getTime();
1135 if (nextTickTime
< nowTime
) {
1139 long timeDifference
= nextTickTime
- nowTime
;
1140 if (timeDifference
< sleepTime
) {
1141 sleepTime
= timeDifference
;
1144 assert (sleepTime
>= 0);
1145 assert (sleepTime
<= timeout
);
1150 * Close window. Note that the window's destructor is NOT called by this
1151 * method, instead the GC is assumed to do the cleanup.
1153 * @param window the window to remove
1155 public final void closeWindow(final TWindow window
) {
1156 synchronized (windows
) {
1157 int z
= window
.getZ();
1160 Collections
.sort(windows
);
1162 TWindow activeWindow
= null;
1163 for (TWindow w
: windows
) {
1165 w
.setZ(w
.getZ() - 1);
1166 if (w
.getZ() == 0) {
1169 assert (activeWindow
== null);
1181 // Perform window cleanup
1184 // Check if we are closing a TMessageBox or similar
1185 if (secondaryEventReceiver
!= null) {
1186 assert (secondaryEventHandler
!= null);
1188 // Do not send events to the secondaryEventReceiver anymore, the
1189 // window is closed.
1190 secondaryEventReceiver
= null;
1192 // Wake the secondary thread, it will wake the primary as it
1194 synchronized (secondaryEventHandler
) {
1195 secondaryEventHandler
.notify();
1201 * Switch to the next window.
1203 * @param forward if true, then switch to the next window in the list,
1204 * otherwise switch to the previous window in the list
1206 public final void switchWindow(final boolean forward
) {
1207 // Only switch if there are multiple windows
1208 if (windows
.size() < 2) {
1212 synchronized (windows
) {
1214 // Swap z/active between active window and the next in the list
1215 int activeWindowI
= -1;
1216 for (int i
= 0; i
< windows
.size(); i
++) {
1217 if (windows
.get(i
).isActive()) {
1222 assert (activeWindowI
>= 0);
1224 // Do not switch if a window is modal
1225 if (windows
.get(activeWindowI
).isModal()) {
1231 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1233 if (activeWindowI
== 0) {
1234 nextWindowI
= windows
.size() - 1;
1236 nextWindowI
= activeWindowI
- 1;
1239 windows
.get(activeWindowI
).setActive(false);
1240 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1241 windows
.get(activeWindowI
).onUnfocus();
1242 windows
.get(nextWindowI
).setZ(0);
1243 windows
.get(nextWindowI
).setActive(true);
1244 windows
.get(nextWindowI
).onFocus();
1246 } // synchronized (windows)
1251 * Add a window to my window list and make it active.
1253 * @param window new window to add
1255 public final void addWindow(final TWindow window
) {
1256 synchronized (windows
) {
1257 // Do not allow a modal window to spawn a non-modal window
1258 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1259 assert (window
.isModal());
1261 for (TWindow w
: windows
) {
1266 w
.setZ(w
.getZ() + 1);
1268 windows
.add(window
);
1270 window
.setActive(true);
1276 * Check if there is a system-modal window on top.
1278 * @return true if the active window is modal
1280 private boolean modalWindowActive() {
1281 if (windows
.size() == 0) {
1284 return windows
.get(windows
.size() - 1).isModal();
1288 * Check if a mouse event would hit either the active menu or any open
1291 * @param mouse mouse event
1292 * @return true if the mouse would hit the active menu or an open
1295 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1296 assert (activeMenu
!= null);
1297 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1298 Collections
.reverse(menus
);
1299 for (TMenu menu
: menus
) {
1300 if (menu
.mouseWouldHit(mouse
)) {
1304 return activeMenu
.mouseWouldHit(mouse
);
1308 * See if we need to switch window or activate the menu based on
1311 * @param mouse mouse event
1313 private void checkSwitchFocus(final TMouseEvent mouse
) {
1315 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1316 && (activeMenu
!= null)
1317 && (mouse
.getAbsoluteY() != 0)
1318 && (!mouseOnMenu(mouse
))
1320 // They clicked outside the active menu, turn it off
1321 activeMenu
.setActive(false);
1323 for (TMenu menu
: subMenus
) {
1324 menu
.setActive(false);
1330 // See if they hit the menu bar
1331 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1332 && (mouse
.isMouse1())
1333 && (!modalWindowActive())
1334 && (mouse
.getAbsoluteY() == 0)
1337 for (TMenu menu
: subMenus
) {
1338 menu
.setActive(false);
1342 // They selected the menu, go activate it
1343 for (TMenu menu
: menus
) {
1344 if ((mouse
.getAbsoluteX() >= menu
.getX())
1345 && (mouse
.getAbsoluteX() < menu
.getX()
1346 + menu
.getTitle().length() + 2)
1348 menu
.setActive(true);
1351 menu
.setActive(false);
1357 // See if they hit the menu bar
1358 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1359 && (mouse
.isMouse1())
1360 && (activeMenu
!= null)
1361 && (mouse
.getAbsoluteY() == 0)
1364 TMenu oldMenu
= activeMenu
;
1365 for (TMenu menu
: subMenus
) {
1366 menu
.setActive(false);
1370 // See if we should switch menus
1371 for (TMenu menu
: menus
) {
1372 if ((mouse
.getAbsoluteX() >= menu
.getX())
1373 && (mouse
.getAbsoluteX() < menu
.getX()
1374 + menu
.getTitle().length() + 2)
1376 menu
.setActive(true);
1380 if (oldMenu
!= activeMenu
) {
1381 // They switched menus
1382 oldMenu
.setActive(false);
1387 // Only switch if there are multiple windows
1388 if (windows
.size() < 2) {
1392 // Switch on the upclick
1393 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1397 synchronized (windows
) {
1398 Collections
.sort(windows
);
1399 if (windows
.get(0).isModal()) {
1400 // Modal windows don't switch
1404 for (TWindow window
: windows
) {
1405 assert (!window
.isModal());
1406 if (window
.mouseWouldHit(mouse
)) {
1407 if (window
== windows
.get(0)) {
1408 // Clicked on the same window, nothing to do
1412 // We will be switching to another window
1413 assert (windows
.get(0).isActive());
1414 assert (!window
.isActive());
1415 windows
.get(0).onUnfocus();
1416 windows
.get(0).setActive(false);
1417 windows
.get(0).setZ(window
.getZ());
1419 window
.setActive(true);
1426 // Clicked on the background, nothing to do
1431 * Turn off the menu.
1433 public final void closeMenu() {
1434 if (activeMenu
!= null) {
1435 activeMenu
.setActive(false);
1437 for (TMenu menu
: subMenus
) {
1438 menu
.setActive(false);
1445 * Turn off a sub-menu.
1447 public final void closeSubMenu() {
1448 assert (activeMenu
!= null);
1449 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1450 assert (item
!= null);
1451 item
.setActive(false);
1452 subMenus
.remove(subMenus
.size() - 1);
1456 * Switch to the next menu.
1458 * @param forward if true, then switch to the next menu in the list,
1459 * otherwise switch to the previous menu in the list
1461 public final void switchMenu(final boolean forward
) {
1462 assert (activeMenu
!= null);
1464 for (TMenu menu
: subMenus
) {
1465 menu
.setActive(false);
1469 for (int i
= 0; i
< menus
.size(); i
++) {
1470 if (activeMenu
== menus
.get(i
)) {
1472 if (i
< menus
.size() - 1) {
1480 activeMenu
.setActive(false);
1481 activeMenu
= menus
.get(i
);
1482 activeMenu
.setActive(true);
1489 * Method that TApplication subclasses can override to handle menu or
1490 * posted command events.
1492 * @param command command event
1493 * @return if true, this event was consumed
1495 protected boolean onCommand(final TCommandEvent command
) {
1496 // Default: handle cmExit
1497 if (command
.equals(cmExit
)) {
1498 if (messageBox("Confirmation", "Exit application?",
1499 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1505 if (command
.equals(cmShell
)) {
1506 openTerminal(0, 0, TWindow
.RESIZABLE
);
1510 if (command
.equals(cmTile
)) {
1514 if (command
.equals(cmCascade
)) {
1518 if (command
.equals(cmCloseAll
)) {
1527 * Display the about dialog.
1529 protected void showAboutDialog() {
1530 messageBox("About", "Jexer Version " +
1531 this.getClass().getPackage().getImplementationVersion(),
1532 TMessageBox
.Type
.OK
);
1536 * Method that TApplication subclasses can override to handle menu
1539 * @param menu menu event
1540 * @return if true, this event was consumed
1542 protected boolean onMenu(final TMenuEvent menu
) {
1544 // Default: handle MID_EXIT
1545 if (menu
.getId() == TMenu
.MID_EXIT
) {
1546 if (messageBox("Confirmation", "Exit application?",
1547 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1553 if (menu
.getId() == TMenu
.MID_SHELL
) {
1554 openTerminal(0, 0, TWindow
.RESIZABLE
);
1558 if (menu
.getId() == TMenu
.MID_TILE
) {
1562 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1566 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1570 if (menu
.getId() == TMenu
.MID_ABOUT
) {
1578 * Method that TApplication subclasses can override to handle keystrokes.
1580 * @param keypress keystroke event
1581 * @return if true, this event was consumed
1583 protected boolean onKeypress(final TKeypressEvent keypress
) {
1584 // Default: only menu shortcuts
1586 // Process Alt-F, Alt-E, etc. menu shortcut keys
1587 if (!keypress
.getKey().isFnKey()
1588 && keypress
.getKey().isAlt()
1589 && !keypress
.getKey().isCtrl()
1590 && (activeMenu
== null)
1593 assert (subMenus
.size() == 0);
1595 for (TMenu menu
: menus
) {
1596 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1597 == Character
.toLowerCase(keypress
.getKey().getChar())
1600 menu
.setActive(true);
1610 * Add a menu item to the global list. If it has a keyboard accelerator,
1611 * that will be added the global hash.
1613 * @param item the menu item
1615 public final void addMenuItem(final TMenuItem item
) {
1616 menuItems
.add(item
);
1618 TKeypress key
= item
.getKey();
1620 synchronized (accelerators
) {
1621 assert (accelerators
.get(key
) == null);
1622 accelerators
.put(key
.toLowerCase(), item
);
1628 * Disable one menu item.
1630 * @param id the menu item ID
1632 public final void disableMenuItem(final int id
) {
1633 for (TMenuItem item
: menuItems
) {
1634 if (item
.getId() == id
) {
1635 item
.setEnabled(false);
1641 * Disable the range of menu items with ID's between lower and upper,
1644 * @param lower the lowest menu item ID
1645 * @param upper the highest menu item ID
1647 public final void disableMenuItems(final int lower
, final int upper
) {
1648 for (TMenuItem item
: menuItems
) {
1649 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1650 item
.setEnabled(false);
1656 * Enable one menu item.
1658 * @param id the menu item ID
1660 public final void enableMenuItem(final int id
) {
1661 for (TMenuItem item
: menuItems
) {
1662 if (item
.getId() == id
) {
1663 item
.setEnabled(true);
1669 * Enable the range of menu items with ID's between lower and upper,
1672 * @param lower the lowest menu item ID
1673 * @param upper the highest menu item ID
1675 public final void enableMenuItems(final int lower
, final int upper
) {
1676 for (TMenuItem item
: menuItems
) {
1677 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1678 item
.setEnabled(true);
1684 * Recompute menu x positions based on their title length.
1686 public final void recomputeMenuX() {
1688 for (TMenu menu
: menus
) {
1690 x
+= menu
.getTitle().length() + 2;
1695 * Post an event to process and turn off the menu.
1697 * @param event new event to add to the queue
1699 public final void postMenuEvent(final TInputEvent event
) {
1700 synchronized (fillEventQueue
) {
1701 fillEventQueue
.add(event
);
1707 * Add a sub-menu to the list of open sub-menus.
1709 * @param menu sub-menu
1711 public final void addSubMenu(final TMenu menu
) {
1716 * Convenience function to add a top-level menu.
1718 * @param title menu title
1719 * @return the new menu
1721 public final TMenu
addMenu(final String title
) {
1724 TMenu menu
= new TMenu(this, x
, y
, title
);
1731 * Convenience function to add a default "File" menu.
1733 * @return the new menu
1735 public final TMenu
addFileMenu() {
1736 TMenu fileMenu
= addMenu("&File");
1737 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1738 fileMenu
.addSeparator();
1739 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1740 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1745 * Convenience function to add a default "Edit" menu.
1747 * @return the new menu
1749 public final TMenu
addEditMenu() {
1750 TMenu editMenu
= addMenu("&Edit");
1751 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1752 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1753 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1754 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1759 * Convenience function to add a default "Window" menu.
1761 * @return the new menu
1763 public final TMenu
addWindowMenu() {
1764 TMenu windowMenu
= addMenu("&Window");
1765 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1766 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1767 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1768 windowMenu
.addSeparator();
1769 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1770 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1771 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1772 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1773 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1778 * Convenience function to add a default "Help" menu.
1780 * @return the new menu
1782 public final TMenu
addHelpMenu() {
1783 TMenu helpMenu
= addMenu("&Help");
1784 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
1785 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
1786 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
1787 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
1788 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
1789 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
1790 helpMenu
.addSeparator();
1791 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
1796 * Close all open windows.
1798 private void closeAllWindows() {
1799 // Don't do anything if we are in the menu
1800 if (activeMenu
!= null) {
1803 while (windows
.size() > 0) {
1804 closeWindow(windows
.get(0));
1809 * Re-layout the open windows as non-overlapping tiles. This produces
1810 * almost the same results as Turbo Pascal 7.0's IDE.
1812 private void tileWindows() {
1813 synchronized (windows
) {
1814 // Don't do anything if we are in the menu
1815 if (activeMenu
!= null) {
1818 int z
= windows
.size();
1824 a
= (int)(Math
.sqrt(z
));
1828 if (((a
* b
) + c
) == z
) {
1836 int newWidth
= (getScreen().getWidth() / a
);
1837 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1838 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1840 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1841 Collections
.sort(sorted
);
1842 Collections
.reverse(sorted
);
1843 for (int i
= 0; i
< sorted
.size(); i
++) {
1844 int logicalX
= i
/ b
;
1845 int logicalY
= i
% b
;
1846 if (i
>= ((a
- 1) * b
)) {
1848 logicalY
= i
- ((a
- 1) * b
);
1851 TWindow w
= sorted
.get(i
);
1852 w
.setX(logicalX
* newWidth
);
1853 w
.setWidth(newWidth
);
1854 if (i
>= ((a
- 1) * b
)) {
1855 w
.setY((logicalY
* newHeight2
) + 1);
1856 w
.setHeight(newHeight2
);
1858 w
.setY((logicalY
* newHeight1
) + 1);
1859 w
.setHeight(newHeight1
);
1866 * Re-layout the open windows as overlapping cascaded windows.
1868 private void cascadeWindows() {
1869 synchronized (windows
) {
1870 // Don't do anything if we are in the menu
1871 if (activeMenu
!= null) {
1876 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1877 Collections
.sort(sorted
);
1878 Collections
.reverse(sorted
);
1879 for (TWindow window
: sorted
) {
1884 if (x
> getScreen().getWidth()) {
1887 if (y
>= getScreen().getHeight()) {
1895 * Convenience function to add a timer.
1897 * @param duration number of milliseconds to wait between ticks
1898 * @param recurring if true, re-schedule this timer after every tick
1899 * @param action function to call when button is pressed
1902 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1903 final TAction action
) {
1905 TTimer timer
= new TTimer(duration
, recurring
, action
);
1906 synchronized (timers
) {
1913 * Convenience function to remove a timer.
1915 * @param timer timer to remove
1917 public final void removeTimer(final TTimer timer
) {
1918 synchronized (timers
) {
1919 timers
.remove(timer
);
1924 * Convenience function to spawn a message box.
1926 * @param title window title, will be centered along the top border
1927 * @param caption message to display. Use embedded newlines to get a
1929 * @return the new message box
1931 public final TMessageBox
messageBox(final String title
,
1932 final String caption
) {
1934 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1938 * Convenience function to spawn a message box.
1940 * @param title window title, will be centered along the top border
1941 * @param caption message to display. Use embedded newlines to get a
1943 * @param type one of the TMessageBox.Type constants. Default is
1945 * @return the new message box
1947 public final TMessageBox
messageBox(final String title
,
1948 final String caption
, final TMessageBox
.Type type
) {
1950 return new TMessageBox(this, title
, caption
, type
);
1954 * Convenience function to spawn an input box.
1956 * @param title window title, will be centered along the top border
1957 * @param caption message to display. Use embedded newlines to get a
1959 * @return the new input box
1961 public final TInputBox
inputBox(final String title
, final String caption
) {
1963 return new TInputBox(this, title
, caption
);
1967 * Convenience function to spawn an input box.
1969 * @param title window title, will be centered along the top border
1970 * @param caption message to display. Use embedded newlines to get a
1972 * @param text initial text to seed the field with
1973 * @return the new input box
1975 public final TInputBox
inputBox(final String title
, final String caption
,
1976 final String text
) {
1978 return new TInputBox(this, title
, caption
, text
);
1982 * Convenience function to open a terminal window.
1984 * @param x column relative to parent
1985 * @param y row relative to parent
1986 * @return the terminal new window
1988 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1989 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1993 * Convenience function to open a terminal window.
1995 * @param x column relative to parent
1996 * @param y row relative to parent
1997 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1998 * @return the terminal new window
2000 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2003 return new TTerminalWindow(this, x
, y
, flags
);
2007 * Convenience function to spawn an file open box.
2009 * @param path path of selected file
2010 * @return the result of the new file open box
2011 * @throws IOException if java.io operation throws
2013 public final String
fileOpenBox(final String path
) throws IOException
{
2015 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2016 return box
.getFilename();
2020 * Convenience function to spawn an file open box.
2022 * @param path path of selected file
2023 * @param type one of the Type constants
2024 * @return the result of the new file open box
2025 * @throws IOException if java.io operation throws
2027 public final String
fileOpenBox(final String path
,
2028 final TFileOpenBox
.Type type
) throws IOException
{
2030 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2031 return box
.getFilename();