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 // Do not activate a hidden window.
1633 w
.setZ(w
.getZ() - 1);
1634 if (w
.getZ() == 0) {
1637 assert (activeWindow
== null);
1649 // Perform window cleanup
1652 // Check if we are closing a TMessageBox or similar
1653 if (secondaryEventReceiver
!= null) {
1654 assert (secondaryEventHandler
!= null);
1656 // Do not send events to the secondaryEventReceiver anymore, the
1657 // window is closed.
1658 secondaryEventReceiver
= null;
1660 // Wake the secondary thread, it will wake the primary as it
1662 synchronized (secondaryEventHandler
) {
1663 secondaryEventHandler
.notify();
1667 // Permit desktop to be active if it is the only thing left.
1668 if (desktop
!= null) {
1669 if (windows
.size() == 0) {
1670 desktop
.setActive(true);
1676 * Switch to the next window.
1678 * @param forward if true, then switch to the next window in the list,
1679 * otherwise switch to the previous window in the list
1681 public final void switchWindow(final boolean forward
) {
1682 // Only switch if there are multiple visible windows
1683 if (shownWindowCount() < 2) {
1686 assert (activeWindow
!= null);
1688 synchronized (windows
) {
1689 // Whatever window might be moving/dragging, stop it now.
1690 for (TWindow w
: windows
) {
1691 if (w
.inMovements()) {
1696 // Swap z/active between active window and the next in the list
1697 int activeWindowI
= -1;
1698 for (int i
= 0; i
< windows
.size(); i
++) {
1699 if (windows
.get(i
) == activeWindow
) {
1700 assert (activeWindow
.isActive());
1704 assert (!windows
.get(0).isActive());
1707 assert (activeWindowI
>= 0);
1709 // Do not switch if a window is modal
1710 if (activeWindow
.isModal()) {
1714 int nextWindowI
= activeWindowI
;
1718 nextWindowI
%= windows
.size();
1721 if (nextWindowI
< 0) {
1722 nextWindowI
= windows
.size() - 1;
1726 if (windows
.get(nextWindowI
).isShown()) {
1727 activateWindow(windows
.get(nextWindowI
));
1731 } // synchronized (windows)
1736 * Add a window to my window list and make it active.
1738 * @param window new window to add
1740 public final void addWindow(final TWindow window
) {
1742 // Do not add menu windows to the window list.
1743 if (window
instanceof TMenu
) {
1747 // Do not add the desktop to the window list.
1748 if (window
instanceof TDesktop
) {
1752 synchronized (windows
) {
1753 // Whatever window might be moving/dragging, stop it now.
1754 for (TWindow w
: windows
) {
1755 if (w
.inMovements()) {
1760 // Do not allow a modal window to spawn a non-modal window. If a
1761 // modal window is active, then this window will become modal
1763 if (modalWindowActive()) {
1764 window
.flags
|= TWindow
.MODAL
;
1765 window
.flags
|= TWindow
.CENTERED
;
1766 window
.hidden
= false;
1768 if (window
.isShown()) {
1769 for (TWindow w
: windows
) {
1774 w
.setZ(w
.getZ() + 1);
1777 windows
.add(window
);
1778 if (window
.isShown()) {
1779 activeWindow
= window
;
1780 activeWindow
.setZ(0);
1781 activeWindow
.setActive(true);
1782 activeWindow
.onFocus();
1785 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1786 && smartWindowPlacement
) {
1788 doSmartPlacement(window
);
1792 // Desktop cannot be active over any other window.
1793 if (desktop
!= null) {
1794 desktop
.setActive(false);
1799 * Check if there is a system-modal window on top.
1801 * @return true if the active window is modal
1803 private boolean modalWindowActive() {
1804 if (windows
.size() == 0) {
1808 for (TWindow w
: windows
) {
1818 * Close all open windows.
1820 private void closeAllWindows() {
1821 // Don't do anything if we are in the menu
1822 if (activeMenu
!= null) {
1825 while (windows
.size() > 0) {
1826 closeWindow(windows
.get(0));
1831 * Re-layout the open windows as non-overlapping tiles. This produces
1832 * almost the same results as Turbo Pascal 7.0's IDE.
1834 private void tileWindows() {
1835 synchronized (windows
) {
1836 // Don't do anything if we are in the menu
1837 if (activeMenu
!= null) {
1840 int z
= windows
.size();
1846 a
= (int)(Math
.sqrt(z
));
1850 if (((a
* b
) + c
) == z
) {
1858 int newWidth
= (getScreen().getWidth() / a
);
1859 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1860 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1862 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1863 Collections
.sort(sorted
);
1864 Collections
.reverse(sorted
);
1865 for (int i
= 0; i
< sorted
.size(); i
++) {
1866 int logicalX
= i
/ b
;
1867 int logicalY
= i
% b
;
1868 if (i
>= ((a
- 1) * b
)) {
1870 logicalY
= i
- ((a
- 1) * b
);
1873 TWindow w
= sorted
.get(i
);
1874 w
.setX(logicalX
* newWidth
);
1875 w
.setWidth(newWidth
);
1876 if (i
>= ((a
- 1) * b
)) {
1877 w
.setY((logicalY
* newHeight2
) + 1);
1878 w
.setHeight(newHeight2
);
1880 w
.setY((logicalY
* newHeight1
) + 1);
1881 w
.setHeight(newHeight1
);
1888 * Re-layout the open windows as overlapping cascaded windows.
1890 private void cascadeWindows() {
1891 synchronized (windows
) {
1892 // Don't do anything if we are in the menu
1893 if (activeMenu
!= null) {
1898 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1899 Collections
.sort(sorted
);
1900 Collections
.reverse(sorted
);
1901 for (TWindow window
: sorted
) {
1906 if (x
> getScreen().getWidth()) {
1909 if (y
>= getScreen().getHeight()) {
1917 * Place a window to minimize its overlap with other windows.
1919 * @param window the window to place
1921 public final void doSmartPlacement(final TWindow window
) {
1922 // This is a pretty dumb algorithm, but seems to work. The hardest
1923 // part is computing these "overlap" values seeking a minimum average
1926 int yMin
= desktopTop
;
1927 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1928 int yMax
= desktopBottom
- window
.getHeight() + 1;
1936 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1937 // No work to do, bail out.
1941 // Compute the overlap matrix without the new window.
1942 int width
= getScreen().getWidth();
1943 int height
= getScreen().getHeight();
1944 int overlapMatrix
[][] = new int[width
][height
];
1945 for (TWindow w
: windows
) {
1949 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1956 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1963 overlapMatrix
[x
][y
]++;
1968 long oldOverlapTotal
= 0;
1969 long oldOverlapN
= 0;
1970 for (int x
= 0; x
< width
; x
++) {
1971 for (int y
= 0; y
< height
; y
++) {
1972 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1973 if (overlapMatrix
[x
][y
] > 0) {
1980 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1981 boolean first
= true;
1982 int windowX
= window
.getX();
1983 int windowY
= window
.getY();
1985 // For each possible (x, y) position for the new window, compute a
1986 // new overlap matrix.
1987 for (int x
= xMin
; x
< xMax
; x
++) {
1988 for (int y
= yMin
; y
< yMax
; y
++) {
1990 // Start with the matrix minus this window.
1991 int newMatrix
[][] = new int[width
][height
];
1992 for (int mx
= 0; mx
< width
; mx
++) {
1993 for (int my
= 0; my
< height
; my
++) {
1994 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1998 // Add this window's values to the new overlap matrix.
1999 long newOverlapTotal
= 0;
2000 long newOverlapN
= 0;
2001 // Start by adding each new cell.
2002 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2006 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2010 newMatrix
[wx
][wy
]++;
2013 // Now figure out the new value for total coverage.
2014 for (int mx
= 0; mx
< width
; mx
++) {
2015 for (int my
= 0; my
< height
; my
++) {
2016 newOverlapTotal
+= newMatrix
[x
][y
];
2017 if (newMatrix
[mx
][my
] > 0) {
2022 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2025 // First time: just record what we got.
2026 oldOverlapAvg
= newOverlapAvg
;
2029 // All other times: pick a new best (x, y) and save the
2031 if (newOverlapAvg
< oldOverlapAvg
) {
2034 oldOverlapAvg
= newOverlapAvg
;
2038 } // for (int x = xMin; x < xMax; x++)
2040 } // for (int y = yMin; y < yMax; y++)
2042 // Finally, set the window's new coordinates.
2043 window
.setX(windowX
);
2044 window
.setY(windowY
);
2047 // ------------------------------------------------------------------------
2048 // TMenu management -------------------------------------------------------
2049 // ------------------------------------------------------------------------
2052 * Check if a mouse event would hit either the active menu or any open
2055 * @param mouse mouse event
2056 * @return true if the mouse would hit the active menu or an open
2059 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2060 assert (activeMenu
!= null);
2061 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
2062 Collections
.reverse(menus
);
2063 for (TMenu menu
: menus
) {
2064 if (menu
.mouseWouldHit(mouse
)) {
2068 return activeMenu
.mouseWouldHit(mouse
);
2072 * See if we need to switch window or activate the menu based on
2075 * @param mouse mouse event
2077 private void checkSwitchFocus(final TMouseEvent mouse
) {
2079 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2080 && (activeMenu
!= null)
2081 && (mouse
.getAbsoluteY() != 0)
2082 && (!mouseOnMenu(mouse
))
2084 // They clicked outside the active menu, turn it off
2085 activeMenu
.setActive(false);
2087 for (TMenu menu
: subMenus
) {
2088 menu
.setActive(false);
2094 // See if they hit the menu bar
2095 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2096 && (mouse
.isMouse1())
2097 && (!modalWindowActive())
2098 && (mouse
.getAbsoluteY() == 0)
2101 for (TMenu menu
: subMenus
) {
2102 menu
.setActive(false);
2106 // They selected the menu, go activate it
2107 for (TMenu menu
: menus
) {
2108 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2109 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2110 + menu
.getTitle().length() + 2)
2112 menu
.setActive(true);
2115 menu
.setActive(false);
2121 // See if they hit the menu bar
2122 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2123 && (mouse
.isMouse1())
2124 && (activeMenu
!= null)
2125 && (mouse
.getAbsoluteY() == 0)
2128 TMenu oldMenu
= activeMenu
;
2129 for (TMenu menu
: subMenus
) {
2130 menu
.setActive(false);
2134 // See if we should switch menus
2135 for (TMenu menu
: menus
) {
2136 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2137 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2138 + menu
.getTitle().length() + 2)
2140 menu
.setActive(true);
2144 if (oldMenu
!= activeMenu
) {
2145 // They switched menus
2146 oldMenu
.setActive(false);
2151 // If a menu is still active, don't switch windows
2152 if (activeMenu
!= null) {
2156 // Only switch if there are multiple windows
2157 if (windows
.size() < 2) {
2161 if (((focusFollowsMouse
== true)
2162 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2163 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2165 synchronized (windows
) {
2166 Collections
.sort(windows
);
2167 if (windows
.get(0).isModal()) {
2168 // Modal windows don't switch
2172 for (TWindow window
: windows
) {
2173 assert (!window
.isModal());
2175 if (window
.isHidden()) {
2176 assert (!window
.isActive());
2180 if (window
.mouseWouldHit(mouse
)) {
2181 if (window
== windows
.get(0)) {
2182 // Clicked on the same window, nothing to do
2183 assert (window
.isActive());
2187 // We will be switching to another window
2188 assert (windows
.get(0).isActive());
2189 assert (windows
.get(0) == activeWindow
);
2190 assert (!window
.isActive());
2191 activeWindow
.onUnfocus();
2192 activeWindow
.setActive(false);
2193 activeWindow
.setZ(window
.getZ());
2194 activeWindow
= window
;
2196 window
.setActive(true);
2203 // Clicked on the background, nothing to do
2207 // Nothing to do: this isn't a mouse up, or focus isn't following
2213 * Turn off the menu.
2215 public final void closeMenu() {
2216 if (activeMenu
!= null) {
2217 activeMenu
.setActive(false);
2219 for (TMenu menu
: subMenus
) {
2220 menu
.setActive(false);
2227 * Get a (shallow) copy of the menu list.
2229 * @return a copy of the menu list
2231 public final List
<TMenu
> getAllMenus() {
2232 return new LinkedList
<TMenu
>(menus
);
2236 * Add a top-level menu to the list.
2238 * @param menu the menu to add
2239 * @throws IllegalArgumentException if the menu is already used in
2240 * another TApplication
2242 public final void addMenu(final TMenu menu
) {
2243 if ((menu
.getApplication() != null)
2244 && (menu
.getApplication() != this)
2246 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2247 "part of application " + menu
.getApplication());
2255 * Remove a top-level menu from the list.
2257 * @param menu the menu to remove
2258 * @throws IllegalArgumentException if the menu is already used in
2259 * another TApplication
2261 public final void removeMenu(final TMenu menu
) {
2262 if ((menu
.getApplication() != null)
2263 && (menu
.getApplication() != this)
2265 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2266 "part of application " + menu
.getApplication());
2274 * Turn off a sub-menu.
2276 public final void closeSubMenu() {
2277 assert (activeMenu
!= null);
2278 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2279 assert (item
!= null);
2280 item
.setActive(false);
2281 subMenus
.remove(subMenus
.size() - 1);
2285 * Switch to the next menu.
2287 * @param forward if true, then switch to the next menu in the list,
2288 * otherwise switch to the previous menu in the list
2290 public final void switchMenu(final boolean forward
) {
2291 assert (activeMenu
!= null);
2293 for (TMenu menu
: subMenus
) {
2294 menu
.setActive(false);
2298 for (int i
= 0; i
< menus
.size(); i
++) {
2299 if (activeMenu
== menus
.get(i
)) {
2301 if (i
< menus
.size() - 1) {
2309 activeMenu
.setActive(false);
2310 activeMenu
= menus
.get(i
);
2311 activeMenu
.setActive(true);
2318 * Add a menu item to the global list. If it has a keyboard accelerator,
2319 * that will be added the global hash.
2321 * @param item the menu item
2323 public final void addMenuItem(final TMenuItem item
) {
2324 menuItems
.add(item
);
2326 TKeypress key
= item
.getKey();
2328 synchronized (accelerators
) {
2329 assert (accelerators
.get(key
) == null);
2330 accelerators
.put(key
.toLowerCase(), item
);
2336 * Disable one menu item.
2338 * @param id the menu item ID
2340 public final void disableMenuItem(final int id
) {
2341 for (TMenuItem item
: menuItems
) {
2342 if (item
.getId() == id
) {
2343 item
.setEnabled(false);
2349 * Disable the range of menu items with ID's between lower and upper,
2352 * @param lower the lowest menu item ID
2353 * @param upper the highest menu item ID
2355 public final void disableMenuItems(final int lower
, final int upper
) {
2356 for (TMenuItem item
: menuItems
) {
2357 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2358 item
.setEnabled(false);
2364 * Enable one menu item.
2366 * @param id the menu item ID
2368 public final void enableMenuItem(final int id
) {
2369 for (TMenuItem item
: menuItems
) {
2370 if (item
.getId() == id
) {
2371 item
.setEnabled(true);
2377 * Enable the range of menu items with ID's between lower and upper,
2380 * @param lower the lowest menu item ID
2381 * @param upper the highest menu item ID
2383 public final void enableMenuItems(final int lower
, final int upper
) {
2384 for (TMenuItem item
: menuItems
) {
2385 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2386 item
.setEnabled(true);
2392 * Recompute menu x positions based on their title length.
2394 public final void recomputeMenuX() {
2396 for (TMenu menu
: menus
) {
2399 x
+= menu
.getTitle().length() + 2;
2401 // Don't let the menu window exceed the screen width
2402 int rightEdge
= menu
.getX() + menu
.getWidth();
2403 if (rightEdge
> getScreen().getWidth()) {
2404 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2410 * Post an event to process.
2412 * @param event new event to add to the queue
2414 public final void postEvent(final TInputEvent event
) {
2415 synchronized (this) {
2416 synchronized (fillEventQueue
) {
2417 fillEventQueue
.add(event
);
2420 System
.err
.println(System
.currentTimeMillis() + " " +
2421 Thread
.currentThread() + " postEvent() wake up main");
2428 * Post an event to process and turn off the menu.
2430 * @param event new event to add to the queue
2432 public final void postMenuEvent(final TInputEvent event
) {
2433 synchronized (this) {
2434 synchronized (fillEventQueue
) {
2435 fillEventQueue
.add(event
);
2438 System
.err
.println(System
.currentTimeMillis() + " " +
2439 Thread
.currentThread() + " postMenuEvent() wake up main");
2447 * Add a sub-menu to the list of open sub-menus.
2449 * @param menu sub-menu
2451 public final void addSubMenu(final TMenu menu
) {
2456 * Convenience function to add a top-level menu.
2458 * @param title menu title
2459 * @return the new menu
2461 public final TMenu
addMenu(final String title
) {
2464 TMenu menu
= new TMenu(this, x
, y
, title
);
2471 * Convenience function to add a default "File" menu.
2473 * @return the new menu
2475 public final TMenu
addFileMenu() {
2476 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
2477 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2478 fileMenu
.addSeparator();
2479 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2480 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2481 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
2482 getString("fileMenuStatus"));
2483 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2488 * Convenience function to add a default "Edit" menu.
2490 * @return the new menu
2492 public final TMenu
addEditMenu() {
2493 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
2494 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2495 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2496 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2497 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2498 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
2499 getString("editMenuStatus"));
2500 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2505 * Convenience function to add a default "Window" menu.
2507 * @return the new menu
2509 public final TMenu
addWindowMenu() {
2510 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
2511 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2512 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2513 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2514 windowMenu
.addSeparator();
2515 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2516 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2517 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2518 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2519 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2520 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
2521 getString("windowMenuStatus"));
2522 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2527 * Convenience function to add a default "Help" menu.
2529 * @return the new menu
2531 public final TMenu
addHelpMenu() {
2532 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
2533 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2534 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2535 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2536 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2537 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2538 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2539 helpMenu
.addSeparator();
2540 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2541 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
2542 getString("helpMenuStatus"));
2543 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2547 // ------------------------------------------------------------------------
2548 // Event handlers ---------------------------------------------------------
2549 // ------------------------------------------------------------------------
2552 * Method that TApplication subclasses can override to handle menu or
2553 * posted command events.
2555 * @param command command event
2556 * @return if true, this event was consumed
2558 protected boolean onCommand(final TCommandEvent command
) {
2559 // Default: handle cmExit
2560 if (command
.equals(cmExit
)) {
2561 if (messageBox(i18n
.getString("exitDialogTitle"),
2562 i18n
.getString("exitDialogText"),
2563 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2569 if (command
.equals(cmShell
)) {
2570 openTerminal(0, 0, TWindow
.RESIZABLE
);
2574 if (command
.equals(cmTile
)) {
2578 if (command
.equals(cmCascade
)) {
2582 if (command
.equals(cmCloseAll
)) {
2587 if (command
.equals(cmMenu
)) {
2588 if (!modalWindowActive() && (activeMenu
== null)) {
2589 if (menus
.size() > 0) {
2590 menus
.get(0).setActive(true);
2591 activeMenu
= menus
.get(0);
2601 * Method that TApplication subclasses can override to handle menu
2604 * @param menu menu event
2605 * @return if true, this event was consumed
2607 protected boolean onMenu(final TMenuEvent menu
) {
2609 // Default: handle MID_EXIT
2610 if (menu
.getId() == TMenu
.MID_EXIT
) {
2611 if (messageBox(i18n
.getString("exitDialogTitle"),
2612 i18n
.getString("exitDialogText"),
2613 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2619 if (menu
.getId() == TMenu
.MID_SHELL
) {
2620 openTerminal(0, 0, TWindow
.RESIZABLE
);
2624 if (menu
.getId() == TMenu
.MID_TILE
) {
2628 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2632 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2636 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2640 if (menu
.getId() == TMenu
.MID_REPAINT
) {
2648 * Method that TApplication subclasses can override to handle keystrokes.
2650 * @param keypress keystroke event
2651 * @return if true, this event was consumed
2653 protected boolean onKeypress(final TKeypressEvent keypress
) {
2654 // Default: only menu shortcuts
2656 // Process Alt-F, Alt-E, etc. menu shortcut keys
2657 if (!keypress
.getKey().isFnKey()
2658 && keypress
.getKey().isAlt()
2659 && !keypress
.getKey().isCtrl()
2660 && (activeMenu
== null)
2661 && !modalWindowActive()
2664 assert (subMenus
.size() == 0);
2666 for (TMenu menu
: menus
) {
2667 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2668 == Character
.toLowerCase(keypress
.getKey().getChar())
2671 menu
.setActive(true);
2680 // ------------------------------------------------------------------------
2681 // TTimer management ------------------------------------------------------
2682 // ------------------------------------------------------------------------
2685 * Get the amount of time I can sleep before missing a Timer tick.
2687 * @param timeout = initial (maximum) timeout in millis
2688 * @return number of milliseconds between now and the next timer event
2690 private long getSleepTime(final long timeout
) {
2691 Date now
= new Date();
2692 long nowTime
= now
.getTime();
2693 long sleepTime
= timeout
;
2695 synchronized (timers
) {
2696 for (TTimer timer
: timers
) {
2697 long nextTickTime
= timer
.getNextTick().getTime();
2698 if (nextTickTime
< nowTime
) {
2702 long timeDifference
= nextTickTime
- nowTime
;
2703 if (timeDifference
< sleepTime
) {
2704 sleepTime
= timeDifference
;
2709 assert (sleepTime
>= 0);
2710 assert (sleepTime
<= timeout
);
2715 * Convenience function to add a timer.
2717 * @param duration number of milliseconds to wait between ticks
2718 * @param recurring if true, re-schedule this timer after every tick
2719 * @param action function to call when button is pressed
2722 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2723 final TAction action
) {
2725 TTimer timer
= new TTimer(duration
, recurring
, action
);
2726 synchronized (timers
) {
2733 * Convenience function to remove a timer.
2735 * @param timer timer to remove
2737 public final void removeTimer(final TTimer timer
) {
2738 synchronized (timers
) {
2739 timers
.remove(timer
);
2743 // ------------------------------------------------------------------------
2744 // Other TWindow constructors ---------------------------------------------
2745 // ------------------------------------------------------------------------
2748 * Convenience function to spawn a message box.
2750 * @param title window title, will be centered along the top border
2751 * @param caption message to display. Use embedded newlines to get a
2753 * @return the new message box
2755 public final TMessageBox
messageBox(final String title
,
2756 final String caption
) {
2758 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2762 * Convenience function to spawn a message box.
2764 * @param title window title, will be centered along the top border
2765 * @param caption message to display. Use embedded newlines to get a
2767 * @param type one of the TMessageBox.Type constants. Default is
2769 * @return the new message box
2771 public final TMessageBox
messageBox(final String title
,
2772 final String caption
, final TMessageBox
.Type type
) {
2774 return new TMessageBox(this, title
, caption
, type
);
2778 * Convenience function to spawn an input box.
2780 * @param title window title, will be centered along the top border
2781 * @param caption message to display. Use embedded newlines to get a
2783 * @return the new input box
2785 public final TInputBox
inputBox(final String title
, final String caption
) {
2787 return new TInputBox(this, title
, caption
);
2791 * Convenience function to spawn an input box.
2793 * @param title window title, will be centered along the top border
2794 * @param caption message to display. Use embedded newlines to get a
2796 * @param text initial text to seed the field with
2797 * @return the new input box
2799 public final TInputBox
inputBox(final String title
, final String caption
,
2800 final String text
) {
2802 return new TInputBox(this, title
, caption
, text
);
2806 * Convenience function to open a terminal window.
2808 * @param x column relative to parent
2809 * @param y row relative to parent
2810 * @return the terminal new window
2812 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2813 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2817 * Convenience function to open a terminal window.
2819 * @param x column relative to parent
2820 * @param y row relative to parent
2821 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2822 * @return the terminal new window
2824 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2827 return new TTerminalWindow(this, x
, y
, flags
);
2831 * Convenience function to open a terminal window and execute a custom
2832 * command line inside it.
2834 * @param x column relative to parent
2835 * @param y row relative to parent
2836 * @param commandLine the command line to execute
2837 * @return the terminal new window
2839 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2840 final String commandLine
) {
2842 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
2846 * Convenience function to open a terminal window and execute a custom
2847 * command line inside it.
2849 * @param x column relative to parent
2850 * @param y row relative to parent
2851 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2852 * @param command the command line to execute
2853 * @return the terminal new window
2855 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2856 final int flags
, final String
[] command
) {
2858 return new TTerminalWindow(this, x
, y
, flags
, command
);
2862 * Convenience function to open a terminal window and execute a custom
2863 * command line inside it.
2865 * @param x column relative to parent
2866 * @param y row relative to parent
2867 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2868 * @param commandLine the command line to execute
2869 * @return the terminal new window
2871 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2872 final int flags
, final String commandLine
) {
2874 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s"));
2878 * Convenience function to spawn an file open box.
2880 * @param path path of selected file
2881 * @return the result of the new file open box
2882 * @throws IOException if java.io operation throws
2884 public final String
fileOpenBox(final String path
) throws IOException
{
2886 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2887 return box
.getFilename();
2891 * Convenience function to spawn an file open box.
2893 * @param path path of selected file
2894 * @param type one of the Type constants
2895 * @return the result of the new file open box
2896 * @throws IOException if java.io operation throws
2898 public final String
fileOpenBox(final String path
,
2899 final TFileOpenBox
.Type type
) throws IOException
{
2901 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2902 return box
.getFilename();
2906 * Convenience function to create a new window and make it active.
2907 * Window will be located at (0, 0).
2909 * @param title window title, will be centered along the top border
2910 * @param width width of window
2911 * @param height height of window
2913 public final TWindow
addWindow(final String title
, final int width
,
2916 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2921 * Convenience function to create a new window and make it active.
2922 * Window will be located at (0, 0).
2924 * @param title window title, will be centered along the top border
2925 * @param width width of window
2926 * @param height height of window
2927 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2929 public final TWindow
addWindow(final String title
,
2930 final int width
, final int height
, final int flags
) {
2932 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2937 * Convenience function to create a new window and make it active.
2939 * @param title window title, will be centered along the top border
2940 * @param x column relative to parent
2941 * @param y row relative to parent
2942 * @param width width of window
2943 * @param height height of window
2945 public final TWindow
addWindow(final String title
,
2946 final int x
, final int y
, final int width
, final int height
) {
2948 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2953 * Convenience function to create a new window and make it active.
2955 * @param title window title, will be centered along the top border
2956 * @param x column relative to parent
2957 * @param y row relative to parent
2958 * @param width width of window
2959 * @param height height of window
2960 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2962 public final TWindow
addWindow(final String title
,
2963 final int x
, final int y
, final int width
, final int height
,
2966 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);
2971 * Convenience function to open a file in an editor window and make it
2974 * @param file the file to open
2975 * @throws IOException if a java.io operation throws
2977 public final TEditorWindow
addEditor(final File file
) throws IOException
{
2979 TEditorWindow editor
= new TEditorWindow(this, file
);