2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2017 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
31 import java
.io
.InputStream
;
32 import java
.io
.IOException
;
33 import java
.io
.OutputStream
;
34 import java
.io
.PrintWriter
;
35 import java
.io
.Reader
;
36 import java
.io
.UnsupportedEncodingException
;
37 import java
.text
.MessageFormat
;
38 import java
.util
.Collections
;
39 import java
.util
.Date
;
40 import java
.util
.HashMap
;
41 import java
.util
.ArrayList
;
42 import java
.util
.LinkedList
;
43 import java
.util
.List
;
45 import java
.util
.ResourceBundle
;
47 import jexer
.bits
.CellAttributes
;
48 import jexer
.bits
.ColorTheme
;
49 import jexer
.event
.TCommandEvent
;
50 import jexer
.event
.TInputEvent
;
51 import jexer
.event
.TKeypressEvent
;
52 import jexer
.event
.TMenuEvent
;
53 import jexer
.event
.TMouseEvent
;
54 import jexer
.event
.TResizeEvent
;
55 import jexer
.backend
.Backend
;
56 import jexer
.backend
.Screen
;
57 import jexer
.backend
.MultiBackend
;
58 import jexer
.backend
.SwingBackend
;
59 import jexer
.backend
.ECMA48Backend
;
60 import jexer
.backend
.TWindowBackend
;
61 import jexer
.menu
.TMenu
;
62 import jexer
.menu
.TMenuItem
;
63 import static jexer
.TCommand
.*;
64 import static jexer
.TKeypress
.*;
67 * TApplication is the main driver class for a full Text User Interface
68 * application. It manages windows, provides a menu bar and status bar, and
69 * processes events received from the user.
71 public class TApplication
implements Runnable
{
76 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
78 // ------------------------------------------------------------------------
79 // Public constants -------------------------------------------------------
80 // ------------------------------------------------------------------------
83 * If true, emit thread stuff to System.err.
85 private static final boolean debugThreads
= false;
88 * If true, emit events being processed to System.err.
90 private static final boolean debugEvents
= false;
93 * If true, do "smart placement" on new windows that are not specified to
96 private static final boolean smartWindowPlacement
= true;
99 * Two backend types are available.
101 public static enum BackendType
{
108 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
113 * Synonym for ECMA48.
118 // ------------------------------------------------------------------------
119 // Primary/secondary event handlers ---------------------------------------
120 // ------------------------------------------------------------------------
123 * WidgetEventHandler is the main event consumer loop. There are at most
124 * two such threads in existence: the primary for normal case and a
125 * secondary that is used for TMessageBox, TInputBox, and similar.
127 private class WidgetEventHandler
implements Runnable
{
129 * The main application.
131 private TApplication application
;
134 * Whether or not this WidgetEventHandler is the primary or secondary
137 private boolean primary
= true;
140 * Public constructor.
142 * @param application the main application
143 * @param primary if true, this is the primary event handler thread
145 public WidgetEventHandler(final TApplication application
,
146 final boolean primary
) {
148 this.application
= application
;
149 this.primary
= primary
;
156 boolean first
= true;
159 while (!application
.quit
) {
161 // Wait until application notifies me
162 while (!application
.quit
) {
164 synchronized (application
.drainEventQueue
) {
165 if (application
.drainEventQueue
.size() > 0) {
174 timeout
= application
.getSleepTime(1000);
178 // A timer needs to fire, break out.
183 System
.err
.printf("%d %s %s sleep %d millis\n",
184 System
.currentTimeMillis(), this,
185 primary ?
"primary" : "secondary", timeout
);
188 synchronized (this) {
193 System
.err
.printf("%d %s %s AWAKE\n",
194 System
.currentTimeMillis(), this,
195 primary ?
"primary" : "secondary");
199 && (application
.secondaryEventReceiver
== null)
201 // Secondary thread, emergency exit. If we got
202 // here then something went wrong with the
203 // handoff between yield() and closeWindow().
204 synchronized (application
.primaryEventHandler
) {
205 application
.primaryEventHandler
.notify();
207 application
.secondaryEventHandler
= null;
208 throw new RuntimeException("secondary exited " +
212 } catch (InterruptedException e
) {
215 } // while (!application.quit)
217 // Pull all events off the queue
219 TInputEvent event
= null;
220 synchronized (application
.drainEventQueue
) {
221 if (application
.drainEventQueue
.size() == 0) {
224 event
= application
.drainEventQueue
.remove(0);
227 // We will have an event to process, so repaint the
228 // screen at the end.
229 application
.repaint
= true;
232 primaryHandleEvent(event
);
234 secondaryHandleEvent(event
);
237 && (application
.secondaryEventReceiver
== null)
239 // Secondary thread, time to exit.
241 // DO NOT UNLOCK. Primary thread just came back from
242 // primaryHandleEvent() and will unlock in the else
243 // block below. Just wake it up.
244 synchronized (application
.primaryEventHandler
) {
245 application
.primaryEventHandler
.notify();
247 // Now eliminate my reference so that
248 // wakeEventHandler() resumes working on the primary.
249 application
.secondaryEventHandler
= null;
257 // Fire timers, update screen.
259 application
.finishEventProcessing();
262 } // while (true) (main runnable loop)
267 * The primary event handler thread.
269 private volatile WidgetEventHandler primaryEventHandler
;
272 * The secondary event handler thread.
274 private volatile WidgetEventHandler secondaryEventHandler
;
277 * The widget receiving events from the secondary event handler thread.
279 private volatile TWidget secondaryEventReceiver
;
282 * Wake the sleeping active event handler.
284 private void wakeEventHandler() {
285 if (secondaryEventHandler
!= null) {
286 synchronized (secondaryEventHandler
) {
287 secondaryEventHandler
.notify();
290 assert (primaryEventHandler
!= null);
291 synchronized (primaryEventHandler
) {
292 primaryEventHandler
.notify();
297 // ------------------------------------------------------------------------
298 // TApplication attributes ------------------------------------------------
299 // ------------------------------------------------------------------------
302 * Access to the physical screen, keyboard, and mouse.
304 private Backend backend
;
309 * @return the Backend
311 public final Backend
getBackend() {
320 public final Screen
getScreen() {
321 if (backend
instanceof TWindowBackend
) {
322 // We are being rendered to a TWindow. We can't use its
323 // getScreen() method because that is how it is rendering to a
324 // hardware backend somewhere. Instead use its getOtherScreen()
326 return ((TWindowBackend
) backend
).getOtherScreen();
328 return backend
.getScreen();
333 * Actual mouse coordinate X.
338 * Actual mouse coordinate Y.
343 * Old version of mouse coordinate X.
345 private int oldMouseX
;
348 * Old version mouse coordinate Y.
350 private int oldMouseY
;
353 * Event queue that is filled by run().
355 private List
<TInputEvent
> fillEventQueue
;
358 * Event queue that will be drained by either primary or secondary
361 private List
<TInputEvent
> drainEventQueue
;
364 * Top-level menus in this application.
366 private List
<TMenu
> menus
;
369 * Stack of activated sub-menus in this application.
371 private List
<TMenu
> subMenus
;
374 * The currently active menu.
376 private TMenu activeMenu
= null;
379 * Active keyboard accelerators.
381 private Map
<TKeypress
, TMenuItem
> accelerators
;
386 private List
<TMenuItem
> menuItems
;
389 * Windows and widgets pull colors from this ColorTheme.
391 private ColorTheme theme
;
394 * Get the color theme.
398 public final ColorTheme
getTheme() {
403 * The top-level windows (but not menus).
405 private List
<TWindow
> windows
;
408 * The currently acive window.
410 private TWindow activeWindow
= null;
413 * Timers that are being ticked.
415 private List
<TTimer
> timers
;
418 * When true, exit the application.
420 private volatile boolean quit
= false;
423 * When true, repaint the entire screen.
425 private volatile boolean repaint
= true;
428 * Repaint the screen on the next update.
430 public void doRepaint() {
436 * Y coordinate of the top edge of the desktop. For now this is a
437 * constant. Someday it would be nice to have a multi-line menu or
440 private static final int desktopTop
= 1;
443 * Get Y coordinate of the top edge of the desktop.
445 * @return Y coordinate of the top edge of the desktop
447 public final int getDesktopTop() {
452 * Y coordinate of the bottom edge of the desktop.
454 private int desktopBottom
;
457 * Get Y coordinate of the bottom edge of the desktop.
459 * @return Y coordinate of the bottom edge of the desktop
461 public final int getDesktopBottom() {
462 return desktopBottom
;
466 * An optional TDesktop background window that is drawn underneath
469 private TDesktop desktop
;
472 * Set the TDesktop instance.
474 * @param desktop a TDesktop instance, or null to remove the one that is
477 public final void setDesktop(final TDesktop desktop
) {
478 if (this.desktop
!= null) {
479 this.desktop
.onClose();
481 this.desktop
= desktop
;
485 * Get the TDesktop instance.
487 * @return the desktop, or null if it is not set
489 public final TDesktop
getDesktop() {
494 * Get the current active window.
496 * @return the active window, or null if it is not set
498 public final TWindow
getActiveWindow() {
503 * Get a (shallow) copy of the window list.
505 * @return a copy of the list of windows for this application
507 public final List
<TWindow
> getAllWindows() {
508 List
<TWindow
> result
= new LinkedList
<TWindow
>();
509 result
.addAll(windows
);
514 * If true, focus follows mouse: windows automatically raised if the
515 * mouse passes over them.
517 private boolean focusFollowsMouse
= false;
520 * Get focusFollowsMouse flag.
522 * @return true if focus follows mouse: windows automatically raised if
523 * the mouse passes over them
525 public boolean getFocusFollowsMouse() {
526 return focusFollowsMouse
;
530 * Set focusFollowsMouse flag.
532 * @param focusFollowsMouse if true, focus follows mouse: windows
533 * automatically raised if the mouse passes over them
535 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
536 this.focusFollowsMouse
= focusFollowsMouse
;
539 // ------------------------------------------------------------------------
540 // General behavior -------------------------------------------------------
541 // ------------------------------------------------------------------------
544 * Display the about dialog.
546 protected void showAboutDialog() {
547 messageBox(i18n
.getString("aboutDialogTitle"),
548 MessageFormat
.format(i18n
.getString("aboutDialogText"),
549 this.getClass().getPackage().getImplementationVersion()),
550 TMessageBox
.Type
.OK
);
553 // ------------------------------------------------------------------------
554 // Constructors -----------------------------------------------------------
555 // ------------------------------------------------------------------------
558 * Public constructor.
560 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
562 * @throws UnsupportedEncodingException if an exception is thrown when
563 * creating the InputStreamReader
565 public TApplication(final BackendType backendType
)
566 throws UnsupportedEncodingException
{
568 switch (backendType
) {
570 // The default SwingBackend is 80x25, 20 pt font. If you want to
571 // change that, you can pass the extra arguments to the
572 // SwingBackend constructor here. For example, if you wanted
573 // 90x30, 16 pt font:
575 // backend = new SwingBackend(this, 90, 30, 16);
576 backend
= new SwingBackend(this);
581 backend
= new ECMA48Backend(this, null, null);
584 throw new IllegalArgumentException("Invalid backend type: "
591 * Public constructor. The backend type will be BackendType.ECMA48.
593 * @param input an InputStream connected to the remote user, or null for
594 * System.in. If System.in is used, then on non-Windows systems it will
595 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
596 * mode. input is always converted to a Reader with UTF-8 encoding.
597 * @param output an OutputStream connected to the remote user, or null
598 * for System.out. output is always converted to a Writer with UTF-8
600 * @throws UnsupportedEncodingException if an exception is thrown when
601 * creating the InputStreamReader
603 public TApplication(final InputStream input
,
604 final OutputStream output
) throws UnsupportedEncodingException
{
606 backend
= new ECMA48Backend(this, input
, output
);
611 * Public constructor. The backend type will be BackendType.ECMA48.
613 * @param input the InputStream underlying 'reader'. Its available()
614 * method is used to determine if reader.read() will block or not.
615 * @param reader a Reader connected to the remote user.
616 * @param writer a PrintWriter connected to the remote user.
617 * @param setRawMode if true, set System.in into raw mode with stty.
618 * This should in general not be used. It is here solely for Demo3,
619 * which uses System.in.
620 * @throws IllegalArgumentException if input, reader, or writer are null.
622 public TApplication(final InputStream input
, final Reader reader
,
623 final PrintWriter writer
, final boolean setRawMode
) {
625 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
630 * Public constructor. The backend type will be BackendType.ECMA48.
632 * @param input the InputStream underlying 'reader'. Its available()
633 * method is used to determine if reader.read() will block or not.
634 * @param reader a Reader connected to the remote user.
635 * @param writer a PrintWriter connected to the remote user.
636 * @throws IllegalArgumentException if input, reader, or writer are null.
638 public TApplication(final InputStream input
, final Reader reader
,
639 final PrintWriter writer
) {
641 this(input
, reader
, writer
, false);
645 * Public constructor. This hook enables use with new non-Jexer
648 * @param backend a Backend that is already ready to go.
650 public TApplication(final Backend backend
) {
651 this.backend
= backend
;
652 backend
.setListener(this);
657 * Finish construction once the backend is set.
659 private void TApplicationImpl() {
660 theme
= new ColorTheme();
661 desktopBottom
= getScreen().getHeight() - 1;
662 fillEventQueue
= new ArrayList
<TInputEvent
>();
663 drainEventQueue
= new ArrayList
<TInputEvent
>();
664 windows
= new LinkedList
<TWindow
>();
665 menus
= new LinkedList
<TMenu
>();
666 subMenus
= new LinkedList
<TMenu
>();
667 timers
= new LinkedList
<TTimer
>();
668 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
669 menuItems
= new ArrayList
<TMenuItem
>();
670 desktop
= new TDesktop(this);
672 // Special case: the Swing backend needs to have a timer to drive its
674 if ((backend
instanceof SwingBackend
)
675 || (backend
instanceof MultiBackend
)
677 // Default to 500 millis, unless a SwingBackend has its own
680 if (backend
instanceof SwingBackend
) {
681 millis
= ((SwingBackend
) backend
).getBlinkMillis();
684 addTimer(millis
, true,
687 TApplication
.this.doRepaint();
695 // ------------------------------------------------------------------------
696 // Screen refresh loop ----------------------------------------------------
697 // ------------------------------------------------------------------------
700 * Process background events, and update the screen.
702 private void finishEventProcessing() {
704 System
.err
.printf(System
.currentTimeMillis() + " " +
705 Thread
.currentThread() + " finishEventProcessing()\n");
708 // Process timers and call doIdle()'s
712 synchronized (getScreen()) {
717 System
.err
.printf(System
.currentTimeMillis() + " " +
718 Thread
.currentThread() + " finishEventProcessing() END\n");
723 * Invert the cell color at a position. This is used to track the mouse.
725 * @param x column position
726 * @param y row position
728 private void invertCell(final int x
, final int y
) {
730 System
.err
.printf("%d %s invertCell() %d %d\n",
731 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
733 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
734 attr
.setForeColor(attr
.getForeColor().invert());
735 attr
.setBackColor(attr
.getBackColor().invert());
736 getScreen().putAttrXY(x
, y
, attr
, false);
742 private void drawAll() {
743 boolean menuIsActive
= false;
746 System
.err
.printf("%d %s drawAll() enter\n",
747 System
.currentTimeMillis(), Thread
.currentThread());
752 System
.err
.printf("%d %s drawAll() !repaint\n",
753 System
.currentTimeMillis(), Thread
.currentThread());
755 synchronized (getScreen()) {
756 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
757 // The only thing that has happened is the mouse moved.
758 // Clear the old position and draw the new position.
759 invertCell(oldMouseX
, oldMouseY
);
760 invertCell(mouseX
, mouseY
);
764 if (getScreen().isDirty()) {
765 backend
.flushScreen();
772 System
.err
.printf("%d %s drawAll() REDRAW\n",
773 System
.currentTimeMillis(), Thread
.currentThread());
776 // If true, the cursor is not visible
777 boolean cursor
= false;
779 // Start with a clean screen
783 if (desktop
!= null) {
784 desktop
.drawChildren();
787 // Draw each window in reverse Z order
788 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
789 Collections
.sort(sorted
);
790 TWindow topLevel
= null;
791 if (sorted
.size() > 0) {
792 topLevel
= sorted
.get(0);
794 Collections
.reverse(sorted
);
795 for (TWindow window
: sorted
) {
796 if (window
.isShown()) {
797 window
.drawChildren();
801 // Draw the blank menubar line - reset the screen clipping first so
802 // it won't trim it out.
803 getScreen().resetClipping();
804 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
805 theme
.getColor("tmenu"));
806 // Now draw the menus.
808 for (TMenu menu
: menus
) {
809 CellAttributes menuColor
;
810 CellAttributes menuMnemonicColor
;
811 if (menu
.isActive()) {
813 menuColor
= theme
.getColor("tmenu.highlighted");
814 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
817 menuColor
= theme
.getColor("tmenu");
818 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
820 // Draw the menu title
821 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
823 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
824 // Draw the highlight character
825 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
826 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
828 if (menu
.isActive()) {
830 // Reset the screen clipping so we can draw the next title.
831 getScreen().resetClipping();
833 x
+= menu
.getTitle().length() + 2;
836 for (TMenu menu
: subMenus
) {
837 // Reset the screen clipping so we can draw the next sub-menu.
838 getScreen().resetClipping();
842 // Draw the status bar of the top-level window
843 TStatusBar statusBar
= null;
844 if (topLevel
!= null) {
845 statusBar
= topLevel
.getStatusBar();
847 if (statusBar
!= null) {
848 getScreen().resetClipping();
849 statusBar
.setWidth(getScreen().getWidth());
850 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
853 CellAttributes barColor
= new CellAttributes();
854 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
855 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
859 // Draw the mouse pointer
860 invertCell(mouseX
, mouseY
);
864 // Place the cursor if it is visible
866 TWidget activeWidget
= null;
867 if (sorted
.size() > 0) {
868 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
869 if (activeWidget
.isCursorVisible()) {
870 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
871 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
873 getScreen().putCursor(true,
874 activeWidget
.getCursorAbsoluteX(),
875 activeWidget
.getCursorAbsoluteY());
878 getScreen().putCursor(false,
879 activeWidget
.getCursorAbsoluteX(),
880 activeWidget
.getCursorAbsoluteY());
889 getScreen().hideCursor();
892 // Flush the screen contents
893 if (getScreen().isDirty()) {
894 backend
.flushScreen();
900 // ------------------------------------------------------------------------
901 // Main loop --------------------------------------------------------------
902 // ------------------------------------------------------------------------
905 * Force this application to exit.
909 synchronized (this) {
915 * Run this application until it exits.
918 // Start the main consumer thread
919 primaryEventHandler
= new WidgetEventHandler(this, true);
920 (new Thread(primaryEventHandler
)).start();
923 synchronized (this) {
924 boolean doWait
= false;
926 synchronized (fillEventQueue
) {
927 if (fillEventQueue
.size() == 0) {
933 // No I/O to dispatch, so wait until the backend
937 System
.err
.println(System
.currentTimeMillis() +
944 System
.err
.println(System
.currentTimeMillis() +
947 } catch (InterruptedException e
) {
948 // I'm awake and don't care why, let's see what's
949 // going on out there.
953 } // synchronized (this)
955 synchronized (fillEventQueue
) {
956 // Pull any pending I/O events
957 backend
.getEvents(fillEventQueue
);
959 // Dispatch each event to the appropriate handler, one at a
962 TInputEvent event
= null;
963 if (fillEventQueue
.size() == 0) {
966 event
= fillEventQueue
.remove(0);
967 metaHandleEvent(event
);
971 // Wake a consumer thread if we have any pending events.
972 if (drainEventQueue
.size() > 0) {
978 // Shutdown the event consumer threads
979 if (secondaryEventHandler
!= null) {
980 synchronized (secondaryEventHandler
) {
981 secondaryEventHandler
.notify();
984 if (primaryEventHandler
!= null) {
985 synchronized (primaryEventHandler
) {
986 primaryEventHandler
.notify();
990 // Shutdown the user I/O thread(s)
993 // Close all the windows. This gives them an opportunity to release
1000 * Peek at certain application-level events, add to eventQueue, and wake
1001 * up the consuming Thread.
1003 * @param event the input event to consume
1005 private void metaHandleEvent(final TInputEvent event
) {
1008 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1009 event
)); System
.err
.flush();
1013 // Do no more processing if the application is already trying
1018 // Special application-wide events -------------------------------
1021 if (event
instanceof TCommandEvent
) {
1022 TCommandEvent command
= (TCommandEvent
) event
;
1023 if (command
.getCmd().equals(cmAbort
)) {
1029 synchronized (drainEventQueue
) {
1031 if (event
instanceof TResizeEvent
) {
1032 TResizeEvent resize
= (TResizeEvent
) event
;
1033 synchronized (getScreen()) {
1034 getScreen().setDimensions(resize
.getWidth(),
1035 resize
.getHeight());
1036 desktopBottom
= getScreen().getHeight() - 1;
1042 if (desktop
!= null) {
1043 desktop
.setDimensions(0, 0, resize
.getWidth(),
1044 resize
.getHeight() - 1);
1047 // Change menu edges if needed.
1050 // We are dirty, redraw the screen.
1055 // Put into the main queue
1056 drainEventQueue
.add(event
);
1061 * Dispatch one event to the appropriate widget or application-level
1062 * event handler. This is the primary event handler, it has the normal
1063 * application-wide event handling.
1065 * @param event the input event to consume
1066 * @see #secondaryHandleEvent(TInputEvent event)
1068 private void primaryHandleEvent(final TInputEvent event
) {
1071 System
.err
.printf("Handle event: %s\n", event
);
1074 // Special application-wide events -----------------------------------
1076 // Peek at the mouse position
1077 if (event
instanceof TMouseEvent
) {
1078 TMouseEvent mouse
= (TMouseEvent
) event
;
1079 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1082 mouseX
= mouse
.getX();
1083 mouseY
= mouse
.getY();
1086 // See if we need to switch focus to another window or the menu
1087 checkSwitchFocus((TMouseEvent
) event
);
1090 // Handle menu events
1091 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1092 TMenu menu
= activeMenu
;
1094 if (event
instanceof TMouseEvent
) {
1095 TMouseEvent mouse
= (TMouseEvent
) event
;
1097 while (subMenus
.size() > 0) {
1098 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1099 if (subMenu
.mouseWouldHit(mouse
)) {
1102 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1103 && (!mouse
.isMouse1())
1104 && (!mouse
.isMouse2())
1105 && (!mouse
.isMouse3())
1106 && (!mouse
.isMouseWheelUp())
1107 && (!mouse
.isMouseWheelDown())
1111 // We navigated away from a sub-menu, so close it
1115 // Convert the mouse relative x/y to menu coordinates
1116 assert (mouse
.getX() == mouse
.getAbsoluteX());
1117 assert (mouse
.getY() == mouse
.getAbsoluteY());
1118 if (subMenus
.size() > 0) {
1119 menu
= subMenus
.get(subMenus
.size() - 1);
1121 mouse
.setX(mouse
.getX() - menu
.getX());
1122 mouse
.setY(mouse
.getY() - menu
.getY());
1124 menu
.handleEvent(event
);
1128 if (event
instanceof TKeypressEvent
) {
1129 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1131 // See if this key matches an accelerator, and is not being
1132 // shortcutted by the active window, and if so dispatch the menu
1134 boolean windowWillShortcut
= false;
1135 if (activeWindow
!= null) {
1136 assert (activeWindow
.isShown());
1137 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1138 // We do not process this key, it will be passed to the
1140 windowWillShortcut
= true;
1144 if (!windowWillShortcut
&& !modalWindowActive()) {
1145 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1146 TMenuItem item
= null;
1147 synchronized (accelerators
) {
1148 item
= accelerators
.get(keypressLowercase
);
1151 if (item
.isEnabled()) {
1152 // Let the menu item dispatch
1158 // Handle the keypress
1159 if (onKeypress(keypress
)) {
1165 if (event
instanceof TCommandEvent
) {
1166 if (onCommand((TCommandEvent
) event
)) {
1171 if (event
instanceof TMenuEvent
) {
1172 if (onMenu((TMenuEvent
) event
)) {
1177 // Dispatch events to the active window -------------------------------
1178 boolean dispatchToDesktop
= true;
1179 TWindow window
= activeWindow
;
1180 if (window
!= null) {
1181 assert (window
.isActive());
1182 assert (window
.isShown());
1183 if (event
instanceof TMouseEvent
) {
1184 TMouseEvent mouse
= (TMouseEvent
) event
;
1185 // Convert the mouse relative x/y to window coordinates
1186 assert (mouse
.getX() == mouse
.getAbsoluteX());
1187 assert (mouse
.getY() == mouse
.getAbsoluteY());
1188 mouse
.setX(mouse
.getX() - window
.getX());
1189 mouse
.setY(mouse
.getY() - window
.getY());
1191 if (window
.mouseWouldHit(mouse
)) {
1192 dispatchToDesktop
= false;
1194 } else if (event
instanceof TKeypressEvent
) {
1195 dispatchToDesktop
= false;
1199 System
.err
.printf("TApplication dispatch event: %s\n",
1202 window
.handleEvent(event
);
1204 if (dispatchToDesktop
) {
1205 // This event is fair game for the desktop to process.
1206 if (desktop
!= null) {
1207 desktop
.handleEvent(event
);
1213 * Dispatch one event to the appropriate widget or application-level
1214 * event handler. This is the secondary event handler used by certain
1215 * special dialogs (currently TMessageBox and TFileOpenBox).
1217 * @param event the input event to consume
1218 * @see #primaryHandleEvent(TInputEvent event)
1220 private void secondaryHandleEvent(final TInputEvent event
) {
1221 // Peek at the mouse position
1222 if (event
instanceof TMouseEvent
) {
1223 TMouseEvent mouse
= (TMouseEvent
) event
;
1224 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1227 mouseX
= mouse
.getX();
1228 mouseY
= mouse
.getY();
1232 secondaryEventReceiver
.handleEvent(event
);
1236 * Enable a widget to override the primary event thread.
1238 * @param widget widget that will receive events
1240 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1242 System
.err
.println(System
.currentTimeMillis() +
1243 " enableSecondaryEventReceiver()");
1246 assert (secondaryEventReceiver
== null);
1247 assert (secondaryEventHandler
== null);
1248 assert ((widget
instanceof TMessageBox
)
1249 || (widget
instanceof TFileOpenBox
));
1250 secondaryEventReceiver
= widget
;
1251 secondaryEventHandler
= new WidgetEventHandler(this, false);
1253 (new Thread(secondaryEventHandler
)).start();
1257 * Yield to the secondary thread.
1259 public final void yield() {
1260 assert (secondaryEventReceiver
!= null);
1262 while (secondaryEventReceiver
!= null) {
1263 synchronized (primaryEventHandler
) {
1265 primaryEventHandler
.wait();
1266 } catch (InterruptedException e
) {
1274 * Do stuff when there is no user input.
1276 private void doIdle() {
1278 System
.err
.printf(System
.currentTimeMillis() + " " +
1279 Thread
.currentThread() + " doIdle()\n");
1282 synchronized (timers
) {
1285 System
.err
.printf(System
.currentTimeMillis() + " " +
1286 Thread
.currentThread() + " doIdle() 2\n");
1289 // Run any timers that have timed out
1290 Date now
= new Date();
1291 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1292 for (TTimer timer
: timers
) {
1293 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1294 // Something might change, so repaint the screen.
1297 if (timer
.recurring
) {
1298 keepTimers
.add(timer
);
1301 keepTimers
.add(timer
);
1304 timers
= keepTimers
;
1308 for (TWindow window
: windows
) {
1311 if (desktop
!= null) {
1316 // ------------------------------------------------------------------------
1317 // TWindow management -----------------------------------------------------
1318 // ------------------------------------------------------------------------
1321 * Return the total number of windows.
1323 * @return the total number of windows
1325 public final int windowCount() {
1326 return windows
.size();
1330 * Return the number of windows that are showing.
1332 * @return the number of windows that are showing on screen
1334 public final int shownWindowCount() {
1336 for (TWindow w
: windows
) {
1345 * Return the number of windows that are hidden.
1347 * @return the number of windows that are hidden
1349 public final int hiddenWindowCount() {
1351 for (TWindow w
: windows
) {
1360 * Check if a window instance is in this application's window list.
1362 * @param window window to look for
1363 * @return true if this window is in the list
1365 public final boolean hasWindow(final TWindow window
) {
1366 if (windows
.size() == 0) {
1369 for (TWindow w
: windows
) {
1371 assert (window
.getApplication() == this);
1379 * Activate a window: bring it to the top and have it receive events.
1381 * @param window the window to become the new active window
1383 public void activateWindow(final TWindow window
) {
1384 if (hasWindow(window
) == false) {
1386 * Someone has a handle to a window I don't have. Ignore this
1392 // Whatever window might be moving/dragging, stop it now.
1393 for (TWindow w
: windows
) {
1394 if (w
.inMovements()) {
1399 assert (windows
.size() > 0);
1401 if (window
.isHidden()) {
1402 // Unhiding will also activate.
1406 assert (window
.isShown());
1408 if (windows
.size() == 1) {
1409 assert (window
== windows
.get(0));
1410 if (activeWindow
== null) {
1411 activeWindow
= window
;
1413 activeWindow
.setActive(true);
1414 activeWindow
.onFocus();
1417 assert (window
.isActive());
1418 assert (activeWindow
== window
);
1422 if (activeWindow
== window
) {
1423 assert (window
.isActive());
1425 // Window is already active, do nothing.
1429 assert (!window
.isActive());
1430 if (activeWindow
!= null) {
1431 assert (activeWindow
.getZ() == 0);
1433 activeWindow
.onUnfocus();
1434 activeWindow
.setActive(false);
1435 activeWindow
.setZ(window
.getZ());
1437 activeWindow
= window
;
1438 activeWindow
.setZ(0);
1439 activeWindow
.setActive(true);
1440 activeWindow
.onFocus();
1447 * @param window the window to hide
1449 public void hideWindow(final TWindow window
) {
1450 if (hasWindow(window
) == false) {
1452 * Someone has a handle to a window I don't have. Ignore this
1458 // Whatever window might be moving/dragging, stop it now.
1459 for (TWindow w
: windows
) {
1460 if (w
.inMovements()) {
1465 assert (windows
.size() > 0);
1467 if (!window
.hidden
) {
1468 if (window
== activeWindow
) {
1469 if (shownWindowCount() > 1) {
1472 activeWindow
= null;
1473 window
.setActive(false);
1477 window
.hidden
= true;
1485 * @param window the window to show
1487 public void showWindow(final TWindow window
) {
1488 if (hasWindow(window
) == false) {
1490 * Someone has a handle to a window I don't have. Ignore this
1496 // Whatever window might be moving/dragging, stop it now.
1497 for (TWindow w
: windows
) {
1498 if (w
.inMovements()) {
1503 assert (windows
.size() > 0);
1505 if (window
.hidden
) {
1506 window
.hidden
= false;
1508 activateWindow(window
);
1513 * Close window. Note that the window's destructor is NOT called by this
1514 * method, instead the GC is assumed to do the cleanup.
1516 * @param window the window to remove
1518 public final void closeWindow(final TWindow window
) {
1519 if (hasWindow(window
) == false) {
1521 * Someone has a handle to a window I don't have. Ignore this
1527 synchronized (windows
) {
1528 // Whatever window might be moving/dragging, stop it now.
1529 for (TWindow w
: windows
) {
1530 if (w
.inMovements()) {
1535 int z
= window
.getZ();
1538 Collections
.sort(windows
);
1540 activeWindow
= null;
1541 for (TWindow w
: windows
) {
1543 w
.setZ(w
.getZ() - 1);
1544 if (w
.getZ() == 0) {
1547 assert (activeWindow
== null);
1559 // Perform window cleanup
1562 // Check if we are closing a TMessageBox or similar
1563 if (secondaryEventReceiver
!= null) {
1564 assert (secondaryEventHandler
!= null);
1566 // Do not send events to the secondaryEventReceiver anymore, the
1567 // window is closed.
1568 secondaryEventReceiver
= null;
1570 // Wake the secondary thread, it will wake the primary as it
1572 synchronized (secondaryEventHandler
) {
1573 secondaryEventHandler
.notify();
1577 // Permit desktop to be active if it is the only thing left.
1578 if (desktop
!= null) {
1579 if (windows
.size() == 0) {
1580 desktop
.setActive(true);
1586 * Switch to the next window.
1588 * @param forward if true, then switch to the next window in the list,
1589 * otherwise switch to the previous window in the list
1591 public final void switchWindow(final boolean forward
) {
1592 // Only switch if there are multiple visible windows
1593 if (shownWindowCount() < 2) {
1596 assert (activeWindow
!= null);
1598 synchronized (windows
) {
1599 // Whatever window might be moving/dragging, stop it now.
1600 for (TWindow w
: windows
) {
1601 if (w
.inMovements()) {
1606 // Swap z/active between active window and the next in the list
1607 int activeWindowI
= -1;
1608 for (int i
= 0; i
< windows
.size(); i
++) {
1609 if (windows
.get(i
) == activeWindow
) {
1610 assert (activeWindow
.isActive());
1614 assert (!windows
.get(0).isActive());
1617 assert (activeWindowI
>= 0);
1619 // Do not switch if a window is modal
1620 if (activeWindow
.isModal()) {
1624 int nextWindowI
= activeWindowI
;
1628 nextWindowI
%= windows
.size();
1631 if (nextWindowI
< 0) {
1632 nextWindowI
= windows
.size() - 1;
1636 if (windows
.get(nextWindowI
).isShown()) {
1637 activateWindow(windows
.get(nextWindowI
));
1641 } // synchronized (windows)
1646 * Add a window to my window list and make it active.
1648 * @param window new window to add
1650 public final void addWindow(final TWindow window
) {
1652 // Do not add menu windows to the window list.
1653 if (window
instanceof TMenu
) {
1657 // Do not add the desktop to the window list.
1658 if (window
instanceof TDesktop
) {
1662 synchronized (windows
) {
1663 // Whatever window might be moving/dragging, stop it now.
1664 for (TWindow w
: windows
) {
1665 if (w
.inMovements()) {
1670 // Do not allow a modal window to spawn a non-modal window. If a
1671 // modal window is active, then this window will become modal
1673 if (modalWindowActive()) {
1674 window
.flags
|= TWindow
.MODAL
;
1675 window
.flags
|= TWindow
.CENTERED
;
1676 window
.hidden
= false;
1678 if (window
.isShown()) {
1679 for (TWindow w
: windows
) {
1684 w
.setZ(w
.getZ() + 1);
1687 windows
.add(window
);
1688 if (window
.isShown()) {
1689 activeWindow
= window
;
1690 activeWindow
.setZ(0);
1691 activeWindow
.setActive(true);
1692 activeWindow
.onFocus();
1695 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1696 && smartWindowPlacement
) {
1698 doSmartPlacement(window
);
1702 // Desktop cannot be active over any other window.
1703 if (desktop
!= null) {
1704 desktop
.setActive(false);
1709 * Check if there is a system-modal window on top.
1711 * @return true if the active window is modal
1713 private boolean modalWindowActive() {
1714 if (windows
.size() == 0) {
1718 for (TWindow w
: windows
) {
1728 * Close all open windows.
1730 private void closeAllWindows() {
1731 // Don't do anything if we are in the menu
1732 if (activeMenu
!= null) {
1735 while (windows
.size() > 0) {
1736 closeWindow(windows
.get(0));
1741 * Re-layout the open windows as non-overlapping tiles. This produces
1742 * almost the same results as Turbo Pascal 7.0's IDE.
1744 private void tileWindows() {
1745 synchronized (windows
) {
1746 // Don't do anything if we are in the menu
1747 if (activeMenu
!= null) {
1750 int z
= windows
.size();
1756 a
= (int)(Math
.sqrt(z
));
1760 if (((a
* b
) + c
) == z
) {
1768 int newWidth
= (getScreen().getWidth() / a
);
1769 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1770 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1772 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1773 Collections
.sort(sorted
);
1774 Collections
.reverse(sorted
);
1775 for (int i
= 0; i
< sorted
.size(); i
++) {
1776 int logicalX
= i
/ b
;
1777 int logicalY
= i
% b
;
1778 if (i
>= ((a
- 1) * b
)) {
1780 logicalY
= i
- ((a
- 1) * b
);
1783 TWindow w
= sorted
.get(i
);
1784 w
.setX(logicalX
* newWidth
);
1785 w
.setWidth(newWidth
);
1786 if (i
>= ((a
- 1) * b
)) {
1787 w
.setY((logicalY
* newHeight2
) + 1);
1788 w
.setHeight(newHeight2
);
1790 w
.setY((logicalY
* newHeight1
) + 1);
1791 w
.setHeight(newHeight1
);
1798 * Re-layout the open windows as overlapping cascaded windows.
1800 private void cascadeWindows() {
1801 synchronized (windows
) {
1802 // Don't do anything if we are in the menu
1803 if (activeMenu
!= null) {
1808 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1809 Collections
.sort(sorted
);
1810 Collections
.reverse(sorted
);
1811 for (TWindow window
: sorted
) {
1816 if (x
> getScreen().getWidth()) {
1819 if (y
>= getScreen().getHeight()) {
1827 * Place a window to minimize its overlap with other windows.
1829 * @param window the window to place
1831 public final void doSmartPlacement(final TWindow window
) {
1832 // This is a pretty dumb algorithm, but seems to work. The hardest
1833 // part is computing these "overlap" values seeking a minimum average
1836 int yMin
= desktopTop
;
1837 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1838 int yMax
= desktopBottom
- window
.getHeight() + 1;
1846 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1847 // No work to do, bail out.
1851 // Compute the overlap matrix without the new window.
1852 int width
= getScreen().getWidth();
1853 int height
= getScreen().getHeight();
1854 int overlapMatrix
[][] = new int[width
][height
];
1855 for (TWindow w
: windows
) {
1859 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1863 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1867 overlapMatrix
[x
][y
]++;
1872 long oldOverlapTotal
= 0;
1873 long oldOverlapN
= 0;
1874 for (int x
= 0; x
< width
; x
++) {
1875 for (int y
= 0; y
< height
; y
++) {
1876 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1877 if (overlapMatrix
[x
][y
] > 0) {
1884 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1885 boolean first
= true;
1886 int windowX
= window
.getX();
1887 int windowY
= window
.getY();
1889 // For each possible (x, y) position for the new window, compute a
1890 // new overlap matrix.
1891 for (int x
= xMin
; x
< xMax
; x
++) {
1892 for (int y
= yMin
; y
< yMax
; y
++) {
1894 // Start with the matrix minus this window.
1895 int newMatrix
[][] = new int[width
][height
];
1896 for (int mx
= 0; mx
< width
; mx
++) {
1897 for (int my
= 0; my
< height
; my
++) {
1898 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1902 // Add this window's values to the new overlap matrix.
1903 long newOverlapTotal
= 0;
1904 long newOverlapN
= 0;
1905 // Start by adding each new cell.
1906 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1910 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1914 newMatrix
[wx
][wy
]++;
1917 // Now figure out the new value for total coverage.
1918 for (int mx
= 0; mx
< width
; mx
++) {
1919 for (int my
= 0; my
< height
; my
++) {
1920 newOverlapTotal
+= newMatrix
[x
][y
];
1921 if (newMatrix
[mx
][my
] > 0) {
1926 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1929 // First time: just record what we got.
1930 oldOverlapAvg
= newOverlapAvg
;
1933 // All other times: pick a new best (x, y) and save the
1935 if (newOverlapAvg
< oldOverlapAvg
) {
1938 oldOverlapAvg
= newOverlapAvg
;
1942 } // for (int x = xMin; x < xMax; x++)
1944 } // for (int y = yMin; y < yMax; y++)
1946 // Finally, set the window's new coordinates.
1947 window
.setX(windowX
);
1948 window
.setY(windowY
);
1951 // ------------------------------------------------------------------------
1952 // TMenu management -------------------------------------------------------
1953 // ------------------------------------------------------------------------
1956 * Check if a mouse event would hit either the active menu or any open
1959 * @param mouse mouse event
1960 * @return true if the mouse would hit the active menu or an open
1963 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1964 assert (activeMenu
!= null);
1965 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1966 Collections
.reverse(menus
);
1967 for (TMenu menu
: menus
) {
1968 if (menu
.mouseWouldHit(mouse
)) {
1972 return activeMenu
.mouseWouldHit(mouse
);
1976 * See if we need to switch window or activate the menu based on
1979 * @param mouse mouse event
1981 private void checkSwitchFocus(final TMouseEvent mouse
) {
1983 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1984 && (activeMenu
!= null)
1985 && (mouse
.getAbsoluteY() != 0)
1986 && (!mouseOnMenu(mouse
))
1988 // They clicked outside the active menu, turn it off
1989 activeMenu
.setActive(false);
1991 for (TMenu menu
: subMenus
) {
1992 menu
.setActive(false);
1998 // See if they hit the menu bar
1999 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2000 && (mouse
.isMouse1())
2001 && (!modalWindowActive())
2002 && (mouse
.getAbsoluteY() == 0)
2005 for (TMenu menu
: subMenus
) {
2006 menu
.setActive(false);
2010 // They selected the menu, go activate it
2011 for (TMenu menu
: menus
) {
2012 if ((mouse
.getAbsoluteX() >= menu
.getX())
2013 && (mouse
.getAbsoluteX() < menu
.getX()
2014 + menu
.getTitle().length() + 2)
2016 menu
.setActive(true);
2019 menu
.setActive(false);
2025 // See if they hit the menu bar
2026 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2027 && (mouse
.isMouse1())
2028 && (activeMenu
!= null)
2029 && (mouse
.getAbsoluteY() == 0)
2032 TMenu oldMenu
= activeMenu
;
2033 for (TMenu menu
: subMenus
) {
2034 menu
.setActive(false);
2038 // See if we should switch menus
2039 for (TMenu menu
: menus
) {
2040 if ((mouse
.getAbsoluteX() >= menu
.getX())
2041 && (mouse
.getAbsoluteX() < menu
.getX()
2042 + menu
.getTitle().length() + 2)
2044 menu
.setActive(true);
2048 if (oldMenu
!= activeMenu
) {
2049 // They switched menus
2050 oldMenu
.setActive(false);
2055 // If a menu is still active, don't switch windows
2056 if (activeMenu
!= null) {
2060 // Only switch if there are multiple windows
2061 if (windows
.size() < 2) {
2065 if (((focusFollowsMouse
== true)
2066 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2067 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2069 synchronized (windows
) {
2070 Collections
.sort(windows
);
2071 if (windows
.get(0).isModal()) {
2072 // Modal windows don't switch
2076 for (TWindow window
: windows
) {
2077 assert (!window
.isModal());
2079 if (window
.isHidden()) {
2080 assert (!window
.isActive());
2084 if (window
.mouseWouldHit(mouse
)) {
2085 if (window
== windows
.get(0)) {
2086 // Clicked on the same window, nothing to do
2087 assert (window
.isActive());
2091 // We will be switching to another window
2092 assert (windows
.get(0).isActive());
2093 assert (windows
.get(0) == activeWindow
);
2094 assert (!window
.isActive());
2095 activeWindow
.onUnfocus();
2096 activeWindow
.setActive(false);
2097 activeWindow
.setZ(window
.getZ());
2098 activeWindow
= window
;
2100 window
.setActive(true);
2107 // Clicked on the background, nothing to do
2111 // Nothing to do: this isn't a mouse up, or focus isn't following
2117 * Turn off the menu.
2119 public final void closeMenu() {
2120 if (activeMenu
!= null) {
2121 activeMenu
.setActive(false);
2123 for (TMenu menu
: subMenus
) {
2124 menu
.setActive(false);
2131 * Get a (shallow) copy of the menu list.
2133 * @return a copy of the menu list
2135 public final List
<TMenu
> getAllMenus() {
2136 return new LinkedList
<TMenu
>(menus
);
2140 * Add a top-level menu to the list.
2142 * @param menu the menu to add
2143 * @throws IllegalArgumentException if the menu is already used in
2144 * another TApplication
2146 public final void addMenu(final TMenu menu
) {
2147 if ((menu
.getApplication() != null)
2148 && (menu
.getApplication() != this)
2150 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2151 "part of application " + menu
.getApplication());
2159 * Remove a top-level menu from the list.
2161 * @param menu the menu to remove
2162 * @throws IllegalArgumentException if the menu is already used in
2163 * another TApplication
2165 public final void removeMenu(final TMenu menu
) {
2166 if ((menu
.getApplication() != null)
2167 && (menu
.getApplication() != this)
2169 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2170 "part of application " + menu
.getApplication());
2178 * Turn off a sub-menu.
2180 public final void closeSubMenu() {
2181 assert (activeMenu
!= null);
2182 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2183 assert (item
!= null);
2184 item
.setActive(false);
2185 subMenus
.remove(subMenus
.size() - 1);
2189 * Switch to the next menu.
2191 * @param forward if true, then switch to the next menu in the list,
2192 * otherwise switch to the previous menu in the list
2194 public final void switchMenu(final boolean forward
) {
2195 assert (activeMenu
!= null);
2197 for (TMenu menu
: subMenus
) {
2198 menu
.setActive(false);
2202 for (int i
= 0; i
< menus
.size(); i
++) {
2203 if (activeMenu
== menus
.get(i
)) {
2205 if (i
< menus
.size() - 1) {
2213 activeMenu
.setActive(false);
2214 activeMenu
= menus
.get(i
);
2215 activeMenu
.setActive(true);
2222 * Add a menu item to the global list. If it has a keyboard accelerator,
2223 * that will be added the global hash.
2225 * @param item the menu item
2227 public final void addMenuItem(final TMenuItem item
) {
2228 menuItems
.add(item
);
2230 TKeypress key
= item
.getKey();
2232 synchronized (accelerators
) {
2233 assert (accelerators
.get(key
) == null);
2234 accelerators
.put(key
.toLowerCase(), item
);
2240 * Disable one menu item.
2242 * @param id the menu item ID
2244 public final void disableMenuItem(final int id
) {
2245 for (TMenuItem item
: menuItems
) {
2246 if (item
.getId() == id
) {
2247 item
.setEnabled(false);
2253 * Disable the range of menu items with ID's between lower and upper,
2256 * @param lower the lowest menu item ID
2257 * @param upper the highest menu item ID
2259 public final void disableMenuItems(final int lower
, final int upper
) {
2260 for (TMenuItem item
: menuItems
) {
2261 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2262 item
.setEnabled(false);
2268 * Enable one menu item.
2270 * @param id the menu item ID
2272 public final void enableMenuItem(final int id
) {
2273 for (TMenuItem item
: menuItems
) {
2274 if (item
.getId() == id
) {
2275 item
.setEnabled(true);
2281 * Enable the range of menu items with ID's between lower and upper,
2284 * @param lower the lowest menu item ID
2285 * @param upper the highest menu item ID
2287 public final void enableMenuItems(final int lower
, final int upper
) {
2288 for (TMenuItem item
: menuItems
) {
2289 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2290 item
.setEnabled(true);
2296 * Recompute menu x positions based on their title length.
2298 public final void recomputeMenuX() {
2300 for (TMenu menu
: menus
) {
2302 x
+= menu
.getTitle().length() + 2;
2304 // Don't let the menu window exceed the screen width
2305 int rightEdge
= menu
.getX() + menu
.getWidth();
2306 if (rightEdge
> getScreen().getWidth()) {
2307 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2313 * Post an event to process and turn off the menu.
2315 * @param event new event to add to the queue
2317 public final void postMenuEvent(final TInputEvent event
) {
2318 synchronized (this) {
2319 synchronized (fillEventQueue
) {
2320 fillEventQueue
.add(event
);
2323 System
.err
.println(System
.currentTimeMillis() + " " +
2324 Thread
.currentThread() + " postMenuEvent() wake up main");
2332 * Add a sub-menu to the list of open sub-menus.
2334 * @param menu sub-menu
2336 public final void addSubMenu(final TMenu menu
) {
2341 * Convenience function to add a top-level menu.
2343 * @param title menu title
2344 * @return the new menu
2346 public final TMenu
addMenu(final String title
) {
2349 TMenu menu
= new TMenu(this, x
, y
, title
);
2356 * Convenience function to add a default "File" menu.
2358 * @return the new menu
2360 public final TMenu
addFileMenu() {
2361 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
2362 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2363 fileMenu
.addSeparator();
2364 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2365 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2366 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
2367 getString("fileMenuStatus"));
2368 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2373 * Convenience function to add a default "Edit" menu.
2375 * @return the new menu
2377 public final TMenu
addEditMenu() {
2378 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
2379 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2380 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2381 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2382 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2383 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
2384 getString("editMenuStatus"));
2385 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2390 * Convenience function to add a default "Window" menu.
2392 * @return the new menu
2394 public final TMenu
addWindowMenu() {
2395 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
2396 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2397 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2398 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2399 windowMenu
.addSeparator();
2400 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2401 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2402 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2403 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2404 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2405 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
2406 getString("windowMenuStatus"));
2407 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2412 * Convenience function to add a default "Help" menu.
2414 * @return the new menu
2416 public final TMenu
addHelpMenu() {
2417 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
2418 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2419 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2420 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2421 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2422 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2423 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2424 helpMenu
.addSeparator();
2425 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2426 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
2427 getString("helpMenuStatus"));
2428 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2432 // ------------------------------------------------------------------------
2433 // Event handlers ---------------------------------------------------------
2434 // ------------------------------------------------------------------------
2437 * Method that TApplication subclasses can override to handle menu or
2438 * posted command events.
2440 * @param command command event
2441 * @return if true, this event was consumed
2443 protected boolean onCommand(final TCommandEvent command
) {
2444 // Default: handle cmExit
2445 if (command
.equals(cmExit
)) {
2446 if (messageBox(i18n
.getString("exitDialogTitle"),
2447 i18n
.getString("exitDialogText"),
2448 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2454 if (command
.equals(cmShell
)) {
2455 openTerminal(0, 0, TWindow
.RESIZABLE
);
2459 if (command
.equals(cmTile
)) {
2463 if (command
.equals(cmCascade
)) {
2467 if (command
.equals(cmCloseAll
)) {
2472 if (command
.equals(cmMenu
)) {
2473 if (!modalWindowActive() && (activeMenu
== null)) {
2474 if (menus
.size() > 0) {
2475 menus
.get(0).setActive(true);
2476 activeMenu
= menus
.get(0);
2486 * Method that TApplication subclasses can override to handle menu
2489 * @param menu menu event
2490 * @return if true, this event was consumed
2492 protected boolean onMenu(final TMenuEvent menu
) {
2494 // Default: handle MID_EXIT
2495 if (menu
.getId() == TMenu
.MID_EXIT
) {
2496 if (messageBox(i18n
.getString("exitDialogTitle"),
2497 i18n
.getString("exitDialogText"),
2498 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2504 if (menu
.getId() == TMenu
.MID_SHELL
) {
2505 openTerminal(0, 0, TWindow
.RESIZABLE
);
2509 if (menu
.getId() == TMenu
.MID_TILE
) {
2513 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2517 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2521 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2525 if (menu
.getId() == TMenu
.MID_REPAINT
) {
2533 * Method that TApplication subclasses can override to handle keystrokes.
2535 * @param keypress keystroke event
2536 * @return if true, this event was consumed
2538 protected boolean onKeypress(final TKeypressEvent keypress
) {
2539 // Default: only menu shortcuts
2541 // Process Alt-F, Alt-E, etc. menu shortcut keys
2542 if (!keypress
.getKey().isFnKey()
2543 && keypress
.getKey().isAlt()
2544 && !keypress
.getKey().isCtrl()
2545 && (activeMenu
== null)
2546 && !modalWindowActive()
2549 assert (subMenus
.size() == 0);
2551 for (TMenu menu
: menus
) {
2552 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2553 == Character
.toLowerCase(keypress
.getKey().getChar())
2556 menu
.setActive(true);
2565 // ------------------------------------------------------------------------
2566 // TTimer management ------------------------------------------------------
2567 // ------------------------------------------------------------------------
2570 * Get the amount of time I can sleep before missing a Timer tick.
2572 * @param timeout = initial (maximum) timeout in millis
2573 * @return number of milliseconds between now and the next timer event
2575 private long getSleepTime(final long timeout
) {
2576 Date now
= new Date();
2577 long nowTime
= now
.getTime();
2578 long sleepTime
= timeout
;
2580 synchronized (timers
) {
2581 for (TTimer timer
: timers
) {
2582 long nextTickTime
= timer
.getNextTick().getTime();
2583 if (nextTickTime
< nowTime
) {
2587 long timeDifference
= nextTickTime
- nowTime
;
2588 if (timeDifference
< sleepTime
) {
2589 sleepTime
= timeDifference
;
2594 assert (sleepTime
>= 0);
2595 assert (sleepTime
<= timeout
);
2600 * Convenience function to add a timer.
2602 * @param duration number of milliseconds to wait between ticks
2603 * @param recurring if true, re-schedule this timer after every tick
2604 * @param action function to call when button is pressed
2607 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2608 final TAction action
) {
2610 TTimer timer
= new TTimer(duration
, recurring
, action
);
2611 synchronized (timers
) {
2618 * Convenience function to remove a timer.
2620 * @param timer timer to remove
2622 public final void removeTimer(final TTimer timer
) {
2623 synchronized (timers
) {
2624 timers
.remove(timer
);
2628 // ------------------------------------------------------------------------
2629 // Other TWindow constructors ---------------------------------------------
2630 // ------------------------------------------------------------------------
2633 * Convenience function to spawn a message box.
2635 * @param title window title, will be centered along the top border
2636 * @param caption message to display. Use embedded newlines to get a
2638 * @return the new message box
2640 public final TMessageBox
messageBox(final String title
,
2641 final String caption
) {
2643 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2647 * Convenience function to spawn a message box.
2649 * @param title window title, will be centered along the top border
2650 * @param caption message to display. Use embedded newlines to get a
2652 * @param type one of the TMessageBox.Type constants. Default is
2654 * @return the new message box
2656 public final TMessageBox
messageBox(final String title
,
2657 final String caption
, final TMessageBox
.Type type
) {
2659 return new TMessageBox(this, title
, caption
, type
);
2663 * Convenience function to spawn an input box.
2665 * @param title window title, will be centered along the top border
2666 * @param caption message to display. Use embedded newlines to get a
2668 * @return the new input box
2670 public final TInputBox
inputBox(final String title
, final String caption
) {
2672 return new TInputBox(this, title
, caption
);
2676 * Convenience function to spawn an input box.
2678 * @param title window title, will be centered along the top border
2679 * @param caption message to display. Use embedded newlines to get a
2681 * @param text initial text to seed the field with
2682 * @return the new input box
2684 public final TInputBox
inputBox(final String title
, final String caption
,
2685 final String text
) {
2687 return new TInputBox(this, title
, caption
, text
);
2691 * Convenience function to open a terminal window.
2693 * @param x column relative to parent
2694 * @param y row relative to parent
2695 * @return the terminal new window
2697 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2698 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2702 * Convenience function to open a terminal window.
2704 * @param x column relative to parent
2705 * @param y row relative to parent
2706 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2707 * @return the terminal new window
2709 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2712 return new TTerminalWindow(this, x
, y
, flags
);
2716 * Convenience function to spawn an file open box.
2718 * @param path path of selected file
2719 * @return the result of the new file open box
2720 * @throws IOException if java.io operation throws
2722 public final String
fileOpenBox(final String path
) throws IOException
{
2724 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2725 return box
.getFilename();
2729 * Convenience function to spawn an file open box.
2731 * @param path path of selected file
2732 * @param type one of the Type constants
2733 * @return the result of the new file open box
2734 * @throws IOException if java.io operation throws
2736 public final String
fileOpenBox(final String path
,
2737 final TFileOpenBox
.Type type
) throws IOException
{
2739 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2740 return box
.getFilename();
2744 * Convenience function to create a new window and make it active.
2745 * Window will be located at (0, 0).
2747 * @param title window title, will be centered along the top border
2748 * @param width width of window
2749 * @param height height of window
2751 public final TWindow
addWindow(final String title
, final int width
,
2754 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2758 * Convenience function to create a new window and make it active.
2759 * Window will be located at (0, 0).
2761 * @param title window title, will be centered along the top border
2762 * @param width width of window
2763 * @param height height of window
2764 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2766 public final TWindow
addWindow(final String title
,
2767 final int width
, final int height
, final int flags
) {
2769 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2774 * Convenience function to create a new window and make it active.
2776 * @param title window title, will be centered along the top border
2777 * @param x column relative to parent
2778 * @param y row relative to parent
2779 * @param width width of window
2780 * @param height height of window
2782 public final TWindow
addWindow(final String title
,
2783 final int x
, final int y
, final int width
, final int height
) {
2785 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2790 * Convenience function to create a new window and make it active.
2792 * @param title window title, will be centered along the top border
2793 * @param x column relative to parent
2794 * @param y row relative to parent
2795 * @param width width of window
2796 * @param height height of window
2797 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2799 public final TWindow
addWindow(final String title
,
2800 final int x
, final int y
, final int width
, final int height
,
2803 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);