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
.SwingBackend
;
56 import jexer
.backend
.ECMA48Backend
;
57 import jexer
.menu
.TMenu
;
58 import jexer
.menu
.TMenuItem
;
59 import static jexer
.TCommand
.*;
60 import static jexer
.TKeypress
.*;
63 * TApplication is the main driver class for a full Text User Interface
64 * application. It manages windows, provides a menu bar and status bar, and
65 * processes events received from the user.
67 public class TApplication
implements Runnable
{
69 // ------------------------------------------------------------------------
70 // Public constants -------------------------------------------------------
71 // ------------------------------------------------------------------------
74 * If true, emit thread stuff to System.err.
76 private static final boolean debugThreads
= false;
79 * If true, emit events being processed to System.err.
81 private static final boolean debugEvents
= false;
84 * If true, do "smart placement" on new windows that are not specified to
87 private static final boolean smartWindowPlacement
= true;
90 * Two backend types are available.
92 public static enum BackendType
{
99 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
104 * Synonym for ECMA48.
109 // ------------------------------------------------------------------------
110 // Primary/secondary event handlers ---------------------------------------
111 // ------------------------------------------------------------------------
114 * WidgetEventHandler is the main event consumer loop. There are at most
115 * two such threads in existence: the primary for normal case and a
116 * secondary that is used for TMessageBox, TInputBox, and similar.
118 private class WidgetEventHandler
implements Runnable
{
120 * The main application.
122 private TApplication application
;
125 * Whether or not this WidgetEventHandler is the primary or secondary
128 private boolean primary
= true;
131 * Public constructor.
133 * @param application the main application
134 * @param primary if true, this is the primary event handler thread
136 public WidgetEventHandler(final TApplication application
,
137 final boolean primary
) {
139 this.application
= application
;
140 this.primary
= primary
;
149 while (!application
.quit
) {
151 // Wait until application notifies me
152 while (!application
.quit
) {
154 synchronized (application
.drainEventQueue
) {
155 if (application
.drainEventQueue
.size() > 0) {
160 synchronized (this) {
162 System
.err
.printf("%s %s sleep\n", this,
163 primary ?
"primary" : "secondary");
169 System
.err
.printf("%s %s AWAKE\n", this,
170 primary ?
"primary" : "secondary");
174 && (application
.secondaryEventReceiver
== null)
176 // Secondary thread, emergency exit. If we
177 // got here then something went wrong with
178 // the handoff between yield() and
180 synchronized (application
.primaryEventHandler
) {
181 application
.primaryEventHandler
.notify();
183 application
.secondaryEventHandler
= null;
184 throw new RuntimeException(
185 "secondary exited at wrong time");
189 } catch (InterruptedException e
) {
194 // Wait for drawAll() or doIdle() to be done, then handle the
196 boolean oldLock
= lockHandleEvent();
197 assert (oldLock
== false);
199 // Pull all events off the queue
201 TInputEvent event
= null;
202 synchronized (application
.drainEventQueue
) {
203 if (application
.drainEventQueue
.size() == 0) {
206 event
= application
.drainEventQueue
.remove(0);
208 application
.repaint
= true;
210 primaryHandleEvent(event
);
212 secondaryHandleEvent(event
);
215 && (application
.secondaryEventReceiver
== null)
217 // Secondary thread, time to exit.
219 // DO NOT UNLOCK. Primary thread just came back from
220 // primaryHandleEvent() and will unlock in the else
221 // block below. Just wake it up.
222 synchronized (application
.primaryEventHandler
) {
223 application
.primaryEventHandler
.notify();
225 // Now eliminate my reference so that
226 // wakeEventHandler() resumes working on the primary.
227 application
.secondaryEventHandler
= null;
234 // Unlock. Either I am primary thread, or I am secondary
235 // thread and still running.
236 oldLock
= unlockHandleEvent();
237 assert (oldLock
== true);
239 // I have done some work of some kind. Tell the main run()
240 // loop to wake up now.
241 synchronized (application
) {
242 application
.notify();
245 } // while (true) (main runnable loop)
250 * The primary event handler thread.
252 private volatile WidgetEventHandler primaryEventHandler
;
255 * The secondary event handler thread.
257 private volatile WidgetEventHandler secondaryEventHandler
;
260 * The widget receiving events from the secondary event handler thread.
262 private volatile TWidget secondaryEventReceiver
;
265 * Spinlock for the primary and secondary event handlers.
266 * WidgetEventHandler.run() is responsible for setting this value.
268 private volatile boolean insideHandleEvent
= false;
271 * Wake the sleeping active event handler.
273 private void wakeEventHandler() {
274 if (secondaryEventHandler
!= null) {
275 synchronized (secondaryEventHandler
) {
276 secondaryEventHandler
.notify();
279 assert (primaryEventHandler
!= null);
280 synchronized (primaryEventHandler
) {
281 primaryEventHandler
.notify();
287 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
288 * spin indefinitely until unlockHandleEvent() is called.
290 * @return the old value of insideHandleEvent
292 private boolean lockHandleEvent() {
294 System
.err
.printf(" >> lockHandleEvent(): oldValue %s",
297 boolean oldValue
= true;
299 synchronized (this) {
300 // Wait for TApplication.run() to finish using the global state
301 // before allowing further event processing.
302 while (lockoutHandleEvent
== true) {
304 // Backoff so that the backend can finish its work.
306 } catch (InterruptedException e
) {
311 oldValue
= insideHandleEvent
;
312 insideHandleEvent
= true;
316 System
.err
.printf(" ***\n");
322 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
323 * spin indefinitely until unlockHandleEvent() is called.
325 * @return the old value of insideHandleEvent
327 private boolean unlockHandleEvent() {
329 System
.err
.printf(" << unlockHandleEvent(): oldValue %s\n",
332 synchronized (this) {
333 boolean oldValue
= insideHandleEvent
;
334 insideHandleEvent
= false;
340 * Spinlock for the primary and secondary event handlers. When true, the
341 * event handlers will spinlock wait before calling handleEvent().
343 private volatile boolean lockoutHandleEvent
= false;
346 * TApplication.run() needs to be able rely on the global data structures
347 * being intact when calling doIdle() and drawAll(). Tell the event
348 * handlers to wait for an unlock before handling their events.
350 private void stopEventHandlers() {
352 System
.err
.printf(">> stopEventHandlers()");
355 lockoutHandleEvent
= true;
356 // Wait for the last event to finish processing before returning
357 // control to TApplication.run().
358 while (insideHandleEvent
== true) {
360 // Backoff so that the event handler can finish its work.
362 } catch (InterruptedException e
) {
368 System
.err
.printf(" XXX\n");
373 * TApplication.run() needs to be able rely on the global data structures
374 * being intact when calling doIdle() and drawAll(). Tell the event
375 * handlers that it is now OK to handle their events.
377 private void startEventHandlers() {
379 System
.err
.printf("<< startEventHandlers()\n");
381 lockoutHandleEvent
= false;
384 // ------------------------------------------------------------------------
385 // TApplication attributes ------------------------------------------------
386 // ------------------------------------------------------------------------
389 * Access to the physical screen, keyboard, and mouse.
391 private Backend backend
;
396 * @return the Backend
398 public final Backend
getBackend() {
407 public final Screen
getScreen() {
408 return backend
.getScreen();
412 * Actual mouse coordinate X.
417 * Actual mouse coordinate Y.
422 * Old version of mouse coordinate X.
424 private int oldMouseX
;
427 * Old version mouse coordinate Y.
429 private int oldMouseY
;
432 * Event queue that is filled by run().
434 private List
<TInputEvent
> fillEventQueue
;
437 * Event queue that will be drained by either primary or secondary
440 private List
<TInputEvent
> drainEventQueue
;
443 * Top-level menus in this application.
445 private List
<TMenu
> menus
;
448 * Stack of activated sub-menus in this application.
450 private List
<TMenu
> subMenus
;
453 * The currently active menu.
455 private TMenu activeMenu
= null;
458 * Active keyboard accelerators.
460 private Map
<TKeypress
, TMenuItem
> accelerators
;
465 private List
<TMenuItem
> menuItems
;
468 * Windows and widgets pull colors from this ColorTheme.
470 private ColorTheme theme
;
473 * Get the color theme.
477 public final ColorTheme
getTheme() {
482 * The top-level windows (but not menus).
484 private List
<TWindow
> windows
;
487 * The currently acive window.
489 private TWindow activeWindow
= null;
492 * Timers that are being ticked.
494 private List
<TTimer
> timers
;
497 * When true, exit the application.
499 private volatile boolean quit
= false;
502 * When true, repaint the entire screen.
504 private volatile boolean repaint
= true;
507 * Y coordinate of the top edge of the desktop. For now this is a
508 * constant. Someday it would be nice to have a multi-line menu or
511 private static final int desktopTop
= 1;
514 * Get Y coordinate of the top edge of the desktop.
516 * @return Y coordinate of the top edge of the desktop
518 public final int getDesktopTop() {
523 * Y coordinate of the bottom edge of the desktop.
525 private int desktopBottom
;
528 * Get Y coordinate of the bottom edge of the desktop.
530 * @return Y coordinate of the bottom edge of the desktop
532 public final int getDesktopBottom() {
533 return desktopBottom
;
537 * An optional TDesktop background window that is drawn underneath
540 private TDesktop desktop
;
543 * Set the TDesktop instance.
545 * @param desktop a TDesktop instance, or null to remove the one that is
548 public final void setDesktop(final TDesktop desktop
) {
549 if (this.desktop
!= null) {
550 this.desktop
.onClose();
552 this.desktop
= desktop
;
556 * Get the TDesktop instance.
558 * @return the desktop, or null if it is not set
560 public final TDesktop
getDesktop() {
565 * Get the current active window.
567 * @return the active window, or null if it is not set
569 public final TWindow
getActiveWindow() {
574 * Get the list of windows.
576 * @return a copy of the list of windows for this application
578 public final List
<TWindow
> getAllWindows() {
579 List
<TWindow
> result
= new LinkedList
<TWindow
>();
580 result
.addAll(windows
);
585 * If true, focus follows mouse: windows automatically raised if the
586 * mouse passes over them.
588 private boolean focusFollowsMouse
= false;
591 * Get focusFollowsMouse flag.
593 * @return true if focus follows mouse: windows automatically raised if
594 * the mouse passes over them
596 public boolean getFocusFollowsMouse() {
597 return focusFollowsMouse
;
601 * Set focusFollowsMouse flag.
603 * @param focusFollowsMouse if true, focus follows mouse: windows
604 * automatically raised if the mouse passes over them
606 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
607 this.focusFollowsMouse
= focusFollowsMouse
;
610 // ------------------------------------------------------------------------
611 // General behavior -------------------------------------------------------
612 // ------------------------------------------------------------------------
615 * Display the about dialog.
617 protected void showAboutDialog() {
618 messageBox("About", "Jexer Version " +
619 this.getClass().getPackage().getImplementationVersion(),
620 TMessageBox
.Type
.OK
);
623 // ------------------------------------------------------------------------
624 // Constructors -----------------------------------------------------------
625 // ------------------------------------------------------------------------
628 * Public constructor.
630 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
632 * @throws UnsupportedEncodingException if an exception is thrown when
633 * creating the InputStreamReader
635 public TApplication(final BackendType backendType
)
636 throws UnsupportedEncodingException
{
638 switch (backendType
) {
640 // The default SwingBackend is 80x25, 20 pt font. If you want to
641 // change that, you can pass the extra arguments to the
642 // SwingBackend constructor here. For example, if you wanted
643 // 90x30, 16 pt font:
645 // backend = new SwingBackend(this, 90, 30, 16);
646 backend
= new SwingBackend(this);
651 backend
= new ECMA48Backend(this, null, null);
654 throw new IllegalArgumentException("Invalid backend type: "
661 * Public constructor. The backend type will be BackendType.ECMA48.
663 * @param input an InputStream connected to the remote user, or null for
664 * System.in. If System.in is used, then on non-Windows systems it will
665 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
666 * mode. input is always converted to a Reader with UTF-8 encoding.
667 * @param output an OutputStream connected to the remote user, or null
668 * for System.out. output is always converted to a Writer with UTF-8
670 * @throws UnsupportedEncodingException if an exception is thrown when
671 * creating the InputStreamReader
673 public TApplication(final InputStream input
,
674 final OutputStream output
) throws UnsupportedEncodingException
{
676 backend
= new ECMA48Backend(this, input
, output
);
681 * Public constructor. The backend type will be BackendType.ECMA48.
683 * @param input the InputStream underlying 'reader'. Its available()
684 * method is used to determine if reader.read() will block or not.
685 * @param reader a Reader connected to the remote user.
686 * @param writer a PrintWriter connected to the remote user.
687 * @param setRawMode if true, set System.in into raw mode with stty.
688 * This should in general not be used. It is here solely for Demo3,
689 * which uses System.in.
690 * @throws IllegalArgumentException if input, reader, or writer are null.
692 public TApplication(final InputStream input
, final Reader reader
,
693 final PrintWriter writer
, final boolean setRawMode
) {
695 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
700 * Public constructor. The backend type will be BackendType.ECMA48.
702 * @param input the InputStream underlying 'reader'. Its available()
703 * method is used to determine if reader.read() will block or not.
704 * @param reader a Reader connected to the remote user.
705 * @param writer a PrintWriter connected to the remote user.
706 * @throws IllegalArgumentException if input, reader, or writer are null.
708 public TApplication(final InputStream input
, final Reader reader
,
709 final PrintWriter writer
) {
711 this(input
, reader
, writer
, false);
715 * Public constructor. This hook enables use with new non-Jexer
718 * @param backend a Backend that is already ready to go.
720 public TApplication(final Backend backend
) {
721 this.backend
= backend
;
726 * Finish construction once the backend is set.
728 private void TApplicationImpl() {
729 theme
= new ColorTheme();
730 desktopBottom
= getScreen().getHeight() - 1;
731 fillEventQueue
= new ArrayList
<TInputEvent
>();
732 drainEventQueue
= new ArrayList
<TInputEvent
>();
733 windows
= new LinkedList
<TWindow
>();
734 menus
= new LinkedList
<TMenu
>();
735 subMenus
= new LinkedList
<TMenu
>();
736 timers
= new LinkedList
<TTimer
>();
737 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
738 menuItems
= new ArrayList
<TMenuItem
>();
739 desktop
= new TDesktop(this);
741 // Setup the main consumer thread
742 primaryEventHandler
= new WidgetEventHandler(this, true);
743 (new Thread(primaryEventHandler
)).start();
746 // ------------------------------------------------------------------------
747 // Screen refresh loop ----------------------------------------------------
748 // ------------------------------------------------------------------------
751 * Invert the cell color at a position. This is used to track the mouse.
753 * @param x column position
754 * @param y row position
756 private void invertCell(final int x
, final int y
) {
758 System
.err
.printf("invertCell() %d %d\n", x
, y
);
760 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
761 attr
.setForeColor(attr
.getForeColor().invert());
762 attr
.setBackColor(attr
.getBackColor().invert());
763 getScreen().putAttrXY(x
, y
, attr
, false);
769 private void drawAll() {
771 System
.err
.printf("drawAll() enter\n");
776 System
.err
.printf("drawAll() !repaint\n");
778 synchronized (getScreen()) {
779 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
780 // The only thing that has happened is the mouse moved.
781 // Clear the old position and draw the new position.
782 invertCell(oldMouseX
, oldMouseY
);
783 invertCell(mouseX
, mouseY
);
787 if (getScreen().isDirty()) {
788 backend
.flushScreen();
795 System
.err
.printf("drawAll() REDRAW\n");
798 // If true, the cursor is not visible
799 boolean cursor
= false;
801 // Start with a clean screen
805 if (desktop
!= null) {
806 desktop
.drawChildren();
809 // Draw each window in reverse Z order
810 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
811 Collections
.sort(sorted
);
812 TWindow topLevel
= null;
813 if (sorted
.size() > 0) {
814 topLevel
= sorted
.get(0);
816 Collections
.reverse(sorted
);
817 for (TWindow window
: sorted
) {
818 if (window
.isShown()) {
819 window
.drawChildren();
823 // Draw the blank menubar line - reset the screen clipping first so
824 // it won't trim it out.
825 getScreen().resetClipping();
826 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
827 theme
.getColor("tmenu"));
828 // Now draw the menus.
830 for (TMenu menu
: menus
) {
831 CellAttributes menuColor
;
832 CellAttributes menuMnemonicColor
;
833 if (menu
.isActive()) {
834 menuColor
= theme
.getColor("tmenu.highlighted");
835 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
838 menuColor
= theme
.getColor("tmenu");
839 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
841 // Draw the menu title
842 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
844 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
845 // Draw the highlight character
846 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
847 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
849 if (menu
.isActive()) {
851 // Reset the screen clipping so we can draw the next title.
852 getScreen().resetClipping();
854 x
+= menu
.getTitle().length() + 2;
857 for (TMenu menu
: subMenus
) {
858 // Reset the screen clipping so we can draw the next sub-menu.
859 getScreen().resetClipping();
863 // Draw the status bar of the top-level window
864 TStatusBar statusBar
= null;
865 if (topLevel
!= null) {
866 statusBar
= topLevel
.getStatusBar();
868 if (statusBar
!= null) {
869 getScreen().resetClipping();
870 statusBar
.setWidth(getScreen().getWidth());
871 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
874 CellAttributes barColor
= new CellAttributes();
875 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
876 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
880 // Draw the mouse pointer
881 invertCell(mouseX
, mouseY
);
885 // Place the cursor if it is visible
886 TWidget activeWidget
= null;
887 if (sorted
.size() > 0) {
888 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
889 if (activeWidget
.isCursorVisible()) {
890 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
891 activeWidget
.getCursorAbsoluteY());
898 getScreen().hideCursor();
901 // Flush the screen contents
902 if (getScreen().isDirty()) {
903 backend
.flushScreen();
909 // ------------------------------------------------------------------------
910 // Main loop --------------------------------------------------------------
911 // ------------------------------------------------------------------------
914 * Force this application to exit.
921 * Run this application until it exits.
925 // Timeout is in milliseconds, so default timeout after 1 second
929 // If I've got no updates to render, wait for something from the
930 // backend or a timer.
932 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
934 // Never sleep longer than 50 millis. We need time for
935 // windows with background tasks to update the display, and
936 // still flip buffers reasonably quickly in
937 // backend.flushPhysical().
938 timeout
= getSleepTime(50);
942 // As of now, I've got nothing to do: no I/O, nothing from
943 // the consumer threads, no timers that need to run ASAP. So
944 // wait until either the backend or the consumer threads have
948 System
.err
.println("sleep " + timeout
+ " millis");
950 synchronized (this) {
953 } catch (InterruptedException e
) {
954 // I'm awake and don't care why, let's see what's going
960 // Prevent stepping on the primary or secondary event handler.
963 // Pull any pending I/O events
964 backend
.getEvents(fillEventQueue
);
966 // Dispatch each event to the appropriate handler, one at a time.
968 TInputEvent event
= null;
969 if (fillEventQueue
.size() == 0) {
972 event
= fillEventQueue
.remove(0);
973 metaHandleEvent(event
);
976 // Wake a consumer thread if we have any pending events.
977 if (drainEventQueue
.size() > 0) {
981 // Process timers and call doIdle()'s
985 synchronized (getScreen()) {
989 // Let the event handlers run again.
990 startEventHandlers();
994 // Shutdown the event consumer threads
995 if (secondaryEventHandler
!= null) {
996 synchronized (secondaryEventHandler
) {
997 secondaryEventHandler
.notify();
1000 if (primaryEventHandler
!= null) {
1001 synchronized (primaryEventHandler
) {
1002 primaryEventHandler
.notify();
1006 // Shutdown the user I/O thread(s)
1009 // Close all the windows. This gives them an opportunity to release
1016 * Peek at certain application-level events, add to eventQueue, and wake
1017 * up the consuming Thread.
1019 * @param event the input event to consume
1021 private void metaHandleEvent(final TInputEvent event
) {
1024 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1025 event
)); System
.err
.flush();
1029 // Do no more processing if the application is already trying
1034 // Special application-wide events -------------------------------
1037 if (event
instanceof TCommandEvent
) {
1038 TCommandEvent command
= (TCommandEvent
) event
;
1039 if (command
.getCmd().equals(cmAbort
)) {
1046 if (event
instanceof TResizeEvent
) {
1047 TResizeEvent resize
= (TResizeEvent
) event
;
1048 synchronized (getScreen()) {
1049 getScreen().setDimensions(resize
.getWidth(),
1050 resize
.getHeight());
1051 desktopBottom
= getScreen().getHeight() - 1;
1057 if (desktop
!= null) {
1058 desktop
.setDimensions(0, 0, resize
.getWidth(),
1059 resize
.getHeight() - 1);
1064 // Peek at the mouse position
1065 if (event
instanceof TMouseEvent
) {
1066 TMouseEvent mouse
= (TMouseEvent
) event
;
1067 synchronized (getScreen()) {
1068 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1071 mouseX
= mouse
.getX();
1072 mouseY
= mouse
.getY();
1077 // Put into the main queue
1078 drainEventQueue
.add(event
);
1082 * Dispatch one event to the appropriate widget or application-level
1083 * event handler. This is the primary event handler, it has the normal
1084 * application-wide event handling.
1086 * @param event the input event to consume
1087 * @see #secondaryHandleEvent(TInputEvent event)
1089 private void primaryHandleEvent(final TInputEvent event
) {
1092 System
.err
.printf("Handle event: %s\n", event
);
1095 // Special application-wide events -----------------------------------
1097 // Peek at the mouse position
1098 if (event
instanceof TMouseEvent
) {
1099 // See if we need to switch focus to another window or the menu
1100 checkSwitchFocus((TMouseEvent
) event
);
1103 // Handle menu events
1104 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1105 TMenu menu
= activeMenu
;
1107 if (event
instanceof TMouseEvent
) {
1108 TMouseEvent mouse
= (TMouseEvent
) event
;
1110 while (subMenus
.size() > 0) {
1111 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1112 if (subMenu
.mouseWouldHit(mouse
)) {
1115 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1116 && (!mouse
.isMouse1())
1117 && (!mouse
.isMouse2())
1118 && (!mouse
.isMouse3())
1119 && (!mouse
.isMouseWheelUp())
1120 && (!mouse
.isMouseWheelDown())
1124 // We navigated away from a sub-menu, so close it
1128 // Convert the mouse relative x/y to menu coordinates
1129 assert (mouse
.getX() == mouse
.getAbsoluteX());
1130 assert (mouse
.getY() == mouse
.getAbsoluteY());
1131 if (subMenus
.size() > 0) {
1132 menu
= subMenus
.get(subMenus
.size() - 1);
1134 mouse
.setX(mouse
.getX() - menu
.getX());
1135 mouse
.setY(mouse
.getY() - menu
.getY());
1137 menu
.handleEvent(event
);
1141 if (event
instanceof TKeypressEvent
) {
1142 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1144 // See if this key matches an accelerator, and is not being
1145 // shortcutted by the active window, and if so dispatch the menu
1147 boolean windowWillShortcut
= false;
1148 if (activeWindow
!= null) {
1149 assert (activeWindow
.isShown());
1150 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1151 // We do not process this key, it will be passed to the
1153 windowWillShortcut
= true;
1157 if (!windowWillShortcut
&& !modalWindowActive()) {
1158 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1159 TMenuItem item
= null;
1160 synchronized (accelerators
) {
1161 item
= accelerators
.get(keypressLowercase
);
1164 if (item
.isEnabled()) {
1165 // Let the menu item dispatch
1171 // Handle the keypress
1172 if (onKeypress(keypress
)) {
1178 if (event
instanceof TCommandEvent
) {
1179 if (onCommand((TCommandEvent
) event
)) {
1184 if (event
instanceof TMenuEvent
) {
1185 if (onMenu((TMenuEvent
) event
)) {
1190 // Dispatch events to the active window -------------------------------
1191 boolean dispatchToDesktop
= true;
1192 TWindow window
= activeWindow
;
1193 if (window
!= null) {
1194 assert (window
.isActive());
1195 assert (window
.isShown());
1196 if (event
instanceof TMouseEvent
) {
1197 TMouseEvent mouse
= (TMouseEvent
) event
;
1198 // Convert the mouse relative x/y to window coordinates
1199 assert (mouse
.getX() == mouse
.getAbsoluteX());
1200 assert (mouse
.getY() == mouse
.getAbsoluteY());
1201 mouse
.setX(mouse
.getX() - window
.getX());
1202 mouse
.setY(mouse
.getY() - window
.getY());
1204 if (window
.mouseWouldHit(mouse
)) {
1205 dispatchToDesktop
= false;
1207 } else if (event
instanceof TKeypressEvent
) {
1208 dispatchToDesktop
= false;
1212 System
.err
.printf("TApplication dispatch event: %s\n",
1215 window
.handleEvent(event
);
1217 if (dispatchToDesktop
) {
1218 // This event is fair game for the desktop to process.
1219 if (desktop
!= null) {
1220 desktop
.handleEvent(event
);
1226 * Dispatch one event to the appropriate widget or application-level
1227 * event handler. This is the secondary event handler used by certain
1228 * special dialogs (currently TMessageBox and TFileOpenBox).
1230 * @param event the input event to consume
1231 * @see #primaryHandleEvent(TInputEvent event)
1233 private void secondaryHandleEvent(final TInputEvent event
) {
1234 secondaryEventReceiver
.handleEvent(event
);
1238 * Enable a widget to override the primary event thread.
1240 * @param widget widget that will receive events
1242 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1243 assert (secondaryEventReceiver
== null);
1244 assert (secondaryEventHandler
== null);
1245 assert ((widget
instanceof TMessageBox
)
1246 || (widget
instanceof TFileOpenBox
));
1247 secondaryEventReceiver
= widget
;
1248 secondaryEventHandler
= new WidgetEventHandler(this, false);
1249 (new Thread(secondaryEventHandler
)).start();
1253 * Yield to the secondary thread.
1255 public final void yield() {
1256 assert (secondaryEventReceiver
!= null);
1257 // This is where we handoff the event handler lock from the primary
1258 // to secondary thread. We unlock here, and in a future loop the
1259 // secondary thread locks again. When it gives up, we have the
1260 // single lock back.
1261 boolean oldLock
= unlockHandleEvent();
1264 while (secondaryEventReceiver
!= null) {
1265 synchronized (primaryEventHandler
) {
1267 primaryEventHandler
.wait();
1268 } catch (InterruptedException e
) {
1276 * Do stuff when there is no user input.
1278 private void doIdle() {
1280 System
.err
.printf("doIdle()\n");
1283 // Now run any timers that have timed out
1284 Date now
= new Date();
1285 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1286 for (TTimer timer
: timers
) {
1287 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1289 if (timer
.recurring
) {
1290 keepTimers
.add(timer
);
1293 keepTimers
.add(timer
);
1296 timers
= keepTimers
;
1299 for (TWindow window
: windows
) {
1302 if (desktop
!= null) {
1307 // ------------------------------------------------------------------------
1308 // TWindow management -----------------------------------------------------
1309 // ------------------------------------------------------------------------
1312 * Return the total number of windows.
1314 * @return the total number of windows
1316 public final int windowCount() {
1317 return windows
.size();
1321 * Return the number of windows that are showing.
1323 * @return the number of windows that are showing on screen
1325 public final int shownWindowCount() {
1327 for (TWindow w
: windows
) {
1336 * Return the number of windows that are hidden.
1338 * @return the number of windows that are hidden
1340 public final int hiddenWindowCount() {
1342 for (TWindow w
: windows
) {
1351 * Check if a window instance is in this application's window list.
1353 * @param window window to look for
1354 * @return true if this window is in the list
1356 public final boolean hasWindow(final TWindow window
) {
1357 if (windows
.size() == 0) {
1360 for (TWindow w
: windows
) {
1362 assert (window
.getApplication() == this);
1370 * Activate a window: bring it to the top and have it receive events.
1372 * @param window the window to become the new active window
1374 public void activateWindow(final TWindow window
) {
1375 if (hasWindow(window
) == false) {
1377 * Someone has a handle to a window I don't have. Ignore this
1383 assert (windows
.size() > 0);
1385 if (window
.isHidden()) {
1386 // Unhiding will also activate.
1390 assert (window
.isShown());
1392 if (windows
.size() == 1) {
1393 assert (window
== windows
.get(0));
1394 if (activeWindow
== null) {
1395 activeWindow
= window
;
1397 activeWindow
.setActive(true);
1398 activeWindow
.onFocus();
1401 assert (window
.isActive());
1402 assert (activeWindow
== window
);
1406 if (activeWindow
== window
) {
1407 assert (window
.isActive());
1409 // Window is already active, do nothing.
1413 assert (!window
.isActive());
1414 if (activeWindow
!= null) {
1415 assert (activeWindow
.getZ() == 0);
1417 activeWindow
.onUnfocus();
1418 activeWindow
.setActive(false);
1419 activeWindow
.setZ(window
.getZ());
1421 activeWindow
= window
;
1422 activeWindow
.setZ(0);
1423 activeWindow
.setActive(true);
1424 activeWindow
.onFocus();
1431 * @param window the window to hide
1433 public void hideWindow(final TWindow window
) {
1434 if (hasWindow(window
) == false) {
1436 * Someone has a handle to a window I don't have. Ignore this
1442 assert (windows
.size() > 0);
1444 if (!window
.hidden
) {
1445 if (window
== activeWindow
) {
1446 if (shownWindowCount() > 1) {
1449 activeWindow
= null;
1450 window
.setActive(false);
1454 window
.hidden
= true;
1462 * @param window the window to show
1464 public void showWindow(final TWindow window
) {
1465 if (hasWindow(window
) == false) {
1467 * Someone has a handle to a window I don't have. Ignore this
1473 assert (windows
.size() > 0);
1475 if (window
.hidden
) {
1476 window
.hidden
= false;
1478 activateWindow(window
);
1483 * Close window. Note that the window's destructor is NOT called by this
1484 * method, instead the GC is assumed to do the cleanup.
1486 * @param window the window to remove
1488 public final void closeWindow(final TWindow window
) {
1489 if (hasWindow(window
) == false) {
1491 * Someone has a handle to a window I don't have. Ignore this
1497 synchronized (windows
) {
1498 int z
= window
.getZ();
1501 Collections
.sort(windows
);
1503 activeWindow
= null;
1504 for (TWindow w
: windows
) {
1506 w
.setZ(w
.getZ() - 1);
1507 if (w
.getZ() == 0) {
1510 assert (activeWindow
== null);
1522 // Perform window cleanup
1525 // Check if we are closing a TMessageBox or similar
1526 if (secondaryEventReceiver
!= null) {
1527 assert (secondaryEventHandler
!= null);
1529 // Do not send events to the secondaryEventReceiver anymore, the
1530 // window is closed.
1531 secondaryEventReceiver
= null;
1533 // Wake the secondary thread, it will wake the primary as it
1535 synchronized (secondaryEventHandler
) {
1536 secondaryEventHandler
.notify();
1540 // Permit desktop to be active if it is the only thing left.
1541 if (desktop
!= null) {
1542 if (windows
.size() == 0) {
1543 desktop
.setActive(true);
1549 * Switch to the next window.
1551 * @param forward if true, then switch to the next window in the list,
1552 * otherwise switch to the previous window in the list
1554 public final void switchWindow(final boolean forward
) {
1555 // Only switch if there are multiple visible windows
1556 if (shownWindowCount() < 2) {
1559 assert (activeWindow
!= null);
1561 synchronized (windows
) {
1563 // Swap z/active between active window and the next in the list
1564 int activeWindowI
= -1;
1565 for (int i
= 0; i
< windows
.size(); i
++) {
1566 if (windows
.get(i
) == activeWindow
) {
1567 assert (activeWindow
.isActive());
1571 assert (!windows
.get(0).isActive());
1574 assert (activeWindowI
>= 0);
1576 // Do not switch if a window is modal
1577 if (activeWindow
.isModal()) {
1581 int nextWindowI
= activeWindowI
;
1585 nextWindowI
%= windows
.size();
1588 if (nextWindowI
< 0) {
1589 nextWindowI
= windows
.size() - 1;
1593 if (windows
.get(nextWindowI
).isShown()) {
1594 activateWindow(windows
.get(nextWindowI
));
1598 } // synchronized (windows)
1603 * Add a window to my window list and make it active.
1605 * @param window new window to add
1607 public final void addWindow(final TWindow window
) {
1609 // Do not add menu windows to the window list.
1610 if (window
instanceof TMenu
) {
1614 // Do not add the desktop to the window list.
1615 if (window
instanceof TDesktop
) {
1619 synchronized (windows
) {
1620 // Do not allow a modal window to spawn a non-modal window. If a
1621 // modal window is active, then this window will become modal
1623 if (modalWindowActive()) {
1624 window
.flags
|= TWindow
.MODAL
;
1625 window
.flags
|= TWindow
.CENTERED
;
1626 window
.hidden
= false;
1628 if (window
.isShown()) {
1629 for (TWindow w
: windows
) {
1634 w
.setZ(w
.getZ() + 1);
1637 windows
.add(window
);
1638 if (window
.isShown()) {
1639 activeWindow
= window
;
1640 activeWindow
.setZ(0);
1641 activeWindow
.setActive(true);
1642 activeWindow
.onFocus();
1645 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1646 && smartWindowPlacement
) {
1648 doSmartPlacement(window
);
1652 // Desktop cannot be active over any other window.
1653 if (desktop
!= null) {
1654 desktop
.setActive(false);
1659 * Check if there is a system-modal window on top.
1661 * @return true if the active window is modal
1663 private boolean modalWindowActive() {
1664 if (windows
.size() == 0) {
1668 for (TWindow w
: windows
) {
1678 * Close all open windows.
1680 private void closeAllWindows() {
1681 // Don't do anything if we are in the menu
1682 if (activeMenu
!= null) {
1685 while (windows
.size() > 0) {
1686 closeWindow(windows
.get(0));
1691 * Re-layout the open windows as non-overlapping tiles. This produces
1692 * almost the same results as Turbo Pascal 7.0's IDE.
1694 private void tileWindows() {
1695 synchronized (windows
) {
1696 // Don't do anything if we are in the menu
1697 if (activeMenu
!= null) {
1700 int z
= windows
.size();
1706 a
= (int)(Math
.sqrt(z
));
1710 if (((a
* b
) + c
) == z
) {
1718 int newWidth
= (getScreen().getWidth() / a
);
1719 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1720 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1722 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1723 Collections
.sort(sorted
);
1724 Collections
.reverse(sorted
);
1725 for (int i
= 0; i
< sorted
.size(); i
++) {
1726 int logicalX
= i
/ b
;
1727 int logicalY
= i
% b
;
1728 if (i
>= ((a
- 1) * b
)) {
1730 logicalY
= i
- ((a
- 1) * b
);
1733 TWindow w
= sorted
.get(i
);
1734 w
.setX(logicalX
* newWidth
);
1735 w
.setWidth(newWidth
);
1736 if (i
>= ((a
- 1) * b
)) {
1737 w
.setY((logicalY
* newHeight2
) + 1);
1738 w
.setHeight(newHeight2
);
1740 w
.setY((logicalY
* newHeight1
) + 1);
1741 w
.setHeight(newHeight1
);
1748 * Re-layout the open windows as overlapping cascaded windows.
1750 private void cascadeWindows() {
1751 synchronized (windows
) {
1752 // Don't do anything if we are in the menu
1753 if (activeMenu
!= null) {
1758 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1759 Collections
.sort(sorted
);
1760 Collections
.reverse(sorted
);
1761 for (TWindow window
: sorted
) {
1766 if (x
> getScreen().getWidth()) {
1769 if (y
>= getScreen().getHeight()) {
1777 * Place a window to minimize its overlap with other windows.
1779 * @param window the window to place
1781 public final void doSmartPlacement(final TWindow window
) {
1782 // This is a pretty dumb algorithm, but seems to work. The hardest
1783 // part is computing these "overlap" values seeking a minimum average
1786 int yMin
= desktopTop
;
1787 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1788 int yMax
= desktopBottom
- window
.getHeight() + 1;
1796 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1797 // No work to do, bail out.
1801 // Compute the overlap matrix without the new window.
1802 int width
= getScreen().getWidth();
1803 int height
= getScreen().getHeight();
1804 int overlapMatrix
[][] = new int[width
][height
];
1805 for (TWindow w
: windows
) {
1809 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1813 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1817 overlapMatrix
[x
][y
]++;
1822 long oldOverlapTotal
= 0;
1823 long oldOverlapN
= 0;
1824 for (int x
= 0; x
< width
; x
++) {
1825 for (int y
= 0; y
< height
; y
++) {
1826 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1827 if (overlapMatrix
[x
][y
] > 0) {
1834 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1835 boolean first
= true;
1836 int windowX
= window
.getX();
1837 int windowY
= window
.getY();
1839 // For each possible (x, y) position for the new window, compute a
1840 // new overlap matrix.
1841 for (int x
= xMin
; x
< xMax
; x
++) {
1842 for (int y
= yMin
; y
< yMax
; y
++) {
1844 // Start with the matrix minus this window.
1845 int newMatrix
[][] = new int[width
][height
];
1846 for (int mx
= 0; mx
< width
; mx
++) {
1847 for (int my
= 0; my
< height
; my
++) {
1848 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1852 // Add this window's values to the new overlap matrix.
1853 long newOverlapTotal
= 0;
1854 long newOverlapN
= 0;
1855 // Start by adding each new cell.
1856 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1860 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1864 newMatrix
[wx
][wy
]++;
1867 // Now figure out the new value for total coverage.
1868 for (int mx
= 0; mx
< width
; mx
++) {
1869 for (int my
= 0; my
< height
; my
++) {
1870 newOverlapTotal
+= newMatrix
[x
][y
];
1871 if (newMatrix
[mx
][my
] > 0) {
1876 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1879 // First time: just record what we got.
1880 oldOverlapAvg
= newOverlapAvg
;
1883 // All other times: pick a new best (x, y) and save the
1885 if (newOverlapAvg
< oldOverlapAvg
) {
1888 oldOverlapAvg
= newOverlapAvg
;
1892 } // for (int x = xMin; x < xMax; x++)
1894 } // for (int y = yMin; y < yMax; y++)
1896 // Finally, set the window's new coordinates.
1897 window
.setX(windowX
);
1898 window
.setY(windowY
);
1901 // ------------------------------------------------------------------------
1902 // TMenu management -------------------------------------------------------
1903 // ------------------------------------------------------------------------
1906 * Check if a mouse event would hit either the active menu or any open
1909 * @param mouse mouse event
1910 * @return true if the mouse would hit the active menu or an open
1913 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1914 assert (activeMenu
!= null);
1915 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1916 Collections
.reverse(menus
);
1917 for (TMenu menu
: menus
) {
1918 if (menu
.mouseWouldHit(mouse
)) {
1922 return activeMenu
.mouseWouldHit(mouse
);
1926 * See if we need to switch window or activate the menu based on
1929 * @param mouse mouse event
1931 private void checkSwitchFocus(final TMouseEvent mouse
) {
1933 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1934 && (activeMenu
!= null)
1935 && (mouse
.getAbsoluteY() != 0)
1936 && (!mouseOnMenu(mouse
))
1938 // They clicked outside the active menu, turn it off
1939 activeMenu
.setActive(false);
1941 for (TMenu menu
: subMenus
) {
1942 menu
.setActive(false);
1948 // See if they hit the menu bar
1949 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1950 && (mouse
.isMouse1())
1951 && (!modalWindowActive())
1952 && (mouse
.getAbsoluteY() == 0)
1955 for (TMenu menu
: subMenus
) {
1956 menu
.setActive(false);
1960 // They selected the menu, go activate it
1961 for (TMenu menu
: menus
) {
1962 if ((mouse
.getAbsoluteX() >= menu
.getX())
1963 && (mouse
.getAbsoluteX() < menu
.getX()
1964 + menu
.getTitle().length() + 2)
1966 menu
.setActive(true);
1969 menu
.setActive(false);
1975 // See if they hit the menu bar
1976 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1977 && (mouse
.isMouse1())
1978 && (activeMenu
!= null)
1979 && (mouse
.getAbsoluteY() == 0)
1982 TMenu oldMenu
= activeMenu
;
1983 for (TMenu menu
: subMenus
) {
1984 menu
.setActive(false);
1988 // See if we should switch menus
1989 for (TMenu menu
: menus
) {
1990 if ((mouse
.getAbsoluteX() >= menu
.getX())
1991 && (mouse
.getAbsoluteX() < menu
.getX()
1992 + menu
.getTitle().length() + 2)
1994 menu
.setActive(true);
1998 if (oldMenu
!= activeMenu
) {
1999 // They switched menus
2000 oldMenu
.setActive(false);
2005 // If a menu is still active, don't switch windows
2006 if (activeMenu
!= null) {
2010 // Only switch if there are multiple windows
2011 if (windows
.size() < 2) {
2015 if (((focusFollowsMouse
== true)
2016 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2017 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2019 synchronized (windows
) {
2020 Collections
.sort(windows
);
2021 if (windows
.get(0).isModal()) {
2022 // Modal windows don't switch
2026 for (TWindow window
: windows
) {
2027 assert (!window
.isModal());
2029 if (window
.isHidden()) {
2030 assert (!window
.isActive());
2034 if (window
.mouseWouldHit(mouse
)) {
2035 if (window
== windows
.get(0)) {
2036 // Clicked on the same window, nothing to do
2037 assert (window
.isActive());
2041 // We will be switching to another window
2042 assert (windows
.get(0).isActive());
2043 assert (windows
.get(0) == activeWindow
);
2044 assert (!window
.isActive());
2045 activeWindow
.onUnfocus();
2046 activeWindow
.setActive(false);
2047 activeWindow
.setZ(window
.getZ());
2048 activeWindow
= window
;
2050 window
.setActive(true);
2057 // Clicked on the background, nothing to do
2061 // Nothing to do: this isn't a mouse up, or focus isn't following
2067 * Turn off the menu.
2069 public final void closeMenu() {
2070 if (activeMenu
!= null) {
2071 activeMenu
.setActive(false);
2073 for (TMenu menu
: subMenus
) {
2074 menu
.setActive(false);
2081 * Turn off a sub-menu.
2083 public final void closeSubMenu() {
2084 assert (activeMenu
!= null);
2085 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2086 assert (item
!= null);
2087 item
.setActive(false);
2088 subMenus
.remove(subMenus
.size() - 1);
2092 * Switch to the next menu.
2094 * @param forward if true, then switch to the next menu in the list,
2095 * otherwise switch to the previous menu in the list
2097 public final void switchMenu(final boolean forward
) {
2098 assert (activeMenu
!= null);
2100 for (TMenu menu
: subMenus
) {
2101 menu
.setActive(false);
2105 for (int i
= 0; i
< menus
.size(); i
++) {
2106 if (activeMenu
== menus
.get(i
)) {
2108 if (i
< menus
.size() - 1) {
2116 activeMenu
.setActive(false);
2117 activeMenu
= menus
.get(i
);
2118 activeMenu
.setActive(true);
2125 * Add a menu item to the global list. If it has a keyboard accelerator,
2126 * that will be added the global hash.
2128 * @param item the menu item
2130 public final void addMenuItem(final TMenuItem item
) {
2131 menuItems
.add(item
);
2133 TKeypress key
= item
.getKey();
2135 synchronized (accelerators
) {
2136 assert (accelerators
.get(key
) == null);
2137 accelerators
.put(key
.toLowerCase(), item
);
2143 * Disable one menu item.
2145 * @param id the menu item ID
2147 public final void disableMenuItem(final int id
) {
2148 for (TMenuItem item
: menuItems
) {
2149 if (item
.getId() == id
) {
2150 item
.setEnabled(false);
2156 * Disable the range of menu items with ID's between lower and upper,
2159 * @param lower the lowest menu item ID
2160 * @param upper the highest menu item ID
2162 public final void disableMenuItems(final int lower
, final int upper
) {
2163 for (TMenuItem item
: menuItems
) {
2164 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2165 item
.setEnabled(false);
2171 * Enable one menu item.
2173 * @param id the menu item ID
2175 public final void enableMenuItem(final int id
) {
2176 for (TMenuItem item
: menuItems
) {
2177 if (item
.getId() == id
) {
2178 item
.setEnabled(true);
2184 * Enable the range of menu items with ID's between lower and upper,
2187 * @param lower the lowest menu item ID
2188 * @param upper the highest menu item ID
2190 public final void enableMenuItems(final int lower
, final int upper
) {
2191 for (TMenuItem item
: menuItems
) {
2192 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2193 item
.setEnabled(true);
2199 * Recompute menu x positions based on their title length.
2201 public final void recomputeMenuX() {
2203 for (TMenu menu
: menus
) {
2205 x
+= menu
.getTitle().length() + 2;
2210 * Post an event to process and turn off the menu.
2212 * @param event new event to add to the queue
2214 public final void postMenuEvent(final TInputEvent event
) {
2215 synchronized (fillEventQueue
) {
2216 fillEventQueue
.add(event
);
2222 * Add a sub-menu to the list of open sub-menus.
2224 * @param menu sub-menu
2226 public final void addSubMenu(final TMenu menu
) {
2231 * Convenience function to add a top-level menu.
2233 * @param title menu title
2234 * @return the new menu
2236 public final TMenu
addMenu(final String title
) {
2239 TMenu menu
= new TMenu(this, x
, y
, title
);
2246 * Convenience function to add a default "File" menu.
2248 * @return the new menu
2250 public final TMenu
addFileMenu() {
2251 TMenu fileMenu
= addMenu("&File");
2252 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2253 fileMenu
.addSeparator();
2254 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2255 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2256 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
2257 "commands (Open, Save, Print, etc.)");
2258 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2263 * Convenience function to add a default "Edit" menu.
2265 * @return the new menu
2267 public final TMenu
addEditMenu() {
2268 TMenu editMenu
= addMenu("&Edit");
2269 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2270 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2271 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2272 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2273 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
2274 "undo, and Clipboard access");
2275 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2280 * Convenience function to add a default "Window" menu.
2282 * @return the new menu
2284 public final TMenu
addWindowMenu() {
2285 TMenu windowMenu
= addMenu("&Window");
2286 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2287 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2288 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2289 windowMenu
.addSeparator();
2290 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2291 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2292 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2293 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2294 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2295 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
2297 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2302 * Convenience function to add a default "Help" menu.
2304 * @return the new menu
2306 public final TMenu
addHelpMenu() {
2307 TMenu helpMenu
= addMenu("&Help");
2308 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2309 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2310 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2311 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2312 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2313 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2314 helpMenu
.addSeparator();
2315 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2316 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
2317 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
2321 // ------------------------------------------------------------------------
2322 // Event handlers ---------------------------------------------------------
2323 // ------------------------------------------------------------------------
2326 * Method that TApplication subclasses can override to handle menu or
2327 * posted command events.
2329 * @param command command event
2330 * @return if true, this event was consumed
2332 protected boolean onCommand(final TCommandEvent command
) {
2333 // Default: handle cmExit
2334 if (command
.equals(cmExit
)) {
2335 if (messageBox("Confirmation", "Exit application?",
2336 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2342 if (command
.equals(cmShell
)) {
2343 openTerminal(0, 0, TWindow
.RESIZABLE
);
2347 if (command
.equals(cmTile
)) {
2351 if (command
.equals(cmCascade
)) {
2355 if (command
.equals(cmCloseAll
)) {
2364 * Method that TApplication subclasses can override to handle menu
2367 * @param menu menu event
2368 * @return if true, this event was consumed
2370 protected boolean onMenu(final TMenuEvent menu
) {
2372 // Default: handle MID_EXIT
2373 if (menu
.getId() == TMenu
.MID_EXIT
) {
2374 if (messageBox("Confirmation", "Exit application?",
2375 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2381 if (menu
.getId() == TMenu
.MID_SHELL
) {
2382 openTerminal(0, 0, TWindow
.RESIZABLE
);
2386 if (menu
.getId() == TMenu
.MID_TILE
) {
2390 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2394 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2398 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2406 * Method that TApplication subclasses can override to handle keystrokes.
2408 * @param keypress keystroke event
2409 * @return if true, this event was consumed
2411 protected boolean onKeypress(final TKeypressEvent keypress
) {
2412 // Default: only menu shortcuts
2414 // Process Alt-F, Alt-E, etc. menu shortcut keys
2415 if (!keypress
.getKey().isFnKey()
2416 && keypress
.getKey().isAlt()
2417 && !keypress
.getKey().isCtrl()
2418 && (activeMenu
== null)
2419 && !modalWindowActive()
2422 assert (subMenus
.size() == 0);
2424 for (TMenu menu
: menus
) {
2425 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2426 == Character
.toLowerCase(keypress
.getKey().getChar())
2429 menu
.setActive(true);
2438 // ------------------------------------------------------------------------
2439 // TTimer management ------------------------------------------------------
2440 // ------------------------------------------------------------------------
2443 * Get the amount of time I can sleep before missing a Timer tick.
2445 * @param timeout = initial (maximum) timeout in millis
2446 * @return number of milliseconds between now and the next timer event
2448 private long getSleepTime(final long timeout
) {
2449 Date now
= new Date();
2450 long nowTime
= now
.getTime();
2451 long sleepTime
= timeout
;
2452 for (TTimer timer
: timers
) {
2453 long nextTickTime
= timer
.getNextTick().getTime();
2454 if (nextTickTime
< nowTime
) {
2458 long timeDifference
= nextTickTime
- nowTime
;
2459 if (timeDifference
< sleepTime
) {
2460 sleepTime
= timeDifference
;
2463 assert (sleepTime
>= 0);
2464 assert (sleepTime
<= timeout
);
2469 * Convenience function to add a timer.
2471 * @param duration number of milliseconds to wait between ticks
2472 * @param recurring if true, re-schedule this timer after every tick
2473 * @param action function to call when button is pressed
2476 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2477 final TAction action
) {
2479 TTimer timer
= new TTimer(duration
, recurring
, action
);
2480 synchronized (timers
) {
2487 * Convenience function to remove a timer.
2489 * @param timer timer to remove
2491 public final void removeTimer(final TTimer timer
) {
2492 synchronized (timers
) {
2493 timers
.remove(timer
);
2497 // ------------------------------------------------------------------------
2498 // Other TWindow constructors ---------------------------------------------
2499 // ------------------------------------------------------------------------
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 * @return the new message box
2509 public final TMessageBox
messageBox(final String title
,
2510 final String caption
) {
2512 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2516 * Convenience function to spawn a message box.
2518 * @param title window title, will be centered along the top border
2519 * @param caption message to display. Use embedded newlines to get a
2521 * @param type one of the TMessageBox.Type constants. Default is
2523 * @return the new message box
2525 public final TMessageBox
messageBox(final String title
,
2526 final String caption
, final TMessageBox
.Type type
) {
2528 return new TMessageBox(this, title
, caption
, type
);
2532 * Convenience function to spawn an input box.
2534 * @param title window title, will be centered along the top border
2535 * @param caption message to display. Use embedded newlines to get a
2537 * @return the new input box
2539 public final TInputBox
inputBox(final String title
, final String caption
) {
2541 return new TInputBox(this, title
, caption
);
2545 * Convenience function to spawn an input box.
2547 * @param title window title, will be centered along the top border
2548 * @param caption message to display. Use embedded newlines to get a
2550 * @param text initial text to seed the field with
2551 * @return the new input box
2553 public final TInputBox
inputBox(final String title
, final String caption
,
2554 final String text
) {
2556 return new TInputBox(this, title
, caption
, text
);
2560 * Convenience function to open a terminal window.
2562 * @param x column relative to parent
2563 * @param y row relative to parent
2564 * @return the terminal new window
2566 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2567 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2571 * Convenience function to open a terminal window.
2573 * @param x column relative to parent
2574 * @param y row relative to parent
2575 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2576 * @return the terminal new window
2578 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2581 return new TTerminalWindow(this, x
, y
, flags
);
2585 * Convenience function to spawn an file open box.
2587 * @param path path of selected file
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
) throws IOException
{
2593 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2594 return box
.getFilename();
2598 * Convenience function to spawn an file open box.
2600 * @param path path of selected file
2601 * @param type one of the Type constants
2602 * @return the result of the new file open box
2603 * @throws IOException if java.io operation throws
2605 public final String
fileOpenBox(final String path
,
2606 final TFileOpenBox
.Type type
) throws IOException
{
2608 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2609 return box
.getFilename();
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
2620 public final TWindow
addWindow(final String title
, final int width
,
2623 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2627 * Convenience function to create a new window and make it active.
2628 * Window will be located at (0, 0).
2630 * @param title window title, will be centered along the top border
2631 * @param width width of window
2632 * @param height height of window
2633 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2635 public final TWindow
addWindow(final String title
,
2636 final int width
, final int height
, final int flags
) {
2638 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2643 * Convenience function to create a new window and make it active.
2645 * @param title window title, will be centered along the top border
2646 * @param x column relative to parent
2647 * @param y row relative to parent
2648 * @param width width of window
2649 * @param height height of window
2651 public final TWindow
addWindow(final String title
,
2652 final int x
, final int y
, final int width
, final int height
) {
2654 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2659 * Convenience function to create a new window and make it active.
2661 * @param title window title, will be centered along the top border
2662 * @param x column relative to parent
2663 * @param y row relative to parent
2664 * @param width width of window
2665 * @param height height of window
2666 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2668 public final TWindow
addWindow(final String title
,
2669 final int x
, final int y
, final int width
, final int height
,
2672 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);