2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2019 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
.ArrayList
;
40 import java
.util
.Collections
;
41 import java
.util
.Date
;
42 import java
.util
.HashMap
;
43 import java
.util
.LinkedList
;
44 import java
.util
.List
;
46 import java
.util
.ResourceBundle
;
48 import jexer
.bits
.Cell
;
49 import jexer
.bits
.CellAttributes
;
50 import jexer
.bits
.ColorTheme
;
51 import jexer
.bits
.StringUtils
;
52 import jexer
.event
.TCommandEvent
;
53 import jexer
.event
.TInputEvent
;
54 import jexer
.event
.TKeypressEvent
;
55 import jexer
.event
.TMenuEvent
;
56 import jexer
.event
.TMouseEvent
;
57 import jexer
.event
.TResizeEvent
;
58 import jexer
.backend
.Backend
;
59 import jexer
.backend
.MultiBackend
;
60 import jexer
.backend
.Screen
;
61 import jexer
.backend
.SwingBackend
;
62 import jexer
.backend
.ECMA48Backend
;
63 import jexer
.backend
.TWindowBackend
;
64 import jexer
.menu
.TMenu
;
65 import jexer
.menu
.TMenuItem
;
66 import jexer
.menu
.TSubMenu
;
67 import static jexer
.TCommand
.*;
68 import static jexer
.TKeypress
.*;
71 * TApplication is the main driver class for a full Text User Interface
72 * application. It manages windows, provides a menu bar and status bar, and
73 * processes events received from the user.
75 public class TApplication
implements Runnable
{
80 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
82 // ------------------------------------------------------------------------
83 // Constants --------------------------------------------------------------
84 // ------------------------------------------------------------------------
87 * If true, emit thread stuff to System.err.
89 private static final boolean debugThreads
= false;
92 * If true, emit events being processed to System.err.
94 private static final boolean debugEvents
= false;
97 * If true, do "smart placement" on new windows that are not specified to
100 private static final boolean smartWindowPlacement
= true;
103 * Two backend types are available.
105 public static enum BackendType
{
112 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
117 * Synonym for ECMA48.
122 // ------------------------------------------------------------------------
123 // Variables --------------------------------------------------------------
124 // ------------------------------------------------------------------------
127 * The primary event handler thread.
129 private volatile WidgetEventHandler primaryEventHandler
;
132 * The secondary event handler thread.
134 private volatile WidgetEventHandler secondaryEventHandler
;
137 * The screen handler thread.
139 private volatile ScreenHandler screenHandler
;
142 * The widget receiving events from the secondary event handler thread.
144 private volatile TWidget secondaryEventReceiver
;
147 * Access to the physical screen, keyboard, and mouse.
149 private Backend backend
;
152 * Actual mouse coordinate X.
157 * Actual mouse coordinate Y.
162 * Old version of mouse coordinate X.
164 private int oldMouseX
;
167 * Old version mouse coordinate Y.
169 private int oldMouseY
;
172 * Old drawn version of mouse coordinate X.
174 private int oldDrawnMouseX
;
177 * Old drawn version mouse coordinate Y.
179 private int oldDrawnMouseY
;
182 * Old drawn version mouse cell.
184 private Cell oldDrawnMouseCell
= new Cell();
187 * The last mouse up click time, used to determine if this is a mouse
190 private long lastMouseUpTime
;
193 * The amount of millis between mouse up events to assume a double-click.
195 private long doubleClickTime
= 250;
198 * Event queue that is filled by run().
200 private List
<TInputEvent
> fillEventQueue
;
203 * Event queue that will be drained by either primary or secondary
206 private List
<TInputEvent
> drainEventQueue
;
209 * Top-level menus in this application.
211 private List
<TMenu
> menus
;
214 * Stack of activated sub-menus in this application.
216 private List
<TMenu
> subMenus
;
219 * The currently active menu.
221 private TMenu activeMenu
= null;
224 * Active keyboard accelerators.
226 private Map
<TKeypress
, TMenuItem
> accelerators
;
231 private List
<TMenuItem
> menuItems
;
234 * Windows and widgets pull colors from this ColorTheme.
236 private ColorTheme theme
;
239 * The top-level windows (but not menus).
241 private List
<TWindow
> windows
;
244 * The currently acive window.
246 private TWindow activeWindow
= null;
249 * Timers that are being ticked.
251 private List
<TTimer
> timers
;
254 * When true, the application has been started.
256 private volatile boolean started
= false;
259 * When true, exit the application.
261 private volatile boolean quit
= false;
264 * When true, repaint the entire screen.
266 private volatile boolean repaint
= true;
269 * Y coordinate of the top edge of the desktop. For now this is a
270 * constant. Someday it would be nice to have a multi-line menu or
273 private int desktopTop
= 1;
276 * Y coordinate of the bottom edge of the desktop.
278 private int desktopBottom
;
281 * An optional TDesktop background window that is drawn underneath
284 private TDesktop desktop
;
287 * If true, focus follows mouse: windows automatically raised if the
288 * mouse passes over them.
290 private boolean focusFollowsMouse
= false;
293 * If true, display a text-based mouse cursor.
295 private boolean textMouse
= true;
298 * If true, hide the mouse after typing a keystroke.
300 private boolean hideMouseWhenTyping
= false;
303 * If true, the mouse should not be displayed because a keystroke was
306 private boolean typingHidMouse
= false;
309 * If true, hide the status bar.
311 private boolean hideStatusBar
= false;
314 * If true, hide the menu bar.
316 private boolean hideMenuBar
= false;
319 * The list of commands to run before the next I/O check.
321 private List
<Runnable
> invokeLaters
= new LinkedList
<Runnable
>();
324 * The last time the screen was resized.
326 private long screenResizeTime
= 0;
329 * WidgetEventHandler is the main event consumer loop. There are at most
330 * two such threads in existence: the primary for normal case and a
331 * secondary that is used for TMessageBox, TInputBox, and similar.
333 private class WidgetEventHandler
implements Runnable
{
335 * The main application.
337 private TApplication application
;
340 * Whether or not this WidgetEventHandler is the primary or secondary
343 private boolean primary
= true;
346 * Public constructor.
348 * @param application the main application
349 * @param primary if true, this is the primary event handler thread
351 public WidgetEventHandler(final TApplication application
,
352 final boolean primary
) {
354 this.application
= application
;
355 this.primary
= primary
;
362 // Wrap everything in a try, so that if we go belly up we can let
363 // the user have their terminal back.
366 } catch (Throwable t
) {
367 this.application
.restoreConsole();
369 this.application
.exit();
376 private void runImpl() {
377 boolean first
= true;
380 while (!application
.quit
) {
382 // Wait until application notifies me
383 while (!application
.quit
) {
385 synchronized (application
.drainEventQueue
) {
386 if (application
.drainEventQueue
.size() > 0) {
395 timeout
= application
.getSleepTime(1000);
399 // A timer needs to fire, break out.
404 System
.err
.printf("%d %s %s %s sleep %d millis\n",
405 System
.currentTimeMillis(), this,
406 primary ?
"primary" : "secondary",
407 Thread
.currentThread(), timeout
);
410 synchronized (this) {
415 System
.err
.printf("%d %s %s %s AWAKE\n",
416 System
.currentTimeMillis(), this,
417 primary ?
"primary" : "secondary",
418 Thread
.currentThread());
422 && (application
.secondaryEventReceiver
== null)
424 // Secondary thread, emergency exit. If we got
425 // here then something went wrong with the
426 // handoff between yield() and closeWindow().
427 synchronized (application
.primaryEventHandler
) {
428 application
.primaryEventHandler
.notify();
430 application
.secondaryEventHandler
= null;
431 throw new RuntimeException("secondary exited " +
435 } catch (InterruptedException e
) {
438 } // while (!application.quit)
440 // Pull all events off the queue
442 TInputEvent event
= null;
443 synchronized (application
.drainEventQueue
) {
444 if (application
.drainEventQueue
.size() == 0) {
447 event
= application
.drainEventQueue
.remove(0);
450 // We will have an event to process, so repaint the
451 // screen at the end.
452 application
.repaint
= true;
455 primaryHandleEvent(event
);
457 secondaryHandleEvent(event
);
460 && (application
.secondaryEventReceiver
== null)
462 // Secondary thread, time to exit.
464 // Eliminate my reference so that wakeEventHandler()
465 // resumes working on the primary.
466 application
.secondaryEventHandler
= null;
468 // We are ready to exit, wake up the primary thread.
469 // Remember that it is currently sleeping inside its
470 // primaryHandleEvent().
471 synchronized (application
.primaryEventHandler
) {
472 application
.primaryEventHandler
.notify();
481 // Fire timers, update screen.
483 application
.finishEventProcessing();
486 } // while (true) (main runnable loop)
491 * ScreenHandler pushes screen updates to the physical device.
493 private class ScreenHandler
implements Runnable
{
495 * The main application.
497 private TApplication application
;
502 private boolean dirty
= false;
505 * Public constructor.
507 * @param application the main application
509 public ScreenHandler(final TApplication application
) {
510 this.application
= application
;
514 * The screen update loop.
517 // Wrap everything in a try, so that if we go belly up we can let
518 // the user have their terminal back.
521 } catch (Throwable t
) {
522 this.application
.restoreConsole();
524 this.application
.exit();
531 private void runImpl() {
534 while (!application
.quit
) {
536 // Wait until application notifies me
537 while (!application
.quit
) {
539 synchronized (this) {
545 // Always check within 50 milliseconds.
548 } catch (InterruptedException e
) {
551 } // while (!application.quit)
553 // Flush the screen contents
555 System
.err
.printf("%d %s backend.flushScreen()\n",
556 System
.currentTimeMillis(), Thread
.currentThread());
558 synchronized (getScreen()) {
559 backend
.flushScreen();
561 } // while (true) (main runnable loop)
563 // Shutdown the user I/O thread(s)
568 * Set the dirty flag.
570 public void setDirty() {
571 synchronized (this) {
578 // ------------------------------------------------------------------------
579 // Constructors -----------------------------------------------------------
580 // ------------------------------------------------------------------------
583 * Public constructor.
585 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
587 * @param windowWidth the number of text columns to start with
588 * @param windowHeight the number of text rows to start with
589 * @param fontSize the size in points
590 * @throws UnsupportedEncodingException if an exception is thrown when
591 * creating the InputStreamReader
593 public TApplication(final BackendType backendType
, final int windowWidth
,
594 final int windowHeight
, final int fontSize
)
595 throws UnsupportedEncodingException
{
597 switch (backendType
) {
599 backend
= new SwingBackend(this, windowWidth
, windowHeight
,
605 backend
= new ECMA48Backend(this, null, null, windowWidth
,
606 windowHeight
, fontSize
);
609 throw new IllegalArgumentException("Invalid backend type: "
616 * Public constructor.
618 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
620 * @throws UnsupportedEncodingException if an exception is thrown when
621 * creating the InputStreamReader
623 public TApplication(final BackendType backendType
)
624 throws UnsupportedEncodingException
{
626 switch (backendType
) {
628 // The default SwingBackend is 80x25, 20 pt font. If you want to
629 // change that, you can pass the extra arguments to the
630 // SwingBackend constructor here. For example, if you wanted
631 // 90x30, 16 pt font:
633 // backend = new SwingBackend(this, 90, 30, 16);
634 backend
= new SwingBackend(this);
639 backend
= new ECMA48Backend(this, null, null);
642 throw new IllegalArgumentException("Invalid backend type: "
649 * Public constructor. The backend type will be BackendType.ECMA48.
651 * @param input an InputStream connected to the remote user, or null for
652 * System.in. If System.in is used, then on non-Windows systems it will
653 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
654 * mode. input is always converted to a Reader with UTF-8 encoding.
655 * @param output an OutputStream connected to the remote user, or null
656 * for System.out. output is always converted to a Writer with UTF-8
658 * @throws UnsupportedEncodingException if an exception is thrown when
659 * creating the InputStreamReader
661 public TApplication(final InputStream input
,
662 final OutputStream output
) throws UnsupportedEncodingException
{
664 backend
= new ECMA48Backend(this, input
, output
);
669 * Public constructor. The backend type will be BackendType.ECMA48.
671 * @param input the InputStream underlying 'reader'. Its available()
672 * method is used to determine if reader.read() will block or not.
673 * @param reader a Reader connected to the remote user.
674 * @param writer a PrintWriter connected to the remote user.
675 * @param setRawMode if true, set System.in into raw mode with stty.
676 * This should in general not be used. It is here solely for Demo3,
677 * which uses System.in.
678 * @throws IllegalArgumentException if input, reader, or writer are null.
680 public TApplication(final InputStream input
, final Reader reader
,
681 final PrintWriter writer
, final boolean setRawMode
) {
683 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
688 * Public constructor. The backend type will be BackendType.ECMA48.
690 * @param input the InputStream underlying 'reader'. Its available()
691 * method is used to determine if reader.read() will block or not.
692 * @param reader a Reader connected to the remote user.
693 * @param writer a PrintWriter connected to the remote user.
694 * @throws IllegalArgumentException if input, reader, or writer are null.
696 public TApplication(final InputStream input
, final Reader reader
,
697 final PrintWriter writer
) {
699 this(input
, reader
, writer
, false);
703 * Public constructor. This hook enables use with new non-Jexer
706 * @param backend a Backend that is already ready to go.
708 public TApplication(final Backend backend
) {
709 this.backend
= backend
;
710 backend
.setListener(this);
715 * Finish construction once the backend is set.
717 private void TApplicationImpl() {
718 // Text block mouse option
719 if (System
.getProperty("jexer.textMouse", "true").equals("false")) {
723 // Hide mouse when typing option
724 if (System
.getProperty("jexer.hideMouseWhenTyping",
725 "false").equals("true")) {
727 hideMouseWhenTyping
= true;
730 // Hide status bar option
731 if (System
.getProperty("jexer.hideStatusBar",
732 "false").equals("true")) {
733 hideStatusBar
= true;
736 // Hide menu bar option
737 if (System
.getProperty("jexer.hideMenuBar", "false").equals("true")) {
741 theme
= new ColorTheme();
742 desktopTop
= (hideMenuBar ?
0 : 1);
743 desktopBottom
= getScreen().getHeight() - 1 + (hideStatusBar ?
1 : 0);
744 fillEventQueue
= new LinkedList
<TInputEvent
>();
745 drainEventQueue
= new LinkedList
<TInputEvent
>();
746 windows
= new LinkedList
<TWindow
>();
747 menus
= new ArrayList
<TMenu
>();
748 subMenus
= new ArrayList
<TMenu
>();
749 timers
= new LinkedList
<TTimer
>();
750 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
751 menuItems
= new LinkedList
<TMenuItem
>();
752 desktop
= new TDesktop(this);
754 // Special case: the Swing backend needs to have a timer to drive its
756 if ((backend
instanceof SwingBackend
)
757 || (backend
instanceof MultiBackend
)
759 // Default to 500 millis, unless a SwingBackend has its own
762 if (backend
instanceof SwingBackend
) {
763 millis
= ((SwingBackend
) backend
).getBlinkMillis();
766 addTimer(millis
, true,
769 TApplication
.this.doRepaint();
778 // ------------------------------------------------------------------------
779 // Runnable ---------------------------------------------------------------
780 // ------------------------------------------------------------------------
783 * Run this application until it exits.
786 // System.err.println("*** TApplication.run() begins ***");
788 // Start the screen updater thread
789 screenHandler
= new ScreenHandler(this);
790 (new Thread(screenHandler
)).start();
792 // Start the main consumer thread
793 primaryEventHandler
= new WidgetEventHandler(this, true);
794 (new Thread(primaryEventHandler
)).start();
799 synchronized (this) {
800 boolean doWait
= false;
802 if (!backend
.hasEvents()) {
803 synchronized (fillEventQueue
) {
804 if (fillEventQueue
.size() == 0) {
811 // No I/O to dispatch, so wait until the backend
815 System
.err
.println(System
.currentTimeMillis() +
816 " " + Thread
.currentThread() + " MAIN sleep");
822 System
.err
.println(System
.currentTimeMillis() +
823 " " + Thread
.currentThread() + " MAIN AWAKE");
825 } catch (InterruptedException e
) {
826 // I'm awake and don't care why, let's see what's
827 // going on out there.
831 } // synchronized (this)
833 synchronized (fillEventQueue
) {
834 // Pull any pending I/O events
835 backend
.getEvents(fillEventQueue
);
837 // Dispatch each event to the appropriate handler, one at a
840 TInputEvent event
= null;
841 if (fillEventQueue
.size() == 0) {
844 event
= fillEventQueue
.remove(0);
845 metaHandleEvent(event
);
849 // Wake a consumer thread if we have any pending events.
850 if (drainEventQueue
.size() > 0) {
856 // Shutdown the event consumer threads
857 if (secondaryEventHandler
!= null) {
858 synchronized (secondaryEventHandler
) {
859 secondaryEventHandler
.notify();
862 if (primaryEventHandler
!= null) {
863 synchronized (primaryEventHandler
) {
864 primaryEventHandler
.notify();
868 // Close all the windows. This gives them an opportunity to release
872 // Close the desktop.
873 if (desktop
!= null) {
877 // Give the overarching application an opportunity to release
881 // System.err.println("*** TApplication.run() exits ***");
884 // ------------------------------------------------------------------------
885 // Event handlers ---------------------------------------------------------
886 // ------------------------------------------------------------------------
889 * Method that TApplication subclasses can override to handle menu or
890 * posted command events.
892 * @param command command event
893 * @return if true, this event was consumed
895 protected boolean onCommand(final TCommandEvent command
) {
896 // Default: handle cmExit
897 if (command
.equals(cmExit
)) {
898 if (messageBox(i18n
.getString("exitDialogTitle"),
899 i18n
.getString("exitDialogText"),
900 TMessageBox
.Type
.YESNO
).isYes()) {
907 if (command
.equals(cmShell
)) {
908 openTerminal(0, 0, TWindow
.RESIZABLE
);
912 if (command
.equals(cmTile
)) {
916 if (command
.equals(cmCascade
)) {
920 if (command
.equals(cmCloseAll
)) {
925 if (command
.equals(cmMenu
) && (hideMenuBar
== false)) {
926 if (!modalWindowActive() && (activeMenu
== null)) {
927 if (menus
.size() > 0) {
928 menus
.get(0).setActive(true);
929 activeMenu
= menus
.get(0);
939 * Method that TApplication subclasses can override to handle menu
942 * @param menu menu event
943 * @return if true, this event was consumed
945 protected boolean onMenu(final TMenuEvent menu
) {
947 // Default: handle MID_EXIT
948 if (menu
.getId() == TMenu
.MID_EXIT
) {
949 if (messageBox(i18n
.getString("exitDialogTitle"),
950 i18n
.getString("exitDialogText"),
951 TMessageBox
.Type
.YESNO
).isYes()) {
958 if (menu
.getId() == TMenu
.MID_SHELL
) {
959 openTerminal(0, 0, TWindow
.RESIZABLE
);
963 if (menu
.getId() == TMenu
.MID_TILE
) {
967 if (menu
.getId() == TMenu
.MID_CASCADE
) {
971 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
975 if (menu
.getId() == TMenu
.MID_ABOUT
) {
979 if (menu
.getId() == TMenu
.MID_REPAINT
) {
980 getScreen().clearPhysical();
984 if (menu
.getId() == TMenu
.MID_VIEW_IMAGE
) {
988 if (menu
.getId() == TMenu
.MID_SCREEN_OPTIONS
) {
989 new TFontChooserWindow(this);
996 * Method that TApplication subclasses can override to handle keystrokes.
998 * @param keypress keystroke event
999 * @return if true, this event was consumed
1001 protected boolean onKeypress(final TKeypressEvent keypress
) {
1002 // Default: only menu shortcuts
1004 // Process Alt-F, Alt-E, etc. menu shortcut keys
1005 if (!keypress
.getKey().isFnKey()
1006 && keypress
.getKey().isAlt()
1007 && !keypress
.getKey().isCtrl()
1008 && (activeMenu
== null)
1009 && !modalWindowActive()
1010 && (hideMenuBar
== false)
1013 assert (subMenus
.size() == 0);
1015 for (TMenu menu
: menus
) {
1016 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
1017 == Character
.toLowerCase(keypress
.getKey().getChar())
1020 menu
.setActive(true);
1030 * Process background events, and update the screen.
1032 private void finishEventProcessing() {
1034 System
.err
.printf(System
.currentTimeMillis() + " " +
1035 Thread
.currentThread() + " finishEventProcessing()\n");
1038 // Process timers and call doIdle()'s
1041 // Update the screen
1042 synchronized (getScreen()) {
1046 // Wake up the screen repainter
1047 wakeScreenHandler();
1050 System
.err
.printf(System
.currentTimeMillis() + " " +
1051 Thread
.currentThread() + " finishEventProcessing() END\n");
1056 * Peek at certain application-level events, add to eventQueue, and wake
1057 * up the consuming Thread.
1059 * @param event the input event to consume
1061 private void metaHandleEvent(final TInputEvent event
) {
1064 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1065 event
)); System
.err
.flush();
1069 // Do no more processing if the application is already trying
1074 // Special application-wide events -------------------------------
1077 if (event
instanceof TCommandEvent
) {
1078 TCommandEvent command
= (TCommandEvent
) event
;
1079 if (command
.equals(cmAbort
)) {
1085 synchronized (drainEventQueue
) {
1087 if (event
instanceof TResizeEvent
) {
1088 TResizeEvent resize
= (TResizeEvent
) event
;
1089 synchronized (getScreen()) {
1090 if ((System
.currentTimeMillis() - screenResizeTime
>= 15)
1091 || (resize
.getWidth() < getScreen().getWidth())
1092 || (resize
.getHeight() < getScreen().getHeight())
1094 getScreen().setDimensions(resize
.getWidth(),
1095 resize
.getHeight());
1096 screenResizeTime
= System
.currentTimeMillis();
1098 desktopBottom
= getScreen().getHeight() - 1;
1099 if (hideStatusBar
) {
1107 if (desktop
!= null) {
1108 desktop
.setDimensions(0, desktopTop
, resize
.getWidth(),
1109 (desktopBottom
- desktopTop
));
1110 desktop
.onResize(resize
);
1113 // Change menu edges if needed.
1116 // We are dirty, redraw the screen.
1120 System.err.println("New screen: " + resize.getWidth() +
1121 " x " + resize.getHeight());
1126 // Put into the main queue
1127 drainEventQueue
.add(event
);
1132 * Dispatch one event to the appropriate widget or application-level
1133 * event handler. This is the primary event handler, it has the normal
1134 * application-wide event handling.
1136 * @param event the input event to consume
1137 * @see #secondaryHandleEvent(TInputEvent event)
1139 private void primaryHandleEvent(final TInputEvent event
) {
1142 System
.err
.printf("%s primaryHandleEvent: %s\n",
1143 Thread
.currentThread(), event
);
1145 TMouseEvent doubleClick
= null;
1147 // Special application-wide events -----------------------------------
1149 if (event
instanceof TKeypressEvent
) {
1150 if (hideMouseWhenTyping
) {
1151 typingHidMouse
= true;
1155 // Peek at the mouse position
1156 if (event
instanceof TMouseEvent
) {
1157 typingHidMouse
= false;
1159 TMouseEvent mouse
= (TMouseEvent
) event
;
1160 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1163 mouseX
= mouse
.getX();
1164 mouseY
= mouse
.getY();
1166 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1167 && (!mouse
.isMouseWheelUp())
1168 && (!mouse
.isMouseWheelDown())
1170 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1173 // This is a double-click.
1174 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1176 mouse
.getX(), mouse
.getY(),
1177 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1178 mouse
.isMouse1(), mouse
.isMouse2(),
1180 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1183 // The first click of a potential double-click.
1184 lastMouseUpTime
= mouse
.getTime().getTime();
1189 // See if we need to switch focus to another window or the menu
1190 checkSwitchFocus((TMouseEvent
) event
);
1193 // Handle menu events
1194 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1195 TMenu menu
= activeMenu
;
1197 if (event
instanceof TMouseEvent
) {
1198 TMouseEvent mouse
= (TMouseEvent
) event
;
1200 while (subMenus
.size() > 0) {
1201 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1202 if (subMenu
.mouseWouldHit(mouse
)) {
1205 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1206 && (!mouse
.isMouse1())
1207 && (!mouse
.isMouse2())
1208 && (!mouse
.isMouse3())
1209 && (!mouse
.isMouseWheelUp())
1210 && (!mouse
.isMouseWheelDown())
1214 // We navigated away from a sub-menu, so close it
1218 // Convert the mouse relative x/y to menu coordinates
1219 assert (mouse
.getX() == mouse
.getAbsoluteX());
1220 assert (mouse
.getY() == mouse
.getAbsoluteY());
1221 if (subMenus
.size() > 0) {
1222 menu
= subMenus
.get(subMenus
.size() - 1);
1224 mouse
.setX(mouse
.getX() - menu
.getX());
1225 mouse
.setY(mouse
.getY() - menu
.getY());
1227 menu
.handleEvent(event
);
1231 if (event
instanceof TKeypressEvent
) {
1232 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1234 // See if this key matches an accelerator, and is not being
1235 // shortcutted by the active window, and if so dispatch the menu
1237 boolean windowWillShortcut
= false;
1238 if (activeWindow
!= null) {
1239 assert (activeWindow
.isShown());
1240 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1241 // We do not process this key, it will be passed to the
1243 windowWillShortcut
= true;
1247 if (!windowWillShortcut
&& !modalWindowActive()) {
1248 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1249 TMenuItem item
= null;
1250 synchronized (accelerators
) {
1251 item
= accelerators
.get(keypressLowercase
);
1254 if (item
.isEnabled()) {
1255 // Let the menu item dispatch
1261 // Handle the keypress
1262 if (onKeypress(keypress
)) {
1268 if (event
instanceof TCommandEvent
) {
1269 if (onCommand((TCommandEvent
) event
)) {
1274 if (event
instanceof TMenuEvent
) {
1275 if (onMenu((TMenuEvent
) event
)) {
1280 // Dispatch events to the active window -------------------------------
1281 boolean dispatchToDesktop
= true;
1282 TWindow window
= activeWindow
;
1283 if (window
!= null) {
1284 assert (window
.isActive());
1285 assert (window
.isShown());
1286 if (event
instanceof TMouseEvent
) {
1287 TMouseEvent mouse
= (TMouseEvent
) event
;
1288 // Convert the mouse relative x/y to window coordinates
1289 assert (mouse
.getX() == mouse
.getAbsoluteX());
1290 assert (mouse
.getY() == mouse
.getAbsoluteY());
1291 mouse
.setX(mouse
.getX() - window
.getX());
1292 mouse
.setY(mouse
.getY() - window
.getY());
1294 if (doubleClick
!= null) {
1295 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1296 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1299 if (window
.mouseWouldHit(mouse
)) {
1300 dispatchToDesktop
= false;
1302 } else if (event
instanceof TKeypressEvent
) {
1303 dispatchToDesktop
= false;
1304 } else if (event
instanceof TMenuEvent
) {
1305 dispatchToDesktop
= false;
1309 System
.err
.printf("TApplication dispatch event: %s\n",
1312 window
.handleEvent(event
);
1313 if (doubleClick
!= null) {
1314 window
.handleEvent(doubleClick
);
1317 if (dispatchToDesktop
) {
1318 // This event is fair game for the desktop to process.
1319 if (desktop
!= null) {
1320 desktop
.handleEvent(event
);
1321 if (doubleClick
!= null) {
1322 desktop
.handleEvent(doubleClick
);
1329 * Dispatch one event to the appropriate widget or application-level
1330 * event handler. This is the secondary event handler used by certain
1331 * special dialogs (currently TMessageBox and TFileOpenBox).
1333 * @param event the input event to consume
1334 * @see #primaryHandleEvent(TInputEvent event)
1336 private void secondaryHandleEvent(final TInputEvent event
) {
1337 TMouseEvent doubleClick
= null;
1340 System
.err
.printf("%s secondaryHandleEvent: %s\n",
1341 Thread
.currentThread(), event
);
1344 // Peek at the mouse position
1345 if (event
instanceof TMouseEvent
) {
1346 typingHidMouse
= false;
1348 TMouseEvent mouse
= (TMouseEvent
) event
;
1349 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1352 mouseX
= mouse
.getX();
1353 mouseY
= mouse
.getY();
1355 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1356 && (!mouse
.isMouseWheelUp())
1357 && (!mouse
.isMouseWheelDown())
1359 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1362 // This is a double-click.
1363 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1365 mouse
.getX(), mouse
.getY(),
1366 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1367 mouse
.isMouse1(), mouse
.isMouse2(),
1369 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1372 // The first click of a potential double-click.
1373 lastMouseUpTime
= mouse
.getTime().getTime();
1379 secondaryEventReceiver
.handleEvent(event
);
1380 // Note that it is possible for secondaryEventReceiver to be null
1381 // now, because its handleEvent() might have finished out on the
1382 // secondary thread. So put any extra processing inside a null
1384 if (secondaryEventReceiver
!= null) {
1385 if (doubleClick
!= null) {
1386 secondaryEventReceiver
.handleEvent(doubleClick
);
1392 * Enable a widget to override the primary event thread.
1394 * @param widget widget that will receive events
1396 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1398 System
.err
.println(System
.currentTimeMillis() +
1399 " enableSecondaryEventReceiver()");
1402 assert (secondaryEventReceiver
== null);
1403 assert (secondaryEventHandler
== null);
1404 assert ((widget
instanceof TMessageBox
)
1405 || (widget
instanceof TFileOpenBox
));
1406 secondaryEventReceiver
= widget
;
1407 secondaryEventHandler
= new WidgetEventHandler(this, false);
1409 (new Thread(secondaryEventHandler
)).start();
1413 * Yield to the secondary thread.
1415 public final void yield() {
1417 System
.err
.printf(System
.currentTimeMillis() + " " +
1418 Thread
.currentThread() + " yield()\n");
1421 assert (secondaryEventReceiver
!= null);
1423 while (secondaryEventReceiver
!= null) {
1424 synchronized (primaryEventHandler
) {
1426 primaryEventHandler
.wait();
1427 } catch (InterruptedException e
) {
1435 * Do stuff when there is no user input.
1437 private void doIdle() {
1439 System
.err
.printf(System
.currentTimeMillis() + " " +
1440 Thread
.currentThread() + " doIdle()\n");
1443 synchronized (timers
) {
1446 System
.err
.printf(System
.currentTimeMillis() + " " +
1447 Thread
.currentThread() + " doIdle() 2\n");
1450 // Run any timers that have timed out
1451 Date now
= new Date();
1452 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1453 for (TTimer timer
: timers
) {
1454 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1455 // Something might change, so repaint the screen.
1458 if (timer
.recurring
) {
1459 keepTimers
.add(timer
);
1462 keepTimers
.add(timer
);
1466 timers
.addAll(keepTimers
);
1470 for (TWindow window
: windows
) {
1473 if (desktop
!= null) {
1477 // Run any invokeLaters
1478 synchronized (invokeLaters
) {
1479 for (Runnable invoke
: invokeLaters
) {
1482 invokeLaters
.clear();
1488 * Wake the sleeping active event handler.
1490 private void wakeEventHandler() {
1495 if (secondaryEventHandler
!= null) {
1496 synchronized (secondaryEventHandler
) {
1497 secondaryEventHandler
.notify();
1500 assert (primaryEventHandler
!= null);
1501 synchronized (primaryEventHandler
) {
1502 primaryEventHandler
.notify();
1508 * Wake the sleeping screen handler.
1510 private void wakeScreenHandler() {
1515 synchronized (screenHandler
) {
1516 screenHandler
.notify();
1520 // ------------------------------------------------------------------------
1521 // TApplication -----------------------------------------------------------
1522 // ------------------------------------------------------------------------
1525 * Place a command on the run queue, and run it before the next round of
1528 * @param command the command to run later
1530 public void invokeLater(final Runnable command
) {
1531 synchronized (invokeLaters
) {
1532 invokeLaters
.add(command
);
1538 * Restore the console to sane defaults. This is meant to be used for
1539 * improper exits (e.g. a caught exception in main()), and should not be
1540 * necessary for normal program termination.
1542 public void restoreConsole() {
1543 if (backend
!= null) {
1544 if (backend
instanceof ECMA48Backend
) {
1553 * @return the Backend
1555 public final Backend
getBackend() {
1562 * @return the Screen
1564 public final Screen
getScreen() {
1565 if (backend
instanceof TWindowBackend
) {
1566 // We are being rendered to a TWindow. We can't use its
1567 // getScreen() method because that is how it is rendering to a
1568 // hardware backend somewhere. Instead use its getOtherScreen()
1570 return ((TWindowBackend
) backend
).getOtherScreen();
1572 return backend
.getScreen();
1577 * Get the color theme.
1581 public final ColorTheme
getTheme() {
1586 * Repaint the screen on the next update.
1588 public void doRepaint() {
1594 * Get Y coordinate of the top edge of the desktop.
1596 * @return Y coordinate of the top edge of the desktop
1598 public final int getDesktopTop() {
1603 * Get Y coordinate of the bottom edge of the desktop.
1605 * @return Y coordinate of the bottom edge of the desktop
1607 public final int getDesktopBottom() {
1608 return desktopBottom
;
1612 * Set the TDesktop instance.
1614 * @param desktop a TDesktop instance, or null to remove the one that is
1617 public final void setDesktop(final TDesktop desktop
) {
1618 if (this.desktop
!= null) {
1619 this.desktop
.onPreClose();
1620 this.desktop
.onUnfocus();
1621 this.desktop
.onClose();
1623 this.desktop
= desktop
;
1627 * Get the TDesktop instance.
1629 * @return the desktop, or null if it is not set
1631 public final TDesktop
getDesktop() {
1636 * Get the current active window.
1638 * @return the active window, or null if it is not set
1640 public final TWindow
getActiveWindow() {
1641 return activeWindow
;
1645 * Get a (shallow) copy of the window list.
1647 * @return a copy of the list of windows for this application
1649 public final List
<TWindow
> getAllWindows() {
1650 List
<TWindow
> result
= new ArrayList
<TWindow
>();
1651 result
.addAll(windows
);
1656 * Get focusFollowsMouse flag.
1658 * @return true if focus follows mouse: windows automatically raised if
1659 * the mouse passes over them
1661 public boolean getFocusFollowsMouse() {
1662 return focusFollowsMouse
;
1666 * Set focusFollowsMouse flag.
1668 * @param focusFollowsMouse if true, focus follows mouse: windows
1669 * automatically raised if the mouse passes over them
1671 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
1672 this.focusFollowsMouse
= focusFollowsMouse
;
1676 * Display the about dialog.
1678 protected void showAboutDialog() {
1679 String version
= getClass().getPackage().getImplementationVersion();
1680 if (version
== null) {
1681 // This is Java 9+, use a hardcoded string here.
1684 messageBox(i18n
.getString("aboutDialogTitle"),
1685 MessageFormat
.format(i18n
.getString("aboutDialogText"), version
),
1686 TMessageBox
.Type
.OK
);
1690 * Handle the Tool | Open image menu item.
1692 private void openImage() {
1694 List
<String
> filters
= new ArrayList
<String
>();
1695 filters
.add("^.*\\.[Jj][Pp][Gg]$");
1696 filters
.add("^.*\\.[Jj][Pp][Ee][Gg]$");
1697 filters
.add("^.*\\.[Pp][Nn][Gg]$");
1698 filters
.add("^.*\\.[Gg][Ii][Ff]$");
1699 filters
.add("^.*\\.[Bb][Mm][Pp]$");
1700 String filename
= fileOpenBox(".", TFileOpenBox
.Type
.OPEN
, filters
);
1701 if (filename
!= null) {
1702 new TImageWindow(this, new File(filename
));
1704 } catch (IOException e
) {
1705 // Show this exception to the user.
1706 new TExceptionDialog(this, e
);
1711 * Check if application is still running.
1713 * @return true if the application is running
1715 public final boolean isRunning() {
1722 // ------------------------------------------------------------------------
1723 // Screen refresh loop ----------------------------------------------------
1724 // ------------------------------------------------------------------------
1727 * Invert the cell color at a position. This is used to track the mouse.
1729 * @param x column position
1730 * @param y row position
1732 private void invertCell(final int x
, final int y
) {
1733 invertCell(x
, y
, false);
1737 * Invert the cell color at a position. This is used to track the mouse.
1739 * @param x column position
1740 * @param y row position
1741 * @param onlyThisCell if true, only invert this cell
1743 private void invertCell(final int x
, final int y
,
1744 final boolean onlyThisCell
) {
1747 System
.err
.printf("%d %s invertCell() %d %d\n",
1748 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1750 if (activeWindow
!= null) {
1751 System
.err
.println("activeWindow.hasHiddenMouse() " +
1752 activeWindow
.hasHiddenMouse());
1756 // If this cell is on top of a visible window that has requested a
1757 // hidden mouse, bail out.
1758 if ((activeWindow
!= null) && (activeMenu
== null)) {
1759 if ((activeWindow
.hasHiddenMouse() == true)
1760 && (x
> activeWindow
.getX())
1761 && (x
< activeWindow
.getX() + activeWindow
.getWidth() - 1)
1762 && (y
> activeWindow
.getY())
1763 && (y
< activeWindow
.getY() + activeWindow
.getHeight() - 1)
1769 // If this cell is on top of the desktop, and the desktop has
1770 // requested a hidden mouse, bail out.
1771 if ((desktop
!= null) && (activeWindow
== null) && (activeMenu
== null)) {
1772 if ((desktop
.hasHiddenMouse() == true)
1773 && (x
> desktop
.getX())
1774 && (x
< desktop
.getX() + desktop
.getWidth() - 1)
1775 && (y
> desktop
.getY())
1776 && (y
< desktop
.getY() + desktop
.getHeight() - 1)
1782 Cell cell
= getScreen().getCharXY(x
, y
);
1783 if (cell
.isImage()) {
1786 if (cell
.getForeColorRGB() < 0) {
1787 cell
.setForeColor(cell
.getForeColor().invert());
1789 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1791 if (cell
.getBackColorRGB() < 0) {
1792 cell
.setBackColor(cell
.getBackColor().invert());
1794 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1796 getScreen().putCharXY(x
, y
, cell
);
1797 if ((onlyThisCell
== true) || (cell
.getWidth() == Cell
.Width
.SINGLE
)) {
1801 // This cell is one half of a fullwidth glyph. Invert the other
1803 if (cell
.getWidth() == Cell
.Width
.LEFT
) {
1804 if (x
< getScreen().getWidth() - 1) {
1805 Cell rightHalf
= getScreen().getCharXY(x
+ 1, y
);
1806 if (rightHalf
.getWidth() == Cell
.Width
.RIGHT
) {
1807 invertCell(x
+ 1, y
, true);
1812 if (cell
.getWidth() == Cell
.Width
.RIGHT
) {
1814 Cell leftHalf
= getScreen().getCharXY(x
- 1, y
);
1815 if (leftHalf
.getWidth() == Cell
.Width
.LEFT
) {
1816 invertCell(x
- 1, y
, true);
1825 private void drawAll() {
1826 boolean menuIsActive
= false;
1829 System
.err
.printf("%d %s drawAll() enter\n",
1830 System
.currentTimeMillis(), Thread
.currentThread());
1833 // I don't think this does anything useful anymore...
1836 System
.err
.printf("%d %s drawAll() !repaint\n",
1837 System
.currentTimeMillis(), Thread
.currentThread());
1839 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1841 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1842 System
.currentTimeMillis(), Thread
.currentThread());
1845 // The only thing that has happened is the mouse moved.
1847 // Redraw the old cell at that position, and save the cell at
1848 // the new mouse position.
1850 System
.err
.printf("%d %s restoreImage() %d %d\n",
1851 System
.currentTimeMillis(), Thread
.currentThread(),
1852 oldDrawnMouseX
, oldDrawnMouseY
);
1854 oldDrawnMouseCell
.restoreImage();
1855 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1857 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1858 if (backend
instanceof ECMA48Backend
) {
1859 // Special case: the entire row containing the mouse has
1860 // to be re-drawn if it has any image data, AND any rows
1862 if (oldDrawnMouseY
!= mouseY
) {
1863 for (int i
= oldDrawnMouseY
; ;) {
1864 getScreen().unsetImageRow(i
);
1868 if (oldDrawnMouseY
< mouseY
) {
1875 getScreen().unsetImageRow(mouseY
);
1879 if ((textMouse
== true) && (typingHidMouse
== false)) {
1880 // Draw mouse at the new position.
1881 invertCell(mouseX
, mouseY
);
1884 oldDrawnMouseX
= mouseX
;
1885 oldDrawnMouseY
= mouseY
;
1887 if (getScreen().isDirty()) {
1888 screenHandler
.setDirty();
1894 System
.err
.printf("%d %s drawAll() REDRAW\n",
1895 System
.currentTimeMillis(), Thread
.currentThread());
1898 // If true, the cursor is not visible
1899 boolean cursor
= false;
1901 // Start with a clean screen
1902 getScreen().clear();
1905 if (desktop
!= null) {
1906 desktop
.drawChildren();
1909 // Draw each window in reverse Z order
1910 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1911 Collections
.sort(sorted
);
1912 TWindow topLevel
= null;
1913 if (sorted
.size() > 0) {
1914 topLevel
= sorted
.get(0);
1916 Collections
.reverse(sorted
);
1917 for (TWindow window
: sorted
) {
1918 if (window
.isShown()) {
1919 window
.drawChildren();
1923 if (hideMenuBar
== false) {
1925 // Draw the blank menubar line - reset the screen clipping first
1926 // so it won't trim it out.
1927 getScreen().resetClipping();
1928 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1929 theme
.getColor("tmenu"));
1930 // Now draw the menus.
1932 for (TMenu menu
: menus
) {
1933 CellAttributes menuColor
;
1934 CellAttributes menuMnemonicColor
;
1935 if (menu
.isActive()) {
1936 menuIsActive
= true;
1937 menuColor
= theme
.getColor("tmenu.highlighted");
1938 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1941 menuColor
= theme
.getColor("tmenu");
1942 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1944 // Draw the menu title
1945 getScreen().hLineXY(x
, 0,
1946 StringUtils
.width(menu
.getTitle()) + 2, ' ', menuColor
);
1947 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1948 // Draw the highlight character
1949 getScreen().putCharXY(x
+ 1 +
1950 menu
.getMnemonic().getScreenShortcutIdx(),
1951 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1953 if (menu
.isActive()) {
1954 ((TWindow
) menu
).drawChildren();
1955 // Reset the screen clipping so we can draw the next
1957 getScreen().resetClipping();
1959 x
+= StringUtils
.width(menu
.getTitle()) + 2;
1962 for (TMenu menu
: subMenus
) {
1963 // Reset the screen clipping so we can draw the next
1965 getScreen().resetClipping();
1966 ((TWindow
) menu
).drawChildren();
1969 getScreen().resetClipping();
1971 if (hideStatusBar
== false) {
1972 // Draw the status bar of the top-level window
1973 TStatusBar statusBar
= null;
1974 if (topLevel
!= null) {
1975 statusBar
= topLevel
.getStatusBar();
1977 if (statusBar
!= null) {
1978 getScreen().resetClipping();
1979 statusBar
.setWidth(getScreen().getWidth());
1980 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1983 CellAttributes barColor
= new CellAttributes();
1984 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1985 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(),
1990 // Draw the mouse pointer
1992 System
.err
.printf("%d %s restoreImage() %d %d\n",
1993 System
.currentTimeMillis(), Thread
.currentThread(),
1994 oldDrawnMouseX
, oldDrawnMouseY
);
1996 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1997 if (backend
instanceof ECMA48Backend
) {
1998 // Special case: the entire row containing the mouse has to be
1999 // re-drawn if it has any image data, AND any rows in between.
2000 if (oldDrawnMouseY
!= mouseY
) {
2001 for (int i
= oldDrawnMouseY
; ;) {
2002 getScreen().unsetImageRow(i
);
2006 if (oldDrawnMouseY
< mouseY
) {
2013 getScreen().unsetImageRow(mouseY
);
2016 if ((textMouse
== true) && (typingHidMouse
== false)) {
2017 invertCell(mouseX
, mouseY
);
2019 oldDrawnMouseX
= mouseX
;
2020 oldDrawnMouseY
= mouseY
;
2022 // Place the cursor if it is visible
2023 if (!menuIsActive
) {
2025 int visibleWindowCount
= 0;
2026 for (TWindow window
: sorted
) {
2027 if (window
.isShown()) {
2028 visibleWindowCount
++;
2031 if (visibleWindowCount
== 0) {
2032 // No windows are visible, only the desktop. Allow it to
2034 if (desktop
!= null) {
2035 sorted
.add(desktop
);
2039 TWidget activeWidget
= null;
2040 if (sorted
.size() > 0) {
2041 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
2042 int cursorClipTop
= desktopTop
;
2043 int cursorClipBottom
= desktopBottom
;
2044 if (activeWidget
.isCursorVisible()) {
2045 if ((activeWidget
.getCursorAbsoluteY() <= cursorClipBottom
)
2046 && (activeWidget
.getCursorAbsoluteY() >= cursorClipTop
)
2048 getScreen().putCursor(true,
2049 activeWidget
.getCursorAbsoluteX(),
2050 activeWidget
.getCursorAbsoluteY());
2053 // Turn off the cursor. Also place it at 0,0.
2054 getScreen().putCursor(false, 0, 0);
2063 getScreen().hideCursor();
2066 if (getScreen().isDirty()) {
2067 screenHandler
.setDirty();
2073 * Force this application to exit.
2075 public void exit() {
2077 synchronized (this) {
2083 * Subclasses can use this hook to cleanup resources. Called as the last
2084 * step of TApplication.run().
2086 public void onExit() {
2087 // Default does nothing.
2090 // ------------------------------------------------------------------------
2091 // TWindow management -----------------------------------------------------
2092 // ------------------------------------------------------------------------
2095 * Return the total number of windows.
2097 * @return the total number of windows
2099 public final int windowCount() {
2100 return windows
.size();
2104 * Return the number of windows that are showing.
2106 * @return the number of windows that are showing on screen
2108 public final int shownWindowCount() {
2110 for (TWindow w
: windows
) {
2119 * Return the number of windows that are hidden.
2121 * @return the number of windows that are hidden
2123 public final int hiddenWindowCount() {
2125 for (TWindow w
: windows
) {
2134 * Check if a window instance is in this application's window list.
2136 * @param window window to look for
2137 * @return true if this window is in the list
2139 public final boolean hasWindow(final TWindow window
) {
2140 if (windows
.size() == 0) {
2143 for (TWindow w
: windows
) {
2145 assert (window
.getApplication() == this);
2153 * Activate a window: bring it to the top and have it receive events.
2155 * @param window the window to become the new active window
2157 public void activateWindow(final TWindow window
) {
2158 if (hasWindow(window
) == false) {
2160 * Someone has a handle to a window I don't have. Ignore this
2166 // Whatever window might be moving/dragging, stop it now.
2167 for (TWindow w
: windows
) {
2168 if (w
.inMovements()) {
2173 assert (windows
.size() > 0);
2175 if (window
.isHidden()) {
2176 // Unhiding will also activate.
2180 assert (window
.isShown());
2182 if (windows
.size() == 1) {
2183 assert (window
== windows
.get(0));
2184 if (activeWindow
== null) {
2185 activeWindow
= window
;
2187 activeWindow
.setActive(true);
2188 activeWindow
.onFocus();
2191 assert (window
.isActive());
2192 assert (activeWindow
== window
);
2196 if (activeWindow
== window
) {
2197 assert (window
.isActive());
2199 // Window is already active, do nothing.
2203 assert (!window
.isActive());
2204 if (activeWindow
!= null) {
2205 // TODO: see if this assertion is really necessary.
2206 // assert (activeWindow.getZ() == 0);
2208 activeWindow
.setActive(false);
2210 // Increment every window Z that is on top of window
2211 for (TWindow w
: windows
) {
2215 if (w
.getZ() < window
.getZ()) {
2216 w
.setZ(w
.getZ() + 1);
2220 // Unset activeWindow now before unfocus, so that a window
2221 // lifecycle change inside onUnfocus() doesn't call
2222 // switchWindow() and lead to a stack overflow.
2223 TWindow oldActiveWindow
= activeWindow
;
2224 activeWindow
= null;
2225 oldActiveWindow
.onUnfocus();
2227 activeWindow
= window
;
2228 activeWindow
.setZ(0);
2229 activeWindow
.setActive(true);
2230 activeWindow
.onFocus();
2237 * @param window the window to hide
2239 public void hideWindow(final TWindow window
) {
2240 if (hasWindow(window
) == false) {
2242 * Someone has a handle to a window I don't have. Ignore this
2248 // Whatever window might be moving/dragging, stop it now.
2249 for (TWindow w
: windows
) {
2250 if (w
.inMovements()) {
2255 assert (windows
.size() > 0);
2257 if (!window
.hidden
) {
2258 if (window
== activeWindow
) {
2259 if (shownWindowCount() > 1) {
2262 activeWindow
= null;
2263 window
.setActive(false);
2267 window
.hidden
= true;
2275 * @param window the window to show
2277 public void showWindow(final TWindow window
) {
2278 if (hasWindow(window
) == false) {
2280 * Someone has a handle to a window I don't have. Ignore this
2286 // Whatever window might be moving/dragging, stop it now.
2287 for (TWindow w
: windows
) {
2288 if (w
.inMovements()) {
2293 assert (windows
.size() > 0);
2295 if (window
.hidden
) {
2296 window
.hidden
= false;
2298 activateWindow(window
);
2303 * Close window. Note that the window's destructor is NOT called by this
2304 * method, instead the GC is assumed to do the cleanup.
2306 * @param window the window to remove
2308 public final void closeWindow(final TWindow window
) {
2309 if (hasWindow(window
) == false) {
2311 * Someone has a handle to a window I don't have. Ignore this
2317 // Let window know that it is about to be closed, while it is still
2318 // visible on screen.
2319 window
.onPreClose();
2321 synchronized (windows
) {
2322 // Whatever window might be moving/dragging, stop it now.
2323 for (TWindow w
: windows
) {
2324 if (w
.inMovements()) {
2329 int z
= window
.getZ();
2332 windows
.remove(window
);
2333 Collections
.sort(windows
);
2334 activeWindow
= null;
2336 boolean foundNextWindow
= false;
2338 for (TWindow w
: windows
) {
2342 // Do not activate a hidden window.
2347 if (foundNextWindow
== false) {
2348 foundNextWindow
= true;
2351 assert (activeWindow
== null);
2363 // Perform window cleanup
2366 // Check if we are closing a TMessageBox or similar
2367 if (secondaryEventReceiver
!= null) {
2368 assert (secondaryEventHandler
!= null);
2370 // Do not send events to the secondaryEventReceiver anymore, the
2371 // window is closed.
2372 secondaryEventReceiver
= null;
2374 // Wake the secondary thread, it will wake the primary as it
2376 synchronized (secondaryEventHandler
) {
2377 secondaryEventHandler
.notify();
2381 // Permit desktop to be active if it is the only thing left.
2382 if (desktop
!= null) {
2383 if (windows
.size() == 0) {
2384 desktop
.setActive(true);
2390 * Switch to the next window.
2392 * @param forward if true, then switch to the next window in the list,
2393 * otherwise switch to the previous window in the list
2395 public final void switchWindow(final boolean forward
) {
2396 // Only switch if there are multiple visible windows
2397 if (shownWindowCount() < 2) {
2400 assert (activeWindow
!= null);
2402 synchronized (windows
) {
2403 // Whatever window might be moving/dragging, stop it now.
2404 for (TWindow w
: windows
) {
2405 if (w
.inMovements()) {
2410 // Swap z/active between active window and the next in the list
2411 int activeWindowI
= -1;
2412 for (int i
= 0; i
< windows
.size(); i
++) {
2413 if (windows
.get(i
) == activeWindow
) {
2414 assert (activeWindow
.isActive());
2418 assert (!windows
.get(0).isActive());
2421 assert (activeWindowI
>= 0);
2423 // Do not switch if a window is modal
2424 if (activeWindow
.isModal()) {
2428 int nextWindowI
= activeWindowI
;
2432 nextWindowI
%= windows
.size();
2435 if (nextWindowI
< 0) {
2436 nextWindowI
= windows
.size() - 1;
2440 if (windows
.get(nextWindowI
).isShown()) {
2441 activateWindow(windows
.get(nextWindowI
));
2445 } // synchronized (windows)
2450 * Add a window to my window list and make it active. Note package
2453 * @param window new window to add
2455 final void addWindowToApplication(final TWindow window
) {
2457 // Do not add menu windows to the window list.
2458 if (window
instanceof TMenu
) {
2462 // Do not add the desktop to the window list.
2463 if (window
instanceof TDesktop
) {
2467 synchronized (windows
) {
2468 if (windows
.contains(window
)) {
2469 throw new IllegalArgumentException("Window " + window
+
2470 " is already in window list");
2473 // Whatever window might be moving/dragging, stop it now.
2474 for (TWindow w
: windows
) {
2475 if (w
.inMovements()) {
2480 // Do not allow a modal window to spawn a non-modal window. If a
2481 // modal window is active, then this window will become modal
2483 if (modalWindowActive()) {
2484 window
.flags
|= TWindow
.MODAL
;
2485 window
.flags
|= TWindow
.CENTERED
;
2486 window
.hidden
= false;
2488 if (window
.isShown()) {
2489 for (TWindow w
: windows
) {
2494 w
.setZ(w
.getZ() + 1);
2497 windows
.add(window
);
2498 if (window
.isShown()) {
2499 activeWindow
= window
;
2500 activeWindow
.setZ(0);
2501 activeWindow
.setActive(true);
2502 activeWindow
.onFocus();
2505 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2506 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2507 && (smartWindowPlacement
== true)
2508 && (!(window
instanceof TDesktop
))
2511 doSmartPlacement(window
);
2515 // Desktop cannot be active over any other window.
2516 if (desktop
!= null) {
2517 desktop
.setActive(false);
2522 * Check if there is a system-modal window on top.
2524 * @return true if the active window is modal
2526 private boolean modalWindowActive() {
2527 if (windows
.size() == 0) {
2531 for (TWindow w
: windows
) {
2541 * Check if there is a window with overridden menu flag on top.
2543 * @return true if the active window is overriding the menu
2545 private boolean overrideMenuWindowActive() {
2546 if (activeWindow
!= null) {
2547 if (activeWindow
.hasOverriddenMenu()) {
2556 * Close all open windows.
2558 private void closeAllWindows() {
2559 // Don't do anything if we are in the menu
2560 if (activeMenu
!= null) {
2563 while (windows
.size() > 0) {
2564 closeWindow(windows
.get(0));
2569 * Re-layout the open windows as non-overlapping tiles. This produces
2570 * almost the same results as Turbo Pascal 7.0's IDE.
2572 private void tileWindows() {
2573 synchronized (windows
) {
2574 // Don't do anything if we are in the menu
2575 if (activeMenu
!= null) {
2578 int z
= windows
.size();
2584 a
= (int)(Math
.sqrt(z
));
2588 if (((a
* b
) + c
) == z
) {
2596 int newWidth
= (getScreen().getWidth() / a
);
2597 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2598 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2600 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2601 Collections
.sort(sorted
);
2602 Collections
.reverse(sorted
);
2603 for (int i
= 0; i
< sorted
.size(); i
++) {
2604 int logicalX
= i
/ b
;
2605 int logicalY
= i
% b
;
2606 if (i
>= ((a
- 1) * b
)) {
2608 logicalY
= i
- ((a
- 1) * b
);
2611 TWindow w
= sorted
.get(i
);
2612 int oldWidth
= w
.getWidth();
2613 int oldHeight
= w
.getHeight();
2615 w
.setX(logicalX
* newWidth
);
2616 w
.setWidth(newWidth
);
2617 if (i
>= ((a
- 1) * b
)) {
2618 w
.setY((logicalY
* newHeight2
) + 1);
2619 w
.setHeight(newHeight2
);
2621 w
.setY((logicalY
* newHeight1
) + 1);
2622 w
.setHeight(newHeight1
);
2624 if ((w
.getWidth() != oldWidth
)
2625 || (w
.getHeight() != oldHeight
)
2627 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2628 w
.getWidth(), w
.getHeight()));
2635 * Re-layout the open windows as overlapping cascaded windows.
2637 private void cascadeWindows() {
2638 synchronized (windows
) {
2639 // Don't do anything if we are in the menu
2640 if (activeMenu
!= null) {
2645 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2646 Collections
.sort(sorted
);
2647 Collections
.reverse(sorted
);
2648 for (TWindow window
: sorted
) {
2653 if (x
> getScreen().getWidth()) {
2656 if (y
>= getScreen().getHeight()) {
2664 * Place a window to minimize its overlap with other windows.
2666 * @param window the window to place
2668 public final void doSmartPlacement(final TWindow window
) {
2669 // This is a pretty dumb algorithm, but seems to work. The hardest
2670 // part is computing these "overlap" values seeking a minimum average
2673 int yMin
= desktopTop
;
2674 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2675 int yMax
= desktopBottom
- window
.getHeight() + 1;
2683 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2684 // No work to do, bail out.
2688 // Compute the overlap matrix without the new window.
2689 int width
= getScreen().getWidth();
2690 int height
= getScreen().getHeight();
2691 int overlapMatrix
[][] = new int[width
][height
];
2692 for (TWindow w
: windows
) {
2696 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2703 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2710 overlapMatrix
[x
][y
]++;
2715 long oldOverlapTotal
= 0;
2716 long oldOverlapN
= 0;
2717 for (int x
= 0; x
< width
; x
++) {
2718 for (int y
= 0; y
< height
; y
++) {
2719 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2720 if (overlapMatrix
[x
][y
] > 0) {
2727 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2728 boolean first
= true;
2729 int windowX
= window
.getX();
2730 int windowY
= window
.getY();
2732 // For each possible (x, y) position for the new window, compute a
2733 // new overlap matrix.
2734 for (int x
= xMin
; x
< xMax
; x
++) {
2735 for (int y
= yMin
; y
< yMax
; y
++) {
2737 // Start with the matrix minus this window.
2738 int newMatrix
[][] = new int[width
][height
];
2739 for (int mx
= 0; mx
< width
; mx
++) {
2740 for (int my
= 0; my
< height
; my
++) {
2741 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2745 // Add this window's values to the new overlap matrix.
2746 long newOverlapTotal
= 0;
2747 long newOverlapN
= 0;
2748 // Start by adding each new cell.
2749 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2753 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2757 newMatrix
[wx
][wy
]++;
2760 // Now figure out the new value for total coverage.
2761 for (int mx
= 0; mx
< width
; mx
++) {
2762 for (int my
= 0; my
< height
; my
++) {
2763 newOverlapTotal
+= newMatrix
[x
][y
];
2764 if (newMatrix
[mx
][my
] > 0) {
2769 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2772 // First time: just record what we got.
2773 oldOverlapAvg
= newOverlapAvg
;
2776 // All other times: pick a new best (x, y) and save the
2778 if (newOverlapAvg
< oldOverlapAvg
) {
2781 oldOverlapAvg
= newOverlapAvg
;
2785 } // for (int x = xMin; x < xMax; x++)
2787 } // for (int y = yMin; y < yMax; y++)
2789 // Finally, set the window's new coordinates.
2790 window
.setX(windowX
);
2791 window
.setY(windowY
);
2794 // ------------------------------------------------------------------------
2795 // TMenu management -------------------------------------------------------
2796 // ------------------------------------------------------------------------
2799 * Check if a mouse event would hit either the active menu or any open
2802 * @param mouse mouse event
2803 * @return true if the mouse would hit the active menu or an open
2806 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2807 assert (activeMenu
!= null);
2808 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2809 Collections
.reverse(menus
);
2810 for (TMenu menu
: menus
) {
2811 if (menu
.mouseWouldHit(mouse
)) {
2815 return activeMenu
.mouseWouldHit(mouse
);
2819 * See if we need to switch window or activate the menu based on
2822 * @param mouse mouse event
2824 private void checkSwitchFocus(final TMouseEvent mouse
) {
2826 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2827 && (activeMenu
!= null)
2828 && (mouse
.getAbsoluteY() != 0)
2829 && (!mouseOnMenu(mouse
))
2831 // They clicked outside the active menu, turn it off
2832 activeMenu
.setActive(false);
2834 for (TMenu menu
: subMenus
) {
2835 menu
.setActive(false);
2841 // See if they hit the menu bar
2842 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2843 && (mouse
.isMouse1())
2844 && (!modalWindowActive())
2845 && (!overrideMenuWindowActive())
2846 && (mouse
.getAbsoluteY() == 0)
2847 && (hideMenuBar
== false)
2850 for (TMenu menu
: subMenus
) {
2851 menu
.setActive(false);
2855 // They selected the menu, go activate it
2856 for (TMenu menu
: menus
) {
2857 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2858 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2859 + StringUtils
.width(menu
.getTitle()) + 2)
2861 menu
.setActive(true);
2864 menu
.setActive(false);
2870 // See if they hit the menu bar
2871 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2872 && (mouse
.isMouse1())
2873 && (activeMenu
!= null)
2874 && (mouse
.getAbsoluteY() == 0)
2875 && (hideMenuBar
== false)
2878 TMenu oldMenu
= activeMenu
;
2879 for (TMenu menu
: subMenus
) {
2880 menu
.setActive(false);
2884 // See if we should switch menus
2885 for (TMenu menu
: menus
) {
2886 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2887 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2888 + StringUtils
.width(menu
.getTitle()) + 2)
2890 menu
.setActive(true);
2894 if (oldMenu
!= activeMenu
) {
2895 // They switched menus
2896 oldMenu
.setActive(false);
2901 // If a menu is still active, don't switch windows
2902 if (activeMenu
!= null) {
2906 // Only switch if there are multiple windows
2907 if (windows
.size() < 2) {
2911 if (((focusFollowsMouse
== true)
2912 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2913 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2915 synchronized (windows
) {
2916 Collections
.sort(windows
);
2917 if (windows
.get(0).isModal()) {
2918 // Modal windows don't switch
2922 for (TWindow window
: windows
) {
2923 assert (!window
.isModal());
2925 if (window
.isHidden()) {
2926 assert (!window
.isActive());
2930 if (window
.mouseWouldHit(mouse
)) {
2931 if (window
== windows
.get(0)) {
2932 // Clicked on the same window, nothing to do
2933 assert (window
.isActive());
2937 // We will be switching to another window
2938 assert (windows
.get(0).isActive());
2939 assert (windows
.get(0) == activeWindow
);
2940 assert (!window
.isActive());
2941 if (activeWindow
!= null) {
2942 activeWindow
.onUnfocus();
2943 activeWindow
.setActive(false);
2944 activeWindow
.setZ(window
.getZ());
2946 activeWindow
= window
;
2948 window
.setActive(true);
2955 // Clicked on the background, nothing to do
2959 // Nothing to do: this isn't a mouse up, or focus isn't following
2965 * Turn off the menu.
2967 public final void closeMenu() {
2968 if (activeMenu
!= null) {
2969 activeMenu
.setActive(false);
2971 for (TMenu menu
: subMenus
) {
2972 menu
.setActive(false);
2979 * Get a (shallow) copy of the menu list.
2981 * @return a copy of the menu list
2983 public final List
<TMenu
> getAllMenus() {
2984 return new ArrayList
<TMenu
>(menus
);
2988 * Add a top-level menu to the list.
2990 * @param menu the menu to add
2991 * @throws IllegalArgumentException if the menu is already used in
2992 * another TApplication
2994 public final void addMenu(final TMenu menu
) {
2995 if ((menu
.getApplication() != null)
2996 && (menu
.getApplication() != this)
2998 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2999 "part of application " + menu
.getApplication());
3007 * Remove a top-level menu from the list.
3009 * @param menu the menu to remove
3010 * @throws IllegalArgumentException if the menu is already used in
3011 * another TApplication
3013 public final void removeMenu(final TMenu menu
) {
3014 if ((menu
.getApplication() != null)
3015 && (menu
.getApplication() != this)
3017 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
3018 "part of application " + menu
.getApplication());
3026 * Turn off a sub-menu.
3028 public final void closeSubMenu() {
3029 assert (activeMenu
!= null);
3030 TMenu item
= subMenus
.get(subMenus
.size() - 1);
3031 assert (item
!= null);
3032 item
.setActive(false);
3033 subMenus
.remove(subMenus
.size() - 1);
3037 * Switch to the next menu.
3039 * @param forward if true, then switch to the next menu in the list,
3040 * otherwise switch to the previous menu in the list
3042 public final void switchMenu(final boolean forward
) {
3043 assert (activeMenu
!= null);
3044 assert (hideMenuBar
== false);
3046 for (TMenu menu
: subMenus
) {
3047 menu
.setActive(false);
3051 for (int i
= 0; i
< menus
.size(); i
++) {
3052 if (activeMenu
== menus
.get(i
)) {
3054 if (i
< menus
.size() - 1) {
3063 i
= menus
.size() - 1;
3066 activeMenu
.setActive(false);
3067 activeMenu
= menus
.get(i
);
3068 activeMenu
.setActive(true);
3075 * Add a menu item to the global list. If it has a keyboard accelerator,
3076 * that will be added the global hash.
3078 * @param item the menu item
3080 public final void addMenuItem(final TMenuItem item
) {
3081 menuItems
.add(item
);
3083 TKeypress key
= item
.getKey();
3085 synchronized (accelerators
) {
3086 assert (accelerators
.get(key
) == null);
3087 accelerators
.put(key
.toLowerCase(), item
);
3093 * Disable one menu item.
3095 * @param id the menu item ID
3097 public final void disableMenuItem(final int id
) {
3098 for (TMenuItem item
: menuItems
) {
3099 if (item
.getId() == id
) {
3100 item
.setEnabled(false);
3106 * Disable the range of menu items with ID's between lower and upper,
3109 * @param lower the lowest menu item ID
3110 * @param upper the highest menu item ID
3112 public final void disableMenuItems(final int lower
, final int upper
) {
3113 for (TMenuItem item
: menuItems
) {
3114 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
3115 item
.setEnabled(false);
3116 item
.getParent().activate(0);
3122 * Enable one menu item.
3124 * @param id the menu item ID
3126 public final void enableMenuItem(final int id
) {
3127 for (TMenuItem item
: menuItems
) {
3128 if (item
.getId() == id
) {
3129 item
.setEnabled(true);
3130 item
.getParent().activate(0);
3136 * Enable the range of menu items with ID's between lower and upper,
3139 * @param lower the lowest menu item ID
3140 * @param upper the highest menu item ID
3142 public final void enableMenuItems(final int lower
, final int upper
) {
3143 for (TMenuItem item
: menuItems
) {
3144 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
3145 item
.setEnabled(true);
3146 item
.getParent().activate(0);
3152 * Get the menu item associated with this ID.
3154 * @param id the menu item ID
3155 * @return the menu item, or null if not found
3157 public final TMenuItem
getMenuItem(final int id
) {
3158 for (TMenuItem item
: menuItems
) {
3159 if (item
.getId() == id
) {
3167 * Recompute menu x positions based on their title length.
3169 public final void recomputeMenuX() {
3171 for (TMenu menu
: menus
) {
3174 x
+= StringUtils
.width(menu
.getTitle()) + 2;
3176 // Don't let the menu window exceed the screen width
3177 int rightEdge
= menu
.getX() + menu
.getWidth();
3178 if (rightEdge
> getScreen().getWidth()) {
3179 menu
.setX(getScreen().getWidth() - menu
.getWidth());
3185 * Post an event to process.
3187 * @param event new event to add to the queue
3189 public final void postEvent(final TInputEvent event
) {
3190 synchronized (this) {
3191 synchronized (fillEventQueue
) {
3192 fillEventQueue
.add(event
);
3195 System
.err
.println(System
.currentTimeMillis() + " " +
3196 Thread
.currentThread() + " postEvent() wake up main");
3203 * Post an event to process and turn off the menu.
3205 * @param event new event to add to the queue
3207 public final void postMenuEvent(final TInputEvent event
) {
3208 synchronized (this) {
3209 synchronized (fillEventQueue
) {
3210 fillEventQueue
.add(event
);
3213 System
.err
.println(System
.currentTimeMillis() + " " +
3214 Thread
.currentThread() + " postMenuEvent() wake up main");
3222 * Add a sub-menu to the list of open sub-menus.
3224 * @param menu sub-menu
3226 public final void addSubMenu(final TMenu menu
) {
3231 * Convenience function to add a top-level menu.
3233 * @param title menu title
3234 * @return the new menu
3236 public final TMenu
addMenu(final String title
) {
3239 TMenu menu
= new TMenu(this, x
, y
, title
);
3246 * Convenience function to add a default tools (hamburger) menu.
3248 * @return the new menu
3250 public final TMenu
addToolMenu() {
3251 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
3252 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
3253 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
3254 toolMenu
.addDefaultItem(TMenu
.MID_SCREEN_OPTIONS
);
3255 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
3256 getString("toolMenuStatus"));
3257 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3262 * Convenience function to add a default "File" menu.
3264 * @return the new menu
3266 public final TMenu
addFileMenu() {
3267 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
3268 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
3269 fileMenu
.addSeparator();
3270 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
3271 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
3272 getString("fileMenuStatus"));
3273 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3278 * Convenience function to add a default "Edit" menu.
3280 * @return the new menu
3282 public final TMenu
addEditMenu() {
3283 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
3284 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
3285 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
3286 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
3287 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
3288 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
3289 getString("editMenuStatus"));
3290 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3295 * Convenience function to add a default "Window" menu.
3297 * @return the new menu
3299 public final TMenu
addWindowMenu() {
3300 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
3301 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
3302 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
3303 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
3304 windowMenu
.addSeparator();
3305 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
3306 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
3307 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3308 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3309 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3310 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3311 getString("windowMenuStatus"));
3312 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3317 * Convenience function to add a default "Help" menu.
3319 * @return the new menu
3321 public final TMenu
addHelpMenu() {
3322 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3323 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3324 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3325 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3326 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3327 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3328 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3329 helpMenu
.addSeparator();
3330 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3331 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3332 getString("helpMenuStatus"));
3333 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3338 * Convenience function to add a default "Table" menu.
3340 * @return the new menu
3342 public final TMenu
addTableMenu() {
3343 TMenu tableMenu
= addMenu(i18n
.getString("tableMenuTitle"));
3344 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_COLUMN
, false);
3345 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_ROW
, false);
3346 tableMenu
.addSeparator();
3348 TSubMenu viewMenu
= tableMenu
.addSubMenu(i18n
.
3349 getString("tableSubMenuView"));
3350 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_ROW_LABELS
, false);
3351 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_COLUMN_LABELS
, false);
3352 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_ROW
, false);
3353 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_COLUMN
, false);
3355 TSubMenu borderMenu
= tableMenu
.addSubMenu(i18n
.
3356 getString("tableSubMenuBorders"));
3357 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_NONE
, false);
3358 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_ALL
, false);
3359 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_NONE
, false);
3360 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_ALL
, false);
3361 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_RIGHT
, false);
3362 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_LEFT
, false);
3363 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_TOP
, false);
3364 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_BOTTOM
, false);
3365 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_DOUBLE_BOTTOM
, false);
3366 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_THICK_BOTTOM
, false);
3367 TSubMenu deleteMenu
= tableMenu
.addSubMenu(i18n
.
3368 getString("tableSubMenuDelete"));
3369 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_LEFT
, false);
3370 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_UP
, false);
3371 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_ROW
, false);
3372 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_COLUMN
, false);
3373 TSubMenu insertMenu
= tableMenu
.addSubMenu(i18n
.
3374 getString("tableSubMenuInsert"));
3375 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_LEFT
, false);
3376 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_RIGHT
, false);
3377 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_ABOVE
, false);
3378 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_BELOW
, false);
3379 TSubMenu columnMenu
= tableMenu
.addSubMenu(i18n
.
3380 getString("tableSubMenuColumn"));
3381 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_NARROW
, false);
3382 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_WIDEN
, false);
3383 TSubMenu fileMenu
= tableMenu
.addSubMenu(i18n
.
3384 getString("tableSubMenuFile"));
3385 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_OPEN_CSV
, false);
3386 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_CSV
, false);
3387 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_TEXT
, false);
3389 TStatusBar statusBar
= tableMenu
.newStatusBar(i18n
.
3390 getString("tableMenuStatus"));
3391 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3395 // ------------------------------------------------------------------------
3396 // TTimer management ------------------------------------------------------
3397 // ------------------------------------------------------------------------
3400 * Get the amount of time I can sleep before missing a Timer tick.
3402 * @param timeout = initial (maximum) timeout in millis
3403 * @return number of milliseconds between now and the next timer event
3405 private long getSleepTime(final long timeout
) {
3406 Date now
= new Date();
3407 long nowTime
= now
.getTime();
3408 long sleepTime
= timeout
;
3410 synchronized (timers
) {
3411 for (TTimer timer
: timers
) {
3412 long nextTickTime
= timer
.getNextTick().getTime();
3413 if (nextTickTime
< nowTime
) {
3417 long timeDifference
= nextTickTime
- nowTime
;
3418 if (timeDifference
< sleepTime
) {
3419 sleepTime
= timeDifference
;
3424 assert (sleepTime
>= 0);
3425 assert (sleepTime
<= timeout
);
3430 * Convenience function to add a timer.
3432 * @param duration number of milliseconds to wait between ticks
3433 * @param recurring if true, re-schedule this timer after every tick
3434 * @param action function to call when button is pressed
3437 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3438 final TAction action
) {
3440 TTimer timer
= new TTimer(duration
, recurring
, action
);
3441 synchronized (timers
) {
3448 * Convenience function to remove a timer.
3450 * @param timer timer to remove
3452 public final void removeTimer(final TTimer timer
) {
3453 synchronized (timers
) {
3454 timers
.remove(timer
);
3458 // ------------------------------------------------------------------------
3459 // Other TWindow constructors ---------------------------------------------
3460 // ------------------------------------------------------------------------
3463 * Convenience function to spawn a message box.
3465 * @param title window title, will be centered along the top border
3466 * @param caption message to display. Use embedded newlines to get a
3468 * @return the new message box
3470 public final TMessageBox
messageBox(final String title
,
3471 final String caption
) {
3473 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3477 * Convenience function to spawn a message box.
3479 * @param title window title, will be centered along the top border
3480 * @param caption message to display. Use embedded newlines to get a
3482 * @param type one of the TMessageBox.Type constants. Default is
3484 * @return the new message box
3486 public final TMessageBox
messageBox(final String title
,
3487 final String caption
, final TMessageBox
.Type type
) {
3489 return new TMessageBox(this, title
, caption
, type
);
3493 * Convenience function to spawn an input box.
3495 * @param title window title, will be centered along the top border
3496 * @param caption message to display. Use embedded newlines to get a
3498 * @return the new input box
3500 public final TInputBox
inputBox(final String title
, final String caption
) {
3502 return new TInputBox(this, title
, caption
);
3506 * Convenience function to spawn an input box.
3508 * @param title window title, will be centered along the top border
3509 * @param caption message to display. Use embedded newlines to get a
3511 * @param text initial text to seed the field with
3512 * @return the new input box
3514 public final TInputBox
inputBox(final String title
, final String caption
,
3515 final String text
) {
3517 return new TInputBox(this, title
, caption
, text
);
3521 * Convenience function to spawn an input box.
3523 * @param title window title, will be centered along the top border
3524 * @param caption message to display. Use embedded newlines to get a
3526 * @param text initial text to seed the field with
3527 * @param type one of the Type constants. Default is Type.OK.
3528 * @return the new input box
3530 public final TInputBox
inputBox(final String title
, final String caption
,
3531 final String text
, final TInputBox
.Type type
) {
3533 return new TInputBox(this, title
, caption
, text
, type
);
3537 * Convenience function to open a terminal window.
3539 * @param x column relative to parent
3540 * @param y row relative to parent
3541 * @return the terminal new window
3543 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3544 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3548 * Convenience function to open a terminal window.
3550 * @param x column relative to parent
3551 * @param y row relative to parent
3552 * @param closeOnExit if true, close the window when the command exits
3553 * @return the terminal new window
3555 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3556 final boolean closeOnExit
) {
3558 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3562 * Convenience function to open a terminal window.
3564 * @param x column relative to parent
3565 * @param y row relative to parent
3566 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3567 * @return the terminal new window
3569 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3572 return new TTerminalWindow(this, x
, y
, flags
);
3576 * Convenience function to open a terminal window.
3578 * @param x column relative to parent
3579 * @param y row relative to parent
3580 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3581 * @param closeOnExit if true, close the window when the command exits
3582 * @return the terminal new window
3584 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3585 final int flags
, final boolean closeOnExit
) {
3587 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3591 * Convenience function to open a terminal window and execute a custom
3592 * command line inside it.
3594 * @param x column relative to parent
3595 * @param y row relative to parent
3596 * @param commandLine the command line to execute
3597 * @return the terminal new window
3599 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3600 final String commandLine
) {
3602 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3606 * Convenience function to open a terminal window and execute a custom
3607 * command line inside it.
3609 * @param x column relative to parent
3610 * @param y row relative to parent
3611 * @param commandLine the command line to execute
3612 * @param closeOnExit if true, close the window when the command exits
3613 * @return the terminal new window
3615 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3616 final String commandLine
, final boolean closeOnExit
) {
3618 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3622 * Convenience function to open a terminal window and execute a custom
3623 * command line inside it.
3625 * @param x column relative to parent
3626 * @param y row relative to parent
3627 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3628 * @param command the command line to execute
3629 * @return the terminal new window
3631 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3632 final int flags
, final String
[] command
) {
3634 return new TTerminalWindow(this, x
, y
, flags
, command
);
3638 * Convenience function to open a terminal window and execute a custom
3639 * command line inside it.
3641 * @param x column relative to parent
3642 * @param y row relative to parent
3643 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3644 * @param command the command line to execute
3645 * @param closeOnExit if true, close the window when the command exits
3646 * @return the terminal new window
3648 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3649 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3651 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3655 * Convenience function to open a terminal window and execute a custom
3656 * command line inside it.
3658 * @param x column relative to parent
3659 * @param y row relative to parent
3660 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3661 * @param commandLine the command line to execute
3662 * @return the terminal new window
3664 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3665 final int flags
, final String commandLine
) {
3667 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"));
3671 * Convenience function to open a terminal window and execute a custom
3672 * command line inside it.
3674 * @param x column relative to parent
3675 * @param y row relative to parent
3676 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3677 * @param commandLine the command line to execute
3678 * @param closeOnExit if true, close the window when the command exits
3679 * @return the terminal new window
3681 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3682 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3684 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"),
3689 * Convenience function to spawn an file open box.
3691 * @param path path of selected file
3692 * @return the result of the new file open box
3693 * @throws IOException if java.io operation throws
3695 public final String
fileOpenBox(final String path
) throws IOException
{
3697 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3698 return box
.getFilename();
3702 * Convenience function to spawn an file open box.
3704 * @param path path of selected file
3705 * @param type one of the Type constants
3706 * @return the result of the new file open box
3707 * @throws IOException if java.io operation throws
3709 public final String
fileOpenBox(final String path
,
3710 final TFileOpenBox
.Type type
) throws IOException
{
3712 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3713 return box
.getFilename();
3717 * Convenience function to spawn a file open box.
3719 * @param path path of selected file
3720 * @param type one of the Type constants
3721 * @param filter a string that files must match to be displayed
3722 * @return the result of the new file open box
3723 * @throws IOException of a java.io operation throws
3725 public final String
fileOpenBox(final String path
,
3726 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3728 ArrayList
<String
> filters
= new ArrayList
<String
>();
3729 filters
.add(filter
);
3731 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3732 return box
.getFilename();
3736 * Convenience function to spawn a file open box.
3738 * @param path path of selected file
3739 * @param type one of the Type constants
3740 * @param filters a list of strings that files must match to be displayed
3741 * @return the result of the new file open box
3742 * @throws IOException of a java.io operation throws
3744 public final String
fileOpenBox(final String path
,
3745 final TFileOpenBox
.Type type
,
3746 final List
<String
> filters
) throws IOException
{
3748 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3749 return box
.getFilename();
3753 * Convenience function to create a new window and make it active.
3754 * Window will be located at (0, 0).
3756 * @param title window title, will be centered along the top border
3757 * @param width width of window
3758 * @param height height of window
3759 * @return the new window
3761 public final TWindow
addWindow(final String title
, final int width
,
3764 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3769 * Convenience function to create a new window and make it active.
3770 * Window will be located at (0, 0).
3772 * @param title window title, will be centered along the top border
3773 * @param width width of window
3774 * @param height height of window
3775 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3776 * @return the new window
3778 public final TWindow
addWindow(final String title
,
3779 final int width
, final int height
, final int flags
) {
3781 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3786 * Convenience function to create a new window and make it active.
3788 * @param title window title, will be centered along the top border
3789 * @param x column relative to parent
3790 * @param y row relative to parent
3791 * @param width width of window
3792 * @param height height of window
3793 * @return the new window
3795 public final TWindow
addWindow(final String title
,
3796 final int x
, final int y
, final int width
, final int height
) {
3798 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3803 * Convenience function to create a new window and make it active.
3805 * @param title window title, will be centered along the top border
3806 * @param x column relative to parent
3807 * @param y row relative to parent
3808 * @param width width of window
3809 * @param height height of window
3810 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3811 * @return the new window
3813 public final TWindow
addWindow(final String title
,
3814 final int x
, final int y
, final int width
, final int height
,
3817 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);