2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2016 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
= sorted
.get(0);
725 Collections
.reverse(sorted
);
726 for (TWindow window
: sorted
) {
727 window
.drawChildren();
730 // Draw the blank menubar line - reset the screen clipping first so
731 // it won't trim it out.
732 getScreen().resetClipping();
733 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
734 theme
.getColor("tmenu"));
735 // Now draw the menus.
737 for (TMenu menu
: menus
) {
738 CellAttributes menuColor
;
739 CellAttributes menuMnemonicColor
;
740 if (menu
.isActive()) {
741 menuColor
= theme
.getColor("tmenu.highlighted");
742 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
745 menuColor
= theme
.getColor("tmenu");
746 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
748 // Draw the menu title
749 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
751 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
752 // Draw the highlight character
753 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
754 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
756 if (menu
.isActive()) {
758 // Reset the screen clipping so we can draw the next title.
759 getScreen().resetClipping();
761 x
+= menu
.getTitle().length() + 2;
764 for (TMenu menu
: subMenus
) {
765 // Reset the screen clipping so we can draw the next sub-menu.
766 getScreen().resetClipping();
770 // Draw the status bar of the top-level window
771 TStatusBar statusBar
= topLevel
.getStatusBar();
772 if (statusBar
!= null) {
773 getScreen().resetClipping();
774 statusBar
.setWidth(getScreen().getWidth());
775 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
778 CellAttributes barColor
= new CellAttributes();
779 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
780 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
784 // Draw the mouse pointer
785 invertCell(mouseX
, mouseY
);
789 // Place the cursor if it is visible
790 TWidget activeWidget
= null;
791 if (sorted
.size() > 0) {
792 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
793 if (activeWidget
.isCursorVisible()) {
794 getScreen().putCursor(true, activeWidget
.getCursorAbsoluteX(),
795 activeWidget
.getCursorAbsoluteY());
802 getScreen().hideCursor();
805 // Flush the screen contents
806 if (getScreen().isDirty()) {
807 backend
.flushScreen();
813 // ------------------------------------------------------------------------
814 // Main loop --------------------------------------------------------------
815 // ------------------------------------------------------------------------
818 * Run this application until it exits.
822 // Timeout is in milliseconds, so default timeout after 1 second
826 // If I've got no updates to render, wait for something from the
827 // backend or a timer.
829 && ((mouseX
== oldMouseX
) && (mouseY
== oldMouseY
))
831 // Never sleep longer than 50 millis. We need time for
832 // windows with background tasks to update the display, and
833 // still flip buffers reasonably quickly in
834 // backend.flushPhysical().
835 timeout
= getSleepTime(50);
839 // As of now, I've got nothing to do: no I/O, nothing from
840 // the consumer threads, no timers that need to run ASAP. So
841 // wait until either the backend or the consumer threads have
845 System
.err
.println("sleep " + timeout
+ " millis");
847 synchronized (this) {
850 } catch (InterruptedException e
) {
851 // I'm awake and don't care why, let's see what's going
857 // Prevent stepping on the primary or secondary event handler.
860 // Pull any pending I/O events
861 backend
.getEvents(fillEventQueue
);
863 // Dispatch each event to the appropriate handler, one at a time.
865 TInputEvent event
= null;
866 if (fillEventQueue
.size() == 0) {
869 event
= fillEventQueue
.remove(0);
870 metaHandleEvent(event
);
873 // Wake a consumer thread if we have any pending events.
874 if (drainEventQueue
.size() > 0) {
878 // Process timers and call doIdle()'s
882 synchronized (getScreen()) {
886 // Let the event handlers run again.
887 startEventHandlers();
891 // Shutdown the event consumer threads
892 if (secondaryEventHandler
!= null) {
893 synchronized (secondaryEventHandler
) {
894 secondaryEventHandler
.notify();
897 if (primaryEventHandler
!= null) {
898 synchronized (primaryEventHandler
) {
899 primaryEventHandler
.notify();
903 // Shutdown the user I/O thread(s)
906 // Close all the windows. This gives them an opportunity to release
913 * Peek at certain application-level events, add to eventQueue, and wake
914 * up the consuming Thread.
916 * @param event the input event to consume
918 private void metaHandleEvent(final TInputEvent event
) {
921 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
922 event
)); System
.err
.flush();
926 // Do no more processing if the application is already trying
931 // Special application-wide events -------------------------------
934 if (event
instanceof TCommandEvent
) {
935 TCommandEvent command
= (TCommandEvent
) event
;
936 if (command
.getCmd().equals(cmAbort
)) {
943 if (event
instanceof TResizeEvent
) {
944 TResizeEvent resize
= (TResizeEvent
) event
;
945 synchronized (getScreen()) {
946 getScreen().setDimensions(resize
.getWidth(),
948 desktopBottom
= getScreen().getHeight() - 1;
957 // Peek at the mouse position
958 if (event
instanceof TMouseEvent
) {
959 TMouseEvent mouse
= (TMouseEvent
) event
;
960 synchronized (getScreen()) {
961 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
964 mouseX
= mouse
.getX();
965 mouseY
= mouse
.getY();
970 // Put into the main queue
971 drainEventQueue
.add(event
);
975 * Dispatch one event to the appropriate widget or application-level
976 * event handler. This is the primary event handler, it has the normal
977 * application-wide event handling.
979 * @param event the input event to consume
980 * @see #secondaryHandleEvent(TInputEvent event)
982 private void primaryHandleEvent(final TInputEvent event
) {
985 System
.err
.printf("Handle event: %s\n", event
);
988 // Special application-wide events -----------------------------------
990 // Peek at the mouse position
991 if (event
instanceof TMouseEvent
) {
992 // See if we need to switch focus to another window or the menu
993 checkSwitchFocus((TMouseEvent
) event
);
996 // Handle menu events
997 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
998 TMenu menu
= activeMenu
;
1000 if (event
instanceof TMouseEvent
) {
1001 TMouseEvent mouse
= (TMouseEvent
) event
;
1003 while (subMenus
.size() > 0) {
1004 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1005 if (subMenu
.mouseWouldHit(mouse
)) {
1008 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1009 && (!mouse
.isMouse1())
1010 && (!mouse
.isMouse2())
1011 && (!mouse
.isMouse3())
1012 && (!mouse
.isMouseWheelUp())
1013 && (!mouse
.isMouseWheelDown())
1017 // We navigated away from a sub-menu, so close it
1021 // Convert the mouse relative x/y to menu coordinates
1022 assert (mouse
.getX() == mouse
.getAbsoluteX());
1023 assert (mouse
.getY() == mouse
.getAbsoluteY());
1024 if (subMenus
.size() > 0) {
1025 menu
= subMenus
.get(subMenus
.size() - 1);
1027 mouse
.setX(mouse
.getX() - menu
.getX());
1028 mouse
.setY(mouse
.getY() - menu
.getY());
1030 menu
.handleEvent(event
);
1034 if (event
instanceof TKeypressEvent
) {
1035 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1037 // See if this key matches an accelerator, and is not being
1038 // shortcutted by the active window, and if so dispatch the menu
1040 boolean windowWillShortcut
= false;
1041 for (TWindow window
: windows
) {
1042 if (window
.isActive()) {
1043 if (window
.isShortcutKeypress(keypress
.getKey())) {
1044 // We do not process this key, it will be passed to
1045 // the window instead.
1046 windowWillShortcut
= true;
1051 if (!windowWillShortcut
&& !modalWindowActive()) {
1052 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1053 TMenuItem item
= null;
1054 synchronized (accelerators
) {
1055 item
= accelerators
.get(keypressLowercase
);
1058 if (item
.isEnabled()) {
1059 // Let the menu item dispatch
1065 // Handle the keypress
1066 if (onKeypress(keypress
)) {
1072 if (event
instanceof TCommandEvent
) {
1073 if (onCommand((TCommandEvent
) event
)) {
1078 if (event
instanceof TMenuEvent
) {
1079 if (onMenu((TMenuEvent
) event
)) {
1084 // Dispatch events to the active window -------------------------------
1085 for (TWindow window
: windows
) {
1086 if (window
.isActive()) {
1087 if (event
instanceof TMouseEvent
) {
1088 TMouseEvent mouse
= (TMouseEvent
) event
;
1089 // Convert the mouse relative x/y to window coordinates
1090 assert (mouse
.getX() == mouse
.getAbsoluteX());
1091 assert (mouse
.getY() == mouse
.getAbsoluteY());
1092 mouse
.setX(mouse
.getX() - window
.getX());
1093 mouse
.setY(mouse
.getY() - window
.getY());
1096 System
.err
.printf("TApplication dispatch event: %s\n",
1099 window
.handleEvent(event
);
1105 * Dispatch one event to the appropriate widget or application-level
1106 * event handler. This is the secondary event handler used by certain
1107 * special dialogs (currently TMessageBox and TFileOpenBox).
1109 * @param event the input event to consume
1110 * @see #primaryHandleEvent(TInputEvent event)
1112 private void secondaryHandleEvent(final TInputEvent event
) {
1113 secondaryEventReceiver
.handleEvent(event
);
1117 * Enable a widget to override the primary event thread.
1119 * @param widget widget that will receive events
1121 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1122 assert (secondaryEventReceiver
== null);
1123 assert (secondaryEventHandler
== null);
1124 assert ((widget
instanceof TMessageBox
)
1125 || (widget
instanceof TFileOpenBox
));
1126 secondaryEventReceiver
= widget
;
1127 secondaryEventHandler
= new WidgetEventHandler(this, false);
1128 (new Thread(secondaryEventHandler
)).start();
1132 * Yield to the secondary thread.
1134 public final void yield() {
1135 assert (secondaryEventReceiver
!= null);
1136 // This is where we handoff the event handler lock from the primary
1137 // to secondary thread. We unlock here, and in a future loop the
1138 // secondary thread locks again. When it gives up, we have the
1139 // single lock back.
1140 boolean oldLock
= unlockHandleEvent();
1143 while (secondaryEventReceiver
!= null) {
1144 synchronized (primaryEventHandler
) {
1146 primaryEventHandler
.wait();
1147 } catch (InterruptedException e
) {
1155 * Do stuff when there is no user input.
1157 private void doIdle() {
1159 System
.err
.printf("doIdle()\n");
1162 // Now run any timers that have timed out
1163 Date now
= new Date();
1164 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1165 for (TTimer timer
: timers
) {
1166 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1168 if (timer
.recurring
) {
1169 keepTimers
.add(timer
);
1172 keepTimers
.add(timer
);
1175 timers
= keepTimers
;
1178 for (TWindow window
: windows
) {
1183 // ------------------------------------------------------------------------
1184 // TWindow management -----------------------------------------------------
1185 // ------------------------------------------------------------------------
1188 * Close window. Note that the window's destructor is NOT called by this
1189 * method, instead the GC is assumed to do the cleanup.
1191 * @param window the window to remove
1193 public final void closeWindow(final TWindow window
) {
1194 synchronized (windows
) {
1195 int z
= window
.getZ();
1198 Collections
.sort(windows
);
1200 TWindow activeWindow
= null;
1201 for (TWindow w
: windows
) {
1203 w
.setZ(w
.getZ() - 1);
1204 if (w
.getZ() == 0) {
1207 assert (activeWindow
== null);
1219 // Perform window cleanup
1222 // Check if we are closing a TMessageBox or similar
1223 if (secondaryEventReceiver
!= null) {
1224 assert (secondaryEventHandler
!= null);
1226 // Do not send events to the secondaryEventReceiver anymore, the
1227 // window is closed.
1228 secondaryEventReceiver
= null;
1230 // Wake the secondary thread, it will wake the primary as it
1232 synchronized (secondaryEventHandler
) {
1233 secondaryEventHandler
.notify();
1239 * Switch to the next window.
1241 * @param forward if true, then switch to the next window in the list,
1242 * otherwise switch to the previous window in the list
1244 public final void switchWindow(final boolean forward
) {
1245 // Only switch if there are multiple windows
1246 if (windows
.size() < 2) {
1250 synchronized (windows
) {
1252 // Swap z/active between active window and the next in the list
1253 int activeWindowI
= -1;
1254 for (int i
= 0; i
< windows
.size(); i
++) {
1255 if (windows
.get(i
).isActive()) {
1260 assert (activeWindowI
>= 0);
1262 // Do not switch if a window is modal
1263 if (windows
.get(activeWindowI
).isModal()) {
1269 nextWindowI
= (activeWindowI
+ 1) % windows
.size();
1271 if (activeWindowI
== 0) {
1272 nextWindowI
= windows
.size() - 1;
1274 nextWindowI
= activeWindowI
- 1;
1277 windows
.get(activeWindowI
).setActive(false);
1278 windows
.get(activeWindowI
).setZ(windows
.get(nextWindowI
).getZ());
1279 windows
.get(activeWindowI
).onUnfocus();
1280 windows
.get(nextWindowI
).setZ(0);
1281 windows
.get(nextWindowI
).setActive(true);
1282 windows
.get(nextWindowI
).onFocus();
1284 } // synchronized (windows)
1289 * Add a window to my window list and make it active.
1291 * @param window new window to add
1293 public final void addWindow(final TWindow window
) {
1295 // Do not add menu windows to the window list.
1296 if (window
instanceof TMenu
) {
1300 synchronized (windows
) {
1301 // Do not allow a modal window to spawn a non-modal window. If a
1302 // modal window is active, then this window will become modal
1304 if (modalWindowActive()) {
1305 window
.flags
|= TWindow
.MODAL
;
1306 window
.flags
|= TWindow
.CENTERED
;
1308 for (TWindow w
: windows
) {
1313 w
.setZ(w
.getZ() + 1);
1315 windows
.add(window
);
1317 window
.setActive(true);
1320 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1321 && smartWindowPlacement
) {
1323 doSmartPlacement(window
);
1329 * Check if there is a system-modal window on top.
1331 * @return true if the active window is modal
1333 private boolean modalWindowActive() {
1334 if (windows
.size() == 0) {
1338 for (TWindow w
: windows
) {
1348 * Close all open windows.
1350 private void closeAllWindows() {
1351 // Don't do anything if we are in the menu
1352 if (activeMenu
!= null) {
1355 while (windows
.size() > 0) {
1356 closeWindow(windows
.get(0));
1361 * Re-layout the open windows as non-overlapping tiles. This produces
1362 * almost the same results as Turbo Pascal 7.0's IDE.
1364 private void tileWindows() {
1365 synchronized (windows
) {
1366 // Don't do anything if we are in the menu
1367 if (activeMenu
!= null) {
1370 int z
= windows
.size();
1376 a
= (int)(Math
.sqrt(z
));
1380 if (((a
* b
) + c
) == z
) {
1388 int newWidth
= (getScreen().getWidth() / a
);
1389 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1390 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1392 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1393 Collections
.sort(sorted
);
1394 Collections
.reverse(sorted
);
1395 for (int i
= 0; i
< sorted
.size(); i
++) {
1396 int logicalX
= i
/ b
;
1397 int logicalY
= i
% b
;
1398 if (i
>= ((a
- 1) * b
)) {
1400 logicalY
= i
- ((a
- 1) * b
);
1403 TWindow w
= sorted
.get(i
);
1404 w
.setX(logicalX
* newWidth
);
1405 w
.setWidth(newWidth
);
1406 if (i
>= ((a
- 1) * b
)) {
1407 w
.setY((logicalY
* newHeight2
) + 1);
1408 w
.setHeight(newHeight2
);
1410 w
.setY((logicalY
* newHeight1
) + 1);
1411 w
.setHeight(newHeight1
);
1418 * Re-layout the open windows as overlapping cascaded windows.
1420 private void cascadeWindows() {
1421 synchronized (windows
) {
1422 // Don't do anything if we are in the menu
1423 if (activeMenu
!= null) {
1428 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1429 Collections
.sort(sorted
);
1430 Collections
.reverse(sorted
);
1431 for (TWindow window
: sorted
) {
1436 if (x
> getScreen().getWidth()) {
1439 if (y
>= getScreen().getHeight()) {
1447 * Place a window to minimize its overlap with other windows.
1449 * @param window the window to place
1451 public final void doSmartPlacement(final TWindow window
) {
1452 // This is a pretty dumb algorithm, but seems to work. The hardest
1453 // part is computing these "overlap" values seeking a minimum average
1456 int yMin
= desktopTop
;
1457 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1458 int yMax
= desktopBottom
- window
.getHeight() + 1;
1466 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1467 // No work to do, bail out.
1471 // Compute the overlap matrix without the new window.
1472 int width
= getScreen().getWidth();
1473 int height
= getScreen().getHeight();
1474 int overlapMatrix
[][] = new int[width
][height
];
1475 for (TWindow w
: windows
) {
1479 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1483 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1487 overlapMatrix
[x
][y
]++;
1492 long oldOverlapTotal
= 0;
1493 long oldOverlapN
= 0;
1494 for (int x
= 0; x
< width
; x
++) {
1495 for (int y
= 0; y
< height
; y
++) {
1496 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1497 if (overlapMatrix
[x
][y
] > 0) {
1504 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1505 boolean first
= true;
1506 int windowX
= window
.getX();
1507 int windowY
= window
.getY();
1509 // For each possible (x, y) position for the new window, compute a
1510 // new overlap matrix.
1511 for (int x
= xMin
; x
< xMax
; x
++) {
1512 for (int y
= yMin
; y
< yMax
; y
++) {
1514 // Start with the matrix minus this window.
1515 int newMatrix
[][] = new int[width
][height
];
1516 for (int mx
= 0; mx
< width
; mx
++) {
1517 for (int my
= 0; my
< height
; my
++) {
1518 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1522 // Add this window's values to the new overlap matrix.
1523 long newOverlapTotal
= 0;
1524 long newOverlapN
= 0;
1525 // Start by adding each new cell.
1526 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1530 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1534 newMatrix
[wx
][wy
]++;
1537 // Now figure out the new value for total coverage.
1538 for (int mx
= 0; mx
< width
; mx
++) {
1539 for (int my
= 0; my
< height
; my
++) {
1540 newOverlapTotal
+= newMatrix
[x
][y
];
1541 if (newMatrix
[mx
][my
] > 0) {
1546 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1549 // First time: just record what we got.
1550 oldOverlapAvg
= newOverlapAvg
;
1553 // All other times: pick a new best (x, y) and save the
1555 if (newOverlapAvg
< oldOverlapAvg
) {
1558 oldOverlapAvg
= newOverlapAvg
;
1562 } // for (int x = xMin; x < xMax; x++)
1564 } // for (int y = yMin; y < yMax; y++)
1566 // Finally, set the window's new coordinates.
1567 window
.setX(windowX
);
1568 window
.setY(windowY
);
1571 // ------------------------------------------------------------------------
1572 // TMenu management -------------------------------------------------------
1573 // ------------------------------------------------------------------------
1576 * Check if a mouse event would hit either the active menu or any open
1579 * @param mouse mouse event
1580 * @return true if the mouse would hit the active menu or an open
1583 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1584 assert (activeMenu
!= null);
1585 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1586 Collections
.reverse(menus
);
1587 for (TMenu menu
: menus
) {
1588 if (menu
.mouseWouldHit(mouse
)) {
1592 return activeMenu
.mouseWouldHit(mouse
);
1596 * See if we need to switch window or activate the menu based on
1599 * @param mouse mouse event
1601 private void checkSwitchFocus(final TMouseEvent mouse
) {
1603 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1604 && (activeMenu
!= null)
1605 && (mouse
.getAbsoluteY() != 0)
1606 && (!mouseOnMenu(mouse
))
1608 // They clicked outside the active menu, turn it off
1609 activeMenu
.setActive(false);
1611 for (TMenu menu
: subMenus
) {
1612 menu
.setActive(false);
1618 // See if they hit the menu bar
1619 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1620 && (mouse
.isMouse1())
1621 && (!modalWindowActive())
1622 && (mouse
.getAbsoluteY() == 0)
1625 for (TMenu menu
: subMenus
) {
1626 menu
.setActive(false);
1630 // They selected the menu, go activate it
1631 for (TMenu menu
: menus
) {
1632 if ((mouse
.getAbsoluteX() >= menu
.getX())
1633 && (mouse
.getAbsoluteX() < menu
.getX()
1634 + menu
.getTitle().length() + 2)
1636 menu
.setActive(true);
1639 menu
.setActive(false);
1645 // See if they hit the menu bar
1646 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1647 && (mouse
.isMouse1())
1648 && (activeMenu
!= null)
1649 && (mouse
.getAbsoluteY() == 0)
1652 TMenu oldMenu
= activeMenu
;
1653 for (TMenu menu
: subMenus
) {
1654 menu
.setActive(false);
1658 // See if we should switch menus
1659 for (TMenu menu
: menus
) {
1660 if ((mouse
.getAbsoluteX() >= menu
.getX())
1661 && (mouse
.getAbsoluteX() < menu
.getX()
1662 + menu
.getTitle().length() + 2)
1664 menu
.setActive(true);
1668 if (oldMenu
!= activeMenu
) {
1669 // They switched menus
1670 oldMenu
.setActive(false);
1675 // Only switch if there are multiple windows
1676 if (windows
.size() < 2) {
1680 // Switch on the upclick
1681 if (mouse
.getType() != TMouseEvent
.Type
.MOUSE_UP
) {
1685 synchronized (windows
) {
1686 Collections
.sort(windows
);
1687 if (windows
.get(0).isModal()) {
1688 // Modal windows don't switch
1692 for (TWindow window
: windows
) {
1693 assert (!window
.isModal());
1694 if (window
.mouseWouldHit(mouse
)) {
1695 if (window
== windows
.get(0)) {
1696 // Clicked on the same window, nothing to do
1700 // We will be switching to another window
1701 assert (windows
.get(0).isActive());
1702 assert (!window
.isActive());
1703 windows
.get(0).onUnfocus();
1704 windows
.get(0).setActive(false);
1705 windows
.get(0).setZ(window
.getZ());
1707 window
.setActive(true);
1714 // Clicked on the background, nothing to do
1719 * Turn off the menu.
1721 public final void closeMenu() {
1722 if (activeMenu
!= null) {
1723 activeMenu
.setActive(false);
1725 for (TMenu menu
: subMenus
) {
1726 menu
.setActive(false);
1733 * Turn off a sub-menu.
1735 public final void closeSubMenu() {
1736 assert (activeMenu
!= null);
1737 TMenu item
= subMenus
.get(subMenus
.size() - 1);
1738 assert (item
!= null);
1739 item
.setActive(false);
1740 subMenus
.remove(subMenus
.size() - 1);
1744 * Switch to the next menu.
1746 * @param forward if true, then switch to the next menu in the list,
1747 * otherwise switch to the previous menu in the list
1749 public final void switchMenu(final boolean forward
) {
1750 assert (activeMenu
!= null);
1752 for (TMenu menu
: subMenus
) {
1753 menu
.setActive(false);
1757 for (int i
= 0; i
< menus
.size(); i
++) {
1758 if (activeMenu
== menus
.get(i
)) {
1760 if (i
< menus
.size() - 1) {
1768 activeMenu
.setActive(false);
1769 activeMenu
= menus
.get(i
);
1770 activeMenu
.setActive(true);
1777 * Add a menu item to the global list. If it has a keyboard accelerator,
1778 * that will be added the global hash.
1780 * @param item the menu item
1782 public final void addMenuItem(final TMenuItem item
) {
1783 menuItems
.add(item
);
1785 TKeypress key
= item
.getKey();
1787 synchronized (accelerators
) {
1788 assert (accelerators
.get(key
) == null);
1789 accelerators
.put(key
.toLowerCase(), item
);
1795 * Disable one menu item.
1797 * @param id the menu item ID
1799 public final void disableMenuItem(final int id
) {
1800 for (TMenuItem item
: menuItems
) {
1801 if (item
.getId() == id
) {
1802 item
.setEnabled(false);
1808 * Disable the range of menu items with ID's between lower and upper,
1811 * @param lower the lowest menu item ID
1812 * @param upper the highest menu item ID
1814 public final void disableMenuItems(final int lower
, final int upper
) {
1815 for (TMenuItem item
: menuItems
) {
1816 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1817 item
.setEnabled(false);
1823 * Enable one menu item.
1825 * @param id the menu item ID
1827 public final void enableMenuItem(final int id
) {
1828 for (TMenuItem item
: menuItems
) {
1829 if (item
.getId() == id
) {
1830 item
.setEnabled(true);
1836 * Enable the range of menu items with ID's between lower and upper,
1839 * @param lower the lowest menu item ID
1840 * @param upper the highest menu item ID
1842 public final void enableMenuItems(final int lower
, final int upper
) {
1843 for (TMenuItem item
: menuItems
) {
1844 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
1845 item
.setEnabled(true);
1851 * Recompute menu x positions based on their title length.
1853 public final void recomputeMenuX() {
1855 for (TMenu menu
: menus
) {
1857 x
+= menu
.getTitle().length() + 2;
1862 * Post an event to process and turn off the menu.
1864 * @param event new event to add to the queue
1866 public final void postMenuEvent(final TInputEvent event
) {
1867 synchronized (fillEventQueue
) {
1868 fillEventQueue
.add(event
);
1874 * Add a sub-menu to the list of open sub-menus.
1876 * @param menu sub-menu
1878 public final void addSubMenu(final TMenu menu
) {
1883 * Convenience function to add a top-level menu.
1885 * @param title menu title
1886 * @return the new menu
1888 public final TMenu
addMenu(final String title
) {
1891 TMenu menu
= new TMenu(this, x
, y
, title
);
1898 * Convenience function to add a default "File" menu.
1900 * @return the new menu
1902 public final TMenu
addFileMenu() {
1903 TMenu fileMenu
= addMenu("&File");
1904 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
1905 fileMenu
.addSeparator();
1906 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
1907 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
1908 TStatusBar statusBar
= fileMenu
.newStatusBar("File-management " +
1909 "commands (Open, Save, Print, etc.)");
1910 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1915 * Convenience function to add a default "Edit" menu.
1917 * @return the new menu
1919 public final TMenu
addEditMenu() {
1920 TMenu editMenu
= addMenu("&Edit");
1921 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
1922 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
1923 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
1924 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
1925 TStatusBar statusBar
= editMenu
.newStatusBar("Editor operations, " +
1926 "undo, and Clipboard access");
1927 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1932 * Convenience function to add a default "Window" menu.
1934 * @return the new menu
1936 public final TMenu
addWindowMenu() {
1937 TMenu windowMenu
= addMenu("&Window");
1938 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
1939 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
1940 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
1941 windowMenu
.addSeparator();
1942 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
1943 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
1944 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
1945 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
1946 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
1947 TStatusBar statusBar
= windowMenu
.newStatusBar("Open, arrange, and " +
1949 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1954 * Convenience function to add a default "Help" menu.
1956 * @return the new menu
1958 public final TMenu
addHelpMenu() {
1959 TMenu helpMenu
= addMenu("&Help");
1960 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
1961 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
1962 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
1963 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
1964 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
1965 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
1966 helpMenu
.addSeparator();
1967 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
1968 TStatusBar statusBar
= helpMenu
.newStatusBar("Access online help");
1969 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, "Help");
1973 // ------------------------------------------------------------------------
1974 // Event handlers ---------------------------------------------------------
1975 // ------------------------------------------------------------------------
1978 * Method that TApplication subclasses can override to handle menu or
1979 * posted command events.
1981 * @param command command event
1982 * @return if true, this event was consumed
1984 protected boolean onCommand(final TCommandEvent command
) {
1985 // Default: handle cmExit
1986 if (command
.equals(cmExit
)) {
1987 if (messageBox("Confirmation", "Exit application?",
1988 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
1994 if (command
.equals(cmShell
)) {
1995 openTerminal(0, 0, TWindow
.RESIZABLE
);
1999 if (command
.equals(cmTile
)) {
2003 if (command
.equals(cmCascade
)) {
2007 if (command
.equals(cmCloseAll
)) {
2016 * Method that TApplication subclasses can override to handle menu
2019 * @param menu menu event
2020 * @return if true, this event was consumed
2022 protected boolean onMenu(final TMenuEvent menu
) {
2024 // Default: handle MID_EXIT
2025 if (menu
.getId() == TMenu
.MID_EXIT
) {
2026 if (messageBox("Confirmation", "Exit application?",
2027 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2033 if (menu
.getId() == TMenu
.MID_SHELL
) {
2034 openTerminal(0, 0, TWindow
.RESIZABLE
);
2038 if (menu
.getId() == TMenu
.MID_TILE
) {
2042 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2046 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2050 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2058 * Method that TApplication subclasses can override to handle keystrokes.
2060 * @param keypress keystroke event
2061 * @return if true, this event was consumed
2063 protected boolean onKeypress(final TKeypressEvent keypress
) {
2064 // Default: only menu shortcuts
2066 // Process Alt-F, Alt-E, etc. menu shortcut keys
2067 if (!keypress
.getKey().isFnKey()
2068 && keypress
.getKey().isAlt()
2069 && !keypress
.getKey().isCtrl()
2070 && (activeMenu
== null)
2071 && !modalWindowActive()
2074 assert (subMenus
.size() == 0);
2076 for (TMenu menu
: menus
) {
2077 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2078 == Character
.toLowerCase(keypress
.getKey().getChar())
2081 menu
.setActive(true);
2090 // ------------------------------------------------------------------------
2091 // TTimer management ------------------------------------------------------
2092 // ------------------------------------------------------------------------
2095 * Get the amount of time I can sleep before missing a Timer tick.
2097 * @param timeout = initial (maximum) timeout in millis
2098 * @return number of milliseconds between now and the next timer event
2100 private long getSleepTime(final long timeout
) {
2101 Date now
= new Date();
2102 long nowTime
= now
.getTime();
2103 long sleepTime
= timeout
;
2104 for (TTimer timer
: timers
) {
2105 long nextTickTime
= timer
.getNextTick().getTime();
2106 if (nextTickTime
< nowTime
) {
2110 long timeDifference
= nextTickTime
- nowTime
;
2111 if (timeDifference
< sleepTime
) {
2112 sleepTime
= timeDifference
;
2115 assert (sleepTime
>= 0);
2116 assert (sleepTime
<= timeout
);
2121 * Convenience function to add a timer.
2123 * @param duration number of milliseconds to wait between ticks
2124 * @param recurring if true, re-schedule this timer after every tick
2125 * @param action function to call when button is pressed
2128 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2129 final TAction action
) {
2131 TTimer timer
= new TTimer(duration
, recurring
, action
);
2132 synchronized (timers
) {
2139 * Convenience function to remove a timer.
2141 * @param timer timer to remove
2143 public final void removeTimer(final TTimer timer
) {
2144 synchronized (timers
) {
2145 timers
.remove(timer
);
2149 // ------------------------------------------------------------------------
2150 // Other TWindow constructors ---------------------------------------------
2151 // ------------------------------------------------------------------------
2154 * Convenience function to spawn a message box.
2156 * @param title window title, will be centered along the top border
2157 * @param caption message to display. Use embedded newlines to get a
2159 * @return the new message box
2161 public final TMessageBox
messageBox(final String title
,
2162 final String caption
) {
2164 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2168 * Convenience function to spawn a message box.
2170 * @param title window title, will be centered along the top border
2171 * @param caption message to display. Use embedded newlines to get a
2173 * @param type one of the TMessageBox.Type constants. Default is
2175 * @return the new message box
2177 public final TMessageBox
messageBox(final String title
,
2178 final String caption
, final TMessageBox
.Type type
) {
2180 return new TMessageBox(this, title
, caption
, type
);
2184 * Convenience function to spawn an input box.
2186 * @param title window title, will be centered along the top border
2187 * @param caption message to display. Use embedded newlines to get a
2189 * @return the new input box
2191 public final TInputBox
inputBox(final String title
, final String caption
) {
2193 return new TInputBox(this, title
, caption
);
2197 * Convenience function to spawn an input box.
2199 * @param title window title, will be centered along the top border
2200 * @param caption message to display. Use embedded newlines to get a
2202 * @param text initial text to seed the field with
2203 * @return the new input box
2205 public final TInputBox
inputBox(final String title
, final String caption
,
2206 final String text
) {
2208 return new TInputBox(this, title
, caption
, text
);
2212 * Convenience function to open a terminal window.
2214 * @param x column relative to parent
2215 * @param y row relative to parent
2216 * @return the terminal new window
2218 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2219 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2223 * Convenience function to open a terminal window.
2225 * @param x column relative to parent
2226 * @param y row relative to parent
2227 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2228 * @return the terminal new window
2230 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2233 return new TTerminalWindow(this, x
, y
, flags
);
2237 * Convenience function to spawn an file open box.
2239 * @param path path of selected file
2240 * @return the result of the new file open box
2241 * @throws IOException if java.io operation throws
2243 public final String
fileOpenBox(final String path
) throws IOException
{
2245 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2246 return box
.getFilename();
2250 * Convenience function to spawn an file open box.
2252 * @param path path of selected file
2253 * @param type one of the Type constants
2254 * @return the result of the new file open box
2255 * @throws IOException if java.io operation throws
2257 public final String
fileOpenBox(final String path
,
2258 final TFileOpenBox
.Type type
) throws IOException
{
2260 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2261 return box
.getFilename();