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
.Screen
;
55 import jexer
.backend
.SwingBackend
;
56 import jexer
.backend
.ECMA48Backend
;
57 import jexer
.backend
.TWindowBackend
;
58 import jexer
.menu
.TMenu
;
59 import jexer
.menu
.TMenuItem
;
60 import static jexer
.TCommand
.*;
61 import static jexer
.TKeypress
.*;
64 * TApplication is the main driver class for a full Text User Interface
65 * application. It manages windows, provides a menu bar and status bar, and
66 * processes events received from the user.
68 public class TApplication
implements Runnable
{
70 // ------------------------------------------------------------------------
71 // Public constants -------------------------------------------------------
72 // ------------------------------------------------------------------------
75 * If true, emit thread stuff to System.err.
77 private static final boolean debugThreads
= false;
80 * If true, emit events being processed to System.err.
82 private static final boolean debugEvents
= false;
85 * If true, do "smart placement" on new windows that are not specified to
88 private static final boolean smartWindowPlacement
= true;
91 * Two backend types are available.
93 public static enum BackendType
{
100 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
105 * Synonym for ECMA48.
110 // ------------------------------------------------------------------------
111 // Primary/secondary event handlers ---------------------------------------
112 // ------------------------------------------------------------------------
115 * WidgetEventHandler is the main event consumer loop. There are at most
116 * two such threads in existence: the primary for normal case and a
117 * secondary that is used for TMessageBox, TInputBox, and similar.
119 private class WidgetEventHandler
implements Runnable
{
121 * The main application.
123 private TApplication application
;
126 * Whether or not this WidgetEventHandler is the primary or secondary
129 private boolean primary
= true;
132 * Public constructor.
134 * @param application the main application
135 * @param primary if true, this is the primary event handler thread
137 public WidgetEventHandler(final TApplication application
,
138 final boolean primary
) {
140 this.application
= application
;
141 this.primary
= primary
;
150 while (!application
.quit
) {
152 // Wait until application notifies me
153 while (!application
.quit
) {
155 synchronized (application
.drainEventQueue
) {
156 if (application
.drainEventQueue
.size() > 0) {
161 synchronized (this) {
163 System
.err
.printf("%s %s sleep\n", this,
164 primary ?
"primary" : "secondary");
170 System
.err
.printf("%s %s AWAKE\n", this,
171 primary ?
"primary" : "secondary");
175 && (application
.secondaryEventReceiver
== null)
177 // Secondary thread, emergency exit. If we
178 // got here then something went wrong with
179 // the handoff between yield() and
181 synchronized (application
.primaryEventHandler
) {
182 application
.primaryEventHandler
.notify();
184 application
.secondaryEventHandler
= null;
185 throw new RuntimeException(
186 "secondary exited at wrong time");
190 } catch (InterruptedException e
) {
195 // Wait for drawAll() or doIdle() to be done, then handle the
197 boolean oldLock
= lockHandleEvent();
198 assert (oldLock
== false);
200 // Pull all events off the queue
202 TInputEvent event
= null;
203 synchronized (application
.drainEventQueue
) {
204 if (application
.drainEventQueue
.size() == 0) {
207 event
= application
.drainEventQueue
.remove(0);
209 application
.repaint
= true;
211 primaryHandleEvent(event
);
213 secondaryHandleEvent(event
);
216 && (application
.secondaryEventReceiver
== null)
218 // Secondary thread, time to exit.
220 // DO NOT UNLOCK. Primary thread just came back from
221 // primaryHandleEvent() and will unlock in the else
222 // block below. Just wake it up.
223 synchronized (application
.primaryEventHandler
) {
224 application
.primaryEventHandler
.notify();
226 // Now eliminate my reference so that
227 // wakeEventHandler() resumes working on the primary.
228 application
.secondaryEventHandler
= null;
235 // Unlock. Either I am primary thread, or I am secondary
236 // thread and still running.
237 oldLock
= unlockHandleEvent();
238 assert (oldLock
== true);
240 // I have done some work of some kind. Tell the main run()
241 // loop to wake up now.
242 synchronized (application
) {
243 application
.notify();
246 } // while (true) (main runnable loop)
251 * The primary event handler thread.
253 private volatile WidgetEventHandler primaryEventHandler
;
256 * The secondary event handler thread.
258 private volatile WidgetEventHandler secondaryEventHandler
;
261 * The widget receiving events from the secondary event handler thread.
263 private volatile TWidget secondaryEventReceiver
;
266 * Spinlock for the primary and secondary event handlers.
267 * WidgetEventHandler.run() is responsible for setting this value.
269 private volatile boolean insideHandleEvent
= false;
272 * Wake the sleeping active event handler.
274 private void wakeEventHandler() {
275 if (secondaryEventHandler
!= null) {
276 synchronized (secondaryEventHandler
) {
277 secondaryEventHandler
.notify();
280 assert (primaryEventHandler
!= null);
281 synchronized (primaryEventHandler
) {
282 primaryEventHandler
.notify();
288 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
289 * spin indefinitely until unlockHandleEvent() is called.
291 * @return the old value of insideHandleEvent
293 private boolean lockHandleEvent() {
295 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
298 boolean oldValue
= true;
300 synchronized (this) {
301 // Wait for TApplication.run() to finish using the global state
302 // before allowing further event processing.
303 while (lockoutHandleEvent
== true) {
305 // Backoff so that the backend can finish its work.
307 } catch (InterruptedException e
) {
312 oldValue
= insideHandleEvent
;
313 insideHandleEvent
= true;
317 System
.err
.printf(" ***\n");
323 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
324 * spin indefinitely until unlockHandleEvent() is called.
326 * @return the old value of insideHandleEvent
328 private boolean unlockHandleEvent() {
330 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
333 synchronized (this) {
334 boolean oldValue
= insideHandleEvent
;
335 insideHandleEvent
= false;
341 * Spinlock for the primary and secondary event handlers. When true, the
342 * event handlers will spinlock wait before calling handleEvent().
344 private volatile boolean lockoutHandleEvent
= false;
347 * TApplication.run() needs to be able rely on the global data structures
348 * being intact when calling doIdle() and drawAll(). Tell the event
349 * handlers to wait for an unlock before handling their events.
351 private void stopEventHandlers() {
353 System
.err
.printf(">> stopEventHandlers()");
356 lockoutHandleEvent
= true;
357 // Wait for the last event to finish processing before returning
358 // control to TApplication.run().
359 while (insideHandleEvent
== true) {
361 // Backoff so that the event handler can finish its work.
363 } catch (InterruptedException e
) {
369 System
.err
.printf(" XXX\n");
374 * TApplication.run() needs to be able rely on the global data structures
375 * being intact when calling doIdle() and drawAll(). Tell the event
376 * handlers that it is now OK to handle their events.
378 private void startEventHandlers() {
380 System
.err
.printf("<< startEventHandlers()\n");
382 lockoutHandleEvent
= false;
385 // ------------------------------------------------------------------------
386 // TApplication attributes ------------------------------------------------
387 // ------------------------------------------------------------------------
390 * Access to the physical screen, keyboard, and mouse.
392 private Backend backend
;
397 * @return the Backend
399 public final Backend
getBackend() {
408 public final Screen
getScreen() {
409 if (backend
instanceof TWindowBackend
) {
410 // We are being rendered to a TWindow. We can't use its
411 // getScreen() method because that is how it is rendering to a
412 // hardware backend somewhere. Instead use its getOtherScreen()
414 return ((TWindowBackend
) backend
).getOtherScreen();
416 return backend
.getScreen();
421 * Actual mouse coordinate X.
426 * Actual mouse coordinate Y.
431 * Old version of mouse coordinate X.
433 private int oldMouseX
;
436 * Old version mouse coordinate Y.
438 private int oldMouseY
;
441 * Event queue that is filled by run().
443 private List
<TInputEvent
> fillEventQueue
;
446 * Event queue that will be drained by either primary or secondary
449 private List
<TInputEvent
> drainEventQueue
;
452 * Top-level menus in this application.
454 private List
<TMenu
> menus
;
457 * Stack of activated sub-menus in this application.
459 private List
<TMenu
> subMenus
;
462 * The currently active menu.
464 private TMenu activeMenu
= null;
467 * Active keyboard accelerators.
469 private Map
<TKeypress
, TMenuItem
> accelerators
;
474 private List
<TMenuItem
> menuItems
;
477 * Windows and widgets pull colors from this ColorTheme.
479 private ColorTheme theme
;
482 * Get the color theme.
486 public final ColorTheme
getTheme() {
491 * The top-level windows (but not menus).
493 private List
<TWindow
> windows
;
496 * The currently acive window.
498 private TWindow activeWindow
= null;
501 * Timers that are being ticked.
503 private List
<TTimer
> timers
;
506 * When true, exit the application.
508 private volatile boolean quit
= false;
511 * When true, repaint the entire screen.
513 private volatile boolean repaint
= true;
516 * Y coordinate of the top edge of the desktop. For now this is a
517 * constant. Someday it would be nice to have a multi-line menu or
520 private static final int desktopTop
= 1;
523 * Get Y coordinate of the top edge of the desktop.
525 * @return Y coordinate of the top edge of the desktop
527 public final int getDesktopTop() {
532 * Y coordinate of the bottom edge of the desktop.
534 private int desktopBottom
;
537 * Get Y coordinate of the bottom edge of the desktop.
539 * @return Y coordinate of the bottom edge of the desktop
541 public final int getDesktopBottom() {
542 return desktopBottom
;
546 * An optional TDesktop background window that is drawn underneath
549 private TDesktop desktop
;
552 * Set the TDesktop instance.
554 * @param desktop a TDesktop instance, or null to remove the one that is
557 public final void setDesktop(final TDesktop desktop
) {
558 if (this.desktop
!= null) {
559 this.desktop
.onClose();
561 this.desktop
= desktop
;
565 * Get the TDesktop instance.
567 * @return the desktop, or null if it is not set
569 public final TDesktop
getDesktop() {
574 * Get the current active window.
576 * @return the active window, or null if it is not set
578 public final TWindow
getActiveWindow() {
583 * Get a (shallow) copy of the window list.
585 * @return a copy of the list of windows for this application
587 public final List
<TWindow
> getAllWindows() {
588 List
<TWindow
> result
= new LinkedList
<TWindow
>();
589 result
.addAll(windows
);
594 * If true, focus follows mouse: windows automatically raised if the
595 * mouse passes over them.
597 private boolean focusFollowsMouse
= false;
600 * Get focusFollowsMouse flag.
602 * @return true if focus follows mouse: windows automatically raised if
603 * the mouse passes over them
605 public boolean getFocusFollowsMouse() {
606 return focusFollowsMouse
;
610 * Set focusFollowsMouse flag.
612 * @param focusFollowsMouse if true, focus follows mouse: windows
613 * automatically raised if the mouse passes over them
615 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
616 this.focusFollowsMouse
= focusFollowsMouse
;
619 // ------------------------------------------------------------------------
620 // General behavior -------------------------------------------------------
621 // ------------------------------------------------------------------------
624 * Display the about dialog.
626 protected void showAboutDialog() {
627 messageBox("About", "Jexer Version " +
628 this.getClass().getPackage().getImplementationVersion(),
629 TMessageBox
.Type
.OK
);
632 // ------------------------------------------------------------------------
633 // Constructors -----------------------------------------------------------
634 // ------------------------------------------------------------------------
637 * Public constructor.
639 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
641 * @throws UnsupportedEncodingException if an exception is thrown when
642 * creating the InputStreamReader
644 public TApplication(final BackendType backendType
)
645 throws UnsupportedEncodingException
{
647 switch (backendType
) {
649 // The default SwingBackend is 80x25, 20 pt font. If you want to
650 // change that, you can pass the extra arguments to the
651 // SwingBackend constructor here. For example, if you wanted
652 // 90x30, 16 pt font:
654 // backend = new SwingBackend(this, 90, 30, 16);
655 backend
= new SwingBackend(this);
660 backend
= new ECMA48Backend(this, null, null);
663 throw new IllegalArgumentException("Invalid backend type: "
670 * Public constructor. The backend type will be BackendType.ECMA48.
672 * @param input an InputStream connected to the remote user, or null for
673 * System.in. If System.in is used, then on non-Windows systems it will
674 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
675 * mode. input is always converted to a Reader with UTF-8 encoding.
676 * @param output an OutputStream connected to the remote user, or null
677 * for System.out. output is always converted to a Writer with UTF-8
679 * @throws UnsupportedEncodingException if an exception is thrown when
680 * creating the InputStreamReader
682 public TApplication(final InputStream input
,
683 final OutputStream output
) throws UnsupportedEncodingException
{
685 backend
= new ECMA48Backend(this, input
, output
);
690 * Public constructor. The backend type will be BackendType.ECMA48.
692 * @param input the InputStream underlying 'reader'. Its available()
693 * method is used to determine if reader.read() will block or not.
694 * @param reader a Reader connected to the remote user.
695 * @param writer a PrintWriter connected to the remote user.
696 * @param setRawMode if true, set System.in into raw mode with stty.
697 * This should in general not be used. It is here solely for Demo3,
698 * which uses System.in.
699 * @throws IllegalArgumentException if input, reader, or writer are null.
701 public TApplication(final InputStream input
, final Reader reader
,
702 final PrintWriter writer
, final boolean setRawMode
) {
704 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
709 * Public constructor. The backend type will be BackendType.ECMA48.
711 * @param input the InputStream underlying 'reader'. Its available()
712 * method is used to determine if reader.read() will block or not.
713 * @param reader a Reader connected to the remote user.
714 * @param writer a PrintWriter connected to the remote user.
715 * @throws IllegalArgumentException if input, reader, or writer are null.
717 public TApplication(final InputStream input
, final Reader reader
,
718 final PrintWriter writer
) {
720 this(input
, reader
, writer
, false);
724 * Public constructor. This hook enables use with new non-Jexer
727 * @param backend a Backend that is already ready to go.
729 public TApplication(final Backend backend
) {
730 this.backend
= backend
;
731 backend
.setListener(this);
736 * Finish construction once the backend is set.
738 private void TApplicationImpl() {
739 theme
= new ColorTheme();
740 desktopBottom
= getScreen().getHeight() - 1;
741 fillEventQueue
= new ArrayList
<TInputEvent
>();
742 drainEventQueue
= new ArrayList
<TInputEvent
>();
743 windows
= new LinkedList
<TWindow
>();
744 menus
= new LinkedList
<TMenu
>();
745 subMenus
= new LinkedList
<TMenu
>();
746 timers
= new LinkedList
<TTimer
>();
747 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
748 menuItems
= new ArrayList
<TMenuItem
>();
749 desktop
= new TDesktop(this);
751 // Setup the main consumer thread
752 primaryEventHandler
= new WidgetEventHandler(this, true);
753 (new Thread(primaryEventHandler
)).start();
756 // ------------------------------------------------------------------------
757 // Screen refresh loop ----------------------------------------------------
758 // ------------------------------------------------------------------------
761 * Invert the cell color at a position. This is used to track the mouse.
763 * @param x column position
764 * @param y row position
766 private void invertCell(final int x
, final int y
) {
768 System
.err
.printf("invertCell() %d %d\n", x
, y
);
770 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
771 attr
.setForeColor(attr
.getForeColor().invert());
772 attr
.setBackColor(attr
.getBackColor().invert());
773 getScreen().putAttrXY(x
, y
, attr
, false);
779 private void drawAll() {
781 System
.err
.printf("drawAll() enter\n");
786 System
.err
.printf("drawAll() !repaint\n");
788 synchronized (getScreen()) {
789 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
790 // The only thing that has happened is the mouse moved.
791 // Clear the old position and draw the new position.
792 invertCell(oldMouseX
, oldMouseY
);
793 invertCell(mouseX
, mouseY
);
797 if (getScreen().isDirty()) {
798 backend
.flushScreen();
805 System
.err
.printf("drawAll() REDRAW\n");
808 // If true, the cursor is not visible
809 boolean cursor
= false;
811 // Start with a clean screen
815 if (desktop
!= null) {
816 desktop
.drawChildren();
819 // Draw each window in reverse Z order
820 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
821 Collections
.sort(sorted
);
822 TWindow topLevel
= null;
823 if (sorted
.size() > 0) {
824 topLevel
= sorted
.get(0);
826 Collections
.reverse(sorted
);
827 for (TWindow window
: sorted
) {
828 if (window
.isShown()) {
829 window
.drawChildren();
833 // Draw the blank menubar line - reset the screen clipping first so
834 // it won't trim it out.
835 getScreen().resetClipping();
836 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
837 theme
.getColor("tmenu"));
838 // Now draw the menus.
840 for (TMenu menu
: menus
) {
841 CellAttributes menuColor
;
842 CellAttributes menuMnemonicColor
;
843 if (menu
.isActive()) {
844 menuColor
= theme
.getColor("tmenu.highlighted");
845 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
848 menuColor
= theme
.getColor("tmenu");
849 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
851 // Draw the menu title
852 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
854 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
855 // Draw the highlight character
856 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
857 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
859 if (menu
.isActive()) {
861 // Reset the screen clipping so we can draw the next title.
862 getScreen().resetClipping();
864 x
+= menu
.getTitle().length() + 2;
867 for (TMenu menu
: subMenus
) {
868 // Reset the screen clipping so we can draw the next sub-menu.
869 getScreen().resetClipping();
873 // Draw the status bar of the top-level window
874 TStatusBar statusBar
= null;
875 if (topLevel
!= null) {
876 statusBar
= topLevel
.getStatusBar();
878 if (statusBar
!= null) {
879 getScreen().resetClipping();
880 statusBar
.setWidth(getScreen().getWidth());
881 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
884 CellAttributes barColor
= new CellAttributes();
885 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
886 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
890 // Draw the mouse pointer
891 invertCell(mouseX
, mouseY
);
895 // Place the cursor if it is visible
896 TWidget activeWidget
= null;
897 if (sorted
.size() > 0) {
898 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
899 if (activeWidget
.isCursorVisible()) {
900 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
901 activeWidget
.getCursorAbsoluteY());
908 getScreen().hideCursor();
911 // Flush the screen contents
912 if (getScreen().isDirty()) {
913 backend
.flushScreen();
919 // ------------------------------------------------------------------------
920 // Main loop --------------------------------------------------------------
921 // ------------------------------------------------------------------------
924 * Force this application to exit.
931 * Run this application until it exits.
934 boolean first
= true;
937 // Timeout is in milliseconds, so default timeout after 1 second
945 // If I've got no updates to render, wait for something from the
946 // backend or a timer.
948 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
950 // Never sleep longer than 50 millis. We need time for
951 // windows with background tasks to update the display, and
952 // still flip buffers reasonably quickly in
953 // backend.flushPhysical().
954 timeout
= getSleepTime(50);
958 // As of now, I've got nothing to do: no I/O, nothing from
959 // the consumer threads, no timers that need to run ASAP. So
960 // wait until either the backend or the consumer threads have
964 System
.err
.println("sleep " + timeout
+ " millis");
966 synchronized (this) {
969 } catch (InterruptedException e
) {
970 // I'm awake and don't care why, let's see what's going
976 // Prevent stepping on the primary or secondary event handler.
979 // Pull any pending I/O events
980 backend
.getEvents(fillEventQueue
);
982 // Dispatch each event to the appropriate handler, one at a time.
984 TInputEvent event
= null;
985 if (fillEventQueue
.size() == 0) {
988 event
= fillEventQueue
.remove(0);
989 metaHandleEvent(event
);
992 // Wake a consumer thread if we have any pending events.
993 if (drainEventQueue
.size() > 0) {
997 // Process timers and call doIdle()'s
1000 // Update the screen
1001 synchronized (getScreen()) {
1005 // Let the event handlers run again.
1006 startEventHandlers();
1010 // Shutdown the event consumer threads
1011 if (secondaryEventHandler
!= null) {
1012 synchronized (secondaryEventHandler
) {
1013 secondaryEventHandler
.notify();
1016 if (primaryEventHandler
!= null) {
1017 synchronized (primaryEventHandler
) {
1018 primaryEventHandler
.notify();
1022 // Shutdown the user I/O thread(s)
1025 // Close all the windows. This gives them an opportunity to release
1032 * Peek at certain application-level events, add to eventQueue, and wake
1033 * up the consuming Thread.
1035 * @param event the input event to consume
1037 private void metaHandleEvent(final TInputEvent event
) {
1040 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1041 event
)); System
.err
.flush();
1045 // Do no more processing if the application is already trying
1050 // Special application-wide events -------------------------------
1053 if (event
instanceof TCommandEvent
) {
1054 TCommandEvent command
= (TCommandEvent
) event
;
1055 if (command
.getCmd().equals(cmAbort
)) {
1062 if (event
instanceof TResizeEvent
) {
1063 TResizeEvent resize
= (TResizeEvent
) event
;
1064 synchronized (getScreen()) {
1065 getScreen().setDimensions(resize
.getWidth(),
1066 resize
.getHeight());
1067 desktopBottom
= getScreen().getHeight() - 1;
1073 if (desktop
!= null) {
1074 desktop
.setDimensions(0, 0, resize
.getWidth(),
1075 resize
.getHeight() - 1);
1080 // Put into the main queue
1081 drainEventQueue
.add(event
);
1085 * Dispatch one event to the appropriate widget or application-level
1086 * event handler. This is the primary event handler, it has the normal
1087 * application-wide event handling.
1089 * @param event the input event to consume
1090 * @see #secondaryHandleEvent(TInputEvent event)
1092 private void primaryHandleEvent(final TInputEvent event
) {
1095 System
.err
.printf("Handle event: %s\n", event
);
1098 // Special application-wide events -----------------------------------
1100 // Peek at the mouse position
1101 if (event
instanceof TMouseEvent
) {
1102 TMouseEvent mouse
= (TMouseEvent
) event
;
1103 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1106 mouseX
= mouse
.getX();
1107 mouseY
= mouse
.getY();
1110 // See if we need to switch focus to another window or the menu
1111 checkSwitchFocus((TMouseEvent
) event
);
1114 // Handle menu events
1115 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1116 TMenu menu
= activeMenu
;
1118 if (event
instanceof TMouseEvent
) {
1119 TMouseEvent mouse
= (TMouseEvent
) event
;
1121 while (subMenus
.size() > 0) {
1122 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1123 if (subMenu
.mouseWouldHit(mouse
)) {
1126 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1127 && (!mouse
.isMouse1())
1128 && (!mouse
.isMouse2())
1129 && (!mouse
.isMouse3())
1130 && (!mouse
.isMouseWheelUp())
1131 && (!mouse
.isMouseWheelDown())
1135 // We navigated away from a sub-menu, so close it
1139 // Convert the mouse relative x/y to menu coordinates
1140 assert (mouse
.getX() == mouse
.getAbsoluteX());
1141 assert (mouse
.getY() == mouse
.getAbsoluteY());
1142 if (subMenus
.size() > 0) {
1143 menu
= subMenus
.get(subMenus
.size() - 1);
1145 mouse
.setX(mouse
.getX() - menu
.getX());
1146 mouse
.setY(mouse
.getY() - menu
.getY());
1148 menu
.handleEvent(event
);
1152 if (event
instanceof TKeypressEvent
) {
1153 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1155 // See if this key matches an accelerator, and is not being
1156 // shortcutted by the active window, and if so dispatch the menu
1158 boolean windowWillShortcut
= false;
1159 if (activeWindow
!= null) {
1160 assert (activeWindow
.isShown());
1161 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1162 // We do not process this key, it will be passed to the
1164 windowWillShortcut
= true;
1168 if (!windowWillShortcut
&& !modalWindowActive()) {
1169 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1170 TMenuItem item
= null;
1171 synchronized (accelerators
) {
1172 item
= accelerators
.get(keypressLowercase
);
1175 if (item
.isEnabled()) {
1176 // Let the menu item dispatch
1182 // Handle the keypress
1183 if (onKeypress(keypress
)) {
1189 if (event
instanceof TCommandEvent
) {
1190 if (onCommand((TCommandEvent
) event
)) {
1195 if (event
instanceof TMenuEvent
) {
1196 if (onMenu((TMenuEvent
) event
)) {
1201 // Dispatch events to the active window -------------------------------
1202 boolean dispatchToDesktop
= true;
1203 TWindow window
= activeWindow
;
1204 if (window
!= null) {
1205 assert (window
.isActive());
1206 assert (window
.isShown());
1207 if (event
instanceof TMouseEvent
) {
1208 TMouseEvent mouse
= (TMouseEvent
) event
;
1209 // Convert the mouse relative x/y to window coordinates
1210 assert (mouse
.getX() == mouse
.getAbsoluteX());
1211 assert (mouse
.getY() == mouse
.getAbsoluteY());
1212 mouse
.setX(mouse
.getX() - window
.getX());
1213 mouse
.setY(mouse
.getY() - window
.getY());
1215 if (window
.mouseWouldHit(mouse
)) {
1216 dispatchToDesktop
= false;
1218 } else if (event
instanceof TKeypressEvent
) {
1219 dispatchToDesktop
= false;
1223 System
.err
.printf("TApplication dispatch event: %s\n",
1226 window
.handleEvent(event
);
1228 if (dispatchToDesktop
) {
1229 // This event is fair game for the desktop to process.
1230 if (desktop
!= null) {
1231 desktop
.handleEvent(event
);
1237 * Dispatch one event to the appropriate widget or application-level
1238 * event handler. This is the secondary event handler used by certain
1239 * special dialogs (currently TMessageBox and TFileOpenBox).
1241 * @param event the input event to consume
1242 * @see #primaryHandleEvent(TInputEvent event)
1244 private void secondaryHandleEvent(final TInputEvent event
) {
1245 // Peek at the mouse position
1246 if (event
instanceof TMouseEvent
) {
1247 TMouseEvent mouse
= (TMouseEvent
) event
;
1248 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1251 mouseX
= mouse
.getX();
1252 mouseY
= mouse
.getY();
1256 secondaryEventReceiver
.handleEvent(event
);
1260 * Enable a widget to override the primary event thread.
1262 * @param widget widget that will receive events
1264 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1265 assert (secondaryEventReceiver
== null);
1266 assert (secondaryEventHandler
== null);
1267 assert ((widget
instanceof TMessageBox
)
1268 || (widget
instanceof TFileOpenBox
));
1269 secondaryEventReceiver
= widget
;
1270 secondaryEventHandler
= new WidgetEventHandler(this, false);
1271 (new Thread(secondaryEventHandler
)).start();
1275 * Yield to the secondary thread.
1277 public final void yield() {
1278 assert (secondaryEventReceiver
!= null);
1279 // This is where we handoff the event handler lock from the primary
1280 // to secondary thread. We unlock here, and in a future loop the
1281 // secondary thread locks again. When it gives up, we have the
1282 // single lock back.
1283 boolean oldLock
= unlockHandleEvent();
1286 while (secondaryEventReceiver
!= null) {
1287 synchronized (primaryEventHandler
) {
1289 primaryEventHandler
.wait();
1290 } catch (InterruptedException e
) {
1298 * Do stuff when there is no user input.
1300 private void doIdle() {
1302 System
.err
.printf("doIdle()\n");
1305 // Now run any timers that have timed out
1306 Date now
= new Date();
1307 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1308 for (TTimer timer
: timers
) {
1309 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1311 if (timer
.recurring
) {
1312 keepTimers
.add(timer
);
1315 keepTimers
.add(timer
);
1318 timers
= keepTimers
;
1321 for (TWindow window
: windows
) {
1324 if (desktop
!= null) {
1329 // ------------------------------------------------------------------------
1330 // TWindow management -----------------------------------------------------
1331 // ------------------------------------------------------------------------
1334 * Return the total number of windows.
1336 * @return the total number of windows
1338 public final int windowCount() {
1339 return windows
.size();
1343 * Return the number of windows that are showing.
1345 * @return the number of windows that are showing on screen
1347 public final int shownWindowCount() {
1349 for (TWindow w
: windows
) {
1358 * Return the number of windows that are hidden.
1360 * @return the number of windows that are hidden
1362 public final int hiddenWindowCount() {
1364 for (TWindow w
: windows
) {
1373 * Check if a window instance is in this application's window list.
1375 * @param window window to look for
1376 * @return true if this window is in the list
1378 public final boolean hasWindow(final TWindow window
) {
1379 if (windows
.size() == 0) {
1382 for (TWindow w
: windows
) {
1384 assert (window
.getApplication() == this);
1392 * Activate a window: bring it to the top and have it receive events.
1394 * @param window the window to become the new active window
1396 public void activateWindow(final TWindow window
) {
1397 if (hasWindow(window
) == false) {
1399 * Someone has a handle to a window I don't have. Ignore this
1405 // Whatever window might be moving/dragging, stop it now.
1406 for (TWindow w
: windows
) {
1407 if (w
.inMovements()) {
1412 assert (windows
.size() > 0);
1414 if (window
.isHidden()) {
1415 // Unhiding will also activate.
1419 assert (window
.isShown());
1421 if (windows
.size() == 1) {
1422 assert (window
== windows
.get(0));
1423 if (activeWindow
== null) {
1424 activeWindow
= window
;
1426 activeWindow
.setActive(true);
1427 activeWindow
.onFocus();
1430 assert (window
.isActive());
1431 assert (activeWindow
== window
);
1435 if (activeWindow
== window
) {
1436 assert (window
.isActive());
1438 // Window is already active, do nothing.
1442 assert (!window
.isActive());
1443 if (activeWindow
!= null) {
1444 assert (activeWindow
.getZ() == 0);
1446 activeWindow
.onUnfocus();
1447 activeWindow
.setActive(false);
1448 activeWindow
.setZ(window
.getZ());
1450 activeWindow
= window
;
1451 activeWindow
.setZ(0);
1452 activeWindow
.setActive(true);
1453 activeWindow
.onFocus();
1460 * @param window the window to hide
1462 public void hideWindow(final TWindow window
) {
1463 if (hasWindow(window
) == false) {
1465 * Someone has a handle to a window I don't have. Ignore this
1471 // Whatever window might be moving/dragging, stop it now.
1472 for (TWindow w
: windows
) {
1473 if (w
.inMovements()) {
1478 assert (windows
.size() > 0);
1480 if (!window
.hidden
) {
1481 if (window
== activeWindow
) {
1482 if (shownWindowCount() > 1) {
1485 activeWindow
= null;
1486 window
.setActive(false);
1490 window
.hidden
= true;
1498 * @param window the window to show
1500 public void showWindow(final TWindow window
) {
1501 if (hasWindow(window
) == false) {
1503 * Someone has a handle to a window I don't have. Ignore this
1509 // Whatever window might be moving/dragging, stop it now.
1510 for (TWindow w
: windows
) {
1511 if (w
.inMovements()) {
1516 assert (windows
.size() > 0);
1518 if (window
.hidden
) {
1519 window
.hidden
= false;
1521 activateWindow(window
);
1526 * Close window. Note that the window's destructor is NOT called by this
1527 * method, instead the GC is assumed to do the cleanup.
1529 * @param window the window to remove
1531 public final void closeWindow(final TWindow window
) {
1532 if (hasWindow(window
) == false) {
1534 * Someone has a handle to a window I don't have. Ignore this
1540 synchronized (windows
) {
1541 // Whatever window might be moving/dragging, stop it now.
1542 for (TWindow w
: windows
) {
1543 if (w
.inMovements()) {
1548 int z
= window
.getZ();
1551 Collections
.sort(windows
);
1553 activeWindow
= null;
1554 for (TWindow w
: windows
) {
1556 w
.setZ(w
.getZ() - 1);
1557 if (w
.getZ() == 0) {
1560 assert (activeWindow
== null);
1572 // Perform window cleanup
1575 // Check if we are closing a TMessageBox or similar
1576 if (secondaryEventReceiver
!= null) {
1577 assert (secondaryEventHandler
!= null);
1579 // Do not send events to the secondaryEventReceiver anymore, the
1580 // window is closed.
1581 secondaryEventReceiver
= null;
1583 // Wake the secondary thread, it will wake the primary as it
1585 synchronized (secondaryEventHandler
) {
1586 secondaryEventHandler
.notify();
1590 // Permit desktop to be active if it is the only thing left.
1591 if (desktop
!= null) {
1592 if (windows
.size() == 0) {
1593 desktop
.setActive(true);
1599 * Switch to the next window.
1601 * @param forward if true, then switch to the next window in the list,
1602 * otherwise switch to the previous window in the list
1604 public final void switchWindow(final boolean forward
) {
1605 // Only switch if there are multiple visible windows
1606 if (shownWindowCount() < 2) {
1609 assert (activeWindow
!= null);
1611 synchronized (windows
) {
1612 // Whatever window might be moving/dragging, stop it now.
1613 for (TWindow w
: windows
) {
1614 if (w
.inMovements()) {
1619 // Swap z/active between active window and the next in the list
1620 int activeWindowI
= -1;
1621 for (int i
= 0; i
< windows
.size(); i
++) {
1622 if (windows
.get(i
) == activeWindow
) {
1623 assert (activeWindow
.isActive());
1627 assert (!windows
.get(0).isActive());
1630 assert (activeWindowI
>= 0);
1632 // Do not switch if a window is modal
1633 if (activeWindow
.isModal()) {
1637 int nextWindowI
= activeWindowI
;
1641 nextWindowI
%= windows
.size();
1644 if (nextWindowI
< 0) {
1645 nextWindowI
= windows
.size() - 1;
1649 if (windows
.get(nextWindowI
).isShown()) {
1650 activateWindow(windows
.get(nextWindowI
));
1654 } // synchronized (windows)
1659 * Add a window to my window list and make it active.
1661 * @param window new window to add
1663 public final void addWindow(final TWindow window
) {
1665 // Do not add menu windows to the window list.
1666 if (window
instanceof TMenu
) {
1670 // Do not add the desktop to the window list.
1671 if (window
instanceof TDesktop
) {
1675 synchronized (windows
) {
1676 // Whatever window might be moving/dragging, stop it now.
1677 for (TWindow w
: windows
) {
1678 if (w
.inMovements()) {
1683 // Do not allow a modal window to spawn a non-modal window. If a
1684 // modal window is active, then this window will become modal
1686 if (modalWindowActive()) {
1687 window
.flags
|= TWindow
.MODAL
;
1688 window
.flags
|= TWindow
.CENTERED
;
1689 window
.hidden
= false;
1691 if (window
.isShown()) {
1692 for (TWindow w
: windows
) {
1697 w
.setZ(w
.getZ() + 1);
1700 windows
.add(window
);
1701 if (window
.isShown()) {
1702 activeWindow
= window
;
1703 activeWindow
.setZ(0);
1704 activeWindow
.setActive(true);
1705 activeWindow
.onFocus();
1708 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1709 && smartWindowPlacement
) {
1711 doSmartPlacement(window
);
1715 // Desktop cannot be active over any other window.
1716 if (desktop
!= null) {
1717 desktop
.setActive(false);
1722 * Check if there is a system-modal window on top.
1724 * @return true if the active window is modal
1726 private boolean modalWindowActive() {
1727 if (windows
.size() == 0) {
1731 for (TWindow w
: windows
) {
1741 * Close all open windows.
1743 private void closeAllWindows() {
1744 // Don't do anything if we are in the menu
1745 if (activeMenu
!= null) {
1748 while (windows
.size() > 0) {
1749 closeWindow(windows
.get(0));
1754 * Re-layout the open windows as non-overlapping tiles. This produces
1755 * almost the same results as Turbo Pascal 7.0's IDE.
1757 private void tileWindows() {
1758 synchronized (windows
) {
1759 // Don't do anything if we are in the menu
1760 if (activeMenu
!= null) {
1763 int z
= windows
.size();
1769 a
= (int)(Math
.sqrt(z
));
1773 if (((a
* b
) + c
) == z
) {
1781 int newWidth
= (getScreen().getWidth() / a
);
1782 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1783 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1785 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1786 Collections
.sort(sorted
);
1787 Collections
.reverse(sorted
);
1788 for (int i
= 0; i
< sorted
.size(); i
++) {
1789 int logicalX
= i
/ b
;
1790 int logicalY
= i
% b
;
1791 if (i
>= ((a
- 1) * b
)) {
1793 logicalY
= i
- ((a
- 1) * b
);
1796 TWindow w
= sorted
.get(i
);
1797 w
.setX(logicalX
* newWidth
);
1798 w
.setWidth(newWidth
);
1799 if (i
>= ((a
- 1) * b
)) {
1800 w
.setY((logicalY
* newHeight2
) + 1);
1801 w
.setHeight(newHeight2
);
1803 w
.setY((logicalY
* newHeight1
) + 1);
1804 w
.setHeight(newHeight1
);
1811 * Re-layout the open windows as overlapping cascaded windows.
1813 private void cascadeWindows() {
1814 synchronized (windows
) {
1815 // Don't do anything if we are in the menu
1816 if (activeMenu
!= null) {
1821 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1822 Collections
.sort(sorted
);
1823 Collections
.reverse(sorted
);
1824 for (TWindow window
: sorted
) {
1829 if (x
> getScreen().getWidth()) {
1832 if (y
>= getScreen().getHeight()) {
1840 * Place a window to minimize its overlap with other windows.
1842 * @param window the window to place
1844 public final void doSmartPlacement(final TWindow window
) {
1845 // This is a pretty dumb algorithm, but seems to work. The hardest
1846 // part is computing these "overlap" values seeking a minimum average
1849 int yMin
= desktopTop
;
1850 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1851 int yMax
= desktopBottom
- window
.getHeight() + 1;
1859 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1860 // No work to do, bail out.
1864 // Compute the overlap matrix without the new window.
1865 int width
= getScreen().getWidth();
1866 int height
= getScreen().getHeight();
1867 int overlapMatrix
[][] = new int[width
][height
];
1868 for (TWindow w
: windows
) {
1872 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1876 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1880 overlapMatrix
[x
][y
]++;
1885 long oldOverlapTotal
= 0;
1886 long oldOverlapN
= 0;
1887 for (int x
= 0; x
< width
; x
++) {
1888 for (int y
= 0; y
< height
; y
++) {
1889 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1890 if (overlapMatrix
[x
][y
] > 0) {
1897 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1898 boolean first
= true;
1899 int windowX
= window
.getX();
1900 int windowY
= window
.getY();
1902 // For each possible (x, y) position for the new window, compute a
1903 // new overlap matrix.
1904 for (int x
= xMin
; x
< xMax
; x
++) {
1905 for (int y
= yMin
; y
< yMax
; y
++) {
1907 // Start with the matrix minus this window.
1908 int newMatrix
[][] = new int[width
][height
];
1909 for (int mx
= 0; mx
< width
; mx
++) {
1910 for (int my
= 0; my
< height
; my
++) {
1911 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1915 // Add this window's values to the new overlap matrix.
1916 long newOverlapTotal
= 0;
1917 long newOverlapN
= 0;
1918 // Start by adding each new cell.
1919 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1923 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1927 newMatrix
[wx
][wy
]++;
1930 // Now figure out the new value for total coverage.
1931 for (int mx
= 0; mx
< width
; mx
++) {
1932 for (int my
= 0; my
< height
; my
++) {
1933 newOverlapTotal
+= newMatrix
[x
][y
];
1934 if (newMatrix
[mx
][my
] > 0) {
1939 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1942 // First time: just record what we got.
1943 oldOverlapAvg
= newOverlapAvg
;
1946 // All other times: pick a new best (x, y) and save the
1948 if (newOverlapAvg
< oldOverlapAvg
) {
1951 oldOverlapAvg
= newOverlapAvg
;
1955 } // for (int x = xMin; x < xMax; x++)
1957 } // for (int y = yMin; y < yMax; y++)
1959 // Finally, set the window's new coordinates.
1960 window
.setX(windowX
);
1961 window
.setY(windowY
);
1964 // ------------------------------------------------------------------------
1965 // TMenu management -------------------------------------------------------
1966 // ------------------------------------------------------------------------
1969 * Check if a mouse event would hit either the active menu or any open
1972 * @param mouse mouse event
1973 * @return true if the mouse would hit the active menu or an open
1976 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1977 assert (activeMenu
!= null);
1978 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1979 Collections
.reverse(menus
);
1980 for (TMenu menu
: menus
) {
1981 if (menu
.mouseWouldHit(mouse
)) {
1985 return activeMenu
.mouseWouldHit(mouse
);
1989 * See if we need to switch window or activate the menu based on
1992 * @param mouse mouse event
1994 private void checkSwitchFocus(final TMouseEvent mouse
) {
1996 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1997 && (activeMenu
!= null)
1998 && (mouse
.getAbsoluteY() != 0)
1999 && (!mouseOnMenu(mouse
))
2001 // They clicked outside the active menu, turn it off
2002 activeMenu
.setActive(false);
2004 for (TMenu menu
: subMenus
) {
2005 menu
.setActive(false);
2011 // See if they hit the menu bar
2012 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2013 && (mouse
.isMouse1())
2014 && (!modalWindowActive())
2015 && (mouse
.getAbsoluteY() == 0)
2018 for (TMenu menu
: subMenus
) {
2019 menu
.setActive(false);
2023 // They selected the menu, go activate it
2024 for (TMenu menu
: menus
) {
2025 if ((mouse
.getAbsoluteX() >= menu
.getX())
2026 && (mouse
.getAbsoluteX() < menu
.getX()
2027 + menu
.getTitle().length() + 2)
2029 menu
.setActive(true);
2032 menu
.setActive(false);
2038 // See if they hit the menu bar
2039 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2040 && (mouse
.isMouse1())
2041 && (activeMenu
!= null)
2042 && (mouse
.getAbsoluteY() == 0)
2045 TMenu oldMenu
= activeMenu
;
2046 for (TMenu menu
: subMenus
) {
2047 menu
.setActive(false);
2051 // See if we should switch menus
2052 for (TMenu menu
: menus
) {
2053 if ((mouse
.getAbsoluteX() >= menu
.getX())
2054 && (mouse
.getAbsoluteX() < menu
.getX()
2055 + menu
.getTitle().length() + 2)
2057 menu
.setActive(true);
2061 if (oldMenu
!= activeMenu
) {
2062 // They switched menus
2063 oldMenu
.setActive(false);
2068 // If a menu is still active, don't switch windows
2069 if (activeMenu
!= null) {
2073 // Only switch if there are multiple windows
2074 if (windows
.size() < 2) {
2078 if (((focusFollowsMouse
== true)
2079 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2080 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2082 synchronized (windows
) {
2083 Collections
.sort(windows
);
2084 if (windows
.get(0).isModal()) {
2085 // Modal windows don't switch
2089 for (TWindow window
: windows
) {
2090 assert (!window
.isModal());
2092 if (window
.isHidden()) {
2093 assert (!window
.isActive());
2097 if (window
.mouseWouldHit(mouse
)) {
2098 if (window
== windows
.get(0)) {
2099 // Clicked on the same window, nothing to do
2100 assert (window
.isActive());
2104 // We will be switching to another window
2105 assert (windows
.get(0).isActive());
2106 assert (windows
.get(0) == activeWindow
);
2107 assert (!window
.isActive());
2108 activeWindow
.onUnfocus();
2109 activeWindow
.setActive(false);
2110 activeWindow
.setZ(window
.getZ());
2111 activeWindow
= window
;
2113 window
.setActive(true);
2120 // Clicked on the background, nothing to do
2124 // Nothing to do: this isn't a mouse up, or focus isn't following
2130 * Turn off the menu.
2132 public final void closeMenu() {
2133 if (activeMenu
!= null) {
2134 activeMenu
.setActive(false);
2136 for (TMenu menu
: subMenus
) {
2137 menu
.setActive(false);
2144 * Get a (shallow) copy of the menu list.
2146 * @return a copy of the menu list
2148 public final List
<TMenu
> getAllMenus() {
2149 return new LinkedList
<TMenu
>(menus
);
2153 * Add a top-level menu to the list.
2155 * @param menu the menu to add
2156 * @throws IllegalArgumentException if the menu is already used in
2157 * another TApplication
2159 public final void addMenu(final TMenu menu
) {
2160 if ((menu
.getApplication() != null)
2161 && (menu
.getApplication() != this)
2163 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2164 "part of application " + menu
.getApplication());
2172 * Remove a top-level menu from the list.
2174 * @param menu the menu to remove
2175 * @throws IllegalArgumentException if the menu is already used in
2176 * another TApplication
2178 public final void removeMenu(final TMenu menu
) {
2179 if ((menu
.getApplication() != null)
2180 && (menu
.getApplication() != this)
2182 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2183 "part of application " + menu
.getApplication());
2191 * Turn off a sub-menu.
2193 public final void closeSubMenu() {
2194 assert (activeMenu
!= null);
2195 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2196 assert (item
!= null);
2197 item
.setActive(false);
2198 subMenus
.remove(subMenus
.size() - 1);
2202 * Switch to the next menu.
2204 * @param forward if true, then switch to the next menu in the list,
2205 * otherwise switch to the previous menu in the list
2207 public final void switchMenu(final boolean forward
) {
2208 assert (activeMenu
!= null);
2210 for (TMenu menu
: subMenus
) {
2211 menu
.setActive(false);
2215 for (int i
= 0; i
< menus
.size(); i
++) {
2216 if (activeMenu
== menus
.get(i
)) {
2218 if (i
< menus
.size() - 1) {
2226 activeMenu
.setActive(false);
2227 activeMenu
= menus
.get(i
);
2228 activeMenu
.setActive(true);
2235 * Add a menu item to the global list. If it has a keyboard accelerator,
2236 * that will be added the global hash.
2238 * @param item the menu item
2240 public final void addMenuItem(final TMenuItem item
) {
2241 menuItems
.add(item
);
2243 TKeypress key
= item
.getKey();
2245 synchronized (accelerators
) {
2246 assert (accelerators
.get(key
) == null);
2247 accelerators
.put(key
.toLowerCase(), item
);
2253 * Disable one menu item.
2255 * @param id the menu item ID
2257 public final void disableMenuItem(final int id
) {
2258 for (TMenuItem item
: menuItems
) {
2259 if (item
.getId() == id
) {
2260 item
.setEnabled(false);
2266 * Disable the range of menu items with ID's between lower and upper,
2269 * @param lower the lowest menu item ID
2270 * @param upper the highest menu item ID
2272 public final void disableMenuItems(final int lower
, final int upper
) {
2273 for (TMenuItem item
: menuItems
) {
2274 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2275 item
.setEnabled(false);
2281 * Enable one menu item.
2283 * @param id the menu item ID
2285 public final void enableMenuItem(final int id
) {
2286 for (TMenuItem item
: menuItems
) {
2287 if (item
.getId() == id
) {
2288 item
.setEnabled(true);
2294 * Enable the range of menu items with ID's between lower and upper,
2297 * @param lower the lowest menu item ID
2298 * @param upper the highest menu item ID
2300 public final void enableMenuItems(final int lower
, final int upper
) {
2301 for (TMenuItem item
: menuItems
) {
2302 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2303 item
.setEnabled(true);
2309 * Recompute menu x positions based on their title length.
2311 public final void recomputeMenuX() {
2313 for (TMenu menu
: menus
) {
2315 x
+= menu
.getTitle().length() + 2;
2320 * Post an event to process and turn off the menu.
2322 * @param event new event to add to the queue
2324 public final void postMenuEvent(final TInputEvent event
) {
2325 synchronized (fillEventQueue
) {
2326 fillEventQueue
.add(event
);
2332 * Add a sub-menu to the list of open sub-menus.
2334 * @param menu sub-menu
2336 public final void addSubMenu(final TMenu menu
) {
2341 * Convenience function to add a top-level menu.
2343 * @param title menu title
2344 * @return the new menu
2346 public final TMenu
addMenu(final String title
) {
2349 TMenu menu
= new TMenu(this, x
, y
, title
);
2356 * Convenience function to add a default "File" menu.
2358 * @return the new menu
2360 public final TMenu
addFileMenu() {
2361 TMenu fileMenu
= addMenu("&File");
2362 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2363 fileMenu
.addSeparator();
2364 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2365 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2366 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2367 "commands (Open, Save, Print, etc.)");
2368 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2373 * Convenience function to add a default "Edit" menu.
2375 * @return the new menu
2377 public final TMenu
addEditMenu() {
2378 TMenu editMenu
= addMenu("&Edit");
2379 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2380 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2381 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2382 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2383 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2384 "undo, and Clipboard access");
2385 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2390 * Convenience function to add a default "Window" menu.
2392 * @return the new menu
2394 public final TMenu
addWindowMenu() {
2395 TMenu windowMenu
= addMenu("&Window");
2396 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2397 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2398 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2399 windowMenu
.addSeparator();
2400 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2401 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2402 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2403 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2404 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2405 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2407 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2412 * Convenience function to add a default "Help" menu.
2414 * @return the new menu
2416 public final TMenu
addHelpMenu() {
2417 TMenu helpMenu
= addMenu("&Help");
2418 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2419 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2420 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2421 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2422 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2423 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2424 helpMenu
.addSeparator();
2425 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2426 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2427 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2431 // ------------------------------------------------------------------------
2432 // Event handlers ---------------------------------------------------------
2433 // ------------------------------------------------------------------------
2436 * Method that TApplication subclasses can override to handle menu or
2437 * posted command events.
2439 * @param command command event
2440 * @return if true, this event was consumed
2442 protected boolean onCommand(final TCommandEvent command
) {
2443 // Default: handle cmExit
2444 if (command
.equals(cmExit
)) {
2445 if (messageBox("Confirmation", "Exit application?",
2446 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2452 if (command
.equals(cmShell
)) {
2453 openTerminal(0, 0, TWindow
.RESIZABLE
);
2457 if (command
.equals(cmTile
)) {
2461 if (command
.equals(cmCascade
)) {
2465 if (command
.equals(cmCloseAll
)) {
2470 if (command
.equals(cmMenu
)) {
2471 if (!modalWindowActive() && (activeMenu
== null)) {
2472 if (menus
.size() > 0) {
2473 menus
.get(0).setActive(true);
2474 activeMenu
= menus
.get(0);
2484 * Method that TApplication subclasses can override to handle menu
2487 * @param menu menu event
2488 * @return if true, this event was consumed
2490 protected boolean onMenu(final TMenuEvent menu
) {
2492 // Default: handle MID_EXIT
2493 if (menu
.getId() == TMenu
.MID_EXIT
) {
2494 if (messageBox("Confirmation", "Exit application?",
2495 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2501 if (menu
.getId() == TMenu
.MID_SHELL
) {
2502 openTerminal(0, 0, TWindow
.RESIZABLE
);
2506 if (menu
.getId() == TMenu
.MID_TILE
) {
2510 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2514 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2518 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2526 * Method that TApplication subclasses can override to handle keystrokes.
2528 * @param keypress keystroke event
2529 * @return if true, this event was consumed
2531 protected boolean onKeypress(final TKeypressEvent keypress
) {
2532 // Default: only menu shortcuts
2534 // Process Alt-F, Alt-E, etc. menu shortcut keys
2535 if (!keypress
.getKey().isFnKey()
2536 && keypress
.getKey().isAlt()
2537 && !keypress
.getKey().isCtrl()
2538 && (activeMenu
== null)
2539 && !modalWindowActive()
2542 assert (subMenus
.size() == 0);
2544 for (TMenu menu
: menus
) {
2545 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2546 == Character
.toLowerCase(keypress
.getKey().getChar())
2549 menu
.setActive(true);
2558 // ------------------------------------------------------------------------
2559 // TTimer management ------------------------------------------------------
2560 // ------------------------------------------------------------------------
2563 * Get the amount of time I can sleep before missing a Timer tick.
2565 * @param timeout = initial (maximum) timeout in millis
2566 * @return number of milliseconds between now and the next timer event
2568 private long getSleepTime(final long timeout
) {
2569 Date now
= new Date();
2570 long nowTime
= now
.getTime();
2571 long sleepTime
= timeout
;
2572 for (TTimer timer
: timers
) {
2573 long nextTickTime
= timer
.getNextTick().getTime();
2574 if (nextTickTime
< nowTime
) {
2578 long timeDifference
= nextTickTime
- nowTime
;
2579 if (timeDifference
< sleepTime
) {
2580 sleepTime
= timeDifference
;
2583 assert (sleepTime
>= 0);
2584 assert (sleepTime
<= timeout
);
2589 * Convenience function to add a timer.
2591 * @param duration number of milliseconds to wait between ticks
2592 * @param recurring if true, re-schedule this timer after every tick
2593 * @param action function to call when button is pressed
2596 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2597 final TAction action
) {
2599 TTimer timer
= new TTimer(duration
, recurring
, action
);
2600 synchronized (timers
) {
2607 * Convenience function to remove a timer.
2609 * @param timer timer to remove
2611 public final void removeTimer(final TTimer timer
) {
2612 synchronized (timers
) {
2613 timers
.remove(timer
);
2617 // ------------------------------------------------------------------------
2618 // Other TWindow constructors ---------------------------------------------
2619 // ------------------------------------------------------------------------
2622 * Convenience function to spawn a message box.
2624 * @param title window title, will be centered along the top border
2625 * @param caption message to display. Use embedded newlines to get a
2627 * @return the new message box
2629 public final TMessageBox
messageBox(final String title
,
2630 final String caption
) {
2632 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2636 * Convenience function to spawn a message box.
2638 * @param title window title, will be centered along the top border
2639 * @param caption message to display. Use embedded newlines to get a
2641 * @param type one of the TMessageBox.Type constants. Default is
2643 * @return the new message box
2645 public final TMessageBox
messageBox(final String title
,
2646 final String caption
, final TMessageBox
.Type type
) {
2648 return new TMessageBox(this, title
, caption
, type
);
2652 * Convenience function to spawn an input box.
2654 * @param title window title, will be centered along the top border
2655 * @param caption message to display. Use embedded newlines to get a
2657 * @return the new input box
2659 public final TInputBox
inputBox(final String title
, final String caption
) {
2661 return new TInputBox(this, title
, caption
);
2665 * Convenience function to spawn an input box.
2667 * @param title window title, will be centered along the top border
2668 * @param caption message to display. Use embedded newlines to get a
2670 * @param text initial text to seed the field with
2671 * @return the new input box
2673 public final TInputBox
inputBox(final String title
, final String caption
,
2674 final String text
) {
2676 return new TInputBox(this, title
, caption
, text
);
2680 * Convenience function to open a terminal window.
2682 * @param x column relative to parent
2683 * @param y row relative to parent
2684 * @return the terminal new window
2686 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2687 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2691 * Convenience function to open a terminal window.
2693 * @param x column relative to parent
2694 * @param y row relative to parent
2695 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2696 * @return the terminal new window
2698 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2701 return new TTerminalWindow(this, x
, y
, flags
);
2705 * Convenience function to spawn an file open box.
2707 * @param path path of selected file
2708 * @return the result of the new file open box
2709 * @throws IOException if java.io operation throws
2711 public final String
fileOpenBox(final String path
) throws IOException
{
2713 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2714 return box
.getFilename();
2718 * Convenience function to spawn an file open box.
2720 * @param path path of selected file
2721 * @param type one of the Type constants
2722 * @return the result of the new file open box
2723 * @throws IOException if java.io operation throws
2725 public final String
fileOpenBox(final String path
,
2726 final TFileOpenBox
.Type type
) throws IOException
{
2728 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2729 return box
.getFilename();
2733 * Convenience function to create a new window and make it active.
2734 * Window will be located at (0, 0).
2736 * @param title window title, will be centered along the top border
2737 * @param width width of window
2738 * @param height height of window
2740 public final TWindow
addWindow(final String title
, final int width
,
2743 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2747 * Convenience function to create a new window and make it active.
2748 * Window will be located at (0, 0).
2750 * @param title window title, will be centered along the top border
2751 * @param width width of window
2752 * @param height height of window
2753 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2755 public final TWindow
addWindow(final String title
,
2756 final int width
, final int height
, final int flags
) {
2758 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2763 * Convenience function to create a new window and make it active.
2765 * @param title window title, will be centered along the top border
2766 * @param x column relative to parent
2767 * @param y row relative to parent
2768 * @param width width of window
2769 * @param height height of window
2771 public final TWindow
addWindow(final String title
,
2772 final int x
, final int y
, final int width
, final int height
) {
2774 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2779 * Convenience function to create a new window and make it active.
2781 * @param title window title, will be centered along the top border
2782 * @param x column relative to parent
2783 * @param y row relative to parent
2784 * @param width width of window
2785 * @param height height of window
2786 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2788 public final TWindow
addWindow(final String title
,
2789 final int x
, final int y
, final int width
, final int height
,
2792 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);