2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2017 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
.event
.TCommandEvent
;
48 import jexer
.event
.TInputEvent
;
49 import jexer
.event
.TKeypressEvent
;
50 import jexer
.event
.TMenuEvent
;
51 import jexer
.event
.TMouseEvent
;
52 import jexer
.event
.TResizeEvent
;
53 import jexer
.backend
.Backend
;
54 import jexer
.backend
.SwingBackend
;
55 import jexer
.backend
.ECMA48Backend
;
56 import jexer
.io
.Screen
;
57 import jexer
.menu
.TMenu
;
58 import jexer
.menu
.TMenuItem
;
59 import static jexer
.TCommand
.*;
60 import static jexer
.TKeypress
.*;
63 * TApplication sets up a full Text User Interface application.
65 public class TApplication
implements Runnable
{
67 // ------------------------------------------------------------------------
68 // Public constants -------------------------------------------------------
69 // ------------------------------------------------------------------------
72 * If true, emit thread stuff to System.err.
74 private static final boolean debugThreads
= false;
77 * If true, emit events being processed to System.err.
79 private static final boolean debugEvents
= false;
82 * If true, do "smart placement" on new windows that are not specified to
85 private static final boolean smartWindowPlacement
= true;
88 * Two backend types are available.
90 public static enum BackendType
{
97 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
102 * Synonym for ECMA48.
107 // ------------------------------------------------------------------------
108 // Primary/secondary event handlers ---------------------------------------
109 // ------------------------------------------------------------------------
112 * WidgetEventHandler is the main event consumer loop. There are at most
113 * two such threads in existence: the primary for normal case and a
114 * secondary that is used for TMessageBox, TInputBox, and similar.
116 private class WidgetEventHandler
implements Runnable
{
118 * The main application.
120 private TApplication application
;
123 * Whether or not this WidgetEventHandler is the primary or secondary
126 private boolean primary
= true;
129 * Public constructor.
131 * @param application the main application
132 * @param primary if true, this is the primary event handler thread
134 public WidgetEventHandler(final TApplication application
,
135 final boolean primary
) {
137 this.application
= application
;
138 this.primary
= primary
;
147 while (!application
.quit
) {
149 // Wait until application notifies me
150 while (!application
.quit
) {
152 synchronized (application
.drainEventQueue
) {
153 if (application
.drainEventQueue
.size() > 0) {
158 synchronized (this) {
160 System
.err
.printf("%s %s sleep\n", this,
161 primary ?
"primary" : "secondary");
167 System
.err
.printf("%s %s AWAKE\n", this,
168 primary ?
"primary" : "secondary");
172 && (application
.secondaryEventReceiver
== null)
174 // Secondary thread, emergency exit. If we
175 // got here then something went wrong with
176 // the handoff between yield() and
178 synchronized (application
.primaryEventHandler
) {
179 application
.primaryEventHandler
.notify();
181 application
.secondaryEventHandler
= null;
182 throw new RuntimeException(
183 "secondary exited at wrong time");
187 } catch (InterruptedException e
) {
192 // Wait for drawAll() or doIdle() to be done, then handle the
194 boolean oldLock
= lockHandleEvent();
195 assert (oldLock
== false);
197 // Pull all events off the queue
199 TInputEvent event
= null;
200 synchronized (application
.drainEventQueue
) {
201 if (application
.drainEventQueue
.size() == 0) {
204 event
= application
.drainEventQueue
.remove(0);
206 application
.repaint
= true;
208 primaryHandleEvent(event
);
210 secondaryHandleEvent(event
);
213 && (application
.secondaryEventReceiver
== null)
215 // Secondary thread, time to exit.
217 // DO NOT UNLOCK. Primary thread just came back from
218 // primaryHandleEvent() and will unlock in the else
219 // block below. Just wake it up.
220 synchronized (application
.primaryEventHandler
) {
221 application
.primaryEventHandler
.notify();
223 // Now eliminate my reference so that
224 // wakeEventHandler() resumes working on the primary.
225 application
.secondaryEventHandler
= null;
232 // Unlock. Either I am primary thread, or I am secondary
233 // thread and still running.
234 oldLock
= unlockHandleEvent();
235 assert (oldLock
== true);
237 // I have done some work of some kind. Tell the main run()
238 // loop to wake up now.
239 synchronized (application
) {
240 application
.notify();
243 } // while (true) (main runnable loop)
248 * The primary event handler thread.
250 private volatile WidgetEventHandler primaryEventHandler
;
253 * The secondary event handler thread.
255 private volatile WidgetEventHandler secondaryEventHandler
;
258 * The widget receiving events from the secondary event handler thread.
260 private volatile TWidget secondaryEventReceiver
;
263 * Spinlock for the primary and secondary event handlers.
264 * WidgetEventHandler.run() is responsible for setting this value.
266 private volatile boolean insideHandleEvent
= false;
269 * Wake the sleeping active event handler.
271 private void wakeEventHandler() {
272 if (secondaryEventHandler
!= null) {
273 synchronized (secondaryEventHandler
) {
274 secondaryEventHandler
.notify();
277 assert (primaryEventHandler
!= null);
278 synchronized (primaryEventHandler
) {
279 primaryEventHandler
.notify();
285 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
286 * spin indefinitely until unlockHandleEvent() is called.
288 * @return the old value of insideHandleEvent
290 private boolean lockHandleEvent() {
292 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
295 boolean oldValue
= true;
297 synchronized (this) {
298 // Wait for TApplication.run() to finish using the global state
299 // before allowing further event processing.
300 while (lockoutHandleEvent
== true) {
302 // Backoff so that the backend can finish its work.
304 } catch (InterruptedException e
) {
309 oldValue
= insideHandleEvent
;
310 insideHandleEvent
= true;
314 System
.err
.printf(" ***\n");
320 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
321 * spin indefinitely until unlockHandleEvent() is called.
323 * @return the old value of insideHandleEvent
325 private boolean unlockHandleEvent() {
327 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
330 synchronized (this) {
331 boolean oldValue
= insideHandleEvent
;
332 insideHandleEvent
= false;
338 * Spinlock for the primary and secondary event handlers. When true, the
339 * event handlers will spinlock wait before calling handleEvent().
341 private volatile boolean lockoutHandleEvent
= false;
344 * TApplication.run() needs to be able rely on the global data structures
345 * being intact when calling doIdle() and drawAll(). Tell the event
346 * handlers to wait for an unlock before handling their events.
348 private void stopEventHandlers() {
350 System
.err
.printf(">> stopEventHandlers()");
353 lockoutHandleEvent
= true;
354 // Wait for the last event to finish processing before returning
355 // control to TApplication.run().
356 while (insideHandleEvent
== true) {
358 // Backoff so that the event handler can finish its work.
360 } catch (InterruptedException e
) {
366 System
.err
.printf(" XXX\n");
371 * TApplication.run() needs to be able rely on the global data structures
372 * being intact when calling doIdle() and drawAll(). Tell the event
373 * handlers that it is now OK to handle their events.
375 private void startEventHandlers() {
377 System
.err
.printf("<< startEventHandlers()\n");
379 lockoutHandleEvent
= false;
382 // ------------------------------------------------------------------------
383 // TApplication attributes ------------------------------------------------
384 // ------------------------------------------------------------------------
387 * Access to the physical screen, keyboard, and mouse.
389 private Backend backend
;
394 * @return the Backend
396 public final Backend
getBackend() {
405 public final Screen
getScreen() {
406 return backend
.getScreen();
410 * Actual mouse coordinate X.
415 * Actual mouse coordinate Y.
420 * Old version of mouse coordinate X.
422 private int oldMouseX
;
425 * Old version mouse coordinate Y.
427 private int oldMouseY
;
430 * Event queue that is filled by run().
432 private List
<TInputEvent
> fillEventQueue
;
435 * Event queue that will be drained by either primary or secondary
438 private List
<TInputEvent
> drainEventQueue
;
441 * Top-level menus in this application.
443 private List
<TMenu
> menus
;
446 * Stack of activated sub-menus in this application.
448 private List
<TMenu
> subMenus
;
451 * The currently active menu.
453 private TMenu activeMenu
= null;
456 * Active keyboard accelerators.
458 private Map
<TKeypress
, TMenuItem
> accelerators
;
463 private List
<TMenuItem
> menuItems
;
466 * Windows and widgets pull colors from this ColorTheme.
468 private ColorTheme theme
;
471 * Get the color theme.
475 public final ColorTheme
getTheme() {
480 * The top-level windows (but not menus).
482 private List
<TWindow
> windows
;
485 * The currently acive window.
487 private TWindow activeWindow
= null;
490 * Timers that are being ticked.
492 private List
<TTimer
> timers
;
495 * When true, exit the application.
497 private volatile boolean quit
= false;
500 * When true, repaint the entire screen.
502 private volatile boolean repaint
= true;
505 * Y coordinate of the top edge of the desktop. For now this is a
506 * constant. Someday it would be nice to have a multi-line menu or
509 private static final int desktopTop
= 1;
512 * Get Y coordinate of the top edge of the desktop.
514 * @return Y coordinate of the top edge of the desktop
516 public final int getDesktopTop() {
521 * Y coordinate of the bottom edge of the desktop.
523 private int desktopBottom
;
526 * Get Y coordinate of the bottom edge of the desktop.
528 * @return Y coordinate of the bottom edge of the desktop
530 public final int getDesktopBottom() {
531 return desktopBottom
;
535 * An optional TDesktop background window that is drawn underneath
538 private TDesktop desktop
;
541 * Set the TDesktop instance.
543 * @param desktop a TDesktop instance, or null to remove the one that is
546 public final void setDesktop(final TDesktop desktop
) {
547 if (this.desktop
!= null) {
548 this.desktop
.onClose();
550 this.desktop
= desktop
;
554 * Get the TDesktop instance.
556 * @return the desktop, or null if it is not set
558 public final TDesktop
getDesktop() {
563 * Get the current active window.
565 * @return the active window, or null if it is not set
567 public final TWindow
getActiveWindow() {
572 * Get the list of windows.
574 * @return a copy of the list of windows for this application
576 public final List
<TWindow
> getAllWindows() {
577 List
<TWindow
> result
= new LinkedList
<TWindow
>();
578 result
.addAll(windows
);
583 * If true, focus follows mouse: windows automatically raised if the
584 * mouse passes over them.
586 private boolean focusFollowsMouse
= false;
589 * Get focusFollowsMouse flag.
591 * @return true if focus follows mouse: windows automatically raised if
592 * the mouse passes over them
594 public boolean getFocusFollowsMouse() {
595 return focusFollowsMouse
;
599 * Set focusFollowsMouse flag.
601 * @param focusFollowsMouse if true, focus follows mouse: windows
602 * automatically raised if the mouse passes over them
604 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
605 this.focusFollowsMouse
= focusFollowsMouse
;
608 // ------------------------------------------------------------------------
609 // General behavior -------------------------------------------------------
610 // ------------------------------------------------------------------------
613 * Display the about dialog.
615 protected void showAboutDialog() {
616 messageBox("About", "Jexer Version " +
617 this.getClass().getPackage().getImplementationVersion(),
618 TMessageBox
.Type
.OK
);
621 // ------------------------------------------------------------------------
622 // Constructors -----------------------------------------------------------
623 // ------------------------------------------------------------------------
626 * Public constructor.
628 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
630 * @throws UnsupportedEncodingException if an exception is thrown when
631 * creating the InputStreamReader
633 public TApplication(final BackendType backendType
)
634 throws UnsupportedEncodingException
{
636 switch (backendType
) {
638 backend
= new SwingBackend(this);
643 backend
= new ECMA48Backend(this, null, null);
646 throw new IllegalArgumentException("Invalid backend type: "
653 * Public constructor. The backend type will be BackendType.ECMA48.
655 * @param input an InputStream connected to the remote user, or null for
656 * System.in. If System.in is used, then on non-Windows systems it will
657 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
658 * mode. input is always converted to a Reader with UTF-8 encoding.
659 * @param output an OutputStream connected to the remote user, or null
660 * for System.out. output is always converted to a Writer with UTF-8
662 * @throws UnsupportedEncodingException if an exception is thrown when
663 * creating the InputStreamReader
665 public TApplication(final InputStream input
,
666 final OutputStream output
) throws UnsupportedEncodingException
{
668 backend
= new ECMA48Backend(this, input
, output
);
673 * Public constructor. The backend type will be BackendType.ECMA48.
675 * @param input the InputStream underlying 'reader'. Its available()
676 * method is used to determine if reader.read() will block or not.
677 * @param reader a Reader connected to the remote user.
678 * @param writer a PrintWriter connected to the remote user.
679 * @param setRawMode if true, set System.in into raw mode with stty.
680 * This should in general not be used. It is here solely for Demo3,
681 * which uses System.in.
682 * @throws IllegalArgumentException if input, reader, or writer are null.
684 public TApplication(final InputStream input
, final Reader reader
,
685 final PrintWriter writer
, final boolean setRawMode
) {
687 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
692 * Public constructor. The backend type will be BackendType.ECMA48.
694 * @param input the InputStream underlying 'reader'. Its available()
695 * method is used to determine if reader.read() will block or not.
696 * @param reader a Reader connected to the remote user.
697 * @param writer a PrintWriter connected to the remote user.
698 * @throws IllegalArgumentException if input, reader, or writer are null.
700 public TApplication(final InputStream input
, final Reader reader
,
701 final PrintWriter writer
) {
703 this(input
, reader
, writer
, false);
707 * Public constructor. This hook enables use with new non-Jexer
710 * @param backend a Backend that is already ready to go.
712 public TApplication(final Backend backend
) {
713 this.backend
= backend
;
718 * Finish construction once the backend is set.
720 private void TApplicationImpl() {
721 theme
= new ColorTheme();
722 desktopBottom
= getScreen().getHeight() - 1;
723 fillEventQueue
= new ArrayList
<TInputEvent
>();
724 drainEventQueue
= new ArrayList
<TInputEvent
>();
725 windows
= new LinkedList
<TWindow
>();
726 menus
= new LinkedList
<TMenu
>();
727 subMenus
= new LinkedList
<TMenu
>();
728 timers
= new LinkedList
<TTimer
>();
729 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
730 menuItems
= new ArrayList
<TMenuItem
>();
731 desktop
= new TDesktop(this);
733 // Setup the main consumer thread
734 primaryEventHandler
= new WidgetEventHandler(this, true);
735 (new Thread(primaryEventHandler
)).start();
738 // ------------------------------------------------------------------------
739 // Screen refresh loop ----------------------------------------------------
740 // ------------------------------------------------------------------------
743 * Invert the cell color at a position. This is used to track the mouse.
745 * @param x column position
746 * @param y row position
748 private void invertCell(final int x
, final int y
) {
750 System
.err
.printf("invertCell() %d %d\n", x
, y
);
752 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
753 attr
.setForeColor(attr
.getForeColor().invert());
754 attr
.setBackColor(attr
.getBackColor().invert());
755 getScreen().putAttrXY(x
, y
, attr
, false);
761 private void drawAll() {
763 System
.err
.printf("drawAll() enter\n");
768 System
.err
.printf("drawAll() !repaint\n");
770 synchronized (getScreen()) {
771 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
772 // The only thing that has happened is the mouse moved.
773 // Clear the old position and draw the new position.
774 invertCell(oldMouseX
, oldMouseY
);
775 invertCell(mouseX
, mouseY
);
779 if (getScreen().isDirty()) {
780 backend
.flushScreen();
787 System
.err
.printf("drawAll() REDRAW\n");
790 // If true, the cursor is not visible
791 boolean cursor
= false;
793 // Start with a clean screen
797 if (desktop
!= null) {
798 desktop
.drawChildren();
801 // Draw each window in reverse Z order
802 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
803 Collections
.sort(sorted
);
804 TWindow topLevel
= null;
805 if (sorted
.size() > 0) {
806 topLevel
= sorted
.get(0);
808 Collections
.reverse(sorted
);
809 for (TWindow window
: sorted
) {
810 if (window
.isShown()) {
811 window
.drawChildren();
815 // Draw the blank menubar line - reset the screen clipping first so
816 // it won't trim it out.
817 getScreen().resetClipping();
818 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
819 theme
.getColor("tmenu"));
820 // Now draw the menus.
822 for (TMenu menu
: menus
) {
823 CellAttributes menuColor
;
824 CellAttributes menuMnemonicColor
;
825 if (menu
.isActive()) {
826 menuColor
= theme
.getColor("tmenu.highlighted");
827 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
830 menuColor
= theme
.getColor("tmenu");
831 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
833 // Draw the menu title
834 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
836 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
837 // Draw the highlight character
838 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
839 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
841 if (menu
.isActive()) {
843 // Reset the screen clipping so we can draw the next title.
844 getScreen().resetClipping();
846 x
+= menu
.getTitle().length() + 2;
849 for (TMenu menu
: subMenus
) {
850 // Reset the screen clipping so we can draw the next sub-menu.
851 getScreen().resetClipping();
855 // Draw the status bar of the top-level window
856 TStatusBar statusBar
= null;
857 if (topLevel
!= null) {
858 statusBar
= topLevel
.getStatusBar();
860 if (statusBar
!= null) {
861 getScreen().resetClipping();
862 statusBar
.setWidth(getScreen().getWidth());
863 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
866 CellAttributes barColor
= new CellAttributes();
867 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
868 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
872 // Draw the mouse pointer
873 invertCell(mouseX
, mouseY
);
877 // Place the cursor if it is visible
878 TWidget activeWidget
= null;
879 if (sorted
.size() > 0) {
880 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
881 if (activeWidget
.isCursorVisible()) {
882 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
883 activeWidget
.getCursorAbsoluteY());
890 getScreen().hideCursor();
893 // Flush the screen contents
894 if (getScreen().isDirty()) {
895 backend
.flushScreen();
901 // ------------------------------------------------------------------------
902 // Main loop --------------------------------------------------------------
903 // ------------------------------------------------------------------------
906 * Run this application until it exits.
910 // Timeout is in milliseconds, so default timeout after 1 second
914 // If I've got no updates to render, wait for something from the
915 // backend or a timer.
917 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
919 // Never sleep longer than 50 millis. We need time for
920 // windows with background tasks to update the display, and
921 // still flip buffers reasonably quickly in
922 // backend.flushPhysical().
923 timeout
= getSleepTime(50);
927 // As of now, I've got nothing to do: no I/O, nothing from
928 // the consumer threads, no timers that need to run ASAP. So
929 // wait until either the backend or the consumer threads have
933 System
.err
.println("sleep " + timeout
+ " millis");
935 synchronized (this) {
938 } catch (InterruptedException e
) {
939 // I'm awake and don't care why, let's see what's going
945 // Prevent stepping on the primary or secondary event handler.
948 // Pull any pending I/O events
949 backend
.getEvents(fillEventQueue
);
951 // Dispatch each event to the appropriate handler, one at a time.
953 TInputEvent event
= null;
954 if (fillEventQueue
.size() == 0) {
957 event
= fillEventQueue
.remove(0);
958 metaHandleEvent(event
);
961 // Wake a consumer thread if we have any pending events.
962 if (drainEventQueue
.size() > 0) {
966 // Process timers and call doIdle()'s
970 synchronized (getScreen()) {
974 // Let the event handlers run again.
975 startEventHandlers();
979 // Shutdown the event consumer threads
980 if (secondaryEventHandler
!= null) {
981 synchronized (secondaryEventHandler
) {
982 secondaryEventHandler
.notify();
985 if (primaryEventHandler
!= null) {
986 synchronized (primaryEventHandler
) {
987 primaryEventHandler
.notify();
991 // Shutdown the user I/O thread(s)
994 // Close all the windows. This gives them an opportunity to release
1001 * Peek at certain application-level events, add to eventQueue, and wake
1002 * up the consuming Thread.
1004 * @param event the input event to consume
1006 private void metaHandleEvent(final TInputEvent event
) {
1009 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1010 event
)); System
.err
.flush();
1014 // Do no more processing if the application is already trying
1019 // Special application-wide events -------------------------------
1022 if (event
instanceof TCommandEvent
) {
1023 TCommandEvent command
= (TCommandEvent
) event
;
1024 if (command
.getCmd().equals(cmAbort
)) {
1031 if (event
instanceof TResizeEvent
) {
1032 TResizeEvent resize
= (TResizeEvent
) event
;
1033 synchronized (getScreen()) {
1034 getScreen().setDimensions(resize
.getWidth(),
1035 resize
.getHeight());
1036 desktopBottom
= getScreen().getHeight() - 1;
1042 if (desktop
!= null) {
1043 desktop
.setDimensions(0, 0, resize
.getWidth(),
1044 resize
.getHeight() - 1);
1049 // Peek at the mouse position
1050 if (event
instanceof TMouseEvent
) {
1051 TMouseEvent mouse
= (TMouseEvent
) event
;
1052 synchronized (getScreen()) {
1053 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1056 mouseX
= mouse
.getX();
1057 mouseY
= mouse
.getY();
1062 // Put into the main queue
1063 drainEventQueue
.add(event
);
1067 * Dispatch one event to the appropriate widget or application-level
1068 * event handler. This is the primary event handler, it has the normal
1069 * application-wide event handling.
1071 * @param event the input event to consume
1072 * @see #secondaryHandleEvent(TInputEvent event)
1074 private void primaryHandleEvent(final TInputEvent event
) {
1077 System
.err
.printf("Handle event: %s\n", event
);
1080 // Special application-wide events -----------------------------------
1082 // Peek at the mouse position
1083 if (event
instanceof TMouseEvent
) {
1084 // See if we need to switch focus to another window or the menu
1085 checkSwitchFocus((TMouseEvent
) event
);
1088 // Handle menu events
1089 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1090 TMenu menu
= activeMenu
;
1092 if (event
instanceof TMouseEvent
) {
1093 TMouseEvent mouse
= (TMouseEvent
) event
;
1095 while (subMenus
.size() > 0) {
1096 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1097 if (subMenu
.mouseWouldHit(mouse
)) {
1100 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1101 && (!mouse
.isMouse1())
1102 && (!mouse
.isMouse2())
1103 && (!mouse
.isMouse3())
1104 && (!mouse
.isMouseWheelUp())
1105 && (!mouse
.isMouseWheelDown())
1109 // We navigated away from a sub-menu, so close it
1113 // Convert the mouse relative x/y to menu coordinates
1114 assert (mouse
.getX() == mouse
.getAbsoluteX());
1115 assert (mouse
.getY() == mouse
.getAbsoluteY());
1116 if (subMenus
.size() > 0) {
1117 menu
= subMenus
.get(subMenus
.size() - 1);
1119 mouse
.setX(mouse
.getX() - menu
.getX());
1120 mouse
.setY(mouse
.getY() - menu
.getY());
1122 menu
.handleEvent(event
);
1126 if (event
instanceof TKeypressEvent
) {
1127 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1129 // See if this key matches an accelerator, and is not being
1130 // shortcutted by the active window, and if so dispatch the menu
1132 boolean windowWillShortcut
= false;
1133 if (activeWindow
!= null) {
1134 assert (activeWindow
.isShown());
1135 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1136 // We do not process this key, it will be passed to the
1138 windowWillShortcut
= true;
1142 if (!windowWillShortcut
&& !modalWindowActive()) {
1143 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1144 TMenuItem item
= null;
1145 synchronized (accelerators
) {
1146 item
= accelerators
.get(keypressLowercase
);
1149 if (item
.isEnabled()) {
1150 // Let the menu item dispatch
1156 // Handle the keypress
1157 if (onKeypress(keypress
)) {
1163 if (event
instanceof TCommandEvent
) {
1164 if (onCommand((TCommandEvent
) event
)) {
1169 if (event
instanceof TMenuEvent
) {
1170 if (onMenu((TMenuEvent
) event
)) {
1175 // Dispatch events to the active window -------------------------------
1176 boolean dispatchToDesktop
= true;
1177 TWindow window
= activeWindow
;
1178 if (window
!= null) {
1179 assert (window
.isActive());
1180 assert (window
.isShown());
1181 if (event
instanceof TMouseEvent
) {
1182 TMouseEvent mouse
= (TMouseEvent
) event
;
1183 // Convert the mouse relative x/y to window coordinates
1184 assert (mouse
.getX() == mouse
.getAbsoluteX());
1185 assert (mouse
.getY() == mouse
.getAbsoluteY());
1186 mouse
.setX(mouse
.getX() - window
.getX());
1187 mouse
.setY(mouse
.getY() - window
.getY());
1189 if (window
.mouseWouldHit(mouse
)) {
1190 dispatchToDesktop
= false;
1192 } else if (event
instanceof TKeypressEvent
) {
1193 dispatchToDesktop
= false;
1197 System
.err
.printf("TApplication dispatch event: %s\n",
1200 window
.handleEvent(event
);
1202 if (dispatchToDesktop
) {
1203 // This event is fair game for the desktop to process.
1204 if (desktop
!= null) {
1205 desktop
.handleEvent(event
);
1211 * Dispatch one event to the appropriate widget or application-level
1212 * event handler. This is the secondary event handler used by certain
1213 * special dialogs (currently TMessageBox and TFileOpenBox).
1215 * @param event the input event to consume
1216 * @see #primaryHandleEvent(TInputEvent event)
1218 private void secondaryHandleEvent(final TInputEvent event
) {
1219 secondaryEventReceiver
.handleEvent(event
);
1223 * Enable a widget to override the primary event thread.
1225 * @param widget widget that will receive events
1227 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1228 assert (secondaryEventReceiver
== null);
1229 assert (secondaryEventHandler
== null);
1230 assert ((widget
instanceof TMessageBox
)
1231 || (widget
instanceof TFileOpenBox
));
1232 secondaryEventReceiver
= widget
;
1233 secondaryEventHandler
= new WidgetEventHandler(this, false);
1234 (new Thread(secondaryEventHandler
)).start();
1238 * Yield to the secondary thread.
1240 public final void yield() {
1241 assert (secondaryEventReceiver
!= null);
1242 // This is where we handoff the event handler lock from the primary
1243 // to secondary thread. We unlock here, and in a future loop the
1244 // secondary thread locks again. When it gives up, we have the
1245 // single lock back.
1246 boolean oldLock
= unlockHandleEvent();
1249 while (secondaryEventReceiver
!= null) {
1250 synchronized (primaryEventHandler
) {
1252 primaryEventHandler
.wait();
1253 } catch (InterruptedException e
) {
1261 * Do stuff when there is no user input.
1263 private void doIdle() {
1265 System
.err
.printf("doIdle()\n");
1268 // Now run any timers that have timed out
1269 Date now
= new Date();
1270 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1271 for (TTimer timer
: timers
) {
1272 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1274 if (timer
.recurring
) {
1275 keepTimers
.add(timer
);
1278 keepTimers
.add(timer
);
1281 timers
= keepTimers
;
1284 for (TWindow window
: windows
) {
1287 if (desktop
!= null) {
1292 // ------------------------------------------------------------------------
1293 // TWindow management -----------------------------------------------------
1294 // ------------------------------------------------------------------------
1297 * Return the total number of windows.
1299 * @return the total number of windows
1301 public final int windowCount() {
1302 return windows
.size();
1306 * Return the number of windows that are showing.
1308 * @return the number of windows that are showing on screen
1310 public final int shownWindowCount() {
1312 for (TWindow w
: windows
) {
1321 * Return the number of windows that are hidden.
1323 * @return the number of windows that are hidden
1325 public final int hiddenWindowCount() {
1327 for (TWindow w
: windows
) {
1336 * Check if a window instance is in this application's window list.
1338 * @param window window to look for
1339 * @return true if this window is in the list
1341 public final boolean hasWindow(final TWindow window
) {
1342 if (windows
.size() == 0) {
1345 for (TWindow w
: windows
) {
1347 assert (window
.getApplication() == this);
1355 * Activate a window: bring it to the top and have it receive events.
1357 * @param window the window to become the new active window
1359 public void activateWindow(final TWindow window
) {
1360 if (hasWindow(window
) == false) {
1362 * Someone has a handle to a window I don't have. Ignore this
1368 assert (windows
.size() > 0);
1370 if (window
.isHidden()) {
1371 // Unhiding will also activate.
1375 assert (window
.isShown());
1377 if (windows
.size() == 1) {
1378 assert (window
== windows
.get(0));
1379 if (activeWindow
== null) {
1380 activeWindow
= window
;
1382 activeWindow
.setActive(true);
1383 activeWindow
.onFocus();
1386 assert (window
.isActive());
1387 assert (activeWindow
== window
);
1391 if (activeWindow
== window
) {
1392 assert (window
.isActive());
1394 // Window is already active, do nothing.
1398 assert (!window
.isActive());
1399 if (activeWindow
!= null) {
1400 assert (activeWindow
.getZ() == 0);
1402 activeWindow
.onUnfocus();
1403 activeWindow
.setActive(false);
1404 activeWindow
.setZ(window
.getZ());
1406 activeWindow
= window
;
1407 activeWindow
.setZ(0);
1408 activeWindow
.setActive(true);
1409 activeWindow
.onFocus();
1416 * @param window the window to hide
1418 public void hideWindow(final TWindow window
) {
1419 if (hasWindow(window
) == false) {
1421 * Someone has a handle to a window I don't have. Ignore this
1427 assert (windows
.size() > 0);
1429 if (!window
.hidden
) {
1430 if (window
== activeWindow
) {
1431 if (shownWindowCount() > 1) {
1434 activeWindow
= null;
1435 window
.setActive(false);
1439 window
.hidden
= true;
1447 * @param window the window to show
1449 public void showWindow(final TWindow window
) {
1450 if (hasWindow(window
) == false) {
1452 * Someone has a handle to a window I don't have. Ignore this
1458 assert (windows
.size() > 0);
1460 if (window
.hidden
) {
1461 window
.hidden
= false;
1463 activateWindow(window
);
1468 * Close window. Note that the window's destructor is NOT called by this
1469 * method, instead the GC is assumed to do the cleanup.
1471 * @param window the window to remove
1473 public final void closeWindow(final TWindow window
) {
1474 if (hasWindow(window
) == false) {
1476 * Someone has a handle to a window I don't have. Ignore this
1482 synchronized (windows
) {
1483 int z
= window
.getZ();
1486 Collections
.sort(windows
);
1488 activeWindow
= null;
1489 for (TWindow w
: windows
) {
1491 w
.setZ(w
.getZ() - 1);
1492 if (w
.getZ() == 0) {
1495 assert (activeWindow
== null);
1507 // Perform window cleanup
1510 // Check if we are closing a TMessageBox or similar
1511 if (secondaryEventReceiver
!= null) {
1512 assert (secondaryEventHandler
!= null);
1514 // Do not send events to the secondaryEventReceiver anymore, the
1515 // window is closed.
1516 secondaryEventReceiver
= null;
1518 // Wake the secondary thread, it will wake the primary as it
1520 synchronized (secondaryEventHandler
) {
1521 secondaryEventHandler
.notify();
1525 // Permit desktop to be active if it is the only thing left.
1526 if (desktop
!= null) {
1527 if (windows
.size() == 0) {
1528 desktop
.setActive(true);
1534 * Switch to the next window.
1536 * @param forward if true, then switch to the next window in the list,
1537 * otherwise switch to the previous window in the list
1539 public final void switchWindow(final boolean forward
) {
1540 // Only switch if there are multiple visible windows
1541 if (shownWindowCount() < 2) {
1544 assert (activeWindow
!= null);
1546 synchronized (windows
) {
1548 // Swap z/active between active window and the next in the list
1549 int activeWindowI
= -1;
1550 for (int i
= 0; i
< windows
.size(); i
++) {
1551 if (windows
.get(i
) == activeWindow
) {
1552 assert (activeWindow
.isActive());
1556 assert (!windows
.get(0).isActive());
1559 assert (activeWindowI
>= 0);
1561 // Do not switch if a window is modal
1562 if (activeWindow
.isModal()) {
1566 int nextWindowI
= activeWindowI
;
1570 nextWindowI
%= windows
.size();
1573 if (nextWindowI
< 0) {
1574 nextWindowI
= windows
.size() - 1;
1578 if (windows
.get(nextWindowI
).isShown()) {
1579 activateWindow(windows
.get(nextWindowI
));
1583 } // synchronized (windows)
1588 * Add a window to my window list and make it active.
1590 * @param window new window to add
1592 public final void addWindow(final TWindow window
) {
1594 // Do not add menu windows to the window list.
1595 if (window
instanceof TMenu
) {
1599 // Do not add the desktop to the window list.
1600 if (window
instanceof TDesktop
) {
1604 synchronized (windows
) {
1605 // Do not allow a modal window to spawn a non-modal window. If a
1606 // modal window is active, then this window will become modal
1608 if (modalWindowActive()) {
1609 window
.flags
|= TWindow
.MODAL
;
1610 window
.flags
|= TWindow
.CENTERED
;
1611 window
.hidden
= false;
1613 if (window
.isShown()) {
1614 for (TWindow w
: windows
) {
1619 w
.setZ(w
.getZ() + 1);
1622 windows
.add(window
);
1623 if (window
.isShown()) {
1624 activeWindow
= window
;
1625 activeWindow
.setZ(0);
1626 activeWindow
.setActive(true);
1627 activeWindow
.onFocus();
1630 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1631 && smartWindowPlacement
) {
1633 doSmartPlacement(window
);
1637 // Desktop cannot be active over any other window.
1638 if (desktop
!= null) {
1639 desktop
.setActive(false);
1644 * Check if there is a system-modal window on top.
1646 * @return true if the active window is modal
1648 private boolean modalWindowActive() {
1649 if (windows
.size() == 0) {
1653 for (TWindow w
: windows
) {
1663 * Close all open windows.
1665 private void closeAllWindows() {
1666 // Don't do anything if we are in the menu
1667 if (activeMenu
!= null) {
1670 while (windows
.size() > 0) {
1671 closeWindow(windows
.get(0));
1676 * Re-layout the open windows as non-overlapping tiles. This produces
1677 * almost the same results as Turbo Pascal 7.0's IDE.
1679 private void tileWindows() {
1680 synchronized (windows
) {
1681 // Don't do anything if we are in the menu
1682 if (activeMenu
!= null) {
1685 int z
= windows
.size();
1691 a
= (int)(Math
.sqrt(z
));
1695 if (((a
* b
) + c
) == z
) {
1703 int newWidth
= (getScreen().getWidth() / a
);
1704 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1705 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1707 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1708 Collections
.sort(sorted
);
1709 Collections
.reverse(sorted
);
1710 for (int i
= 0; i
< sorted
.size(); i
++) {
1711 int logicalX
= i
/ b
;
1712 int logicalY
= i
% b
;
1713 if (i
>= ((a
- 1) * b
)) {
1715 logicalY
= i
- ((a
- 1) * b
);
1718 TWindow w
= sorted
.get(i
);
1719 w
.setX(logicalX
* newWidth
);
1720 w
.setWidth(newWidth
);
1721 if (i
>= ((a
- 1) * b
)) {
1722 w
.setY((logicalY
* newHeight2
) + 1);
1723 w
.setHeight(newHeight2
);
1725 w
.setY((logicalY
* newHeight1
) + 1);
1726 w
.setHeight(newHeight1
);
1733 * Re-layout the open windows as overlapping cascaded windows.
1735 private void cascadeWindows() {
1736 synchronized (windows
) {
1737 // Don't do anything if we are in the menu
1738 if (activeMenu
!= null) {
1743 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1744 Collections
.sort(sorted
);
1745 Collections
.reverse(sorted
);
1746 for (TWindow window
: sorted
) {
1751 if (x
> getScreen().getWidth()) {
1754 if (y
>= getScreen().getHeight()) {
1762 * Place a window to minimize its overlap with other windows.
1764 * @param window the window to place
1766 public final void doSmartPlacement(final TWindow window
) {
1767 // This is a pretty dumb algorithm, but seems to work. The hardest
1768 // part is computing these "overlap" values seeking a minimum average
1771 int yMin
= desktopTop
;
1772 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1773 int yMax
= desktopBottom
- window
.getHeight() + 1;
1781 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1782 // No work to do, bail out.
1786 // Compute the overlap matrix without the new window.
1787 int width
= getScreen().getWidth();
1788 int height
= getScreen().getHeight();
1789 int overlapMatrix
[][] = new int[width
][height
];
1790 for (TWindow w
: windows
) {
1794 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1798 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1802 overlapMatrix
[x
][y
]++;
1807 long oldOverlapTotal
= 0;
1808 long oldOverlapN
= 0;
1809 for (int x
= 0; x
< width
; x
++) {
1810 for (int y
= 0; y
< height
; y
++) {
1811 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1812 if (overlapMatrix
[x
][y
] > 0) {
1819 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1820 boolean first
= true;
1821 int windowX
= window
.getX();
1822 int windowY
= window
.getY();
1824 // For each possible (x, y) position for the new window, compute a
1825 // new overlap matrix.
1826 for (int x
= xMin
; x
< xMax
; x
++) {
1827 for (int y
= yMin
; y
< yMax
; y
++) {
1829 // Start with the matrix minus this window.
1830 int newMatrix
[][] = new int[width
][height
];
1831 for (int mx
= 0; mx
< width
; mx
++) {
1832 for (int my
= 0; my
< height
; my
++) {
1833 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1837 // Add this window's values to the new overlap matrix.
1838 long newOverlapTotal
= 0;
1839 long newOverlapN
= 0;
1840 // Start by adding each new cell.
1841 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1845 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1849 newMatrix
[wx
][wy
]++;
1852 // Now figure out the new value for total coverage.
1853 for (int mx
= 0; mx
< width
; mx
++) {
1854 for (int my
= 0; my
< height
; my
++) {
1855 newOverlapTotal
+= newMatrix
[x
][y
];
1856 if (newMatrix
[mx
][my
] > 0) {
1861 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1864 // First time: just record what we got.
1865 oldOverlapAvg
= newOverlapAvg
;
1868 // All other times: pick a new best (x, y) and save the
1870 if (newOverlapAvg
< oldOverlapAvg
) {
1873 oldOverlapAvg
= newOverlapAvg
;
1877 } // for (int x = xMin; x < xMax; x++)
1879 } // for (int y = yMin; y < yMax; y++)
1881 // Finally, set the window's new coordinates.
1882 window
.setX(windowX
);
1883 window
.setY(windowY
);
1886 // ------------------------------------------------------------------------
1887 // TMenu management -------------------------------------------------------
1888 // ------------------------------------------------------------------------
1891 * Check if a mouse event would hit either the active menu or any open
1894 * @param mouse mouse event
1895 * @return true if the mouse would hit the active menu or an open
1898 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1899 assert (activeMenu
!= null);
1900 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1901 Collections
.reverse(menus
);
1902 for (TMenu menu
: menus
) {
1903 if (menu
.mouseWouldHit(mouse
)) {
1907 return activeMenu
.mouseWouldHit(mouse
);
1911 * See if we need to switch window or activate the menu based on
1914 * @param mouse mouse event
1916 private void checkSwitchFocus(final TMouseEvent mouse
) {
1918 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1919 && (activeMenu
!= null)
1920 && (mouse
.getAbsoluteY() != 0)
1921 && (!mouseOnMenu(mouse
))
1923 // They clicked outside the active menu, turn it off
1924 activeMenu
.setActive(false);
1926 for (TMenu menu
: subMenus
) {
1927 menu
.setActive(false);
1933 // See if they hit the menu bar
1934 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1935 && (mouse
.isMouse1())
1936 && (!modalWindowActive())
1937 && (mouse
.getAbsoluteY() == 0)
1940 for (TMenu menu
: subMenus
) {
1941 menu
.setActive(false);
1945 // They selected the menu, go activate it
1946 for (TMenu menu
: menus
) {
1947 if ((mouse
.getAbsoluteX() >= menu
.getX())
1948 && (mouse
.getAbsoluteX() < menu
.getX()
1949 + menu
.getTitle().length() + 2)
1951 menu
.setActive(true);
1954 menu
.setActive(false);
1960 // See if they hit the menu bar
1961 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1962 && (mouse
.isMouse1())
1963 && (activeMenu
!= null)
1964 && (mouse
.getAbsoluteY() == 0)
1967 TMenu oldMenu
= activeMenu
;
1968 for (TMenu menu
: subMenus
) {
1969 menu
.setActive(false);
1973 // See if we should switch menus
1974 for (TMenu menu
: menus
) {
1975 if ((mouse
.getAbsoluteX() >= menu
.getX())
1976 && (mouse
.getAbsoluteX() < menu
.getX()
1977 + menu
.getTitle().length() + 2)
1979 menu
.setActive(true);
1983 if (oldMenu
!= activeMenu
) {
1984 // They switched menus
1985 oldMenu
.setActive(false);
1990 // If a menu is still active, don't switch windows
1991 if (activeMenu
!= null) {
1995 // Only switch if there are multiple windows
1996 if (windows
.size() < 2) {
2000 if (((focusFollowsMouse
== true)
2001 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2002 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2004 synchronized (windows
) {
2005 Collections
.sort(windows
);
2006 if (windows
.get(0).isModal()) {
2007 // Modal windows don't switch
2011 for (TWindow window
: windows
) {
2012 assert (!window
.isModal());
2014 if (window
.isHidden()) {
2015 assert (!window
.isActive());
2019 if (window
.mouseWouldHit(mouse
)) {
2020 if (window
== windows
.get(0)) {
2021 // Clicked on the same window, nothing to do
2022 assert (window
.isActive());
2026 // We will be switching to another window
2027 assert (windows
.get(0).isActive());
2028 assert (windows
.get(0) == activeWindow
);
2029 assert (!window
.isActive());
2030 activeWindow
.onUnfocus();
2031 activeWindow
.setActive(false);
2032 activeWindow
.setZ(window
.getZ());
2033 activeWindow
= window
;
2035 window
.setActive(true);
2042 // Clicked on the background, nothing to do
2046 // Nothing to do: this isn't a mouse up, or focus isn't following
2052 * Turn off the menu.
2054 public final void closeMenu() {
2055 if (activeMenu
!= null) {
2056 activeMenu
.setActive(false);
2058 for (TMenu menu
: subMenus
) {
2059 menu
.setActive(false);
2066 * Turn off a sub-menu.
2068 public final void closeSubMenu() {
2069 assert (activeMenu
!= null);
2070 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2071 assert (item
!= null);
2072 item
.setActive(false);
2073 subMenus
.remove(subMenus
.size() - 1);
2077 * Switch to the next menu.
2079 * @param forward if true, then switch to the next menu in the list,
2080 * otherwise switch to the previous menu in the list
2082 public final void switchMenu(final boolean forward
) {
2083 assert (activeMenu
!= null);
2085 for (TMenu menu
: subMenus
) {
2086 menu
.setActive(false);
2090 for (int i
= 0; i
< menus
.size(); i
++) {
2091 if (activeMenu
== menus
.get(i
)) {
2093 if (i
< menus
.size() - 1) {
2101 activeMenu
.setActive(false);
2102 activeMenu
= menus
.get(i
);
2103 activeMenu
.setActive(true);
2110 * Add a menu item to the global list. If it has a keyboard accelerator,
2111 * that will be added the global hash.
2113 * @param item the menu item
2115 public final void addMenuItem(final TMenuItem item
) {
2116 menuItems
.add(item
);
2118 TKeypress key
= item
.getKey();
2120 synchronized (accelerators
) {
2121 assert (accelerators
.get(key
) == null);
2122 accelerators
.put(key
.toLowerCase(), item
);
2128 * Disable one menu item.
2130 * @param id the menu item ID
2132 public final void disableMenuItem(final int id
) {
2133 for (TMenuItem item
: menuItems
) {
2134 if (item
.getId() == id
) {
2135 item
.setEnabled(false);
2141 * Disable the range of menu items with ID's between lower and upper,
2144 * @param lower the lowest menu item ID
2145 * @param upper the highest menu item ID
2147 public final void disableMenuItems(final int lower
, final int upper
) {
2148 for (TMenuItem item
: menuItems
) {
2149 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2150 item
.setEnabled(false);
2156 * Enable one menu item.
2158 * @param id the menu item ID
2160 public final void enableMenuItem(final int id
) {
2161 for (TMenuItem item
: menuItems
) {
2162 if (item
.getId() == id
) {
2163 item
.setEnabled(true);
2169 * Enable the range of menu items with ID's between lower and upper,
2172 * @param lower the lowest menu item ID
2173 * @param upper the highest menu item ID
2175 public final void enableMenuItems(final int lower
, final int upper
) {
2176 for (TMenuItem item
: menuItems
) {
2177 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2178 item
.setEnabled(true);
2184 * Recompute menu x positions based on their title length.
2186 public final void recomputeMenuX() {
2188 for (TMenu menu
: menus
) {
2190 x
+= menu
.getTitle().length() + 2;
2195 * Post an event to process and turn off the menu.
2197 * @param event new event to add to the queue
2199 public final void postMenuEvent(final TInputEvent event
) {
2200 synchronized (fillEventQueue
) {
2201 fillEventQueue
.add(event
);
2207 * Add a sub-menu to the list of open sub-menus.
2209 * @param menu sub-menu
2211 public final void addSubMenu(final TMenu menu
) {
2216 * Convenience function to add a top-level menu.
2218 * @param title menu title
2219 * @return the new menu
2221 public final TMenu
addMenu(final String title
) {
2224 TMenu menu
= new TMenu(this, x
, y
, title
);
2231 * Convenience function to add a default "File" menu.
2233 * @return the new menu
2235 public final TMenu
addFileMenu() {
2236 TMenu fileMenu
= addMenu("&File");
2237 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2238 fileMenu
.addSeparator();
2239 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2240 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2241 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2242 "commands (Open, Save, Print, etc.)");
2243 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2248 * Convenience function to add a default "Edit" menu.
2250 * @return the new menu
2252 public final TMenu
addEditMenu() {
2253 TMenu editMenu
= addMenu("&Edit");
2254 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2255 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2256 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2257 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2258 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2259 "undo, and Clipboard access");
2260 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2265 * Convenience function to add a default "Window" menu.
2267 * @return the new menu
2269 public final TMenu
addWindowMenu() {
2270 TMenu windowMenu
= addMenu("&Window");
2271 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2272 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2273 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2274 windowMenu
.addSeparator();
2275 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2276 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2277 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2278 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2279 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2280 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2282 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2287 * Convenience function to add a default "Help" menu.
2289 * @return the new menu
2291 public final TMenu
addHelpMenu() {
2292 TMenu helpMenu
= addMenu("&Help");
2293 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2294 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2295 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2296 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2297 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2298 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2299 helpMenu
.addSeparator();
2300 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2301 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2302 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2306 // ------------------------------------------------------------------------
2307 // Event handlers ---------------------------------------------------------
2308 // ------------------------------------------------------------------------
2311 * Method that TApplication subclasses can override to handle menu or
2312 * posted command events.
2314 * @param command command event
2315 * @return if true, this event was consumed
2317 protected boolean onCommand(final TCommandEvent command
) {
2318 // Default: handle cmExit
2319 if (command
.equals(cmExit
)) {
2320 if (messageBox("Confirmation", "Exit application?",
2321 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2327 if (command
.equals(cmShell
)) {
2328 openTerminal(0, 0, TWindow
.RESIZABLE
);
2332 if (command
.equals(cmTile
)) {
2336 if (command
.equals(cmCascade
)) {
2340 if (command
.equals(cmCloseAll
)) {
2349 * Method that TApplication subclasses can override to handle menu
2352 * @param menu menu event
2353 * @return if true, this event was consumed
2355 protected boolean onMenu(final TMenuEvent menu
) {
2357 // Default: handle MID_EXIT
2358 if (menu
.getId() == TMenu
.MID_EXIT
) {
2359 if (messageBox("Confirmation", "Exit application?",
2360 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2366 if (menu
.getId() == TMenu
.MID_SHELL
) {
2367 openTerminal(0, 0, TWindow
.RESIZABLE
);
2371 if (menu
.getId() == TMenu
.MID_TILE
) {
2375 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2379 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2383 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2391 * Method that TApplication subclasses can override to handle keystrokes.
2393 * @param keypress keystroke event
2394 * @return if true, this event was consumed
2396 protected boolean onKeypress(final TKeypressEvent keypress
) {
2397 // Default: only menu shortcuts
2399 // Process Alt-F, Alt-E, etc. menu shortcut keys
2400 if (!keypress
.getKey().isFnKey()
2401 && keypress
.getKey().isAlt()
2402 && !keypress
.getKey().isCtrl()
2403 && (activeMenu
== null)
2404 && !modalWindowActive()
2407 assert (subMenus
.size() == 0);
2409 for (TMenu menu
: menus
) {
2410 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2411 == Character
.toLowerCase(keypress
.getKey().getChar())
2414 menu
.setActive(true);
2423 // ------------------------------------------------------------------------
2424 // TTimer management ------------------------------------------------------
2425 // ------------------------------------------------------------------------
2428 * Get the amount of time I can sleep before missing a Timer tick.
2430 * @param timeout = initial (maximum) timeout in millis
2431 * @return number of milliseconds between now and the next timer event
2433 private long getSleepTime(final long timeout
) {
2434 Date now
= new Date();
2435 long nowTime
= now
.getTime();
2436 long sleepTime
= timeout
;
2437 for (TTimer timer
: timers
) {
2438 long nextTickTime
= timer
.getNextTick().getTime();
2439 if (nextTickTime
< nowTime
) {
2443 long timeDifference
= nextTickTime
- nowTime
;
2444 if (timeDifference
< sleepTime
) {
2445 sleepTime
= timeDifference
;
2448 assert (sleepTime
>= 0);
2449 assert (sleepTime
<= timeout
);
2454 * Convenience function to add a timer.
2456 * @param duration number of milliseconds to wait between ticks
2457 * @param recurring if true, re-schedule this timer after every tick
2458 * @param action function to call when button is pressed
2461 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2462 final TAction action
) {
2464 TTimer timer
= new TTimer(duration
, recurring
, action
);
2465 synchronized (timers
) {
2472 * Convenience function to remove a timer.
2474 * @param timer timer to remove
2476 public final void removeTimer(final TTimer timer
) {
2477 synchronized (timers
) {
2478 timers
.remove(timer
);
2482 // ------------------------------------------------------------------------
2483 // Other TWindow constructors ---------------------------------------------
2484 // ------------------------------------------------------------------------
2487 * Convenience function to spawn a message box.
2489 * @param title window title, will be centered along the top border
2490 * @param caption message to display. Use embedded newlines to get a
2492 * @return the new message box
2494 public final TMessageBox
messageBox(final String title
,
2495 final String caption
) {
2497 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2501 * Convenience function to spawn a message box.
2503 * @param title window title, will be centered along the top border
2504 * @param caption message to display. Use embedded newlines to get a
2506 * @param type one of the TMessageBox.Type constants. Default is
2508 * @return the new message box
2510 public final TMessageBox
messageBox(final String title
,
2511 final String caption
, final TMessageBox
.Type type
) {
2513 return new TMessageBox(this, title
, caption
, type
);
2517 * Convenience function to spawn an input box.
2519 * @param title window title, will be centered along the top border
2520 * @param caption message to display. Use embedded newlines to get a
2522 * @return the new input box
2524 public final TInputBox
inputBox(final String title
, final String caption
) {
2526 return new TInputBox(this, title
, caption
);
2530 * Convenience function to spawn an input box.
2532 * @param title window title, will be centered along the top border
2533 * @param caption message to display. Use embedded newlines to get a
2535 * @param text initial text to seed the field with
2536 * @return the new input box
2538 public final TInputBox
inputBox(final String title
, final String caption
,
2539 final String text
) {
2541 return new TInputBox(this, title
, caption
, text
);
2545 * Convenience function to open a terminal window.
2547 * @param x column relative to parent
2548 * @param y row relative to parent
2549 * @return the terminal new window
2551 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2552 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2556 * Convenience function to open a terminal window.
2558 * @param x column relative to parent
2559 * @param y row relative to parent
2560 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2561 * @return the terminal new window
2563 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2566 return new TTerminalWindow(this, x
, y
, flags
);
2570 * Convenience function to spawn an file open box.
2572 * @param path path of selected file
2573 * @return the result of the new file open box
2574 * @throws IOException if java.io operation throws
2576 public final String
fileOpenBox(final String path
) throws IOException
{
2578 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2579 return box
.getFilename();
2583 * Convenience function to spawn an file open box.
2585 * @param path path of selected file
2586 * @param type one of the Type constants
2587 * @return the result of the new file open box
2588 * @throws IOException if java.io operation throws
2590 public final String
fileOpenBox(final String path
,
2591 final TFileOpenBox
.Type type
) throws IOException
{
2593 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2594 return box
.getFilename();
2598 * Convenience function to create a new window and make it active.
2599 * Window will be located at (0, 0).
2601 * @param title window title, will be centered along the top border
2602 * @param width width of window
2603 * @param height height of window
2605 public final TWindow
addWindow(final String title
, final int width
,
2608 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2612 * Convenience function to create a new window and make it active.
2613 * Window will be located at (0, 0).
2615 * @param title window title, will be centered along the top border
2616 * @param width width of window
2617 * @param height height of window
2618 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2620 public final TWindow
addWindow(final String title
,
2621 final int width
, final int height
, final int flags
) {
2623 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2628 * Convenience function to create a new window and make it active.
2630 * @param title window title, will be centered along the top border
2631 * @param x column relative to parent
2632 * @param y row relative to parent
2633 * @param width width of window
2634 * @param height height of window
2636 public final TWindow
addWindow(final String title
,
2637 final int x
, final int y
, final int width
, final int height
) {
2639 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2644 * Convenience function to create a new window and make it active.
2646 * @param title window title, will be centered along the top border
2647 * @param x column relative to parent
2648 * @param y row relative to parent
2649 * @param width width of window
2650 * @param height height of window
2651 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2653 public final TWindow
addWindow(final String title
,
2654 final int x
, final int y
, final int width
, final int height
,
2657 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);