2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2017 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
31 import java
.io
.InputStream
;
32 import java
.io
.IOException
;
33 import java
.io
.OutputStream
;
34 import java
.io
.PrintWriter
;
35 import java
.io
.Reader
;
36 import java
.io
.UnsupportedEncodingException
;
37 import java
.util
.Collections
;
38 import java
.util
.Date
;
39 import java
.util
.HashMap
;
40 import java
.util
.ArrayList
;
41 import java
.util
.LinkedList
;
42 import java
.util
.List
;
45 import jexer
.bits
.CellAttributes
;
46 import jexer
.bits
.ColorTheme
;
47 import jexer
.event
.TCommandEvent
;
48 import jexer
.event
.TInputEvent
;
49 import jexer
.event
.TKeypressEvent
;
50 import jexer
.event
.TMenuEvent
;
51 import jexer
.event
.TMouseEvent
;
52 import jexer
.event
.TResizeEvent
;
53 import jexer
.backend
.Backend
;
54 import jexer
.backend
.Screen
;
55 import jexer
.backend
.MultiBackend
;
56 import jexer
.backend
.SwingBackend
;
57 import jexer
.backend
.ECMA48Backend
;
58 import jexer
.backend
.TWindowBackend
;
59 import jexer
.menu
.TMenu
;
60 import jexer
.menu
.TMenuItem
;
61 import static jexer
.TCommand
.*;
62 import static jexer
.TKeypress
.*;
65 * TApplication is the main driver class for a full Text User Interface
66 * application. It manages windows, provides a menu bar and status bar, and
67 * processes events received from the user.
69 public class TApplication
implements Runnable
{
71 // ------------------------------------------------------------------------
72 // Public constants -------------------------------------------------------
73 // ------------------------------------------------------------------------
76 * If true, emit thread stuff to System.err.
78 private static final boolean debugThreads
= false;
81 * If true, emit events being processed to System.err.
83 private static final boolean debugEvents
= false;
86 * If true, do "smart placement" on new windows that are not specified to
89 private static final boolean smartWindowPlacement
= true;
92 * Two backend types are available.
94 public static enum BackendType
{
101 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
106 * Synonym for ECMA48.
111 // ------------------------------------------------------------------------
112 // Primary/secondary event handlers ---------------------------------------
113 // ------------------------------------------------------------------------
116 * WidgetEventHandler is the main event consumer loop. There are at most
117 * two such threads in existence: the primary for normal case and a
118 * secondary that is used for TMessageBox, TInputBox, and similar.
120 private class WidgetEventHandler
implements Runnable
{
122 * The main application.
124 private TApplication application
;
127 * Whether or not this WidgetEventHandler is the primary or secondary
130 private boolean primary
= true;
133 * Public constructor.
135 * @param application the main application
136 * @param primary if true, this is the primary event handler thread
138 public WidgetEventHandler(final TApplication application
,
139 final boolean primary
) {
141 this.application
= application
;
142 this.primary
= primary
;
149 boolean first
= true;
152 while (!application
.quit
) {
154 // Wait until application notifies me
155 while (!application
.quit
) {
157 synchronized (application
.drainEventQueue
) {
158 if (application
.drainEventQueue
.size() > 0) {
167 timeout
= application
.getSleepTime(1000);
171 // A timer needs to fire, break out.
176 System
.err
.printf("%d %s %s sleep %d millis\n",
177 System
.currentTimeMillis(), this,
178 primary ?
"primary" : "secondary", timeout
);
181 synchronized (this) {
186 System
.err
.printf("%d %s %s AWAKE\n",
187 System
.currentTimeMillis(), this,
188 primary ?
"primary" : "secondary");
192 && (application
.secondaryEventReceiver
== null)
194 // Secondary thread, emergency exit. If we got
195 // here then something went wrong with the
196 // handoff between yield() and closeWindow().
197 synchronized (application
.primaryEventHandler
) {
198 application
.primaryEventHandler
.notify();
200 application
.secondaryEventHandler
= null;
201 throw new RuntimeException("secondary exited " +
205 } catch (InterruptedException e
) {
208 } // while (!application.quit)
210 // Pull all events off the queue
212 TInputEvent event
= null;
213 synchronized (application
.drainEventQueue
) {
214 if (application
.drainEventQueue
.size() == 0) {
217 event
= application
.drainEventQueue
.remove(0);
220 // We will have an event to process, so repaint the
221 // screen at the end.
222 application
.repaint
= true;
225 primaryHandleEvent(event
);
227 secondaryHandleEvent(event
);
230 && (application
.secondaryEventReceiver
== null)
232 // Secondary thread, time to exit.
234 // DO NOT UNLOCK. Primary thread just came back from
235 // primaryHandleEvent() and will unlock in the else
236 // block below. Just wake it up.
237 synchronized (application
.primaryEventHandler
) {
238 application
.primaryEventHandler
.notify();
240 // Now eliminate my reference so that
241 // wakeEventHandler() resumes working on the primary.
242 application
.secondaryEventHandler
= null;
250 // Fire timers, update screen.
252 application
.finishEventProcessing();
255 } // while (true) (main runnable loop)
260 * The primary event handler thread.
262 private volatile WidgetEventHandler primaryEventHandler
;
265 * The secondary event handler thread.
267 private volatile WidgetEventHandler secondaryEventHandler
;
270 * The widget receiving events from the secondary event handler thread.
272 private volatile TWidget secondaryEventReceiver
;
275 * Wake the sleeping active event handler.
277 private void wakeEventHandler() {
278 if (secondaryEventHandler
!= null) {
279 synchronized (secondaryEventHandler
) {
280 secondaryEventHandler
.notify();
283 assert (primaryEventHandler
!= null);
284 synchronized (primaryEventHandler
) {
285 primaryEventHandler
.notify();
290 // ------------------------------------------------------------------------
291 // TApplication attributes ------------------------------------------------
292 // ------------------------------------------------------------------------
295 * Access to the physical screen, keyboard, and mouse.
297 private Backend backend
;
302 * @return the Backend
304 public final Backend
getBackend() {
313 public final Screen
getScreen() {
314 if (backend
instanceof TWindowBackend
) {
315 // We are being rendered to a TWindow. We can't use its
316 // getScreen() method because that is how it is rendering to a
317 // hardware backend somewhere. Instead use its getOtherScreen()
319 return ((TWindowBackend
) backend
).getOtherScreen();
321 return backend
.getScreen();
326 * Actual mouse coordinate X.
331 * Actual mouse coordinate Y.
336 * Old version of mouse coordinate X.
338 private int oldMouseX
;
341 * Old version mouse coordinate Y.
343 private int oldMouseY
;
346 * Event queue that is filled by run().
348 private List
<TInputEvent
> fillEventQueue
;
351 * Event queue that will be drained by either primary or secondary
354 private List
<TInputEvent
> drainEventQueue
;
357 * Top-level menus in this application.
359 private List
<TMenu
> menus
;
362 * Stack of activated sub-menus in this application.
364 private List
<TMenu
> subMenus
;
367 * The currently active menu.
369 private TMenu activeMenu
= null;
372 * Active keyboard accelerators.
374 private Map
<TKeypress
, TMenuItem
> accelerators
;
379 private List
<TMenuItem
> menuItems
;
382 * Windows and widgets pull colors from this ColorTheme.
384 private ColorTheme theme
;
387 * Get the color theme.
391 public final ColorTheme
getTheme() {
396 * The top-level windows (but not menus).
398 private List
<TWindow
> windows
;
401 * The currently acive window.
403 private TWindow activeWindow
= null;
406 * Timers that are being ticked.
408 private List
<TTimer
> timers
;
411 * When true, exit the application.
413 private volatile boolean quit
= false;
416 * When true, repaint the entire screen.
418 private volatile boolean repaint
= true;
421 * Repaint the screen on the next update.
423 public void doRepaint() {
429 * Y coordinate of the top edge of the desktop. For now this is a
430 * constant. Someday it would be nice to have a multi-line menu or
433 private static final int desktopTop
= 1;
436 * Get Y coordinate of the top edge of the desktop.
438 * @return Y coordinate of the top edge of the desktop
440 public final int getDesktopTop() {
445 * Y coordinate of the bottom edge of the desktop.
447 private int desktopBottom
;
450 * Get Y coordinate of the bottom edge of the desktop.
452 * @return Y coordinate of the bottom edge of the desktop
454 public final int getDesktopBottom() {
455 return desktopBottom
;
459 * An optional TDesktop background window that is drawn underneath
462 private TDesktop desktop
;
465 * Set the TDesktop instance.
467 * @param desktop a TDesktop instance, or null to remove the one that is
470 public final void setDesktop(final TDesktop desktop
) {
471 if (this.desktop
!= null) {
472 this.desktop
.onClose();
474 this.desktop
= desktop
;
478 * Get the TDesktop instance.
480 * @return the desktop, or null if it is not set
482 public final TDesktop
getDesktop() {
487 * Get the current active window.
489 * @return the active window, or null if it is not set
491 public final TWindow
getActiveWindow() {
496 * Get a (shallow) copy of the window list.
498 * @return a copy of the list of windows for this application
500 public final List
<TWindow
> getAllWindows() {
501 List
<TWindow
> result
= new LinkedList
<TWindow
>();
502 result
.addAll(windows
);
507 * If true, focus follows mouse: windows automatically raised if the
508 * mouse passes over them.
510 private boolean focusFollowsMouse
= false;
513 * Get focusFollowsMouse flag.
515 * @return true if focus follows mouse: windows automatically raised if
516 * the mouse passes over them
518 public boolean getFocusFollowsMouse() {
519 return focusFollowsMouse
;
523 * Set focusFollowsMouse flag.
525 * @param focusFollowsMouse if true, focus follows mouse: windows
526 * automatically raised if the mouse passes over them
528 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
529 this.focusFollowsMouse
= focusFollowsMouse
;
532 // ------------------------------------------------------------------------
533 // General behavior -------------------------------------------------------
534 // ------------------------------------------------------------------------
537 * Display the about dialog.
539 protected void showAboutDialog() {
540 messageBox("About", "Jexer Version " +
541 this.getClass().getPackage().getImplementationVersion(),
542 TMessageBox
.Type
.OK
);
545 // ------------------------------------------------------------------------
546 // Constructors -----------------------------------------------------------
547 // ------------------------------------------------------------------------
550 * Public constructor.
552 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
554 * @throws UnsupportedEncodingException if an exception is thrown when
555 * creating the InputStreamReader
557 public TApplication(final BackendType backendType
)
558 throws UnsupportedEncodingException
{
560 switch (backendType
) {
562 // The default SwingBackend is 80x25, 20 pt font. If you want to
563 // change that, you can pass the extra arguments to the
564 // SwingBackend constructor here. For example, if you wanted
565 // 90x30, 16 pt font:
567 // backend = new SwingBackend(this, 90, 30, 16);
568 backend
= new SwingBackend(this);
573 backend
= new ECMA48Backend(this, null, null);
576 throw new IllegalArgumentException("Invalid backend type: "
583 * Public constructor. The backend type will be BackendType.ECMA48.
585 * @param input an InputStream connected to the remote user, or null for
586 * System.in. If System.in is used, then on non-Windows systems it will
587 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
588 * mode. input is always converted to a Reader with UTF-8 encoding.
589 * @param output an OutputStream connected to the remote user, or null
590 * for System.out. output is always converted to a Writer with UTF-8
592 * @throws UnsupportedEncodingException if an exception is thrown when
593 * creating the InputStreamReader
595 public TApplication(final InputStream input
,
596 final OutputStream output
) throws UnsupportedEncodingException
{
598 backend
= new ECMA48Backend(this, input
, output
);
603 * Public constructor. The backend type will be BackendType.ECMA48.
605 * @param input the InputStream underlying 'reader'. Its available()
606 * method is used to determine if reader.read() will block or not.
607 * @param reader a Reader connected to the remote user.
608 * @param writer a PrintWriter connected to the remote user.
609 * @param setRawMode if true, set System.in into raw mode with stty.
610 * This should in general not be used. It is here solely for Demo3,
611 * which uses System.in.
612 * @throws IllegalArgumentException if input, reader, or writer are null.
614 public TApplication(final InputStream input
, final Reader reader
,
615 final PrintWriter writer
, final boolean setRawMode
) {
617 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
622 * Public constructor. The backend type will be BackendType.ECMA48.
624 * @param input the InputStream underlying 'reader'. Its available()
625 * method is used to determine if reader.read() will block or not.
626 * @param reader a Reader connected to the remote user.
627 * @param writer a PrintWriter connected to the remote user.
628 * @throws IllegalArgumentException if input, reader, or writer are null.
630 public TApplication(final InputStream input
, final Reader reader
,
631 final PrintWriter writer
) {
633 this(input
, reader
, writer
, false);
637 * Public constructor. This hook enables use with new non-Jexer
640 * @param backend a Backend that is already ready to go.
642 public TApplication(final Backend backend
) {
643 this.backend
= backend
;
644 backend
.setListener(this);
649 * Finish construction once the backend is set.
651 private void TApplicationImpl() {
652 theme
= new ColorTheme();
653 desktopBottom
= getScreen().getHeight() - 1;
654 fillEventQueue
= new ArrayList
<TInputEvent
>();
655 drainEventQueue
= new ArrayList
<TInputEvent
>();
656 windows
= new LinkedList
<TWindow
>();
657 menus
= new LinkedList
<TMenu
>();
658 subMenus
= new LinkedList
<TMenu
>();
659 timers
= new LinkedList
<TTimer
>();
660 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
661 menuItems
= new ArrayList
<TMenuItem
>();
662 desktop
= new TDesktop(this);
664 // Special case: the Swing backend needs to have a timer to drive its
666 if ((backend
instanceof SwingBackend
)
667 || (backend
instanceof MultiBackend
)
669 // Default to 500 millis, unless a SwingBackend has its own
672 if (backend
instanceof SwingBackend
) {
673 millis
= ((SwingBackend
) backend
).getBlinkMillis();
676 addTimer(millis
, true,
679 TApplication
.this.doRepaint();
687 // ------------------------------------------------------------------------
688 // Screen refresh loop ----------------------------------------------------
689 // ------------------------------------------------------------------------
692 * Process background events, and update the screen.
694 private void finishEventProcessing() {
696 System
.err
.printf(System
.currentTimeMillis() + " " +
697 Thread
.currentThread() + " finishEventProcessing()\n");
700 // Process timers and call doIdle()'s
704 synchronized (getScreen()) {
709 System
.err
.printf(System
.currentTimeMillis() + " " +
710 Thread
.currentThread() + " finishEventProcessing() END\n");
715 * Invert the cell color at a position. This is used to track the mouse.
717 * @param x column position
718 * @param y row position
720 private void invertCell(final int x
, final int y
) {
722 System
.err
.printf("%d %s invertCell() %d %d\n",
723 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
725 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
726 attr
.setForeColor(attr
.getForeColor().invert());
727 attr
.setBackColor(attr
.getBackColor().invert());
728 getScreen().putAttrXY(x
, y
, attr
, false);
734 private void drawAll() {
736 System
.err
.printf("%d %s drawAll() enter\n",
737 System
.currentTimeMillis(), Thread
.currentThread());
742 System
.err
.printf("%d %s drawAll() !repaint\n",
743 System
.currentTimeMillis(), Thread
.currentThread());
745 synchronized (getScreen()) {
746 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
747 // The only thing that has happened is the mouse moved.
748 // Clear the old position and draw the new position.
749 invertCell(oldMouseX
, oldMouseY
);
750 invertCell(mouseX
, mouseY
);
754 if (getScreen().isDirty()) {
755 backend
.flushScreen();
762 System
.err
.printf("%d %s drawAll() REDRAW\n",
763 System
.currentTimeMillis(), Thread
.currentThread());
766 // If true, the cursor is not visible
767 boolean cursor
= false;
769 // Start with a clean screen
773 if (desktop
!= null) {
774 desktop
.drawChildren();
777 // Draw each window in reverse Z order
778 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
779 Collections
.sort(sorted
);
780 TWindow topLevel
= null;
781 if (sorted
.size() > 0) {
782 topLevel
= sorted
.get(0);
784 Collections
.reverse(sorted
);
785 for (TWindow window
: sorted
) {
786 if (window
.isShown()) {
787 window
.drawChildren();
791 // Draw the blank menubar line - reset the screen clipping first so
792 // it won't trim it out.
793 getScreen().resetClipping();
794 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
795 theme
.getColor("tmenu"));
796 // Now draw the menus.
798 for (TMenu menu
: menus
) {
799 CellAttributes menuColor
;
800 CellAttributes menuMnemonicColor
;
801 if (menu
.isActive()) {
802 menuColor
= theme
.getColor("tmenu.highlighted");
803 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
806 menuColor
= theme
.getColor("tmenu");
807 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
809 // Draw the menu title
810 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
812 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
813 // Draw the highlight character
814 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
815 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
817 if (menu
.isActive()) {
819 // Reset the screen clipping so we can draw the next title.
820 getScreen().resetClipping();
822 x
+= menu
.getTitle().length() + 2;
825 for (TMenu menu
: subMenus
) {
826 // Reset the screen clipping so we can draw the next sub-menu.
827 getScreen().resetClipping();
831 // Draw the status bar of the top-level window
832 TStatusBar statusBar
= null;
833 if (topLevel
!= null) {
834 statusBar
= topLevel
.getStatusBar();
836 if (statusBar
!= null) {
837 getScreen().resetClipping();
838 statusBar
.setWidth(getScreen().getWidth());
839 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
842 CellAttributes barColor
= new CellAttributes();
843 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
844 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
848 // Draw the mouse pointer
849 invertCell(mouseX
, mouseY
);
853 // Place the cursor if it is visible
854 TWidget activeWidget
= null;
855 if (sorted
.size() > 0) {
856 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
857 if (activeWidget
.isCursorVisible()) {
858 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
859 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
861 getScreen().putCursor(true,
862 activeWidget
.getCursorAbsoluteX(),
863 activeWidget
.getCursorAbsoluteY());
866 getScreen().putCursor(false,
867 activeWidget
.getCursorAbsoluteX(),
868 activeWidget
.getCursorAbsoluteY());
876 getScreen().hideCursor();
879 // Flush the screen contents
880 if (getScreen().isDirty()) {
881 backend
.flushScreen();
887 // ------------------------------------------------------------------------
888 // Main loop --------------------------------------------------------------
889 // ------------------------------------------------------------------------
892 * Force this application to exit.
896 synchronized (this) {
902 * Run this application until it exits.
905 // Start the main consumer thread
906 primaryEventHandler
= new WidgetEventHandler(this, true);
907 (new Thread(primaryEventHandler
)).start();
910 synchronized (this) {
911 boolean doWait
= false;
913 synchronized (fillEventQueue
) {
914 if (fillEventQueue
.size() == 0) {
920 // No I/O to dispatch, so wait until the backend
924 System
.err
.println(System
.currentTimeMillis() +
931 System
.err
.println(System
.currentTimeMillis() +
934 } catch (InterruptedException e
) {
935 // I'm awake and don't care why, let's see what's
936 // going on out there.
940 } // synchronized (this)
942 synchronized (fillEventQueue
) {
943 // Pull any pending I/O events
944 backend
.getEvents(fillEventQueue
);
946 // Dispatch each event to the appropriate handler, one at a
949 TInputEvent event
= null;
950 if (fillEventQueue
.size() == 0) {
953 event
= fillEventQueue
.remove(0);
954 metaHandleEvent(event
);
958 // Wake a consumer thread if we have any pending events.
959 if (drainEventQueue
.size() > 0) {
965 // Shutdown the event consumer threads
966 if (secondaryEventHandler
!= null) {
967 synchronized (secondaryEventHandler
) {
968 secondaryEventHandler
.notify();
971 if (primaryEventHandler
!= null) {
972 synchronized (primaryEventHandler
) {
973 primaryEventHandler
.notify();
977 // Shutdown the user I/O thread(s)
980 // Close all the windows. This gives them an opportunity to release
987 * Peek at certain application-level events, add to eventQueue, and wake
988 * up the consuming Thread.
990 * @param event the input event to consume
992 private void metaHandleEvent(final TInputEvent event
) {
995 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
996 event
)); System
.err
.flush();
1000 // Do no more processing if the application is already trying
1005 // Special application-wide events -------------------------------
1008 if (event
instanceof TCommandEvent
) {
1009 TCommandEvent command
= (TCommandEvent
) event
;
1010 if (command
.getCmd().equals(cmAbort
)) {
1016 synchronized (drainEventQueue
) {
1018 if (event
instanceof TResizeEvent
) {
1019 TResizeEvent resize
= (TResizeEvent
) event
;
1020 synchronized (getScreen()) {
1021 getScreen().setDimensions(resize
.getWidth(),
1022 resize
.getHeight());
1023 desktopBottom
= getScreen().getHeight() - 1;
1029 if (desktop
!= null) {
1030 desktop
.setDimensions(0, 0, resize
.getWidth(),
1031 resize
.getHeight() - 1);
1033 // We are dirty, redraw the screen.
1038 // Put into the main queue
1039 drainEventQueue
.add(event
);
1044 * Dispatch one event to the appropriate widget or application-level
1045 * event handler. This is the primary event handler, it has the normal
1046 * application-wide event handling.
1048 * @param event the input event to consume
1049 * @see #secondaryHandleEvent(TInputEvent event)
1051 private void primaryHandleEvent(final TInputEvent event
) {
1054 System
.err
.printf("Handle event: %s\n", event
);
1057 // Special application-wide events -----------------------------------
1059 // Peek at the mouse position
1060 if (event
instanceof TMouseEvent
) {
1061 TMouseEvent mouse
= (TMouseEvent
) event
;
1062 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1065 mouseX
= mouse
.getX();
1066 mouseY
= mouse
.getY();
1069 // See if we need to switch focus to another window or the menu
1070 checkSwitchFocus((TMouseEvent
) event
);
1073 // Handle menu events
1074 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1075 TMenu menu
= activeMenu
;
1077 if (event
instanceof TMouseEvent
) {
1078 TMouseEvent mouse
= (TMouseEvent
) event
;
1080 while (subMenus
.size() > 0) {
1081 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1082 if (subMenu
.mouseWouldHit(mouse
)) {
1085 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1086 && (!mouse
.isMouse1())
1087 && (!mouse
.isMouse2())
1088 && (!mouse
.isMouse3())
1089 && (!mouse
.isMouseWheelUp())
1090 && (!mouse
.isMouseWheelDown())
1094 // We navigated away from a sub-menu, so close it
1098 // Convert the mouse relative x/y to menu coordinates
1099 assert (mouse
.getX() == mouse
.getAbsoluteX());
1100 assert (mouse
.getY() == mouse
.getAbsoluteY());
1101 if (subMenus
.size() > 0) {
1102 menu
= subMenus
.get(subMenus
.size() - 1);
1104 mouse
.setX(mouse
.getX() - menu
.getX());
1105 mouse
.setY(mouse
.getY() - menu
.getY());
1107 menu
.handleEvent(event
);
1111 if (event
instanceof TKeypressEvent
) {
1112 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1114 // See if this key matches an accelerator, and is not being
1115 // shortcutted by the active window, and if so dispatch the menu
1117 boolean windowWillShortcut
= false;
1118 if (activeWindow
!= null) {
1119 assert (activeWindow
.isShown());
1120 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1121 // We do not process this key, it will be passed to the
1123 windowWillShortcut
= true;
1127 if (!windowWillShortcut
&& !modalWindowActive()) {
1128 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1129 TMenuItem item
= null;
1130 synchronized (accelerators
) {
1131 item
= accelerators
.get(keypressLowercase
);
1134 if (item
.isEnabled()) {
1135 // Let the menu item dispatch
1141 // Handle the keypress
1142 if (onKeypress(keypress
)) {
1148 if (event
instanceof TCommandEvent
) {
1149 if (onCommand((TCommandEvent
) event
)) {
1154 if (event
instanceof TMenuEvent
) {
1155 if (onMenu((TMenuEvent
) event
)) {
1160 // Dispatch events to the active window -------------------------------
1161 boolean dispatchToDesktop
= true;
1162 TWindow window
= activeWindow
;
1163 if (window
!= null) {
1164 assert (window
.isActive());
1165 assert (window
.isShown());
1166 if (event
instanceof TMouseEvent
) {
1167 TMouseEvent mouse
= (TMouseEvent
) event
;
1168 // Convert the mouse relative x/y to window coordinates
1169 assert (mouse
.getX() == mouse
.getAbsoluteX());
1170 assert (mouse
.getY() == mouse
.getAbsoluteY());
1171 mouse
.setX(mouse
.getX() - window
.getX());
1172 mouse
.setY(mouse
.getY() - window
.getY());
1174 if (window
.mouseWouldHit(mouse
)) {
1175 dispatchToDesktop
= false;
1177 } else if (event
instanceof TKeypressEvent
) {
1178 dispatchToDesktop
= false;
1182 System
.err
.printf("TApplication dispatch event: %s\n",
1185 window
.handleEvent(event
);
1187 if (dispatchToDesktop
) {
1188 // This event is fair game for the desktop to process.
1189 if (desktop
!= null) {
1190 desktop
.handleEvent(event
);
1196 * Dispatch one event to the appropriate widget or application-level
1197 * event handler. This is the secondary event handler used by certain
1198 * special dialogs (currently TMessageBox and TFileOpenBox).
1200 * @param event the input event to consume
1201 * @see #primaryHandleEvent(TInputEvent event)
1203 private void secondaryHandleEvent(final TInputEvent event
) {
1204 // Peek at the mouse position
1205 if (event
instanceof TMouseEvent
) {
1206 TMouseEvent mouse
= (TMouseEvent
) event
;
1207 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1210 mouseX
= mouse
.getX();
1211 mouseY
= mouse
.getY();
1215 secondaryEventReceiver
.handleEvent(event
);
1219 * Enable a widget to override the primary event thread.
1221 * @param widget widget that will receive events
1223 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1225 System
.err
.println(System
.currentTimeMillis() +
1226 " enableSecondaryEventReceiver()");
1229 assert (secondaryEventReceiver
== null);
1230 assert (secondaryEventHandler
== null);
1231 assert ((widget
instanceof TMessageBox
)
1232 || (widget
instanceof TFileOpenBox
));
1233 secondaryEventReceiver
= widget
;
1234 secondaryEventHandler
= new WidgetEventHandler(this, false);
1236 (new Thread(secondaryEventHandler
)).start();
1240 * Yield to the secondary thread.
1242 public final void yield() {
1243 assert (secondaryEventReceiver
!= null);
1245 while (secondaryEventReceiver
!= null) {
1246 synchronized (primaryEventHandler
) {
1248 primaryEventHandler
.wait();
1249 } catch (InterruptedException e
) {
1257 * Do stuff when there is no user input.
1259 private void doIdle() {
1261 System
.err
.printf(System
.currentTimeMillis() + " " +
1262 Thread
.currentThread() + " doIdle()\n");
1265 synchronized (timers
) {
1268 System
.err
.printf(System
.currentTimeMillis() + " " +
1269 Thread
.currentThread() + " doIdle() 2\n");
1272 // Run any timers that have timed out
1273 Date now
= new Date();
1274 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1275 for (TTimer timer
: timers
) {
1276 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1277 // Something might change, so repaint the screen.
1280 if (timer
.recurring
) {
1281 keepTimers
.add(timer
);
1284 keepTimers
.add(timer
);
1287 timers
= keepTimers
;
1291 for (TWindow window
: windows
) {
1294 if (desktop
!= null) {
1299 // ------------------------------------------------------------------------
1300 // TWindow management -----------------------------------------------------
1301 // ------------------------------------------------------------------------
1304 * Return the total number of windows.
1306 * @return the total number of windows
1308 public final int windowCount() {
1309 return windows
.size();
1313 * Return the number of windows that are showing.
1315 * @return the number of windows that are showing on screen
1317 public final int shownWindowCount() {
1319 for (TWindow w
: windows
) {
1328 * Return the number of windows that are hidden.
1330 * @return the number of windows that are hidden
1332 public final int hiddenWindowCount() {
1334 for (TWindow w
: windows
) {
1343 * Check if a window instance is in this application's window list.
1345 * @param window window to look for
1346 * @return true if this window is in the list
1348 public final boolean hasWindow(final TWindow window
) {
1349 if (windows
.size() == 0) {
1352 for (TWindow w
: windows
) {
1354 assert (window
.getApplication() == this);
1362 * Activate a window: bring it to the top and have it receive events.
1364 * @param window the window to become the new active window
1366 public void activateWindow(final TWindow window
) {
1367 if (hasWindow(window
) == false) {
1369 * Someone has a handle to a window I don't have. Ignore this
1375 // Whatever window might be moving/dragging, stop it now.
1376 for (TWindow w
: windows
) {
1377 if (w
.inMovements()) {
1382 assert (windows
.size() > 0);
1384 if (window
.isHidden()) {
1385 // Unhiding will also activate.
1389 assert (window
.isShown());
1391 if (windows
.size() == 1) {
1392 assert (window
== windows
.get(0));
1393 if (activeWindow
== null) {
1394 activeWindow
= window
;
1396 activeWindow
.setActive(true);
1397 activeWindow
.onFocus();
1400 assert (window
.isActive());
1401 assert (activeWindow
== window
);
1405 if (activeWindow
== window
) {
1406 assert (window
.isActive());
1408 // Window is already active, do nothing.
1412 assert (!window
.isActive());
1413 if (activeWindow
!= null) {
1414 assert (activeWindow
.getZ() == 0);
1416 activeWindow
.onUnfocus();
1417 activeWindow
.setActive(false);
1418 activeWindow
.setZ(window
.getZ());
1420 activeWindow
= window
;
1421 activeWindow
.setZ(0);
1422 activeWindow
.setActive(true);
1423 activeWindow
.onFocus();
1430 * @param window the window to hide
1432 public void hideWindow(final TWindow window
) {
1433 if (hasWindow(window
) == false) {
1435 * Someone has a handle to a window I don't have. Ignore this
1441 // Whatever window might be moving/dragging, stop it now.
1442 for (TWindow w
: windows
) {
1443 if (w
.inMovements()) {
1448 assert (windows
.size() > 0);
1450 if (!window
.hidden
) {
1451 if (window
== activeWindow
) {
1452 if (shownWindowCount() > 1) {
1455 activeWindow
= null;
1456 window
.setActive(false);
1460 window
.hidden
= true;
1468 * @param window the window to show
1470 public void showWindow(final TWindow window
) {
1471 if (hasWindow(window
) == false) {
1473 * Someone has a handle to a window I don't have. Ignore this
1479 // Whatever window might be moving/dragging, stop it now.
1480 for (TWindow w
: windows
) {
1481 if (w
.inMovements()) {
1486 assert (windows
.size() > 0);
1488 if (window
.hidden
) {
1489 window
.hidden
= false;
1491 activateWindow(window
);
1496 * Close window. Note that the window's destructor is NOT called by this
1497 * method, instead the GC is assumed to do the cleanup.
1499 * @param window the window to remove
1501 public final void closeWindow(final TWindow window
) {
1502 if (hasWindow(window
) == false) {
1504 * Someone has a handle to a window I don't have. Ignore this
1510 synchronized (windows
) {
1511 // Whatever window might be moving/dragging, stop it now.
1512 for (TWindow w
: windows
) {
1513 if (w
.inMovements()) {
1518 int z
= window
.getZ();
1521 Collections
.sort(windows
);
1523 activeWindow
= null;
1524 for (TWindow w
: windows
) {
1526 w
.setZ(w
.getZ() - 1);
1527 if (w
.getZ() == 0) {
1530 assert (activeWindow
== null);
1542 // Perform window cleanup
1545 // Check if we are closing a TMessageBox or similar
1546 if (secondaryEventReceiver
!= null) {
1547 assert (secondaryEventHandler
!= null);
1549 // Do not send events to the secondaryEventReceiver anymore, the
1550 // window is closed.
1551 secondaryEventReceiver
= null;
1553 // Wake the secondary thread, it will wake the primary as it
1555 synchronized (secondaryEventHandler
) {
1556 secondaryEventHandler
.notify();
1560 // Permit desktop to be active if it is the only thing left.
1561 if (desktop
!= null) {
1562 if (windows
.size() == 0) {
1563 desktop
.setActive(true);
1569 * Switch to the next window.
1571 * @param forward if true, then switch to the next window in the list,
1572 * otherwise switch to the previous window in the list
1574 public final void switchWindow(final boolean forward
) {
1575 // Only switch if there are multiple visible windows
1576 if (shownWindowCount() < 2) {
1579 assert (activeWindow
!= null);
1581 synchronized (windows
) {
1582 // Whatever window might be moving/dragging, stop it now.
1583 for (TWindow w
: windows
) {
1584 if (w
.inMovements()) {
1589 // Swap z/active between active window and the next in the list
1590 int activeWindowI
= -1;
1591 for (int i
= 0; i
< windows
.size(); i
++) {
1592 if (windows
.get(i
) == activeWindow
) {
1593 assert (activeWindow
.isActive());
1597 assert (!windows
.get(0).isActive());
1600 assert (activeWindowI
>= 0);
1602 // Do not switch if a window is modal
1603 if (activeWindow
.isModal()) {
1607 int nextWindowI
= activeWindowI
;
1611 nextWindowI
%= windows
.size();
1614 if (nextWindowI
< 0) {
1615 nextWindowI
= windows
.size() - 1;
1619 if (windows
.get(nextWindowI
).isShown()) {
1620 activateWindow(windows
.get(nextWindowI
));
1624 } // synchronized (windows)
1629 * Add a window to my window list and make it active.
1631 * @param window new window to add
1633 public final void addWindow(final TWindow window
) {
1635 // Do not add menu windows to the window list.
1636 if (window
instanceof TMenu
) {
1640 // Do not add the desktop to the window list.
1641 if (window
instanceof TDesktop
) {
1645 synchronized (windows
) {
1646 // Whatever window might be moving/dragging, stop it now.
1647 for (TWindow w
: windows
) {
1648 if (w
.inMovements()) {
1653 // Do not allow a modal window to spawn a non-modal window. If a
1654 // modal window is active, then this window will become modal
1656 if (modalWindowActive()) {
1657 window
.flags
|= TWindow
.MODAL
;
1658 window
.flags
|= TWindow
.CENTERED
;
1659 window
.hidden
= false;
1661 if (window
.isShown()) {
1662 for (TWindow w
: windows
) {
1667 w
.setZ(w
.getZ() + 1);
1670 windows
.add(window
);
1671 if (window
.isShown()) {
1672 activeWindow
= window
;
1673 activeWindow
.setZ(0);
1674 activeWindow
.setActive(true);
1675 activeWindow
.onFocus();
1678 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1679 && smartWindowPlacement
) {
1681 doSmartPlacement(window
);
1685 // Desktop cannot be active over any other window.
1686 if (desktop
!= null) {
1687 desktop
.setActive(false);
1692 * Check if there is a system-modal window on top.
1694 * @return true if the active window is modal
1696 private boolean modalWindowActive() {
1697 if (windows
.size() == 0) {
1701 for (TWindow w
: windows
) {
1711 * Close all open windows.
1713 private void closeAllWindows() {
1714 // Don't do anything if we are in the menu
1715 if (activeMenu
!= null) {
1718 while (windows
.size() > 0) {
1719 closeWindow(windows
.get(0));
1724 * Re-layout the open windows as non-overlapping tiles. This produces
1725 * almost the same results as Turbo Pascal 7.0's IDE.
1727 private void tileWindows() {
1728 synchronized (windows
) {
1729 // Don't do anything if we are in the menu
1730 if (activeMenu
!= null) {
1733 int z
= windows
.size();
1739 a
= (int)(Math
.sqrt(z
));
1743 if (((a
* b
) + c
) == z
) {
1751 int newWidth
= (getScreen().getWidth() / a
);
1752 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1753 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1755 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1756 Collections
.sort(sorted
);
1757 Collections
.reverse(sorted
);
1758 for (int i
= 0; i
< sorted
.size(); i
++) {
1759 int logicalX
= i
/ b
;
1760 int logicalY
= i
% b
;
1761 if (i
>= ((a
- 1) * b
)) {
1763 logicalY
= i
- ((a
- 1) * b
);
1766 TWindow w
= sorted
.get(i
);
1767 w
.setX(logicalX
* newWidth
);
1768 w
.setWidth(newWidth
);
1769 if (i
>= ((a
- 1) * b
)) {
1770 w
.setY((logicalY
* newHeight2
) + 1);
1771 w
.setHeight(newHeight2
);
1773 w
.setY((logicalY
* newHeight1
) + 1);
1774 w
.setHeight(newHeight1
);
1781 * Re-layout the open windows as overlapping cascaded windows.
1783 private void cascadeWindows() {
1784 synchronized (windows
) {
1785 // Don't do anything if we are in the menu
1786 if (activeMenu
!= null) {
1791 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1792 Collections
.sort(sorted
);
1793 Collections
.reverse(sorted
);
1794 for (TWindow window
: sorted
) {
1799 if (x
> getScreen().getWidth()) {
1802 if (y
>= getScreen().getHeight()) {
1810 * Place a window to minimize its overlap with other windows.
1812 * @param window the window to place
1814 public final void doSmartPlacement(final TWindow window
) {
1815 // This is a pretty dumb algorithm, but seems to work. The hardest
1816 // part is computing these "overlap" values seeking a minimum average
1819 int yMin
= desktopTop
;
1820 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1821 int yMax
= desktopBottom
- window
.getHeight() + 1;
1829 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1830 // No work to do, bail out.
1834 // Compute the overlap matrix without the new window.
1835 int width
= getScreen().getWidth();
1836 int height
= getScreen().getHeight();
1837 int overlapMatrix
[][] = new int[width
][height
];
1838 for (TWindow w
: windows
) {
1842 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1846 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1850 overlapMatrix
[x
][y
]++;
1855 long oldOverlapTotal
= 0;
1856 long oldOverlapN
= 0;
1857 for (int x
= 0; x
< width
; x
++) {
1858 for (int y
= 0; y
< height
; y
++) {
1859 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1860 if (overlapMatrix
[x
][y
] > 0) {
1867 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1868 boolean first
= true;
1869 int windowX
= window
.getX();
1870 int windowY
= window
.getY();
1872 // For each possible (x, y) position for the new window, compute a
1873 // new overlap matrix.
1874 for (int x
= xMin
; x
< xMax
; x
++) {
1875 for (int y
= yMin
; y
< yMax
; y
++) {
1877 // Start with the matrix minus this window.
1878 int newMatrix
[][] = new int[width
][height
];
1879 for (int mx
= 0; mx
< width
; mx
++) {
1880 for (int my
= 0; my
< height
; my
++) {
1881 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1885 // Add this window's values to the new overlap matrix.
1886 long newOverlapTotal
= 0;
1887 long newOverlapN
= 0;
1888 // Start by adding each new cell.
1889 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1893 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1897 newMatrix
[wx
][wy
]++;
1900 // Now figure out the new value for total coverage.
1901 for (int mx
= 0; mx
< width
; mx
++) {
1902 for (int my
= 0; my
< height
; my
++) {
1903 newOverlapTotal
+= newMatrix
[x
][y
];
1904 if (newMatrix
[mx
][my
] > 0) {
1909 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1912 // First time: just record what we got.
1913 oldOverlapAvg
= newOverlapAvg
;
1916 // All other times: pick a new best (x, y) and save the
1918 if (newOverlapAvg
< oldOverlapAvg
) {
1921 oldOverlapAvg
= newOverlapAvg
;
1925 } // for (int x = xMin; x < xMax; x++)
1927 } // for (int y = yMin; y < yMax; y++)
1929 // Finally, set the window's new coordinates.
1930 window
.setX(windowX
);
1931 window
.setY(windowY
);
1934 // ------------------------------------------------------------------------
1935 // TMenu management -------------------------------------------------------
1936 // ------------------------------------------------------------------------
1939 * Check if a mouse event would hit either the active menu or any open
1942 * @param mouse mouse event
1943 * @return true if the mouse would hit the active menu or an open
1946 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1947 assert (activeMenu
!= null);
1948 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1949 Collections
.reverse(menus
);
1950 for (TMenu menu
: menus
) {
1951 if (menu
.mouseWouldHit(mouse
)) {
1955 return activeMenu
.mouseWouldHit(mouse
);
1959 * See if we need to switch window or activate the menu based on
1962 * @param mouse mouse event
1964 private void checkSwitchFocus(final TMouseEvent mouse
) {
1966 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1967 && (activeMenu
!= null)
1968 && (mouse
.getAbsoluteY() != 0)
1969 && (!mouseOnMenu(mouse
))
1971 // They clicked outside the active menu, turn it off
1972 activeMenu
.setActive(false);
1974 for (TMenu menu
: subMenus
) {
1975 menu
.setActive(false);
1981 // See if they hit the menu bar
1982 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1983 && (mouse
.isMouse1())
1984 && (!modalWindowActive())
1985 && (mouse
.getAbsoluteY() == 0)
1988 for (TMenu menu
: subMenus
) {
1989 menu
.setActive(false);
1993 // They selected the menu, go activate it
1994 for (TMenu menu
: menus
) {
1995 if ((mouse
.getAbsoluteX() >= menu
.getX())
1996 && (mouse
.getAbsoluteX() < menu
.getX()
1997 + menu
.getTitle().length() + 2)
1999 menu
.setActive(true);
2002 menu
.setActive(false);
2008 // See if they hit the menu bar
2009 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2010 && (mouse
.isMouse1())
2011 && (activeMenu
!= null)
2012 && (mouse
.getAbsoluteY() == 0)
2015 TMenu oldMenu
= activeMenu
;
2016 for (TMenu menu
: subMenus
) {
2017 menu
.setActive(false);
2021 // See if we should switch menus
2022 for (TMenu menu
: menus
) {
2023 if ((mouse
.getAbsoluteX() >= menu
.getX())
2024 && (mouse
.getAbsoluteX() < menu
.getX()
2025 + menu
.getTitle().length() + 2)
2027 menu
.setActive(true);
2031 if (oldMenu
!= activeMenu
) {
2032 // They switched menus
2033 oldMenu
.setActive(false);
2038 // If a menu is still active, don't switch windows
2039 if (activeMenu
!= null) {
2043 // Only switch if there are multiple windows
2044 if (windows
.size() < 2) {
2048 if (((focusFollowsMouse
== true)
2049 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2050 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2052 synchronized (windows
) {
2053 Collections
.sort(windows
);
2054 if (windows
.get(0).isModal()) {
2055 // Modal windows don't switch
2059 for (TWindow window
: windows
) {
2060 assert (!window
.isModal());
2062 if (window
.isHidden()) {
2063 assert (!window
.isActive());
2067 if (window
.mouseWouldHit(mouse
)) {
2068 if (window
== windows
.get(0)) {
2069 // Clicked on the same window, nothing to do
2070 assert (window
.isActive());
2074 // We will be switching to another window
2075 assert (windows
.get(0).isActive());
2076 assert (windows
.get(0) == activeWindow
);
2077 assert (!window
.isActive());
2078 activeWindow
.onUnfocus();
2079 activeWindow
.setActive(false);
2080 activeWindow
.setZ(window
.getZ());
2081 activeWindow
= window
;
2083 window
.setActive(true);
2090 // Clicked on the background, nothing to do
2094 // Nothing to do: this isn't a mouse up, or focus isn't following
2100 * Turn off the menu.
2102 public final void closeMenu() {
2103 if (activeMenu
!= null) {
2104 activeMenu
.setActive(false);
2106 for (TMenu menu
: subMenus
) {
2107 menu
.setActive(false);
2114 * Get a (shallow) copy of the menu list.
2116 * @return a copy of the menu list
2118 public final List
<TMenu
> getAllMenus() {
2119 return new LinkedList
<TMenu
>(menus
);
2123 * Add a top-level menu to the list.
2125 * @param menu the menu to add
2126 * @throws IllegalArgumentException if the menu is already used in
2127 * another TApplication
2129 public final void addMenu(final TMenu menu
) {
2130 if ((menu
.getApplication() != null)
2131 && (menu
.getApplication() != this)
2133 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2134 "part of application " + menu
.getApplication());
2142 * Remove a top-level menu from the list.
2144 * @param menu the menu to remove
2145 * @throws IllegalArgumentException if the menu is already used in
2146 * another TApplication
2148 public final void removeMenu(final TMenu menu
) {
2149 if ((menu
.getApplication() != null)
2150 && (menu
.getApplication() != this)
2152 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2153 "part of application " + menu
.getApplication());
2161 * Turn off a sub-menu.
2163 public final void closeSubMenu() {
2164 assert (activeMenu
!= null);
2165 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2166 assert (item
!= null);
2167 item
.setActive(false);
2168 subMenus
.remove(subMenus
.size() - 1);
2172 * Switch to the next menu.
2174 * @param forward if true, then switch to the next menu in the list,
2175 * otherwise switch to the previous menu in the list
2177 public final void switchMenu(final boolean forward
) {
2178 assert (activeMenu
!= null);
2180 for (TMenu menu
: subMenus
) {
2181 menu
.setActive(false);
2185 for (int i
= 0; i
< menus
.size(); i
++) {
2186 if (activeMenu
== menus
.get(i
)) {
2188 if (i
< menus
.size() - 1) {
2196 activeMenu
.setActive(false);
2197 activeMenu
= menus
.get(i
);
2198 activeMenu
.setActive(true);
2205 * Add a menu item to the global list. If it has a keyboard accelerator,
2206 * that will be added the global hash.
2208 * @param item the menu item
2210 public final void addMenuItem(final TMenuItem item
) {
2211 menuItems
.add(item
);
2213 TKeypress key
= item
.getKey();
2215 synchronized (accelerators
) {
2216 assert (accelerators
.get(key
) == null);
2217 accelerators
.put(key
.toLowerCase(), item
);
2223 * Disable one menu item.
2225 * @param id the menu item ID
2227 public final void disableMenuItem(final int id
) {
2228 for (TMenuItem item
: menuItems
) {
2229 if (item
.getId() == id
) {
2230 item
.setEnabled(false);
2236 * Disable the range of menu items with ID's between lower and upper,
2239 * @param lower the lowest menu item ID
2240 * @param upper the highest menu item ID
2242 public final void disableMenuItems(final int lower
, final int upper
) {
2243 for (TMenuItem item
: menuItems
) {
2244 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2245 item
.setEnabled(false);
2251 * Enable one menu item.
2253 * @param id the menu item ID
2255 public final void enableMenuItem(final int id
) {
2256 for (TMenuItem item
: menuItems
) {
2257 if (item
.getId() == id
) {
2258 item
.setEnabled(true);
2264 * Enable the range of menu items with ID's between lower and upper,
2267 * @param lower the lowest menu item ID
2268 * @param upper the highest menu item ID
2270 public final void enableMenuItems(final int lower
, final int upper
) {
2271 for (TMenuItem item
: menuItems
) {
2272 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2273 item
.setEnabled(true);
2279 * Recompute menu x positions based on their title length.
2281 public final void recomputeMenuX() {
2283 for (TMenu menu
: menus
) {
2285 x
+= menu
.getTitle().length() + 2;
2290 * Post an event to process and turn off the menu.
2292 * @param event new event to add to the queue
2294 public final void postMenuEvent(final TInputEvent event
) {
2295 synchronized (this) {
2296 synchronized (fillEventQueue
) {
2297 fillEventQueue
.add(event
);
2300 System
.err
.println(System
.currentTimeMillis() + " " +
2301 Thread
.currentThread() + " postMenuEvent() wake up main");
2309 * Add a sub-menu to the list of open sub-menus.
2311 * @param menu sub-menu
2313 public final void addSubMenu(final TMenu menu
) {
2318 * Convenience function to add a top-level menu.
2320 * @param title menu title
2321 * @return the new menu
2323 public final TMenu
addMenu(final String title
) {
2326 TMenu menu
= new TMenu(this, x
, y
, title
);
2333 * Convenience function to add a default "File" menu.
2335 * @return the new menu
2337 public final TMenu
addFileMenu() {
2338 TMenu fileMenu
= addMenu("&File");
2339 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2340 fileMenu
.addSeparator();
2341 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2342 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2343 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2344 "commands (Open, Save, Print, etc.)");
2345 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2350 * Convenience function to add a default "Edit" menu.
2352 * @return the new menu
2354 public final TMenu
addEditMenu() {
2355 TMenu editMenu
= addMenu("&Edit");
2356 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2357 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2358 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2359 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2360 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2361 "undo, and Clipboard access");
2362 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2367 * Convenience function to add a default "Window" menu.
2369 * @return the new menu
2371 public final TMenu
addWindowMenu() {
2372 TMenu windowMenu
= addMenu("&Window");
2373 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2374 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2375 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2376 windowMenu
.addSeparator();
2377 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2378 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2379 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2380 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2381 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2382 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2384 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2389 * Convenience function to add a default "Help" menu.
2391 * @return the new menu
2393 public final TMenu
addHelpMenu() {
2394 TMenu helpMenu
= addMenu("&Help");
2395 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2396 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2397 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2398 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2399 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2400 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2401 helpMenu
.addSeparator();
2402 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2403 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2404 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2408 // ------------------------------------------------------------------------
2409 // Event handlers ---------------------------------------------------------
2410 // ------------------------------------------------------------------------
2413 * Method that TApplication subclasses can override to handle menu or
2414 * posted command events.
2416 * @param command command event
2417 * @return if true, this event was consumed
2419 protected boolean onCommand(final TCommandEvent command
) {
2420 // Default: handle cmExit
2421 if (command
.equals(cmExit
)) {
2422 if (messageBox("Confirmation", "Exit application?",
2423 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2429 if (command
.equals(cmShell
)) {
2430 openTerminal(0, 0, TWindow
.RESIZABLE
);
2434 if (command
.equals(cmTile
)) {
2438 if (command
.equals(cmCascade
)) {
2442 if (command
.equals(cmCloseAll
)) {
2447 if (command
.equals(cmMenu
)) {
2448 if (!modalWindowActive() && (activeMenu
== null)) {
2449 if (menus
.size() > 0) {
2450 menus
.get(0).setActive(true);
2451 activeMenu
= menus
.get(0);
2461 * Method that TApplication subclasses can override to handle menu
2464 * @param menu menu event
2465 * @return if true, this event was consumed
2467 protected boolean onMenu(final TMenuEvent menu
) {
2469 // Default: handle MID_EXIT
2470 if (menu
.getId() == TMenu
.MID_EXIT
) {
2471 if (messageBox("Confirmation", "Exit application?",
2472 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2478 if (menu
.getId() == TMenu
.MID_SHELL
) {
2479 openTerminal(0, 0, TWindow
.RESIZABLE
);
2483 if (menu
.getId() == TMenu
.MID_TILE
) {
2487 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2491 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2495 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2503 * Method that TApplication subclasses can override to handle keystrokes.
2505 * @param keypress keystroke event
2506 * @return if true, this event was consumed
2508 protected boolean onKeypress(final TKeypressEvent keypress
) {
2509 // Default: only menu shortcuts
2511 // Process Alt-F, Alt-E, etc. menu shortcut keys
2512 if (!keypress
.getKey().isFnKey()
2513 && keypress
.getKey().isAlt()
2514 && !keypress
.getKey().isCtrl()
2515 && (activeMenu
== null)
2516 && !modalWindowActive()
2519 assert (subMenus
.size() == 0);
2521 for (TMenu menu
: menus
) {
2522 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2523 == Character
.toLowerCase(keypress
.getKey().getChar())
2526 menu
.setActive(true);
2535 // ------------------------------------------------------------------------
2536 // TTimer management ------------------------------------------------------
2537 // ------------------------------------------------------------------------
2540 * Get the amount of time I can sleep before missing a Timer tick.
2542 * @param timeout = initial (maximum) timeout in millis
2543 * @return number of milliseconds between now and the next timer event
2545 private long getSleepTime(final long timeout
) {
2546 Date now
= new Date();
2547 long nowTime
= now
.getTime();
2548 long sleepTime
= timeout
;
2550 synchronized (timers
) {
2551 for (TTimer timer
: timers
) {
2552 long nextTickTime
= timer
.getNextTick().getTime();
2553 if (nextTickTime
< nowTime
) {
2557 long timeDifference
= nextTickTime
- nowTime
;
2558 if (timeDifference
< sleepTime
) {
2559 sleepTime
= timeDifference
;
2564 assert (sleepTime
>= 0);
2565 assert (sleepTime
<= timeout
);
2570 * Convenience function to add a timer.
2572 * @param duration number of milliseconds to wait between ticks
2573 * @param recurring if true, re-schedule this timer after every tick
2574 * @param action function to call when button is pressed
2577 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2578 final TAction action
) {
2580 TTimer timer
= new TTimer(duration
, recurring
, action
);
2581 synchronized (timers
) {
2588 * Convenience function to remove a timer.
2590 * @param timer timer to remove
2592 public final void removeTimer(final TTimer timer
) {
2593 synchronized (timers
) {
2594 timers
.remove(timer
);
2598 // ------------------------------------------------------------------------
2599 // Other TWindow constructors ---------------------------------------------
2600 // ------------------------------------------------------------------------
2603 * Convenience function to spawn a message box.
2605 * @param title window title, will be centered along the top border
2606 * @param caption message to display. Use embedded newlines to get a
2608 * @return the new message box
2610 public final TMessageBox
messageBox(final String title
,
2611 final String caption
) {
2613 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2617 * Convenience function to spawn a message box.
2619 * @param title window title, will be centered along the top border
2620 * @param caption message to display. Use embedded newlines to get a
2622 * @param type one of the TMessageBox.Type constants. Default is
2624 * @return the new message box
2626 public final TMessageBox
messageBox(final String title
,
2627 final String caption
, final TMessageBox
.Type type
) {
2629 return new TMessageBox(this, title
, caption
, type
);
2633 * Convenience function to spawn an input 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 input box
2640 public final TInputBox
inputBox(final String title
, final String caption
) {
2642 return new TInputBox(this, title
, caption
);
2646 * Convenience function to spawn an input box.
2648 * @param title window title, will be centered along the top border
2649 * @param caption message to display. Use embedded newlines to get a
2651 * @param text initial text to seed the field with
2652 * @return the new input box
2654 public final TInputBox
inputBox(final String title
, final String caption
,
2655 final String text
) {
2657 return new TInputBox(this, title
, caption
, text
);
2661 * Convenience function to open a terminal window.
2663 * @param x column relative to parent
2664 * @param y row relative to parent
2665 * @return the terminal new window
2667 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2668 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2672 * Convenience function to open a terminal window.
2674 * @param x column relative to parent
2675 * @param y row relative to parent
2676 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2677 * @return the terminal new window
2679 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2682 return new TTerminalWindow(this, x
, y
, flags
);
2686 * Convenience function to spawn an file open box.
2688 * @param path path of selected file
2689 * @return the result of the new file open box
2690 * @throws IOException if java.io operation throws
2692 public final String
fileOpenBox(final String path
) throws IOException
{
2694 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2695 return box
.getFilename();
2699 * Convenience function to spawn an file open box.
2701 * @param path path of selected file
2702 * @param type one of the Type constants
2703 * @return the result of the new file open box
2704 * @throws IOException if java.io operation throws
2706 public final String
fileOpenBox(final String path
,
2707 final TFileOpenBox
.Type type
) throws IOException
{
2709 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2710 return box
.getFilename();
2714 * Convenience function to create a new window and make it active.
2715 * Window will be located at (0, 0).
2717 * @param title window title, will be centered along the top border
2718 * @param width width of window
2719 * @param height height of window
2721 public final TWindow
addWindow(final String title
, final int width
,
2724 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2728 * Convenience function to create a new window and make it active.
2729 * Window will be located at (0, 0).
2731 * @param title window title, will be centered along the top border
2732 * @param width width of window
2733 * @param height height of window
2734 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2736 public final TWindow
addWindow(final String title
,
2737 final int width
, final int height
, final int flags
) {
2739 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2744 * Convenience function to create a new window and make it active.
2746 * @param title window title, will be centered along the top border
2747 * @param x column relative to parent
2748 * @param y row relative to parent
2749 * @param width width of window
2750 * @param height height of window
2752 public final TWindow
addWindow(final String title
,
2753 final int x
, final int y
, final int width
, final int height
) {
2755 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
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
2767 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2769 public final TWindow
addWindow(final String title
,
2770 final int x
, final int y
, final int width
, final int height
,
2773 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);