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]
32 import java
.io
.InputStream
;
33 import java
.io
.IOException
;
34 import java
.io
.OutputStream
;
35 import java
.io
.PrintWriter
;
36 import java
.io
.Reader
;
37 import java
.io
.UnsupportedEncodingException
;
38 import java
.text
.MessageFormat
;
39 import java
.util
.Collections
;
40 import java
.util
.Date
;
41 import java
.util
.HashMap
;
42 import java
.util
.ArrayList
;
43 import java
.util
.LinkedList
;
44 import java
.util
.List
;
46 import java
.util
.ResourceBundle
;
48 import jexer
.bits
.CellAttributes
;
49 import jexer
.bits
.ColorTheme
;
50 import jexer
.event
.TCommandEvent
;
51 import jexer
.event
.TInputEvent
;
52 import jexer
.event
.TKeypressEvent
;
53 import jexer
.event
.TMenuEvent
;
54 import jexer
.event
.TMouseEvent
;
55 import jexer
.event
.TResizeEvent
;
56 import jexer
.backend
.Backend
;
57 import jexer
.backend
.Screen
;
58 import jexer
.backend
.MultiBackend
;
59 import jexer
.backend
.SwingBackend
;
60 import jexer
.backend
.ECMA48Backend
;
61 import jexer
.backend
.TWindowBackend
;
62 import jexer
.menu
.TMenu
;
63 import jexer
.menu
.TMenuItem
;
64 import static jexer
.TCommand
.*;
65 import static jexer
.TKeypress
.*;
68 * TApplication is the main driver class for a full Text User Interface
69 * application. It manages windows, provides a menu bar and status bar, and
70 * processes events received from the user.
72 public class TApplication
implements Runnable
{
77 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
79 // ------------------------------------------------------------------------
80 // Public constants -------------------------------------------------------
81 // ------------------------------------------------------------------------
84 * If true, emit thread stuff to System.err.
86 private static final boolean debugThreads
= false;
89 * If true, emit events being processed to System.err.
91 private static final boolean debugEvents
= false;
94 * If true, do "smart placement" on new windows that are not specified to
97 private static final boolean smartWindowPlacement
= true;
100 * Two backend types are available.
102 public static enum BackendType
{
109 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
114 * Synonym for ECMA48.
119 // ------------------------------------------------------------------------
120 // Primary/secondary event handlers ---------------------------------------
121 // ------------------------------------------------------------------------
124 * WidgetEventHandler is the main event consumer loop. There are at most
125 * two such threads in existence: the primary for normal case and a
126 * secondary that is used for TMessageBox, TInputBox, and similar.
128 private class WidgetEventHandler
implements Runnable
{
130 * The main application.
132 private TApplication application
;
135 * Whether or not this WidgetEventHandler is the primary or secondary
138 private boolean primary
= true;
141 * Public constructor.
143 * @param application the main application
144 * @param primary if true, this is the primary event handler thread
146 public WidgetEventHandler(final TApplication application
,
147 final boolean primary
) {
149 this.application
= application
;
150 this.primary
= primary
;
157 boolean first
= true;
160 while (!application
.quit
) {
162 // Wait until application notifies me
163 while (!application
.quit
) {
165 synchronized (application
.drainEventQueue
) {
166 if (application
.drainEventQueue
.size() > 0) {
175 timeout
= application
.getSleepTime(1000);
179 // A timer needs to fire, break out.
184 System
.err
.printf("%d %s %s sleep %d millis\n",
185 System
.currentTimeMillis(), this,
186 primary ?
"primary" : "secondary", timeout
);
189 synchronized (this) {
194 System
.err
.printf("%d %s %s AWAKE\n",
195 System
.currentTimeMillis(), this,
196 primary ?
"primary" : "secondary");
200 && (application
.secondaryEventReceiver
== null)
202 // Secondary thread, emergency exit. If we got
203 // here then something went wrong with the
204 // handoff between yield() and closeWindow().
205 synchronized (application
.primaryEventHandler
) {
206 application
.primaryEventHandler
.notify();
208 application
.secondaryEventHandler
= null;
209 throw new RuntimeException("secondary exited " +
213 } catch (InterruptedException e
) {
216 } // while (!application.quit)
218 // Pull all events off the queue
220 TInputEvent event
= null;
221 synchronized (application
.drainEventQueue
) {
222 if (application
.drainEventQueue
.size() == 0) {
225 event
= application
.drainEventQueue
.remove(0);
228 // We will have an event to process, so repaint the
229 // screen at the end.
230 application
.repaint
= true;
233 primaryHandleEvent(event
);
235 secondaryHandleEvent(event
);
238 && (application
.secondaryEventReceiver
== null)
240 // Secondary thread, time to exit.
242 // DO NOT UNLOCK. Primary thread just came back from
243 // primaryHandleEvent() and will unlock in the else
244 // block below. Just wake it up.
245 synchronized (application
.primaryEventHandler
) {
246 application
.primaryEventHandler
.notify();
248 // Now eliminate my reference so that
249 // wakeEventHandler() resumes working on the primary.
250 application
.secondaryEventHandler
= null;
258 // Fire timers, update screen.
260 application
.finishEventProcessing();
263 } // while (true) (main runnable loop)
268 * The primary event handler thread.
270 private volatile WidgetEventHandler primaryEventHandler
;
273 * The secondary event handler thread.
275 private volatile WidgetEventHandler secondaryEventHandler
;
278 * The widget receiving events from the secondary event handler thread.
280 private volatile TWidget secondaryEventReceiver
;
283 * Wake the sleeping active event handler.
285 private void wakeEventHandler() {
286 if (secondaryEventHandler
!= null) {
287 synchronized (secondaryEventHandler
) {
288 secondaryEventHandler
.notify();
291 assert (primaryEventHandler
!= null);
292 synchronized (primaryEventHandler
) {
293 primaryEventHandler
.notify();
298 // ------------------------------------------------------------------------
299 // TApplication attributes ------------------------------------------------
300 // ------------------------------------------------------------------------
303 * Access to the physical screen, keyboard, and mouse.
305 private Backend backend
;
310 * @return the Backend
312 public final Backend
getBackend() {
321 public final Screen
getScreen() {
322 if (backend
instanceof TWindowBackend
) {
323 // We are being rendered to a TWindow. We can't use its
324 // getScreen() method because that is how it is rendering to a
325 // hardware backend somewhere. Instead use its getOtherScreen()
327 return ((TWindowBackend
) backend
).getOtherScreen();
329 return backend
.getScreen();
334 * Actual mouse coordinate X.
339 * Actual mouse coordinate Y.
344 * Old version of mouse coordinate X.
346 private int oldMouseX
;
349 * Old version mouse coordinate Y.
351 private int oldMouseY
;
354 * Event queue that is filled by run().
356 private List
<TInputEvent
> fillEventQueue
;
359 * Event queue that will be drained by either primary or secondary
362 private List
<TInputEvent
> drainEventQueue
;
365 * Top-level menus in this application.
367 private List
<TMenu
> menus
;
370 * Stack of activated sub-menus in this application.
372 private List
<TMenu
> subMenus
;
375 * The currently active menu.
377 private TMenu activeMenu
= null;
380 * Active keyboard accelerators.
382 private Map
<TKeypress
, TMenuItem
> accelerators
;
387 private List
<TMenuItem
> menuItems
;
390 * Windows and widgets pull colors from this ColorTheme.
392 private ColorTheme theme
;
395 * Get the color theme.
399 public final ColorTheme
getTheme() {
404 * The top-level windows (but not menus).
406 private List
<TWindow
> windows
;
409 * The currently acive window.
411 private TWindow activeWindow
= null;
414 * Timers that are being ticked.
416 private List
<TTimer
> timers
;
419 * When true, exit the application.
421 private volatile boolean quit
= false;
424 * When true, repaint the entire screen.
426 private volatile boolean repaint
= true;
429 * Repaint the screen on the next update.
431 public void doRepaint() {
437 * Y coordinate of the top edge of the desktop. For now this is a
438 * constant. Someday it would be nice to have a multi-line menu or
441 private static final int desktopTop
= 1;
444 * Get Y coordinate of the top edge of the desktop.
446 * @return Y coordinate of the top edge of the desktop
448 public final int getDesktopTop() {
453 * Y coordinate of the bottom edge of the desktop.
455 private int desktopBottom
;
458 * Get Y coordinate of the bottom edge of the desktop.
460 * @return Y coordinate of the bottom edge of the desktop
462 public final int getDesktopBottom() {
463 return desktopBottom
;
467 * An optional TDesktop background window that is drawn underneath
470 private TDesktop desktop
;
473 * Set the TDesktop instance.
475 * @param desktop a TDesktop instance, or null to remove the one that is
478 public final void setDesktop(final TDesktop desktop
) {
479 if (this.desktop
!= null) {
480 this.desktop
.onClose();
482 this.desktop
= desktop
;
486 * Get the TDesktop instance.
488 * @return the desktop, or null if it is not set
490 public final TDesktop
getDesktop() {
495 * Get the current active window.
497 * @return the active window, or null if it is not set
499 public final TWindow
getActiveWindow() {
504 * Get a (shallow) copy of the window list.
506 * @return a copy of the list of windows for this application
508 public final List
<TWindow
> getAllWindows() {
509 List
<TWindow
> result
= new LinkedList
<TWindow
>();
510 result
.addAll(windows
);
515 * If true, focus follows mouse: windows automatically raised if the
516 * mouse passes over them.
518 private boolean focusFollowsMouse
= false;
521 * Get focusFollowsMouse flag.
523 * @return true if focus follows mouse: windows automatically raised if
524 * the mouse passes over them
526 public boolean getFocusFollowsMouse() {
527 return focusFollowsMouse
;
531 * Set focusFollowsMouse flag.
533 * @param focusFollowsMouse if true, focus follows mouse: windows
534 * automatically raised if the mouse passes over them
536 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
537 this.focusFollowsMouse
= focusFollowsMouse
;
540 // ------------------------------------------------------------------------
541 // General behavior -------------------------------------------------------
542 // ------------------------------------------------------------------------
545 * Display the about dialog.
547 protected void showAboutDialog() {
548 messageBox(i18n
.getString("aboutDialogTitle"),
549 MessageFormat
.format(i18n
.getString("aboutDialogText"),
550 this.getClass().getPackage().getImplementationVersion()),
551 TMessageBox
.Type
.OK
);
554 // ------------------------------------------------------------------------
555 // Constructors -----------------------------------------------------------
556 // ------------------------------------------------------------------------
559 * Public constructor.
561 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
563 * @throws UnsupportedEncodingException if an exception is thrown when
564 * creating the InputStreamReader
566 public TApplication(final BackendType backendType
)
567 throws UnsupportedEncodingException
{
569 switch (backendType
) {
571 // The default SwingBackend is 80x25, 20 pt font. If you want to
572 // change that, you can pass the extra arguments to the
573 // SwingBackend constructor here. For example, if you wanted
574 // 90x30, 16 pt font:
576 // backend = new SwingBackend(this, 90, 30, 16);
577 backend
= new SwingBackend(this);
582 backend
= new ECMA48Backend(this, null, null);
585 throw new IllegalArgumentException("Invalid backend type: "
592 * Public constructor. The backend type will be BackendType.ECMA48.
594 * @param input an InputStream connected to the remote user, or null for
595 * System.in. If System.in is used, then on non-Windows systems it will
596 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
597 * mode. input is always converted to a Reader with UTF-8 encoding.
598 * @param output an OutputStream connected to the remote user, or null
599 * for System.out. output is always converted to a Writer with UTF-8
601 * @throws UnsupportedEncodingException if an exception is thrown when
602 * creating the InputStreamReader
604 public TApplication(final InputStream input
,
605 final OutputStream output
) throws UnsupportedEncodingException
{
607 backend
= new ECMA48Backend(this, input
, output
);
612 * Public constructor. The backend type will be BackendType.ECMA48.
614 * @param input the InputStream underlying 'reader'. Its available()
615 * method is used to determine if reader.read() will block or not.
616 * @param reader a Reader connected to the remote user.
617 * @param writer a PrintWriter connected to the remote user.
618 * @param setRawMode if true, set System.in into raw mode with stty.
619 * This should in general not be used. It is here solely for Demo3,
620 * which uses System.in.
621 * @throws IllegalArgumentException if input, reader, or writer are null.
623 public TApplication(final InputStream input
, final Reader reader
,
624 final PrintWriter writer
, final boolean setRawMode
) {
626 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
631 * Public constructor. The backend type will be BackendType.ECMA48.
633 * @param input the InputStream underlying 'reader'. Its available()
634 * method is used to determine if reader.read() will block or not.
635 * @param reader a Reader connected to the remote user.
636 * @param writer a PrintWriter connected to the remote user.
637 * @throws IllegalArgumentException if input, reader, or writer are null.
639 public TApplication(final InputStream input
, final Reader reader
,
640 final PrintWriter writer
) {
642 this(input
, reader
, writer
, false);
646 * Public constructor. This hook enables use with new non-Jexer
649 * @param backend a Backend that is already ready to go.
651 public TApplication(final Backend backend
) {
652 this.backend
= backend
;
653 backend
.setListener(this);
658 * Finish construction once the backend is set.
660 private void TApplicationImpl() {
661 theme
= new ColorTheme();
662 desktopBottom
= getScreen().getHeight() - 1;
663 fillEventQueue
= new ArrayList
<TInputEvent
>();
664 drainEventQueue
= new ArrayList
<TInputEvent
>();
665 windows
= new LinkedList
<TWindow
>();
666 menus
= new LinkedList
<TMenu
>();
667 subMenus
= new LinkedList
<TMenu
>();
668 timers
= new LinkedList
<TTimer
>();
669 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
670 menuItems
= new ArrayList
<TMenuItem
>();
671 desktop
= new TDesktop(this);
673 // Special case: the Swing backend needs to have a timer to drive its
675 if ((backend
instanceof SwingBackend
)
676 || (backend
instanceof MultiBackend
)
678 // Default to 500 millis, unless a SwingBackend has its own
681 if (backend
instanceof SwingBackend
) {
682 millis
= ((SwingBackend
) backend
).getBlinkMillis();
685 addTimer(millis
, true,
688 TApplication
.this.doRepaint();
696 // ------------------------------------------------------------------------
697 // Screen refresh loop ----------------------------------------------------
698 // ------------------------------------------------------------------------
701 * Process background events, and update the screen.
703 private void finishEventProcessing() {
705 System
.err
.printf(System
.currentTimeMillis() + " " +
706 Thread
.currentThread() + " finishEventProcessing()\n");
709 // Process timers and call doIdle()'s
713 synchronized (getScreen()) {
718 System
.err
.printf(System
.currentTimeMillis() + " " +
719 Thread
.currentThread() + " finishEventProcessing() END\n");
724 * Invert the cell color at a position. This is used to track the mouse.
726 * @param x column position
727 * @param y row position
729 private void invertCell(final int x
, final int y
) {
731 System
.err
.printf("%d %s invertCell() %d %d\n",
732 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
734 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
735 attr
.setForeColor(attr
.getForeColor().invert());
736 attr
.setBackColor(attr
.getBackColor().invert());
737 getScreen().putAttrXY(x
, y
, attr
, false);
743 private void drawAll() {
744 boolean menuIsActive
= false;
747 System
.err
.printf("%d %s drawAll() enter\n",
748 System
.currentTimeMillis(), Thread
.currentThread());
753 System
.err
.printf("%d %s drawAll() !repaint\n",
754 System
.currentTimeMillis(), Thread
.currentThread());
756 synchronized (getScreen()) {
757 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
758 // The only thing that has happened is the mouse moved.
759 // Clear the old position and draw the new position.
760 invertCell(oldMouseX
, oldMouseY
);
761 invertCell(mouseX
, mouseY
);
765 if (getScreen().isDirty()) {
766 backend
.flushScreen();
773 System
.err
.printf("%d %s drawAll() REDRAW\n",
774 System
.currentTimeMillis(), Thread
.currentThread());
777 // If true, the cursor is not visible
778 boolean cursor
= false;
780 // Start with a clean screen
784 if (desktop
!= null) {
785 desktop
.drawChildren();
788 // Draw each window in reverse Z order
789 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
790 Collections
.sort(sorted
);
791 TWindow topLevel
= null;
792 if (sorted
.size() > 0) {
793 topLevel
= sorted
.get(0);
795 Collections
.reverse(sorted
);
796 for (TWindow window
: sorted
) {
797 if (window
.isShown()) {
798 window
.drawChildren();
802 // Draw the blank menubar line - reset the screen clipping first so
803 // it won't trim it out.
804 getScreen().resetClipping();
805 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
806 theme
.getColor("tmenu"));
807 // Now draw the menus.
809 for (TMenu menu
: menus
) {
810 CellAttributes menuColor
;
811 CellAttributes menuMnemonicColor
;
812 if (menu
.isActive()) {
814 menuColor
= theme
.getColor("tmenu.highlighted");
815 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
818 menuColor
= theme
.getColor("tmenu");
819 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
821 // Draw the menu title
822 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
824 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
825 // Draw the highlight character
826 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
827 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
829 if (menu
.isActive()) {
831 // Reset the screen clipping so we can draw the next title.
832 getScreen().resetClipping();
834 x
+= menu
.getTitle().length() + 2;
837 for (TMenu menu
: subMenus
) {
838 // Reset the screen clipping so we can draw the next sub-menu.
839 getScreen().resetClipping();
843 // Draw the status bar of the top-level window
844 TStatusBar statusBar
= null;
845 if (topLevel
!= null) {
846 statusBar
= topLevel
.getStatusBar();
848 if (statusBar
!= null) {
849 getScreen().resetClipping();
850 statusBar
.setWidth(getScreen().getWidth());
851 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
854 CellAttributes barColor
= new CellAttributes();
855 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
856 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
860 // Draw the mouse pointer
861 invertCell(mouseX
, mouseY
);
865 // Place the cursor if it is visible
867 TWidget activeWidget
= null;
868 if (sorted
.size() > 0) {
869 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
870 if (activeWidget
.isCursorVisible()) {
871 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
872 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
874 getScreen().putCursor(true,
875 activeWidget
.getCursorAbsoluteX(),
876 activeWidget
.getCursorAbsoluteY());
879 getScreen().putCursor(false,
880 activeWidget
.getCursorAbsoluteX(),
881 activeWidget
.getCursorAbsoluteY());
890 getScreen().hideCursor();
893 // Flush the screen contents
894 if (getScreen().isDirty()) {
895 backend
.flushScreen();
901 // ------------------------------------------------------------------------
902 // Main loop --------------------------------------------------------------
903 // ------------------------------------------------------------------------
906 * Force this application to exit.
910 synchronized (this) {
916 * Run this application until it exits.
919 // Start the main consumer thread
920 primaryEventHandler
= new WidgetEventHandler(this, true);
921 (new Thread(primaryEventHandler
)).start();
924 synchronized (this) {
925 boolean doWait
= false;
927 synchronized (fillEventQueue
) {
928 if (fillEventQueue
.size() == 0) {
934 // No I/O to dispatch, so wait until the backend
938 System
.err
.println(System
.currentTimeMillis() +
945 System
.err
.println(System
.currentTimeMillis() +
948 } catch (InterruptedException e
) {
949 // I'm awake and don't care why, let's see what's
950 // going on out there.
954 } // synchronized (this)
956 synchronized (fillEventQueue
) {
957 // Pull any pending I/O events
958 backend
.getEvents(fillEventQueue
);
960 // Dispatch each event to the appropriate handler, one at a
963 TInputEvent event
= null;
964 if (fillEventQueue
.size() == 0) {
967 event
= fillEventQueue
.remove(0);
968 metaHandleEvent(event
);
972 // Wake a consumer thread if we have any pending events.
973 if (drainEventQueue
.size() > 0) {
979 // Shutdown the event consumer threads
980 if (secondaryEventHandler
!= null) {
981 synchronized (secondaryEventHandler
) {
982 secondaryEventHandler
.notify();
985 if (primaryEventHandler
!= null) {
986 synchronized (primaryEventHandler
) {
987 primaryEventHandler
.notify();
991 // Shutdown the user I/O thread(s)
994 // Close all the windows. This gives them an opportunity to release
1001 * Peek at certain application-level events, add to eventQueue, and wake
1002 * up the consuming Thread.
1004 * @param event the input event to consume
1006 private void metaHandleEvent(final TInputEvent event
) {
1009 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1010 event
)); System
.err
.flush();
1014 // Do no more processing if the application is already trying
1019 // Special application-wide events -------------------------------
1022 if (event
instanceof TCommandEvent
) {
1023 TCommandEvent command
= (TCommandEvent
) event
;
1024 if (command
.getCmd().equals(cmAbort
)) {
1030 synchronized (drainEventQueue
) {
1032 if (event
instanceof TResizeEvent
) {
1033 TResizeEvent resize
= (TResizeEvent
) event
;
1034 synchronized (getScreen()) {
1035 getScreen().setDimensions(resize
.getWidth(),
1036 resize
.getHeight());
1037 desktopBottom
= getScreen().getHeight() - 1;
1043 if (desktop
!= null) {
1044 desktop
.setDimensions(0, 0, resize
.getWidth(),
1045 resize
.getHeight() - 1);
1048 // Change menu edges if needed.
1051 // We are dirty, redraw the screen.
1056 // Put into the main queue
1057 drainEventQueue
.add(event
);
1062 * Dispatch one event to the appropriate widget or application-level
1063 * event handler. This is the primary event handler, it has the normal
1064 * application-wide event handling.
1066 * @param event the input event to consume
1067 * @see #secondaryHandleEvent(TInputEvent event)
1069 private void primaryHandleEvent(final TInputEvent event
) {
1072 System
.err
.printf("Handle event: %s\n", event
);
1075 // Special application-wide events -----------------------------------
1077 // Peek at the mouse position
1078 if (event
instanceof TMouseEvent
) {
1079 TMouseEvent mouse
= (TMouseEvent
) event
;
1080 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1083 mouseX
= mouse
.getX();
1084 mouseY
= mouse
.getY();
1087 // See if we need to switch focus to another window or the menu
1088 checkSwitchFocus((TMouseEvent
) event
);
1091 // Handle menu events
1092 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1093 TMenu menu
= activeMenu
;
1095 if (event
instanceof TMouseEvent
) {
1096 TMouseEvent mouse
= (TMouseEvent
) event
;
1098 while (subMenus
.size() > 0) {
1099 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1100 if (subMenu
.mouseWouldHit(mouse
)) {
1103 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1104 && (!mouse
.isMouse1())
1105 && (!mouse
.isMouse2())
1106 && (!mouse
.isMouse3())
1107 && (!mouse
.isMouseWheelUp())
1108 && (!mouse
.isMouseWheelDown())
1112 // We navigated away from a sub-menu, so close it
1116 // Convert the mouse relative x/y to menu coordinates
1117 assert (mouse
.getX() == mouse
.getAbsoluteX());
1118 assert (mouse
.getY() == mouse
.getAbsoluteY());
1119 if (subMenus
.size() > 0) {
1120 menu
= subMenus
.get(subMenus
.size() - 1);
1122 mouse
.setX(mouse
.getX() - menu
.getX());
1123 mouse
.setY(mouse
.getY() - menu
.getY());
1125 menu
.handleEvent(event
);
1129 if (event
instanceof TKeypressEvent
) {
1130 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1132 // See if this key matches an accelerator, and is not being
1133 // shortcutted by the active window, and if so dispatch the menu
1135 boolean windowWillShortcut
= false;
1136 if (activeWindow
!= null) {
1137 assert (activeWindow
.isShown());
1138 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1139 // We do not process this key, it will be passed to the
1141 windowWillShortcut
= true;
1145 if (!windowWillShortcut
&& !modalWindowActive()) {
1146 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1147 TMenuItem item
= null;
1148 synchronized (accelerators
) {
1149 item
= accelerators
.get(keypressLowercase
);
1152 if (item
.isEnabled()) {
1153 // Let the menu item dispatch
1159 // Handle the keypress
1160 if (onKeypress(keypress
)) {
1166 if (event
instanceof TCommandEvent
) {
1167 if (onCommand((TCommandEvent
) event
)) {
1172 if (event
instanceof TMenuEvent
) {
1173 if (onMenu((TMenuEvent
) event
)) {
1178 // Dispatch events to the active window -------------------------------
1179 boolean dispatchToDesktop
= true;
1180 TWindow window
= activeWindow
;
1181 if (window
!= null) {
1182 assert (window
.isActive());
1183 assert (window
.isShown());
1184 if (event
instanceof TMouseEvent
) {
1185 TMouseEvent mouse
= (TMouseEvent
) event
;
1186 // Convert the mouse relative x/y to window coordinates
1187 assert (mouse
.getX() == mouse
.getAbsoluteX());
1188 assert (mouse
.getY() == mouse
.getAbsoluteY());
1189 mouse
.setX(mouse
.getX() - window
.getX());
1190 mouse
.setY(mouse
.getY() - window
.getY());
1192 if (window
.mouseWouldHit(mouse
)) {
1193 dispatchToDesktop
= false;
1195 } else if (event
instanceof TKeypressEvent
) {
1196 dispatchToDesktop
= false;
1200 System
.err
.printf("TApplication dispatch event: %s\n",
1203 window
.handleEvent(event
);
1205 if (dispatchToDesktop
) {
1206 // This event is fair game for the desktop to process.
1207 if (desktop
!= null) {
1208 desktop
.handleEvent(event
);
1214 * Dispatch one event to the appropriate widget or application-level
1215 * event handler. This is the secondary event handler used by certain
1216 * special dialogs (currently TMessageBox and TFileOpenBox).
1218 * @param event the input event to consume
1219 * @see #primaryHandleEvent(TInputEvent event)
1221 private void secondaryHandleEvent(final TInputEvent event
) {
1222 // Peek at the mouse position
1223 if (event
instanceof TMouseEvent
) {
1224 TMouseEvent mouse
= (TMouseEvent
) event
;
1225 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1228 mouseX
= mouse
.getX();
1229 mouseY
= mouse
.getY();
1233 secondaryEventReceiver
.handleEvent(event
);
1237 * Enable a widget to override the primary event thread.
1239 * @param widget widget that will receive events
1241 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1243 System
.err
.println(System
.currentTimeMillis() +
1244 " enableSecondaryEventReceiver()");
1247 assert (secondaryEventReceiver
== null);
1248 assert (secondaryEventHandler
== null);
1249 assert ((widget
instanceof TMessageBox
)
1250 || (widget
instanceof TFileOpenBox
));
1251 secondaryEventReceiver
= widget
;
1252 secondaryEventHandler
= new WidgetEventHandler(this, false);
1254 (new Thread(secondaryEventHandler
)).start();
1258 * Yield to the secondary thread.
1260 public final void yield() {
1261 assert (secondaryEventReceiver
!= null);
1263 while (secondaryEventReceiver
!= null) {
1264 synchronized (primaryEventHandler
) {
1266 primaryEventHandler
.wait();
1267 } catch (InterruptedException e
) {
1275 * Do stuff when there is no user input.
1277 private void doIdle() {
1279 System
.err
.printf(System
.currentTimeMillis() + " " +
1280 Thread
.currentThread() + " doIdle()\n");
1283 synchronized (timers
) {
1286 System
.err
.printf(System
.currentTimeMillis() + " " +
1287 Thread
.currentThread() + " doIdle() 2\n");
1290 // Run any timers that have timed out
1291 Date now
= new Date();
1292 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1293 for (TTimer timer
: timers
) {
1294 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1295 // Something might change, so repaint the screen.
1298 if (timer
.recurring
) {
1299 keepTimers
.add(timer
);
1302 keepTimers
.add(timer
);
1305 timers
= keepTimers
;
1309 for (TWindow window
: windows
) {
1312 if (desktop
!= null) {
1317 // ------------------------------------------------------------------------
1318 // TWindow management -----------------------------------------------------
1319 // ------------------------------------------------------------------------
1322 * Return the total number of windows.
1324 * @return the total number of windows
1326 public final int windowCount() {
1327 return windows
.size();
1331 * Return the number of windows that are showing.
1333 * @return the number of windows that are showing on screen
1335 public final int shownWindowCount() {
1337 for (TWindow w
: windows
) {
1346 * Return the number of windows that are hidden.
1348 * @return the number of windows that are hidden
1350 public final int hiddenWindowCount() {
1352 for (TWindow w
: windows
) {
1361 * Check if a window instance is in this application's window list.
1363 * @param window window to look for
1364 * @return true if this window is in the list
1366 public final boolean hasWindow(final TWindow window
) {
1367 if (windows
.size() == 0) {
1370 for (TWindow w
: windows
) {
1372 assert (window
.getApplication() == this);
1380 * Activate a window: bring it to the top and have it receive events.
1382 * @param window the window to become the new active window
1384 public void activateWindow(final TWindow window
) {
1385 if (hasWindow(window
) == false) {
1387 * Someone has a handle to a window I don't have. Ignore this
1393 // Whatever window might be moving/dragging, stop it now.
1394 for (TWindow w
: windows
) {
1395 if (w
.inMovements()) {
1400 assert (windows
.size() > 0);
1402 if (window
.isHidden()) {
1403 // Unhiding will also activate.
1407 assert (window
.isShown());
1409 if (windows
.size() == 1) {
1410 assert (window
== windows
.get(0));
1411 if (activeWindow
== null) {
1412 activeWindow
= window
;
1414 activeWindow
.setActive(true);
1415 activeWindow
.onFocus();
1418 assert (window
.isActive());
1419 assert (activeWindow
== window
);
1423 if (activeWindow
== window
) {
1424 assert (window
.isActive());
1426 // Window is already active, do nothing.
1430 assert (!window
.isActive());
1431 if (activeWindow
!= null) {
1432 assert (activeWindow
.getZ() == 0);
1434 activeWindow
.onUnfocus();
1435 activeWindow
.setActive(false);
1436 activeWindow
.setZ(window
.getZ());
1438 activeWindow
= window
;
1439 activeWindow
.setZ(0);
1440 activeWindow
.setActive(true);
1441 activeWindow
.onFocus();
1448 * @param window the window to hide
1450 public void hideWindow(final TWindow window
) {
1451 if (hasWindow(window
) == false) {
1453 * Someone has a handle to a window I don't have. Ignore this
1459 // Whatever window might be moving/dragging, stop it now.
1460 for (TWindow w
: windows
) {
1461 if (w
.inMovements()) {
1466 assert (windows
.size() > 0);
1468 if (!window
.hidden
) {
1469 if (window
== activeWindow
) {
1470 if (shownWindowCount() > 1) {
1473 activeWindow
= null;
1474 window
.setActive(false);
1478 window
.hidden
= true;
1486 * @param window the window to show
1488 public void showWindow(final TWindow window
) {
1489 if (hasWindow(window
) == false) {
1491 * Someone has a handle to a window I don't have. Ignore this
1497 // Whatever window might be moving/dragging, stop it now.
1498 for (TWindow w
: windows
) {
1499 if (w
.inMovements()) {
1504 assert (windows
.size() > 0);
1506 if (window
.hidden
) {
1507 window
.hidden
= false;
1509 activateWindow(window
);
1514 * Close window. Note that the window's destructor is NOT called by this
1515 * method, instead the GC is assumed to do the cleanup.
1517 * @param window the window to remove
1519 public final void closeWindow(final TWindow window
) {
1520 if (hasWindow(window
) == false) {
1522 * Someone has a handle to a window I don't have. Ignore this
1528 synchronized (windows
) {
1529 // Whatever window might be moving/dragging, stop it now.
1530 for (TWindow w
: windows
) {
1531 if (w
.inMovements()) {
1536 int z
= window
.getZ();
1539 Collections
.sort(windows
);
1541 activeWindow
= null;
1542 for (TWindow w
: windows
) {
1544 w
.setZ(w
.getZ() - 1);
1545 if (w
.getZ() == 0) {
1548 assert (activeWindow
== null);
1560 // Perform window cleanup
1563 // Check if we are closing a TMessageBox or similar
1564 if (secondaryEventReceiver
!= null) {
1565 assert (secondaryEventHandler
!= null);
1567 // Do not send events to the secondaryEventReceiver anymore, the
1568 // window is closed.
1569 secondaryEventReceiver
= null;
1571 // Wake the secondary thread, it will wake the primary as it
1573 synchronized (secondaryEventHandler
) {
1574 secondaryEventHandler
.notify();
1578 // Permit desktop to be active if it is the only thing left.
1579 if (desktop
!= null) {
1580 if (windows
.size() == 0) {
1581 desktop
.setActive(true);
1587 * Switch to the next window.
1589 * @param forward if true, then switch to the next window in the list,
1590 * otherwise switch to the previous window in the list
1592 public final void switchWindow(final boolean forward
) {
1593 // Only switch if there are multiple visible windows
1594 if (shownWindowCount() < 2) {
1597 assert (activeWindow
!= null);
1599 synchronized (windows
) {
1600 // Whatever window might be moving/dragging, stop it now.
1601 for (TWindow w
: windows
) {
1602 if (w
.inMovements()) {
1607 // Swap z/active between active window and the next in the list
1608 int activeWindowI
= -1;
1609 for (int i
= 0; i
< windows
.size(); i
++) {
1610 if (windows
.get(i
) == activeWindow
) {
1611 assert (activeWindow
.isActive());
1615 assert (!windows
.get(0).isActive());
1618 assert (activeWindowI
>= 0);
1620 // Do not switch if a window is modal
1621 if (activeWindow
.isModal()) {
1625 int nextWindowI
= activeWindowI
;
1629 nextWindowI
%= windows
.size();
1632 if (nextWindowI
< 0) {
1633 nextWindowI
= windows
.size() - 1;
1637 if (windows
.get(nextWindowI
).isShown()) {
1638 activateWindow(windows
.get(nextWindowI
));
1642 } // synchronized (windows)
1647 * Add a window to my window list and make it active.
1649 * @param window new window to add
1651 public final void addWindow(final TWindow window
) {
1653 // Do not add menu windows to the window list.
1654 if (window
instanceof TMenu
) {
1658 // Do not add the desktop to the window list.
1659 if (window
instanceof TDesktop
) {
1663 synchronized (windows
) {
1664 // Whatever window might be moving/dragging, stop it now.
1665 for (TWindow w
: windows
) {
1666 if (w
.inMovements()) {
1671 // Do not allow a modal window to spawn a non-modal window. If a
1672 // modal window is active, then this window will become modal
1674 if (modalWindowActive()) {
1675 window
.flags
|= TWindow
.MODAL
;
1676 window
.flags
|= TWindow
.CENTERED
;
1677 window
.hidden
= false;
1679 if (window
.isShown()) {
1680 for (TWindow w
: windows
) {
1685 w
.setZ(w
.getZ() + 1);
1688 windows
.add(window
);
1689 if (window
.isShown()) {
1690 activeWindow
= window
;
1691 activeWindow
.setZ(0);
1692 activeWindow
.setActive(true);
1693 activeWindow
.onFocus();
1696 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1697 && smartWindowPlacement
) {
1699 doSmartPlacement(window
);
1703 // Desktop cannot be active over any other window.
1704 if (desktop
!= null) {
1705 desktop
.setActive(false);
1710 * Check if there is a system-modal window on top.
1712 * @return true if the active window is modal
1714 private boolean modalWindowActive() {
1715 if (windows
.size() == 0) {
1719 for (TWindow w
: windows
) {
1729 * Close all open windows.
1731 private void closeAllWindows() {
1732 // Don't do anything if we are in the menu
1733 if (activeMenu
!= null) {
1736 while (windows
.size() > 0) {
1737 closeWindow(windows
.get(0));
1742 * Re-layout the open windows as non-overlapping tiles. This produces
1743 * almost the same results as Turbo Pascal 7.0's IDE.
1745 private void tileWindows() {
1746 synchronized (windows
) {
1747 // Don't do anything if we are in the menu
1748 if (activeMenu
!= null) {
1751 int z
= windows
.size();
1757 a
= (int)(Math
.sqrt(z
));
1761 if (((a
* b
) + c
) == z
) {
1769 int newWidth
= (getScreen().getWidth() / a
);
1770 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1771 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1773 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1774 Collections
.sort(sorted
);
1775 Collections
.reverse(sorted
);
1776 for (int i
= 0; i
< sorted
.size(); i
++) {
1777 int logicalX
= i
/ b
;
1778 int logicalY
= i
% b
;
1779 if (i
>= ((a
- 1) * b
)) {
1781 logicalY
= i
- ((a
- 1) * b
);
1784 TWindow w
= sorted
.get(i
);
1785 w
.setX(logicalX
* newWidth
);
1786 w
.setWidth(newWidth
);
1787 if (i
>= ((a
- 1) * b
)) {
1788 w
.setY((logicalY
* newHeight2
) + 1);
1789 w
.setHeight(newHeight2
);
1791 w
.setY((logicalY
* newHeight1
) + 1);
1792 w
.setHeight(newHeight1
);
1799 * Re-layout the open windows as overlapping cascaded windows.
1801 private void cascadeWindows() {
1802 synchronized (windows
) {
1803 // Don't do anything if we are in the menu
1804 if (activeMenu
!= null) {
1809 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1810 Collections
.sort(sorted
);
1811 Collections
.reverse(sorted
);
1812 for (TWindow window
: sorted
) {
1817 if (x
> getScreen().getWidth()) {
1820 if (y
>= getScreen().getHeight()) {
1828 * Place a window to minimize its overlap with other windows.
1830 * @param window the window to place
1832 public final void doSmartPlacement(final TWindow window
) {
1833 // This is a pretty dumb algorithm, but seems to work. The hardest
1834 // part is computing these "overlap" values seeking a minimum average
1837 int yMin
= desktopTop
;
1838 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1839 int yMax
= desktopBottom
- window
.getHeight() + 1;
1847 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1848 // No work to do, bail out.
1852 // Compute the overlap matrix without the new window.
1853 int width
= getScreen().getWidth();
1854 int height
= getScreen().getHeight();
1855 int overlapMatrix
[][] = new int[width
][height
];
1856 for (TWindow w
: windows
) {
1860 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1864 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1868 overlapMatrix
[x
][y
]++;
1873 long oldOverlapTotal
= 0;
1874 long oldOverlapN
= 0;
1875 for (int x
= 0; x
< width
; x
++) {
1876 for (int y
= 0; y
< height
; y
++) {
1877 oldOverlapTotal
+= overlapMatrix
[x
][y
];
1878 if (overlapMatrix
[x
][y
] > 0) {
1885 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
1886 boolean first
= true;
1887 int windowX
= window
.getX();
1888 int windowY
= window
.getY();
1890 // For each possible (x, y) position for the new window, compute a
1891 // new overlap matrix.
1892 for (int x
= xMin
; x
< xMax
; x
++) {
1893 for (int y
= yMin
; y
< yMax
; y
++) {
1895 // Start with the matrix minus this window.
1896 int newMatrix
[][] = new int[width
][height
];
1897 for (int mx
= 0; mx
< width
; mx
++) {
1898 for (int my
= 0; my
< height
; my
++) {
1899 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
1903 // Add this window's values to the new overlap matrix.
1904 long newOverlapTotal
= 0;
1905 long newOverlapN
= 0;
1906 // Start by adding each new cell.
1907 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
1911 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
1915 newMatrix
[wx
][wy
]++;
1918 // Now figure out the new value for total coverage.
1919 for (int mx
= 0; mx
< width
; mx
++) {
1920 for (int my
= 0; my
< height
; my
++) {
1921 newOverlapTotal
+= newMatrix
[x
][y
];
1922 if (newMatrix
[mx
][my
] > 0) {
1927 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
1930 // First time: just record what we got.
1931 oldOverlapAvg
= newOverlapAvg
;
1934 // All other times: pick a new best (x, y) and save the
1936 if (newOverlapAvg
< oldOverlapAvg
) {
1939 oldOverlapAvg
= newOverlapAvg
;
1943 } // for (int x = xMin; x < xMax; x++)
1945 } // for (int y = yMin; y < yMax; y++)
1947 // Finally, set the window's new coordinates.
1948 window
.setX(windowX
);
1949 window
.setY(windowY
);
1952 // ------------------------------------------------------------------------
1953 // TMenu management -------------------------------------------------------
1954 // ------------------------------------------------------------------------
1957 * Check if a mouse event would hit either the active menu or any open
1960 * @param mouse mouse event
1961 * @return true if the mouse would hit the active menu or an open
1964 private boolean mouseOnMenu(final TMouseEvent mouse
) {
1965 assert (activeMenu
!= null);
1966 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
1967 Collections
.reverse(menus
);
1968 for (TMenu menu
: menus
) {
1969 if (menu
.mouseWouldHit(mouse
)) {
1973 return activeMenu
.mouseWouldHit(mouse
);
1977 * See if we need to switch window or activate the menu based on
1980 * @param mouse mouse event
1982 private void checkSwitchFocus(final TMouseEvent mouse
) {
1984 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1985 && (activeMenu
!= null)
1986 && (mouse
.getAbsoluteY() != 0)
1987 && (!mouseOnMenu(mouse
))
1989 // They clicked outside the active menu, turn it off
1990 activeMenu
.setActive(false);
1992 for (TMenu menu
: subMenus
) {
1993 menu
.setActive(false);
1999 // See if they hit the menu bar
2000 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2001 && (mouse
.isMouse1())
2002 && (!modalWindowActive())
2003 && (mouse
.getAbsoluteY() == 0)
2006 for (TMenu menu
: subMenus
) {
2007 menu
.setActive(false);
2011 // They selected the menu, go activate it
2012 for (TMenu menu
: menus
) {
2013 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2014 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2015 + menu
.getTitle().length() + 2)
2017 menu
.setActive(true);
2020 menu
.setActive(false);
2026 // See if they hit the menu bar
2027 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2028 && (mouse
.isMouse1())
2029 && (activeMenu
!= null)
2030 && (mouse
.getAbsoluteY() == 0)
2033 TMenu oldMenu
= activeMenu
;
2034 for (TMenu menu
: subMenus
) {
2035 menu
.setActive(false);
2039 // See if we should switch menus
2040 for (TMenu menu
: menus
) {
2041 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2042 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2043 + menu
.getTitle().length() + 2)
2045 menu
.setActive(true);
2049 if (oldMenu
!= activeMenu
) {
2050 // They switched menus
2051 oldMenu
.setActive(false);
2056 // If a menu is still active, don't switch windows
2057 if (activeMenu
!= null) {
2061 // Only switch if there are multiple windows
2062 if (windows
.size() < 2) {
2066 if (((focusFollowsMouse
== true)
2067 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2068 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2070 synchronized (windows
) {
2071 Collections
.sort(windows
);
2072 if (windows
.get(0).isModal()) {
2073 // Modal windows don't switch
2077 for (TWindow window
: windows
) {
2078 assert (!window
.isModal());
2080 if (window
.isHidden()) {
2081 assert (!window
.isActive());
2085 if (window
.mouseWouldHit(mouse
)) {
2086 if (window
== windows
.get(0)) {
2087 // Clicked on the same window, nothing to do
2088 assert (window
.isActive());
2092 // We will be switching to another window
2093 assert (windows
.get(0).isActive());
2094 assert (windows
.get(0) == activeWindow
);
2095 assert (!window
.isActive());
2096 activeWindow
.onUnfocus();
2097 activeWindow
.setActive(false);
2098 activeWindow
.setZ(window
.getZ());
2099 activeWindow
= window
;
2101 window
.setActive(true);
2108 // Clicked on the background, nothing to do
2112 // Nothing to do: this isn't a mouse up, or focus isn't following
2118 * Turn off the menu.
2120 public final void closeMenu() {
2121 if (activeMenu
!= null) {
2122 activeMenu
.setActive(false);
2124 for (TMenu menu
: subMenus
) {
2125 menu
.setActive(false);
2132 * Get a (shallow) copy of the menu list.
2134 * @return a copy of the menu list
2136 public final List
<TMenu
> getAllMenus() {
2137 return new LinkedList
<TMenu
>(menus
);
2141 * Add a top-level menu to the list.
2143 * @param menu the menu to add
2144 * @throws IllegalArgumentException if the menu is already used in
2145 * another TApplication
2147 public final void addMenu(final TMenu menu
) {
2148 if ((menu
.getApplication() != null)
2149 && (menu
.getApplication() != this)
2151 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2152 "part of application " + menu
.getApplication());
2160 * Remove a top-level menu from the list.
2162 * @param menu the menu to remove
2163 * @throws IllegalArgumentException if the menu is already used in
2164 * another TApplication
2166 public final void removeMenu(final TMenu menu
) {
2167 if ((menu
.getApplication() != null)
2168 && (menu
.getApplication() != this)
2170 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2171 "part of application " + menu
.getApplication());
2179 * Turn off a sub-menu.
2181 public final void closeSubMenu() {
2182 assert (activeMenu
!= null);
2183 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2184 assert (item
!= null);
2185 item
.setActive(false);
2186 subMenus
.remove(subMenus
.size() - 1);
2190 * Switch to the next menu.
2192 * @param forward if true, then switch to the next menu in the list,
2193 * otherwise switch to the previous menu in the list
2195 public final void switchMenu(final boolean forward
) {
2196 assert (activeMenu
!= null);
2198 for (TMenu menu
: subMenus
) {
2199 menu
.setActive(false);
2203 for (int i
= 0; i
< menus
.size(); i
++) {
2204 if (activeMenu
== menus
.get(i
)) {
2206 if (i
< menus
.size() - 1) {
2214 activeMenu
.setActive(false);
2215 activeMenu
= menus
.get(i
);
2216 activeMenu
.setActive(true);
2223 * Add a menu item to the global list. If it has a keyboard accelerator,
2224 * that will be added the global hash.
2226 * @param item the menu item
2228 public final void addMenuItem(final TMenuItem item
) {
2229 menuItems
.add(item
);
2231 TKeypress key
= item
.getKey();
2233 synchronized (accelerators
) {
2234 assert (accelerators
.get(key
) == null);
2235 accelerators
.put(key
.toLowerCase(), item
);
2241 * Disable one menu item.
2243 * @param id the menu item ID
2245 public final void disableMenuItem(final int id
) {
2246 for (TMenuItem item
: menuItems
) {
2247 if (item
.getId() == id
) {
2248 item
.setEnabled(false);
2254 * Disable the range of menu items with ID's between lower and upper,
2257 * @param lower the lowest menu item ID
2258 * @param upper the highest menu item ID
2260 public final void disableMenuItems(final int lower
, final int upper
) {
2261 for (TMenuItem item
: menuItems
) {
2262 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2263 item
.setEnabled(false);
2269 * Enable one menu item.
2271 * @param id the menu item ID
2273 public final void enableMenuItem(final int id
) {
2274 for (TMenuItem item
: menuItems
) {
2275 if (item
.getId() == id
) {
2276 item
.setEnabled(true);
2282 * Enable the range of menu items with ID's between lower and upper,
2285 * @param lower the lowest menu item ID
2286 * @param upper the highest menu item ID
2288 public final void enableMenuItems(final int lower
, final int upper
) {
2289 for (TMenuItem item
: menuItems
) {
2290 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2291 item
.setEnabled(true);
2297 * Recompute menu x positions based on their title length.
2299 public final void recomputeMenuX() {
2301 for (TMenu menu
: menus
) {
2304 x
+= menu
.getTitle().length() + 2;
2306 // Don't let the menu window exceed the screen width
2307 int rightEdge
= menu
.getX() + menu
.getWidth();
2308 if (rightEdge
> getScreen().getWidth()) {
2309 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2315 * Post an event to process and turn off the menu.
2317 * @param event new event to add to the queue
2319 public final void postMenuEvent(final TInputEvent event
) {
2320 synchronized (this) {
2321 synchronized (fillEventQueue
) {
2322 fillEventQueue
.add(event
);
2325 System
.err
.println(System
.currentTimeMillis() + " " +
2326 Thread
.currentThread() + " postMenuEvent() wake up main");
2334 * Add a sub-menu to the list of open sub-menus.
2336 * @param menu sub-menu
2338 public final void addSubMenu(final TMenu menu
) {
2343 * Convenience function to add a top-level menu.
2345 * @param title menu title
2346 * @return the new menu
2348 public final TMenu
addMenu(final String title
) {
2351 TMenu menu
= new TMenu(this, x
, y
, title
);
2358 * Convenience function to add a default "File" menu.
2360 * @return the new menu
2362 public final TMenu
addFileMenu() {
2363 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
2364 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2365 fileMenu
.addSeparator();
2366 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2367 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2368 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
2369 getString("fileMenuStatus"));
2370 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2375 * Convenience function to add a default "Edit" menu.
2377 * @return the new menu
2379 public final TMenu
addEditMenu() {
2380 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
2381 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2382 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2383 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2384 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2385 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
2386 getString("editMenuStatus"));
2387 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2392 * Convenience function to add a default "Window" menu.
2394 * @return the new menu
2396 public final TMenu
addWindowMenu() {
2397 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
2398 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2399 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2400 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2401 windowMenu
.addSeparator();
2402 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2403 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2404 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2405 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2406 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2407 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
2408 getString("windowMenuStatus"));
2409 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2414 * Convenience function to add a default "Help" menu.
2416 * @return the new menu
2418 public final TMenu
addHelpMenu() {
2419 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
2420 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2421 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2422 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2423 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2424 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2425 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2426 helpMenu
.addSeparator();
2427 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2428 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
2429 getString("helpMenuStatus"));
2430 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2434 // ------------------------------------------------------------------------
2435 // Event handlers ---------------------------------------------------------
2436 // ------------------------------------------------------------------------
2439 * Method that TApplication subclasses can override to handle menu or
2440 * posted command events.
2442 * @param command command event
2443 * @return if true, this event was consumed
2445 protected boolean onCommand(final TCommandEvent command
) {
2446 // Default: handle cmExit
2447 if (command
.equals(cmExit
)) {
2448 if (messageBox(i18n
.getString("exitDialogTitle"),
2449 i18n
.getString("exitDialogText"),
2450 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2456 if (command
.equals(cmShell
)) {
2457 openTerminal(0, 0, TWindow
.RESIZABLE
);
2461 if (command
.equals(cmTile
)) {
2465 if (command
.equals(cmCascade
)) {
2469 if (command
.equals(cmCloseAll
)) {
2474 if (command
.equals(cmMenu
)) {
2475 if (!modalWindowActive() && (activeMenu
== null)) {
2476 if (menus
.size() > 0) {
2477 menus
.get(0).setActive(true);
2478 activeMenu
= menus
.get(0);
2488 * Method that TApplication subclasses can override to handle menu
2491 * @param menu menu event
2492 * @return if true, this event was consumed
2494 protected boolean onMenu(final TMenuEvent menu
) {
2496 // Default: handle MID_EXIT
2497 if (menu
.getId() == TMenu
.MID_EXIT
) {
2498 if (messageBox(i18n
.getString("exitDialogTitle"),
2499 i18n
.getString("exitDialogText"),
2500 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2506 if (menu
.getId() == TMenu
.MID_SHELL
) {
2507 openTerminal(0, 0, TWindow
.RESIZABLE
);
2511 if (menu
.getId() == TMenu
.MID_TILE
) {
2515 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2519 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2523 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2527 if (menu
.getId() == TMenu
.MID_REPAINT
) {
2535 * Method that TApplication subclasses can override to handle keystrokes.
2537 * @param keypress keystroke event
2538 * @return if true, this event was consumed
2540 protected boolean onKeypress(final TKeypressEvent keypress
) {
2541 // Default: only menu shortcuts
2543 // Process Alt-F, Alt-E, etc. menu shortcut keys
2544 if (!keypress
.getKey().isFnKey()
2545 && keypress
.getKey().isAlt()
2546 && !keypress
.getKey().isCtrl()
2547 && (activeMenu
== null)
2548 && !modalWindowActive()
2551 assert (subMenus
.size() == 0);
2553 for (TMenu menu
: menus
) {
2554 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2555 == Character
.toLowerCase(keypress
.getKey().getChar())
2558 menu
.setActive(true);
2567 // ------------------------------------------------------------------------
2568 // TTimer management ------------------------------------------------------
2569 // ------------------------------------------------------------------------
2572 * Get the amount of time I can sleep before missing a Timer tick.
2574 * @param timeout = initial (maximum) timeout in millis
2575 * @return number of milliseconds between now and the next timer event
2577 private long getSleepTime(final long timeout
) {
2578 Date now
= new Date();
2579 long nowTime
= now
.getTime();
2580 long sleepTime
= timeout
;
2582 synchronized (timers
) {
2583 for (TTimer timer
: timers
) {
2584 long nextTickTime
= timer
.getNextTick().getTime();
2585 if (nextTickTime
< nowTime
) {
2589 long timeDifference
= nextTickTime
- nowTime
;
2590 if (timeDifference
< sleepTime
) {
2591 sleepTime
= timeDifference
;
2596 assert (sleepTime
>= 0);
2597 assert (sleepTime
<= timeout
);
2602 * Convenience function to add a timer.
2604 * @param duration number of milliseconds to wait between ticks
2605 * @param recurring if true, re-schedule this timer after every tick
2606 * @param action function to call when button is pressed
2609 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2610 final TAction action
) {
2612 TTimer timer
= new TTimer(duration
, recurring
, action
);
2613 synchronized (timers
) {
2620 * Convenience function to remove a timer.
2622 * @param timer timer to remove
2624 public final void removeTimer(final TTimer timer
) {
2625 synchronized (timers
) {
2626 timers
.remove(timer
);
2630 // ------------------------------------------------------------------------
2631 // Other TWindow constructors ---------------------------------------------
2632 // ------------------------------------------------------------------------
2635 * Convenience function to spawn a message box.
2637 * @param title window title, will be centered along the top border
2638 * @param caption message to display. Use embedded newlines to get a
2640 * @return the new message box
2642 public final TMessageBox
messageBox(final String title
,
2643 final String caption
) {
2645 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2649 * Convenience function to spawn a message box.
2651 * @param title window title, will be centered along the top border
2652 * @param caption message to display. Use embedded newlines to get a
2654 * @param type one of the TMessageBox.Type constants. Default is
2656 * @return the new message box
2658 public final TMessageBox
messageBox(final String title
,
2659 final String caption
, final TMessageBox
.Type type
) {
2661 return new TMessageBox(this, title
, caption
, type
);
2665 * Convenience function to spawn an input box.
2667 * @param title window title, will be centered along the top border
2668 * @param caption message to display. Use embedded newlines to get a
2670 * @return the new input box
2672 public final TInputBox
inputBox(final String title
, final String caption
) {
2674 return new TInputBox(this, title
, caption
);
2678 * Convenience function to spawn an input box.
2680 * @param title window title, will be centered along the top border
2681 * @param caption message to display. Use embedded newlines to get a
2683 * @param text initial text to seed the field with
2684 * @return the new input box
2686 public final TInputBox
inputBox(final String title
, final String caption
,
2687 final String text
) {
2689 return new TInputBox(this, title
, caption
, text
);
2693 * Convenience function to open a terminal window.
2695 * @param x column relative to parent
2696 * @param y row relative to parent
2697 * @return the terminal new window
2699 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2700 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2704 * Convenience function to open a terminal window.
2706 * @param x column relative to parent
2707 * @param y row relative to parent
2708 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2709 * @return the terminal new window
2711 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2714 return new TTerminalWindow(this, x
, y
, flags
);
2718 * Convenience function to spawn an file open box.
2720 * @param path path of selected file
2721 * @return the result of the new file open box
2722 * @throws IOException if java.io operation throws
2724 public final String
fileOpenBox(final String path
) throws IOException
{
2726 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2727 return box
.getFilename();
2731 * Convenience function to spawn an file open box.
2733 * @param path path of selected file
2734 * @param type one of the Type constants
2735 * @return the result of the new file open box
2736 * @throws IOException if java.io operation throws
2738 public final String
fileOpenBox(final String path
,
2739 final TFileOpenBox
.Type type
) throws IOException
{
2741 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2742 return box
.getFilename();
2746 * Convenience function to create a new window and make it active.
2747 * Window will be located at (0, 0).
2749 * @param title window title, will be centered along the top border
2750 * @param width width of window
2751 * @param height height of window
2753 public final TWindow
addWindow(final String title
, final int width
,
2756 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2761 * Convenience function to create a new window and make it active.
2762 * Window will be located at (0, 0).
2764 * @param title window title, will be centered along the top border
2765 * @param width width of window
2766 * @param height height of window
2767 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2769 public final TWindow
addWindow(final String title
,
2770 final int width
, final int height
, final int flags
) {
2772 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2777 * Convenience function to create a new window and make it active.
2779 * @param title window title, will be centered along the top border
2780 * @param x column relative to parent
2781 * @param y row relative to parent
2782 * @param width width of window
2783 * @param height height of window
2785 public final TWindow
addWindow(final String title
,
2786 final int x
, final int y
, final int width
, final int height
) {
2788 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2793 * Convenience function to create a new window and make it active.
2795 * @param title window title, will be centered along the top border
2796 * @param x column relative to parent
2797 * @param y row relative to parent
2798 * @param width width of window
2799 * @param height height of window
2800 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2802 public final TWindow
addWindow(final String title
,
2803 final int x
, final int y
, final int width
, final int height
,
2806 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);
2811 * Convenience function to open a file in an editor window and make it
2814 * @param file the file to open
2815 * @throws IOException if a java.io operation throws
2817 public final TEditorWindow
addEditor(final File file
) throws IOException
{
2819 TEditorWindow editor
= new TEditorWindow(this, file
);