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
.bits
.GraphicsChars
;
48 import jexer
.event
.TCommandEvent
;
49 import jexer
.event
.TInputEvent
;
50 import jexer
.event
.TKeypressEvent
;
51 import jexer
.event
.TMenuEvent
;
52 import jexer
.event
.TMouseEvent
;
53 import jexer
.event
.TResizeEvent
;
54 import jexer
.backend
.Backend
;
55 import jexer
.backend
.SwingBackend
;
56 import jexer
.backend
.ECMA48Backend
;
57 import jexer
.io
.Screen
;
58 import jexer
.menu
.TMenu
;
59 import jexer
.menu
.TMenuItem
;
60 import static jexer
.TCommand
.*;
61 import static jexer
.TKeypress
.*;
64 * TApplication sets up a full Text User Interface application.
66 public class TApplication
implements Runnable
{
68 // ------------------------------------------------------------------------
69 // Public constants -------------------------------------------------------
70 // ------------------------------------------------------------------------
73 * If true, emit thread stuff to System.err.
75 private static final boolean debugThreads
= false;
78 * If true, emit events being processed to System.err.
80 private static final boolean debugEvents
= false;
83 * If true, do "smart placement" on new windows that are not specified to
86 private static final boolean smartWindowPlacement
= true;
89 * Two backend types are available.
91 public static enum BackendType
{
98 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
103 * Synonym for ECMA48.
108 // ------------------------------------------------------------------------
109 // Primary/secondary event handlers ---------------------------------------
110 // ------------------------------------------------------------------------
113 * WidgetEventHandler is the main event consumer loop. There are at most
114 * two such threads in existence: the primary for normal case and a
115 * secondary that is used for TMessageBox, TInputBox, and similar.
117 private class WidgetEventHandler
implements Runnable
{
119 * The main application.
121 private TApplication application
;
124 * Whether or not this WidgetEventHandler is the primary or secondary
127 private boolean primary
= true;
130 * Public constructor.
132 * @param application the main application
133 * @param primary if true, this is the primary event handler thread
135 public WidgetEventHandler(final TApplication application
,
136 final boolean primary
) {
138 this.application
= application
;
139 this.primary
= primary
;
148 while (!application
.quit
) {
150 // Wait until application notifies me
151 while (!application
.quit
) {
153 synchronized (application
.drainEventQueue
) {
154 if (application
.drainEventQueue
.size() > 0) {
159 synchronized (this) {
161 System
.err
.printf("%s %s sleep\n", this,
162 primary ?
"primary" : "secondary");
168 System
.err
.printf("%s %s AWAKE\n", this,
169 primary ?
"primary" : "secondary");
173 && (application
.secondaryEventReceiver
== null)
175 // Secondary thread, emergency exit. If we
176 // got here then something went wrong with
177 // the handoff between yield() and
179 synchronized (application
.primaryEventHandler
) {
180 application
.primaryEventHandler
.notify();
182 application
.secondaryEventHandler
= null;
183 throw new RuntimeException(
184 "secondary exited at wrong time");
188 } catch (InterruptedException e
) {
193 // Wait for drawAll() or doIdle() to be done, then handle the
195 boolean oldLock
= lockHandleEvent();
196 assert (oldLock
== false);
198 // Pull all events off the queue
200 TInputEvent event
= null;
201 synchronized (application
.drainEventQueue
) {
202 if (application
.drainEventQueue
.size() == 0) {
205 event
= application
.drainEventQueue
.remove(0);
207 application
.repaint
= true;
209 primaryHandleEvent(event
);
211 secondaryHandleEvent(event
);
214 && (application
.secondaryEventReceiver
== null)
216 // Secondary thread, time to exit.
218 // DO NOT UNLOCK. Primary thread just came back from
219 // primaryHandleEvent() and will unlock in the else
220 // block below. Just wake it up.
221 synchronized (application
.primaryEventHandler
) {
222 application
.primaryEventHandler
.notify();
224 // Now eliminate my reference so that
225 // wakeEventHandler() resumes working on the primary.
226 application
.secondaryEventHandler
= null;
233 // Unlock. Either I am primary thread, or I am secondary
234 // thread and still running.
235 oldLock
= unlockHandleEvent();
236 assert (oldLock
== true);
238 // I have done some work of some kind. Tell the main run()
239 // loop to wake up now.
240 synchronized (application
) {
241 application
.notify();
244 } // while (true) (main runnable loop)
249 * The primary event handler thread.
251 private volatile WidgetEventHandler primaryEventHandler
;
254 * The secondary event handler thread.
256 private volatile WidgetEventHandler secondaryEventHandler
;
259 * The widget receiving events from the secondary event handler thread.
261 private volatile TWidget secondaryEventReceiver
;
264 * Spinlock for the primary and secondary event handlers.
265 * WidgetEventHandler.run() is responsible for setting this value.
267 private volatile boolean insideHandleEvent
= false;
270 * Wake the sleeping active event handler.
272 private void wakeEventHandler() {
273 if (secondaryEventHandler
!= null) {
274 synchronized (secondaryEventHandler
) {
275 secondaryEventHandler
.notify();
278 assert (primaryEventHandler
!= null);
279 synchronized (primaryEventHandler
) {
280 primaryEventHandler
.notify();
286 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
287 * spin indefinitely until unlockHandleEvent() is called.
289 * @return the old value of insideHandleEvent
291 private boolean lockHandleEvent() {
293 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
296 boolean oldValue
= true;
298 synchronized (this) {
299 // Wait for TApplication.run() to finish using the global state
300 // before allowing further event processing.
301 while (lockoutHandleEvent
== true) {
303 // Backoff so that the backend can finish its work.
305 } catch (InterruptedException e
) {
310 oldValue
= insideHandleEvent
;
311 insideHandleEvent
= true;
315 System
.err
.printf(" ***\n");
321 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
322 * spin indefinitely until unlockHandleEvent() is called.
324 * @return the old value of insideHandleEvent
326 private boolean unlockHandleEvent() {
328 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
331 synchronized (this) {
332 boolean oldValue
= insideHandleEvent
;
333 insideHandleEvent
= false;
339 * Spinlock for the primary and secondary event handlers. When true, the
340 * event handlers will spinlock wait before calling handleEvent().
342 private volatile boolean lockoutHandleEvent
= false;
345 * TApplication.run() needs to be able rely on the global data structures
346 * being intact when calling doIdle() and drawAll(). Tell the event
347 * handlers to wait for an unlock before handling their events.
349 private void stopEventHandlers() {
351 System
.err
.printf(">> stopEventHandlers()");
354 lockoutHandleEvent
= true;
355 // Wait for the last event to finish processing before returning
356 // control to TApplication.run().
357 while (insideHandleEvent
== true) {
359 // Backoff so that the event handler can finish its work.
361 } catch (InterruptedException e
) {
367 System
.err
.printf(" XXX\n");
372 * TApplication.run() needs to be able rely on the global data structures
373 * being intact when calling doIdle() and drawAll(). Tell the event
374 * handlers that it is now OK to handle their events.
376 private void startEventHandlers() {
378 System
.err
.printf("<< startEventHandlers()\n");
380 lockoutHandleEvent
= false;
383 // ------------------------------------------------------------------------
384 // TApplication attributes ------------------------------------------------
385 // ------------------------------------------------------------------------
388 * Access to the physical screen, keyboard, and mouse.
390 private Backend backend
;
395 * @return the Backend
397 public final Backend
getBackend() {
406 public final Screen
getScreen() {
407 return backend
.getScreen();
411 * Actual mouse coordinate X.
416 * Actual mouse coordinate Y.
421 * Old version of mouse coordinate X.
423 private int oldMouseX
;
426 * Old version mouse coordinate Y.
428 private int oldMouseY
;
431 * Event queue that is filled by run().
433 private List
<TInputEvent
> fillEventQueue
;
436 * Event queue that will be drained by either primary or secondary
439 private List
<TInputEvent
> drainEventQueue
;
442 * Top-level menus in this application.
444 private List
<TMenu
> menus
;
447 * Stack of activated sub-menus in this application.
449 private List
<TMenu
> subMenus
;
452 * The currently active menu.
454 private TMenu activeMenu
= null;
457 * Active keyboard accelerators.
459 private Map
<TKeypress
, TMenuItem
> accelerators
;
464 private List
<TMenuItem
> menuItems
;
467 * Windows and widgets pull colors from this ColorTheme.
469 private ColorTheme theme
;
472 * Get the color theme.
476 public final ColorTheme
getTheme() {
481 * The top-level windows (but not menus).
483 private List
<TWindow
> windows
;
486 * The currently acive window.
488 private TWindow activeWindow
= null;
491 * Timers that are being ticked.
493 private List
<TTimer
> timers
;
496 * When true, exit the application.
498 private volatile boolean quit
= false;
501 * When true, repaint the entire screen.
503 private volatile boolean repaint
= true;
506 * Y coordinate of the top edge of the desktop. For now this is a
507 * constant. Someday it would be nice to have a multi-line menu or
510 private static final int desktopTop
= 1;
513 * Get Y coordinate of the top edge of the desktop.
515 * @return Y coordinate of the top edge of the desktop
517 public final int getDesktopTop() {
522 * Y coordinate of the bottom edge of the desktop.
524 private int desktopBottom
;
527 * Get Y coordinate of the bottom edge of the desktop.
529 * @return Y coordinate of the bottom edge of the desktop
531 public final int getDesktopBottom() {
532 return desktopBottom
;
536 * An optional TDesktop background window that is drawn underneath
539 private TDesktop desktop
;
542 * Set the TDesktop instance.
544 * @param desktop a TDesktop instance, or null to remove the one that is
547 public final void setDesktop(final TDesktop desktop
) {
548 if (this.desktop
!= null) {
549 this.desktop
.onClose();
551 this.desktop
= desktop
;
555 * Get the TDesktop instance.
557 * @return the desktop, or null if it is not set
559 public final TDesktop
getDesktop() {
564 * Get the current active window.
566 * @return the active window, or null if it is not set
568 public final TWindow
getActiveWindow() {
573 * Get the list of windows.
575 * @return a copy of the list of windows for this application
577 public final List
<TWindow
> getAllWindows() {
578 List
<TWindow
> result
= new LinkedList
<TWindow
>();
579 result
.addAll(windows
);
584 * If true, focus follows mouse: windows automatically raised if the
585 * mouse passes over them.
587 private boolean focusFollowsMouse
= false;
590 * Get focusFollowsMouse flag.
592 * @return true if focus follows mouse: windows automatically raised if
593 * the mouse passes over them
595 public boolean getFocusFollowsMouse() {
596 return focusFollowsMouse
;
600 * Set focusFollowsMouse flag.
602 * @param focusFollowsMouse if true, focus follows mouse: windows
603 * automatically raised if the mouse passes over them
605 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
606 this.focusFollowsMouse
= focusFollowsMouse
;
609 // ------------------------------------------------------------------------
610 // General behavior -------------------------------------------------------
611 // ------------------------------------------------------------------------
614 * Display the about dialog.
616 protected void showAboutDialog() {
617 messageBox("About", "Jexer Version " +
618 this.getClass().getPackage().getImplementationVersion(),
619 TMessageBox
.Type
.OK
);
622 // ------------------------------------------------------------------------
623 // Constructors -----------------------------------------------------------
624 // ------------------------------------------------------------------------
627 * Public constructor.
629 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
631 * @throws UnsupportedEncodingException if an exception is thrown when
632 * creating the InputStreamReader
634 public TApplication(final BackendType backendType
)
635 throws UnsupportedEncodingException
{
637 switch (backendType
) {
639 backend
= new SwingBackend(this);
644 backend
= new ECMA48Backend(this, null, null);
647 throw new IllegalArgumentException("Invalid backend type: "
654 * Public constructor. The backend type will be BackendType.ECMA48.
656 * @param input an InputStream connected to the remote user, or null for
657 * System.in. If System.in is used, then on non-Windows systems it will
658 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
659 * mode. input is always converted to a Reader with UTF-8 encoding.
660 * @param output an OutputStream connected to the remote user, or null
661 * for System.out. output is always converted to a Writer with UTF-8
663 * @throws UnsupportedEncodingException if an exception is thrown when
664 * creating the InputStreamReader
666 public TApplication(final InputStream input
,
667 final OutputStream output
) throws UnsupportedEncodingException
{
669 backend
= new ECMA48Backend(this, input
, output
);
674 * Public constructor. The backend type will be BackendType.ECMA48.
676 * @param input the InputStream underlying 'reader'. Its available()
677 * method is used to determine if reader.read() will block or not.
678 * @param reader a Reader connected to the remote user.
679 * @param writer a PrintWriter connected to the remote user.
680 * @param setRawMode if true, set System.in into raw mode with stty.
681 * This should in general not be used. It is here solely for Demo3,
682 * which uses System.in.
683 * @throws IllegalArgumentException if input, reader, or writer are null.
685 public TApplication(final InputStream input
, final Reader reader
,
686 final PrintWriter writer
, final boolean setRawMode
) {
688 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
693 * Public constructor. The backend type will be BackendType.ECMA48.
695 * @param input the InputStream underlying 'reader'. Its available()
696 * method is used to determine if reader.read() will block or not.
697 * @param reader a Reader connected to the remote user.
698 * @param writer a PrintWriter connected to the remote user.
699 * @throws IllegalArgumentException if input, reader, or writer are null.
701 public TApplication(final InputStream input
, final Reader reader
,
702 final PrintWriter writer
) {
704 this(input
, reader
, writer
, false);
708 * Public constructor. This hook enables use with new non-Jexer
711 * @param backend a Backend that is already ready to go.
713 public TApplication(final Backend backend
) {
714 this.backend
= backend
;
719 * Finish construction once the backend is set.
721 private void TApplicationImpl() {
722 theme
= new ColorTheme();
723 desktopBottom
= getScreen().getHeight() - 1;
724 fillEventQueue
= new ArrayList
<TInputEvent
>();
725 drainEventQueue
= new ArrayList
<TInputEvent
>();
726 windows
= new LinkedList
<TWindow
>();
727 menus
= new LinkedList
<TMenu
>();
728 subMenus
= new LinkedList
<TMenu
>();
729 timers
= new LinkedList
<TTimer
>();
730 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
731 menuItems
= new ArrayList
<TMenuItem
>();
732 desktop
= new TDesktop(this);
734 // Setup the main consumer thread
735 primaryEventHandler
= new WidgetEventHandler(this, true);
736 (new Thread(primaryEventHandler
)).start();
739 // ------------------------------------------------------------------------
740 // Screen refresh loop ----------------------------------------------------
741 // ------------------------------------------------------------------------
744 * Invert the cell color at a position. This is used to track the mouse.
746 * @param x column position
747 * @param y row position
749 private void invertCell(final int x
, final int y
) {
751 System
.err
.printf("invertCell() %d %d\n", x
, y
);
753 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
754 attr
.setForeColor(attr
.getForeColor().invert());
755 attr
.setBackColor(attr
.getBackColor().invert());
756 getScreen().putAttrXY(x
, y
, attr
, false);
762 private void drawAll() {
764 System
.err
.printf("drawAll() enter\n");
769 System
.err
.printf("drawAll() !repaint\n");
771 synchronized (getScreen()) {
772 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
773 // The only thing that has happened is the mouse moved.
774 // Clear the old position and draw the new position.
775 invertCell(oldMouseX
, oldMouseY
);
776 invertCell(mouseX
, mouseY
);
780 if (getScreen().isDirty()) {
781 backend
.flushScreen();
788 System
.err
.printf("drawAll() REDRAW\n");
791 // If true, the cursor is not visible
792 boolean cursor
= false;
794 // Start with a clean screen
798 if (desktop
!= null) {
799 desktop
.drawChildren();
802 // Draw each window in reverse Z order
803 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
804 Collections
.sort(sorted
);
805 TWindow topLevel
= null;
806 if (sorted
.size() > 0) {
807 topLevel
= sorted
.get(0);
809 Collections
.reverse(sorted
);
810 for (TWindow window
: sorted
) {
811 if (window
.isShown()) {
812 window
.drawChildren();
816 // Draw the blank menubar line - reset the screen clipping first so
817 // it won't trim it out.
818 getScreen().resetClipping();
819 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
820 theme
.getColor("tmenu"));
821 // Now draw the menus.
823 for (TMenu menu
: menus
) {
824 CellAttributes menuColor
;
825 CellAttributes menuMnemonicColor
;
826 if (menu
.isActive()) {
827 menuColor
= theme
.getColor("tmenu.highlighted");
828 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
831 menuColor
= theme
.getColor("tmenu");
832 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
834 // Draw the menu title
835 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
837 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
838 // Draw the highlight character
839 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
840 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
842 if (menu
.isActive()) {
844 // Reset the screen clipping so we can draw the next title.
845 getScreen().resetClipping();
847 x
+= menu
.getTitle().length() + 2;
850 for (TMenu menu
: subMenus
) {
851 // Reset the screen clipping so we can draw the next sub-menu.
852 getScreen().resetClipping();
856 // Draw the status bar of the top-level window
857 TStatusBar statusBar
= null;
858 if (topLevel
!= null) {
859 statusBar
= topLevel
.getStatusBar();
861 if (statusBar
!= null) {
862 getScreen().resetClipping();
863 statusBar
.setWidth(getScreen().getWidth());
864 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
867 CellAttributes barColor
= new CellAttributes();
868 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
869 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
873 // Draw the mouse pointer
874 invertCell(mouseX
, mouseY
);
878 // Place the cursor if it is visible
879 TWidget activeWidget
= null;
880 if (sorted
.size() > 0) {
881 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
882 if (activeWidget
.isCursorVisible()) {
883 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
884 activeWidget
.getCursorAbsoluteY());
891 getScreen().hideCursor();
894 // Flush the screen contents
895 if (getScreen().isDirty()) {
896 backend
.flushScreen();
902 // ------------------------------------------------------------------------
903 // Main loop --------------------------------------------------------------
904 // ------------------------------------------------------------------------
907 * Run this application until it exits.
911 // Timeout is in milliseconds, so default timeout after 1 second
915 // If I've got no updates to render, wait for something from the
916 // backend or a timer.
918 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
920 // Never sleep longer than 50 millis. We need time for
921 // windows with background tasks to update the display, and
922 // still flip buffers reasonably quickly in
923 // backend.flushPhysical().
924 timeout
= getSleepTime(50);
928 // As of now, I've got nothing to do: no I/O, nothing from
929 // the consumer threads, no timers that need to run ASAP. So
930 // wait until either the backend or the consumer threads have
934 System
.err
.println("sleep " + timeout
+ " millis");
936 synchronized (this) {
939 } catch (InterruptedException e
) {
940 // I'm awake and don't care why, let's see what's going
946 // Prevent stepping on the primary or secondary event handler.
949 // Pull any pending I/O events
950 backend
.getEvents(fillEventQueue
);
952 // Dispatch each event to the appropriate handler, one at a time.
954 TInputEvent event
= null;
955 if (fillEventQueue
.size() == 0) {
958 event
= fillEventQueue
.remove(0);
959 metaHandleEvent(event
);
962 // Wake a consumer thread if we have any pending events.
963 if (drainEventQueue
.size() > 0) {
967 // Process timers and call doIdle()'s
971 synchronized (getScreen()) {
975 // Let the event handlers run again.
976 startEventHandlers();
980 // Shutdown the event consumer threads
981 if (secondaryEventHandler
!= null) {
982 synchronized (secondaryEventHandler
) {
983 secondaryEventHandler
.notify();
986 if (primaryEventHandler
!= null) {
987 synchronized (primaryEventHandler
) {
988 primaryEventHandler
.notify();
992 // Shutdown the user I/O thread(s)
995 // Close all the windows. This gives them an opportunity to release
1002 * Peek at certain application-level events, add to eventQueue, and wake
1003 * up the consuming Thread.
1005 * @param event the input event to consume
1007 private void metaHandleEvent(final TInputEvent event
) {
1010 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1011 event
)); System
.err
.flush();
1015 // Do no more processing if the application is already trying
1020 // Special application-wide events -------------------------------
1023 if (event
instanceof TCommandEvent
) {
1024 TCommandEvent command
= (TCommandEvent
) event
;
1025 if (command
.getCmd().equals(cmAbort
)) {
1032 if (event
instanceof TResizeEvent
) {
1033 TResizeEvent resize
= (TResizeEvent
) event
;
1034 synchronized (getScreen()) {
1035 getScreen().setDimensions(resize
.getWidth(),
1036 resize
.getHeight());
1037 desktopBottom
= getScreen().getHeight() - 1;
1043 if (desktop
!= null) {
1044 desktop
.setDimensions(0, 0, resize
.getWidth(),
1045 resize
.getHeight() - 1);
1050 // Peek at the mouse position
1051 if (event
instanceof TMouseEvent
) {
1052 TMouseEvent mouse
= (TMouseEvent
) event
;
1053 synchronized (getScreen()) {
1054 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1057 mouseX
= mouse
.getX();
1058 mouseY
= mouse
.getY();
1063 // Put into the main queue
1064 drainEventQueue
.add(event
);
1068 * Dispatch one event to the appropriate widget or application-level
1069 * event handler. This is the primary event handler, it has the normal
1070 * application-wide event handling.
1072 * @param event the input event to consume
1073 * @see #secondaryHandleEvent(TInputEvent event)
1075 private void primaryHandleEvent(final TInputEvent event
) {
1078 System
.err
.printf("Handle event: %s\n", event
);
1081 // Special application-wide events -----------------------------------
1083 // Peek at the mouse position
1084 if (event
instanceof TMouseEvent
) {
1085 // See if we need to switch focus to another window or the menu
1086 checkSwitchFocus((TMouseEvent
) event
);
1089 // Handle menu events
1090 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1091 TMenu menu
= activeMenu
;
1093 if (event
instanceof TMouseEvent
) {
1094 TMouseEvent mouse
= (TMouseEvent
) event
;
1096 while (subMenus
.size() > 0) {
1097 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1098 if (subMenu
.mouseWouldHit(mouse
)) {
1101 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1102 && (!mouse
.isMouse1())
1103 && (!mouse
.isMouse2())
1104 && (!mouse
.isMouse3())
1105 && (!mouse
.isMouseWheelUp())
1106 && (!mouse
.isMouseWheelDown())
1110 // We navigated away from a sub-menu, so close it
1114 // Convert the mouse relative x/y to menu coordinates
1115 assert (mouse
.getX() == mouse
.getAbsoluteX());
1116 assert (mouse
.getY() == mouse
.getAbsoluteY());
1117 if (subMenus
.size() > 0) {
1118 menu
= subMenus
.get(subMenus
.size() - 1);
1120 mouse
.setX(mouse
.getX() - menu
.getX());
1121 mouse
.setY(mouse
.getY() - menu
.getY());
1123 menu
.handleEvent(event
);
1127 if (event
instanceof TKeypressEvent
) {
1128 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1130 // See if this key matches an accelerator, and is not being
1131 // shortcutted by the active window, and if so dispatch the menu
1133 boolean windowWillShortcut
= false;
1134 if (activeWindow
!= null) {
1135 assert (activeWindow
.isShown());
1136 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1137 // We do not process this key, it will be passed to the
1139 windowWillShortcut
= true;
1143 if (!windowWillShortcut
&& !modalWindowActive()) {
1144 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1145 TMenuItem item
= null;
1146 synchronized (accelerators
) {
1147 item
= accelerators
.get(keypressLowercase
);
1150 if (item
.isEnabled()) {
1151 // Let the menu item dispatch
1157 // Handle the keypress
1158 if (onKeypress(keypress
)) {
1164 if (event
instanceof TCommandEvent
) {
1165 if (onCommand((TCommandEvent
) event
)) {
1170 if (event
instanceof TMenuEvent
) {
1171 if (onMenu((TMenuEvent
) event
)) {
1176 // Dispatch events to the active window -------------------------------
1177 boolean dispatchToDesktop
= true;
1178 TWindow window
= activeWindow
;
1179 if (window
!= null) {
1180 assert (window
.isActive());
1181 assert (window
.isShown());
1182 if (event
instanceof TMouseEvent
) {
1183 TMouseEvent mouse
= (TMouseEvent
) event
;
1184 // Convert the mouse relative x/y to window coordinates
1185 assert (mouse
.getX() == mouse
.getAbsoluteX());
1186 assert (mouse
.getY() == mouse
.getAbsoluteY());
1187 mouse
.setX(mouse
.getX() - window
.getX());
1188 mouse
.setY(mouse
.getY() - window
.getY());
1190 if (window
.mouseWouldHit(mouse
)) {
1191 dispatchToDesktop
= false;
1193 } else if (event
instanceof TKeypressEvent
) {
1194 dispatchToDesktop
= false;
1198 System
.err
.printf("TApplication dispatch event: %s\n",
1201 window
.handleEvent(event
);
1203 if (dispatchToDesktop
) {
1204 // This event is fair game for the desktop to process.
1205 if (desktop
!= null) {
1206 desktop
.handleEvent(event
);
1212 * Dispatch one event to the appropriate widget or application-level
1213 * event handler. This is the secondary event handler used by certain
1214 * special dialogs (currently TMessageBox and TFileOpenBox).
1216 * @param event the input event to consume
1217 * @see #primaryHandleEvent(TInputEvent event)
1219 private void secondaryHandleEvent(final TInputEvent event
) {
1220 secondaryEventReceiver
.handleEvent(event
);
1224 * Enable a widget to override the primary event thread.
1226 * @param widget widget that will receive events
1228 public final void enableSecondaryEventReceiver(final TWidget widget
) {
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);
1235 (new Thread(secondaryEventHandler
)).start();
1239 * Yield to the secondary thread.
1241 public final void yield() {
1242 assert (secondaryEventReceiver
!= null);
1243 // This is where we handoff the event handler lock from the primary
1244 // to secondary thread. We unlock here, and in a future loop the
1245 // secondary thread locks again. When it gives up, we have the
1246 // single lock back.
1247 boolean oldLock
= unlockHandleEvent();
1250 while (secondaryEventReceiver
!= null) {
1251 synchronized (primaryEventHandler
) {
1253 primaryEventHandler
.wait();
1254 } catch (InterruptedException e
) {
1262 * Do stuff when there is no user input.
1264 private void doIdle() {
1266 System
.err
.printf("doIdle()\n");
1269 // Now run any timers that have timed out
1270 Date now
= new Date();
1271 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1272 for (TTimer timer
: timers
) {
1273 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1275 if (timer
.recurring
) {
1276 keepTimers
.add(timer
);
1279 keepTimers
.add(timer
);
1282 timers
= keepTimers
;
1285 for (TWindow window
: windows
) {
1288 if (desktop
!= null) {
1293 // ------------------------------------------------------------------------
1294 // TWindow management -----------------------------------------------------
1295 // ------------------------------------------------------------------------
1298 * Return the total number of windows.
1300 * @return the total number of windows
1302 public final int windowCount() {
1303 return windows
.size();
1307 * Return the number of windows that are showing.
1309 * @return the number of windows that are showing on screen
1311 public final int shownWindowCount() {
1313 for (TWindow w
: windows
) {
1322 * Return the number of windows that are hidden.
1324 * @return the number of windows that are hidden
1326 public final int hiddenWindowCount() {
1328 for (TWindow w
: windows
) {
1337 * Check if a window instance is in this application's window list.
1339 * @param window window to look for
1340 * @return true if this window is in the list
1342 public final boolean hasWindow(final TWindow window
) {
1343 if (windows
.size() == 0) {
1346 for (TWindow w
: windows
) {
1348 assert (window
.getApplication() == this);
1356 * Activate a window: bring it to the top and have it receive events.
1358 * @param window the window to become the new active window
1360 public void activateWindow(final TWindow window
) {
1361 if (hasWindow(window
) == false) {
1363 * Someone has a handle to a window I don't have. Ignore this
1369 assert (windows
.size() > 0);
1371 if (window
.isHidden()) {
1372 // Unhiding will also activate.
1376 assert (window
.isShown());
1378 if (windows
.size() == 1) {
1379 assert (window
== windows
.get(0));
1380 if (activeWindow
== null) {
1381 activeWindow
= window
;
1383 activeWindow
.setActive(true);
1384 activeWindow
.onFocus();
1387 assert (window
.isActive());
1388 assert (activeWindow
== window
);
1392 if (activeWindow
== window
) {
1393 assert (window
.isActive());
1395 // Window is already active, do nothing.
1399 assert (!window
.isActive());
1400 if (activeWindow
!= null) {
1401 assert (activeWindow
.getZ() == 0);
1403 activeWindow
.onUnfocus();
1404 activeWindow
.setActive(false);
1405 activeWindow
.setZ(window
.getZ());
1407 activeWindow
= window
;
1408 activeWindow
.setZ(0);
1409 activeWindow
.setActive(true);
1410 activeWindow
.onFocus();
1417 * @param window the window to hide
1419 public void hideWindow(final TWindow window
) {
1420 if (hasWindow(window
) == false) {
1422 * Someone has a handle to a window I don't have. Ignore this
1428 assert (windows
.size() > 0);
1430 if (!window
.hidden
) {
1431 if (window
== activeWindow
) {
1432 if (shownWindowCount() > 1) {
1435 activeWindow
= null;
1436 window
.setActive(false);
1440 window
.hidden
= true;
1448 * @param window the window to show
1450 public void showWindow(final TWindow window
) {
1451 if (hasWindow(window
) == false) {
1453 * Someone has a handle to a window I don't have. Ignore this
1459 assert (windows
.size() > 0);
1461 if (window
.hidden
) {
1462 window
.hidden
= false;
1464 activateWindow(window
);
1469 * Close window. Note that the window's destructor is NOT called by this
1470 * method, instead the GC is assumed to do the cleanup.
1472 * @param window the window to remove
1474 public final void closeWindow(final TWindow window
) {
1475 if (hasWindow(window
) == false) {
1477 * Someone has a handle to a window I don't have. Ignore this
1483 synchronized (windows
) {
1484 int z
= window
.getZ();
1487 Collections
.sort(windows
);
1489 activeWindow
= null;
1490 for (TWindow w
: windows
) {
1492 w
.setZ(w
.getZ() - 1);
1493 if (w
.getZ() == 0) {
1496 assert (activeWindow
== null);
1508 // Perform window cleanup
1511 // Check if we are closing a TMessageBox or similar
1512 if (secondaryEventReceiver
!= null) {
1513 assert (secondaryEventHandler
!= null);
1515 // Do not send events to the secondaryEventReceiver anymore, the
1516 // window is closed.
1517 secondaryEventReceiver
= null;
1519 // Wake the secondary thread, it will wake the primary as it
1521 synchronized (secondaryEventHandler
) {
1522 secondaryEventHandler
.notify();
1526 // Permit desktop to be active if it is the only thing left.
1527 if (desktop
!= null) {
1528 if (windows
.size() == 0) {
1529 desktop
.setActive(true);
1535 * Switch to the next window.
1537 * @param forward if true, then switch to the next window in the list,
1538 * otherwise switch to the previous window in the list
1540 public final void switchWindow(final boolean forward
) {
1541 // Only switch if there are multiple visible windows
1542 if (shownWindowCount() < 2) {
1545 assert (activeWindow
!= null);
1547 synchronized (windows
) {
1549 // Swap z/active between active window and the next in the list
1550 int activeWindowI
= -1;
1551 for (int i
= 0; i
< windows
.size(); i
++) {
1552 if (windows
.get(i
) == activeWindow
) {
1553 assert (activeWindow
.isActive());
1557 assert (!windows
.get(0).isActive());
1560 assert (activeWindowI
>= 0);
1562 // Do not switch if a window is modal
1563 if (activeWindow
.isModal()) {
1567 int nextWindowI
= activeWindowI
;
1571 nextWindowI
%= windows
.size();
1574 if (nextWindowI
< 0) {
1575 nextWindowI
= windows
.size() - 1;
1579 if (windows
.get(nextWindowI
).isShown()) {
1580 activateWindow(windows
.get(nextWindowI
));
1584 } // synchronized (windows)
1589 * Add a window to my window list and make it active.
1591 * @param window new window to add
1593 public final void addWindow(final TWindow window
) {
1595 // Do not add menu windows to the window list.
1596 if (window
instanceof TMenu
) {
1600 // Do not add the desktop to the window list.
1601 if (window
instanceof TDesktop
) {
1605 synchronized (windows
) {
1606 // Do not allow a modal window to spawn a non-modal window. If a
1607 // modal window is active, then this window will become modal
1609 if (modalWindowActive()) {
1610 window
.flags
|= TWindow
.MODAL
;
1611 window
.flags
|= TWindow
.CENTERED
;
1612 window
.hidden
= false;
1614 if (window
.isShown()) {
1615 for (TWindow w
: windows
) {
1620 w
.setZ(w
.getZ() + 1);
1623 windows
.add(window
);
1624 if (window
.isShown()) {
1625 activeWindow
= window
;
1626 activeWindow
.setZ(0);
1627 activeWindow
.setActive(true);
1628 activeWindow
.onFocus();
1631 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1632 && smartWindowPlacement
) {
1634 doSmartPlacement(window
);
1638 // Desktop cannot be active over any other window.
1639 if (desktop
!= null) {
1640 desktop
.setActive(false);
1645 * Check if there is a system-modal window on top.
1647 * @return true if the active window is modal
1649 private boolean modalWindowActive() {
1650 if (windows
.size() == 0) {
1654 for (TWindow w
: windows
) {
1664 * Close all open windows.
1666 private void closeAllWindows() {
1667 // Don't do anything if we are in the menu
1668 if (activeMenu
!= null) {
1671 while (windows
.size() > 0) {
1672 closeWindow(windows
.get(0));
1677 * Re-layout the open windows as non-overlapping tiles. This produces
1678 * almost the same results as Turbo Pascal 7.0's IDE.
1680 private void tileWindows() {
1681 synchronized (windows
) {
1682 // Don't do anything if we are in the menu
1683 if (activeMenu
!= null) {
1686 int z
= windows
.size();
1692 a
= (int)(Math
.sqrt(z
));
1696 if (((a
* b
) + c
) == z
) {
1704 int newWidth
= (getScreen().getWidth() / a
);
1705 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1706 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1708 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1709 Collections
.sort(sorted
);
1710 Collections
.reverse(sorted
);
1711 for (int i
= 0; i
< sorted
.size(); i
++) {
1712 int logicalX
= i
/ b
;
1713 int logicalY
= i
% b
;
1714 if (i
>= ((a
- 1) * b
)) {
1716 logicalY
= i
- ((a
- 1) * b
);
1719 TWindow w
= sorted
.get(i
);
1720 w
.setX(logicalX
* newWidth
);
1721 w
.setWidth(newWidth
);
1722 if (i
>= ((a
- 1) * b
)) {
1723 w
.setY((logicalY
* newHeight2
) + 1);
1724 w
.setHeight(newHeight2
);
1726 w
.setY((logicalY
* newHeight1
) + 1);
1727 w
.setHeight(newHeight1
);
1734 * Re-layout the open windows as overlapping cascaded windows.
1736 private void cascadeWindows() {
1737 synchronized (windows
) {
1738 // Don't do anything if we are in the menu
1739 if (activeMenu
!= null) {
1744 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1745 Collections
.sort(sorted
);
1746 Collections
.reverse(sorted
);
1747 for (TWindow window
: sorted
) {
1752 if (x
> getScreen().getWidth()) {
1755 if (y
>= getScreen().getHeight()) {
1763 * Place a window to minimize its overlap with other windows.
1765 * @param window the window to place
1767 public final void doSmartPlacement(final TWindow window
) {
1768 // This is a pretty dumb algorithm, but seems to work. The hardest
1769 // part is computing these "overlap" values seeking a minimum average
1772 int yMin
= desktopTop
;
1773 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1774 int yMax
= desktopBottom
- window
.getHeight() + 1;
1782 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1783 // No work to do, bail out.
1787 // Compute the overlap matrix without the new window.
1788 int width
= getScreen().getWidth();
1789 int height
= getScreen().getHeight();
1790 int overlapMatrix
[][] = new int[width
][height
];
1791 for (TWindow w
: windows
) {
1795 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1799 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1803 overlapMatrix
[x
][y
]++;
1808 long oldOverlapTotal
= 0;
1809 long oldOverlapN
= 0;
1810 for (int x
= 0; x
< width
; x
++) {
1811 for (int y
= 0; y
< height
; y
++) {
1812 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1813 if (overlapMatrix
[x
][y
] > 0) {
1820 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1821 boolean first
= true;
1822 int windowX
= window
.getX();
1823 int windowY
= window
.getY();
1825 // For each possible (x, y) position for the new window, compute a
1826 // new overlap matrix.
1827 for (int x
= xMin
; x
< xMax
; x
++) {
1828 for (int y
= yMin
; y
< yMax
; y
++) {
1830 // Start with the matrix minus this window.
1831 int newMatrix
[][] = new int[width
][height
];
1832 for (int mx
= 0; mx
< width
; mx
++) {
1833 for (int my
= 0; my
< height
; my
++) {
1834 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1838 // Add this window's values to the new overlap matrix.
1839 long newOverlapTotal
= 0;
1840 long newOverlapN
= 0;
1841 // Start by adding each new cell.
1842 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1846 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1850 newMatrix
[wx
][wy
]++;
1853 // Now figure out the new value for total coverage.
1854 for (int mx
= 0; mx
< width
; mx
++) {
1855 for (int my
= 0; my
< height
; my
++) {
1856 newOverlapTotal
+= newMatrix
[x
][y
];
1857 if (newMatrix
[mx
][my
] > 0) {
1862 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1865 // First time: just record what we got.
1866 oldOverlapAvg
= newOverlapAvg
;
1869 // All other times: pick a new best (x, y) and save the
1871 if (newOverlapAvg
< oldOverlapAvg
) {
1874 oldOverlapAvg
= newOverlapAvg
;
1878 } // for (int x = xMin; x < xMax; x++)
1880 } // for (int y = yMin; y < yMax; y++)
1882 // Finally, set the window's new coordinates.
1883 window
.setX(windowX
);
1884 window
.setY(windowY
);
1887 // ------------------------------------------------------------------------
1888 // TMenu management -------------------------------------------------------
1889 // ------------------------------------------------------------------------
1892 * Check if a mouse event would hit either the active menu or any open
1895 * @param mouse mouse event
1896 * @return true if the mouse would hit the active menu or an open
1899 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1900 assert (activeMenu
!= null);
1901 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1902 Collections
.reverse(menus
);
1903 for (TMenu menu
: menus
) {
1904 if (menu
.mouseWouldHit(mouse
)) {
1908 return activeMenu
.mouseWouldHit(mouse
);
1912 * See if we need to switch window or activate the menu based on
1915 * @param mouse mouse event
1917 private void checkSwitchFocus(final TMouseEvent mouse
) {
1919 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1920 && (activeMenu
!= null)
1921 && (mouse
.getAbsoluteY() != 0)
1922 && (!mouseOnMenu(mouse
))
1924 // They clicked outside the active menu, turn it off
1925 activeMenu
.setActive(false);
1927 for (TMenu menu
: subMenus
) {
1928 menu
.setActive(false);
1934 // See if they hit the menu bar
1935 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1936 && (mouse
.isMouse1())
1937 && (!modalWindowActive())
1938 && (mouse
.getAbsoluteY() == 0)
1941 for (TMenu menu
: subMenus
) {
1942 menu
.setActive(false);
1946 // They selected the menu, go activate it
1947 for (TMenu menu
: menus
) {
1948 if ((mouse
.getAbsoluteX() >= menu
.getX())
1949 && (mouse
.getAbsoluteX() < menu
.getX()
1950 + menu
.getTitle().length() + 2)
1952 menu
.setActive(true);
1955 menu
.setActive(false);
1961 // See if they hit the menu bar
1962 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1963 && (mouse
.isMouse1())
1964 && (activeMenu
!= null)
1965 && (mouse
.getAbsoluteY() == 0)
1968 TMenu oldMenu
= activeMenu
;
1969 for (TMenu menu
: subMenus
) {
1970 menu
.setActive(false);
1974 // See if we should switch menus
1975 for (TMenu menu
: menus
) {
1976 if ((mouse
.getAbsoluteX() >= menu
.getX())
1977 && (mouse
.getAbsoluteX() < menu
.getX()
1978 + menu
.getTitle().length() + 2)
1980 menu
.setActive(true);
1984 if (oldMenu
!= activeMenu
) {
1985 // They switched menus
1986 oldMenu
.setActive(false);
1991 // If a menu is still active, don't switch windows
1992 if (activeMenu
!= null) {
1996 // Only switch if there are multiple windows
1997 if (windows
.size() < 2) {
2001 if (((focusFollowsMouse
== true)
2002 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2003 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2005 synchronized (windows
) {
2006 Collections
.sort(windows
);
2007 if (windows
.get(0).isModal()) {
2008 // Modal windows don't switch
2012 for (TWindow window
: windows
) {
2013 assert (!window
.isModal());
2015 if (window
.isHidden()) {
2016 assert (!window
.isActive());
2020 if (window
.mouseWouldHit(mouse
)) {
2021 if (window
== windows
.get(0)) {
2022 // Clicked on the same window, nothing to do
2023 assert (window
.isActive());
2027 // We will be switching to another window
2028 assert (windows
.get(0).isActive());
2029 assert (windows
.get(0) == activeWindow
);
2030 assert (!window
.isActive());
2031 activeWindow
.onUnfocus();
2032 activeWindow
.setActive(false);
2033 activeWindow
.setZ(window
.getZ());
2034 activeWindow
= window
;
2036 window
.setActive(true);
2043 // Clicked on the background, nothing to do
2047 // Nothing to do: this isn't a mouse up, or focus isn't following
2053 * Turn off the menu.
2055 public final void closeMenu() {
2056 if (activeMenu
!= null) {
2057 activeMenu
.setActive(false);
2059 for (TMenu menu
: subMenus
) {
2060 menu
.setActive(false);
2067 * Turn off a sub-menu.
2069 public final void closeSubMenu() {
2070 assert (activeMenu
!= null);
2071 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2072 assert (item
!= null);
2073 item
.setActive(false);
2074 subMenus
.remove(subMenus
.size() - 1);
2078 * Switch to the next menu.
2080 * @param forward if true, then switch to the next menu in the list,
2081 * otherwise switch to the previous menu in the list
2083 public final void switchMenu(final boolean forward
) {
2084 assert (activeMenu
!= null);
2086 for (TMenu menu
: subMenus
) {
2087 menu
.setActive(false);
2091 for (int i
= 0; i
< menus
.size(); i
++) {
2092 if (activeMenu
== menus
.get(i
)) {
2094 if (i
< menus
.size() - 1) {
2102 activeMenu
.setActive(false);
2103 activeMenu
= menus
.get(i
);
2104 activeMenu
.setActive(true);
2111 * Add a menu item to the global list. If it has a keyboard accelerator,
2112 * that will be added the global hash.
2114 * @param item the menu item
2116 public final void addMenuItem(final TMenuItem item
) {
2117 menuItems
.add(item
);
2119 TKeypress key
= item
.getKey();
2121 synchronized (accelerators
) {
2122 assert (accelerators
.get(key
) == null);
2123 accelerators
.put(key
.toLowerCase(), item
);
2129 * Disable one menu item.
2131 * @param id the menu item ID
2133 public final void disableMenuItem(final int id
) {
2134 for (TMenuItem item
: menuItems
) {
2135 if (item
.getId() == id
) {
2136 item
.setEnabled(false);
2142 * Disable the range of menu items with ID's between lower and upper,
2145 * @param lower the lowest menu item ID
2146 * @param upper the highest menu item ID
2148 public final void disableMenuItems(final int lower
, final int upper
) {
2149 for (TMenuItem item
: menuItems
) {
2150 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2151 item
.setEnabled(false);
2157 * Enable one menu item.
2159 * @param id the menu item ID
2161 public final void enableMenuItem(final int id
) {
2162 for (TMenuItem item
: menuItems
) {
2163 if (item
.getId() == id
) {
2164 item
.setEnabled(true);
2170 * Enable the range of menu items with ID's between lower and upper,
2173 * @param lower the lowest menu item ID
2174 * @param upper the highest menu item ID
2176 public final void enableMenuItems(final int lower
, final int upper
) {
2177 for (TMenuItem item
: menuItems
) {
2178 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2179 item
.setEnabled(true);
2185 * Recompute menu x positions based on their title length.
2187 public final void recomputeMenuX() {
2189 for (TMenu menu
: menus
) {
2191 x
+= menu
.getTitle().length() + 2;
2196 * Post an event to process and turn off the menu.
2198 * @param event new event to add to the queue
2200 public final void postMenuEvent(final TInputEvent event
) {
2201 synchronized (fillEventQueue
) {
2202 fillEventQueue
.add(event
);
2208 * Add a sub-menu to the list of open sub-menus.
2210 * @param menu sub-menu
2212 public final void addSubMenu(final TMenu menu
) {
2217 * Convenience function to add a top-level menu.
2219 * @param title menu title
2220 * @return the new menu
2222 public final TMenu
addMenu(final String title
) {
2225 TMenu menu
= new TMenu(this, x
, y
, title
);
2232 * Convenience function to add a default "File" menu.
2234 * @return the new menu
2236 public final TMenu
addFileMenu() {
2237 TMenu fileMenu
= addMenu("&File");
2238 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2239 fileMenu
.addSeparator();
2240 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2241 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2242 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2243 "commands (Open, Save, Print, etc.)");
2244 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2249 * Convenience function to add a default "Edit" menu.
2251 * @return the new menu
2253 public final TMenu
addEditMenu() {
2254 TMenu editMenu
= addMenu("&Edit");
2255 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2256 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2257 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2258 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2259 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2260 "undo, and Clipboard access");
2261 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2266 * Convenience function to add a default "Window" menu.
2268 * @return the new menu
2270 public final TMenu
addWindowMenu() {
2271 TMenu windowMenu
= addMenu("&Window");
2272 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2273 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2274 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2275 windowMenu
.addSeparator();
2276 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2277 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2278 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2279 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2280 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2281 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2283 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2288 * Convenience function to add a default "Help" menu.
2290 * @return the new menu
2292 public final TMenu
addHelpMenu() {
2293 TMenu helpMenu
= addMenu("&Help");
2294 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2295 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2296 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2297 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2298 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2299 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2300 helpMenu
.addSeparator();
2301 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2302 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2303 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2307 // ------------------------------------------------------------------------
2308 // Event handlers ---------------------------------------------------------
2309 // ------------------------------------------------------------------------
2312 * Method that TApplication subclasses can override to handle menu or
2313 * posted command events.
2315 * @param command command event
2316 * @return if true, this event was consumed
2318 protected boolean onCommand(final TCommandEvent command
) {
2319 // Default: handle cmExit
2320 if (command
.equals(cmExit
)) {
2321 if (messageBox("Confirmation", "Exit application?",
2322 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2328 if (command
.equals(cmShell
)) {
2329 openTerminal(0, 0, TWindow
.RESIZABLE
);
2333 if (command
.equals(cmTile
)) {
2337 if (command
.equals(cmCascade
)) {
2341 if (command
.equals(cmCloseAll
)) {
2350 * Method that TApplication subclasses can override to handle menu
2353 * @param menu menu event
2354 * @return if true, this event was consumed
2356 protected boolean onMenu(final TMenuEvent menu
) {
2358 // Default: handle MID_EXIT
2359 if (menu
.getId() == TMenu
.MID_EXIT
) {
2360 if (messageBox("Confirmation", "Exit application?",
2361 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2367 if (menu
.getId() == TMenu
.MID_SHELL
) {
2368 openTerminal(0, 0, TWindow
.RESIZABLE
);
2372 if (menu
.getId() == TMenu
.MID_TILE
) {
2376 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2380 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2384 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2392 * Method that TApplication subclasses can override to handle keystrokes.
2394 * @param keypress keystroke event
2395 * @return if true, this event was consumed
2397 protected boolean onKeypress(final TKeypressEvent keypress
) {
2398 // Default: only menu shortcuts
2400 // Process Alt-F, Alt-E, etc. menu shortcut keys
2401 if (!keypress
.getKey().isFnKey()
2402 && keypress
.getKey().isAlt()
2403 && !keypress
.getKey().isCtrl()
2404 && (activeMenu
== null)
2405 && !modalWindowActive()
2408 assert (subMenus
.size() == 0);
2410 for (TMenu menu
: menus
) {
2411 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2412 == Character
.toLowerCase(keypress
.getKey().getChar())
2415 menu
.setActive(true);
2424 // ------------------------------------------------------------------------
2425 // TTimer management ------------------------------------------------------
2426 // ------------------------------------------------------------------------
2429 * Get the amount of time I can sleep before missing a Timer tick.
2431 * @param timeout = initial (maximum) timeout in millis
2432 * @return number of milliseconds between now and the next timer event
2434 private long getSleepTime(final long timeout
) {
2435 Date now
= new Date();
2436 long nowTime
= now
.getTime();
2437 long sleepTime
= timeout
;
2438 for (TTimer timer
: timers
) {
2439 long nextTickTime
= timer
.getNextTick().getTime();
2440 if (nextTickTime
< nowTime
) {
2444 long timeDifference
= nextTickTime
- nowTime
;
2445 if (timeDifference
< sleepTime
) {
2446 sleepTime
= timeDifference
;
2449 assert (sleepTime
>= 0);
2450 assert (sleepTime
<= timeout
);
2455 * Convenience function to add a timer.
2457 * @param duration number of milliseconds to wait between ticks
2458 * @param recurring if true, re-schedule this timer after every tick
2459 * @param action function to call when button is pressed
2462 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2463 final TAction action
) {
2465 TTimer timer
= new TTimer(duration
, recurring
, action
);
2466 synchronized (timers
) {
2473 * Convenience function to remove a timer.
2475 * @param timer timer to remove
2477 public final void removeTimer(final TTimer timer
) {
2478 synchronized (timers
) {
2479 timers
.remove(timer
);
2483 // ------------------------------------------------------------------------
2484 // Other TWindow constructors ---------------------------------------------
2485 // ------------------------------------------------------------------------
2488 * Convenience function to spawn a message box.
2490 * @param title window title, will be centered along the top border
2491 * @param caption message to display. Use embedded newlines to get a
2493 * @return the new message box
2495 public final TMessageBox
messageBox(final String title
,
2496 final String caption
) {
2498 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2502 * Convenience function to spawn a message box.
2504 * @param title window title, will be centered along the top border
2505 * @param caption message to display. Use embedded newlines to get a
2507 * @param type one of the TMessageBox.Type constants. Default is
2509 * @return the new message box
2511 public final TMessageBox
messageBox(final String title
,
2512 final String caption
, final TMessageBox
.Type type
) {
2514 return new TMessageBox(this, title
, caption
, type
);
2518 * Convenience function to spawn an input box.
2520 * @param title window title, will be centered along the top border
2521 * @param caption message to display. Use embedded newlines to get a
2523 * @return the new input box
2525 public final TInputBox
inputBox(final String title
, final String caption
) {
2527 return new TInputBox(this, title
, caption
);
2531 * Convenience function to spawn an input box.
2533 * @param title window title, will be centered along the top border
2534 * @param caption message to display. Use embedded newlines to get a
2536 * @param text initial text to seed the field with
2537 * @return the new input box
2539 public final TInputBox
inputBox(final String title
, final String caption
,
2540 final String text
) {
2542 return new TInputBox(this, title
, caption
, text
);
2546 * Convenience function to open a terminal window.
2548 * @param x column relative to parent
2549 * @param y row relative to parent
2550 * @return the terminal new window
2552 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2553 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2557 * Convenience function to open a terminal window.
2559 * @param x column relative to parent
2560 * @param y row relative to parent
2561 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2562 * @return the terminal new window
2564 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2567 return new TTerminalWindow(this, x
, y
, flags
);
2571 * Convenience function to spawn an file open box.
2573 * @param path path of selected file
2574 * @return the result of the new file open box
2575 * @throws IOException if java.io operation throws
2577 public final String
fileOpenBox(final String path
) throws IOException
{
2579 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2580 return box
.getFilename();
2584 * Convenience function to spawn an file open box.
2586 * @param path path of selected file
2587 * @param type one of the Type constants
2588 * @return the result of the new file open box
2589 * @throws IOException if java.io operation throws
2591 public final String
fileOpenBox(final String path
,
2592 final TFileOpenBox
.Type type
) throws IOException
{
2594 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2595 return box
.getFilename();
2599 * Convenience function to create a new window and make it active.
2600 * Window will be located at (0, 0).
2602 * @param title window title, will be centered along the top border
2603 * @param width width of window
2604 * @param height height of window
2606 public final TWindow
addWindow(final String title
, final int width
,
2609 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2613 * Convenience function to create a new window and make it active.
2614 * Window will be located at (0, 0).
2616 * @param title window title, will be centered along the top border
2617 * @param width width of window
2618 * @param height height of window
2619 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2621 public final TWindow
addWindow(final String title
,
2622 final int width
, final int height
, final int flags
) {
2624 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2629 * Convenience function to create a new window and make it active.
2631 * @param title window title, will be centered along the top border
2632 * @param x column relative to parent
2633 * @param y row relative to parent
2634 * @param width width of window
2635 * @param height height of window
2637 public final TWindow
addWindow(final String title
,
2638 final int x
, final int y
, final int width
, final int height
) {
2640 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2645 * Convenience function to create a new window and make it active.
2647 * @param title window title, will be centered along the top border
2648 * @param x column relative to parent
2649 * @param y row relative to parent
2650 * @param width width of window
2651 * @param height height of window
2652 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2654 public final TWindow
addWindow(final String title
,
2655 final int x
, final int y
, final int width
, final int height
,
2658 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);