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 // The default SwingBackend is 80x25, 20 pt font. If you want to
639 // change that, you can pass the extra arguments to the
640 // SwingBackend constructor here. For example, if you wanted
641 // 90x30, 16 pt font:
643 // backend = new SwingBackend(this, 90, 30, 16);
644 backend
= new SwingBackend(this);
649 backend
= new ECMA48Backend(this, null, null);
652 throw new IllegalArgumentException("Invalid backend type: "
659 * Public constructor. The backend type will be BackendType.ECMA48.
661 * @param input an InputStream connected to the remote user, or null for
662 * System.in. If System.in is used, then on non-Windows systems it will
663 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
664 * mode. input is always converted to a Reader with UTF-8 encoding.
665 * @param output an OutputStream connected to the remote user, or null
666 * for System.out. output is always converted to a Writer with UTF-8
668 * @throws UnsupportedEncodingException if an exception is thrown when
669 * creating the InputStreamReader
671 public TApplication(final InputStream input
,
672 final OutputStream output
) throws UnsupportedEncodingException
{
674 backend
= new ECMA48Backend(this, input
, output
);
679 * Public constructor. The backend type will be BackendType.ECMA48.
681 * @param input the InputStream underlying 'reader'. Its available()
682 * method is used to determine if reader.read() will block or not.
683 * @param reader a Reader connected to the remote user.
684 * @param writer a PrintWriter connected to the remote user.
685 * @param setRawMode if true, set System.in into raw mode with stty.
686 * This should in general not be used. It is here solely for Demo3,
687 * which uses System.in.
688 * @throws IllegalArgumentException if input, reader, or writer are null.
690 public TApplication(final InputStream input
, final Reader reader
,
691 final PrintWriter writer
, final boolean setRawMode
) {
693 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
698 * Public constructor. The backend type will be BackendType.ECMA48.
700 * @param input the InputStream underlying 'reader'. Its available()
701 * method is used to determine if reader.read() will block or not.
702 * @param reader a Reader connected to the remote user.
703 * @param writer a PrintWriter connected to the remote user.
704 * @throws IllegalArgumentException if input, reader, or writer are null.
706 public TApplication(final InputStream input
, final Reader reader
,
707 final PrintWriter writer
) {
709 this(input
, reader
, writer
, false);
713 * Public constructor. This hook enables use with new non-Jexer
716 * @param backend a Backend that is already ready to go.
718 public TApplication(final Backend backend
) {
719 this.backend
= backend
;
724 * Finish construction once the backend is set.
726 private void TApplicationImpl() {
727 theme
= new ColorTheme();
728 desktopBottom
= getScreen().getHeight() - 1;
729 fillEventQueue
= new ArrayList
<TInputEvent
>();
730 drainEventQueue
= new ArrayList
<TInputEvent
>();
731 windows
= new LinkedList
<TWindow
>();
732 menus
= new LinkedList
<TMenu
>();
733 subMenus
= new LinkedList
<TMenu
>();
734 timers
= new LinkedList
<TTimer
>();
735 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
736 menuItems
= new ArrayList
<TMenuItem
>();
737 desktop
= new TDesktop(this);
739 // Setup the main consumer thread
740 primaryEventHandler
= new WidgetEventHandler(this, true);
741 (new Thread(primaryEventHandler
)).start();
744 // ------------------------------------------------------------------------
745 // Screen refresh loop ----------------------------------------------------
746 // ------------------------------------------------------------------------
749 * Invert the cell color at a position. This is used to track the mouse.
751 * @param x column position
752 * @param y row position
754 private void invertCell(final int x
, final int y
) {
756 System
.err
.printf("invertCell() %d %d\n", x
, y
);
758 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
759 attr
.setForeColor(attr
.getForeColor().invert());
760 attr
.setBackColor(attr
.getBackColor().invert());
761 getScreen().putAttrXY(x
, y
, attr
, false);
767 private void drawAll() {
769 System
.err
.printf("drawAll() enter\n");
774 System
.err
.printf("drawAll() !repaint\n");
776 synchronized (getScreen()) {
777 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
778 // The only thing that has happened is the mouse moved.
779 // Clear the old position and draw the new position.
780 invertCell(oldMouseX
, oldMouseY
);
781 invertCell(mouseX
, mouseY
);
785 if (getScreen().isDirty()) {
786 backend
.flushScreen();
793 System
.err
.printf("drawAll() REDRAW\n");
796 // If true, the cursor is not visible
797 boolean cursor
= false;
799 // Start with a clean screen
803 if (desktop
!= null) {
804 desktop
.drawChildren();
807 // Draw each window in reverse Z order
808 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
809 Collections
.sort(sorted
);
810 TWindow topLevel
= null;
811 if (sorted
.size() > 0) {
812 topLevel
= sorted
.get(0);
814 Collections
.reverse(sorted
);
815 for (TWindow window
: sorted
) {
816 if (window
.isShown()) {
817 window
.drawChildren();
821 // Draw the blank menubar line - reset the screen clipping first so
822 // it won't trim it out.
823 getScreen().resetClipping();
824 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
825 theme
.getColor("tmenu"));
826 // Now draw the menus.
828 for (TMenu menu
: menus
) {
829 CellAttributes menuColor
;
830 CellAttributes menuMnemonicColor
;
831 if (menu
.isActive()) {
832 menuColor
= theme
.getColor("tmenu.highlighted");
833 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
836 menuColor
= theme
.getColor("tmenu");
837 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
839 // Draw the menu title
840 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
842 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
843 // Draw the highlight character
844 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
845 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
847 if (menu
.isActive()) {
849 // Reset the screen clipping so we can draw the next title.
850 getScreen().resetClipping();
852 x
+= menu
.getTitle().length() + 2;
855 for (TMenu menu
: subMenus
) {
856 // Reset the screen clipping so we can draw the next sub-menu.
857 getScreen().resetClipping();
861 // Draw the status bar of the top-level window
862 TStatusBar statusBar
= null;
863 if (topLevel
!= null) {
864 statusBar
= topLevel
.getStatusBar();
866 if (statusBar
!= null) {
867 getScreen().resetClipping();
868 statusBar
.setWidth(getScreen().getWidth());
869 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
872 CellAttributes barColor
= new CellAttributes();
873 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
874 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
878 // Draw the mouse pointer
879 invertCell(mouseX
, mouseY
);
883 // Place the cursor if it is visible
884 TWidget activeWidget
= null;
885 if (sorted
.size() > 0) {
886 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
887 if (activeWidget
.isCursorVisible()) {
888 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
889 activeWidget
.getCursorAbsoluteY());
896 getScreen().hideCursor();
899 // Flush the screen contents
900 if (getScreen().isDirty()) {
901 backend
.flushScreen();
907 // ------------------------------------------------------------------------
908 // Main loop --------------------------------------------------------------
909 // ------------------------------------------------------------------------
912 * Run this application until it exits.
916 // Timeout is in milliseconds, so default timeout after 1 second
920 // If I've got no updates to render, wait for something from the
921 // backend or a timer.
923 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
925 // Never sleep longer than 50 millis. We need time for
926 // windows with background tasks to update the display, and
927 // still flip buffers reasonably quickly in
928 // backend.flushPhysical().
929 timeout
= getSleepTime(50);
933 // As of now, I've got nothing to do: no I/O, nothing from
934 // the consumer threads, no timers that need to run ASAP. So
935 // wait until either the backend or the consumer threads have
939 System
.err
.println("sleep " + timeout
+ " millis");
941 synchronized (this) {
944 } catch (InterruptedException e
) {
945 // I'm awake and don't care why, let's see what's going
951 // Prevent stepping on the primary or secondary event handler.
954 // Pull any pending I/O events
955 backend
.getEvents(fillEventQueue
);
957 // Dispatch each event to the appropriate handler, one at a time.
959 TInputEvent event
= null;
960 if (fillEventQueue
.size() == 0) {
963 event
= fillEventQueue
.remove(0);
964 metaHandleEvent(event
);
967 // Wake a consumer thread if we have any pending events.
968 if (drainEventQueue
.size() > 0) {
972 // Process timers and call doIdle()'s
976 synchronized (getScreen()) {
980 // Let the event handlers run again.
981 startEventHandlers();
985 // Shutdown the event consumer threads
986 if (secondaryEventHandler
!= null) {
987 synchronized (secondaryEventHandler
) {
988 secondaryEventHandler
.notify();
991 if (primaryEventHandler
!= null) {
992 synchronized (primaryEventHandler
) {
993 primaryEventHandler
.notify();
997 // Shutdown the user I/O thread(s)
1000 // Close all the windows. This gives them an opportunity to release
1007 * Peek at certain application-level events, add to eventQueue, and wake
1008 * up the consuming Thread.
1010 * @param event the input event to consume
1012 private void metaHandleEvent(final TInputEvent event
) {
1015 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1016 event
)); System
.err
.flush();
1020 // Do no more processing if the application is already trying
1025 // Special application-wide events -------------------------------
1028 if (event
instanceof TCommandEvent
) {
1029 TCommandEvent command
= (TCommandEvent
) event
;
1030 if (command
.getCmd().equals(cmAbort
)) {
1037 if (event
instanceof TResizeEvent
) {
1038 TResizeEvent resize
= (TResizeEvent
) event
;
1039 synchronized (getScreen()) {
1040 getScreen().setDimensions(resize
.getWidth(),
1041 resize
.getHeight());
1042 desktopBottom
= getScreen().getHeight() - 1;
1048 if (desktop
!= null) {
1049 desktop
.setDimensions(0, 0, resize
.getWidth(),
1050 resize
.getHeight() - 1);
1055 // Peek at the mouse position
1056 if (event
instanceof TMouseEvent
) {
1057 TMouseEvent mouse
= (TMouseEvent
) event
;
1058 synchronized (getScreen()) {
1059 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1062 mouseX
= mouse
.getX();
1063 mouseY
= mouse
.getY();
1068 // Put into the main queue
1069 drainEventQueue
.add(event
);
1073 * Dispatch one event to the appropriate widget or application-level
1074 * event handler. This is the primary event handler, it has the normal
1075 * application-wide event handling.
1077 * @param event the input event to consume
1078 * @see #secondaryHandleEvent(TInputEvent event)
1080 private void primaryHandleEvent(final TInputEvent event
) {
1083 System
.err
.printf("Handle event: %s\n", event
);
1086 // Special application-wide events -----------------------------------
1088 // Peek at the mouse position
1089 if (event
instanceof TMouseEvent
) {
1090 // See if we need to switch focus to another window or the menu
1091 checkSwitchFocus((TMouseEvent
) event
);
1094 // Handle menu events
1095 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1096 TMenu menu
= activeMenu
;
1098 if (event
instanceof TMouseEvent
) {
1099 TMouseEvent mouse
= (TMouseEvent
) event
;
1101 while (subMenus
.size() > 0) {
1102 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1103 if (subMenu
.mouseWouldHit(mouse
)) {
1106 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1107 && (!mouse
.isMouse1())
1108 && (!mouse
.isMouse2())
1109 && (!mouse
.isMouse3())
1110 && (!mouse
.isMouseWheelUp())
1111 && (!mouse
.isMouseWheelDown())
1115 // We navigated away from a sub-menu, so close it
1119 // Convert the mouse relative x/y to menu coordinates
1120 assert (mouse
.getX() == mouse
.getAbsoluteX());
1121 assert (mouse
.getY() == mouse
.getAbsoluteY());
1122 if (subMenus
.size() > 0) {
1123 menu
= subMenus
.get(subMenus
.size() - 1);
1125 mouse
.setX(mouse
.getX() - menu
.getX());
1126 mouse
.setY(mouse
.getY() - menu
.getY());
1128 menu
.handleEvent(event
);
1132 if (event
instanceof TKeypressEvent
) {
1133 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1135 // See if this key matches an accelerator, and is not being
1136 // shortcutted by the active window, and if so dispatch the menu
1138 boolean windowWillShortcut
= false;
1139 if (activeWindow
!= null) {
1140 assert (activeWindow
.isShown());
1141 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1142 // We do not process this key, it will be passed to the
1144 windowWillShortcut
= true;
1148 if (!windowWillShortcut
&& !modalWindowActive()) {
1149 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1150 TMenuItem item
= null;
1151 synchronized (accelerators
) {
1152 item
= accelerators
.get(keypressLowercase
);
1155 if (item
.isEnabled()) {
1156 // Let the menu item dispatch
1162 // Handle the keypress
1163 if (onKeypress(keypress
)) {
1169 if (event
instanceof TCommandEvent
) {
1170 if (onCommand((TCommandEvent
) event
)) {
1175 if (event
instanceof TMenuEvent
) {
1176 if (onMenu((TMenuEvent
) event
)) {
1181 // Dispatch events to the active window -------------------------------
1182 boolean dispatchToDesktop
= true;
1183 TWindow window
= activeWindow
;
1184 if (window
!= null) {
1185 assert (window
.isActive());
1186 assert (window
.isShown());
1187 if (event
instanceof TMouseEvent
) {
1188 TMouseEvent mouse
= (TMouseEvent
) event
;
1189 // Convert the mouse relative x/y to window coordinates
1190 assert (mouse
.getX() == mouse
.getAbsoluteX());
1191 assert (mouse
.getY() == mouse
.getAbsoluteY());
1192 mouse
.setX(mouse
.getX() - window
.getX());
1193 mouse
.setY(mouse
.getY() - window
.getY());
1195 if (window
.mouseWouldHit(mouse
)) {
1196 dispatchToDesktop
= false;
1198 } else if (event
instanceof TKeypressEvent
) {
1199 dispatchToDesktop
= false;
1203 System
.err
.printf("TApplication dispatch event: %s\n",
1206 window
.handleEvent(event
);
1208 if (dispatchToDesktop
) {
1209 // This event is fair game for the desktop to process.
1210 if (desktop
!= null) {
1211 desktop
.handleEvent(event
);
1217 * Dispatch one event to the appropriate widget or application-level
1218 * event handler. This is the secondary event handler used by certain
1219 * special dialogs (currently TMessageBox and TFileOpenBox).
1221 * @param event the input event to consume
1222 * @see #primaryHandleEvent(TInputEvent event)
1224 private void secondaryHandleEvent(final TInputEvent event
) {
1225 secondaryEventReceiver
.handleEvent(event
);
1229 * Enable a widget to override the primary event thread.
1231 * @param widget widget that will receive events
1233 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1234 assert (secondaryEventReceiver
== null);
1235 assert (secondaryEventHandler
== null);
1236 assert ((widget
instanceof TMessageBox
)
1237 || (widget
instanceof TFileOpenBox
));
1238 secondaryEventReceiver
= widget
;
1239 secondaryEventHandler
= new WidgetEventHandler(this, false);
1240 (new Thread(secondaryEventHandler
)).start();
1244 * Yield to the secondary thread.
1246 public final void yield() {
1247 assert (secondaryEventReceiver
!= null);
1248 // This is where we handoff the event handler lock from the primary
1249 // to secondary thread. We unlock here, and in a future loop the
1250 // secondary thread locks again. When it gives up, we have the
1251 // single lock back.
1252 boolean oldLock
= unlockHandleEvent();
1255 while (secondaryEventReceiver
!= null) {
1256 synchronized (primaryEventHandler
) {
1258 primaryEventHandler
.wait();
1259 } catch (InterruptedException e
) {
1267 * Do stuff when there is no user input.
1269 private void doIdle() {
1271 System
.err
.printf("doIdle()\n");
1274 // Now run any timers that have timed out
1275 Date now
= new Date();
1276 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1277 for (TTimer timer
: timers
) {
1278 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1280 if (timer
.recurring
) {
1281 keepTimers
.add(timer
);
1284 keepTimers
.add(timer
);
1287 timers
= keepTimers
;
1290 for (TWindow window
: windows
) {
1293 if (desktop
!= null) {
1298 // ------------------------------------------------------------------------
1299 // TWindow management -----------------------------------------------------
1300 // ------------------------------------------------------------------------
1303 * Return the total number of windows.
1305 * @return the total number of windows
1307 public final int windowCount() {
1308 return windows
.size();
1312 * Return the number of windows that are showing.
1314 * @return the number of windows that are showing on screen
1316 public final int shownWindowCount() {
1318 for (TWindow w
: windows
) {
1327 * Return the number of windows that are hidden.
1329 * @return the number of windows that are hidden
1331 public final int hiddenWindowCount() {
1333 for (TWindow w
: windows
) {
1342 * Check if a window instance is in this application's window list.
1344 * @param window window to look for
1345 * @return true if this window is in the list
1347 public final boolean hasWindow(final TWindow window
) {
1348 if (windows
.size() == 0) {
1351 for (TWindow w
: windows
) {
1353 assert (window
.getApplication() == this);
1361 * Activate a window: bring it to the top and have it receive events.
1363 * @param window the window to become the new active window
1365 public void activateWindow(final TWindow window
) {
1366 if (hasWindow(window
) == false) {
1368 * Someone has a handle to a window I don't have. Ignore this
1374 assert (windows
.size() > 0);
1376 if (window
.isHidden()) {
1377 // Unhiding will also activate.
1381 assert (window
.isShown());
1383 if (windows
.size() == 1) {
1384 assert (window
== windows
.get(0));
1385 if (activeWindow
== null) {
1386 activeWindow
= window
;
1388 activeWindow
.setActive(true);
1389 activeWindow
.onFocus();
1392 assert (window
.isActive());
1393 assert (activeWindow
== window
);
1397 if (activeWindow
== window
) {
1398 assert (window
.isActive());
1400 // Window is already active, do nothing.
1404 assert (!window
.isActive());
1405 if (activeWindow
!= null) {
1406 assert (activeWindow
.getZ() == 0);
1408 activeWindow
.onUnfocus();
1409 activeWindow
.setActive(false);
1410 activeWindow
.setZ(window
.getZ());
1412 activeWindow
= window
;
1413 activeWindow
.setZ(0);
1414 activeWindow
.setActive(true);
1415 activeWindow
.onFocus();
1422 * @param window the window to hide
1424 public void hideWindow(final TWindow window
) {
1425 if (hasWindow(window
) == false) {
1427 * Someone has a handle to a window I don't have. Ignore this
1433 assert (windows
.size() > 0);
1435 if (!window
.hidden
) {
1436 if (window
== activeWindow
) {
1437 if (shownWindowCount() > 1) {
1440 activeWindow
= null;
1441 window
.setActive(false);
1445 window
.hidden
= true;
1453 * @param window the window to show
1455 public void showWindow(final TWindow window
) {
1456 if (hasWindow(window
) == false) {
1458 * Someone has a handle to a window I don't have. Ignore this
1464 assert (windows
.size() > 0);
1466 if (window
.hidden
) {
1467 window
.hidden
= false;
1469 activateWindow(window
);
1474 * Close window. Note that the window's destructor is NOT called by this
1475 * method, instead the GC is assumed to do the cleanup.
1477 * @param window the window to remove
1479 public final void closeWindow(final TWindow window
) {
1480 if (hasWindow(window
) == false) {
1482 * Someone has a handle to a window I don't have. Ignore this
1488 synchronized (windows
) {
1489 int z
= window
.getZ();
1492 Collections
.sort(windows
);
1494 activeWindow
= null;
1495 for (TWindow w
: windows
) {
1497 w
.setZ(w
.getZ() - 1);
1498 if (w
.getZ() == 0) {
1501 assert (activeWindow
== null);
1513 // Perform window cleanup
1516 // Check if we are closing a TMessageBox or similar
1517 if (secondaryEventReceiver
!= null) {
1518 assert (secondaryEventHandler
!= null);
1520 // Do not send events to the secondaryEventReceiver anymore, the
1521 // window is closed.
1522 secondaryEventReceiver
= null;
1524 // Wake the secondary thread, it will wake the primary as it
1526 synchronized (secondaryEventHandler
) {
1527 secondaryEventHandler
.notify();
1531 // Permit desktop to be active if it is the only thing left.
1532 if (desktop
!= null) {
1533 if (windows
.size() == 0) {
1534 desktop
.setActive(true);
1540 * Switch to the next window.
1542 * @param forward if true, then switch to the next window in the list,
1543 * otherwise switch to the previous window in the list
1545 public final void switchWindow(final boolean forward
) {
1546 // Only switch if there are multiple visible windows
1547 if (shownWindowCount() < 2) {
1550 assert (activeWindow
!= null);
1552 synchronized (windows
) {
1554 // Swap z/active between active window and the next in the list
1555 int activeWindowI
= -1;
1556 for (int i
= 0; i
< windows
.size(); i
++) {
1557 if (windows
.get(i
) == activeWindow
) {
1558 assert (activeWindow
.isActive());
1562 assert (!windows
.get(0).isActive());
1565 assert (activeWindowI
>= 0);
1567 // Do not switch if a window is modal
1568 if (activeWindow
.isModal()) {
1572 int nextWindowI
= activeWindowI
;
1576 nextWindowI
%= windows
.size();
1579 if (nextWindowI
< 0) {
1580 nextWindowI
= windows
.size() - 1;
1584 if (windows
.get(nextWindowI
).isShown()) {
1585 activateWindow(windows
.get(nextWindowI
));
1589 } // synchronized (windows)
1594 * Add a window to my window list and make it active.
1596 * @param window new window to add
1598 public final void addWindow(final TWindow window
) {
1600 // Do not add menu windows to the window list.
1601 if (window
instanceof TMenu
) {
1605 // Do not add the desktop to the window list.
1606 if (window
instanceof TDesktop
) {
1610 synchronized (windows
) {
1611 // Do not allow a modal window to spawn a non-modal window. If a
1612 // modal window is active, then this window will become modal
1614 if (modalWindowActive()) {
1615 window
.flags
|= TWindow
.MODAL
;
1616 window
.flags
|= TWindow
.CENTERED
;
1617 window
.hidden
= false;
1619 if (window
.isShown()) {
1620 for (TWindow w
: windows
) {
1625 w
.setZ(w
.getZ() + 1);
1628 windows
.add(window
);
1629 if (window
.isShown()) {
1630 activeWindow
= window
;
1631 activeWindow
.setZ(0);
1632 activeWindow
.setActive(true);
1633 activeWindow
.onFocus();
1636 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1637 && smartWindowPlacement
) {
1639 doSmartPlacement(window
);
1643 // Desktop cannot be active over any other window.
1644 if (desktop
!= null) {
1645 desktop
.setActive(false);
1650 * Check if there is a system-modal window on top.
1652 * @return true if the active window is modal
1654 private boolean modalWindowActive() {
1655 if (windows
.size() == 0) {
1659 for (TWindow w
: windows
) {
1669 * Close all open windows.
1671 private void closeAllWindows() {
1672 // Don't do anything if we are in the menu
1673 if (activeMenu
!= null) {
1676 while (windows
.size() > 0) {
1677 closeWindow(windows
.get(0));
1682 * Re-layout the open windows as non-overlapping tiles. This produces
1683 * almost the same results as Turbo Pascal 7.0's IDE.
1685 private void tileWindows() {
1686 synchronized (windows
) {
1687 // Don't do anything if we are in the menu
1688 if (activeMenu
!= null) {
1691 int z
= windows
.size();
1697 a
= (int)(Math
.sqrt(z
));
1701 if (((a
* b
) + c
) == z
) {
1709 int newWidth
= (getScreen().getWidth() / a
);
1710 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1711 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1713 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1714 Collections
.sort(sorted
);
1715 Collections
.reverse(sorted
);
1716 for (int i
= 0; i
< sorted
.size(); i
++) {
1717 int logicalX
= i
/ b
;
1718 int logicalY
= i
% b
;
1719 if (i
>= ((a
- 1) * b
)) {
1721 logicalY
= i
- ((a
- 1) * b
);
1724 TWindow w
= sorted
.get(i
);
1725 w
.setX(logicalX
* newWidth
);
1726 w
.setWidth(newWidth
);
1727 if (i
>= ((a
- 1) * b
)) {
1728 w
.setY((logicalY
* newHeight2
) + 1);
1729 w
.setHeight(newHeight2
);
1731 w
.setY((logicalY
* newHeight1
) + 1);
1732 w
.setHeight(newHeight1
);
1739 * Re-layout the open windows as overlapping cascaded windows.
1741 private void cascadeWindows() {
1742 synchronized (windows
) {
1743 // Don't do anything if we are in the menu
1744 if (activeMenu
!= null) {
1749 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1750 Collections
.sort(sorted
);
1751 Collections
.reverse(sorted
);
1752 for (TWindow window
: sorted
) {
1757 if (x
> getScreen().getWidth()) {
1760 if (y
>= getScreen().getHeight()) {
1768 * Place a window to minimize its overlap with other windows.
1770 * @param window the window to place
1772 public final void doSmartPlacement(final TWindow window
) {
1773 // This is a pretty dumb algorithm, but seems to work. The hardest
1774 // part is computing these "overlap" values seeking a minimum average
1777 int yMin
= desktopTop
;
1778 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1779 int yMax
= desktopBottom
- window
.getHeight() + 1;
1787 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1788 // No work to do, bail out.
1792 // Compute the overlap matrix without the new window.
1793 int width
= getScreen().getWidth();
1794 int height
= getScreen().getHeight();
1795 int overlapMatrix
[][] = new int[width
][height
];
1796 for (TWindow w
: windows
) {
1800 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1804 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1808 overlapMatrix
[x
][y
]++;
1813 long oldOverlapTotal
= 0;
1814 long oldOverlapN
= 0;
1815 for (int x
= 0; x
< width
; x
++) {
1816 for (int y
= 0; y
< height
; y
++) {
1817 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1818 if (overlapMatrix
[x
][y
] > 0) {
1825 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1826 boolean first
= true;
1827 int windowX
= window
.getX();
1828 int windowY
= window
.getY();
1830 // For each possible (x, y) position for the new window, compute a
1831 // new overlap matrix.
1832 for (int x
= xMin
; x
< xMax
; x
++) {
1833 for (int y
= yMin
; y
< yMax
; y
++) {
1835 // Start with the matrix minus this window.
1836 int newMatrix
[][] = new int[width
][height
];
1837 for (int mx
= 0; mx
< width
; mx
++) {
1838 for (int my
= 0; my
< height
; my
++) {
1839 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1843 // Add this window's values to the new overlap matrix.
1844 long newOverlapTotal
= 0;
1845 long newOverlapN
= 0;
1846 // Start by adding each new cell.
1847 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1851 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1855 newMatrix
[wx
][wy
]++;
1858 // Now figure out the new value for total coverage.
1859 for (int mx
= 0; mx
< width
; mx
++) {
1860 for (int my
= 0; my
< height
; my
++) {
1861 newOverlapTotal
+= newMatrix
[x
][y
];
1862 if (newMatrix
[mx
][my
] > 0) {
1867 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1870 // First time: just record what we got.
1871 oldOverlapAvg
= newOverlapAvg
;
1874 // All other times: pick a new best (x, y) and save the
1876 if (newOverlapAvg
< oldOverlapAvg
) {
1879 oldOverlapAvg
= newOverlapAvg
;
1883 } // for (int x = xMin; x < xMax; x++)
1885 } // for (int y = yMin; y < yMax; y++)
1887 // Finally, set the window's new coordinates.
1888 window
.setX(windowX
);
1889 window
.setY(windowY
);
1892 // ------------------------------------------------------------------------
1893 // TMenu management -------------------------------------------------------
1894 // ------------------------------------------------------------------------
1897 * Check if a mouse event would hit either the active menu or any open
1900 * @param mouse mouse event
1901 * @return true if the mouse would hit the active menu or an open
1904 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1905 assert (activeMenu
!= null);
1906 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1907 Collections
.reverse(menus
);
1908 for (TMenu menu
: menus
) {
1909 if (menu
.mouseWouldHit(mouse
)) {
1913 return activeMenu
.mouseWouldHit(mouse
);
1917 * See if we need to switch window or activate the menu based on
1920 * @param mouse mouse event
1922 private void checkSwitchFocus(final TMouseEvent mouse
) {
1924 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1925 && (activeMenu
!= null)
1926 && (mouse
.getAbsoluteY() != 0)
1927 && (!mouseOnMenu(mouse
))
1929 // They clicked outside the active menu, turn it off
1930 activeMenu
.setActive(false);
1932 for (TMenu menu
: subMenus
) {
1933 menu
.setActive(false);
1939 // See if they hit the menu bar
1940 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1941 && (mouse
.isMouse1())
1942 && (!modalWindowActive())
1943 && (mouse
.getAbsoluteY() == 0)
1946 for (TMenu menu
: subMenus
) {
1947 menu
.setActive(false);
1951 // They selected the menu, go activate it
1952 for (TMenu menu
: menus
) {
1953 if ((mouse
.getAbsoluteX() >= menu
.getX())
1954 && (mouse
.getAbsoluteX() < menu
.getX()
1955 + menu
.getTitle().length() + 2)
1957 menu
.setActive(true);
1960 menu
.setActive(false);
1966 // See if they hit the menu bar
1967 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1968 && (mouse
.isMouse1())
1969 && (activeMenu
!= null)
1970 && (mouse
.getAbsoluteY() == 0)
1973 TMenu oldMenu
= activeMenu
;
1974 for (TMenu menu
: subMenus
) {
1975 menu
.setActive(false);
1979 // See if we should switch menus
1980 for (TMenu menu
: menus
) {
1981 if ((mouse
.getAbsoluteX() >= menu
.getX())
1982 && (mouse
.getAbsoluteX() < menu
.getX()
1983 + menu
.getTitle().length() + 2)
1985 menu
.setActive(true);
1989 if (oldMenu
!= activeMenu
) {
1990 // They switched menus
1991 oldMenu
.setActive(false);
1996 // If a menu is still active, don't switch windows
1997 if (activeMenu
!= null) {
2001 // Only switch if there are multiple windows
2002 if (windows
.size() < 2) {
2006 if (((focusFollowsMouse
== true)
2007 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2008 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2010 synchronized (windows
) {
2011 Collections
.sort(windows
);
2012 if (windows
.get(0).isModal()) {
2013 // Modal windows don't switch
2017 for (TWindow window
: windows
) {
2018 assert (!window
.isModal());
2020 if (window
.isHidden()) {
2021 assert (!window
.isActive());
2025 if (window
.mouseWouldHit(mouse
)) {
2026 if (window
== windows
.get(0)) {
2027 // Clicked on the same window, nothing to do
2028 assert (window
.isActive());
2032 // We will be switching to another window
2033 assert (windows
.get(0).isActive());
2034 assert (windows
.get(0) == activeWindow
);
2035 assert (!window
.isActive());
2036 activeWindow
.onUnfocus();
2037 activeWindow
.setActive(false);
2038 activeWindow
.setZ(window
.getZ());
2039 activeWindow
= window
;
2041 window
.setActive(true);
2048 // Clicked on the background, nothing to do
2052 // Nothing to do: this isn't a mouse up, or focus isn't following
2058 * Turn off the menu.
2060 public final void closeMenu() {
2061 if (activeMenu
!= null) {
2062 activeMenu
.setActive(false);
2064 for (TMenu menu
: subMenus
) {
2065 menu
.setActive(false);
2072 * Turn off a sub-menu.
2074 public final void closeSubMenu() {
2075 assert (activeMenu
!= null);
2076 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2077 assert (item
!= null);
2078 item
.setActive(false);
2079 subMenus
.remove(subMenus
.size() - 1);
2083 * Switch to the next menu.
2085 * @param forward if true, then switch to the next menu in the list,
2086 * otherwise switch to the previous menu in the list
2088 public final void switchMenu(final boolean forward
) {
2089 assert (activeMenu
!= null);
2091 for (TMenu menu
: subMenus
) {
2092 menu
.setActive(false);
2096 for (int i
= 0; i
< menus
.size(); i
++) {
2097 if (activeMenu
== menus
.get(i
)) {
2099 if (i
< menus
.size() - 1) {
2107 activeMenu
.setActive(false);
2108 activeMenu
= menus
.get(i
);
2109 activeMenu
.setActive(true);
2116 * Add a menu item to the global list. If it has a keyboard accelerator,
2117 * that will be added the global hash.
2119 * @param item the menu item
2121 public final void addMenuItem(final TMenuItem item
) {
2122 menuItems
.add(item
);
2124 TKeypress key
= item
.getKey();
2126 synchronized (accelerators
) {
2127 assert (accelerators
.get(key
) == null);
2128 accelerators
.put(key
.toLowerCase(), item
);
2134 * Disable one menu item.
2136 * @param id the menu item ID
2138 public final void disableMenuItem(final int id
) {
2139 for (TMenuItem item
: menuItems
) {
2140 if (item
.getId() == id
) {
2141 item
.setEnabled(false);
2147 * Disable the range of menu items with ID's between lower and upper,
2150 * @param lower the lowest menu item ID
2151 * @param upper the highest menu item ID
2153 public final void disableMenuItems(final int lower
, final int upper
) {
2154 for (TMenuItem item
: menuItems
) {
2155 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2156 item
.setEnabled(false);
2162 * Enable one menu item.
2164 * @param id the menu item ID
2166 public final void enableMenuItem(final int id
) {
2167 for (TMenuItem item
: menuItems
) {
2168 if (item
.getId() == id
) {
2169 item
.setEnabled(true);
2175 * Enable the range of menu items with ID's between lower and upper,
2178 * @param lower the lowest menu item ID
2179 * @param upper the highest menu item ID
2181 public final void enableMenuItems(final int lower
, final int upper
) {
2182 for (TMenuItem item
: menuItems
) {
2183 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2184 item
.setEnabled(true);
2190 * Recompute menu x positions based on their title length.
2192 public final void recomputeMenuX() {
2194 for (TMenu menu
: menus
) {
2196 x
+= menu
.getTitle().length() + 2;
2201 * Post an event to process and turn off the menu.
2203 * @param event new event to add to the queue
2205 public final void postMenuEvent(final TInputEvent event
) {
2206 synchronized (fillEventQueue
) {
2207 fillEventQueue
.add(event
);
2213 * Add a sub-menu to the list of open sub-menus.
2215 * @param menu sub-menu
2217 public final void addSubMenu(final TMenu menu
) {
2222 * Convenience function to add a top-level menu.
2224 * @param title menu title
2225 * @return the new menu
2227 public final TMenu
addMenu(final String title
) {
2230 TMenu menu
= new TMenu(this, x
, y
, title
);
2237 * Convenience function to add a default "File" menu.
2239 * @return the new menu
2241 public final TMenu
addFileMenu() {
2242 TMenu fileMenu
= addMenu("&File");
2243 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2244 fileMenu
.addSeparator();
2245 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2246 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2247 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2248 "commands (Open, Save, Print, etc.)");
2249 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2254 * Convenience function to add a default "Edit" menu.
2256 * @return the new menu
2258 public final TMenu
addEditMenu() {
2259 TMenu editMenu
= addMenu("&Edit");
2260 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2261 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2262 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2263 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2264 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2265 "undo, and Clipboard access");
2266 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2271 * Convenience function to add a default "Window" menu.
2273 * @return the new menu
2275 public final TMenu
addWindowMenu() {
2276 TMenu windowMenu
= addMenu("&Window");
2277 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2278 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2279 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2280 windowMenu
.addSeparator();
2281 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2282 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2283 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2284 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2285 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2286 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2288 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2293 * Convenience function to add a default "Help" menu.
2295 * @return the new menu
2297 public final TMenu
addHelpMenu() {
2298 TMenu helpMenu
= addMenu("&Help");
2299 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2300 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2301 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2302 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2303 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2304 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2305 helpMenu
.addSeparator();
2306 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2307 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2308 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2312 // ------------------------------------------------------------------------
2313 // Event handlers ---------------------------------------------------------
2314 // ------------------------------------------------------------------------
2317 * Method that TApplication subclasses can override to handle menu or
2318 * posted command events.
2320 * @param command command event
2321 * @return if true, this event was consumed
2323 protected boolean onCommand(final TCommandEvent command
) {
2324 // Default: handle cmExit
2325 if (command
.equals(cmExit
)) {
2326 if (messageBox("Confirmation", "Exit application?",
2327 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2333 if (command
.equals(cmShell
)) {
2334 openTerminal(0, 0, TWindow
.RESIZABLE
);
2338 if (command
.equals(cmTile
)) {
2342 if (command
.equals(cmCascade
)) {
2346 if (command
.equals(cmCloseAll
)) {
2355 * Method that TApplication subclasses can override to handle menu
2358 * @param menu menu event
2359 * @return if true, this event was consumed
2361 protected boolean onMenu(final TMenuEvent menu
) {
2363 // Default: handle MID_EXIT
2364 if (menu
.getId() == TMenu
.MID_EXIT
) {
2365 if (messageBox("Confirmation", "Exit application?",
2366 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2372 if (menu
.getId() == TMenu
.MID_SHELL
) {
2373 openTerminal(0, 0, TWindow
.RESIZABLE
);
2377 if (menu
.getId() == TMenu
.MID_TILE
) {
2381 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2385 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2389 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2397 * Method that TApplication subclasses can override to handle keystrokes.
2399 * @param keypress keystroke event
2400 * @return if true, this event was consumed
2402 protected boolean onKeypress(final TKeypressEvent keypress
) {
2403 // Default: only menu shortcuts
2405 // Process Alt-F, Alt-E, etc. menu shortcut keys
2406 if (!keypress
.getKey().isFnKey()
2407 && keypress
.getKey().isAlt()
2408 && !keypress
.getKey().isCtrl()
2409 && (activeMenu
== null)
2410 && !modalWindowActive()
2413 assert (subMenus
.size() == 0);
2415 for (TMenu menu
: menus
) {
2416 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2417 == Character
.toLowerCase(keypress
.getKey().getChar())
2420 menu
.setActive(true);
2429 // ------------------------------------------------------------------------
2430 // TTimer management ------------------------------------------------------
2431 // ------------------------------------------------------------------------
2434 * Get the amount of time I can sleep before missing a Timer tick.
2436 * @param timeout = initial (maximum) timeout in millis
2437 * @return number of milliseconds between now and the next timer event
2439 private long getSleepTime(final long timeout
) {
2440 Date now
= new Date();
2441 long nowTime
= now
.getTime();
2442 long sleepTime
= timeout
;
2443 for (TTimer timer
: timers
) {
2444 long nextTickTime
= timer
.getNextTick().getTime();
2445 if (nextTickTime
< nowTime
) {
2449 long timeDifference
= nextTickTime
- nowTime
;
2450 if (timeDifference
< sleepTime
) {
2451 sleepTime
= timeDifference
;
2454 assert (sleepTime
>= 0);
2455 assert (sleepTime
<= timeout
);
2460 * Convenience function to add a timer.
2462 * @param duration number of milliseconds to wait between ticks
2463 * @param recurring if true, re-schedule this timer after every tick
2464 * @param action function to call when button is pressed
2467 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2468 final TAction action
) {
2470 TTimer timer
= new TTimer(duration
, recurring
, action
);
2471 synchronized (timers
) {
2478 * Convenience function to remove a timer.
2480 * @param timer timer to remove
2482 public final void removeTimer(final TTimer timer
) {
2483 synchronized (timers
) {
2484 timers
.remove(timer
);
2488 // ------------------------------------------------------------------------
2489 // Other TWindow constructors ---------------------------------------------
2490 // ------------------------------------------------------------------------
2493 * Convenience function to spawn a message box.
2495 * @param title window title, will be centered along the top border
2496 * @param caption message to display. Use embedded newlines to get a
2498 * @return the new message box
2500 public final TMessageBox
messageBox(final String title
,
2501 final String caption
) {
2503 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2507 * Convenience function to spawn a message box.
2509 * @param title window title, will be centered along the top border
2510 * @param caption message to display. Use embedded newlines to get a
2512 * @param type one of the TMessageBox.Type constants. Default is
2514 * @return the new message box
2516 public final TMessageBox
messageBox(final String title
,
2517 final String caption
, final TMessageBox
.Type type
) {
2519 return new TMessageBox(this, title
, caption
, type
);
2523 * Convenience function to spawn an input box.
2525 * @param title window title, will be centered along the top border
2526 * @param caption message to display. Use embedded newlines to get a
2528 * @return the new input box
2530 public final TInputBox
inputBox(final String title
, final String caption
) {
2532 return new TInputBox(this, title
, caption
);
2536 * Convenience function to spawn an input box.
2538 * @param title window title, will be centered along the top border
2539 * @param caption message to display. Use embedded newlines to get a
2541 * @param text initial text to seed the field with
2542 * @return the new input box
2544 public final TInputBox
inputBox(final String title
, final String caption
,
2545 final String text
) {
2547 return new TInputBox(this, title
, caption
, text
);
2551 * Convenience function to open a terminal window.
2553 * @param x column relative to parent
2554 * @param y row relative to parent
2555 * @return the terminal new window
2557 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2558 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2562 * Convenience function to open a terminal window.
2564 * @param x column relative to parent
2565 * @param y row relative to parent
2566 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2567 * @return the terminal new window
2569 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2572 return new TTerminalWindow(this, x
, y
, flags
);
2576 * Convenience function to spawn an file open box.
2578 * @param path path of selected file
2579 * @return the result of the new file open box
2580 * @throws IOException if java.io operation throws
2582 public final String
fileOpenBox(final String path
) throws IOException
{
2584 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2585 return box
.getFilename();
2589 * Convenience function to spawn an file open box.
2591 * @param path path of selected file
2592 * @param type one of the Type constants
2593 * @return the result of the new file open box
2594 * @throws IOException if java.io operation throws
2596 public final String
fileOpenBox(final String path
,
2597 final TFileOpenBox
.Type type
) throws IOException
{
2599 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2600 return box
.getFilename();
2604 * Convenience function to create a new window and make it active.
2605 * Window will be located at (0, 0).
2607 * @param title window title, will be centered along the top border
2608 * @param width width of window
2609 * @param height height of window
2611 public final TWindow
addWindow(final String title
, final int width
,
2614 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2618 * Convenience function to create a new window and make it active.
2619 * Window will be located at (0, 0).
2621 * @param title window title, will be centered along the top border
2622 * @param width width of window
2623 * @param height height of window
2624 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2626 public final TWindow
addWindow(final String title
,
2627 final int width
, final int height
, final int flags
) {
2629 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2634 * Convenience function to create a new window and make it active.
2636 * @param title window title, will be centered along the top border
2637 * @param x column relative to parent
2638 * @param y row relative to parent
2639 * @param width width of window
2640 * @param height height of window
2642 public final TWindow
addWindow(final String title
,
2643 final int x
, final int y
, final int width
, final int height
) {
2645 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2650 * Convenience function to create a new window and make it active.
2652 * @param title window title, will be centered along the top border
2653 * @param x column relative to parent
2654 * @param y row relative to parent
2655 * @param width width of window
2656 * @param height height of window
2657 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2659 public final TWindow
addWindow(final String title
,
2660 final int x
, final int y
, final int width
, final int height
,
2663 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);