2 * Jexer - Java Text User Interface
4 * License: LGPLv3 or later
6 * This module is licensed under the GNU Lesser General Public License
7 * Version 3. Please see the file "COPYING" in this directory for more
8 * information about the GNU Lesser General Public License Version 3.
10 * Copyright (C) 2015 Kevin Lamonte
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 3 of
15 * the License, or (at your option) any later version.
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this program; if not, see
24 * http://www.gnu.org/licenses/, or write to the Free Software
25 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
28 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
33 import java
.io
.InputStream
;
34 import java
.io
.IOException
;
35 import java
.io
.OutputStream
;
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
;
434 * Windows and widgets pull colors from this ColorTheme.
436 private ColorTheme theme
;
439 * Get the color theme.
443 public final ColorTheme
getTheme() {
448 * The top-level windows (but not menus).
450 private List
<TWindow
> windows
;
453 * Timers that are being ticked.
455 private List
<TTimer
> timers
;
458 * When true, exit the application.
460 private volatile boolean quit
= false;
463 * When true, repaint the entire screen.
465 private volatile boolean repaint
= true;
468 * Y coordinate of the top edge of the desktop. For now this is a
469 * constant. Someday it would be nice to have a multi-line menu or
472 private static final int desktopTop
= 1;
475 * Get Y coordinate of the top edge of the desktop.
477 * @return Y coordinate of the top edge of the desktop
479 public final int getDesktopTop() {
484 * Y coordinate of the bottom edge of the desktop.
486 private int desktopBottom
;
489 * Get Y coordinate of the bottom edge of the desktop.
491 * @return Y coordinate of the bottom edge of the desktop
493 public final int getDesktopBottom() {
494 return desktopBottom
;
498 * Public constructor.
500 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
502 * @throws UnsupportedEncodingException if an exception is thrown when
503 * creating the InputStreamReader
505 public TApplication(final BackendType backendType
)
506 throws UnsupportedEncodingException
{
508 switch (backendType
) {
510 backend
= new SwingBackend(this);
515 backend
= new ECMA48Backend(this, null, null);
521 * Public constructor. The backend type will be BackendType.ECMA48.
523 * @param input an InputStream connected to the remote user, or null for
524 * System.in. If System.in is used, then on non-Windows systems it will
525 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
526 * mode. input is always converted to a Reader with UTF-8 encoding.
527 * @param output an OutputStream connected to the remote user, or null
528 * for System.out. output is always converted to a Writer with UTF-8
530 * @throws UnsupportedEncodingException if an exception is thrown when
531 * creating the InputStreamReader
533 public TApplication(final InputStream input
,
534 final OutputStream output
) throws UnsupportedEncodingException
{
536 backend
= new ECMA48Backend(this, input
, output
);
541 * Public constructor. This hook enables use with new non-Jexer
544 * @param backend a Backend that is already ready to go.
546 public TApplication(final Backend backend
) {
547 this.backend
= backend
;
552 * Finish construction once the backend is set.
554 private void TApplicationImpl() {
555 theme
= new ColorTheme();
556 desktopBottom
= getScreen().getHeight() - 1;
557 fillEventQueue
= new ArrayList
<TInputEvent
>();
558 drainEventQueue
= new ArrayList
<TInputEvent
>();
559 windows
= new LinkedList
<TWindow
>();
560 menus
= new LinkedList
<TMenu
>();
561 subMenus
= new LinkedList
<TMenu
>();
562 timers
= new LinkedList
<TTimer
>();
563 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
565 // Setup the main consumer thread
566 primaryEventHandler
= new WidgetEventHandler(this, true);
567 (new Thread(primaryEventHandler
)).start();
571 * Invert the cell color at a position. This is used to track the mouse.
573 * @param x column position
574 * @param y row position
576 private void invertCell(final int x
, final int y
) {
577 synchronized (getScreen()) {
578 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
579 attr
.setForeColor(attr
.getForeColor().invert());
580 attr
.setBackColor(attr
.getBackColor().invert());
581 getScreen().putAttrXY(x
, y
, attr
, false);
588 private void drawAll() {
590 System
.err
.printf("drawAll() enter\n");
594 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
595 // The only thing that has happened is the mouse moved.
596 // Clear the old position and draw the new position.
597 invertCell(oldMouseX
, oldMouseY
);
598 invertCell(mouseX
, mouseY
);
602 if (getScreen().isDirty()) {
603 backend
.flushScreen();
609 System
.err
.printf("drawAll() REDRAW\n");
612 // If true, the cursor is not visible
613 boolean cursor
= false;
615 // Start with a clean screen
618 // Draw the background
619 CellAttributes background
= theme
.getColor("tapplication.background");
620 getScreen().putAll(GraphicsChars
.HATCH
, background
);
622 // Draw each window in reverse Z order
623 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
624 Collections
.sort(sorted
);
625 Collections
.reverse(sorted
);
626 for (TWindow window
: sorted
) {
627 window
.drawChildren();
630 // Draw the blank menubar line - reset the screen clipping first so
631 // it won't trim it out.
632 getScreen().resetClipping();
633 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
634 theme
.getColor("tmenu"));
635 // Now draw the menus.
637 for (TMenu menu
: menus
) {
638 CellAttributes menuColor
;
639 CellAttributes menuMnemonicColor
;
640 if (menu
.isActive()) {
641 menuColor
= theme
.getColor("tmenu.highlighted");
642 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
644 menuColor
= theme
.getColor("tmenu");
645 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
647 // Draw the menu title
648 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
650 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
651 // Draw the highlight character
652 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
653 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
655 if (menu
.isActive()) {
657 // Reset the screen clipping so we can draw the next title.
658 getScreen().resetClipping();
660 x
+= menu
.getTitle().length() + 2;
663 for (TMenu menu
: subMenus
) {
664 // Reset the screen clipping so we can draw the next sub-menu.
665 getScreen().resetClipping();
669 // Draw the mouse pointer
670 invertCell(mouseX
, mouseY
);
672 // Place the cursor if it is visible
673 TWidget activeWidget
= null;
674 if (sorted
.size() > 0) {
675 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
676 if (activeWidget
.isCursorVisible()) {
677 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
678 activeWidget
.getCursorAbsoluteY());
685 getScreen().hideCursor();
688 // Flush the screen contents
689 backend
.flushScreen();
695 * Run this application until it exits.
699 // Timeout is in milliseconds, so default timeout after 1 second
703 // If I've got no updates to render, wait for something from the
704 // backend or a timer.
706 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
708 // Never sleep longer than 50 millis. We need time for
709 // windows with background tasks to update the display, and
710 // still flip buffers reasonably quickly in
711 // backend.flushPhysical().
712 timeout
= getSleepTime(50);
716 // As of now, I've got nothing to do: no I/O, nothing from
717 // the consumer threads, no timers that need to run ASAP. So
718 // wait until either the backend or the consumer threads have
721 synchronized (this) {
724 } catch (InterruptedException e
) {
725 // I'm awake and don't care why, let's see what's going
731 // Prevent stepping on the primary or secondary event handler.
734 // Pull any pending I/O events
735 backend
.getEvents(fillEventQueue
);
737 // Dispatch each event to the appropriate handler, one at a time.
739 TInputEvent event
= null;
740 if (fillEventQueue
.size() == 0) {
743 event
= fillEventQueue
.remove(0);
744 metaHandleEvent(event
);
747 // Wake a consumer thread if we have any pending events.
748 if (drainEventQueue
.size() > 0) {
752 // Process timers and call doIdle()'s
756 synchronized (getScreen()) {
760 // Let the event handlers run again.
761 startEventHandlers();
765 // Shutdown the event consumer threads
766 if (secondaryEventHandler
!= null) {
767 synchronized (secondaryEventHandler
) {
768 secondaryEventHandler
.notify();
771 if (primaryEventHandler
!= null) {
772 synchronized (primaryEventHandler
) {
773 primaryEventHandler
.notify();
777 // Shutdown the user I/O thread(s)
780 // Close all the windows. This gives them an opportunity to release
787 * Peek at certain application-level events, add to eventQueue, and wake
788 * up the consuming Thread.
790 * @param event the input event to consume
792 private void metaHandleEvent(final TInputEvent event
) {
795 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
796 event
)); System
.err
.flush();
800 // Do no more processing if the application is already trying
805 // Special application-wide events -------------------------------
808 if (event
instanceof TCommandEvent
) {
809 TCommandEvent command
= (TCommandEvent
) event
;
810 if (command
.getCmd().equals(cmAbort
)) {
817 if (event
instanceof TResizeEvent
) {
818 TResizeEvent resize
= (TResizeEvent
) event
;
819 synchronized (getScreen()) {
820 getScreen().setDimensions(resize
.getWidth(),
822 desktopBottom
= getScreen().getHeight() - 1;
831 // Peek at the mouse position
832 if (event
instanceof TMouseEvent
) {
833 TMouseEvent mouse
= (TMouseEvent
) event
;
834 synchronized (getScreen()) {
835 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
838 mouseX
= mouse
.getX();
839 mouseY
= mouse
.getY();
844 // Put into the main queue
845 drainEventQueue
.add(event
);
849 * Dispatch one event to the appropriate widget or application-level
850 * event handler. This is the primary event handler, it has the normal
851 * application-wide event handling.
853 * @param event the input event to consume
854 * @see #secondaryHandleEvent(TInputEvent event)
856 private void primaryHandleEvent(final TInputEvent event
) {
859 System
.err
.printf("Handle event: %s\n", event
);
862 // Special application-wide events -----------------------------------
864 // Peek at the mouse position
865 if (event
instanceof TMouseEvent
) {
866 // See if we need to switch focus to another window or the menu
867 checkSwitchFocus((TMouseEvent
) event
);
870 // Handle menu events
871 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
872 TMenu menu
= activeMenu
;
874 if (event
instanceof TMouseEvent
) {
875 TMouseEvent mouse
= (TMouseEvent
) event
;
877 while (subMenus
.size() > 0) {
878 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
879 if (subMenu
.mouseWouldHit(mouse
)) {
882 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
883 && (!mouse
.isMouse1())
884 && (!mouse
.isMouse2())
885 && (!mouse
.isMouse3())
886 && (!mouse
.isMouseWheelUp())
887 && (!mouse
.isMouseWheelDown())
891 // We navigated away from a sub-menu, so close it
895 // Convert the mouse relative x/y to menu coordinates
896 assert (mouse
.getX() == mouse
.getAbsoluteX());
897 assert (mouse
.getY() == mouse
.getAbsoluteY());
898 if (subMenus
.size() > 0) {
899 menu
= subMenus
.get(subMenus
.size() - 1);
901 mouse
.setX(mouse
.getX() - menu
.getX());
902 mouse
.setY(mouse
.getY() - menu
.getY());
904 menu
.handleEvent(event
);
908 if (event
instanceof TKeypressEvent
) {
909 TKeypressEvent keypress
= (TKeypressEvent
) event
;
911 // See if this key matches an accelerator, and if so dispatch the
913 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
914 TMenuItem item
= null;
915 synchronized (accelerators
) {
916 item
= accelerators
.get(keypressLowercase
);
919 if (item
.isEnabled()) {
920 // Let the menu item dispatch
925 // Handle the keypress
926 if (onKeypress(keypress
)) {
931 if (event
instanceof TCommandEvent
) {
932 if (onCommand((TCommandEvent
) event
)) {
937 if (event
instanceof TMenuEvent
) {
938 if (onMenu((TMenuEvent
) event
)) {
943 // Dispatch events to the active window -------------------------------
944 for (TWindow window
: windows
) {
945 if (window
.isActive()) {
946 if (event
instanceof TMouseEvent
) {
947 TMouseEvent mouse
= (TMouseEvent
) event
;
948 // Convert the mouse relative x/y to window coordinates
949 assert (mouse
.getX() == mouse
.getAbsoluteX());
950 assert (mouse
.getY() == mouse
.getAbsoluteY());
951 mouse
.setX(mouse
.getX() - window
.getX());
952 mouse
.setY(mouse
.getY() - window
.getY());
955 System
.err
.printf("TApplication dispatch event: %s\n",
958 window
.handleEvent(event
);
964 * Dispatch one event to the appropriate widget or application-level
965 * event handler. This is the secondary event handler used by certain
966 * special dialogs (currently TMessageBox and TFileOpenBox).
968 * @param event the input event to consume
969 * @see #primaryHandleEvent(TInputEvent event)
971 private void secondaryHandleEvent(final TInputEvent event
) {
972 secondaryEventReceiver
.handleEvent(event
);
976 * Enable a widget to override the primary event thread.
978 * @param widget widget that will receive events
980 public final void enableSecondaryEventReceiver(final TWidget widget
) {
981 assert (secondaryEventReceiver
== null);
982 assert (secondaryEventHandler
== null);
983 assert (widget
instanceof TMessageBox
);
984 secondaryEventReceiver
= widget
;
985 secondaryEventHandler
= new WidgetEventHandler(this, false);
986 (new Thread(secondaryEventHandler
)).start();
990 * Yield to the secondary thread.
992 public final void yield() {
993 assert (secondaryEventReceiver
!= null);
994 // This is where we handoff the event handler lock from the primary
995 // to secondary thread. We unlock here, and in a future loop the
996 // secondary thread locks again. When it gives up, we have the
998 boolean oldLock
= unlockHandleEvent();
999 assert (oldLock
== true);
1001 while (secondaryEventReceiver
!= null) {
1002 synchronized (primaryEventHandler
) {
1004 primaryEventHandler
.wait();
1005 } catch (InterruptedException e
) {
1013 * Do stuff when there is no user input.
1015 private void doIdle() {
1017 System
.err
.printf("doIdle()\n");
1020 // Now run any timers that have timed out
1021 Date now
= new Date();
1022 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1023 for (TTimer timer
: timers
) {
1024 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1026 if (timer
.recurring
) {
1027 keepTimers
.add(timer
);
1030 keepTimers
.add(timer
);
1033 timers
= keepTimers
;
1036 for (TWindow window
: windows
) {
1042 * Get the amount of time I can sleep before missing a Timer tick.
1044 * @param timeout = initial (maximum) timeout in millis
1045 * @return number of milliseconds between now and the next timer event
1047 private long getSleepTime(final long timeout
) {
1048 Date now
= new Date();
1049 long nowTime
= now
.getTime();
1050 long sleepTime
= timeout
;
1051 for (TTimer timer
: timers
) {
1052 long nextTickTime
= timer
.getNextTick().getTime();
1053 if (nextTickTime
< nowTime
) {
1057 long timeDifference
= nextTickTime
- nowTime
;
1058 if (timeDifference
< sleepTime
) {
1059 sleepTime
= timeDifference
;
1062 assert (sleepTime
>= 0);
1063 assert (sleepTime
<= timeout
);
1068 * Close window. Note that the window's destructor is NOT called by this
1069 * method, instead the GC is assumed to do the cleanup.
1071 * @param window the window to remove
1073 public final void closeWindow(final TWindow window
) {
1074 synchronized (windows
) {
1075 int z
= window
.getZ();
1077 Collections
.sort(windows
);
1079 TWindow activeWindow
= null;
1080 for (TWindow w
: windows
) {
1082 w
.setZ(w
.getZ() - 1);
1083 if (w
.getZ() == 0) {
1085 assert (activeWindow
== null);
1094 // Perform window cleanup
1097 // Check if we are closing a TMessageBox or similar
1098 if (secondaryEventReceiver
!= null) {
1099 assert (secondaryEventHandler
!= null);
1101 // Do not send events to the secondaryEventReceiver anymore, the
1102 // window is closed.
1103 secondaryEventReceiver
= null;
1105 // Wake the secondary thread, it will wake the primary as it
1107 synchronized (secondaryEventHandler
) {
1108 secondaryEventHandler
.notify();
1114 * Switch to the next window.
1116 * @param forward if true, then switch to the next window in the list,
1117 * otherwise switch to the previous window in the list
1119 public final void switchWindow(final boolean forward
) {
1120 // Only switch if there are multiple windows
1121 if (windows
.size() < 2) {
1125 synchronized (windows
) {
1127 // Swap z/active between active window and the next in the list
1128 int activeWindowI
= -1;
1129 for (int i
= 0; i
< windows
.size(); i
++) {
1130 if (windows
.get(i
).isActive()) {
1135 assert (activeWindowI
>= 0);
1137 // Do not switch if a window is modal
1138 if (windows
.get(activeWindowI
).isModal()) {
1144 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1146 if (activeWindowI
== 0) {
1147 nextWindowI
= windows
.size() - 1;
1149 nextWindowI
= activeWindowI
- 1;
1152 windows
.get(activeWindowI
).setActive(false);
1153 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1154 windows
.get(nextWindowI
).setZ(0);
1155 windows
.get(nextWindowI
).setActive(true);
1157 } // synchronized (windows)
1162 * Add a window to my window list and make it active.
1164 * @param window new window to add
1166 public final void addWindow(final TWindow window
) {
1167 synchronized (windows
) {
1168 // Do not allow a modal window to spawn a non-modal window
1169 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1170 assert (window
.isModal());
1172 for (TWindow w
: windows
) {
1174 w
.setZ(w
.getZ() + 1);
1176 windows
.add(window
);
1177 window
.setActive(true);
1183 * Check if there is a system-modal window on top.
1185 * @return true if the active window is modal
1187 private boolean modalWindowActive() {
1188 if (windows
.size() == 0) {
1191 return windows
.get(windows
.size() - 1).isModal();
1195 * Check if a mouse event would hit either the active menu or any open
1198 * @param mouse mouse event
1199 * @return true if the mouse would hit the active menu or an open
1202 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1203 assert (activeMenu
!= null);
1204 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1205 Collections
.reverse(menus
);
1206 for (TMenu menu
: menus
) {
1207 if (menu
.mouseWouldHit(mouse
)) {
1211 return activeMenu
.mouseWouldHit(mouse
);
1215 * See if we need to switch window or activate the menu based on
1218 * @param mouse mouse event
1220 private void checkSwitchFocus(final TMouseEvent mouse
) {
1222 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1223 && (activeMenu
!= null)
1224 && (mouse
.getAbsoluteY() != 0)
1225 && (!mouseOnMenu(mouse
))
1227 // They clicked outside the active menu, turn it off
1228 activeMenu
.setActive(false);
1230 for (TMenu menu
: subMenus
) {
1231 menu
.setActive(false);
1237 // See if they hit the menu bar
1238 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1239 && (mouse
.isMouse1())
1240 && (!modalWindowActive())
1241 && (mouse
.getAbsoluteY() == 0)
1244 for (TMenu menu
: subMenus
) {
1245 menu
.setActive(false);
1249 // They selected the menu, go activate it
1250 for (TMenu menu
: menus
) {
1251 if ((mouse
.getAbsoluteX() >= menu
.getX())
1252 && (mouse
.getAbsoluteX() < menu
.getX()
1253 + menu
.getTitle().length() + 2)
1255 menu
.setActive(true);
1258 menu
.setActive(false);
1264 // See if they hit the menu bar
1265 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1266 && (mouse
.isMouse1())
1267 && (activeMenu
!= null)
1268 && (mouse
.getAbsoluteY() == 0)
1271 TMenu oldMenu
= activeMenu
;
1272 for (TMenu menu
: subMenus
) {
1273 menu
.setActive(false);
1277 // See if we should switch menus
1278 for (TMenu menu
: menus
) {
1279 if ((mouse
.getAbsoluteX() >= menu
.getX())
1280 && (mouse
.getAbsoluteX() < menu
.getX()
1281 + menu
.getTitle().length() + 2)
1283 menu
.setActive(true);
1287 if (oldMenu
!= activeMenu
) {
1288 // They switched menus
1289 oldMenu
.setActive(false);
1294 // Only switch if there are multiple windows
1295 if (windows
.size() < 2) {
1299 // Switch on the upclick
1300 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1304 synchronized (windows
) {
1305 Collections
.sort(windows
);
1306 if (windows
.get(0).isModal()) {
1307 // Modal windows don't switch
1311 for (TWindow window
: windows
) {
1312 assert (!window
.isModal());
1313 if (window
.mouseWouldHit(mouse
)) {
1314 if (window
== windows
.get(0)) {
1315 // Clicked on the same window, nothing to do
1319 // We will be switching to another window
1320 assert (windows
.get(0).isActive());
1321 assert (!window
.isActive());
1322 windows
.get(0).setActive(false);
1323 windows
.get(0).setZ(window
.getZ());
1325 window
.setActive(true);
1331 // Clicked on the background, nothing to do
1336 * Turn off the menu.
1338 public final void closeMenu() {
1339 if (activeMenu
!= null) {
1340 activeMenu
.setActive(false);
1342 for (TMenu menu
: subMenus
) {
1343 menu
.setActive(false);
1350 * Turn off a sub-menu.
1352 public final void closeSubMenu() {
1353 assert (activeMenu
!= null);
1354 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1355 assert (item
!= null);
1356 item
.setActive(false);
1357 subMenus
.remove(subMenus
.size() - 1);
1361 * Switch to the next menu.
1363 * @param forward if true, then switch to the next menu in the list,
1364 * otherwise switch to the previous menu in the list
1366 public final void switchMenu(final boolean forward
) {
1367 assert (activeMenu
!= null);
1369 for (TMenu menu
: subMenus
) {
1370 menu
.setActive(false);
1374 for (int i
= 0; i
< menus
.size(); i
++) {
1375 if (activeMenu
== menus
.get(i
)) {
1377 if (i
< menus
.size() - 1) {
1385 activeMenu
.setActive(false);
1386 activeMenu
= menus
.get(i
);
1387 activeMenu
.setActive(true);
1394 * Method that TApplication subclasses can override to handle menu or
1395 * posted command events.
1397 * @param command command event
1398 * @return if true, this event was consumed
1400 protected boolean onCommand(final TCommandEvent command
) {
1401 // Default: handle cmExit
1402 if (command
.equals(cmExit
)) {
1403 if (messageBox("Confirmation", "Exit application?",
1404 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1410 if (command
.equals(cmShell
)) {
1411 openTerminal(0, 0, TWindow
.RESIZABLE
);
1415 if (command
.equals(cmTile
)) {
1419 if (command
.equals(cmCascade
)) {
1423 if (command
.equals(cmCloseAll
)) {
1432 * Method that TApplication subclasses can override to handle menu
1435 * @param menu menu event
1436 * @return if true, this event was consumed
1438 protected boolean onMenu(final TMenuEvent menu
) {
1440 // Default: handle MID_EXIT
1441 if (menu
.getId() == TMenu
.MID_EXIT
) {
1442 if (messageBox("Confirmation", "Exit application?",
1443 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1449 if (menu
.getId() == TMenu
.MID_SHELL
) {
1450 openTerminal(0, 0, TWindow
.RESIZABLE
);
1454 if (menu
.getId() == TMenu
.MID_TILE
) {
1458 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1462 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1470 * Method that TApplication subclasses can override to handle keystrokes.
1472 * @param keypress keystroke event
1473 * @return if true, this event was consumed
1475 protected boolean onKeypress(final TKeypressEvent keypress
) {
1476 // Default: only menu shortcuts
1478 // Process Alt-F, Alt-E, etc. menu shortcut keys
1479 if (!keypress
.getKey().isFnKey()
1480 && keypress
.getKey().isAlt()
1481 && !keypress
.getKey().isCtrl()
1482 && (activeMenu
== null)
1485 assert (subMenus
.size() == 0);
1487 for (TMenu menu
: menus
) {
1488 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1489 == Character
.toLowerCase(keypress
.getKey().getChar())
1492 menu
.setActive(true);
1502 * Add a keyboard accelerator to the global hash.
1504 * @param item menu item this accelerator relates to
1505 * @param keypress keypress that will dispatch a TMenuEvent
1507 public final void addAccelerator(final TMenuItem item
,
1508 final TKeypress keypress
) {
1510 synchronized (accelerators
) {
1511 assert (accelerators
.get(keypress
) == null);
1512 accelerators
.put(keypress
, item
);
1517 * Recompute menu x positions based on their title length.
1519 public final void recomputeMenuX() {
1521 for (TMenu menu
: menus
) {
1523 x
+= menu
.getTitle().length() + 2;
1528 * Post an event to process and turn off the menu.
1530 * @param event new event to add to the queue
1532 public final void addMenuEvent(final TInputEvent event
) {
1533 synchronized (fillEventQueue
) {
1534 fillEventQueue
.add(event
);
1540 * Add a sub-menu to the list of open sub-menus.
1542 * @param menu sub-menu
1544 public final void addSubMenu(final TMenu menu
) {
1549 * Convenience function to add a top-level menu.
1551 * @param title menu title
1552 * @return the new menu
1554 public final TMenu
addMenu(final String title
) {
1557 TMenu menu
= new TMenu(this, x
, y
, title
);
1564 * Convenience function to add a default "File" menu.
1566 * @return the new menu
1568 public final TMenu
addFileMenu() {
1569 TMenu fileMenu
= addMenu("&File");
1570 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1571 fileMenu
.addSeparator();
1572 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1573 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1578 * Convenience function to add a default "Edit" menu.
1580 * @return the new menu
1582 public final TMenu
addEditMenu() {
1583 TMenu editMenu
= addMenu("&Edit");
1584 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1585 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1586 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1587 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1592 * Convenience function to add a default "Window" menu.
1594 * @return the new menu
1596 public final TMenu
addWindowMenu() {
1597 TMenu windowMenu
= addMenu("&Window");
1598 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1599 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1600 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1601 windowMenu
.addSeparator();
1602 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1603 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1604 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1605 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1606 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1611 * Close all open windows.
1613 private void closeAllWindows() {
1614 // Don't do anything if we are in the menu
1615 if (activeMenu
!= null) {
1619 synchronized (windows
) {
1620 for (TWindow window
: windows
) {
1621 closeWindow(window
);
1627 * Re-layout the open windows as non-overlapping tiles. This produces
1628 * almost the same results as Turbo Pascal 7.0's IDE.
1630 private void tileWindows() {
1631 synchronized (windows
) {
1632 // Don't do anything if we are in the menu
1633 if (activeMenu
!= null) {
1636 int z
= windows
.size();
1642 a
= (int)(Math
.sqrt(z
));
1646 if (((a
* b
) + c
) == z
) {
1654 int newWidth
= (getScreen().getWidth() / a
);
1655 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1656 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1658 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1659 Collections
.sort(sorted
);
1660 Collections
.reverse(sorted
);
1661 for (int i
= 0; i
< sorted
.size(); i
++) {
1662 int logicalX
= i
/ b
;
1663 int logicalY
= i
% b
;
1664 if (i
>= ((a
- 1) * b
)) {
1666 logicalY
= i
- ((a
- 1) * b
);
1669 TWindow w
= sorted
.get(i
);
1670 w
.setX(logicalX
* newWidth
);
1671 w
.setWidth(newWidth
);
1672 if (i
>= ((a
- 1) * b
)) {
1673 w
.setY((logicalY
* newHeight2
) + 1);
1674 w
.setHeight(newHeight2
);
1676 w
.setY((logicalY
* newHeight1
) + 1);
1677 w
.setHeight(newHeight1
);
1684 * Re-layout the open windows as overlapping cascaded windows.
1686 private void cascadeWindows() {
1687 synchronized (windows
) {
1688 // Don't do anything if we are in the menu
1689 if (activeMenu
!= null) {
1694 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1695 Collections
.sort(sorted
);
1696 Collections
.reverse(sorted
);
1697 for (TWindow window
: sorted
) {
1702 if (x
> getScreen().getWidth()) {
1705 if (y
>= getScreen().getHeight()) {
1713 * Convenience function to add a timer.
1715 * @param duration number of milliseconds to wait between ticks
1716 * @param recurring if true, re-schedule this timer after every tick
1717 * @param action function to call when button is pressed
1720 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1721 final TAction action
) {
1723 TTimer timer
= new TTimer(duration
, recurring
, action
);
1724 synchronized (timers
) {
1731 * Convenience function to remove a timer.
1733 * @param timer timer to remove
1735 public final void removeTimer(final TTimer timer
) {
1736 synchronized (timers
) {
1737 timers
.remove(timer
);
1742 * Convenience function to spawn a message box.
1744 * @param title window title, will be centered along the top border
1745 * @param caption message to display. Use embedded newlines to get a
1747 * @return the new message box
1749 public final TMessageBox
messageBox(final String title
,
1750 final String caption
) {
1752 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1756 * Convenience function to spawn a message box.
1758 * @param title window title, will be centered along the top border
1759 * @param caption message to display. Use embedded newlines to get a
1761 * @param type one of the TMessageBox.Type constants. Default is
1763 * @return the new message box
1765 public final TMessageBox
messageBox(final String title
,
1766 final String caption
, final TMessageBox
.Type type
) {
1768 return new TMessageBox(this, title
, caption
, type
);
1772 * Convenience function to spawn an input box.
1774 * @param title window title, will be centered along the top border
1775 * @param caption message to display. Use embedded newlines to get a
1777 * @return the new input box
1779 public final TInputBox
inputBox(final String title
, final String caption
) {
1781 return new TInputBox(this, title
, caption
);
1785 * Convenience function to spawn an input box.
1787 * @param title window title, will be centered along the top border
1788 * @param caption message to display. Use embedded newlines to get a
1790 * @param text initial text to seed the field with
1791 * @return the new input box
1793 public final TInputBox
inputBox(final String title
, final String caption
,
1794 final String text
) {
1796 return new TInputBox(this, title
, caption
, text
);
1800 * Convenience function to open a terminal window.
1802 * @param x column relative to parent
1803 * @param y row relative to parent
1804 * @return the terminal new window
1806 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1807 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1811 * Convenience function to open a terminal window.
1813 * @param x column relative to parent
1814 * @param y row relative to parent
1815 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1816 * @return the terminal new window
1818 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1821 return new TTerminalWindow(this, x
, y
, flags
);
1825 * Convenience function to spawn an file open box.
1827 * @param path path of selected file
1828 * @return the result of the new file open box
1830 public final String
fileOpenBox(final String path
) throws IOException
{
1832 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
1833 return box
.getFilename();
1837 * Convenience function to spawn an file open box.
1839 * @param path path of selected file
1840 * @param type one of the Type constants
1841 * @return the result of the new file open box
1843 public final String
fileOpenBox(final String path
,
1844 final TFileOpenBox
.Type type
) throws IOException
{
1846 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
1847 return box
.getFilename();