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.
935 // Timeout is in milliseconds, so default timeout after 1 second
939 // If I've got no updates to render, wait for something from the
940 // backend or a timer.
942 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
944 // Never sleep longer than 50 millis. We need time for
945 // windows with background tasks to update the display, and
946 // still flip buffers reasonably quickly in
947 // backend.flushPhysical().
948 timeout
= getSleepTime(50);
952 // As of now, I've got nothing to do: no I/O, nothing from
953 // the consumer threads, no timers that need to run ASAP. So
954 // wait until either the backend or the consumer threads have
958 System
.err
.println("sleep " + timeout
+ " millis");
960 synchronized (this) {
963 } catch (InterruptedException e
) {
964 // I'm awake and don't care why, let's see what's going
970 // Prevent stepping on the primary or secondary event handler.
973 // Pull any pending I/O events
974 backend
.getEvents(fillEventQueue
);
976 // Dispatch each event to the appropriate handler, one at a time.
978 TInputEvent event
= null;
979 if (fillEventQueue
.size() == 0) {
982 event
= fillEventQueue
.remove(0);
983 metaHandleEvent(event
);
986 // Wake a consumer thread if we have any pending events.
987 if (drainEventQueue
.size() > 0) {
991 // Process timers and call doIdle()'s
995 synchronized (getScreen()) {
999 // Let the event handlers run again.
1000 startEventHandlers();
1004 // Shutdown the event consumer threads
1005 if (secondaryEventHandler
!= null) {
1006 synchronized (secondaryEventHandler
) {
1007 secondaryEventHandler
.notify();
1010 if (primaryEventHandler
!= null) {
1011 synchronized (primaryEventHandler
) {
1012 primaryEventHandler
.notify();
1016 // Shutdown the user I/O thread(s)
1019 // Close all the windows. This gives them an opportunity to release
1026 * Peek at certain application-level events, add to eventQueue, and wake
1027 * up the consuming Thread.
1029 * @param event the input event to consume
1031 private void metaHandleEvent(final TInputEvent event
) {
1034 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1035 event
)); System
.err
.flush();
1039 // Do no more processing if the application is already trying
1044 // Special application-wide events -------------------------------
1047 if (event
instanceof TCommandEvent
) {
1048 TCommandEvent command
= (TCommandEvent
) event
;
1049 if (command
.getCmd().equals(cmAbort
)) {
1056 if (event
instanceof TResizeEvent
) {
1057 TResizeEvent resize
= (TResizeEvent
) event
;
1058 synchronized (getScreen()) {
1059 getScreen().setDimensions(resize
.getWidth(),
1060 resize
.getHeight());
1061 desktopBottom
= getScreen().getHeight() - 1;
1067 if (desktop
!= null) {
1068 desktop
.setDimensions(0, 0, resize
.getWidth(),
1069 resize
.getHeight() - 1);
1074 // Put into the main queue
1075 drainEventQueue
.add(event
);
1079 * Dispatch one event to the appropriate widget or application-level
1080 * event handler. This is the primary event handler, it has the normal
1081 * application-wide event handling.
1083 * @param event the input event to consume
1084 * @see #secondaryHandleEvent(TInputEvent event)
1086 private void primaryHandleEvent(final TInputEvent event
) {
1089 System
.err
.printf("Handle event: %s\n", event
);
1092 // Special application-wide events -----------------------------------
1094 // Peek at the mouse position
1095 if (event
instanceof TMouseEvent
) {
1096 TMouseEvent mouse
= (TMouseEvent
) event
;
1097 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1100 mouseX
= mouse
.getX();
1101 mouseY
= mouse
.getY();
1104 // See if we need to switch focus to another window or the menu
1105 checkSwitchFocus((TMouseEvent
) event
);
1108 // Handle menu events
1109 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1110 TMenu menu
= activeMenu
;
1112 if (event
instanceof TMouseEvent
) {
1113 TMouseEvent mouse
= (TMouseEvent
) event
;
1115 while (subMenus
.size() > 0) {
1116 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1117 if (subMenu
.mouseWouldHit(mouse
)) {
1120 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1121 && (!mouse
.isMouse1())
1122 && (!mouse
.isMouse2())
1123 && (!mouse
.isMouse3())
1124 && (!mouse
.isMouseWheelUp())
1125 && (!mouse
.isMouseWheelDown())
1129 // We navigated away from a sub-menu, so close it
1133 // Convert the mouse relative x/y to menu coordinates
1134 assert (mouse
.getX() == mouse
.getAbsoluteX());
1135 assert (mouse
.getY() == mouse
.getAbsoluteY());
1136 if (subMenus
.size() > 0) {
1137 menu
= subMenus
.get(subMenus
.size() - 1);
1139 mouse
.setX(mouse
.getX() - menu
.getX());
1140 mouse
.setY(mouse
.getY() - menu
.getY());
1142 menu
.handleEvent(event
);
1146 if (event
instanceof TKeypressEvent
) {
1147 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1149 // See if this key matches an accelerator, and is not being
1150 // shortcutted by the active window, and if so dispatch the menu
1152 boolean windowWillShortcut
= false;
1153 if (activeWindow
!= null) {
1154 assert (activeWindow
.isShown());
1155 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1156 // We do not process this key, it will be passed to the
1158 windowWillShortcut
= true;
1162 if (!windowWillShortcut
&& !modalWindowActive()) {
1163 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1164 TMenuItem item
= null;
1165 synchronized (accelerators
) {
1166 item
= accelerators
.get(keypressLowercase
);
1169 if (item
.isEnabled()) {
1170 // Let the menu item dispatch
1176 // Handle the keypress
1177 if (onKeypress(keypress
)) {
1183 if (event
instanceof TCommandEvent
) {
1184 if (onCommand((TCommandEvent
) event
)) {
1189 if (event
instanceof TMenuEvent
) {
1190 if (onMenu((TMenuEvent
) event
)) {
1195 // Dispatch events to the active window -------------------------------
1196 boolean dispatchToDesktop
= true;
1197 TWindow window
= activeWindow
;
1198 if (window
!= null) {
1199 assert (window
.isActive());
1200 assert (window
.isShown());
1201 if (event
instanceof TMouseEvent
) {
1202 TMouseEvent mouse
= (TMouseEvent
) event
;
1203 // Convert the mouse relative x/y to window coordinates
1204 assert (mouse
.getX() == mouse
.getAbsoluteX());
1205 assert (mouse
.getY() == mouse
.getAbsoluteY());
1206 mouse
.setX(mouse
.getX() - window
.getX());
1207 mouse
.setY(mouse
.getY() - window
.getY());
1209 if (window
.mouseWouldHit(mouse
)) {
1210 dispatchToDesktop
= false;
1212 } else if (event
instanceof TKeypressEvent
) {
1213 dispatchToDesktop
= false;
1217 System
.err
.printf("TApplication dispatch event: %s\n",
1220 window
.handleEvent(event
);
1222 if (dispatchToDesktop
) {
1223 // This event is fair game for the desktop to process.
1224 if (desktop
!= null) {
1225 desktop
.handleEvent(event
);
1231 * Dispatch one event to the appropriate widget or application-level
1232 * event handler. This is the secondary event handler used by certain
1233 * special dialogs (currently TMessageBox and TFileOpenBox).
1235 * @param event the input event to consume
1236 * @see #primaryHandleEvent(TInputEvent event)
1238 private void secondaryHandleEvent(final TInputEvent event
) {
1239 // Peek at the mouse position
1240 if (event
instanceof TMouseEvent
) {
1241 TMouseEvent mouse
= (TMouseEvent
) event
;
1242 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1245 mouseX
= mouse
.getX();
1246 mouseY
= mouse
.getY();
1250 secondaryEventReceiver
.handleEvent(event
);
1254 * Enable a widget to override the primary event thread.
1256 * @param widget widget that will receive events
1258 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1259 assert (secondaryEventReceiver
== null);
1260 assert (secondaryEventHandler
== null);
1261 assert ((widget
instanceof TMessageBox
)
1262 || (widget
instanceof TFileOpenBox
));
1263 secondaryEventReceiver
= widget
;
1264 secondaryEventHandler
= new WidgetEventHandler(this, false);
1265 (new Thread(secondaryEventHandler
)).start();
1269 * Yield to the secondary thread.
1271 public final void yield() {
1272 assert (secondaryEventReceiver
!= null);
1273 // This is where we handoff the event handler lock from the primary
1274 // to secondary thread. We unlock here, and in a future loop the
1275 // secondary thread locks again. When it gives up, we have the
1276 // single lock back.
1277 boolean oldLock
= unlockHandleEvent();
1280 while (secondaryEventReceiver
!= null) {
1281 synchronized (primaryEventHandler
) {
1283 primaryEventHandler
.wait();
1284 } catch (InterruptedException e
) {
1292 * Do stuff when there is no user input.
1294 private void doIdle() {
1296 System
.err
.printf("doIdle()\n");
1299 // Now run any timers that have timed out
1300 Date now
= new Date();
1301 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1302 for (TTimer timer
: timers
) {
1303 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1305 if (timer
.recurring
) {
1306 keepTimers
.add(timer
);
1309 keepTimers
.add(timer
);
1312 timers
= keepTimers
;
1315 for (TWindow window
: windows
) {
1318 if (desktop
!= null) {
1323 // ------------------------------------------------------------------------
1324 // TWindow management -----------------------------------------------------
1325 // ------------------------------------------------------------------------
1328 * Return the total number of windows.
1330 * @return the total number of windows
1332 public final int windowCount() {
1333 return windows
.size();
1337 * Return the number of windows that are showing.
1339 * @return the number of windows that are showing on screen
1341 public final int shownWindowCount() {
1343 for (TWindow w
: windows
) {
1352 * Return the number of windows that are hidden.
1354 * @return the number of windows that are hidden
1356 public final int hiddenWindowCount() {
1358 for (TWindow w
: windows
) {
1367 * Check if a window instance is in this application's window list.
1369 * @param window window to look for
1370 * @return true if this window is in the list
1372 public final boolean hasWindow(final TWindow window
) {
1373 if (windows
.size() == 0) {
1376 for (TWindow w
: windows
) {
1378 assert (window
.getApplication() == this);
1386 * Activate a window: bring it to the top and have it receive events.
1388 * @param window the window to become the new active window
1390 public void activateWindow(final TWindow window
) {
1391 if (hasWindow(window
) == false) {
1393 * Someone has a handle to a window I don't have. Ignore this
1399 // Whatever window might be moving/dragging, stop it now.
1400 for (TWindow w
: windows
) {
1401 if (w
.inMovements()) {
1406 assert (windows
.size() > 0);
1408 if (window
.isHidden()) {
1409 // Unhiding will also activate.
1413 assert (window
.isShown());
1415 if (windows
.size() == 1) {
1416 assert (window
== windows
.get(0));
1417 if (activeWindow
== null) {
1418 activeWindow
= window
;
1420 activeWindow
.setActive(true);
1421 activeWindow
.onFocus();
1424 assert (window
.isActive());
1425 assert (activeWindow
== window
);
1429 if (activeWindow
== window
) {
1430 assert (window
.isActive());
1432 // Window is already active, do nothing.
1436 assert (!window
.isActive());
1437 if (activeWindow
!= null) {
1438 assert (activeWindow
.getZ() == 0);
1440 activeWindow
.onUnfocus();
1441 activeWindow
.setActive(false);
1442 activeWindow
.setZ(window
.getZ());
1444 activeWindow
= window
;
1445 activeWindow
.setZ(0);
1446 activeWindow
.setActive(true);
1447 activeWindow
.onFocus();
1454 * @param window the window to hide
1456 public void hideWindow(final TWindow window
) {
1457 if (hasWindow(window
) == false) {
1459 * Someone has a handle to a window I don't have. Ignore this
1465 // Whatever window might be moving/dragging, stop it now.
1466 for (TWindow w
: windows
) {
1467 if (w
.inMovements()) {
1472 assert (windows
.size() > 0);
1474 if (!window
.hidden
) {
1475 if (window
== activeWindow
) {
1476 if (shownWindowCount() > 1) {
1479 activeWindow
= null;
1480 window
.setActive(false);
1484 window
.hidden
= true;
1492 * @param window the window to show
1494 public void showWindow(final TWindow window
) {
1495 if (hasWindow(window
) == false) {
1497 * Someone has a handle to a window I don't have. Ignore this
1503 // Whatever window might be moving/dragging, stop it now.
1504 for (TWindow w
: windows
) {
1505 if (w
.inMovements()) {
1510 assert (windows
.size() > 0);
1512 if (window
.hidden
) {
1513 window
.hidden
= false;
1515 activateWindow(window
);
1520 * Close window. Note that the window's destructor is NOT called by this
1521 * method, instead the GC is assumed to do the cleanup.
1523 * @param window the window to remove
1525 public final void closeWindow(final TWindow window
) {
1526 if (hasWindow(window
) == false) {
1528 * Someone has a handle to a window I don't have. Ignore this
1534 synchronized (windows
) {
1535 // Whatever window might be moving/dragging, stop it now.
1536 for (TWindow w
: windows
) {
1537 if (w
.inMovements()) {
1542 int z
= window
.getZ();
1545 Collections
.sort(windows
);
1547 activeWindow
= null;
1548 for (TWindow w
: windows
) {
1550 w
.setZ(w
.getZ() - 1);
1551 if (w
.getZ() == 0) {
1554 assert (activeWindow
== null);
1566 // Perform window cleanup
1569 // Check if we are closing a TMessageBox or similar
1570 if (secondaryEventReceiver
!= null) {
1571 assert (secondaryEventHandler
!= null);
1573 // Do not send events to the secondaryEventReceiver anymore, the
1574 // window is closed.
1575 secondaryEventReceiver
= null;
1577 // Wake the secondary thread, it will wake the primary as it
1579 synchronized (secondaryEventHandler
) {
1580 secondaryEventHandler
.notify();
1584 // Permit desktop to be active if it is the only thing left.
1585 if (desktop
!= null) {
1586 if (windows
.size() == 0) {
1587 desktop
.setActive(true);
1593 * Switch to the next window.
1595 * @param forward if true, then switch to the next window in the list,
1596 * otherwise switch to the previous window in the list
1598 public final void switchWindow(final boolean forward
) {
1599 // Only switch if there are multiple visible windows
1600 if (shownWindowCount() < 2) {
1603 assert (activeWindow
!= null);
1605 synchronized (windows
) {
1606 // Whatever window might be moving/dragging, stop it now.
1607 for (TWindow w
: windows
) {
1608 if (w
.inMovements()) {
1613 // Swap z/active between active window and the next in the list
1614 int activeWindowI
= -1;
1615 for (int i
= 0; i
< windows
.size(); i
++) {
1616 if (windows
.get(i
) == activeWindow
) {
1617 assert (activeWindow
.isActive());
1621 assert (!windows
.get(0).isActive());
1624 assert (activeWindowI
>= 0);
1626 // Do not switch if a window is modal
1627 if (activeWindow
.isModal()) {
1631 int nextWindowI
= activeWindowI
;
1635 nextWindowI
%= windows
.size();
1638 if (nextWindowI
< 0) {
1639 nextWindowI
= windows
.size() - 1;
1643 if (windows
.get(nextWindowI
).isShown()) {
1644 activateWindow(windows
.get(nextWindowI
));
1648 } // synchronized (windows)
1653 * Add a window to my window list and make it active.
1655 * @param window new window to add
1657 public final void addWindow(final TWindow window
) {
1659 // Do not add menu windows to the window list.
1660 if (window
instanceof TMenu
) {
1664 // Do not add the desktop to the window list.
1665 if (window
instanceof TDesktop
) {
1669 synchronized (windows
) {
1670 // Whatever window might be moving/dragging, stop it now.
1671 for (TWindow w
: windows
) {
1672 if (w
.inMovements()) {
1677 // Do not allow a modal window to spawn a non-modal window. If a
1678 // modal window is active, then this window will become modal
1680 if (modalWindowActive()) {
1681 window
.flags
|= TWindow
.MODAL
;
1682 window
.flags
|= TWindow
.CENTERED
;
1683 window
.hidden
= false;
1685 if (window
.isShown()) {
1686 for (TWindow w
: windows
) {
1691 w
.setZ(w
.getZ() + 1);
1694 windows
.add(window
);
1695 if (window
.isShown()) {
1696 activeWindow
= window
;
1697 activeWindow
.setZ(0);
1698 activeWindow
.setActive(true);
1699 activeWindow
.onFocus();
1702 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1703 && smartWindowPlacement
) {
1705 doSmartPlacement(window
);
1709 // Desktop cannot be active over any other window.
1710 if (desktop
!= null) {
1711 desktop
.setActive(false);
1716 * Check if there is a system-modal window on top.
1718 * @return true if the active window is modal
1720 private boolean modalWindowActive() {
1721 if (windows
.size() == 0) {
1725 for (TWindow w
: windows
) {
1735 * Close all open windows.
1737 private void closeAllWindows() {
1738 // Don't do anything if we are in the menu
1739 if (activeMenu
!= null) {
1742 while (windows
.size() > 0) {
1743 closeWindow(windows
.get(0));
1748 * Re-layout the open windows as non-overlapping tiles. This produces
1749 * almost the same results as Turbo Pascal 7.0's IDE.
1751 private void tileWindows() {
1752 synchronized (windows
) {
1753 // Don't do anything if we are in the menu
1754 if (activeMenu
!= null) {
1757 int z
= windows
.size();
1763 a
= (int)(Math
.sqrt(z
));
1767 if (((a
* b
) + c
) == z
) {
1775 int newWidth
= (getScreen().getWidth() / a
);
1776 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1777 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1779 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1780 Collections
.sort(sorted
);
1781 Collections
.reverse(sorted
);
1782 for (int i
= 0; i
< sorted
.size(); i
++) {
1783 int logicalX
= i
/ b
;
1784 int logicalY
= i
% b
;
1785 if (i
>= ((a
- 1) * b
)) {
1787 logicalY
= i
- ((a
- 1) * b
);
1790 TWindow w
= sorted
.get(i
);
1791 w
.setX(logicalX
* newWidth
);
1792 w
.setWidth(newWidth
);
1793 if (i
>= ((a
- 1) * b
)) {
1794 w
.setY((logicalY
* newHeight2
) + 1);
1795 w
.setHeight(newHeight2
);
1797 w
.setY((logicalY
* newHeight1
) + 1);
1798 w
.setHeight(newHeight1
);
1805 * Re-layout the open windows as overlapping cascaded windows.
1807 private void cascadeWindows() {
1808 synchronized (windows
) {
1809 // Don't do anything if we are in the menu
1810 if (activeMenu
!= null) {
1815 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1816 Collections
.sort(sorted
);
1817 Collections
.reverse(sorted
);
1818 for (TWindow window
: sorted
) {
1823 if (x
> getScreen().getWidth()) {
1826 if (y
>= getScreen().getHeight()) {
1834 * Place a window to minimize its overlap with other windows.
1836 * @param window the window to place
1838 public final void doSmartPlacement(final TWindow window
) {
1839 // This is a pretty dumb algorithm, but seems to work. The hardest
1840 // part is computing these "overlap" values seeking a minimum average
1843 int yMin
= desktopTop
;
1844 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1845 int yMax
= desktopBottom
- window
.getHeight() + 1;
1853 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1854 // No work to do, bail out.
1858 // Compute the overlap matrix without the new window.
1859 int width
= getScreen().getWidth();
1860 int height
= getScreen().getHeight();
1861 int overlapMatrix
[][] = new int[width
][height
];
1862 for (TWindow w
: windows
) {
1866 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1870 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1874 overlapMatrix
[x
][y
]++;
1879 long oldOverlapTotal
= 0;
1880 long oldOverlapN
= 0;
1881 for (int x
= 0; x
< width
; x
++) {
1882 for (int y
= 0; y
< height
; y
++) {
1883 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1884 if (overlapMatrix
[x
][y
] > 0) {
1891 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1892 boolean first
= true;
1893 int windowX
= window
.getX();
1894 int windowY
= window
.getY();
1896 // For each possible (x, y) position for the new window, compute a
1897 // new overlap matrix.
1898 for (int x
= xMin
; x
< xMax
; x
++) {
1899 for (int y
= yMin
; y
< yMax
; y
++) {
1901 // Start with the matrix minus this window.
1902 int newMatrix
[][] = new int[width
][height
];
1903 for (int mx
= 0; mx
< width
; mx
++) {
1904 for (int my
= 0; my
< height
; my
++) {
1905 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1909 // Add this window's values to the new overlap matrix.
1910 long newOverlapTotal
= 0;
1911 long newOverlapN
= 0;
1912 // Start by adding each new cell.
1913 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1917 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1921 newMatrix
[wx
][wy
]++;
1924 // Now figure out the new value for total coverage.
1925 for (int mx
= 0; mx
< width
; mx
++) {
1926 for (int my
= 0; my
< height
; my
++) {
1927 newOverlapTotal
+= newMatrix
[x
][y
];
1928 if (newMatrix
[mx
][my
] > 0) {
1933 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1936 // First time: just record what we got.
1937 oldOverlapAvg
= newOverlapAvg
;
1940 // All other times: pick a new best (x, y) and save the
1942 if (newOverlapAvg
< oldOverlapAvg
) {
1945 oldOverlapAvg
= newOverlapAvg
;
1949 } // for (int x = xMin; x < xMax; x++)
1951 } // for (int y = yMin; y < yMax; y++)
1953 // Finally, set the window's new coordinates.
1954 window
.setX(windowX
);
1955 window
.setY(windowY
);
1958 // ------------------------------------------------------------------------
1959 // TMenu management -------------------------------------------------------
1960 // ------------------------------------------------------------------------
1963 * Check if a mouse event would hit either the active menu or any open
1966 * @param mouse mouse event
1967 * @return true if the mouse would hit the active menu or an open
1970 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1971 assert (activeMenu
!= null);
1972 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1973 Collections
.reverse(menus
);
1974 for (TMenu menu
: menus
) {
1975 if (menu
.mouseWouldHit(mouse
)) {
1979 return activeMenu
.mouseWouldHit(mouse
);
1983 * See if we need to switch window or activate the menu based on
1986 * @param mouse mouse event
1988 private void checkSwitchFocus(final TMouseEvent mouse
) {
1990 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1991 && (activeMenu
!= null)
1992 && (mouse
.getAbsoluteY() != 0)
1993 && (!mouseOnMenu(mouse
))
1995 // They clicked outside the active menu, turn it off
1996 activeMenu
.setActive(false);
1998 for (TMenu menu
: subMenus
) {
1999 menu
.setActive(false);
2005 // See if they hit the menu bar
2006 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2007 && (mouse
.isMouse1())
2008 && (!modalWindowActive())
2009 && (mouse
.getAbsoluteY() == 0)
2012 for (TMenu menu
: subMenus
) {
2013 menu
.setActive(false);
2017 // They selected the menu, go activate it
2018 for (TMenu menu
: menus
) {
2019 if ((mouse
.getAbsoluteX() >= menu
.getX())
2020 && (mouse
.getAbsoluteX() < menu
.getX()
2021 + menu
.getTitle().length() + 2)
2023 menu
.setActive(true);
2026 menu
.setActive(false);
2032 // See if they hit the menu bar
2033 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2034 && (mouse
.isMouse1())
2035 && (activeMenu
!= null)
2036 && (mouse
.getAbsoluteY() == 0)
2039 TMenu oldMenu
= activeMenu
;
2040 for (TMenu menu
: subMenus
) {
2041 menu
.setActive(false);
2045 // See if we should switch menus
2046 for (TMenu menu
: menus
) {
2047 if ((mouse
.getAbsoluteX() >= menu
.getX())
2048 && (mouse
.getAbsoluteX() < menu
.getX()
2049 + menu
.getTitle().length() + 2)
2051 menu
.setActive(true);
2055 if (oldMenu
!= activeMenu
) {
2056 // They switched menus
2057 oldMenu
.setActive(false);
2062 // If a menu is still active, don't switch windows
2063 if (activeMenu
!= null) {
2067 // Only switch if there are multiple windows
2068 if (windows
.size() < 2) {
2072 if (((focusFollowsMouse
== true)
2073 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2074 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2076 synchronized (windows
) {
2077 Collections
.sort(windows
);
2078 if (windows
.get(0).isModal()) {
2079 // Modal windows don't switch
2083 for (TWindow window
: windows
) {
2084 assert (!window
.isModal());
2086 if (window
.isHidden()) {
2087 assert (!window
.isActive());
2091 if (window
.mouseWouldHit(mouse
)) {
2092 if (window
== windows
.get(0)) {
2093 // Clicked on the same window, nothing to do
2094 assert (window
.isActive());
2098 // We will be switching to another window
2099 assert (windows
.get(0).isActive());
2100 assert (windows
.get(0) == activeWindow
);
2101 assert (!window
.isActive());
2102 activeWindow
.onUnfocus();
2103 activeWindow
.setActive(false);
2104 activeWindow
.setZ(window
.getZ());
2105 activeWindow
= window
;
2107 window
.setActive(true);
2114 // Clicked on the background, nothing to do
2118 // Nothing to do: this isn't a mouse up, or focus isn't following
2124 * Turn off the menu.
2126 public final void closeMenu() {
2127 if (activeMenu
!= null) {
2128 activeMenu
.setActive(false);
2130 for (TMenu menu
: subMenus
) {
2131 menu
.setActive(false);
2138 * Get a (shallow) copy of the menu list.
2140 * @return a copy of the menu list
2142 public final List
<TMenu
> getAllMenus() {
2143 return new LinkedList
<TMenu
>(menus
);
2147 * Add a top-level menu to the list.
2149 * @param menu the menu to add
2150 * @throws IllegalArgumentException if the menu is already used in
2151 * another TApplication
2153 public final void addMenu(final TMenu menu
) {
2154 if ((menu
.getApplication() != null)
2155 && (menu
.getApplication() != this)
2157 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2158 "part of application " + menu
.getApplication());
2166 * Remove a top-level menu from the list.
2168 * @param menu the menu to remove
2169 * @throws IllegalArgumentException if the menu is already used in
2170 * another TApplication
2172 public final void removeMenu(final TMenu menu
) {
2173 if ((menu
.getApplication() != null)
2174 && (menu
.getApplication() != this)
2176 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2177 "part of application " + menu
.getApplication());
2185 * Turn off a sub-menu.
2187 public final void closeSubMenu() {
2188 assert (activeMenu
!= null);
2189 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2190 assert (item
!= null);
2191 item
.setActive(false);
2192 subMenus
.remove(subMenus
.size() - 1);
2196 * Switch to the next menu.
2198 * @param forward if true, then switch to the next menu in the list,
2199 * otherwise switch to the previous menu in the list
2201 public final void switchMenu(final boolean forward
) {
2202 assert (activeMenu
!= null);
2204 for (TMenu menu
: subMenus
) {
2205 menu
.setActive(false);
2209 for (int i
= 0; i
< menus
.size(); i
++) {
2210 if (activeMenu
== menus
.get(i
)) {
2212 if (i
< menus
.size() - 1) {
2220 activeMenu
.setActive(false);
2221 activeMenu
= menus
.get(i
);
2222 activeMenu
.setActive(true);
2229 * Add a menu item to the global list. If it has a keyboard accelerator,
2230 * that will be added the global hash.
2232 * @param item the menu item
2234 public final void addMenuItem(final TMenuItem item
) {
2235 menuItems
.add(item
);
2237 TKeypress key
= item
.getKey();
2239 synchronized (accelerators
) {
2240 assert (accelerators
.get(key
) == null);
2241 accelerators
.put(key
.toLowerCase(), item
);
2247 * Disable one menu item.
2249 * @param id the menu item ID
2251 public final void disableMenuItem(final int id
) {
2252 for (TMenuItem item
: menuItems
) {
2253 if (item
.getId() == id
) {
2254 item
.setEnabled(false);
2260 * Disable the range of menu items with ID's between lower and upper,
2263 * @param lower the lowest menu item ID
2264 * @param upper the highest menu item ID
2266 public final void disableMenuItems(final int lower
, final int upper
) {
2267 for (TMenuItem item
: menuItems
) {
2268 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2269 item
.setEnabled(false);
2275 * Enable one menu item.
2277 * @param id the menu item ID
2279 public final void enableMenuItem(final int id
) {
2280 for (TMenuItem item
: menuItems
) {
2281 if (item
.getId() == id
) {
2282 item
.setEnabled(true);
2288 * Enable the range of menu items with ID's between lower and upper,
2291 * @param lower the lowest menu item ID
2292 * @param upper the highest menu item ID
2294 public final void enableMenuItems(final int lower
, final int upper
) {
2295 for (TMenuItem item
: menuItems
) {
2296 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2297 item
.setEnabled(true);
2303 * Recompute menu x positions based on their title length.
2305 public final void recomputeMenuX() {
2307 for (TMenu menu
: menus
) {
2309 x
+= menu
.getTitle().length() + 2;
2314 * Post an event to process and turn off the menu.
2316 * @param event new event to add to the queue
2318 public final void postMenuEvent(final TInputEvent event
) {
2319 synchronized (fillEventQueue
) {
2320 fillEventQueue
.add(event
);
2326 * Add a sub-menu to the list of open sub-menus.
2328 * @param menu sub-menu
2330 public final void addSubMenu(final TMenu menu
) {
2335 * Convenience function to add a top-level menu.
2337 * @param title menu title
2338 * @return the new menu
2340 public final TMenu
addMenu(final String title
) {
2343 TMenu menu
= new TMenu(this, x
, y
, title
);
2350 * Convenience function to add a default "File" menu.
2352 * @return the new menu
2354 public final TMenu
addFileMenu() {
2355 TMenu fileMenu
= addMenu("&File");
2356 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2357 fileMenu
.addSeparator();
2358 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2359 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2360 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2361 "commands (Open, Save, Print, etc.)");
2362 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2367 * Convenience function to add a default "Edit" menu.
2369 * @return the new menu
2371 public final TMenu
addEditMenu() {
2372 TMenu editMenu
= addMenu("&Edit");
2373 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2374 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2375 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2376 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2377 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2378 "undo, and Clipboard access");
2379 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2384 * Convenience function to add a default "Window" menu.
2386 * @return the new menu
2388 public final TMenu
addWindowMenu() {
2389 TMenu windowMenu
= addMenu("&Window");
2390 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2391 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2392 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2393 windowMenu
.addSeparator();
2394 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2395 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2396 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2397 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2398 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2399 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2401 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2406 * Convenience function to add a default "Help" menu.
2408 * @return the new menu
2410 public final TMenu
addHelpMenu() {
2411 TMenu helpMenu
= addMenu("&Help");
2412 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2413 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2414 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2415 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2416 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2417 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2418 helpMenu
.addSeparator();
2419 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2420 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2421 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2425 // ------------------------------------------------------------------------
2426 // Event handlers ---------------------------------------------------------
2427 // ------------------------------------------------------------------------
2430 * Method that TApplication subclasses can override to handle menu or
2431 * posted command events.
2433 * @param command command event
2434 * @return if true, this event was consumed
2436 protected boolean onCommand(final TCommandEvent command
) {
2437 // Default: handle cmExit
2438 if (command
.equals(cmExit
)) {
2439 if (messageBox("Confirmation", "Exit application?",
2440 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2446 if (command
.equals(cmShell
)) {
2447 openTerminal(0, 0, TWindow
.RESIZABLE
);
2451 if (command
.equals(cmTile
)) {
2455 if (command
.equals(cmCascade
)) {
2459 if (command
.equals(cmCloseAll
)) {
2464 if (command
.equals(cmMenu
)) {
2465 if (!modalWindowActive() && (activeMenu
== null)) {
2466 if (menus
.size() > 0) {
2467 menus
.get(0).setActive(true);
2468 activeMenu
= menus
.get(0);
2478 * Method that TApplication subclasses can override to handle menu
2481 * @param menu menu event
2482 * @return if true, this event was consumed
2484 protected boolean onMenu(final TMenuEvent menu
) {
2486 // Default: handle MID_EXIT
2487 if (menu
.getId() == TMenu
.MID_EXIT
) {
2488 if (messageBox("Confirmation", "Exit application?",
2489 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2495 if (menu
.getId() == TMenu
.MID_SHELL
) {
2496 openTerminal(0, 0, TWindow
.RESIZABLE
);
2500 if (menu
.getId() == TMenu
.MID_TILE
) {
2504 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2508 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2512 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2520 * Method that TApplication subclasses can override to handle keystrokes.
2522 * @param keypress keystroke event
2523 * @return if true, this event was consumed
2525 protected boolean onKeypress(final TKeypressEvent keypress
) {
2526 // Default: only menu shortcuts
2528 // Process Alt-F, Alt-E, etc. menu shortcut keys
2529 if (!keypress
.getKey().isFnKey()
2530 && keypress
.getKey().isAlt()
2531 && !keypress
.getKey().isCtrl()
2532 && (activeMenu
== null)
2533 && !modalWindowActive()
2536 assert (subMenus
.size() == 0);
2538 for (TMenu menu
: menus
) {
2539 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2540 == Character
.toLowerCase(keypress
.getKey().getChar())
2543 menu
.setActive(true);
2552 // ------------------------------------------------------------------------
2553 // TTimer management ------------------------------------------------------
2554 // ------------------------------------------------------------------------
2557 * Get the amount of time I can sleep before missing a Timer tick.
2559 * @param timeout = initial (maximum) timeout in millis
2560 * @return number of milliseconds between now and the next timer event
2562 private long getSleepTime(final long timeout
) {
2563 Date now
= new Date();
2564 long nowTime
= now
.getTime();
2565 long sleepTime
= timeout
;
2566 for (TTimer timer
: timers
) {
2567 long nextTickTime
= timer
.getNextTick().getTime();
2568 if (nextTickTime
< nowTime
) {
2572 long timeDifference
= nextTickTime
- nowTime
;
2573 if (timeDifference
< sleepTime
) {
2574 sleepTime
= timeDifference
;
2577 assert (sleepTime
>= 0);
2578 assert (sleepTime
<= timeout
);
2583 * Convenience function to add a timer.
2585 * @param duration number of milliseconds to wait between ticks
2586 * @param recurring if true, re-schedule this timer after every tick
2587 * @param action function to call when button is pressed
2590 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2591 final TAction action
) {
2593 TTimer timer
= new TTimer(duration
, recurring
, action
);
2594 synchronized (timers
) {
2601 * Convenience function to remove a timer.
2603 * @param timer timer to remove
2605 public final void removeTimer(final TTimer timer
) {
2606 synchronized (timers
) {
2607 timers
.remove(timer
);
2611 // ------------------------------------------------------------------------
2612 // Other TWindow constructors ---------------------------------------------
2613 // ------------------------------------------------------------------------
2616 * Convenience function to spawn a message box.
2618 * @param title window title, will be centered along the top border
2619 * @param caption message to display. Use embedded newlines to get a
2621 * @return the new message box
2623 public final TMessageBox
messageBox(final String title
,
2624 final String caption
) {
2626 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2630 * Convenience function to spawn a message box.
2632 * @param title window title, will be centered along the top border
2633 * @param caption message to display. Use embedded newlines to get a
2635 * @param type one of the TMessageBox.Type constants. Default is
2637 * @return the new message box
2639 public final TMessageBox
messageBox(final String title
,
2640 final String caption
, final TMessageBox
.Type type
) {
2642 return new TMessageBox(this, title
, caption
, type
);
2646 * Convenience function to spawn an input box.
2648 * @param title window title, will be centered along the top border
2649 * @param caption message to display. Use embedded newlines to get a
2651 * @return the new input box
2653 public final TInputBox
inputBox(final String title
, final String caption
) {
2655 return new TInputBox(this, title
, caption
);
2659 * Convenience function to spawn an input box.
2661 * @param title window title, will be centered along the top border
2662 * @param caption message to display. Use embedded newlines to get a
2664 * @param text initial text to seed the field with
2665 * @return the new input box
2667 public final TInputBox
inputBox(final String title
, final String caption
,
2668 final String text
) {
2670 return new TInputBox(this, title
, caption
, text
);
2674 * Convenience function to open a terminal window.
2676 * @param x column relative to parent
2677 * @param y row relative to parent
2678 * @return the terminal new window
2680 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2681 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2685 * Convenience function to open a terminal window.
2687 * @param x column relative to parent
2688 * @param y row relative to parent
2689 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2690 * @return the terminal new window
2692 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2695 return new TTerminalWindow(this, x
, y
, flags
);
2699 * Convenience function to spawn an file open box.
2701 * @param path path of selected file
2702 * @return the result of the new file open box
2703 * @throws IOException if java.io operation throws
2705 public final String
fileOpenBox(final String path
) throws IOException
{
2707 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2708 return box
.getFilename();
2712 * Convenience function to spawn an file open box.
2714 * @param path path of selected file
2715 * @param type one of the Type constants
2716 * @return the result of the new file open box
2717 * @throws IOException if java.io operation throws
2719 public final String
fileOpenBox(final String path
,
2720 final TFileOpenBox
.Type type
) throws IOException
{
2722 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2723 return box
.getFilename();
2727 * Convenience function to create a new window and make it active.
2728 * Window will be located at (0, 0).
2730 * @param title window title, will be centered along the top border
2731 * @param width width of window
2732 * @param height height of window
2734 public final TWindow
addWindow(final String title
, final int width
,
2737 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2741 * Convenience function to create a new window and make it active.
2742 * Window will be located at (0, 0).
2744 * @param title window title, will be centered along the top border
2745 * @param width width of window
2746 * @param height height of window
2747 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2749 public final TWindow
addWindow(final String title
,
2750 final int width
, final int height
, final int flags
) {
2752 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2757 * Convenience function to create a new window and make it active.
2759 * @param title window title, will be centered along the top border
2760 * @param x column relative to parent
2761 * @param y row relative to parent
2762 * @param width width of window
2763 * @param height height of window
2765 public final TWindow
addWindow(final String title
,
2766 final int x
, final int y
, final int width
, final int height
) {
2768 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2773 * Convenience function to create a new window and make it active.
2775 * @param title window title, will be centered along the top border
2776 * @param x column relative to parent
2777 * @param y row relative to parent
2778 * @param width width of window
2779 * @param height height of window
2780 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2782 public final TWindow
addWindow(final String title
,
2783 final int x
, final int y
, final int width
, final int height
,
2786 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);