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 acive 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 * Timers that are being ticked.
488 private List
<TTimer
> timers
;
491 * When true, exit the application.
493 private volatile boolean quit
= false;
496 * When true, repaint the entire screen.
498 private volatile boolean repaint
= true;
501 * Y coordinate of the top edge of the desktop. For now this is a
502 * constant. Someday it would be nice to have a multi-line menu or
505 private static final int desktopTop
= 1;
508 * Get Y coordinate of the top edge of the desktop.
510 * @return Y coordinate of the top edge of the desktop
512 public final int getDesktopTop() {
517 * Y coordinate of the bottom edge of the desktop.
519 private int desktopBottom
;
522 * Get Y coordinate of the bottom edge of the desktop.
524 * @return Y coordinate of the bottom edge of the desktop
526 public final int getDesktopBottom() {
527 return desktopBottom
;
530 // ------------------------------------------------------------------------
531 // General behavior -------------------------------------------------------
532 // ------------------------------------------------------------------------
535 * Display the about dialog.
537 protected void showAboutDialog() {
538 messageBox("About", "Jexer Version " +
539 this.getClass().getPackage().getImplementationVersion(),
540 TMessageBox
.Type
.OK
);
543 // ------------------------------------------------------------------------
544 // Constructors -----------------------------------------------------------
545 // ------------------------------------------------------------------------
548 * Public constructor.
550 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
552 * @throws UnsupportedEncodingException if an exception is thrown when
553 * creating the InputStreamReader
555 public TApplication(final BackendType backendType
)
556 throws UnsupportedEncodingException
{
558 switch (backendType
) {
560 backend
= new SwingBackend(this);
565 backend
= new ECMA48Backend(this, null, null);
568 throw new IllegalArgumentException("Invalid backend type: "
575 * Public constructor. The backend type will be BackendType.ECMA48.
577 * @param input an InputStream connected to the remote user, or null for
578 * System.in. If System.in is used, then on non-Windows systems it will
579 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
580 * mode. input is always converted to a Reader with UTF-8 encoding.
581 * @param output an OutputStream connected to the remote user, or null
582 * for System.out. output is always converted to a Writer with UTF-8
584 * @throws UnsupportedEncodingException if an exception is thrown when
585 * creating the InputStreamReader
587 public TApplication(final InputStream input
,
588 final OutputStream output
) throws UnsupportedEncodingException
{
590 backend
= new ECMA48Backend(this, input
, output
);
595 * Public constructor. The backend type will be BackendType.ECMA48.
597 * @param input the InputStream underlying 'reader'. Its available()
598 * method is used to determine if reader.read() will block or not.
599 * @param reader a Reader connected to the remote user.
600 * @param writer a PrintWriter connected to the remote user.
601 * @param setRawMode if true, set System.in into raw mode with stty.
602 * This should in general not be used. It is here solely for Demo3,
603 * which uses System.in.
604 * @throws IllegalArgumentException if input, reader, or writer are null.
606 public TApplication(final InputStream input
, final Reader reader
,
607 final PrintWriter writer
, final boolean setRawMode
) {
609 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
614 * Public constructor. The backend type will be BackendType.ECMA48.
616 * @param input the InputStream underlying 'reader'. Its available()
617 * method is used to determine if reader.read() will block or not.
618 * @param reader a Reader connected to the remote user.
619 * @param writer a PrintWriter connected to the remote user.
620 * @throws IllegalArgumentException if input, reader, or writer are null.
622 public TApplication(final InputStream input
, final Reader reader
,
623 final PrintWriter writer
) {
625 this(input
, reader
, writer
, false);
629 * Public constructor. This hook enables use with new non-Jexer
632 * @param backend a Backend that is already ready to go.
634 public TApplication(final Backend backend
) {
635 this.backend
= backend
;
640 * Finish construction once the backend is set.
642 private void TApplicationImpl() {
643 theme
= new ColorTheme();
644 desktopBottom
= getScreen().getHeight() - 1;
645 fillEventQueue
= new ArrayList
<TInputEvent
>();
646 drainEventQueue
= new ArrayList
<TInputEvent
>();
647 windows
= new LinkedList
<TWindow
>();
648 menus
= new LinkedList
<TMenu
>();
649 subMenus
= new LinkedList
<TMenu
>();
650 timers
= new LinkedList
<TTimer
>();
651 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
652 menuItems
= new ArrayList
<TMenuItem
>();
654 // Setup the main consumer thread
655 primaryEventHandler
= new WidgetEventHandler(this, true);
656 (new Thread(primaryEventHandler
)).start();
659 // ------------------------------------------------------------------------
660 // Screen refresh loop ----------------------------------------------------
661 // ------------------------------------------------------------------------
664 * Invert the cell color at a position. This is used to track the mouse.
666 * @param x column position
667 * @param y row position
669 private void invertCell(final int x
, final int y
) {
671 System
.err
.printf("invertCell() %d %d\n", x
, y
);
673 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
674 attr
.setForeColor(attr
.getForeColor().invert());
675 attr
.setBackColor(attr
.getBackColor().invert());
676 getScreen().putAttrXY(x
, y
, attr
, false);
682 private void drawAll() {
684 System
.err
.printf("drawAll() enter\n");
689 System
.err
.printf("drawAll() !repaint\n");
691 synchronized (getScreen()) {
692 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
693 // The only thing that has happened is the mouse moved.
694 // Clear the old position and draw the new position.
695 invertCell(oldMouseX
, oldMouseY
);
696 invertCell(mouseX
, mouseY
);
700 if (getScreen().isDirty()) {
701 backend
.flushScreen();
708 System
.err
.printf("drawAll() REDRAW\n");
711 // If true, the cursor is not visible
712 boolean cursor
= false;
714 // Start with a clean screen
717 // Draw the background
718 CellAttributes background
= theme
.getColor("tapplication.background");
719 getScreen().putAll(GraphicsChars
.HATCH
, background
);
721 // Draw each window in reverse Z order
722 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
723 Collections
.sort(sorted
);
724 TWindow topLevel
= null;
725 if (sorted
.size() > 0) {
726 topLevel
= sorted
.get(0);
728 Collections
.reverse(sorted
);
729 for (TWindow window
: sorted
) {
730 window
.drawChildren();
733 // Draw the blank menubar line - reset the screen clipping first so
734 // it won't trim it out.
735 getScreen().resetClipping();
736 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
737 theme
.getColor("tmenu"));
738 // Now draw the menus.
740 for (TMenu menu
: menus
) {
741 CellAttributes menuColor
;
742 CellAttributes menuMnemonicColor
;
743 if (menu
.isActive()) {
744 menuColor
= theme
.getColor("tmenu.highlighted");
745 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
748 menuColor
= theme
.getColor("tmenu");
749 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
751 // Draw the menu title
752 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
754 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
755 // Draw the highlight character
756 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
757 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
759 if (menu
.isActive()) {
761 // Reset the screen clipping so we can draw the next title.
762 getScreen().resetClipping();
764 x
+= menu
.getTitle().length() + 2;
767 for (TMenu menu
: subMenus
) {
768 // Reset the screen clipping so we can draw the next sub-menu.
769 getScreen().resetClipping();
773 // Draw the status bar of the top-level window
774 TStatusBar statusBar
= null;
775 if (topLevel
!= null) {
776 statusBar
= topLevel
.getStatusBar();
778 if (statusBar
!= null) {
779 getScreen().resetClipping();
780 statusBar
.setWidth(getScreen().getWidth());
781 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
784 CellAttributes barColor
= new CellAttributes();
785 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
786 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
790 // Draw the mouse pointer
791 invertCell(mouseX
, mouseY
);
795 // Place the cursor if it is visible
796 TWidget activeWidget
= null;
797 if (sorted
.size() > 0) {
798 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
799 if (activeWidget
.isCursorVisible()) {
800 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
801 activeWidget
.getCursorAbsoluteY());
808 getScreen().hideCursor();
811 // Flush the screen contents
812 if (getScreen().isDirty()) {
813 backend
.flushScreen();
819 // ------------------------------------------------------------------------
820 // Main loop --------------------------------------------------------------
821 // ------------------------------------------------------------------------
824 * Run this application until it exits.
828 // Timeout is in milliseconds, so default timeout after 1 second
832 // If I've got no updates to render, wait for something from the
833 // backend or a timer.
835 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
837 // Never sleep longer than 50 millis. We need time for
838 // windows with background tasks to update the display, and
839 // still flip buffers reasonably quickly in
840 // backend.flushPhysical().
841 timeout
= getSleepTime(50);
845 // As of now, I've got nothing to do: no I/O, nothing from
846 // the consumer threads, no timers that need to run ASAP. So
847 // wait until either the backend or the consumer threads have
851 System
.err
.println("sleep " + timeout
+ " millis");
853 synchronized (this) {
856 } catch (InterruptedException e
) {
857 // I'm awake and don't care why, let's see what's going
863 // Prevent stepping on the primary or secondary event handler.
866 // Pull any pending I/O events
867 backend
.getEvents(fillEventQueue
);
869 // Dispatch each event to the appropriate handler, one at a time.
871 TInputEvent event
= null;
872 if (fillEventQueue
.size() == 0) {
875 event
= fillEventQueue
.remove(0);
876 metaHandleEvent(event
);
879 // Wake a consumer thread if we have any pending events.
880 if (drainEventQueue
.size() > 0) {
884 // Process timers and call doIdle()'s
888 synchronized (getScreen()) {
892 // Let the event handlers run again.
893 startEventHandlers();
897 // Shutdown the event consumer threads
898 if (secondaryEventHandler
!= null) {
899 synchronized (secondaryEventHandler
) {
900 secondaryEventHandler
.notify();
903 if (primaryEventHandler
!= null) {
904 synchronized (primaryEventHandler
) {
905 primaryEventHandler
.notify();
909 // Shutdown the user I/O thread(s)
912 // Close all the windows. This gives them an opportunity to release
919 * Peek at certain application-level events, add to eventQueue, and wake
920 * up the consuming Thread.
922 * @param event the input event to consume
924 private void metaHandleEvent(final TInputEvent event
) {
927 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
928 event
)); System
.err
.flush();
932 // Do no more processing if the application is already trying
937 // Special application-wide events -------------------------------
940 if (event
instanceof TCommandEvent
) {
941 TCommandEvent command
= (TCommandEvent
) event
;
942 if (command
.getCmd().equals(cmAbort
)) {
949 if (event
instanceof TResizeEvent
) {
950 TResizeEvent resize
= (TResizeEvent
) event
;
951 synchronized (getScreen()) {
952 getScreen().setDimensions(resize
.getWidth(),
954 desktopBottom
= getScreen().getHeight() - 1;
963 // Peek at the mouse position
964 if (event
instanceof TMouseEvent
) {
965 TMouseEvent mouse
= (TMouseEvent
) event
;
966 synchronized (getScreen()) {
967 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
970 mouseX
= mouse
.getX();
971 mouseY
= mouse
.getY();
976 // Put into the main queue
977 drainEventQueue
.add(event
);
981 * Dispatch one event to the appropriate widget or application-level
982 * event handler. This is the primary event handler, it has the normal
983 * application-wide event handling.
985 * @param event the input event to consume
986 * @see #secondaryHandleEvent(TInputEvent event)
988 private void primaryHandleEvent(final TInputEvent event
) {
991 System
.err
.printf("Handle event: %s\n", event
);
994 // Special application-wide events -----------------------------------
996 // Peek at the mouse position
997 if (event
instanceof TMouseEvent
) {
998 // See if we need to switch focus to another window or the menu
999 checkSwitchFocus((TMouseEvent
) event
);
1002 // Handle menu events
1003 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1004 TMenu menu
= activeMenu
;
1006 if (event
instanceof TMouseEvent
) {
1007 TMouseEvent mouse
= (TMouseEvent
) event
;
1009 while (subMenus
.size() > 0) {
1010 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1011 if (subMenu
.mouseWouldHit(mouse
)) {
1014 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1015 && (!mouse
.isMouse1())
1016 && (!mouse
.isMouse2())
1017 && (!mouse
.isMouse3())
1018 && (!mouse
.isMouseWheelUp())
1019 && (!mouse
.isMouseWheelDown())
1023 // We navigated away from a sub-menu, so close it
1027 // Convert the mouse relative x/y to menu coordinates
1028 assert (mouse
.getX() == mouse
.getAbsoluteX());
1029 assert (mouse
.getY() == mouse
.getAbsoluteY());
1030 if (subMenus
.size() > 0) {
1031 menu
= subMenus
.get(subMenus
.size() - 1);
1033 mouse
.setX(mouse
.getX() - menu
.getX());
1034 mouse
.setY(mouse
.getY() - menu
.getY());
1036 menu
.handleEvent(event
);
1040 if (event
instanceof TKeypressEvent
) {
1041 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1043 // See if this key matches an accelerator, and is not being
1044 // shortcutted by the active window, and if so dispatch the menu
1046 boolean windowWillShortcut
= false;
1047 for (TWindow window
: windows
) {
1048 if (window
.isActive()) {
1049 if (window
.isShortcutKeypress(keypress
.getKey())) {
1050 // We do not process this key, it will be passed to
1051 // the window instead.
1052 windowWillShortcut
= true;
1057 if (!windowWillShortcut
&& !modalWindowActive()) {
1058 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1059 TMenuItem item
= null;
1060 synchronized (accelerators
) {
1061 item
= accelerators
.get(keypressLowercase
);
1064 if (item
.isEnabled()) {
1065 // Let the menu item dispatch
1071 // Handle the keypress
1072 if (onKeypress(keypress
)) {
1078 if (event
instanceof TCommandEvent
) {
1079 if (onCommand((TCommandEvent
) event
)) {
1084 if (event
instanceof TMenuEvent
) {
1085 if (onMenu((TMenuEvent
) event
)) {
1090 // Dispatch events to the active window -------------------------------
1091 for (TWindow window
: windows
) {
1092 if (window
.isActive()) {
1093 if (event
instanceof TMouseEvent
) {
1094 TMouseEvent mouse
= (TMouseEvent
) event
;
1095 // Convert the mouse relative x/y to window coordinates
1096 assert (mouse
.getX() == mouse
.getAbsoluteX());
1097 assert (mouse
.getY() == mouse
.getAbsoluteY());
1098 mouse
.setX(mouse
.getX() - window
.getX());
1099 mouse
.setY(mouse
.getY() - window
.getY());
1102 System
.err
.printf("TApplication dispatch event: %s\n",
1105 window
.handleEvent(event
);
1111 * Dispatch one event to the appropriate widget or application-level
1112 * event handler. This is the secondary event handler used by certain
1113 * special dialogs (currently TMessageBox and TFileOpenBox).
1115 * @param event the input event to consume
1116 * @see #primaryHandleEvent(TInputEvent event)
1118 private void secondaryHandleEvent(final TInputEvent event
) {
1119 secondaryEventReceiver
.handleEvent(event
);
1123 * Enable a widget to override the primary event thread.
1125 * @param widget widget that will receive events
1127 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1128 assert (secondaryEventReceiver
== null);
1129 assert (secondaryEventHandler
== null);
1130 assert ((widget
instanceof TMessageBox
)
1131 || (widget
instanceof TFileOpenBox
));
1132 secondaryEventReceiver
= widget
;
1133 secondaryEventHandler
= new WidgetEventHandler(this, false);
1134 (new Thread(secondaryEventHandler
)).start();
1138 * Yield to the secondary thread.
1140 public final void yield() {
1141 assert (secondaryEventReceiver
!= null);
1142 // This is where we handoff the event handler lock from the primary
1143 // to secondary thread. We unlock here, and in a future loop the
1144 // secondary thread locks again. When it gives up, we have the
1145 // single lock back.
1146 boolean oldLock
= unlockHandleEvent();
1149 while (secondaryEventReceiver
!= null) {
1150 synchronized (primaryEventHandler
) {
1152 primaryEventHandler
.wait();
1153 } catch (InterruptedException e
) {
1161 * Do stuff when there is no user input.
1163 private void doIdle() {
1165 System
.err
.printf("doIdle()\n");
1168 // Now run any timers that have timed out
1169 Date now
= new Date();
1170 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1171 for (TTimer timer
: timers
) {
1172 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1174 if (timer
.recurring
) {
1175 keepTimers
.add(timer
);
1178 keepTimers
.add(timer
);
1181 timers
= keepTimers
;
1184 for (TWindow window
: windows
) {
1189 // ------------------------------------------------------------------------
1190 // TWindow management -----------------------------------------------------
1191 // ------------------------------------------------------------------------
1194 * Close window. Note that the window's destructor is NOT called by this
1195 * method, instead the GC is assumed to do the cleanup.
1197 * @param window the window to remove
1199 public final void closeWindow(final TWindow window
) {
1200 synchronized (windows
) {
1201 int z
= window
.getZ();
1204 Collections
.sort(windows
);
1206 TWindow activeWindow
= null;
1207 for (TWindow w
: windows
) {
1209 w
.setZ(w
.getZ() - 1);
1210 if (w
.getZ() == 0) {
1213 assert (activeWindow
== null);
1225 // Perform window cleanup
1228 // Check if we are closing a TMessageBox or similar
1229 if (secondaryEventReceiver
!= null) {
1230 assert (secondaryEventHandler
!= null);
1232 // Do not send events to the secondaryEventReceiver anymore, the
1233 // window is closed.
1234 secondaryEventReceiver
= null;
1236 // Wake the secondary thread, it will wake the primary as it
1238 synchronized (secondaryEventHandler
) {
1239 secondaryEventHandler
.notify();
1245 * Switch to the next window.
1247 * @param forward if true, then switch to the next window in the list,
1248 * otherwise switch to the previous window in the list
1250 public final void switchWindow(final boolean forward
) {
1251 // Only switch if there are multiple windows
1252 if (windows
.size() < 2) {
1256 synchronized (windows
) {
1258 // Swap z/active between active window and the next in the list
1259 int activeWindowI
= -1;
1260 for (int i
= 0; i
< windows
.size(); i
++) {
1261 if (windows
.get(i
).isActive()) {
1266 assert (activeWindowI
>= 0);
1268 // Do not switch if a window is modal
1269 if (windows
.get(activeWindowI
).isModal()) {
1275 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1277 if (activeWindowI
== 0) {
1278 nextWindowI
= windows
.size() - 1;
1280 nextWindowI
= activeWindowI
- 1;
1283 windows
.get(activeWindowI
).setActive(false);
1284 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1285 windows
.get(activeWindowI
).onUnfocus();
1286 windows
.get(nextWindowI
).setZ(0);
1287 windows
.get(nextWindowI
).setActive(true);
1288 windows
.get(nextWindowI
).onFocus();
1290 } // synchronized (windows)
1295 * Add a window to my window list and make it active.
1297 * @param window new window to add
1299 public final void addWindow(final TWindow window
) {
1301 // Do not add menu windows to the window list.
1302 if (window
instanceof TMenu
) {
1306 synchronized (windows
) {
1307 // Do not allow a modal window to spawn a non-modal window. If a
1308 // modal window is active, then this window will become modal
1310 if (modalWindowActive()) {
1311 window
.flags
|= TWindow
.MODAL
;
1312 window
.flags
|= TWindow
.CENTERED
;
1314 for (TWindow w
: windows
) {
1319 w
.setZ(w
.getZ() + 1);
1321 windows
.add(window
);
1323 window
.setActive(true);
1326 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1327 && smartWindowPlacement
) {
1329 doSmartPlacement(window
);
1335 * Check if there is a system-modal window on top.
1337 * @return true if the active window is modal
1339 private boolean modalWindowActive() {
1340 if (windows
.size() == 0) {
1344 for (TWindow w
: windows
) {
1354 * Close all open windows.
1356 private void closeAllWindows() {
1357 // Don't do anything if we are in the menu
1358 if (activeMenu
!= null) {
1361 while (windows
.size() > 0) {
1362 closeWindow(windows
.get(0));
1367 * Re-layout the open windows as non-overlapping tiles. This produces
1368 * almost the same results as Turbo Pascal 7.0's IDE.
1370 private void tileWindows() {
1371 synchronized (windows
) {
1372 // Don't do anything if we are in the menu
1373 if (activeMenu
!= null) {
1376 int z
= windows
.size();
1382 a
= (int)(Math
.sqrt(z
));
1386 if (((a
* b
) + c
) == z
) {
1394 int newWidth
= (getScreen().getWidth() / a
);
1395 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1396 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1398 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1399 Collections
.sort(sorted
);
1400 Collections
.reverse(sorted
);
1401 for (int i
= 0; i
< sorted
.size(); i
++) {
1402 int logicalX
= i
/ b
;
1403 int logicalY
= i
% b
;
1404 if (i
>= ((a
- 1) * b
)) {
1406 logicalY
= i
- ((a
- 1) * b
);
1409 TWindow w
= sorted
.get(i
);
1410 w
.setX(logicalX
* newWidth
);
1411 w
.setWidth(newWidth
);
1412 if (i
>= ((a
- 1) * b
)) {
1413 w
.setY((logicalY
* newHeight2
) + 1);
1414 w
.setHeight(newHeight2
);
1416 w
.setY((logicalY
* newHeight1
) + 1);
1417 w
.setHeight(newHeight1
);
1424 * Re-layout the open windows as overlapping cascaded windows.
1426 private void cascadeWindows() {
1427 synchronized (windows
) {
1428 // Don't do anything if we are in the menu
1429 if (activeMenu
!= null) {
1434 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1435 Collections
.sort(sorted
);
1436 Collections
.reverse(sorted
);
1437 for (TWindow window
: sorted
) {
1442 if (x
> getScreen().getWidth()) {
1445 if (y
>= getScreen().getHeight()) {
1453 * Place a window to minimize its overlap with other windows.
1455 * @param window the window to place
1457 public final void doSmartPlacement(final TWindow window
) {
1458 // This is a pretty dumb algorithm, but seems to work. The hardest
1459 // part is computing these "overlap" values seeking a minimum average
1462 int yMin
= desktopTop
;
1463 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1464 int yMax
= desktopBottom
- window
.getHeight() + 1;
1472 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1473 // No work to do, bail out.
1477 // Compute the overlap matrix without the new window.
1478 int width
= getScreen().getWidth();
1479 int height
= getScreen().getHeight();
1480 int overlapMatrix
[][] = new int[width
][height
];
1481 for (TWindow w
: windows
) {
1485 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1489 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1493 overlapMatrix
[x
][y
]++;
1498 long oldOverlapTotal
= 0;
1499 long oldOverlapN
= 0;
1500 for (int x
= 0; x
< width
; x
++) {
1501 for (int y
= 0; y
< height
; y
++) {
1502 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1503 if (overlapMatrix
[x
][y
] > 0) {
1510 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1511 boolean first
= true;
1512 int windowX
= window
.getX();
1513 int windowY
= window
.getY();
1515 // For each possible (x, y) position for the new window, compute a
1516 // new overlap matrix.
1517 for (int x
= xMin
; x
< xMax
; x
++) {
1518 for (int y
= yMin
; y
< yMax
; y
++) {
1520 // Start with the matrix minus this window.
1521 int newMatrix
[][] = new int[width
][height
];
1522 for (int mx
= 0; mx
< width
; mx
++) {
1523 for (int my
= 0; my
< height
; my
++) {
1524 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1528 // Add this window's values to the new overlap matrix.
1529 long newOverlapTotal
= 0;
1530 long newOverlapN
= 0;
1531 // Start by adding each new cell.
1532 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1536 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1540 newMatrix
[wx
][wy
]++;
1543 // Now figure out the new value for total coverage.
1544 for (int mx
= 0; mx
< width
; mx
++) {
1545 for (int my
= 0; my
< height
; my
++) {
1546 newOverlapTotal
+= newMatrix
[x
][y
];
1547 if (newMatrix
[mx
][my
] > 0) {
1552 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1555 // First time: just record what we got.
1556 oldOverlapAvg
= newOverlapAvg
;
1559 // All other times: pick a new best (x, y) and save the
1561 if (newOverlapAvg
< oldOverlapAvg
) {
1564 oldOverlapAvg
= newOverlapAvg
;
1568 } // for (int x = xMin; x < xMax; x++)
1570 } // for (int y = yMin; y < yMax; y++)
1572 // Finally, set the window's new coordinates.
1573 window
.setX(windowX
);
1574 window
.setY(windowY
);
1577 // ------------------------------------------------------------------------
1578 // TMenu management -------------------------------------------------------
1579 // ------------------------------------------------------------------------
1582 * Check if a mouse event would hit either the active menu or any open
1585 * @param mouse mouse event
1586 * @return true if the mouse would hit the active menu or an open
1589 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1590 assert (activeMenu
!= null);
1591 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1592 Collections
.reverse(menus
);
1593 for (TMenu menu
: menus
) {
1594 if (menu
.mouseWouldHit(mouse
)) {
1598 return activeMenu
.mouseWouldHit(mouse
);
1602 * See if we need to switch window or activate the menu based on
1605 * @param mouse mouse event
1607 private void checkSwitchFocus(final TMouseEvent mouse
) {
1609 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1610 && (activeMenu
!= null)
1611 && (mouse
.getAbsoluteY() != 0)
1612 && (!mouseOnMenu(mouse
))
1614 // They clicked outside the active menu, turn it off
1615 activeMenu
.setActive(false);
1617 for (TMenu menu
: subMenus
) {
1618 menu
.setActive(false);
1624 // See if they hit the menu bar
1625 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1626 && (mouse
.isMouse1())
1627 && (!modalWindowActive())
1628 && (mouse
.getAbsoluteY() == 0)
1631 for (TMenu menu
: subMenus
) {
1632 menu
.setActive(false);
1636 // They selected the menu, go activate it
1637 for (TMenu menu
: menus
) {
1638 if ((mouse
.getAbsoluteX() >= menu
.getX())
1639 && (mouse
.getAbsoluteX() < menu
.getX()
1640 + menu
.getTitle().length() + 2)
1642 menu
.setActive(true);
1645 menu
.setActive(false);
1651 // See if they hit the menu bar
1652 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1653 && (mouse
.isMouse1())
1654 && (activeMenu
!= null)
1655 && (mouse
.getAbsoluteY() == 0)
1658 TMenu oldMenu
= activeMenu
;
1659 for (TMenu menu
: subMenus
) {
1660 menu
.setActive(false);
1664 // See if we should switch menus
1665 for (TMenu menu
: menus
) {
1666 if ((mouse
.getAbsoluteX() >= menu
.getX())
1667 && (mouse
.getAbsoluteX() < menu
.getX()
1668 + menu
.getTitle().length() + 2)
1670 menu
.setActive(true);
1674 if (oldMenu
!= activeMenu
) {
1675 // They switched menus
1676 oldMenu
.setActive(false);
1681 // Only switch if there are multiple windows
1682 if (windows
.size() < 2) {
1686 // Switch on the upclick
1687 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1691 synchronized (windows
) {
1692 Collections
.sort(windows
);
1693 if (windows
.get(0).isModal()) {
1694 // Modal windows don't switch
1698 for (TWindow window
: windows
) {
1699 assert (!window
.isModal());
1700 if (window
.mouseWouldHit(mouse
)) {
1701 if (window
== windows
.get(0)) {
1702 // Clicked on the same window, nothing to do
1706 // We will be switching to another window
1707 assert (windows
.get(0).isActive());
1708 assert (!window
.isActive());
1709 windows
.get(0).onUnfocus();
1710 windows
.get(0).setActive(false);
1711 windows
.get(0).setZ(window
.getZ());
1713 window
.setActive(true);
1720 // Clicked on the background, nothing to do
1725 * Turn off the menu.
1727 public final void closeMenu() {
1728 if (activeMenu
!= null) {
1729 activeMenu
.setActive(false);
1731 for (TMenu menu
: subMenus
) {
1732 menu
.setActive(false);
1739 * Turn off a sub-menu.
1741 public final void closeSubMenu() {
1742 assert (activeMenu
!= null);
1743 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1744 assert (item
!= null);
1745 item
.setActive(false);
1746 subMenus
.remove(subMenus
.size() - 1);
1750 * Switch to the next menu.
1752 * @param forward if true, then switch to the next menu in the list,
1753 * otherwise switch to the previous menu in the list
1755 public final void switchMenu(final boolean forward
) {
1756 assert (activeMenu
!= null);
1758 for (TMenu menu
: subMenus
) {
1759 menu
.setActive(false);
1763 for (int i
= 0; i
< menus
.size(); i
++) {
1764 if (activeMenu
== menus
.get(i
)) {
1766 if (i
< menus
.size() - 1) {
1774 activeMenu
.setActive(false);
1775 activeMenu
= menus
.get(i
);
1776 activeMenu
.setActive(true);
1783 * Add a menu item to the global list. If it has a keyboard accelerator,
1784 * that will be added the global hash.
1786 * @param item the menu item
1788 public final void addMenuItem(final TMenuItem item
) {
1789 menuItems
.add(item
);
1791 TKeypress key
= item
.getKey();
1793 synchronized (accelerators
) {
1794 assert (accelerators
.get(key
) == null);
1795 accelerators
.put(key
.toLowerCase(), item
);
1801 * Disable one menu item.
1803 * @param id the menu item ID
1805 public final void disableMenuItem(final int id
) {
1806 for (TMenuItem item
: menuItems
) {
1807 if (item
.getId() == id
) {
1808 item
.setEnabled(false);
1814 * Disable the range of menu items with ID's between lower and upper,
1817 * @param lower the lowest menu item ID
1818 * @param upper the highest menu item ID
1820 public final void disableMenuItems(final int lower
, final int upper
) {
1821 for (TMenuItem item
: menuItems
) {
1822 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1823 item
.setEnabled(false);
1829 * Enable one menu item.
1831 * @param id the menu item ID
1833 public final void enableMenuItem(final int id
) {
1834 for (TMenuItem item
: menuItems
) {
1835 if (item
.getId() == id
) {
1836 item
.setEnabled(true);
1842 * Enable the range of menu items with ID's between lower and upper,
1845 * @param lower the lowest menu item ID
1846 * @param upper the highest menu item ID
1848 public final void enableMenuItems(final int lower
, final int upper
) {
1849 for (TMenuItem item
: menuItems
) {
1850 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1851 item
.setEnabled(true);
1857 * Recompute menu x positions based on their title length.
1859 public final void recomputeMenuX() {
1861 for (TMenu menu
: menus
) {
1863 x
+= menu
.getTitle().length() + 2;
1868 * Post an event to process and turn off the menu.
1870 * @param event new event to add to the queue
1872 public final void postMenuEvent(final TInputEvent event
) {
1873 synchronized (fillEventQueue
) {
1874 fillEventQueue
.add(event
);
1880 * Add a sub-menu to the list of open sub-menus.
1882 * @param menu sub-menu
1884 public final void addSubMenu(final TMenu menu
) {
1889 * Convenience function to add a top-level menu.
1891 * @param title menu title
1892 * @return the new menu
1894 public final TMenu
addMenu(final String title
) {
1897 TMenu menu
= new TMenu(this, x
, y
, title
);
1904 * Convenience function to add a default "File" menu.
1906 * @return the new menu
1908 public final TMenu
addFileMenu() {
1909 TMenu fileMenu
= addMenu("&File");
1910 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1911 fileMenu
.addSeparator();
1912 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1913 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1914 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
1915 "commands (Open, Save, Print, etc.)");
1916 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1921 * Convenience function to add a default "Edit" menu.
1923 * @return the new menu
1925 public final TMenu
addEditMenu() {
1926 TMenu editMenu
= addMenu("&Edit");
1927 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1928 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1929 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1930 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1931 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
1932 "undo, and Clipboard access");
1933 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1938 * Convenience function to add a default "Window" menu.
1940 * @return the new menu
1942 public final TMenu
addWindowMenu() {
1943 TMenu windowMenu
= addMenu("&Window");
1944 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1945 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1946 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1947 windowMenu
.addSeparator();
1948 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1949 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1950 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1951 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1952 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1953 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
1955 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1960 * Convenience function to add a default "Help" menu.
1962 * @return the new menu
1964 public final TMenu
addHelpMenu() {
1965 TMenu helpMenu
= addMenu("&Help");
1966 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
1967 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
1968 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
1969 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
1970 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
1971 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
1972 helpMenu
.addSeparator();
1973 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
1974 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
1975 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1979 // ------------------------------------------------------------------------
1980 // Event handlers ---------------------------------------------------------
1981 // ------------------------------------------------------------------------
1984 * Method that TApplication subclasses can override to handle menu or
1985 * posted command events.
1987 * @param command command event
1988 * @return if true, this event was consumed
1990 protected boolean onCommand(final TCommandEvent command
) {
1991 // Default: handle cmExit
1992 if (command
.equals(cmExit
)) {
1993 if (messageBox("Confirmation", "Exit application?",
1994 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2000 if (command
.equals(cmShell
)) {
2001 openTerminal(0, 0, TWindow
.RESIZABLE
);
2005 if (command
.equals(cmTile
)) {
2009 if (command
.equals(cmCascade
)) {
2013 if (command
.equals(cmCloseAll
)) {
2022 * Method that TApplication subclasses can override to handle menu
2025 * @param menu menu event
2026 * @return if true, this event was consumed
2028 protected boolean onMenu(final TMenuEvent menu
) {
2030 // Default: handle MID_EXIT
2031 if (menu
.getId() == TMenu
.MID_EXIT
) {
2032 if (messageBox("Confirmation", "Exit application?",
2033 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2039 if (menu
.getId() == TMenu
.MID_SHELL
) {
2040 openTerminal(0, 0, TWindow
.RESIZABLE
);
2044 if (menu
.getId() == TMenu
.MID_TILE
) {
2048 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2052 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2056 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2064 * Method that TApplication subclasses can override to handle keystrokes.
2066 * @param keypress keystroke event
2067 * @return if true, this event was consumed
2069 protected boolean onKeypress(final TKeypressEvent keypress
) {
2070 // Default: only menu shortcuts
2072 // Process Alt-F, Alt-E, etc. menu shortcut keys
2073 if (!keypress
.getKey().isFnKey()
2074 && keypress
.getKey().isAlt()
2075 && !keypress
.getKey().isCtrl()
2076 && (activeMenu
== null)
2077 && !modalWindowActive()
2080 assert (subMenus
.size() == 0);
2082 for (TMenu menu
: menus
) {
2083 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2084 == Character
.toLowerCase(keypress
.getKey().getChar())
2087 menu
.setActive(true);
2096 // ------------------------------------------------------------------------
2097 // TTimer management ------------------------------------------------------
2098 // ------------------------------------------------------------------------
2101 * Get the amount of time I can sleep before missing a Timer tick.
2103 * @param timeout = initial (maximum) timeout in millis
2104 * @return number of milliseconds between now and the next timer event
2106 private long getSleepTime(final long timeout
) {
2107 Date now
= new Date();
2108 long nowTime
= now
.getTime();
2109 long sleepTime
= timeout
;
2110 for (TTimer timer
: timers
) {
2111 long nextTickTime
= timer
.getNextTick().getTime();
2112 if (nextTickTime
< nowTime
) {
2116 long timeDifference
= nextTickTime
- nowTime
;
2117 if (timeDifference
< sleepTime
) {
2118 sleepTime
= timeDifference
;
2121 assert (sleepTime
>= 0);
2122 assert (sleepTime
<= timeout
);
2127 * Convenience function to add a timer.
2129 * @param duration number of milliseconds to wait between ticks
2130 * @param recurring if true, re-schedule this timer after every tick
2131 * @param action function to call when button is pressed
2134 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2135 final TAction action
) {
2137 TTimer timer
= new TTimer(duration
, recurring
, action
);
2138 synchronized (timers
) {
2145 * Convenience function to remove a timer.
2147 * @param timer timer to remove
2149 public final void removeTimer(final TTimer timer
) {
2150 synchronized (timers
) {
2151 timers
.remove(timer
);
2155 // ------------------------------------------------------------------------
2156 // Other TWindow constructors ---------------------------------------------
2157 // ------------------------------------------------------------------------
2160 * Convenience function to spawn a message box.
2162 * @param title window title, will be centered along the top border
2163 * @param caption message to display. Use embedded newlines to get a
2165 * @return the new message box
2167 public final TMessageBox
messageBox(final String title
,
2168 final String caption
) {
2170 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2174 * Convenience function to spawn a message box.
2176 * @param title window title, will be centered along the top border
2177 * @param caption message to display. Use embedded newlines to get a
2179 * @param type one of the TMessageBox.Type constants. Default is
2181 * @return the new message box
2183 public final TMessageBox
messageBox(final String title
,
2184 final String caption
, final TMessageBox
.Type type
) {
2186 return new TMessageBox(this, title
, caption
, type
);
2190 * Convenience function to spawn an input box.
2192 * @param title window title, will be centered along the top border
2193 * @param caption message to display. Use embedded newlines to get a
2195 * @return the new input box
2197 public final TInputBox
inputBox(final String title
, final String caption
) {
2199 return new TInputBox(this, title
, caption
);
2203 * Convenience function to spawn an input box.
2205 * @param title window title, will be centered along the top border
2206 * @param caption message to display. Use embedded newlines to get a
2208 * @param text initial text to seed the field with
2209 * @return the new input box
2211 public final TInputBox
inputBox(final String title
, final String caption
,
2212 final String text
) {
2214 return new TInputBox(this, title
, caption
, text
);
2218 * Convenience function to open a terminal window.
2220 * @param x column relative to parent
2221 * @param y row relative to parent
2222 * @return the terminal new window
2224 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2225 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2229 * Convenience function to open a terminal window.
2231 * @param x column relative to parent
2232 * @param y row relative to parent
2233 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2234 * @return the terminal new window
2236 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2239 return new TTerminalWindow(this, x
, y
, flags
);
2243 * Convenience function to spawn an file open box.
2245 * @param path path of selected file
2246 * @return the result of the new file open box
2247 * @throws IOException if java.io operation throws
2249 public final String
fileOpenBox(final String path
) throws IOException
{
2251 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2252 return box
.getFilename();
2256 * Convenience function to spawn an file open box.
2258 * @param path path of selected file
2259 * @param type one of the Type constants
2260 * @return the result of the new file open box
2261 * @throws IOException if java.io operation throws
2263 public final String
fileOpenBox(final String path
,
2264 final TFileOpenBox
.Type type
) throws IOException
{
2266 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2267 return box
.getFilename();