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]
32 import java
.io
.InputStream
;
33 import java
.io
.IOException
;
34 import java
.io
.OutputStream
;
35 import java
.io
.PrintWriter
;
36 import java
.io
.Reader
;
37 import java
.io
.UnsupportedEncodingException
;
38 import java
.text
.MessageFormat
;
39 import java
.util
.Collections
;
40 import java
.util
.Date
;
41 import java
.util
.HashMap
;
42 import java
.util
.ArrayList
;
43 import java
.util
.LinkedList
;
44 import java
.util
.List
;
46 import java
.util
.ResourceBundle
;
48 import jexer
.bits
.CellAttributes
;
49 import jexer
.bits
.ColorTheme
;
50 import jexer
.event
.TCommandEvent
;
51 import jexer
.event
.TInputEvent
;
52 import jexer
.event
.TKeypressEvent
;
53 import jexer
.event
.TMenuEvent
;
54 import jexer
.event
.TMouseEvent
;
55 import jexer
.event
.TResizeEvent
;
56 import jexer
.backend
.Backend
;
57 import jexer
.backend
.Screen
;
58 import jexer
.backend
.MultiBackend
;
59 import jexer
.backend
.SwingBackend
;
60 import jexer
.backend
.ECMA48Backend
;
61 import jexer
.backend
.TWindowBackend
;
62 import jexer
.menu
.TMenu
;
63 import jexer
.menu
.TMenuItem
;
64 import static jexer
.TCommand
.*;
65 import static jexer
.TKeypress
.*;
68 * TApplication is the main driver class for a full Text User Interface
69 * application. It manages windows, provides a menu bar and status bar, and
70 * processes events received from the user.
72 public class TApplication
implements Runnable
{
77 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
79 // ------------------------------------------------------------------------
80 // Public constants -------------------------------------------------------
81 // ------------------------------------------------------------------------
84 * If true, emit thread stuff to System.err.
86 private static final boolean debugThreads
= false;
89 * If true, emit events being processed to System.err.
91 private static final boolean debugEvents
= false;
94 * If true, do "smart placement" on new windows that are not specified to
97 private static final boolean smartWindowPlacement
= true;
100 * Two backend types are available.
102 public static enum BackendType
{
109 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
114 * Synonym for ECMA48.
119 // ------------------------------------------------------------------------
120 // Primary/secondary event handlers ---------------------------------------
121 // ------------------------------------------------------------------------
124 * WidgetEventHandler is the main event consumer loop. There are at most
125 * two such threads in existence: the primary for normal case and a
126 * secondary that is used for TMessageBox, TInputBox, and similar.
128 private class WidgetEventHandler
implements Runnable
{
130 * The main application.
132 private TApplication application
;
135 * Whether or not this WidgetEventHandler is the primary or secondary
138 private boolean primary
= true;
141 * Public constructor.
143 * @param application the main application
144 * @param primary if true, this is the primary event handler thread
146 public WidgetEventHandler(final TApplication application
,
147 final boolean primary
) {
149 this.application
= application
;
150 this.primary
= primary
;
157 boolean first
= true;
160 while (!application
.quit
) {
162 // Wait until application notifies me
163 while (!application
.quit
) {
165 synchronized (application
.drainEventQueue
) {
166 if (application
.drainEventQueue
.size() > 0) {
175 timeout
= application
.getSleepTime(1000);
179 // A timer needs to fire, break out.
184 System
.err
.printf("%d %s %s sleep %d millis\n",
185 System
.currentTimeMillis(), this,
186 primary ?
"primary" : "secondary", timeout
);
189 synchronized (this) {
194 System
.err
.printf("%d %s %s AWAKE\n",
195 System
.currentTimeMillis(), this,
196 primary ?
"primary" : "secondary");
200 && (application
.secondaryEventReceiver
== null)
202 // Secondary thread, emergency exit. If we got
203 // here then something went wrong with the
204 // handoff between yield() and closeWindow().
205 synchronized (application
.primaryEventHandler
) {
206 application
.primaryEventHandler
.notify();
208 application
.secondaryEventHandler
= null;
209 throw new RuntimeException("secondary exited " +
213 } catch (InterruptedException e
) {
216 } // while (!application.quit)
218 // Pull all events off the queue
220 TInputEvent event
= null;
221 synchronized (application
.drainEventQueue
) {
222 if (application
.drainEventQueue
.size() == 0) {
225 event
= application
.drainEventQueue
.remove(0);
228 // We will have an event to process, so repaint the
229 // screen at the end.
230 application
.repaint
= true;
233 primaryHandleEvent(event
);
235 secondaryHandleEvent(event
);
238 && (application
.secondaryEventReceiver
== null)
240 // Secondary thread, time to exit.
242 // DO NOT UNLOCK. Primary thread just came back from
243 // primaryHandleEvent() and will unlock in the else
244 // block below. Just wake it up.
245 synchronized (application
.primaryEventHandler
) {
246 application
.primaryEventHandler
.notify();
248 // Now eliminate my reference so that
249 // wakeEventHandler() resumes working on the primary.
250 application
.secondaryEventHandler
= null;
258 // Fire timers, update screen.
260 application
.finishEventProcessing();
263 } // while (true) (main runnable loop)
268 * The primary event handler thread.
270 private volatile WidgetEventHandler primaryEventHandler
;
273 * The secondary event handler thread.
275 private volatile WidgetEventHandler secondaryEventHandler
;
278 * The widget receiving events from the secondary event handler thread.
280 private volatile TWidget secondaryEventReceiver
;
283 * Wake the sleeping active event handler.
285 private void wakeEventHandler() {
290 if (secondaryEventHandler
!= null) {
291 synchronized (secondaryEventHandler
) {
292 secondaryEventHandler
.notify();
295 assert (primaryEventHandler
!= null);
296 synchronized (primaryEventHandler
) {
297 primaryEventHandler
.notify();
302 // ------------------------------------------------------------------------
303 // TApplication attributes ------------------------------------------------
304 // ------------------------------------------------------------------------
307 * Access to the physical screen, keyboard, and mouse.
309 private Backend backend
;
314 * @return the Backend
316 public final Backend
getBackend() {
325 public final Screen
getScreen() {
326 if (backend
instanceof TWindowBackend
) {
327 // We are being rendered to a TWindow. We can't use its
328 // getScreen() method because that is how it is rendering to a
329 // hardware backend somewhere. Instead use its getOtherScreen()
331 return ((TWindowBackend
) backend
).getOtherScreen();
333 return backend
.getScreen();
338 * Actual mouse coordinate X.
343 * Actual mouse coordinate Y.
348 * Old version of mouse coordinate X.
350 private int oldMouseX
;
353 * Old version mouse coordinate Y.
355 private int oldMouseY
;
358 * The last mouse up click time, used to determine if this is a mouse
361 private long lastMouseUpTime
;
364 * The amount of millis between mouse up events to assume a double-click.
366 private long doubleClickTime
= 250;
369 * Event queue that is filled by run().
371 private List
<TInputEvent
> fillEventQueue
;
374 * Event queue that will be drained by either primary or secondary
377 private List
<TInputEvent
> drainEventQueue
;
380 * Top-level menus in this application.
382 private List
<TMenu
> menus
;
385 * Stack of activated sub-menus in this application.
387 private List
<TMenu
> subMenus
;
390 * The currently active menu.
392 private TMenu activeMenu
= null;
395 * Active keyboard accelerators.
397 private Map
<TKeypress
, TMenuItem
> accelerators
;
402 private List
<TMenuItem
> menuItems
;
405 * Windows and widgets pull colors from this ColorTheme.
407 private ColorTheme theme
;
410 * Get the color theme.
414 public final ColorTheme
getTheme() {
419 * The top-level windows (but not menus).
421 private List
<TWindow
> windows
;
424 * The currently acive window.
426 private TWindow activeWindow
= null;
429 * Timers that are being ticked.
431 private List
<TTimer
> timers
;
434 * When true, the application has been started.
436 private volatile boolean started
= false;
439 * When true, exit the application.
441 private volatile boolean quit
= false;
444 * When true, repaint the entire screen.
446 private volatile boolean repaint
= true;
449 * Repaint the screen on the next update.
451 public void doRepaint() {
457 * Y coordinate of the top edge of the desktop. For now this is a
458 * constant. Someday it would be nice to have a multi-line menu or
461 private static final int desktopTop
= 1;
464 * Get Y coordinate of the top edge of the desktop.
466 * @return Y coordinate of the top edge of the desktop
468 public final int getDesktopTop() {
473 * Y coordinate of the bottom edge of the desktop.
475 private int desktopBottom
;
478 * Get Y coordinate of the bottom edge of the desktop.
480 * @return Y coordinate of the bottom edge of the desktop
482 public final int getDesktopBottom() {
483 return desktopBottom
;
487 * An optional TDesktop background window that is drawn underneath
490 private TDesktop desktop
;
493 * Set the TDesktop instance.
495 * @param desktop a TDesktop instance, or null to remove the one that is
498 public final void setDesktop(final TDesktop desktop
) {
499 if (this.desktop
!= null) {
500 this.desktop
.onClose();
502 this.desktop
= desktop
;
506 * Get the TDesktop instance.
508 * @return the desktop, or null if it is not set
510 public final TDesktop
getDesktop() {
515 * Get the current active window.
517 * @return the active window, or null if it is not set
519 public final TWindow
getActiveWindow() {
524 * Get a (shallow) copy of the window list.
526 * @return a copy of the list of windows for this application
528 public final List
<TWindow
> getAllWindows() {
529 List
<TWindow
> result
= new LinkedList
<TWindow
>();
530 result
.addAll(windows
);
535 * If true, focus follows mouse: windows automatically raised if the
536 * mouse passes over them.
538 private boolean focusFollowsMouse
= false;
541 * Get focusFollowsMouse flag.
543 * @return true if focus follows mouse: windows automatically raised if
544 * the mouse passes over them
546 public boolean getFocusFollowsMouse() {
547 return focusFollowsMouse
;
551 * Set focusFollowsMouse flag.
553 * @param focusFollowsMouse if true, focus follows mouse: windows
554 * automatically raised if the mouse passes over them
556 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
557 this.focusFollowsMouse
= focusFollowsMouse
;
560 // ------------------------------------------------------------------------
561 // General behavior -------------------------------------------------------
562 // ------------------------------------------------------------------------
565 * Display the about dialog.
567 protected void showAboutDialog() {
568 messageBox(i18n
.getString("aboutDialogTitle"),
569 MessageFormat
.format(i18n
.getString("aboutDialogText"),
570 this.getClass().getPackage().getImplementationVersion()),
571 TMessageBox
.Type
.OK
);
574 // ------------------------------------------------------------------------
575 // Constructors -----------------------------------------------------------
576 // ------------------------------------------------------------------------
579 * Public constructor.
581 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
583 * @throws UnsupportedEncodingException if an exception is thrown when
584 * creating the InputStreamReader
586 public TApplication(final BackendType backendType
)
587 throws UnsupportedEncodingException
{
589 switch (backendType
) {
591 // The default SwingBackend is 80x25, 20 pt font. If you want to
592 // change that, you can pass the extra arguments to the
593 // SwingBackend constructor here. For example, if you wanted
594 // 90x30, 16 pt font:
596 // backend = new SwingBackend(this, 90, 30, 16);
597 backend
= new SwingBackend(this);
602 backend
= new ECMA48Backend(this, null, null);
605 throw new IllegalArgumentException("Invalid backend type: "
612 * Public constructor. The backend type will be BackendType.ECMA48.
614 * @param input an InputStream connected to the remote user, or null for
615 * System.in. If System.in is used, then on non-Windows systems it will
616 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
617 * mode. input is always converted to a Reader with UTF-8 encoding.
618 * @param output an OutputStream connected to the remote user, or null
619 * for System.out. output is always converted to a Writer with UTF-8
621 * @throws UnsupportedEncodingException if an exception is thrown when
622 * creating the InputStreamReader
624 public TApplication(final InputStream input
,
625 final OutputStream output
) throws UnsupportedEncodingException
{
627 backend
= new ECMA48Backend(this, input
, output
);
632 * Public constructor. The backend type will be BackendType.ECMA48.
634 * @param input the InputStream underlying 'reader'. Its available()
635 * method is used to determine if reader.read() will block or not.
636 * @param reader a Reader connected to the remote user.
637 * @param writer a PrintWriter connected to the remote user.
638 * @param setRawMode if true, set System.in into raw mode with stty.
639 * This should in general not be used. It is here solely for Demo3,
640 * which uses System.in.
641 * @throws IllegalArgumentException if input, reader, or writer are null.
643 public TApplication(final InputStream input
, final Reader reader
,
644 final PrintWriter writer
, final boolean setRawMode
) {
646 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
651 * Public constructor. The backend type will be BackendType.ECMA48.
653 * @param input the InputStream underlying 'reader'. Its available()
654 * method is used to determine if reader.read() will block or not.
655 * @param reader a Reader connected to the remote user.
656 * @param writer a PrintWriter connected to the remote user.
657 * @throws IllegalArgumentException if input, reader, or writer are null.
659 public TApplication(final InputStream input
, final Reader reader
,
660 final PrintWriter writer
) {
662 this(input
, reader
, writer
, false);
666 * Public constructor. This hook enables use with new non-Jexer
669 * @param backend a Backend that is already ready to go.
671 public TApplication(final Backend backend
) {
672 this.backend
= backend
;
673 backend
.setListener(this);
678 * Finish construction once the backend is set.
680 private void TApplicationImpl() {
681 theme
= new ColorTheme();
682 desktopBottom
= getScreen().getHeight() - 1;
683 fillEventQueue
= new ArrayList
<TInputEvent
>();
684 drainEventQueue
= new ArrayList
<TInputEvent
>();
685 windows
= new LinkedList
<TWindow
>();
686 menus
= new LinkedList
<TMenu
>();
687 subMenus
= new LinkedList
<TMenu
>();
688 timers
= new LinkedList
<TTimer
>();
689 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
690 menuItems
= new ArrayList
<TMenuItem
>();
691 desktop
= new TDesktop(this);
693 // Special case: the Swing backend needs to have a timer to drive its
695 if ((backend
instanceof SwingBackend
)
696 || (backend
instanceof MultiBackend
)
698 // Default to 500 millis, unless a SwingBackend has its own
701 if (backend
instanceof SwingBackend
) {
702 millis
= ((SwingBackend
) backend
).getBlinkMillis();
705 addTimer(millis
, true,
708 TApplication
.this.doRepaint();
716 // ------------------------------------------------------------------------
717 // Screen refresh loop ----------------------------------------------------
718 // ------------------------------------------------------------------------
721 * Process background events, and update the screen.
723 private void finishEventProcessing() {
725 System
.err
.printf(System
.currentTimeMillis() + " " +
726 Thread
.currentThread() + " finishEventProcessing()\n");
729 // Process timers and call doIdle()'s
733 synchronized (getScreen()) {
738 System
.err
.printf(System
.currentTimeMillis() + " " +
739 Thread
.currentThread() + " finishEventProcessing() END\n");
744 * Invert the cell color at a position. This is used to track the mouse.
746 * @param x column position
747 * @param y row position
749 private void invertCell(final int x
, final int y
) {
751 System
.err
.printf("%d %s invertCell() %d %d\n",
752 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
754 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
755 attr
.setForeColor(attr
.getForeColor().invert());
756 attr
.setBackColor(attr
.getBackColor().invert());
757 getScreen().putAttrXY(x
, y
, attr
, false);
763 private void drawAll() {
764 boolean menuIsActive
= false;
767 System
.err
.printf("%d %s drawAll() enter\n",
768 System
.currentTimeMillis(), Thread
.currentThread());
773 System
.err
.printf("%d %s drawAll() !repaint\n",
774 System
.currentTimeMillis(), Thread
.currentThread());
776 synchronized (getScreen()) {
777 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
778 // The only thing that has happened is the mouse moved.
779 // Clear the old position and draw the new position.
780 invertCell(oldMouseX
, oldMouseY
);
781 invertCell(mouseX
, mouseY
);
785 if (getScreen().isDirty()) {
786 backend
.flushScreen();
793 System
.err
.printf("%d %s drawAll() REDRAW\n",
794 System
.currentTimeMillis(), Thread
.currentThread());
797 // If true, the cursor is not visible
798 boolean cursor
= false;
800 // Start with a clean screen
804 if (desktop
!= null) {
805 desktop
.drawChildren();
808 // Draw each window in reverse Z order
809 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
810 Collections
.sort(sorted
);
811 TWindow topLevel
= null;
812 if (sorted
.size() > 0) {
813 topLevel
= sorted
.get(0);
815 Collections
.reverse(sorted
);
816 for (TWindow window
: sorted
) {
817 if (window
.isShown()) {
818 window
.drawChildren();
822 // Draw the blank menubar line - reset the screen clipping first so
823 // it won't trim it out.
824 getScreen().resetClipping();
825 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
826 theme
.getColor("tmenu"));
827 // Now draw the menus.
829 for (TMenu menu
: menus
) {
830 CellAttributes menuColor
;
831 CellAttributes menuMnemonicColor
;
832 if (menu
.isActive()) {
834 menuColor
= theme
.getColor("tmenu.highlighted");
835 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
838 menuColor
= theme
.getColor("tmenu");
839 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
841 // Draw the menu title
842 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
844 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
845 // Draw the highlight character
846 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
847 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
849 if (menu
.isActive()) {
851 // Reset the screen clipping so we can draw the next title.
852 getScreen().resetClipping();
854 x
+= menu
.getTitle().length() + 2;
857 for (TMenu menu
: subMenus
) {
858 // Reset the screen clipping so we can draw the next sub-menu.
859 getScreen().resetClipping();
863 // Draw the status bar of the top-level window
864 TStatusBar statusBar
= null;
865 if (topLevel
!= null) {
866 statusBar
= topLevel
.getStatusBar();
868 if (statusBar
!= null) {
869 getScreen().resetClipping();
870 statusBar
.setWidth(getScreen().getWidth());
871 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
874 CellAttributes barColor
= new CellAttributes();
875 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
876 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
880 // Draw the mouse pointer
881 invertCell(mouseX
, mouseY
);
885 // Place the cursor if it is visible
887 TWidget activeWidget
= null;
888 if (sorted
.size() > 0) {
889 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
890 if (activeWidget
.isCursorVisible()) {
891 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
892 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
894 getScreen().putCursor(true,
895 activeWidget
.getCursorAbsoluteX(),
896 activeWidget
.getCursorAbsoluteY());
899 getScreen().putCursor(false,
900 activeWidget
.getCursorAbsoluteX(),
901 activeWidget
.getCursorAbsoluteY());
910 getScreen().hideCursor();
913 // Flush the screen contents
914 if (getScreen().isDirty()) {
915 backend
.flushScreen();
921 // ------------------------------------------------------------------------
922 // Main loop --------------------------------------------------------------
923 // ------------------------------------------------------------------------
926 * Force this application to exit.
930 synchronized (this) {
936 * Run this application until it exits.
939 // Start the main consumer thread
940 primaryEventHandler
= new WidgetEventHandler(this, true);
941 (new Thread(primaryEventHandler
)).start();
946 synchronized (this) {
947 boolean doWait
= false;
949 synchronized (fillEventQueue
) {
950 if (fillEventQueue
.size() == 0) {
956 // No I/O to dispatch, so wait until the backend
960 System
.err
.println(System
.currentTimeMillis() +
967 System
.err
.println(System
.currentTimeMillis() +
970 } catch (InterruptedException e
) {
971 // I'm awake and don't care why, let's see what's
972 // going on out there.
976 } // synchronized (this)
978 synchronized (fillEventQueue
) {
979 // Pull any pending I/O events
980 backend
.getEvents(fillEventQueue
);
982 // Dispatch each event to the appropriate handler, one at a
985 TInputEvent event
= null;
986 if (fillEventQueue
.size() == 0) {
989 event
= fillEventQueue
.remove(0);
990 metaHandleEvent(event
);
994 // Wake a consumer thread if we have any pending events.
995 if (drainEventQueue
.size() > 0) {
1001 // Shutdown the event consumer threads
1002 if (secondaryEventHandler
!= null) {
1003 synchronized (secondaryEventHandler
) {
1004 secondaryEventHandler
.notify();
1007 if (primaryEventHandler
!= null) {
1008 synchronized (primaryEventHandler
) {
1009 primaryEventHandler
.notify();
1013 // Shutdown the user I/O thread(s)
1016 // Close all the windows. This gives them an opportunity to release
1023 * Peek at certain application-level events, add to eventQueue, and wake
1024 * up the consuming Thread.
1026 * @param event the input event to consume
1028 private void metaHandleEvent(final TInputEvent event
) {
1031 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1032 event
)); System
.err
.flush();
1036 // Do no more processing if the application is already trying
1041 // Special application-wide events -------------------------------
1044 if (event
instanceof TCommandEvent
) {
1045 TCommandEvent command
= (TCommandEvent
) event
;
1046 if (command
.getCmd().equals(cmAbort
)) {
1052 synchronized (drainEventQueue
) {
1054 if (event
instanceof TResizeEvent
) {
1055 TResizeEvent resize
= (TResizeEvent
) event
;
1056 synchronized (getScreen()) {
1057 getScreen().setDimensions(resize
.getWidth(),
1058 resize
.getHeight());
1059 desktopBottom
= getScreen().getHeight() - 1;
1065 if (desktop
!= null) {
1066 desktop
.setDimensions(0, 0, resize
.getWidth(),
1067 resize
.getHeight() - 1);
1070 // Change menu edges if needed.
1073 // We are dirty, redraw the screen.
1078 // Put into the main queue
1079 drainEventQueue
.add(event
);
1084 * Dispatch one event to the appropriate widget or application-level
1085 * event handler. This is the primary event handler, it has the normal
1086 * application-wide event handling.
1088 * @param event the input event to consume
1089 * @see #secondaryHandleEvent(TInputEvent event)
1091 private void primaryHandleEvent(final TInputEvent event
) {
1094 System
.err
.printf("Handle event: %s\n", event
);
1096 TMouseEvent doubleClick
= null;
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();
1109 if (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
) {
1110 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1113 // This is a double-click.
1114 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1116 mouse
.getX(), mouse
.getY(),
1117 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1118 mouse
.isMouse1(), mouse
.isMouse2(),
1120 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1123 // The first click of a potential double-click.
1124 lastMouseUpTime
= mouse
.getTime().getTime();
1129 // See if we need to switch focus to another window or the menu
1130 checkSwitchFocus((TMouseEvent
) event
);
1133 // Handle menu events
1134 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1135 TMenu menu
= activeMenu
;
1137 if (event
instanceof TMouseEvent
) {
1138 TMouseEvent mouse
= (TMouseEvent
) event
;
1140 while (subMenus
.size() > 0) {
1141 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1142 if (subMenu
.mouseWouldHit(mouse
)) {
1145 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1146 && (!mouse
.isMouse1())
1147 && (!mouse
.isMouse2())
1148 && (!mouse
.isMouse3())
1149 && (!mouse
.isMouseWheelUp())
1150 && (!mouse
.isMouseWheelDown())
1154 // We navigated away from a sub-menu, so close it
1158 // Convert the mouse relative x/y to menu coordinates
1159 assert (mouse
.getX() == mouse
.getAbsoluteX());
1160 assert (mouse
.getY() == mouse
.getAbsoluteY());
1161 if (subMenus
.size() > 0) {
1162 menu
= subMenus
.get(subMenus
.size() - 1);
1164 mouse
.setX(mouse
.getX() - menu
.getX());
1165 mouse
.setY(mouse
.getY() - menu
.getY());
1167 menu
.handleEvent(event
);
1171 if (event
instanceof TKeypressEvent
) {
1172 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1174 // See if this key matches an accelerator, and is not being
1175 // shortcutted by the active window, and if so dispatch the menu
1177 boolean windowWillShortcut
= false;
1178 if (activeWindow
!= null) {
1179 assert (activeWindow
.isShown());
1180 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1181 // We do not process this key, it will be passed to the
1183 windowWillShortcut
= true;
1187 if (!windowWillShortcut
&& !modalWindowActive()) {
1188 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1189 TMenuItem item
= null;
1190 synchronized (accelerators
) {
1191 item
= accelerators
.get(keypressLowercase
);
1194 if (item
.isEnabled()) {
1195 // Let the menu item dispatch
1201 // Handle the keypress
1202 if (onKeypress(keypress
)) {
1208 if (event
instanceof TCommandEvent
) {
1209 if (onCommand((TCommandEvent
) event
)) {
1214 if (event
instanceof TMenuEvent
) {
1215 if (onMenu((TMenuEvent
) event
)) {
1220 // Dispatch events to the active window -------------------------------
1221 boolean dispatchToDesktop
= true;
1222 TWindow window
= activeWindow
;
1223 if (window
!= null) {
1224 assert (window
.isActive());
1225 assert (window
.isShown());
1226 if (event
instanceof TMouseEvent
) {
1227 TMouseEvent mouse
= (TMouseEvent
) event
;
1228 // Convert the mouse relative x/y to window coordinates
1229 assert (mouse
.getX() == mouse
.getAbsoluteX());
1230 assert (mouse
.getY() == mouse
.getAbsoluteY());
1231 mouse
.setX(mouse
.getX() - window
.getX());
1232 mouse
.setY(mouse
.getY() - window
.getY());
1234 if (doubleClick
!= null) {
1235 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1236 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1239 if (window
.mouseWouldHit(mouse
)) {
1240 dispatchToDesktop
= false;
1242 } else if (event
instanceof TKeypressEvent
) {
1243 dispatchToDesktop
= false;
1247 System
.err
.printf("TApplication dispatch event: %s\n",
1250 window
.handleEvent(event
);
1251 if (doubleClick
!= null) {
1252 window
.handleEvent(doubleClick
);
1255 if (dispatchToDesktop
) {
1256 // This event is fair game for the desktop to process.
1257 if (desktop
!= null) {
1258 desktop
.handleEvent(event
);
1259 if (doubleClick
!= null) {
1260 desktop
.handleEvent(doubleClick
);
1267 * Dispatch one event to the appropriate widget or application-level
1268 * event handler. This is the secondary event handler used by certain
1269 * special dialogs (currently TMessageBox and TFileOpenBox).
1271 * @param event the input event to consume
1272 * @see #primaryHandleEvent(TInputEvent event)
1274 private void secondaryHandleEvent(final TInputEvent event
) {
1275 TMouseEvent doubleClick
= null;
1277 // Peek at the mouse position
1278 if (event
instanceof TMouseEvent
) {
1279 TMouseEvent mouse
= (TMouseEvent
) event
;
1280 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1283 mouseX
= mouse
.getX();
1284 mouseY
= mouse
.getY();
1286 if (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
) {
1287 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1290 // This is a double-click.
1291 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1293 mouse
.getX(), mouse
.getY(),
1294 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1295 mouse
.isMouse1(), mouse
.isMouse2(),
1297 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1300 // The first click of a potential double-click.
1301 lastMouseUpTime
= mouse
.getTime().getTime();
1307 secondaryEventReceiver
.handleEvent(event
);
1308 if (doubleClick
!= null) {
1309 secondaryEventReceiver
.handleEvent(doubleClick
);
1314 * Enable a widget to override the primary event thread.
1316 * @param widget widget that will receive events
1318 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1320 System
.err
.println(System
.currentTimeMillis() +
1321 " enableSecondaryEventReceiver()");
1324 assert (secondaryEventReceiver
== null);
1325 assert (secondaryEventHandler
== null);
1326 assert ((widget
instanceof TMessageBox
)
1327 || (widget
instanceof TFileOpenBox
));
1328 secondaryEventReceiver
= widget
;
1329 secondaryEventHandler
= new WidgetEventHandler(this, false);
1331 (new Thread(secondaryEventHandler
)).start();
1335 * Yield to the secondary thread.
1337 public final void yield() {
1338 assert (secondaryEventReceiver
!= null);
1340 while (secondaryEventReceiver
!= null) {
1341 synchronized (primaryEventHandler
) {
1343 primaryEventHandler
.wait();
1344 } catch (InterruptedException e
) {
1352 * Do stuff when there is no user input.
1354 private void doIdle() {
1356 System
.err
.printf(System
.currentTimeMillis() + " " +
1357 Thread
.currentThread() + " doIdle()\n");
1360 synchronized (timers
) {
1363 System
.err
.printf(System
.currentTimeMillis() + " " +
1364 Thread
.currentThread() + " doIdle() 2\n");
1367 // Run any timers that have timed out
1368 Date now
= new Date();
1369 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1370 for (TTimer timer
: timers
) {
1371 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1372 // Something might change, so repaint the screen.
1375 if (timer
.recurring
) {
1376 keepTimers
.add(timer
);
1379 keepTimers
.add(timer
);
1382 timers
= keepTimers
;
1386 for (TWindow window
: windows
) {
1389 if (desktop
!= null) {
1394 // ------------------------------------------------------------------------
1395 // TWindow management -----------------------------------------------------
1396 // ------------------------------------------------------------------------
1399 * Return the total number of windows.
1401 * @return the total number of windows
1403 public final int windowCount() {
1404 return windows
.size();
1408 * Return the number of windows that are showing.
1410 * @return the number of windows that are showing on screen
1412 public final int shownWindowCount() {
1414 for (TWindow w
: windows
) {
1423 * Return the number of windows that are hidden.
1425 * @return the number of windows that are hidden
1427 public final int hiddenWindowCount() {
1429 for (TWindow w
: windows
) {
1438 * Check if a window instance is in this application's window list.
1440 * @param window window to look for
1441 * @return true if this window is in the list
1443 public final boolean hasWindow(final TWindow window
) {
1444 if (windows
.size() == 0) {
1447 for (TWindow w
: windows
) {
1449 assert (window
.getApplication() == this);
1457 * Activate a window: bring it to the top and have it receive events.
1459 * @param window the window to become the new active window
1461 public void activateWindow(final TWindow window
) {
1462 if (hasWindow(window
) == false) {
1464 * Someone has a handle to a window I don't have. Ignore this
1470 // Whatever window might be moving/dragging, stop it now.
1471 for (TWindow w
: windows
) {
1472 if (w
.inMovements()) {
1477 assert (windows
.size() > 0);
1479 if (window
.isHidden()) {
1480 // Unhiding will also activate.
1484 assert (window
.isShown());
1486 if (windows
.size() == 1) {
1487 assert (window
== windows
.get(0));
1488 if (activeWindow
== null) {
1489 activeWindow
= window
;
1491 activeWindow
.setActive(true);
1492 activeWindow
.onFocus();
1495 assert (window
.isActive());
1496 assert (activeWindow
== window
);
1500 if (activeWindow
== window
) {
1501 assert (window
.isActive());
1503 // Window is already active, do nothing.
1507 assert (!window
.isActive());
1508 if (activeWindow
!= null) {
1509 assert (activeWindow
.getZ() == 0);
1511 activeWindow
.setActive(false);
1512 activeWindow
.setZ(window
.getZ());
1514 // Unset activeWindow now before unfocus, so that a window
1515 // lifecycle change inside onUnfocus() doesn't call
1516 // switchWindow() and lead to a stack overflow.
1517 TWindow oldActiveWindow
= activeWindow
;
1518 activeWindow
= null;
1519 oldActiveWindow
.onUnfocus();
1521 activeWindow
= window
;
1522 activeWindow
.setZ(0);
1523 activeWindow
.setActive(true);
1524 activeWindow
.onFocus();
1531 * @param window the window to hide
1533 public void hideWindow(final TWindow window
) {
1534 if (hasWindow(window
) == false) {
1536 * Someone has a handle to a window I don't have. Ignore this
1542 // Whatever window might be moving/dragging, stop it now.
1543 for (TWindow w
: windows
) {
1544 if (w
.inMovements()) {
1549 assert (windows
.size() > 0);
1551 if (!window
.hidden
) {
1552 if (window
== activeWindow
) {
1553 if (shownWindowCount() > 1) {
1556 activeWindow
= null;
1557 window
.setActive(false);
1561 window
.hidden
= true;
1569 * @param window the window to show
1571 public void showWindow(final TWindow window
) {
1572 if (hasWindow(window
) == false) {
1574 * Someone has a handle to a window I don't have. Ignore this
1580 // Whatever window might be moving/dragging, stop it now.
1581 for (TWindow w
: windows
) {
1582 if (w
.inMovements()) {
1587 assert (windows
.size() > 0);
1589 if (window
.hidden
) {
1590 window
.hidden
= false;
1592 activateWindow(window
);
1597 * Close window. Note that the window's destructor is NOT called by this
1598 * method, instead the GC is assumed to do the cleanup.
1600 * @param window the window to remove
1602 public final void closeWindow(final TWindow window
) {
1603 if (hasWindow(window
) == false) {
1605 * Someone has a handle to a window I don't have. Ignore this
1611 synchronized (windows
) {
1612 // Whatever window might be moving/dragging, stop it now.
1613 for (TWindow w
: windows
) {
1614 if (w
.inMovements()) {
1619 int z
= window
.getZ();
1622 Collections
.sort(windows
);
1624 activeWindow
= null;
1625 for (TWindow w
: windows
) {
1627 w
.setZ(w
.getZ() - 1);
1628 if (w
.getZ() == 0) {
1631 assert (activeWindow
== null);
1643 // Perform window cleanup
1646 // Check if we are closing a TMessageBox or similar
1647 if (secondaryEventReceiver
!= null) {
1648 assert (secondaryEventHandler
!= null);
1650 // Do not send events to the secondaryEventReceiver anymore, the
1651 // window is closed.
1652 secondaryEventReceiver
= null;
1654 // Wake the secondary thread, it will wake the primary as it
1656 synchronized (secondaryEventHandler
) {
1657 secondaryEventHandler
.notify();
1661 // Permit desktop to be active if it is the only thing left.
1662 if (desktop
!= null) {
1663 if (windows
.size() == 0) {
1664 desktop
.setActive(true);
1670 * Switch to the next window.
1672 * @param forward if true, then switch to the next window in the list,
1673 * otherwise switch to the previous window in the list
1675 public final void switchWindow(final boolean forward
) {
1676 // Only switch if there are multiple visible windows
1677 if (shownWindowCount() < 2) {
1680 assert (activeWindow
!= null);
1682 synchronized (windows
) {
1683 // Whatever window might be moving/dragging, stop it now.
1684 for (TWindow w
: windows
) {
1685 if (w
.inMovements()) {
1690 // Swap z/active between active window and the next in the list
1691 int activeWindowI
= -1;
1692 for (int i
= 0; i
< windows
.size(); i
++) {
1693 if (windows
.get(i
) == activeWindow
) {
1694 assert (activeWindow
.isActive());
1698 assert (!windows
.get(0).isActive());
1701 assert (activeWindowI
>= 0);
1703 // Do not switch if a window is modal
1704 if (activeWindow
.isModal()) {
1708 int nextWindowI
= activeWindowI
;
1712 nextWindowI
%= windows
.size();
1715 if (nextWindowI
< 0) {
1716 nextWindowI
= windows
.size() - 1;
1720 if (windows
.get(nextWindowI
).isShown()) {
1721 activateWindow(windows
.get(nextWindowI
));
1725 } // synchronized (windows)
1730 * Add a window to my window list and make it active.
1732 * @param window new window to add
1734 public final void addWindow(final TWindow window
) {
1736 // Do not add menu windows to the window list.
1737 if (window
instanceof TMenu
) {
1741 // Do not add the desktop to the window list.
1742 if (window
instanceof TDesktop
) {
1746 synchronized (windows
) {
1747 // Whatever window might be moving/dragging, stop it now.
1748 for (TWindow w
: windows
) {
1749 if (w
.inMovements()) {
1754 // Do not allow a modal window to spawn a non-modal window. If a
1755 // modal window is active, then this window will become modal
1757 if (modalWindowActive()) {
1758 window
.flags
|= TWindow
.MODAL
;
1759 window
.flags
|= TWindow
.CENTERED
;
1760 window
.hidden
= false;
1762 if (window
.isShown()) {
1763 for (TWindow w
: windows
) {
1768 w
.setZ(w
.getZ() + 1);
1771 windows
.add(window
);
1772 if (window
.isShown()) {
1773 activeWindow
= window
;
1774 activeWindow
.setZ(0);
1775 activeWindow
.setActive(true);
1776 activeWindow
.onFocus();
1779 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1780 && smartWindowPlacement
) {
1782 doSmartPlacement(window
);
1786 // Desktop cannot be active over any other window.
1787 if (desktop
!= null) {
1788 desktop
.setActive(false);
1793 * Check if there is a system-modal window on top.
1795 * @return true if the active window is modal
1797 private boolean modalWindowActive() {
1798 if (windows
.size() == 0) {
1802 for (TWindow w
: windows
) {
1812 * Close all open windows.
1814 private void closeAllWindows() {
1815 // Don't do anything if we are in the menu
1816 if (activeMenu
!= null) {
1819 while (windows
.size() > 0) {
1820 closeWindow(windows
.get(0));
1825 * Re-layout the open windows as non-overlapping tiles. This produces
1826 * almost the same results as Turbo Pascal 7.0's IDE.
1828 private void tileWindows() {
1829 synchronized (windows
) {
1830 // Don't do anything if we are in the menu
1831 if (activeMenu
!= null) {
1834 int z
= windows
.size();
1840 a
= (int)(Math
.sqrt(z
));
1844 if (((a
* b
) + c
) == z
) {
1852 int newWidth
= (getScreen().getWidth() / a
);
1853 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1854 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1856 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1857 Collections
.sort(sorted
);
1858 Collections
.reverse(sorted
);
1859 for (int i
= 0; i
< sorted
.size(); i
++) {
1860 int logicalX
= i
/ b
;
1861 int logicalY
= i
% b
;
1862 if (i
>= ((a
- 1) * b
)) {
1864 logicalY
= i
- ((a
- 1) * b
);
1867 TWindow w
= sorted
.get(i
);
1868 w
.setX(logicalX
* newWidth
);
1869 w
.setWidth(newWidth
);
1870 if (i
>= ((a
- 1) * b
)) {
1871 w
.setY((logicalY
* newHeight2
) + 1);
1872 w
.setHeight(newHeight2
);
1874 w
.setY((logicalY
* newHeight1
) + 1);
1875 w
.setHeight(newHeight1
);
1882 * Re-layout the open windows as overlapping cascaded windows.
1884 private void cascadeWindows() {
1885 synchronized (windows
) {
1886 // Don't do anything if we are in the menu
1887 if (activeMenu
!= null) {
1892 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1893 Collections
.sort(sorted
);
1894 Collections
.reverse(sorted
);
1895 for (TWindow window
: sorted
) {
1900 if (x
> getScreen().getWidth()) {
1903 if (y
>= getScreen().getHeight()) {
1911 * Place a window to minimize its overlap with other windows.
1913 * @param window the window to place
1915 public final void doSmartPlacement(final TWindow window
) {
1916 // This is a pretty dumb algorithm, but seems to work. The hardest
1917 // part is computing these "overlap" values seeking a minimum average
1920 int yMin
= desktopTop
;
1921 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1922 int yMax
= desktopBottom
- window
.getHeight() + 1;
1930 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1931 // No work to do, bail out.
1935 // Compute the overlap matrix without the new window.
1936 int width
= getScreen().getWidth();
1937 int height
= getScreen().getHeight();
1938 int overlapMatrix
[][] = new int[width
][height
];
1939 for (TWindow w
: windows
) {
1943 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1950 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1957 overlapMatrix
[x
][y
]++;
1962 long oldOverlapTotal
= 0;
1963 long oldOverlapN
= 0;
1964 for (int x
= 0; x
< width
; x
++) {
1965 for (int y
= 0; y
< height
; y
++) {
1966 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1967 if (overlapMatrix
[x
][y
] > 0) {
1974 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1975 boolean first
= true;
1976 int windowX
= window
.getX();
1977 int windowY
= window
.getY();
1979 // For each possible (x, y) position for the new window, compute a
1980 // new overlap matrix.
1981 for (int x
= xMin
; x
< xMax
; x
++) {
1982 for (int y
= yMin
; y
< yMax
; y
++) {
1984 // Start with the matrix minus this window.
1985 int newMatrix
[][] = new int[width
][height
];
1986 for (int mx
= 0; mx
< width
; mx
++) {
1987 for (int my
= 0; my
< height
; my
++) {
1988 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1992 // Add this window's values to the new overlap matrix.
1993 long newOverlapTotal
= 0;
1994 long newOverlapN
= 0;
1995 // Start by adding each new cell.
1996 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2000 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2004 newMatrix
[wx
][wy
]++;
2007 // Now figure out the new value for total coverage.
2008 for (int mx
= 0; mx
< width
; mx
++) {
2009 for (int my
= 0; my
< height
; my
++) {
2010 newOverlapTotal
+= newMatrix
[x
][y
];
2011 if (newMatrix
[mx
][my
] > 0) {
2016 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2019 // First time: just record what we got.
2020 oldOverlapAvg
= newOverlapAvg
;
2023 // All other times: pick a new best (x, y) and save the
2025 if (newOverlapAvg
< oldOverlapAvg
) {
2028 oldOverlapAvg
= newOverlapAvg
;
2032 } // for (int x = xMin; x < xMax; x++)
2034 } // for (int y = yMin; y < yMax; y++)
2036 // Finally, set the window's new coordinates.
2037 window
.setX(windowX
);
2038 window
.setY(windowY
);
2041 // ------------------------------------------------------------------------
2042 // TMenu management -------------------------------------------------------
2043 // ------------------------------------------------------------------------
2046 * Check if a mouse event would hit either the active menu or any open
2049 * @param mouse mouse event
2050 * @return true if the mouse would hit the active menu or an open
2053 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2054 assert (activeMenu
!= null);
2055 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
2056 Collections
.reverse(menus
);
2057 for (TMenu menu
: menus
) {
2058 if (menu
.mouseWouldHit(mouse
)) {
2062 return activeMenu
.mouseWouldHit(mouse
);
2066 * See if we need to switch window or activate the menu based on
2069 * @param mouse mouse event
2071 private void checkSwitchFocus(final TMouseEvent mouse
) {
2073 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2074 && (activeMenu
!= null)
2075 && (mouse
.getAbsoluteY() != 0)
2076 && (!mouseOnMenu(mouse
))
2078 // They clicked outside the active menu, turn it off
2079 activeMenu
.setActive(false);
2081 for (TMenu menu
: subMenus
) {
2082 menu
.setActive(false);
2088 // See if they hit the menu bar
2089 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2090 && (mouse
.isMouse1())
2091 && (!modalWindowActive())
2092 && (mouse
.getAbsoluteY() == 0)
2095 for (TMenu menu
: subMenus
) {
2096 menu
.setActive(false);
2100 // They selected the menu, go activate it
2101 for (TMenu menu
: menus
) {
2102 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2103 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2104 + menu
.getTitle().length() + 2)
2106 menu
.setActive(true);
2109 menu
.setActive(false);
2115 // See if they hit the menu bar
2116 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2117 && (mouse
.isMouse1())
2118 && (activeMenu
!= null)
2119 && (mouse
.getAbsoluteY() == 0)
2122 TMenu oldMenu
= activeMenu
;
2123 for (TMenu menu
: subMenus
) {
2124 menu
.setActive(false);
2128 // See if we should switch menus
2129 for (TMenu menu
: menus
) {
2130 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2131 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2132 + menu
.getTitle().length() + 2)
2134 menu
.setActive(true);
2138 if (oldMenu
!= activeMenu
) {
2139 // They switched menus
2140 oldMenu
.setActive(false);
2145 // If a menu is still active, don't switch windows
2146 if (activeMenu
!= null) {
2150 // Only switch if there are multiple windows
2151 if (windows
.size() < 2) {
2155 if (((focusFollowsMouse
== true)
2156 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2157 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2159 synchronized (windows
) {
2160 Collections
.sort(windows
);
2161 if (windows
.get(0).isModal()) {
2162 // Modal windows don't switch
2166 for (TWindow window
: windows
) {
2167 assert (!window
.isModal());
2169 if (window
.isHidden()) {
2170 assert (!window
.isActive());
2174 if (window
.mouseWouldHit(mouse
)) {
2175 if (window
== windows
.get(0)) {
2176 // Clicked on the same window, nothing to do
2177 assert (window
.isActive());
2181 // We will be switching to another window
2182 assert (windows
.get(0).isActive());
2183 assert (windows
.get(0) == activeWindow
);
2184 assert (!window
.isActive());
2185 activeWindow
.onUnfocus();
2186 activeWindow
.setActive(false);
2187 activeWindow
.setZ(window
.getZ());
2188 activeWindow
= window
;
2190 window
.setActive(true);
2197 // Clicked on the background, nothing to do
2201 // Nothing to do: this isn't a mouse up, or focus isn't following
2207 * Turn off the menu.
2209 public final void closeMenu() {
2210 if (activeMenu
!= null) {
2211 activeMenu
.setActive(false);
2213 for (TMenu menu
: subMenus
) {
2214 menu
.setActive(false);
2221 * Get a (shallow) copy of the menu list.
2223 * @return a copy of the menu list
2225 public final List
<TMenu
> getAllMenus() {
2226 return new LinkedList
<TMenu
>(menus
);
2230 * Add a top-level menu to the list.
2232 * @param menu the menu to add
2233 * @throws IllegalArgumentException if the menu is already used in
2234 * another TApplication
2236 public final void addMenu(final TMenu menu
) {
2237 if ((menu
.getApplication() != null)
2238 && (menu
.getApplication() != this)
2240 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2241 "part of application " + menu
.getApplication());
2249 * Remove a top-level menu from the list.
2251 * @param menu the menu to remove
2252 * @throws IllegalArgumentException if the menu is already used in
2253 * another TApplication
2255 public final void removeMenu(final TMenu menu
) {
2256 if ((menu
.getApplication() != null)
2257 && (menu
.getApplication() != this)
2259 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2260 "part of application " + menu
.getApplication());
2268 * Turn off a sub-menu.
2270 public final void closeSubMenu() {
2271 assert (activeMenu
!= null);
2272 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2273 assert (item
!= null);
2274 item
.setActive(false);
2275 subMenus
.remove(subMenus
.size() - 1);
2279 * Switch to the next menu.
2281 * @param forward if true, then switch to the next menu in the list,
2282 * otherwise switch to the previous menu in the list
2284 public final void switchMenu(final boolean forward
) {
2285 assert (activeMenu
!= null);
2287 for (TMenu menu
: subMenus
) {
2288 menu
.setActive(false);
2292 for (int i
= 0; i
< menus
.size(); i
++) {
2293 if (activeMenu
== menus
.get(i
)) {
2295 if (i
< menus
.size() - 1) {
2303 activeMenu
.setActive(false);
2304 activeMenu
= menus
.get(i
);
2305 activeMenu
.setActive(true);
2312 * Add a menu item to the global list. If it has a keyboard accelerator,
2313 * that will be added the global hash.
2315 * @param item the menu item
2317 public final void addMenuItem(final TMenuItem item
) {
2318 menuItems
.add(item
);
2320 TKeypress key
= item
.getKey();
2322 synchronized (accelerators
) {
2323 assert (accelerators
.get(key
) == null);
2324 accelerators
.put(key
.toLowerCase(), item
);
2330 * Disable one menu item.
2332 * @param id the menu item ID
2334 public final void disableMenuItem(final int id
) {
2335 for (TMenuItem item
: menuItems
) {
2336 if (item
.getId() == id
) {
2337 item
.setEnabled(false);
2343 * Disable the range of menu items with ID's between lower and upper,
2346 * @param lower the lowest menu item ID
2347 * @param upper the highest menu item ID
2349 public final void disableMenuItems(final int lower
, final int upper
) {
2350 for (TMenuItem item
: menuItems
) {
2351 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2352 item
.setEnabled(false);
2358 * Enable one menu item.
2360 * @param id the menu item ID
2362 public final void enableMenuItem(final int id
) {
2363 for (TMenuItem item
: menuItems
) {
2364 if (item
.getId() == id
) {
2365 item
.setEnabled(true);
2371 * Enable the range of menu items with ID's between lower and upper,
2374 * @param lower the lowest menu item ID
2375 * @param upper the highest menu item ID
2377 public final void enableMenuItems(final int lower
, final int upper
) {
2378 for (TMenuItem item
: menuItems
) {
2379 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2380 item
.setEnabled(true);
2386 * Recompute menu x positions based on their title length.
2388 public final void recomputeMenuX() {
2390 for (TMenu menu
: menus
) {
2393 x
+= menu
.getTitle().length() + 2;
2395 // Don't let the menu window exceed the screen width
2396 int rightEdge
= menu
.getX() + menu
.getWidth();
2397 if (rightEdge
> getScreen().getWidth()) {
2398 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2404 * Post an event to process.
2406 * @param event new event to add to the queue
2408 public final void postEvent(final TInputEvent event
) {
2409 synchronized (this) {
2410 synchronized (fillEventQueue
) {
2411 fillEventQueue
.add(event
);
2414 System
.err
.println(System
.currentTimeMillis() + " " +
2415 Thread
.currentThread() + " postEvent() wake up main");
2422 * Post an event to process and turn off the menu.
2424 * @param event new event to add to the queue
2426 public final void postMenuEvent(final TInputEvent event
) {
2427 synchronized (this) {
2428 synchronized (fillEventQueue
) {
2429 fillEventQueue
.add(event
);
2432 System
.err
.println(System
.currentTimeMillis() + " " +
2433 Thread
.currentThread() + " postMenuEvent() wake up main");
2441 * Add a sub-menu to the list of open sub-menus.
2443 * @param menu sub-menu
2445 public final void addSubMenu(final TMenu menu
) {
2450 * Convenience function to add a top-level menu.
2452 * @param title menu title
2453 * @return the new menu
2455 public final TMenu
addMenu(final String title
) {
2458 TMenu menu
= new TMenu(this, x
, y
, title
);
2465 * Convenience function to add a default "File" menu.
2467 * @return the new menu
2469 public final TMenu
addFileMenu() {
2470 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
2471 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2472 fileMenu
.addSeparator();
2473 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2474 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2475 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
2476 getString("fileMenuStatus"));
2477 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2482 * Convenience function to add a default "Edit" menu.
2484 * @return the new menu
2486 public final TMenu
addEditMenu() {
2487 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
2488 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2489 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2490 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2491 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2492 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
2493 getString("editMenuStatus"));
2494 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2499 * Convenience function to add a default "Window" menu.
2501 * @return the new menu
2503 public final TMenu
addWindowMenu() {
2504 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
2505 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2506 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2507 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2508 windowMenu
.addSeparator();
2509 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2510 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2511 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2512 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2513 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2514 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
2515 getString("windowMenuStatus"));
2516 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2521 * Convenience function to add a default "Help" menu.
2523 * @return the new menu
2525 public final TMenu
addHelpMenu() {
2526 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
2527 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2528 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2529 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2530 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2531 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2532 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2533 helpMenu
.addSeparator();
2534 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2535 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
2536 getString("helpMenuStatus"));
2537 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2541 // ------------------------------------------------------------------------
2542 // Event handlers ---------------------------------------------------------
2543 // ------------------------------------------------------------------------
2546 * Method that TApplication subclasses can override to handle menu or
2547 * posted command events.
2549 * @param command command event
2550 * @return if true, this event was consumed
2552 protected boolean onCommand(final TCommandEvent command
) {
2553 // Default: handle cmExit
2554 if (command
.equals(cmExit
)) {
2555 if (messageBox(i18n
.getString("exitDialogTitle"),
2556 i18n
.getString("exitDialogText"),
2557 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2563 if (command
.equals(cmShell
)) {
2564 openTerminal(0, 0, TWindow
.RESIZABLE
);
2568 if (command
.equals(cmTile
)) {
2572 if (command
.equals(cmCascade
)) {
2576 if (command
.equals(cmCloseAll
)) {
2581 if (command
.equals(cmMenu
)) {
2582 if (!modalWindowActive() && (activeMenu
== null)) {
2583 if (menus
.size() > 0) {
2584 menus
.get(0).setActive(true);
2585 activeMenu
= menus
.get(0);
2595 * Method that TApplication subclasses can override to handle menu
2598 * @param menu menu event
2599 * @return if true, this event was consumed
2601 protected boolean onMenu(final TMenuEvent menu
) {
2603 // Default: handle MID_EXIT
2604 if (menu
.getId() == TMenu
.MID_EXIT
) {
2605 if (messageBox(i18n
.getString("exitDialogTitle"),
2606 i18n
.getString("exitDialogText"),
2607 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2613 if (menu
.getId() == TMenu
.MID_SHELL
) {
2614 openTerminal(0, 0, TWindow
.RESIZABLE
);
2618 if (menu
.getId() == TMenu
.MID_TILE
) {
2622 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2626 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2630 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2634 if (menu
.getId() == TMenu
.MID_REPAINT
) {
2642 * Method that TApplication subclasses can override to handle keystrokes.
2644 * @param keypress keystroke event
2645 * @return if true, this event was consumed
2647 protected boolean onKeypress(final TKeypressEvent keypress
) {
2648 // Default: only menu shortcuts
2650 // Process Alt-F, Alt-E, etc. menu shortcut keys
2651 if (!keypress
.getKey().isFnKey()
2652 && keypress
.getKey().isAlt()
2653 && !keypress
.getKey().isCtrl()
2654 && (activeMenu
== null)
2655 && !modalWindowActive()
2658 assert (subMenus
.size() == 0);
2660 for (TMenu menu
: menus
) {
2661 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2662 == Character
.toLowerCase(keypress
.getKey().getChar())
2665 menu
.setActive(true);
2674 // ------------------------------------------------------------------------
2675 // TTimer management ------------------------------------------------------
2676 // ------------------------------------------------------------------------
2679 * Get the amount of time I can sleep before missing a Timer tick.
2681 * @param timeout = initial (maximum) timeout in millis
2682 * @return number of milliseconds between now and the next timer event
2684 private long getSleepTime(final long timeout
) {
2685 Date now
= new Date();
2686 long nowTime
= now
.getTime();
2687 long sleepTime
= timeout
;
2689 synchronized (timers
) {
2690 for (TTimer timer
: timers
) {
2691 long nextTickTime
= timer
.getNextTick().getTime();
2692 if (nextTickTime
< nowTime
) {
2696 long timeDifference
= nextTickTime
- nowTime
;
2697 if (timeDifference
< sleepTime
) {
2698 sleepTime
= timeDifference
;
2703 assert (sleepTime
>= 0);
2704 assert (sleepTime
<= timeout
);
2709 * Convenience function to add a timer.
2711 * @param duration number of milliseconds to wait between ticks
2712 * @param recurring if true, re-schedule this timer after every tick
2713 * @param action function to call when button is pressed
2716 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2717 final TAction action
) {
2719 TTimer timer
= new TTimer(duration
, recurring
, action
);
2720 synchronized (timers
) {
2727 * Convenience function to remove a timer.
2729 * @param timer timer to remove
2731 public final void removeTimer(final TTimer timer
) {
2732 synchronized (timers
) {
2733 timers
.remove(timer
);
2737 // ------------------------------------------------------------------------
2738 // Other TWindow constructors ---------------------------------------------
2739 // ------------------------------------------------------------------------
2742 * Convenience function to spawn a message box.
2744 * @param title window title, will be centered along the top border
2745 * @param caption message to display. Use embedded newlines to get a
2747 * @return the new message box
2749 public final TMessageBox
messageBox(final String title
,
2750 final String caption
) {
2752 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2756 * Convenience function to spawn a message box.
2758 * @param title window title, will be centered along the top border
2759 * @param caption message to display. Use embedded newlines to get a
2761 * @param type one of the TMessageBox.Type constants. Default is
2763 * @return the new message box
2765 public final TMessageBox
messageBox(final String title
,
2766 final String caption
, final TMessageBox
.Type type
) {
2768 return new TMessageBox(this, title
, caption
, type
);
2772 * Convenience function to spawn an input box.
2774 * @param title window title, will be centered along the top border
2775 * @param caption message to display. Use embedded newlines to get a
2777 * @return the new input box
2779 public final TInputBox
inputBox(final String title
, final String caption
) {
2781 return new TInputBox(this, title
, caption
);
2785 * Convenience function to spawn an input box.
2787 * @param title window title, will be centered along the top border
2788 * @param caption message to display. Use embedded newlines to get a
2790 * @param text initial text to seed the field with
2791 * @return the new input box
2793 public final TInputBox
inputBox(final String title
, final String caption
,
2794 final String text
) {
2796 return new TInputBox(this, title
, caption
, text
);
2800 * Convenience function to open a terminal window.
2802 * @param x column relative to parent
2803 * @param y row relative to parent
2804 * @return the terminal new window
2806 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2807 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2811 * Convenience function to open a terminal window.
2813 * @param x column relative to parent
2814 * @param y row relative to parent
2815 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2816 * @return the terminal new window
2818 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2821 return new TTerminalWindow(this, x
, y
, flags
);
2825 * Convenience function to open a terminal window and execute a custom
2826 * command line inside it.
2828 * @param x column relative to parent
2829 * @param y row relative to parent
2830 * @param commandLine the command line to execute
2831 * @return the terminal new window
2833 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2834 final String commandLine
) {
2836 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
2840 * Convenience function to open a terminal window and execute a custom
2841 * command line inside it.
2843 * @param x column relative to parent
2844 * @param y row relative to parent
2845 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2846 * @param commandLine the command line to execute
2847 * @return the terminal new window
2849 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2850 final int flags
, final String commandLine
) {
2852 return new TTerminalWindow(this, x
, y
, flags
, commandLine
);
2856 * Convenience function to spawn an file open box.
2858 * @param path path of selected file
2859 * @return the result of the new file open box
2860 * @throws IOException if java.io operation throws
2862 public final String
fileOpenBox(final String path
) throws IOException
{
2864 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2865 return box
.getFilename();
2869 * Convenience function to spawn an file open box.
2871 * @param path path of selected file
2872 * @param type one of the Type constants
2873 * @return the result of the new file open box
2874 * @throws IOException if java.io operation throws
2876 public final String
fileOpenBox(final String path
,
2877 final TFileOpenBox
.Type type
) throws IOException
{
2879 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2880 return box
.getFilename();
2884 * Convenience function to create a new window and make it active.
2885 * Window will be located at (0, 0).
2887 * @param title window title, will be centered along the top border
2888 * @param width width of window
2889 * @param height height of window
2891 public final TWindow
addWindow(final String title
, final int width
,
2894 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2899 * Convenience function to create a new window and make it active.
2900 * Window will be located at (0, 0).
2902 * @param title window title, will be centered along the top border
2903 * @param width width of window
2904 * @param height height of window
2905 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2907 public final TWindow
addWindow(final String title
,
2908 final int width
, final int height
, final int flags
) {
2910 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2915 * Convenience function to create a new window and make it active.
2917 * @param title window title, will be centered along the top border
2918 * @param x column relative to parent
2919 * @param y row relative to parent
2920 * @param width width of window
2921 * @param height height of window
2923 public final TWindow
addWindow(final String title
,
2924 final int x
, final int y
, final int width
, final int height
) {
2926 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2931 * Convenience function to create a new window and make it active.
2933 * @param title window title, will be centered along the top border
2934 * @param x column relative to parent
2935 * @param y row relative to parent
2936 * @param width width of window
2937 * @param height height of window
2938 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2940 public final TWindow
addWindow(final String title
,
2941 final int x
, final int y
, final int width
, final int height
,
2944 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);
2949 * Convenience function to open a file in an editor window and make it
2952 * @param file the file to open
2953 * @throws IOException if a java.io operation throws
2955 public final TEditorWindow
addEditor(final File file
) throws IOException
{
2957 TEditorWindow editor
= new TEditorWindow(this, file
);