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
;
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);
526 * Public constructor. The backend type will be BackendType.ECMA48.
528 * @param input an InputStream connected to the remote user, or null for
529 * System.in. If System.in is used, then on non-Windows systems it will
530 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
531 * mode. input is always converted to a Reader with UTF-8 encoding.
532 * @param output an OutputStream connected to the remote user, or null
533 * for System.out. output is always converted to a Writer with UTF-8
535 * @throws UnsupportedEncodingException if an exception is thrown when
536 * creating the InputStreamReader
538 public TApplication(final InputStream input
,
539 final OutputStream output
) throws UnsupportedEncodingException
{
541 backend
= new ECMA48Backend(this, input
, output
);
546 * Public constructor. This hook enables use with new non-Jexer
549 * @param backend a Backend that is already ready to go.
551 public TApplication(final Backend backend
) {
552 this.backend
= backend
;
557 * Finish construction once the backend is set.
559 private void TApplicationImpl() {
560 theme
= new ColorTheme();
561 desktopBottom
= getScreen().getHeight() - 1;
562 fillEventQueue
= new ArrayList
<TInputEvent
>();
563 drainEventQueue
= new ArrayList
<TInputEvent
>();
564 windows
= new LinkedList
<TWindow
>();
565 menus
= new LinkedList
<TMenu
>();
566 subMenus
= new LinkedList
<TMenu
>();
567 timers
= new LinkedList
<TTimer
>();
568 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
569 menuItems
= new ArrayList
<TMenuItem
>();
571 // Setup the main consumer thread
572 primaryEventHandler
= new WidgetEventHandler(this, true);
573 (new Thread(primaryEventHandler
)).start();
577 * Invert the cell color at a position. This is used to track the mouse.
579 * @param x column position
580 * @param y row position
582 private void invertCell(final int x
, final int y
) {
583 synchronized (getScreen()) {
584 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
585 attr
.setForeColor(attr
.getForeColor().invert());
586 attr
.setBackColor(attr
.getBackColor().invert());
587 getScreen().putAttrXY(x
, y
, attr
, false);
594 private void drawAll() {
596 System
.err
.printf("drawAll() enter\n");
600 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
601 // The only thing that has happened is the mouse moved.
602 // Clear the old position and draw the new position.
603 invertCell(oldMouseX
, oldMouseY
);
604 invertCell(mouseX
, mouseY
);
608 if (getScreen().isDirty()) {
609 backend
.flushScreen();
615 System
.err
.printf("drawAll() REDRAW\n");
618 // If true, the cursor is not visible
619 boolean cursor
= false;
621 // Start with a clean screen
624 // Draw the background
625 CellAttributes background
= theme
.getColor("tapplication.background");
626 getScreen().putAll(GraphicsChars
.HATCH
, background
);
628 // Draw each window in reverse Z order
629 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
630 Collections
.sort(sorted
);
631 Collections
.reverse(sorted
);
632 for (TWindow window
: sorted
) {
633 window
.drawChildren();
636 // Draw the blank menubar line - reset the screen clipping first so
637 // it won't trim it out.
638 getScreen().resetClipping();
639 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
640 theme
.getColor("tmenu"));
641 // Now draw the menus.
643 for (TMenu menu
: menus
) {
644 CellAttributes menuColor
;
645 CellAttributes menuMnemonicColor
;
646 if (menu
.isActive()) {
647 menuColor
= theme
.getColor("tmenu.highlighted");
648 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
650 menuColor
= theme
.getColor("tmenu");
651 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
653 // Draw the menu title
654 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
656 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
657 // Draw the highlight character
658 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
659 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
661 if (menu
.isActive()) {
663 // Reset the screen clipping so we can draw the next title.
664 getScreen().resetClipping();
666 x
+= menu
.getTitle().length() + 2;
669 for (TMenu menu
: subMenus
) {
670 // Reset the screen clipping so we can draw the next sub-menu.
671 getScreen().resetClipping();
675 // Draw the mouse pointer
676 invertCell(mouseX
, mouseY
);
678 // Place the cursor if it is visible
679 TWidget activeWidget
= null;
680 if (sorted
.size() > 0) {
681 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
682 if (activeWidget
.isCursorVisible()) {
683 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
684 activeWidget
.getCursorAbsoluteY());
691 getScreen().hideCursor();
694 // Flush the screen contents
695 backend
.flushScreen();
701 * Run this application until it exits.
705 // Timeout is in milliseconds, so default timeout after 1 second
709 // If I've got no updates to render, wait for something from the
710 // backend or a timer.
712 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
714 // Never sleep longer than 50 millis. We need time for
715 // windows with background tasks to update the display, and
716 // still flip buffers reasonably quickly in
717 // backend.flushPhysical().
718 timeout
= getSleepTime(50);
722 // As of now, I've got nothing to do: no I/O, nothing from
723 // the consumer threads, no timers that need to run ASAP. So
724 // wait until either the backend or the consumer threads have
727 synchronized (this) {
730 } catch (InterruptedException e
) {
731 // I'm awake and don't care why, let's see what's going
737 // Prevent stepping on the primary or secondary event handler.
740 // Pull any pending I/O events
741 backend
.getEvents(fillEventQueue
);
743 // Dispatch each event to the appropriate handler, one at a time.
745 TInputEvent event
= null;
746 if (fillEventQueue
.size() == 0) {
749 event
= fillEventQueue
.remove(0);
750 metaHandleEvent(event
);
753 // Wake a consumer thread if we have any pending events.
754 if (drainEventQueue
.size() > 0) {
758 // Process timers and call doIdle()'s
762 synchronized (getScreen()) {
766 // Let the event handlers run again.
767 startEventHandlers();
771 // Shutdown the event consumer threads
772 if (secondaryEventHandler
!= null) {
773 synchronized (secondaryEventHandler
) {
774 secondaryEventHandler
.notify();
777 if (primaryEventHandler
!= null) {
778 synchronized (primaryEventHandler
) {
779 primaryEventHandler
.notify();
783 // Shutdown the user I/O thread(s)
786 // Close all the windows. This gives them an opportunity to release
793 * Peek at certain application-level events, add to eventQueue, and wake
794 * up the consuming Thread.
796 * @param event the input event to consume
798 private void metaHandleEvent(final TInputEvent event
) {
801 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
802 event
)); System
.err
.flush();
806 // Do no more processing if the application is already trying
811 // Special application-wide events -------------------------------
814 if (event
instanceof TCommandEvent
) {
815 TCommandEvent command
= (TCommandEvent
) event
;
816 if (command
.getCmd().equals(cmAbort
)) {
823 if (event
instanceof TResizeEvent
) {
824 TResizeEvent resize
= (TResizeEvent
) event
;
825 synchronized (getScreen()) {
826 getScreen().setDimensions(resize
.getWidth(),
828 desktopBottom
= getScreen().getHeight() - 1;
837 // Peek at the mouse position
838 if (event
instanceof TMouseEvent
) {
839 TMouseEvent mouse
= (TMouseEvent
) event
;
840 synchronized (getScreen()) {
841 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
844 mouseX
= mouse
.getX();
845 mouseY
= mouse
.getY();
850 // Put into the main queue
851 drainEventQueue
.add(event
);
855 * Dispatch one event to the appropriate widget or application-level
856 * event handler. This is the primary event handler, it has the normal
857 * application-wide event handling.
859 * @param event the input event to consume
860 * @see #secondaryHandleEvent(TInputEvent event)
862 private void primaryHandleEvent(final TInputEvent event
) {
865 System
.err
.printf("Handle event: %s\n", event
);
868 // Special application-wide events -----------------------------------
870 // Peek at the mouse position
871 if (event
instanceof TMouseEvent
) {
872 // See if we need to switch focus to another window or the menu
873 checkSwitchFocus((TMouseEvent
) event
);
876 // Handle menu events
877 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
878 TMenu menu
= activeMenu
;
880 if (event
instanceof TMouseEvent
) {
881 TMouseEvent mouse
= (TMouseEvent
) event
;
883 while (subMenus
.size() > 0) {
884 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
885 if (subMenu
.mouseWouldHit(mouse
)) {
888 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
889 && (!mouse
.isMouse1())
890 && (!mouse
.isMouse2())
891 && (!mouse
.isMouse3())
892 && (!mouse
.isMouseWheelUp())
893 && (!mouse
.isMouseWheelDown())
897 // We navigated away from a sub-menu, so close it
901 // Convert the mouse relative x/y to menu coordinates
902 assert (mouse
.getX() == mouse
.getAbsoluteX());
903 assert (mouse
.getY() == mouse
.getAbsoluteY());
904 if (subMenus
.size() > 0) {
905 menu
= subMenus
.get(subMenus
.size() - 1);
907 mouse
.setX(mouse
.getX() - menu
.getX());
908 mouse
.setY(mouse
.getY() - menu
.getY());
910 menu
.handleEvent(event
);
914 if (event
instanceof TKeypressEvent
) {
915 TKeypressEvent keypress
= (TKeypressEvent
) event
;
917 // See if this key matches an accelerator, and if so dispatch the
919 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
920 TMenuItem item
= null;
921 synchronized (accelerators
) {
922 item
= accelerators
.get(keypressLowercase
);
925 if (item
.isEnabled()) {
926 // Let the menu item dispatch
931 // Handle the keypress
932 if (onKeypress(keypress
)) {
937 if (event
instanceof TCommandEvent
) {
938 if (onCommand((TCommandEvent
) event
)) {
943 if (event
instanceof TMenuEvent
) {
944 if (onMenu((TMenuEvent
) event
)) {
949 // Dispatch events to the active window -------------------------------
950 for (TWindow window
: windows
) {
951 if (window
.isActive()) {
952 if (event
instanceof TMouseEvent
) {
953 TMouseEvent mouse
= (TMouseEvent
) event
;
954 // Convert the mouse relative x/y to window coordinates
955 assert (mouse
.getX() == mouse
.getAbsoluteX());
956 assert (mouse
.getY() == mouse
.getAbsoluteY());
957 mouse
.setX(mouse
.getX() - window
.getX());
958 mouse
.setY(mouse
.getY() - window
.getY());
961 System
.err
.printf("TApplication dispatch event: %s\n",
964 window
.handleEvent(event
);
970 * Dispatch one event to the appropriate widget or application-level
971 * event handler. This is the secondary event handler used by certain
972 * special dialogs (currently TMessageBox and TFileOpenBox).
974 * @param event the input event to consume
975 * @see #primaryHandleEvent(TInputEvent event)
977 private void secondaryHandleEvent(final TInputEvent event
) {
978 secondaryEventReceiver
.handleEvent(event
);
982 * Enable a widget to override the primary event thread.
984 * @param widget widget that will receive events
986 public final void enableSecondaryEventReceiver(final TWidget widget
) {
987 assert (secondaryEventReceiver
== null);
988 assert (secondaryEventHandler
== null);
989 assert ((widget
instanceof TMessageBox
)
990 || (widget
instanceof TFileOpenBox
));
991 secondaryEventReceiver
= widget
;
992 secondaryEventHandler
= new WidgetEventHandler(this, false);
993 (new Thread(secondaryEventHandler
)).start();
997 * Yield to the secondary thread.
999 public final void yield() {
1000 assert (secondaryEventReceiver
!= null);
1001 // This is where we handoff the event handler lock from the primary
1002 // to secondary thread. We unlock here, and in a future loop the
1003 // secondary thread locks again. When it gives up, we have the
1004 // single lock back.
1005 boolean oldLock
= unlockHandleEvent();
1006 assert (oldLock
== true);
1008 while (secondaryEventReceiver
!= null) {
1009 synchronized (primaryEventHandler
) {
1011 primaryEventHandler
.wait();
1012 } catch (InterruptedException e
) {
1020 * Do stuff when there is no user input.
1022 private void doIdle() {
1024 System
.err
.printf("doIdle()\n");
1027 // Now run any timers that have timed out
1028 Date now
= new Date();
1029 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1030 for (TTimer timer
: timers
) {
1031 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1033 if (timer
.recurring
) {
1034 keepTimers
.add(timer
);
1037 keepTimers
.add(timer
);
1040 timers
= keepTimers
;
1043 for (TWindow window
: windows
) {
1049 * Get the amount of time I can sleep before missing a Timer tick.
1051 * @param timeout = initial (maximum) timeout in millis
1052 * @return number of milliseconds between now and the next timer event
1054 private long getSleepTime(final long timeout
) {
1055 Date now
= new Date();
1056 long nowTime
= now
.getTime();
1057 long sleepTime
= timeout
;
1058 for (TTimer timer
: timers
) {
1059 long nextTickTime
= timer
.getNextTick().getTime();
1060 if (nextTickTime
< nowTime
) {
1064 long timeDifference
= nextTickTime
- nowTime
;
1065 if (timeDifference
< sleepTime
) {
1066 sleepTime
= timeDifference
;
1069 assert (sleepTime
>= 0);
1070 assert (sleepTime
<= timeout
);
1075 * Close window. Note that the window's destructor is NOT called by this
1076 * method, instead the GC is assumed to do the cleanup.
1078 * @param window the window to remove
1080 public final void closeWindow(final TWindow window
) {
1081 synchronized (windows
) {
1082 int z
= window
.getZ();
1085 Collections
.sort(windows
);
1087 TWindow activeWindow
= null;
1088 for (TWindow w
: windows
) {
1090 w
.setZ(w
.getZ() - 1);
1091 if (w
.getZ() == 0) {
1094 assert (activeWindow
== null);
1106 // Perform window cleanup
1109 // Check if we are closing a TMessageBox or similar
1110 if (secondaryEventReceiver
!= null) {
1111 assert (secondaryEventHandler
!= null);
1113 // Do not send events to the secondaryEventReceiver anymore, the
1114 // window is closed.
1115 secondaryEventReceiver
= null;
1117 // Wake the secondary thread, it will wake the primary as it
1119 synchronized (secondaryEventHandler
) {
1120 secondaryEventHandler
.notify();
1126 * Switch to the next window.
1128 * @param forward if true, then switch to the next window in the list,
1129 * otherwise switch to the previous window in the list
1131 public final void switchWindow(final boolean forward
) {
1132 // Only switch if there are multiple windows
1133 if (windows
.size() < 2) {
1137 synchronized (windows
) {
1139 // Swap z/active between active window and the next in the list
1140 int activeWindowI
= -1;
1141 for (int i
= 0; i
< windows
.size(); i
++) {
1142 if (windows
.get(i
).isActive()) {
1147 assert (activeWindowI
>= 0);
1149 // Do not switch if a window is modal
1150 if (windows
.get(activeWindowI
).isModal()) {
1156 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1158 if (activeWindowI
== 0) {
1159 nextWindowI
= windows
.size() - 1;
1161 nextWindowI
= activeWindowI
- 1;
1164 windows
.get(activeWindowI
).setActive(false);
1165 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1166 windows
.get(activeWindowI
).onUnfocus();
1167 windows
.get(nextWindowI
).setZ(0);
1168 windows
.get(nextWindowI
).setActive(true);
1169 windows
.get(nextWindowI
).onFocus();
1171 } // synchronized (windows)
1176 * Add a window to my window list and make it active.
1178 * @param window new window to add
1180 public final void addWindow(final TWindow window
) {
1181 synchronized (windows
) {
1182 // Do not allow a modal window to spawn a non-modal window
1183 if ((windows
.size() > 0) && (windows
.get(0).isModal())) {
1184 assert (window
.isModal());
1186 for (TWindow w
: windows
) {
1191 w
.setZ(w
.getZ() + 1);
1193 windows
.add(window
);
1195 window
.setActive(true);
1201 * Check if there is a system-modal window on top.
1203 * @return true if the active window is modal
1205 private boolean modalWindowActive() {
1206 if (windows
.size() == 0) {
1209 return windows
.get(windows
.size() - 1).isModal();
1213 * Check if a mouse event would hit either the active menu or any open
1216 * @param mouse mouse event
1217 * @return true if the mouse would hit the active menu or an open
1220 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1221 assert (activeMenu
!= null);
1222 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1223 Collections
.reverse(menus
);
1224 for (TMenu menu
: menus
) {
1225 if (menu
.mouseWouldHit(mouse
)) {
1229 return activeMenu
.mouseWouldHit(mouse
);
1233 * See if we need to switch window or activate the menu based on
1236 * @param mouse mouse event
1238 private void checkSwitchFocus(final TMouseEvent mouse
) {
1240 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1241 && (activeMenu
!= null)
1242 && (mouse
.getAbsoluteY() != 0)
1243 && (!mouseOnMenu(mouse
))
1245 // They clicked outside the active menu, turn it off
1246 activeMenu
.setActive(false);
1248 for (TMenu menu
: subMenus
) {
1249 menu
.setActive(false);
1255 // See if they hit the menu bar
1256 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1257 && (mouse
.isMouse1())
1258 && (!modalWindowActive())
1259 && (mouse
.getAbsoluteY() == 0)
1262 for (TMenu menu
: subMenus
) {
1263 menu
.setActive(false);
1267 // They selected the menu, go activate it
1268 for (TMenu menu
: menus
) {
1269 if ((mouse
.getAbsoluteX() >= menu
.getX())
1270 && (mouse
.getAbsoluteX() < menu
.getX()
1271 + menu
.getTitle().length() + 2)
1273 menu
.setActive(true);
1276 menu
.setActive(false);
1282 // See if they hit the menu bar
1283 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1284 && (mouse
.isMouse1())
1285 && (activeMenu
!= null)
1286 && (mouse
.getAbsoluteY() == 0)
1289 TMenu oldMenu
= activeMenu
;
1290 for (TMenu menu
: subMenus
) {
1291 menu
.setActive(false);
1295 // See if we should switch menus
1296 for (TMenu menu
: menus
) {
1297 if ((mouse
.getAbsoluteX() >= menu
.getX())
1298 && (mouse
.getAbsoluteX() < menu
.getX()
1299 + menu
.getTitle().length() + 2)
1301 menu
.setActive(true);
1305 if (oldMenu
!= activeMenu
) {
1306 // They switched menus
1307 oldMenu
.setActive(false);
1312 // Only switch if there are multiple windows
1313 if (windows
.size() < 2) {
1317 // Switch on the upclick
1318 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1322 synchronized (windows
) {
1323 Collections
.sort(windows
);
1324 if (windows
.get(0).isModal()) {
1325 // Modal windows don't switch
1329 for (TWindow window
: windows
) {
1330 assert (!window
.isModal());
1331 if (window
.mouseWouldHit(mouse
)) {
1332 if (window
== windows
.get(0)) {
1333 // Clicked on the same window, nothing to do
1337 // We will be switching to another window
1338 assert (windows
.get(0).isActive());
1339 assert (!window
.isActive());
1340 windows
.get(0).onUnfocus();
1341 windows
.get(0).setActive(false);
1342 windows
.get(0).setZ(window
.getZ());
1344 window
.setActive(true);
1351 // Clicked on the background, nothing to do
1356 * Turn off the menu.
1358 public final void closeMenu() {
1359 if (activeMenu
!= null) {
1360 activeMenu
.setActive(false);
1362 for (TMenu menu
: subMenus
) {
1363 menu
.setActive(false);
1370 * Turn off a sub-menu.
1372 public final void closeSubMenu() {
1373 assert (activeMenu
!= null);
1374 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1375 assert (item
!= null);
1376 item
.setActive(false);
1377 subMenus
.remove(subMenus
.size() - 1);
1381 * Switch to the next menu.
1383 * @param forward if true, then switch to the next menu in the list,
1384 * otherwise switch to the previous menu in the list
1386 public final void switchMenu(final boolean forward
) {
1387 assert (activeMenu
!= null);
1389 for (TMenu menu
: subMenus
) {
1390 menu
.setActive(false);
1394 for (int i
= 0; i
< menus
.size(); i
++) {
1395 if (activeMenu
== menus
.get(i
)) {
1397 if (i
< menus
.size() - 1) {
1405 activeMenu
.setActive(false);
1406 activeMenu
= menus
.get(i
);
1407 activeMenu
.setActive(true);
1414 * Method that TApplication subclasses can override to handle menu or
1415 * posted command events.
1417 * @param command command event
1418 * @return if true, this event was consumed
1420 protected boolean onCommand(final TCommandEvent command
) {
1421 // Default: handle cmExit
1422 if (command
.equals(cmExit
)) {
1423 if (messageBox("Confirmation", "Exit application?",
1424 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1430 if (command
.equals(cmShell
)) {
1431 openTerminal(0, 0, TWindow
.RESIZABLE
);
1435 if (command
.equals(cmTile
)) {
1439 if (command
.equals(cmCascade
)) {
1443 if (command
.equals(cmCloseAll
)) {
1452 * Method that TApplication subclasses can override to handle menu
1455 * @param menu menu event
1456 * @return if true, this event was consumed
1458 protected boolean onMenu(final TMenuEvent menu
) {
1460 // Default: handle MID_EXIT
1461 if (menu
.getId() == TMenu
.MID_EXIT
) {
1462 if (messageBox("Confirmation", "Exit application?",
1463 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1469 if (menu
.getId() == TMenu
.MID_SHELL
) {
1470 openTerminal(0, 0, TWindow
.RESIZABLE
);
1474 if (menu
.getId() == TMenu
.MID_TILE
) {
1478 if (menu
.getId() == TMenu
.MID_CASCADE
) {
1482 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
1490 * Method that TApplication subclasses can override to handle keystrokes.
1492 * @param keypress keystroke event
1493 * @return if true, this event was consumed
1495 protected boolean onKeypress(final TKeypressEvent keypress
) {
1496 // Default: only menu shortcuts
1498 // Process Alt-F, Alt-E, etc. menu shortcut keys
1499 if (!keypress
.getKey().isFnKey()
1500 && keypress
.getKey().isAlt()
1501 && !keypress
.getKey().isCtrl()
1502 && (activeMenu
== null)
1505 assert (subMenus
.size() == 0);
1507 for (TMenu menu
: menus
) {
1508 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1509 == Character
.toLowerCase(keypress
.getKey().getChar())
1512 menu
.setActive(true);
1522 * Add a menu item to the global list. If it has a keyboard accelerator,
1523 * that will be added the global hash.
1525 * @param item the menu item
1527 public final void addMenuItem(final TMenuItem item
) {
1528 menuItems
.add(item
);
1530 TKeypress key
= item
.getKey();
1532 synchronized (accelerators
) {
1533 assert (accelerators
.get(key
) == null);
1534 accelerators
.put(key
.toLowerCase(), item
);
1540 * Disable one menu item.
1542 * @param id the menu item ID
1544 public final void disableMenuItem(final int id
) {
1545 for (TMenuItem item
: menuItems
) {
1546 if (item
.getId() == id
) {
1547 item
.setEnabled(false);
1553 * Disable the range of menu items with ID's between lower and upper,
1556 * @param lower the lowest menu item ID
1557 * @param upper the highest menu item ID
1559 public final void disableMenuItems(final int lower
, final int upper
) {
1560 for (TMenuItem item
: menuItems
) {
1561 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1562 item
.setEnabled(false);
1568 * Enable one menu item.
1570 * @param id the menu item ID
1572 public final void enableMenuItem(final int id
) {
1573 for (TMenuItem item
: menuItems
) {
1574 if (item
.getId() == id
) {
1575 item
.setEnabled(true);
1581 * Enable the range of menu items with ID's between lower and upper,
1584 * @param lower the lowest menu item ID
1585 * @param upper the highest menu item ID
1587 public final void enableMenuItems(final int lower
, final int upper
) {
1588 for (TMenuItem item
: menuItems
) {
1589 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1590 item
.setEnabled(true);
1596 * Recompute menu x positions based on their title length.
1598 public final void recomputeMenuX() {
1600 for (TMenu menu
: menus
) {
1602 x
+= menu
.getTitle().length() + 2;
1607 * Post an event to process and turn off the menu.
1609 * @param event new event to add to the queue
1611 public final void addMenuEvent(final TInputEvent event
) {
1612 synchronized (fillEventQueue
) {
1613 fillEventQueue
.add(event
);
1619 * Add a sub-menu to the list of open sub-menus.
1621 * @param menu sub-menu
1623 public final void addSubMenu(final TMenu menu
) {
1628 * Convenience function to add a top-level menu.
1630 * @param title menu title
1631 * @return the new menu
1633 public final TMenu
addMenu(final String title
) {
1636 TMenu menu
= new TMenu(this, x
, y
, title
);
1643 * Convenience function to add a default "File" menu.
1645 * @return the new menu
1647 public final TMenu
addFileMenu() {
1648 TMenu fileMenu
= addMenu("&File");
1649 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1650 fileMenu
.addSeparator();
1651 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1652 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1657 * Convenience function to add a default "Edit" menu.
1659 * @return the new menu
1661 public final TMenu
addEditMenu() {
1662 TMenu editMenu
= addMenu("&Edit");
1663 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1664 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1665 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1666 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1671 * Convenience function to add a default "Window" menu.
1673 * @return the new menu
1675 public final TMenu
addWindowMenu() {
1676 TMenu windowMenu
= addMenu("&Window");
1677 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1678 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1679 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1680 windowMenu
.addSeparator();
1681 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1682 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1683 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1684 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1685 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1690 * Close all open windows.
1692 private void closeAllWindows() {
1693 // Don't do anything if we are in the menu
1694 if (activeMenu
!= null) {
1698 synchronized (windows
) {
1699 for (TWindow window
: windows
) {
1700 closeWindow(window
);
1706 * Re-layout the open windows as non-overlapping tiles. This produces
1707 * almost the same results as Turbo Pascal 7.0's IDE.
1709 private void tileWindows() {
1710 synchronized (windows
) {
1711 // Don't do anything if we are in the menu
1712 if (activeMenu
!= null) {
1715 int z
= windows
.size();
1721 a
= (int)(Math
.sqrt(z
));
1725 if (((a
* b
) + c
) == z
) {
1733 int newWidth
= (getScreen().getWidth() / a
);
1734 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1735 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1737 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1738 Collections
.sort(sorted
);
1739 Collections
.reverse(sorted
);
1740 for (int i
= 0; i
< sorted
.size(); i
++) {
1741 int logicalX
= i
/ b
;
1742 int logicalY
= i
% b
;
1743 if (i
>= ((a
- 1) * b
)) {
1745 logicalY
= i
- ((a
- 1) * b
);
1748 TWindow w
= sorted
.get(i
);
1749 w
.setX(logicalX
* newWidth
);
1750 w
.setWidth(newWidth
);
1751 if (i
>= ((a
- 1) * b
)) {
1752 w
.setY((logicalY
* newHeight2
) + 1);
1753 w
.setHeight(newHeight2
);
1755 w
.setY((logicalY
* newHeight1
) + 1);
1756 w
.setHeight(newHeight1
);
1763 * Re-layout the open windows as overlapping cascaded windows.
1765 private void cascadeWindows() {
1766 synchronized (windows
) {
1767 // Don't do anything if we are in the menu
1768 if (activeMenu
!= null) {
1773 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1774 Collections
.sort(sorted
);
1775 Collections
.reverse(sorted
);
1776 for (TWindow window
: sorted
) {
1781 if (x
> getScreen().getWidth()) {
1784 if (y
>= getScreen().getHeight()) {
1792 * Convenience function to add a timer.
1794 * @param duration number of milliseconds to wait between ticks
1795 * @param recurring if true, re-schedule this timer after every tick
1796 * @param action function to call when button is pressed
1799 public final TTimer
addTimer(final long duration
, final boolean recurring
,
1800 final TAction action
) {
1802 TTimer timer
= new TTimer(duration
, recurring
, action
);
1803 synchronized (timers
) {
1810 * Convenience function to remove a timer.
1812 * @param timer timer to remove
1814 public final void removeTimer(final TTimer timer
) {
1815 synchronized (timers
) {
1816 timers
.remove(timer
);
1821 * Convenience function to spawn a message box.
1823 * @param title window title, will be centered along the top border
1824 * @param caption message to display. Use embedded newlines to get a
1826 * @return the new message box
1828 public final TMessageBox
messageBox(final String title
,
1829 final String caption
) {
1831 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
1835 * Convenience function to spawn a message box.
1837 * @param title window title, will be centered along the top border
1838 * @param caption message to display. Use embedded newlines to get a
1840 * @param type one of the TMessageBox.Type constants. Default is
1842 * @return the new message box
1844 public final TMessageBox
messageBox(final String title
,
1845 final String caption
, final TMessageBox
.Type type
) {
1847 return new TMessageBox(this, title
, caption
, type
);
1851 * Convenience function to spawn an input box.
1853 * @param title window title, will be centered along the top border
1854 * @param caption message to display. Use embedded newlines to get a
1856 * @return the new input box
1858 public final TInputBox
inputBox(final String title
, final String caption
) {
1860 return new TInputBox(this, title
, caption
);
1864 * Convenience function to spawn an input box.
1866 * @param title window title, will be centered along the top border
1867 * @param caption message to display. Use embedded newlines to get a
1869 * @param text initial text to seed the field with
1870 * @return the new input box
1872 public final TInputBox
inputBox(final String title
, final String caption
,
1873 final String text
) {
1875 return new TInputBox(this, title
, caption
, text
);
1879 * Convenience function to open a terminal window.
1881 * @param x column relative to parent
1882 * @param y row relative to parent
1883 * @return the terminal new window
1885 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
1886 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
1890 * Convenience function to open a terminal window.
1892 * @param x column relative to parent
1893 * @param y row relative to parent
1894 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1895 * @return the terminal new window
1897 public final TTerminalWindow
openTerminal(final int x
, final int y
,
1900 return new TTerminalWindow(this, x
, y
, flags
);
1904 * Convenience function to spawn an file open box.
1906 * @param path path of selected file
1907 * @return the result of the new file open box
1909 public final String
fileOpenBox(final String path
) throws IOException
{
1911 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
1912 return box
.getFilename();
1916 * Convenience function to spawn an file open box.
1918 * @param path path of selected file
1919 * @param type one of the Type constants
1920 * @return the result of the new file open box
1922 public final String
fileOpenBox(final String path
,
1923 final TFileOpenBox
.Type type
) throws IOException
{
1925 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
1926 return box
.getFilename();