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);
1046 // We are dirty, redraw the screen.
1051 // Put into the main queue
1052 drainEventQueue
.add(event
);
1057 * Dispatch one event to the appropriate widget or application-level
1058 * event handler. This is the primary event handler, it has the normal
1059 * application-wide event handling.
1061 * @param event the input event to consume
1062 * @see #secondaryHandleEvent(TInputEvent event)
1064 private void primaryHandleEvent(final TInputEvent event
) {
1067 System
.err
.printf("Handle event: %s\n", event
);
1070 // Special application-wide events -----------------------------------
1072 // Peek at the mouse position
1073 if (event
instanceof TMouseEvent
) {
1074 TMouseEvent mouse
= (TMouseEvent
) event
;
1075 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1078 mouseX
= mouse
.getX();
1079 mouseY
= mouse
.getY();
1082 // See if we need to switch focus to another window or the menu
1083 checkSwitchFocus((TMouseEvent
) event
);
1086 // Handle menu events
1087 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1088 TMenu menu
= activeMenu
;
1090 if (event
instanceof TMouseEvent
) {
1091 TMouseEvent mouse
= (TMouseEvent
) event
;
1093 while (subMenus
.size() > 0) {
1094 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1095 if (subMenu
.mouseWouldHit(mouse
)) {
1098 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1099 && (!mouse
.isMouse1())
1100 && (!mouse
.isMouse2())
1101 && (!mouse
.isMouse3())
1102 && (!mouse
.isMouseWheelUp())
1103 && (!mouse
.isMouseWheelDown())
1107 // We navigated away from a sub-menu, so close it
1111 // Convert the mouse relative x/y to menu coordinates
1112 assert (mouse
.getX() == mouse
.getAbsoluteX());
1113 assert (mouse
.getY() == mouse
.getAbsoluteY());
1114 if (subMenus
.size() > 0) {
1115 menu
= subMenus
.get(subMenus
.size() - 1);
1117 mouse
.setX(mouse
.getX() - menu
.getX());
1118 mouse
.setY(mouse
.getY() - menu
.getY());
1120 menu
.handleEvent(event
);
1124 if (event
instanceof TKeypressEvent
) {
1125 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1127 // See if this key matches an accelerator, and is not being
1128 // shortcutted by the active window, and if so dispatch the menu
1130 boolean windowWillShortcut
= false;
1131 if (activeWindow
!= null) {
1132 assert (activeWindow
.isShown());
1133 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1134 // We do not process this key, it will be passed to the
1136 windowWillShortcut
= true;
1140 if (!windowWillShortcut
&& !modalWindowActive()) {
1141 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1142 TMenuItem item
= null;
1143 synchronized (accelerators
) {
1144 item
= accelerators
.get(keypressLowercase
);
1147 if (item
.isEnabled()) {
1148 // Let the menu item dispatch
1154 // Handle the keypress
1155 if (onKeypress(keypress
)) {
1161 if (event
instanceof TCommandEvent
) {
1162 if (onCommand((TCommandEvent
) event
)) {
1167 if (event
instanceof TMenuEvent
) {
1168 if (onMenu((TMenuEvent
) event
)) {
1173 // Dispatch events to the active window -------------------------------
1174 boolean dispatchToDesktop
= true;
1175 TWindow window
= activeWindow
;
1176 if (window
!= null) {
1177 assert (window
.isActive());
1178 assert (window
.isShown());
1179 if (event
instanceof TMouseEvent
) {
1180 TMouseEvent mouse
= (TMouseEvent
) event
;
1181 // Convert the mouse relative x/y to window coordinates
1182 assert (mouse
.getX() == mouse
.getAbsoluteX());
1183 assert (mouse
.getY() == mouse
.getAbsoluteY());
1184 mouse
.setX(mouse
.getX() - window
.getX());
1185 mouse
.setY(mouse
.getY() - window
.getY());
1187 if (window
.mouseWouldHit(mouse
)) {
1188 dispatchToDesktop
= false;
1190 } else if (event
instanceof TKeypressEvent
) {
1191 dispatchToDesktop
= false;
1195 System
.err
.printf("TApplication dispatch event: %s\n",
1198 window
.handleEvent(event
);
1200 if (dispatchToDesktop
) {
1201 // This event is fair game for the desktop to process.
1202 if (desktop
!= null) {
1203 desktop
.handleEvent(event
);
1209 * Dispatch one event to the appropriate widget or application-level
1210 * event handler. This is the secondary event handler used by certain
1211 * special dialogs (currently TMessageBox and TFileOpenBox).
1213 * @param event the input event to consume
1214 * @see #primaryHandleEvent(TInputEvent event)
1216 private void secondaryHandleEvent(final TInputEvent event
) {
1217 // Peek at the mouse position
1218 if (event
instanceof TMouseEvent
) {
1219 TMouseEvent mouse
= (TMouseEvent
) event
;
1220 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1223 mouseX
= mouse
.getX();
1224 mouseY
= mouse
.getY();
1228 secondaryEventReceiver
.handleEvent(event
);
1232 * Enable a widget to override the primary event thread.
1234 * @param widget widget that will receive events
1236 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1238 System
.err
.println(System
.currentTimeMillis() +
1239 " enableSecondaryEventReceiver()");
1242 assert (secondaryEventReceiver
== null);
1243 assert (secondaryEventHandler
== null);
1244 assert ((widget
instanceof TMessageBox
)
1245 || (widget
instanceof TFileOpenBox
));
1246 secondaryEventReceiver
= widget
;
1247 secondaryEventHandler
= new WidgetEventHandler(this, false);
1249 (new Thread(secondaryEventHandler
)).start();
1253 * Yield to the secondary thread.
1255 public final void yield() {
1256 assert (secondaryEventReceiver
!= null);
1258 while (secondaryEventReceiver
!= null) {
1259 synchronized (primaryEventHandler
) {
1261 primaryEventHandler
.wait();
1262 } catch (InterruptedException e
) {
1270 * Do stuff when there is no user input.
1272 private void doIdle() {
1274 System
.err
.printf(System
.currentTimeMillis() + " " +
1275 Thread
.currentThread() + " doIdle()\n");
1278 synchronized (timers
) {
1281 System
.err
.printf(System
.currentTimeMillis() + " " +
1282 Thread
.currentThread() + " doIdle() 2\n");
1285 // Run any timers that have timed out
1286 Date now
= new Date();
1287 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1288 for (TTimer timer
: timers
) {
1289 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1290 // Something might change, so repaint the screen.
1293 if (timer
.recurring
) {
1294 keepTimers
.add(timer
);
1297 keepTimers
.add(timer
);
1300 timers
= keepTimers
;
1304 for (TWindow window
: windows
) {
1307 if (desktop
!= null) {
1312 // ------------------------------------------------------------------------
1313 // TWindow management -----------------------------------------------------
1314 // ------------------------------------------------------------------------
1317 * Return the total number of windows.
1319 * @return the total number of windows
1321 public final int windowCount() {
1322 return windows
.size();
1326 * Return the number of windows that are showing.
1328 * @return the number of windows that are showing on screen
1330 public final int shownWindowCount() {
1332 for (TWindow w
: windows
) {
1341 * Return the number of windows that are hidden.
1343 * @return the number of windows that are hidden
1345 public final int hiddenWindowCount() {
1347 for (TWindow w
: windows
) {
1356 * Check if a window instance is in this application's window list.
1358 * @param window window to look for
1359 * @return true if this window is in the list
1361 public final boolean hasWindow(final TWindow window
) {
1362 if (windows
.size() == 0) {
1365 for (TWindow w
: windows
) {
1367 assert (window
.getApplication() == this);
1375 * Activate a window: bring it to the top and have it receive events.
1377 * @param window the window to become the new active window
1379 public void activateWindow(final TWindow window
) {
1380 if (hasWindow(window
) == false) {
1382 * Someone has a handle to a window I don't have. Ignore this
1388 // Whatever window might be moving/dragging, stop it now.
1389 for (TWindow w
: windows
) {
1390 if (w
.inMovements()) {
1395 assert (windows
.size() > 0);
1397 if (window
.isHidden()) {
1398 // Unhiding will also activate.
1402 assert (window
.isShown());
1404 if (windows
.size() == 1) {
1405 assert (window
== windows
.get(0));
1406 if (activeWindow
== null) {
1407 activeWindow
= window
;
1409 activeWindow
.setActive(true);
1410 activeWindow
.onFocus();
1413 assert (window
.isActive());
1414 assert (activeWindow
== window
);
1418 if (activeWindow
== window
) {
1419 assert (window
.isActive());
1421 // Window is already active, do nothing.
1425 assert (!window
.isActive());
1426 if (activeWindow
!= null) {
1427 assert (activeWindow
.getZ() == 0);
1429 activeWindow
.onUnfocus();
1430 activeWindow
.setActive(false);
1431 activeWindow
.setZ(window
.getZ());
1433 activeWindow
= window
;
1434 activeWindow
.setZ(0);
1435 activeWindow
.setActive(true);
1436 activeWindow
.onFocus();
1443 * @param window the window to hide
1445 public void hideWindow(final TWindow window
) {
1446 if (hasWindow(window
) == false) {
1448 * Someone has a handle to a window I don't have. Ignore this
1454 // Whatever window might be moving/dragging, stop it now.
1455 for (TWindow w
: windows
) {
1456 if (w
.inMovements()) {
1461 assert (windows
.size() > 0);
1463 if (!window
.hidden
) {
1464 if (window
== activeWindow
) {
1465 if (shownWindowCount() > 1) {
1468 activeWindow
= null;
1469 window
.setActive(false);
1473 window
.hidden
= true;
1481 * @param window the window to show
1483 public void showWindow(final TWindow window
) {
1484 if (hasWindow(window
) == false) {
1486 * Someone has a handle to a window I don't have. Ignore this
1492 // Whatever window might be moving/dragging, stop it now.
1493 for (TWindow w
: windows
) {
1494 if (w
.inMovements()) {
1499 assert (windows
.size() > 0);
1501 if (window
.hidden
) {
1502 window
.hidden
= false;
1504 activateWindow(window
);
1509 * Close window. Note that the window's destructor is NOT called by this
1510 * method, instead the GC is assumed to do the cleanup.
1512 * @param window the window to remove
1514 public final void closeWindow(final TWindow window
) {
1515 if (hasWindow(window
) == false) {
1517 * Someone has a handle to a window I don't have. Ignore this
1523 synchronized (windows
) {
1524 // Whatever window might be moving/dragging, stop it now.
1525 for (TWindow w
: windows
) {
1526 if (w
.inMovements()) {
1531 int z
= window
.getZ();
1534 Collections
.sort(windows
);
1536 activeWindow
= null;
1537 for (TWindow w
: windows
) {
1539 w
.setZ(w
.getZ() - 1);
1540 if (w
.getZ() == 0) {
1543 assert (activeWindow
== null);
1555 // Perform window cleanup
1558 // Check if we are closing a TMessageBox or similar
1559 if (secondaryEventReceiver
!= null) {
1560 assert (secondaryEventHandler
!= null);
1562 // Do not send events to the secondaryEventReceiver anymore, the
1563 // window is closed.
1564 secondaryEventReceiver
= null;
1566 // Wake the secondary thread, it will wake the primary as it
1568 synchronized (secondaryEventHandler
) {
1569 secondaryEventHandler
.notify();
1573 // Permit desktop to be active if it is the only thing left.
1574 if (desktop
!= null) {
1575 if (windows
.size() == 0) {
1576 desktop
.setActive(true);
1582 * Switch to the next window.
1584 * @param forward if true, then switch to the next window in the list,
1585 * otherwise switch to the previous window in the list
1587 public final void switchWindow(final boolean forward
) {
1588 // Only switch if there are multiple visible windows
1589 if (shownWindowCount() < 2) {
1592 assert (activeWindow
!= null);
1594 synchronized (windows
) {
1595 // Whatever window might be moving/dragging, stop it now.
1596 for (TWindow w
: windows
) {
1597 if (w
.inMovements()) {
1602 // Swap z/active between active window and the next in the list
1603 int activeWindowI
= -1;
1604 for (int i
= 0; i
< windows
.size(); i
++) {
1605 if (windows
.get(i
) == activeWindow
) {
1606 assert (activeWindow
.isActive());
1610 assert (!windows
.get(0).isActive());
1613 assert (activeWindowI
>= 0);
1615 // Do not switch if a window is modal
1616 if (activeWindow
.isModal()) {
1620 int nextWindowI
= activeWindowI
;
1624 nextWindowI
%= windows
.size();
1627 if (nextWindowI
< 0) {
1628 nextWindowI
= windows
.size() - 1;
1632 if (windows
.get(nextWindowI
).isShown()) {
1633 activateWindow(windows
.get(nextWindowI
));
1637 } // synchronized (windows)
1642 * Add a window to my window list and make it active.
1644 * @param window new window to add
1646 public final void addWindow(final TWindow window
) {
1648 // Do not add menu windows to the window list.
1649 if (window
instanceof TMenu
) {
1653 // Do not add the desktop to the window list.
1654 if (window
instanceof TDesktop
) {
1658 synchronized (windows
) {
1659 // Whatever window might be moving/dragging, stop it now.
1660 for (TWindow w
: windows
) {
1661 if (w
.inMovements()) {
1666 // Do not allow a modal window to spawn a non-modal window. If a
1667 // modal window is active, then this window will become modal
1669 if (modalWindowActive()) {
1670 window
.flags
|= TWindow
.MODAL
;
1671 window
.flags
|= TWindow
.CENTERED
;
1672 window
.hidden
= false;
1674 if (window
.isShown()) {
1675 for (TWindow w
: windows
) {
1680 w
.setZ(w
.getZ() + 1);
1683 windows
.add(window
);
1684 if (window
.isShown()) {
1685 activeWindow
= window
;
1686 activeWindow
.setZ(0);
1687 activeWindow
.setActive(true);
1688 activeWindow
.onFocus();
1691 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1692 && smartWindowPlacement
) {
1694 doSmartPlacement(window
);
1698 // Desktop cannot be active over any other window.
1699 if (desktop
!= null) {
1700 desktop
.setActive(false);
1705 * Check if there is a system-modal window on top.
1707 * @return true if the active window is modal
1709 private boolean modalWindowActive() {
1710 if (windows
.size() == 0) {
1714 for (TWindow w
: windows
) {
1724 * Close all open windows.
1726 private void closeAllWindows() {
1727 // Don't do anything if we are in the menu
1728 if (activeMenu
!= null) {
1731 while (windows
.size() > 0) {
1732 closeWindow(windows
.get(0));
1737 * Re-layout the open windows as non-overlapping tiles. This produces
1738 * almost the same results as Turbo Pascal 7.0's IDE.
1740 private void tileWindows() {
1741 synchronized (windows
) {
1742 // Don't do anything if we are in the menu
1743 if (activeMenu
!= null) {
1746 int z
= windows
.size();
1752 a
= (int)(Math
.sqrt(z
));
1756 if (((a
* b
) + c
) == z
) {
1764 int newWidth
= (getScreen().getWidth() / a
);
1765 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1766 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1768 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1769 Collections
.sort(sorted
);
1770 Collections
.reverse(sorted
);
1771 for (int i
= 0; i
< sorted
.size(); i
++) {
1772 int logicalX
= i
/ b
;
1773 int logicalY
= i
% b
;
1774 if (i
>= ((a
- 1) * b
)) {
1776 logicalY
= i
- ((a
- 1) * b
);
1779 TWindow w
= sorted
.get(i
);
1780 w
.setX(logicalX
* newWidth
);
1781 w
.setWidth(newWidth
);
1782 if (i
>= ((a
- 1) * b
)) {
1783 w
.setY((logicalY
* newHeight2
) + 1);
1784 w
.setHeight(newHeight2
);
1786 w
.setY((logicalY
* newHeight1
) + 1);
1787 w
.setHeight(newHeight1
);
1794 * Re-layout the open windows as overlapping cascaded windows.
1796 private void cascadeWindows() {
1797 synchronized (windows
) {
1798 // Don't do anything if we are in the menu
1799 if (activeMenu
!= null) {
1804 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1805 Collections
.sort(sorted
);
1806 Collections
.reverse(sorted
);
1807 for (TWindow window
: sorted
) {
1812 if (x
> getScreen().getWidth()) {
1815 if (y
>= getScreen().getHeight()) {
1823 * Place a window to minimize its overlap with other windows.
1825 * @param window the window to place
1827 public final void doSmartPlacement(final TWindow window
) {
1828 // This is a pretty dumb algorithm, but seems to work. The hardest
1829 // part is computing these "overlap" values seeking a minimum average
1832 int yMin
= desktopTop
;
1833 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1834 int yMax
= desktopBottom
- window
.getHeight() + 1;
1842 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1843 // No work to do, bail out.
1847 // Compute the overlap matrix without the new window.
1848 int width
= getScreen().getWidth();
1849 int height
= getScreen().getHeight();
1850 int overlapMatrix
[][] = new int[width
][height
];
1851 for (TWindow w
: windows
) {
1855 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1859 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1863 overlapMatrix
[x
][y
]++;
1868 long oldOverlapTotal
= 0;
1869 long oldOverlapN
= 0;
1870 for (int x
= 0; x
< width
; x
++) {
1871 for (int y
= 0; y
< height
; y
++) {
1872 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1873 if (overlapMatrix
[x
][y
] > 0) {
1880 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1881 boolean first
= true;
1882 int windowX
= window
.getX();
1883 int windowY
= window
.getY();
1885 // For each possible (x, y) position for the new window, compute a
1886 // new overlap matrix.
1887 for (int x
= xMin
; x
< xMax
; x
++) {
1888 for (int y
= yMin
; y
< yMax
; y
++) {
1890 // Start with the matrix minus this window.
1891 int newMatrix
[][] = new int[width
][height
];
1892 for (int mx
= 0; mx
< width
; mx
++) {
1893 for (int my
= 0; my
< height
; my
++) {
1894 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1898 // Add this window's values to the new overlap matrix.
1899 long newOverlapTotal
= 0;
1900 long newOverlapN
= 0;
1901 // Start by adding each new cell.
1902 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1906 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1910 newMatrix
[wx
][wy
]++;
1913 // Now figure out the new value for total coverage.
1914 for (int mx
= 0; mx
< width
; mx
++) {
1915 for (int my
= 0; my
< height
; my
++) {
1916 newOverlapTotal
+= newMatrix
[x
][y
];
1917 if (newMatrix
[mx
][my
] > 0) {
1922 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1925 // First time: just record what we got.
1926 oldOverlapAvg
= newOverlapAvg
;
1929 // All other times: pick a new best (x, y) and save the
1931 if (newOverlapAvg
< oldOverlapAvg
) {
1934 oldOverlapAvg
= newOverlapAvg
;
1938 } // for (int x = xMin; x < xMax; x++)
1940 } // for (int y = yMin; y < yMax; y++)
1942 // Finally, set the window's new coordinates.
1943 window
.setX(windowX
);
1944 window
.setY(windowY
);
1947 // ------------------------------------------------------------------------
1948 // TMenu management -------------------------------------------------------
1949 // ------------------------------------------------------------------------
1952 * Check if a mouse event would hit either the active menu or any open
1955 * @param mouse mouse event
1956 * @return true if the mouse would hit the active menu or an open
1959 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1960 assert (activeMenu
!= null);
1961 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1962 Collections
.reverse(menus
);
1963 for (TMenu menu
: menus
) {
1964 if (menu
.mouseWouldHit(mouse
)) {
1968 return activeMenu
.mouseWouldHit(mouse
);
1972 * See if we need to switch window or activate the menu based on
1975 * @param mouse mouse event
1977 private void checkSwitchFocus(final TMouseEvent mouse
) {
1979 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1980 && (activeMenu
!= null)
1981 && (mouse
.getAbsoluteY() != 0)
1982 && (!mouseOnMenu(mouse
))
1984 // They clicked outside the active menu, turn it off
1985 activeMenu
.setActive(false);
1987 for (TMenu menu
: subMenus
) {
1988 menu
.setActive(false);
1994 // See if they hit the menu bar
1995 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1996 && (mouse
.isMouse1())
1997 && (!modalWindowActive())
1998 && (mouse
.getAbsoluteY() == 0)
2001 for (TMenu menu
: subMenus
) {
2002 menu
.setActive(false);
2006 // They selected the menu, go activate it
2007 for (TMenu menu
: menus
) {
2008 if ((mouse
.getAbsoluteX() >= menu
.getX())
2009 && (mouse
.getAbsoluteX() < menu
.getX()
2010 + menu
.getTitle().length() + 2)
2012 menu
.setActive(true);
2015 menu
.setActive(false);
2021 // See if they hit the menu bar
2022 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2023 && (mouse
.isMouse1())
2024 && (activeMenu
!= null)
2025 && (mouse
.getAbsoluteY() == 0)
2028 TMenu oldMenu
= activeMenu
;
2029 for (TMenu menu
: subMenus
) {
2030 menu
.setActive(false);
2034 // See if we should switch menus
2035 for (TMenu menu
: menus
) {
2036 if ((mouse
.getAbsoluteX() >= menu
.getX())
2037 && (mouse
.getAbsoluteX() < menu
.getX()
2038 + menu
.getTitle().length() + 2)
2040 menu
.setActive(true);
2044 if (oldMenu
!= activeMenu
) {
2045 // They switched menus
2046 oldMenu
.setActive(false);
2051 // If a menu is still active, don't switch windows
2052 if (activeMenu
!= null) {
2056 // Only switch if there are multiple windows
2057 if (windows
.size() < 2) {
2061 if (((focusFollowsMouse
== true)
2062 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2063 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2065 synchronized (windows
) {
2066 Collections
.sort(windows
);
2067 if (windows
.get(0).isModal()) {
2068 // Modal windows don't switch
2072 for (TWindow window
: windows
) {
2073 assert (!window
.isModal());
2075 if (window
.isHidden()) {
2076 assert (!window
.isActive());
2080 if (window
.mouseWouldHit(mouse
)) {
2081 if (window
== windows
.get(0)) {
2082 // Clicked on the same window, nothing to do
2083 assert (window
.isActive());
2087 // We will be switching to another window
2088 assert (windows
.get(0).isActive());
2089 assert (windows
.get(0) == activeWindow
);
2090 assert (!window
.isActive());
2091 activeWindow
.onUnfocus();
2092 activeWindow
.setActive(false);
2093 activeWindow
.setZ(window
.getZ());
2094 activeWindow
= window
;
2096 window
.setActive(true);
2103 // Clicked on the background, nothing to do
2107 // Nothing to do: this isn't a mouse up, or focus isn't following
2113 * Turn off the menu.
2115 public final void closeMenu() {
2116 if (activeMenu
!= null) {
2117 activeMenu
.setActive(false);
2119 for (TMenu menu
: subMenus
) {
2120 menu
.setActive(false);
2127 * Get a (shallow) copy of the menu list.
2129 * @return a copy of the menu list
2131 public final List
<TMenu
> getAllMenus() {
2132 return new LinkedList
<TMenu
>(menus
);
2136 * Add a top-level menu to the list.
2138 * @param menu the menu to add
2139 * @throws IllegalArgumentException if the menu is already used in
2140 * another TApplication
2142 public final void addMenu(final TMenu menu
) {
2143 if ((menu
.getApplication() != null)
2144 && (menu
.getApplication() != this)
2146 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2147 "part of application " + menu
.getApplication());
2155 * Remove a top-level menu from the list.
2157 * @param menu the menu to remove
2158 * @throws IllegalArgumentException if the menu is already used in
2159 * another TApplication
2161 public final void removeMenu(final TMenu menu
) {
2162 if ((menu
.getApplication() != null)
2163 && (menu
.getApplication() != this)
2165 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2166 "part of application " + menu
.getApplication());
2174 * Turn off a sub-menu.
2176 public final void closeSubMenu() {
2177 assert (activeMenu
!= null);
2178 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2179 assert (item
!= null);
2180 item
.setActive(false);
2181 subMenus
.remove(subMenus
.size() - 1);
2185 * Switch to the next menu.
2187 * @param forward if true, then switch to the next menu in the list,
2188 * otherwise switch to the previous menu in the list
2190 public final void switchMenu(final boolean forward
) {
2191 assert (activeMenu
!= null);
2193 for (TMenu menu
: subMenus
) {
2194 menu
.setActive(false);
2198 for (int i
= 0; i
< menus
.size(); i
++) {
2199 if (activeMenu
== menus
.get(i
)) {
2201 if (i
< menus
.size() - 1) {
2209 activeMenu
.setActive(false);
2210 activeMenu
= menus
.get(i
);
2211 activeMenu
.setActive(true);
2218 * Add a menu item to the global list. If it has a keyboard accelerator,
2219 * that will be added the global hash.
2221 * @param item the menu item
2223 public final void addMenuItem(final TMenuItem item
) {
2224 menuItems
.add(item
);
2226 TKeypress key
= item
.getKey();
2228 synchronized (accelerators
) {
2229 assert (accelerators
.get(key
) == null);
2230 accelerators
.put(key
.toLowerCase(), item
);
2236 * Disable one menu item.
2238 * @param id the menu item ID
2240 public final void disableMenuItem(final int id
) {
2241 for (TMenuItem item
: menuItems
) {
2242 if (item
.getId() == id
) {
2243 item
.setEnabled(false);
2249 * Disable the range of menu items with ID's between lower and upper,
2252 * @param lower the lowest menu item ID
2253 * @param upper the highest menu item ID
2255 public final void disableMenuItems(final int lower
, final int upper
) {
2256 for (TMenuItem item
: menuItems
) {
2257 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2258 item
.setEnabled(false);
2264 * Enable one menu item.
2266 * @param id the menu item ID
2268 public final void enableMenuItem(final int id
) {
2269 for (TMenuItem item
: menuItems
) {
2270 if (item
.getId() == id
) {
2271 item
.setEnabled(true);
2277 * Enable the range of menu items with ID's between lower and upper,
2280 * @param lower the lowest menu item ID
2281 * @param upper the highest menu item ID
2283 public final void enableMenuItems(final int lower
, final int upper
) {
2284 for (TMenuItem item
: menuItems
) {
2285 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2286 item
.setEnabled(true);
2292 * Recompute menu x positions based on their title length.
2294 public final void recomputeMenuX() {
2296 for (TMenu menu
: menus
) {
2298 x
+= menu
.getTitle().length() + 2;
2303 * Post an event to process and turn off the menu.
2305 * @param event new event to add to the queue
2307 public final void postMenuEvent(final TInputEvent event
) {
2308 synchronized (this) {
2309 synchronized (fillEventQueue
) {
2310 fillEventQueue
.add(event
);
2313 System
.err
.println(System
.currentTimeMillis() + " " +
2314 Thread
.currentThread() + " postMenuEvent() wake up main");
2322 * Add a sub-menu to the list of open sub-menus.
2324 * @param menu sub-menu
2326 public final void addSubMenu(final TMenu menu
) {
2331 * Convenience function to add a top-level menu.
2333 * @param title menu title
2334 * @return the new menu
2336 public final TMenu
addMenu(final String title
) {
2339 TMenu menu
= new TMenu(this, x
, y
, title
);
2346 * Convenience function to add a default "File" menu.
2348 * @return the new menu
2350 public final TMenu
addFileMenu() {
2351 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
2352 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2353 fileMenu
.addSeparator();
2354 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2355 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2356 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
2357 getString("fileMenuStatus"));
2358 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2363 * Convenience function to add a default "Edit" menu.
2365 * @return the new menu
2367 public final TMenu
addEditMenu() {
2368 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
2369 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2370 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2371 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2372 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2373 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
2374 getString("editMenuStatus"));
2375 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2380 * Convenience function to add a default "Window" menu.
2382 * @return the new menu
2384 public final TMenu
addWindowMenu() {
2385 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
2386 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2387 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2388 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2389 windowMenu
.addSeparator();
2390 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2391 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2392 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2393 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2394 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2395 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
2396 getString("windowMenuStatus"));
2397 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2402 * Convenience function to add a default "Help" menu.
2404 * @return the new menu
2406 public final TMenu
addHelpMenu() {
2407 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
2408 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2409 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2410 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2411 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2412 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2413 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2414 helpMenu
.addSeparator();
2415 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2416 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
2417 getString("helpMenuStatus"));
2418 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2422 // ------------------------------------------------------------------------
2423 // Event handlers ---------------------------------------------------------
2424 // ------------------------------------------------------------------------
2427 * Method that TApplication subclasses can override to handle menu or
2428 * posted command events.
2430 * @param command command event
2431 * @return if true, this event was consumed
2433 protected boolean onCommand(final TCommandEvent command
) {
2434 // Default: handle cmExit
2435 if (command
.equals(cmExit
)) {
2436 if (messageBox(i18n
.getString("exitDialogTitle"),
2437 i18n
.getString("exitDialogText"),
2438 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2444 if (command
.equals(cmShell
)) {
2445 openTerminal(0, 0, TWindow
.RESIZABLE
);
2449 if (command
.equals(cmTile
)) {
2453 if (command
.equals(cmCascade
)) {
2457 if (command
.equals(cmCloseAll
)) {
2462 if (command
.equals(cmMenu
)) {
2463 if (!modalWindowActive() && (activeMenu
== null)) {
2464 if (menus
.size() > 0) {
2465 menus
.get(0).setActive(true);
2466 activeMenu
= menus
.get(0);
2476 * Method that TApplication subclasses can override to handle menu
2479 * @param menu menu event
2480 * @return if true, this event was consumed
2482 protected boolean onMenu(final TMenuEvent menu
) {
2484 // Default: handle MID_EXIT
2485 if (menu
.getId() == TMenu
.MID_EXIT
) {
2486 if (messageBox(i18n
.getString("exitDialogTitle"),
2487 i18n
.getString("exitDialogText"),
2488 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2494 if (menu
.getId() == TMenu
.MID_SHELL
) {
2495 openTerminal(0, 0, TWindow
.RESIZABLE
);
2499 if (menu
.getId() == TMenu
.MID_TILE
) {
2503 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2507 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2511 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2519 * Method that TApplication subclasses can override to handle keystrokes.
2521 * @param keypress keystroke event
2522 * @return if true, this event was consumed
2524 protected boolean onKeypress(final TKeypressEvent keypress
) {
2525 // Default: only menu shortcuts
2527 // Process Alt-F, Alt-E, etc. menu shortcut keys
2528 if (!keypress
.getKey().isFnKey()
2529 && keypress
.getKey().isAlt()
2530 && !keypress
.getKey().isCtrl()
2531 && (activeMenu
== null)
2532 && !modalWindowActive()
2535 assert (subMenus
.size() == 0);
2537 for (TMenu menu
: menus
) {
2538 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2539 == Character
.toLowerCase(keypress
.getKey().getChar())
2542 menu
.setActive(true);
2551 // ------------------------------------------------------------------------
2552 // TTimer management ------------------------------------------------------
2553 // ------------------------------------------------------------------------
2556 * Get the amount of time I can sleep before missing a Timer tick.
2558 * @param timeout = initial (maximum) timeout in millis
2559 * @return number of milliseconds between now and the next timer event
2561 private long getSleepTime(final long timeout
) {
2562 Date now
= new Date();
2563 long nowTime
= now
.getTime();
2564 long sleepTime
= timeout
;
2566 synchronized (timers
) {
2567 for (TTimer timer
: timers
) {
2568 long nextTickTime
= timer
.getNextTick().getTime();
2569 if (nextTickTime
< nowTime
) {
2573 long timeDifference
= nextTickTime
- nowTime
;
2574 if (timeDifference
< sleepTime
) {
2575 sleepTime
= timeDifference
;
2580 assert (sleepTime
>= 0);
2581 assert (sleepTime
<= timeout
);
2586 * Convenience function to add a timer.
2588 * @param duration number of milliseconds to wait between ticks
2589 * @param recurring if true, re-schedule this timer after every tick
2590 * @param action function to call when button is pressed
2593 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2594 final TAction action
) {
2596 TTimer timer
= new TTimer(duration
, recurring
, action
);
2597 synchronized (timers
) {
2604 * Convenience function to remove a timer.
2606 * @param timer timer to remove
2608 public final void removeTimer(final TTimer timer
) {
2609 synchronized (timers
) {
2610 timers
.remove(timer
);
2614 // ------------------------------------------------------------------------
2615 // Other TWindow constructors ---------------------------------------------
2616 // ------------------------------------------------------------------------
2619 * Convenience function to spawn a message box.
2621 * @param title window title, will be centered along the top border
2622 * @param caption message to display. Use embedded newlines to get a
2624 * @return the new message box
2626 public final TMessageBox
messageBox(final String title
,
2627 final String caption
) {
2629 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
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 * @param type one of the TMessageBox.Type constants. Default is
2640 * @return the new message box
2642 public final TMessageBox
messageBox(final String title
,
2643 final String caption
, final TMessageBox
.Type type
) {
2645 return new TMessageBox(this, title
, caption
, type
);
2649 * Convenience function to spawn an input box.
2651 * @param title window title, will be centered along the top border
2652 * @param caption message to display. Use embedded newlines to get a
2654 * @return the new input box
2656 public final TInputBox
inputBox(final String title
, final String caption
) {
2658 return new TInputBox(this, title
, caption
);
2662 * Convenience function to spawn an input box.
2664 * @param title window title, will be centered along the top border
2665 * @param caption message to display. Use embedded newlines to get a
2667 * @param text initial text to seed the field with
2668 * @return the new input box
2670 public final TInputBox
inputBox(final String title
, final String caption
,
2671 final String text
) {
2673 return new TInputBox(this, title
, caption
, text
);
2677 * Convenience function to open a terminal window.
2679 * @param x column relative to parent
2680 * @param y row relative to parent
2681 * @return the terminal new window
2683 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2684 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2688 * Convenience function to open a terminal window.
2690 * @param x column relative to parent
2691 * @param y row relative to parent
2692 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2693 * @return the terminal new window
2695 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2698 return new TTerminalWindow(this, x
, y
, flags
);
2702 * Convenience function to spawn an file open box.
2704 * @param path path of selected file
2705 * @return the result of the new file open box
2706 * @throws IOException if java.io operation throws
2708 public final String
fileOpenBox(final String path
) throws IOException
{
2710 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2711 return box
.getFilename();
2715 * Convenience function to spawn an file open box.
2717 * @param path path of selected file
2718 * @param type one of the Type constants
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
,
2723 final TFileOpenBox
.Type type
) throws IOException
{
2725 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2726 return box
.getFilename();
2730 * Convenience function to create a new window and make it active.
2731 * Window will be located at (0, 0).
2733 * @param title window title, will be centered along the top border
2734 * @param width width of window
2735 * @param height height of window
2737 public final TWindow
addWindow(final String title
, final int width
,
2740 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
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
2750 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2752 public final TWindow
addWindow(final String title
,
2753 final int width
, final int height
, final int flags
) {
2755 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2760 * Convenience function to create a new window and make it active.
2762 * @param title window title, will be centered along the top border
2763 * @param x column relative to parent
2764 * @param y row relative to parent
2765 * @param width width of window
2766 * @param height height of window
2768 public final TWindow
addWindow(final String title
,
2769 final int x
, final int y
, final int width
, final int height
) {
2771 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2776 * Convenience function to create a new window and make it active.
2778 * @param title window title, will be centered along the top border
2779 * @param x column relative to parent
2780 * @param y row relative to parent
2781 * @param width width of window
2782 * @param height height of window
2783 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2785 public final TWindow
addWindow(final String title
,
2786 final int x
, final int y
, final int width
, final int height
,
2789 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);