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 static final 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 * The list of commands to run before the next I/O check.
311 private List
<Runnable
> invokeLaters
= new LinkedList
<Runnable
>();
314 * The last time the screen was resized.
316 private long screenResizeTime
= 0;
319 * WidgetEventHandler is the main event consumer loop. There are at most
320 * two such threads in existence: the primary for normal case and a
321 * secondary that is used for TMessageBox, TInputBox, and similar.
323 private class WidgetEventHandler
implements Runnable
{
325 * The main application.
327 private TApplication application
;
330 * Whether or not this WidgetEventHandler is the primary or secondary
333 private boolean primary
= true;
336 * Public constructor.
338 * @param application the main application
339 * @param primary if true, this is the primary event handler thread
341 public WidgetEventHandler(final TApplication application
,
342 final boolean primary
) {
344 this.application
= application
;
345 this.primary
= primary
;
352 // Wrap everything in a try, so that if we go belly up we can let
353 // the user have their terminal back.
356 } catch (Throwable t
) {
357 this.application
.restoreConsole();
359 this.application
.exit();
366 private void runImpl() {
367 boolean first
= true;
370 while (!application
.quit
) {
372 // Wait until application notifies me
373 while (!application
.quit
) {
375 synchronized (application
.drainEventQueue
) {
376 if (application
.drainEventQueue
.size() > 0) {
385 timeout
= application
.getSleepTime(1000);
389 // A timer needs to fire, break out.
394 System
.err
.printf("%d %s %s %s sleep %d millis\n",
395 System
.currentTimeMillis(), this,
396 primary ?
"primary" : "secondary",
397 Thread
.currentThread(), timeout
);
400 synchronized (this) {
405 System
.err
.printf("%d %s %s %s AWAKE\n",
406 System
.currentTimeMillis(), this,
407 primary ?
"primary" : "secondary",
408 Thread
.currentThread());
412 && (application
.secondaryEventReceiver
== null)
414 // Secondary thread, emergency exit. If we got
415 // here then something went wrong with the
416 // handoff between yield() and closeWindow().
417 synchronized (application
.primaryEventHandler
) {
418 application
.primaryEventHandler
.notify();
420 application
.secondaryEventHandler
= null;
421 throw new RuntimeException("secondary exited " +
425 } catch (InterruptedException e
) {
428 } // while (!application.quit)
430 // Pull all events off the queue
432 TInputEvent event
= null;
433 synchronized (application
.drainEventQueue
) {
434 if (application
.drainEventQueue
.size() == 0) {
437 event
= application
.drainEventQueue
.remove(0);
440 // We will have an event to process, so repaint the
441 // screen at the end.
442 application
.repaint
= true;
445 primaryHandleEvent(event
);
447 secondaryHandleEvent(event
);
450 && (application
.secondaryEventReceiver
== null)
452 // Secondary thread, time to exit.
454 // Eliminate my reference so that wakeEventHandler()
455 // resumes working on the primary.
456 application
.secondaryEventHandler
= null;
458 // We are ready to exit, wake up the primary thread.
459 // Remember that it is currently sleeping inside its
460 // primaryHandleEvent().
461 synchronized (application
.primaryEventHandler
) {
462 application
.primaryEventHandler
.notify();
471 // Fire timers, update screen.
473 application
.finishEventProcessing();
476 } // while (true) (main runnable loop)
481 * ScreenHandler pushes screen updates to the physical device.
483 private class ScreenHandler
implements Runnable
{
485 * The main application.
487 private TApplication application
;
492 private boolean dirty
= false;
495 * Public constructor.
497 * @param application the main application
499 public ScreenHandler(final TApplication application
) {
500 this.application
= application
;
504 * The screen update loop.
507 // Wrap everything in a try, so that if we go belly up we can let
508 // the user have their terminal back.
511 } catch (Throwable t
) {
512 this.application
.restoreConsole();
514 this.application
.exit();
521 private void runImpl() {
524 while (!application
.quit
) {
526 // Wait until application notifies me
527 while (!application
.quit
) {
529 synchronized (this) {
535 // Always check within 50 milliseconds.
538 } catch (InterruptedException e
) {
541 } // while (!application.quit)
543 // Flush the screen contents
545 System
.err
.printf("%d %s backend.flushScreen()\n",
546 System
.currentTimeMillis(), Thread
.currentThread());
548 synchronized (getScreen()) {
549 backend
.flushScreen();
551 } // while (true) (main runnable loop)
553 // Shutdown the user I/O thread(s)
558 * Set the dirty flag.
560 public void setDirty() {
561 synchronized (this) {
568 // ------------------------------------------------------------------------
569 // Constructors -----------------------------------------------------------
570 // ------------------------------------------------------------------------
573 * Public constructor.
575 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
577 * @param windowWidth the number of text columns to start with
578 * @param windowHeight the number of text rows to start with
579 * @param fontSize the size in points
580 * @throws UnsupportedEncodingException if an exception is thrown when
581 * creating the InputStreamReader
583 public TApplication(final BackendType backendType
, final int windowWidth
,
584 final int windowHeight
, final int fontSize
)
585 throws UnsupportedEncodingException
{
587 switch (backendType
) {
589 backend
= new SwingBackend(this, windowWidth
, windowHeight
,
595 backend
= new ECMA48Backend(this, null, null, windowWidth
,
596 windowHeight
, fontSize
);
599 throw new IllegalArgumentException("Invalid backend type: "
606 * Public constructor.
608 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
610 * @throws UnsupportedEncodingException if an exception is thrown when
611 * creating the InputStreamReader
613 public TApplication(final BackendType backendType
)
614 throws UnsupportedEncodingException
{
616 switch (backendType
) {
618 // The default SwingBackend is 80x25, 20 pt font. If you want to
619 // change that, you can pass the extra arguments to the
620 // SwingBackend constructor here. For example, if you wanted
621 // 90x30, 16 pt font:
623 // backend = new SwingBackend(this, 90, 30, 16);
624 backend
= new SwingBackend(this);
629 backend
= new ECMA48Backend(this, null, null);
632 throw new IllegalArgumentException("Invalid backend type: "
639 * Public constructor. The backend type will be BackendType.ECMA48.
641 * @param input an InputStream connected to the remote user, or null for
642 * System.in. If System.in is used, then on non-Windows systems it will
643 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
644 * mode. input is always converted to a Reader with UTF-8 encoding.
645 * @param output an OutputStream connected to the remote user, or null
646 * for System.out. output is always converted to a Writer with UTF-8
648 * @throws UnsupportedEncodingException if an exception is thrown when
649 * creating the InputStreamReader
651 public TApplication(final InputStream input
,
652 final OutputStream output
) throws UnsupportedEncodingException
{
654 backend
= new ECMA48Backend(this, input
, output
);
659 * Public constructor. The backend type will be BackendType.ECMA48.
661 * @param input the InputStream underlying 'reader'. Its available()
662 * method is used to determine if reader.read() will block or not.
663 * @param reader a Reader connected to the remote user.
664 * @param writer a PrintWriter connected to the remote user.
665 * @param setRawMode if true, set System.in into raw mode with stty.
666 * This should in general not be used. It is here solely for Demo3,
667 * which uses System.in.
668 * @throws IllegalArgumentException if input, reader, or writer are null.
670 public TApplication(final InputStream input
, final Reader reader
,
671 final PrintWriter writer
, final boolean setRawMode
) {
673 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
678 * Public constructor. The backend type will be BackendType.ECMA48.
680 * @param input the InputStream underlying 'reader'. Its available()
681 * method is used to determine if reader.read() will block or not.
682 * @param reader a Reader connected to the remote user.
683 * @param writer a PrintWriter connected to the remote user.
684 * @throws IllegalArgumentException if input, reader, or writer are null.
686 public TApplication(final InputStream input
, final Reader reader
,
687 final PrintWriter writer
) {
689 this(input
, reader
, writer
, false);
693 * Public constructor. This hook enables use with new non-Jexer
696 * @param backend a Backend that is already ready to go.
698 public TApplication(final Backend backend
) {
699 this.backend
= backend
;
700 backend
.setListener(this);
705 * Finish construction once the backend is set.
707 private void TApplicationImpl() {
708 theme
= new ColorTheme();
709 desktopBottom
= getScreen().getHeight() - 1;
710 fillEventQueue
= new LinkedList
<TInputEvent
>();
711 drainEventQueue
= new LinkedList
<TInputEvent
>();
712 windows
= new LinkedList
<TWindow
>();
713 menus
= new ArrayList
<TMenu
>();
714 subMenus
= new ArrayList
<TMenu
>();
715 timers
= new LinkedList
<TTimer
>();
716 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
717 menuItems
= new LinkedList
<TMenuItem
>();
718 desktop
= new TDesktop(this);
720 // Special case: the Swing backend needs to have a timer to drive its
722 if ((backend
instanceof SwingBackend
)
723 || (backend
instanceof MultiBackend
)
725 // Default to 500 millis, unless a SwingBackend has its own
728 if (backend
instanceof SwingBackend
) {
729 millis
= ((SwingBackend
) backend
).getBlinkMillis();
732 addTimer(millis
, true,
735 TApplication
.this.doRepaint();
742 // Text block mouse option
743 if (System
.getProperty("jexer.textMouse", "true").equals("false")) {
747 // Hide mouse when typing option
748 if (System
.getProperty("jexer.hideMouseWhenTyping",
749 "false").equals("true")) {
751 hideMouseWhenTyping
= true;
756 // ------------------------------------------------------------------------
757 // Runnable ---------------------------------------------------------------
758 // ------------------------------------------------------------------------
761 * Run this application until it exits.
764 // System.err.println("*** TApplication.run() begins ***");
766 // Start the screen updater thread
767 screenHandler
= new ScreenHandler(this);
768 (new Thread(screenHandler
)).start();
770 // Start the main consumer thread
771 primaryEventHandler
= new WidgetEventHandler(this, true);
772 (new Thread(primaryEventHandler
)).start();
777 synchronized (this) {
778 boolean doWait
= false;
780 if (!backend
.hasEvents()) {
781 synchronized (fillEventQueue
) {
782 if (fillEventQueue
.size() == 0) {
789 // No I/O to dispatch, so wait until the backend
793 System
.err
.println(System
.currentTimeMillis() +
794 " " + Thread
.currentThread() + " MAIN sleep");
800 System
.err
.println(System
.currentTimeMillis() +
801 " " + Thread
.currentThread() + " MAIN AWAKE");
803 } catch (InterruptedException e
) {
804 // I'm awake and don't care why, let's see what's
805 // going on out there.
809 } // synchronized (this)
811 synchronized (fillEventQueue
) {
812 // Pull any pending I/O events
813 backend
.getEvents(fillEventQueue
);
815 // Dispatch each event to the appropriate handler, one at a
818 TInputEvent event
= null;
819 if (fillEventQueue
.size() == 0) {
822 event
= fillEventQueue
.remove(0);
823 metaHandleEvent(event
);
827 // Wake a consumer thread if we have any pending events.
828 if (drainEventQueue
.size() > 0) {
834 // Shutdown the event consumer threads
835 if (secondaryEventHandler
!= null) {
836 synchronized (secondaryEventHandler
) {
837 secondaryEventHandler
.notify();
840 if (primaryEventHandler
!= null) {
841 synchronized (primaryEventHandler
) {
842 primaryEventHandler
.notify();
846 // Close all the windows. This gives them an opportunity to release
850 // Give the overarching application an opportunity to release
854 // System.err.println("*** TApplication.run() exits ***");
857 // ------------------------------------------------------------------------
858 // Event handlers ---------------------------------------------------------
859 // ------------------------------------------------------------------------
862 * Method that TApplication subclasses can override to handle menu or
863 * posted command events.
865 * @param command command event
866 * @return if true, this event was consumed
868 protected boolean onCommand(final TCommandEvent command
) {
869 // Default: handle cmExit
870 if (command
.equals(cmExit
)) {
871 if (messageBox(i18n
.getString("exitDialogTitle"),
872 i18n
.getString("exitDialogText"),
873 TMessageBox
.Type
.YESNO
).isYes()) {
880 if (command
.equals(cmShell
)) {
881 openTerminal(0, 0, TWindow
.RESIZABLE
);
885 if (command
.equals(cmTile
)) {
889 if (command
.equals(cmCascade
)) {
893 if (command
.equals(cmCloseAll
)) {
898 if (command
.equals(cmMenu
)) {
899 if (!modalWindowActive() && (activeMenu
== null)) {
900 if (menus
.size() > 0) {
901 menus
.get(0).setActive(true);
902 activeMenu
= menus
.get(0);
912 * Method that TApplication subclasses can override to handle menu
915 * @param menu menu event
916 * @return if true, this event was consumed
918 protected boolean onMenu(final TMenuEvent menu
) {
920 // Default: handle MID_EXIT
921 if (menu
.getId() == TMenu
.MID_EXIT
) {
922 if (messageBox(i18n
.getString("exitDialogTitle"),
923 i18n
.getString("exitDialogText"),
924 TMessageBox
.Type
.YESNO
).isYes()) {
931 if (menu
.getId() == TMenu
.MID_SHELL
) {
932 openTerminal(0, 0, TWindow
.RESIZABLE
);
936 if (menu
.getId() == TMenu
.MID_TILE
) {
940 if (menu
.getId() == TMenu
.MID_CASCADE
) {
944 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
948 if (menu
.getId() == TMenu
.MID_ABOUT
) {
952 if (menu
.getId() == TMenu
.MID_REPAINT
) {
953 getScreen().clearPhysical();
957 if (menu
.getId() == TMenu
.MID_VIEW_IMAGE
) {
961 if (menu
.getId() == TMenu
.MID_SCREEN_OPTIONS
) {
962 new TFontChooserWindow(this);
969 * Method that TApplication subclasses can override to handle keystrokes.
971 * @param keypress keystroke event
972 * @return if true, this event was consumed
974 protected boolean onKeypress(final TKeypressEvent keypress
) {
975 // Default: only menu shortcuts
977 // Process Alt-F, Alt-E, etc. menu shortcut keys
978 if (!keypress
.getKey().isFnKey()
979 && keypress
.getKey().isAlt()
980 && !keypress
.getKey().isCtrl()
981 && (activeMenu
== null)
982 && !modalWindowActive()
985 assert (subMenus
.size() == 0);
987 for (TMenu menu
: menus
) {
988 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
989 == Character
.toLowerCase(keypress
.getKey().getChar())
992 menu
.setActive(true);
1002 * Process background events, and update the screen.
1004 private void finishEventProcessing() {
1006 System
.err
.printf(System
.currentTimeMillis() + " " +
1007 Thread
.currentThread() + " finishEventProcessing()\n");
1010 // Process timers and call doIdle()'s
1013 // Update the screen
1014 synchronized (getScreen()) {
1018 // Wake up the screen repainter
1019 wakeScreenHandler();
1022 System
.err
.printf(System
.currentTimeMillis() + " " +
1023 Thread
.currentThread() + " finishEventProcessing() END\n");
1028 * Peek at certain application-level events, add to eventQueue, and wake
1029 * up the consuming Thread.
1031 * @param event the input event to consume
1033 private void metaHandleEvent(final TInputEvent event
) {
1036 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1037 event
)); System
.err
.flush();
1041 // Do no more processing if the application is already trying
1046 // Special application-wide events -------------------------------
1049 if (event
instanceof TCommandEvent
) {
1050 TCommandEvent command
= (TCommandEvent
) event
;
1051 if (command
.equals(cmAbort
)) {
1057 synchronized (drainEventQueue
) {
1059 if (event
instanceof TResizeEvent
) {
1060 TResizeEvent resize
= (TResizeEvent
) event
;
1061 synchronized (getScreen()) {
1062 if ((System
.currentTimeMillis() - screenResizeTime
>= 15)
1063 || (resize
.getWidth() < getScreen().getWidth())
1064 || (resize
.getHeight() < getScreen().getHeight())
1066 getScreen().setDimensions(resize
.getWidth(),
1067 resize
.getHeight());
1068 screenResizeTime
= System
.currentTimeMillis();
1070 desktopBottom
= getScreen().getHeight() - 1;
1076 if (desktop
!= null) {
1077 desktop
.setDimensions(0, 0, resize
.getWidth(),
1078 resize
.getHeight() - 1);
1079 desktop
.onResize(resize
);
1082 // Change menu edges if needed.
1085 // We are dirty, redraw the screen.
1089 System.err.println("New screen: " + resize.getWidth() +
1090 " x " + resize.getHeight());
1095 // Put into the main queue
1096 drainEventQueue
.add(event
);
1101 * Dispatch one event to the appropriate widget or application-level
1102 * event handler. This is the primary event handler, it has the normal
1103 * application-wide event handling.
1105 * @param event the input event to consume
1106 * @see #secondaryHandleEvent(TInputEvent event)
1108 private void primaryHandleEvent(final TInputEvent event
) {
1111 System
.err
.printf("%s primaryHandleEvent: %s\n",
1112 Thread
.currentThread(), event
);
1114 TMouseEvent doubleClick
= null;
1116 // Special application-wide events -----------------------------------
1118 if (event
instanceof TKeypressEvent
) {
1119 if (hideMouseWhenTyping
) {
1120 typingHidMouse
= true;
1124 // Peek at the mouse position
1125 if (event
instanceof TMouseEvent
) {
1126 typingHidMouse
= false;
1128 TMouseEvent mouse
= (TMouseEvent
) event
;
1129 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1132 mouseX
= mouse
.getX();
1133 mouseY
= mouse
.getY();
1135 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1136 && (!mouse
.isMouseWheelUp())
1137 && (!mouse
.isMouseWheelDown())
1139 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1142 // This is a double-click.
1143 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1145 mouse
.getX(), mouse
.getY(),
1146 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1147 mouse
.isMouse1(), mouse
.isMouse2(),
1149 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1152 // The first click of a potential double-click.
1153 lastMouseUpTime
= mouse
.getTime().getTime();
1158 // See if we need to switch focus to another window or the menu
1159 checkSwitchFocus((TMouseEvent
) event
);
1162 // Handle menu events
1163 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1164 TMenu menu
= activeMenu
;
1166 if (event
instanceof TMouseEvent
) {
1167 TMouseEvent mouse
= (TMouseEvent
) event
;
1169 while (subMenus
.size() > 0) {
1170 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1171 if (subMenu
.mouseWouldHit(mouse
)) {
1174 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1175 && (!mouse
.isMouse1())
1176 && (!mouse
.isMouse2())
1177 && (!mouse
.isMouse3())
1178 && (!mouse
.isMouseWheelUp())
1179 && (!mouse
.isMouseWheelDown())
1183 // We navigated away from a sub-menu, so close it
1187 // Convert the mouse relative x/y to menu coordinates
1188 assert (mouse
.getX() == mouse
.getAbsoluteX());
1189 assert (mouse
.getY() == mouse
.getAbsoluteY());
1190 if (subMenus
.size() > 0) {
1191 menu
= subMenus
.get(subMenus
.size() - 1);
1193 mouse
.setX(mouse
.getX() - menu
.getX());
1194 mouse
.setY(mouse
.getY() - menu
.getY());
1196 menu
.handleEvent(event
);
1200 if (event
instanceof TKeypressEvent
) {
1201 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1203 // See if this key matches an accelerator, and is not being
1204 // shortcutted by the active window, and if so dispatch the menu
1206 boolean windowWillShortcut
= false;
1207 if (activeWindow
!= null) {
1208 assert (activeWindow
.isShown());
1209 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1210 // We do not process this key, it will be passed to the
1212 windowWillShortcut
= true;
1216 if (!windowWillShortcut
&& !modalWindowActive()) {
1217 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1218 TMenuItem item
= null;
1219 synchronized (accelerators
) {
1220 item
= accelerators
.get(keypressLowercase
);
1223 if (item
.isEnabled()) {
1224 // Let the menu item dispatch
1230 // Handle the keypress
1231 if (onKeypress(keypress
)) {
1237 if (event
instanceof TCommandEvent
) {
1238 if (onCommand((TCommandEvent
) event
)) {
1243 if (event
instanceof TMenuEvent
) {
1244 if (onMenu((TMenuEvent
) event
)) {
1249 // Dispatch events to the active window -------------------------------
1250 boolean dispatchToDesktop
= true;
1251 TWindow window
= activeWindow
;
1252 if (window
!= null) {
1253 assert (window
.isActive());
1254 assert (window
.isShown());
1255 if (event
instanceof TMouseEvent
) {
1256 TMouseEvent mouse
= (TMouseEvent
) event
;
1257 // Convert the mouse relative x/y to window coordinates
1258 assert (mouse
.getX() == mouse
.getAbsoluteX());
1259 assert (mouse
.getY() == mouse
.getAbsoluteY());
1260 mouse
.setX(mouse
.getX() - window
.getX());
1261 mouse
.setY(mouse
.getY() - window
.getY());
1263 if (doubleClick
!= null) {
1264 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1265 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1268 if (window
.mouseWouldHit(mouse
)) {
1269 dispatchToDesktop
= false;
1271 } else if (event
instanceof TKeypressEvent
) {
1272 dispatchToDesktop
= false;
1276 System
.err
.printf("TApplication dispatch event: %s\n",
1279 window
.handleEvent(event
);
1280 if (doubleClick
!= null) {
1281 window
.handleEvent(doubleClick
);
1284 if (dispatchToDesktop
) {
1285 // This event is fair game for the desktop to process.
1286 if (desktop
!= null) {
1287 desktop
.handleEvent(event
);
1288 if (doubleClick
!= null) {
1289 desktop
.handleEvent(doubleClick
);
1296 * Dispatch one event to the appropriate widget or application-level
1297 * event handler. This is the secondary event handler used by certain
1298 * special dialogs (currently TMessageBox and TFileOpenBox).
1300 * @param event the input event to consume
1301 * @see #primaryHandleEvent(TInputEvent event)
1303 private void secondaryHandleEvent(final TInputEvent event
) {
1304 TMouseEvent doubleClick
= null;
1307 System
.err
.printf("%s secondaryHandleEvent: %s\n",
1308 Thread
.currentThread(), event
);
1311 // Peek at the mouse position
1312 if (event
instanceof TMouseEvent
) {
1313 typingHidMouse
= false;
1315 TMouseEvent mouse
= (TMouseEvent
) event
;
1316 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1319 mouseX
= mouse
.getX();
1320 mouseY
= mouse
.getY();
1322 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1323 && (!mouse
.isMouseWheelUp())
1324 && (!mouse
.isMouseWheelDown())
1326 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1329 // This is a double-click.
1330 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1332 mouse
.getX(), mouse
.getY(),
1333 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1334 mouse
.isMouse1(), mouse
.isMouse2(),
1336 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1339 // The first click of a potential double-click.
1340 lastMouseUpTime
= mouse
.getTime().getTime();
1346 secondaryEventReceiver
.handleEvent(event
);
1347 // Note that it is possible for secondaryEventReceiver to be null
1348 // now, because its handleEvent() might have finished out on the
1349 // secondary thread. So put any extra processing inside a null
1351 if (secondaryEventReceiver
!= null) {
1352 if (doubleClick
!= null) {
1353 secondaryEventReceiver
.handleEvent(doubleClick
);
1359 * Enable a widget to override the primary event thread.
1361 * @param widget widget that will receive events
1363 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1365 System
.err
.println(System
.currentTimeMillis() +
1366 " enableSecondaryEventReceiver()");
1369 assert (secondaryEventReceiver
== null);
1370 assert (secondaryEventHandler
== null);
1371 assert ((widget
instanceof TMessageBox
)
1372 || (widget
instanceof TFileOpenBox
));
1373 secondaryEventReceiver
= widget
;
1374 secondaryEventHandler
= new WidgetEventHandler(this, false);
1376 (new Thread(secondaryEventHandler
)).start();
1380 * Yield to the secondary thread.
1382 public final void yield() {
1384 System
.err
.printf(System
.currentTimeMillis() + " " +
1385 Thread
.currentThread() + " yield()\n");
1388 assert (secondaryEventReceiver
!= null);
1390 while (secondaryEventReceiver
!= null) {
1391 synchronized (primaryEventHandler
) {
1393 primaryEventHandler
.wait();
1394 } catch (InterruptedException e
) {
1402 * Do stuff when there is no user input.
1404 private void doIdle() {
1406 System
.err
.printf(System
.currentTimeMillis() + " " +
1407 Thread
.currentThread() + " doIdle()\n");
1410 synchronized (timers
) {
1413 System
.err
.printf(System
.currentTimeMillis() + " " +
1414 Thread
.currentThread() + " doIdle() 2\n");
1417 // Run any timers that have timed out
1418 Date now
= new Date();
1419 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1420 for (TTimer timer
: timers
) {
1421 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1422 // Something might change, so repaint the screen.
1425 if (timer
.recurring
) {
1426 keepTimers
.add(timer
);
1429 keepTimers
.add(timer
);
1433 timers
.addAll(keepTimers
);
1437 for (TWindow window
: windows
) {
1440 if (desktop
!= null) {
1444 // Run any invokeLaters
1445 synchronized (invokeLaters
) {
1446 for (Runnable invoke
: invokeLaters
) {
1449 invokeLaters
.clear();
1455 * Wake the sleeping active event handler.
1457 private void wakeEventHandler() {
1462 if (secondaryEventHandler
!= null) {
1463 synchronized (secondaryEventHandler
) {
1464 secondaryEventHandler
.notify();
1467 assert (primaryEventHandler
!= null);
1468 synchronized (primaryEventHandler
) {
1469 primaryEventHandler
.notify();
1475 * Wake the sleeping screen handler.
1477 private void wakeScreenHandler() {
1482 synchronized (screenHandler
) {
1483 screenHandler
.notify();
1487 // ------------------------------------------------------------------------
1488 // TApplication -----------------------------------------------------------
1489 // ------------------------------------------------------------------------
1492 * Place a command on the run queue, and run it before the next round of
1495 * @param command the command to run later
1497 public void invokeLater(final Runnable command
) {
1498 synchronized (invokeLaters
) {
1499 invokeLaters
.add(command
);
1505 * Restore the console to sane defaults. This is meant to be used for
1506 * improper exits (e.g. a caught exception in main()), and should not be
1507 * necessary for normal program termination.
1509 public void restoreConsole() {
1510 if (backend
!= null) {
1511 if (backend
instanceof ECMA48Backend
) {
1520 * @return the Backend
1522 public final Backend
getBackend() {
1529 * @return the Screen
1531 public final Screen
getScreen() {
1532 if (backend
instanceof TWindowBackend
) {
1533 // We are being rendered to a TWindow. We can't use its
1534 // getScreen() method because that is how it is rendering to a
1535 // hardware backend somewhere. Instead use its getOtherScreen()
1537 return ((TWindowBackend
) backend
).getOtherScreen();
1539 return backend
.getScreen();
1544 * Get the color theme.
1548 public final ColorTheme
getTheme() {
1553 * Repaint the screen on the next update.
1555 public void doRepaint() {
1561 * Get Y coordinate of the top edge of the desktop.
1563 * @return Y coordinate of the top edge of the desktop
1565 public final int getDesktopTop() {
1570 * Get Y coordinate of the bottom edge of the desktop.
1572 * @return Y coordinate of the bottom edge of the desktop
1574 public final int getDesktopBottom() {
1575 return desktopBottom
;
1579 * Set the TDesktop instance.
1581 * @param desktop a TDesktop instance, or null to remove the one that is
1584 public final void setDesktop(final TDesktop desktop
) {
1585 if (this.desktop
!= null) {
1586 this.desktop
.onClose();
1588 this.desktop
= desktop
;
1592 * Get the TDesktop instance.
1594 * @return the desktop, or null if it is not set
1596 public final TDesktop
getDesktop() {
1601 * Get the current active window.
1603 * @return the active window, or null if it is not set
1605 public final TWindow
getActiveWindow() {
1606 return activeWindow
;
1610 * Get a (shallow) copy of the window list.
1612 * @return a copy of the list of windows for this application
1614 public final List
<TWindow
> getAllWindows() {
1615 List
<TWindow
> result
= new ArrayList
<TWindow
>();
1616 result
.addAll(windows
);
1621 * Get focusFollowsMouse flag.
1623 * @return true if focus follows mouse: windows automatically raised if
1624 * the mouse passes over them
1626 public boolean getFocusFollowsMouse() {
1627 return focusFollowsMouse
;
1631 * Set focusFollowsMouse flag.
1633 * @param focusFollowsMouse if true, focus follows mouse: windows
1634 * automatically raised if the mouse passes over them
1636 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
1637 this.focusFollowsMouse
= focusFollowsMouse
;
1641 * Display the about dialog.
1643 protected void showAboutDialog() {
1644 String version
= getClass().getPackage().getImplementationVersion();
1645 if (version
== null) {
1646 // This is Java 9+, use a hardcoded string here.
1649 messageBox(i18n
.getString("aboutDialogTitle"),
1650 MessageFormat
.format(i18n
.getString("aboutDialogText"), version
),
1651 TMessageBox
.Type
.OK
);
1655 * Handle the Tool | Open image menu item.
1657 private void openImage() {
1659 List
<String
> filters
= new ArrayList
<String
>();
1660 filters
.add("^.*\\.[Jj][Pp][Gg]$");
1661 filters
.add("^.*\\.[Jj][Pp][Ee][Gg]$");
1662 filters
.add("^.*\\.[Pp][Nn][Gg]$");
1663 filters
.add("^.*\\.[Gg][Ii][Ff]$");
1664 filters
.add("^.*\\.[Bb][Mm][Pp]$");
1665 String filename
= fileOpenBox(".", TFileOpenBox
.Type
.OPEN
, filters
);
1666 if (filename
!= null) {
1667 new TImageWindow(this, new File(filename
));
1669 } catch (IOException e
) {
1670 // Show this exception to the user.
1671 new TExceptionDialog(this, e
);
1676 * Check if application is still running.
1678 * @return true if the application is running
1680 public final boolean isRunning() {
1687 // ------------------------------------------------------------------------
1688 // Screen refresh loop ----------------------------------------------------
1689 // ------------------------------------------------------------------------
1692 * Invert the cell color at a position. This is used to track the mouse.
1694 * @param x column position
1695 * @param y row position
1697 private void invertCell(final int x
, final int y
) {
1698 invertCell(x
, y
, false);
1702 * Invert the cell color at a position. This is used to track the mouse.
1704 * @param x column position
1705 * @param y row position
1706 * @param onlyThisCell if true, only invert this cell
1708 private void invertCell(final int x
, final int y
,
1709 final boolean onlyThisCell
) {
1712 System
.err
.printf("%d %s invertCell() %d %d\n",
1713 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1715 if (activeWindow
!= null) {
1716 System
.err
.println("activeWindow.hasHiddenMouse() " +
1717 activeWindow
.hasHiddenMouse());
1721 // If this cell is on top of a visible window that has requested a
1722 // hidden mouse, bail out.
1723 if ((activeWindow
!= null) && (activeMenu
== null)) {
1724 if ((activeWindow
.hasHiddenMouse() == true)
1725 && (x
> activeWindow
.getX())
1726 && (x
< activeWindow
.getX() + activeWindow
.getWidth() - 1)
1727 && (y
> activeWindow
.getY())
1728 && (y
< activeWindow
.getY() + activeWindow
.getHeight() - 1)
1734 Cell cell
= getScreen().getCharXY(x
, y
);
1735 if (cell
.isImage()) {
1738 if (cell
.getForeColorRGB() < 0) {
1739 cell
.setForeColor(cell
.getForeColor().invert());
1741 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1743 if (cell
.getBackColorRGB() < 0) {
1744 cell
.setBackColor(cell
.getBackColor().invert());
1746 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1748 getScreen().putCharXY(x
, y
, cell
);
1749 if ((onlyThisCell
== true) || (cell
.getWidth() == Cell
.Width
.SINGLE
)) {
1753 // This cell is one half of a fullwidth glyph. Invert the other
1755 if (cell
.getWidth() == Cell
.Width
.LEFT
) {
1756 if (x
< getScreen().getWidth() - 1) {
1757 Cell rightHalf
= getScreen().getCharXY(x
+ 1, y
);
1758 if (rightHalf
.getWidth() == Cell
.Width
.RIGHT
) {
1759 invertCell(x
+ 1, y
, true);
1764 if (cell
.getWidth() == Cell
.Width
.RIGHT
) {
1766 Cell leftHalf
= getScreen().getCharXY(x
- 1, y
);
1767 if (leftHalf
.getWidth() == Cell
.Width
.LEFT
) {
1768 invertCell(x
- 1, y
, true);
1777 private void drawAll() {
1778 boolean menuIsActive
= false;
1781 System
.err
.printf("%d %s drawAll() enter\n",
1782 System
.currentTimeMillis(), Thread
.currentThread());
1785 // I don't think this does anything useful anymore...
1788 System
.err
.printf("%d %s drawAll() !repaint\n",
1789 System
.currentTimeMillis(), Thread
.currentThread());
1791 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1793 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1794 System
.currentTimeMillis(), Thread
.currentThread());
1797 // The only thing that has happened is the mouse moved.
1799 // Redraw the old cell at that position, and save the cell at
1800 // the new mouse position.
1802 System
.err
.printf("%d %s restoreImage() %d %d\n",
1803 System
.currentTimeMillis(), Thread
.currentThread(),
1804 oldDrawnMouseX
, oldDrawnMouseY
);
1806 oldDrawnMouseCell
.restoreImage();
1807 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1809 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1810 if (backend
instanceof ECMA48Backend
) {
1811 // Special case: the entire row containing the mouse has
1812 // to be re-drawn if it has any image data, AND any rows
1814 if (oldDrawnMouseY
!= mouseY
) {
1815 for (int i
= oldDrawnMouseY
; ;) {
1816 getScreen().unsetImageRow(i
);
1820 if (oldDrawnMouseY
< mouseY
) {
1827 getScreen().unsetImageRow(mouseY
);
1831 if ((textMouse
== true) && (typingHidMouse
== false)) {
1832 // Draw mouse at the new position.
1833 invertCell(mouseX
, mouseY
);
1836 oldDrawnMouseX
= mouseX
;
1837 oldDrawnMouseY
= mouseY
;
1839 if (getScreen().isDirty()) {
1840 screenHandler
.setDirty();
1846 System
.err
.printf("%d %s drawAll() REDRAW\n",
1847 System
.currentTimeMillis(), Thread
.currentThread());
1850 // If true, the cursor is not visible
1851 boolean cursor
= false;
1853 // Start with a clean screen
1854 getScreen().clear();
1857 if (desktop
!= null) {
1858 desktop
.drawChildren();
1861 // Draw each window in reverse Z order
1862 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1863 Collections
.sort(sorted
);
1864 TWindow topLevel
= null;
1865 if (sorted
.size() > 0) {
1866 topLevel
= sorted
.get(0);
1868 Collections
.reverse(sorted
);
1869 for (TWindow window
: sorted
) {
1870 if (window
.isShown()) {
1871 window
.drawChildren();
1875 // Draw the blank menubar line - reset the screen clipping first so
1876 // it won't trim it out.
1877 getScreen().resetClipping();
1878 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1879 theme
.getColor("tmenu"));
1880 // Now draw the menus.
1882 for (TMenu menu
: menus
) {
1883 CellAttributes menuColor
;
1884 CellAttributes menuMnemonicColor
;
1885 if (menu
.isActive()) {
1886 menuIsActive
= true;
1887 menuColor
= theme
.getColor("tmenu.highlighted");
1888 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1891 menuColor
= theme
.getColor("tmenu");
1892 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1894 // Draw the menu title
1895 getScreen().hLineXY(x
, 0, StringUtils
.width(menu
.getTitle()) + 2, ' ',
1897 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1898 // Draw the highlight character
1899 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getScreenShortcutIdx(),
1900 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1902 if (menu
.isActive()) {
1903 ((TWindow
) menu
).drawChildren();
1904 // Reset the screen clipping so we can draw the next title.
1905 getScreen().resetClipping();
1907 x
+= StringUtils
.width(menu
.getTitle()) + 2;
1910 for (TMenu menu
: subMenus
) {
1911 // Reset the screen clipping so we can draw the next sub-menu.
1912 getScreen().resetClipping();
1913 ((TWindow
) menu
).drawChildren();
1915 getScreen().resetClipping();
1917 // Draw the status bar of the top-level window
1918 TStatusBar statusBar
= null;
1919 if (topLevel
!= null) {
1920 statusBar
= topLevel
.getStatusBar();
1922 if (statusBar
!= null) {
1923 getScreen().resetClipping();
1924 statusBar
.setWidth(getScreen().getWidth());
1925 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1928 CellAttributes barColor
= new CellAttributes();
1929 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1930 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
1934 // Draw the mouse pointer
1936 System
.err
.printf("%d %s restoreImage() %d %d\n",
1937 System
.currentTimeMillis(), Thread
.currentThread(),
1938 oldDrawnMouseX
, oldDrawnMouseY
);
1940 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1941 if (backend
instanceof ECMA48Backend
) {
1942 // Special case: the entire row containing the mouse has to be
1943 // re-drawn if it has any image data, AND any rows in between.
1944 if (oldDrawnMouseY
!= mouseY
) {
1945 for (int i
= oldDrawnMouseY
; ;) {
1946 getScreen().unsetImageRow(i
);
1950 if (oldDrawnMouseY
< mouseY
) {
1957 getScreen().unsetImageRow(mouseY
);
1960 if ((textMouse
== true) && (typingHidMouse
== false)) {
1961 invertCell(mouseX
, mouseY
);
1963 oldDrawnMouseX
= mouseX
;
1964 oldDrawnMouseY
= mouseY
;
1966 // Place the cursor if it is visible
1967 if (!menuIsActive
) {
1968 TWidget activeWidget
= null;
1969 if (sorted
.size() > 0) {
1970 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
1971 if (activeWidget
.isCursorVisible()) {
1972 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
1973 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
1975 getScreen().putCursor(true,
1976 activeWidget
.getCursorAbsoluteX(),
1977 activeWidget
.getCursorAbsoluteY());
1980 // Turn off the cursor. Also place it at 0,0.
1981 getScreen().putCursor(false, 0, 0);
1990 getScreen().hideCursor();
1993 if (getScreen().isDirty()) {
1994 screenHandler
.setDirty();
2000 * Force this application to exit.
2002 public void exit() {
2004 synchronized (this) {
2010 * Subclasses can use this hook to cleanup resources. Called as the last
2011 * step of TApplication.run().
2013 public void onExit() {
2014 // Default does nothing.
2017 // ------------------------------------------------------------------------
2018 // TWindow management -----------------------------------------------------
2019 // ------------------------------------------------------------------------
2022 * Return the total number of windows.
2024 * @return the total number of windows
2026 public final int windowCount() {
2027 return windows
.size();
2031 * Return the number of windows that are showing.
2033 * @return the number of windows that are showing on screen
2035 public final int shownWindowCount() {
2037 for (TWindow w
: windows
) {
2046 * Return the number of windows that are hidden.
2048 * @return the number of windows that are hidden
2050 public final int hiddenWindowCount() {
2052 for (TWindow w
: windows
) {
2061 * Check if a window instance is in this application's window list.
2063 * @param window window to look for
2064 * @return true if this window is in the list
2066 public final boolean hasWindow(final TWindow window
) {
2067 if (windows
.size() == 0) {
2070 for (TWindow w
: windows
) {
2072 assert (window
.getApplication() == this);
2080 * Activate a window: bring it to the top and have it receive events.
2082 * @param window the window to become the new active window
2084 public void activateWindow(final TWindow window
) {
2085 if (hasWindow(window
) == false) {
2087 * Someone has a handle to a window I don't have. Ignore this
2093 // Whatever window might be moving/dragging, stop it now.
2094 for (TWindow w
: windows
) {
2095 if (w
.inMovements()) {
2100 assert (windows
.size() > 0);
2102 if (window
.isHidden()) {
2103 // Unhiding will also activate.
2107 assert (window
.isShown());
2109 if (windows
.size() == 1) {
2110 assert (window
== windows
.get(0));
2111 if (activeWindow
== null) {
2112 activeWindow
= window
;
2114 activeWindow
.setActive(true);
2115 activeWindow
.onFocus();
2118 assert (window
.isActive());
2119 assert (activeWindow
== window
);
2123 if (activeWindow
== window
) {
2124 assert (window
.isActive());
2126 // Window is already active, do nothing.
2130 assert (!window
.isActive());
2131 if (activeWindow
!= null) {
2132 // TODO: see if this assertion is really necessary.
2133 // assert (activeWindow.getZ() == 0);
2135 activeWindow
.setActive(false);
2137 // Increment every window Z that is on top of window
2138 for (TWindow w
: windows
) {
2142 if (w
.getZ() < window
.getZ()) {
2143 w
.setZ(w
.getZ() + 1);
2147 // Unset activeWindow now before unfocus, so that a window
2148 // lifecycle change inside onUnfocus() doesn't call
2149 // switchWindow() and lead to a stack overflow.
2150 TWindow oldActiveWindow
= activeWindow
;
2151 activeWindow
= null;
2152 oldActiveWindow
.onUnfocus();
2154 activeWindow
= window
;
2155 activeWindow
.setZ(0);
2156 activeWindow
.setActive(true);
2157 activeWindow
.onFocus();
2164 * @param window the window to hide
2166 public void hideWindow(final TWindow window
) {
2167 if (hasWindow(window
) == false) {
2169 * Someone has a handle to a window I don't have. Ignore this
2175 // Whatever window might be moving/dragging, stop it now.
2176 for (TWindow w
: windows
) {
2177 if (w
.inMovements()) {
2182 assert (windows
.size() > 0);
2184 if (!window
.hidden
) {
2185 if (window
== activeWindow
) {
2186 if (shownWindowCount() > 1) {
2189 activeWindow
= null;
2190 window
.setActive(false);
2194 window
.hidden
= true;
2202 * @param window the window to show
2204 public void showWindow(final TWindow window
) {
2205 if (hasWindow(window
) == false) {
2207 * Someone has a handle to a window I don't have. Ignore this
2213 // Whatever window might be moving/dragging, stop it now.
2214 for (TWindow w
: windows
) {
2215 if (w
.inMovements()) {
2220 assert (windows
.size() > 0);
2222 if (window
.hidden
) {
2223 window
.hidden
= false;
2225 activateWindow(window
);
2230 * Close window. Note that the window's destructor is NOT called by this
2231 * method, instead the GC is assumed to do the cleanup.
2233 * @param window the window to remove
2235 public final void closeWindow(final TWindow window
) {
2236 if (hasWindow(window
) == false) {
2238 * Someone has a handle to a window I don't have. Ignore this
2244 // Let window know that it is about to be closed, while it is still
2245 // visible on screen.
2246 window
.onPreClose();
2248 synchronized (windows
) {
2249 // Whatever window might be moving/dragging, stop it now.
2250 for (TWindow w
: windows
) {
2251 if (w
.inMovements()) {
2256 int z
= window
.getZ();
2259 windows
.remove(window
);
2260 Collections
.sort(windows
);
2261 activeWindow
= null;
2263 boolean foundNextWindow
= false;
2265 for (TWindow w
: windows
) {
2269 // Do not activate a hidden window.
2274 if (foundNextWindow
== false) {
2275 foundNextWindow
= true;
2278 assert (activeWindow
== null);
2290 // Perform window cleanup
2293 // Check if we are closing a TMessageBox or similar
2294 if (secondaryEventReceiver
!= null) {
2295 assert (secondaryEventHandler
!= null);
2297 // Do not send events to the secondaryEventReceiver anymore, the
2298 // window is closed.
2299 secondaryEventReceiver
= null;
2301 // Wake the secondary thread, it will wake the primary as it
2303 synchronized (secondaryEventHandler
) {
2304 secondaryEventHandler
.notify();
2308 // Permit desktop to be active if it is the only thing left.
2309 if (desktop
!= null) {
2310 if (windows
.size() == 0) {
2311 desktop
.setActive(true);
2317 * Switch to the next window.
2319 * @param forward if true, then switch to the next window in the list,
2320 * otherwise switch to the previous window in the list
2322 public final void switchWindow(final boolean forward
) {
2323 // Only switch if there are multiple visible windows
2324 if (shownWindowCount() < 2) {
2327 assert (activeWindow
!= null);
2329 synchronized (windows
) {
2330 // Whatever window might be moving/dragging, stop it now.
2331 for (TWindow w
: windows
) {
2332 if (w
.inMovements()) {
2337 // Swap z/active between active window and the next in the list
2338 int activeWindowI
= -1;
2339 for (int i
= 0; i
< windows
.size(); i
++) {
2340 if (windows
.get(i
) == activeWindow
) {
2341 assert (activeWindow
.isActive());
2345 assert (!windows
.get(0).isActive());
2348 assert (activeWindowI
>= 0);
2350 // Do not switch if a window is modal
2351 if (activeWindow
.isModal()) {
2355 int nextWindowI
= activeWindowI
;
2359 nextWindowI
%= windows
.size();
2362 if (nextWindowI
< 0) {
2363 nextWindowI
= windows
.size() - 1;
2367 if (windows
.get(nextWindowI
).isShown()) {
2368 activateWindow(windows
.get(nextWindowI
));
2372 } // synchronized (windows)
2377 * Add a window to my window list and make it active. Note package
2380 * @param window new window to add
2382 final void addWindowToApplication(final TWindow window
) {
2384 // Do not add menu windows to the window list.
2385 if (window
instanceof TMenu
) {
2389 // Do not add the desktop to the window list.
2390 if (window
instanceof TDesktop
) {
2394 synchronized (windows
) {
2395 if (windows
.contains(window
)) {
2396 throw new IllegalArgumentException("Window " + window
+
2397 " is already in window list");
2400 // Whatever window might be moving/dragging, stop it now.
2401 for (TWindow w
: windows
) {
2402 if (w
.inMovements()) {
2407 // Do not allow a modal window to spawn a non-modal window. If a
2408 // modal window is active, then this window will become modal
2410 if (modalWindowActive()) {
2411 window
.flags
|= TWindow
.MODAL
;
2412 window
.flags
|= TWindow
.CENTERED
;
2413 window
.hidden
= false;
2415 if (window
.isShown()) {
2416 for (TWindow w
: windows
) {
2421 w
.setZ(w
.getZ() + 1);
2424 windows
.add(window
);
2425 if (window
.isShown()) {
2426 activeWindow
= window
;
2427 activeWindow
.setZ(0);
2428 activeWindow
.setActive(true);
2429 activeWindow
.onFocus();
2432 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2433 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2434 && (smartWindowPlacement
== true)
2437 doSmartPlacement(window
);
2441 // Desktop cannot be active over any other window.
2442 if (desktop
!= null) {
2443 desktop
.setActive(false);
2448 * Check if there is a system-modal window on top.
2450 * @return true if the active window is modal
2452 private boolean modalWindowActive() {
2453 if (windows
.size() == 0) {
2457 for (TWindow w
: windows
) {
2467 * Check if there is a window with overridden menu flag on top.
2469 * @return true if the active window is overriding the menu
2471 private boolean overrideMenuWindowActive() {
2472 if (activeWindow
!= null) {
2473 if (activeWindow
.hasOverriddenMenu()) {
2482 * Close all open windows.
2484 private void closeAllWindows() {
2485 // Don't do anything if we are in the menu
2486 if (activeMenu
!= null) {
2489 while (windows
.size() > 0) {
2490 closeWindow(windows
.get(0));
2495 * Re-layout the open windows as non-overlapping tiles. This produces
2496 * almost the same results as Turbo Pascal 7.0's IDE.
2498 private void tileWindows() {
2499 synchronized (windows
) {
2500 // Don't do anything if we are in the menu
2501 if (activeMenu
!= null) {
2504 int z
= windows
.size();
2510 a
= (int)(Math
.sqrt(z
));
2514 if (((a
* b
) + c
) == z
) {
2522 int newWidth
= (getScreen().getWidth() / a
);
2523 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2524 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2526 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2527 Collections
.sort(sorted
);
2528 Collections
.reverse(sorted
);
2529 for (int i
= 0; i
< sorted
.size(); i
++) {
2530 int logicalX
= i
/ b
;
2531 int logicalY
= i
% b
;
2532 if (i
>= ((a
- 1) * b
)) {
2534 logicalY
= i
- ((a
- 1) * b
);
2537 TWindow w
= sorted
.get(i
);
2538 int oldWidth
= w
.getWidth();
2539 int oldHeight
= w
.getHeight();
2541 w
.setX(logicalX
* newWidth
);
2542 w
.setWidth(newWidth
);
2543 if (i
>= ((a
- 1) * b
)) {
2544 w
.setY((logicalY
* newHeight2
) + 1);
2545 w
.setHeight(newHeight2
);
2547 w
.setY((logicalY
* newHeight1
) + 1);
2548 w
.setHeight(newHeight1
);
2550 if ((w
.getWidth() != oldWidth
)
2551 || (w
.getHeight() != oldHeight
)
2553 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2554 w
.getWidth(), w
.getHeight()));
2561 * Re-layout the open windows as overlapping cascaded windows.
2563 private void cascadeWindows() {
2564 synchronized (windows
) {
2565 // Don't do anything if we are in the menu
2566 if (activeMenu
!= null) {
2571 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2572 Collections
.sort(sorted
);
2573 Collections
.reverse(sorted
);
2574 for (TWindow window
: sorted
) {
2579 if (x
> getScreen().getWidth()) {
2582 if (y
>= getScreen().getHeight()) {
2590 * Place a window to minimize its overlap with other windows.
2592 * @param window the window to place
2594 public final void doSmartPlacement(final TWindow window
) {
2595 // This is a pretty dumb algorithm, but seems to work. The hardest
2596 // part is computing these "overlap" values seeking a minimum average
2599 int yMin
= desktopTop
;
2600 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2601 int yMax
= desktopBottom
- window
.getHeight() + 1;
2609 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2610 // No work to do, bail out.
2614 // Compute the overlap matrix without the new window.
2615 int width
= getScreen().getWidth();
2616 int height
= getScreen().getHeight();
2617 int overlapMatrix
[][] = new int[width
][height
];
2618 for (TWindow w
: windows
) {
2622 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2629 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2636 overlapMatrix
[x
][y
]++;
2641 long oldOverlapTotal
= 0;
2642 long oldOverlapN
= 0;
2643 for (int x
= 0; x
< width
; x
++) {
2644 for (int y
= 0; y
< height
; y
++) {
2645 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2646 if (overlapMatrix
[x
][y
] > 0) {
2653 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2654 boolean first
= true;
2655 int windowX
= window
.getX();
2656 int windowY
= window
.getY();
2658 // For each possible (x, y) position for the new window, compute a
2659 // new overlap matrix.
2660 for (int x
= xMin
; x
< xMax
; x
++) {
2661 for (int y
= yMin
; y
< yMax
; y
++) {
2663 // Start with the matrix minus this window.
2664 int newMatrix
[][] = new int[width
][height
];
2665 for (int mx
= 0; mx
< width
; mx
++) {
2666 for (int my
= 0; my
< height
; my
++) {
2667 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2671 // Add this window's values to the new overlap matrix.
2672 long newOverlapTotal
= 0;
2673 long newOverlapN
= 0;
2674 // Start by adding each new cell.
2675 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2679 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2683 newMatrix
[wx
][wy
]++;
2686 // Now figure out the new value for total coverage.
2687 for (int mx
= 0; mx
< width
; mx
++) {
2688 for (int my
= 0; my
< height
; my
++) {
2689 newOverlapTotal
+= newMatrix
[x
][y
];
2690 if (newMatrix
[mx
][my
] > 0) {
2695 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2698 // First time: just record what we got.
2699 oldOverlapAvg
= newOverlapAvg
;
2702 // All other times: pick a new best (x, y) and save the
2704 if (newOverlapAvg
< oldOverlapAvg
) {
2707 oldOverlapAvg
= newOverlapAvg
;
2711 } // for (int x = xMin; x < xMax; x++)
2713 } // for (int y = yMin; y < yMax; y++)
2715 // Finally, set the window's new coordinates.
2716 window
.setX(windowX
);
2717 window
.setY(windowY
);
2720 // ------------------------------------------------------------------------
2721 // TMenu management -------------------------------------------------------
2722 // ------------------------------------------------------------------------
2725 * Check if a mouse event would hit either the active menu or any open
2728 * @param mouse mouse event
2729 * @return true if the mouse would hit the active menu or an open
2732 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2733 assert (activeMenu
!= null);
2734 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2735 Collections
.reverse(menus
);
2736 for (TMenu menu
: menus
) {
2737 if (menu
.mouseWouldHit(mouse
)) {
2741 return activeMenu
.mouseWouldHit(mouse
);
2745 * See if we need to switch window or activate the menu based on
2748 * @param mouse mouse event
2750 private void checkSwitchFocus(final TMouseEvent mouse
) {
2752 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2753 && (activeMenu
!= null)
2754 && (mouse
.getAbsoluteY() != 0)
2755 && (!mouseOnMenu(mouse
))
2757 // They clicked outside the active menu, turn it off
2758 activeMenu
.setActive(false);
2760 for (TMenu menu
: subMenus
) {
2761 menu
.setActive(false);
2767 // See if they hit the menu bar
2768 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2769 && (mouse
.isMouse1())
2770 && (!modalWindowActive())
2771 && (!overrideMenuWindowActive())
2772 && (mouse
.getAbsoluteY() == 0)
2775 for (TMenu menu
: subMenus
) {
2776 menu
.setActive(false);
2780 // They selected the menu, go activate it
2781 for (TMenu menu
: menus
) {
2782 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2783 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2784 + StringUtils
.width(menu
.getTitle()) + 2)
2786 menu
.setActive(true);
2789 menu
.setActive(false);
2795 // See if they hit the menu bar
2796 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2797 && (mouse
.isMouse1())
2798 && (activeMenu
!= null)
2799 && (mouse
.getAbsoluteY() == 0)
2802 TMenu oldMenu
= activeMenu
;
2803 for (TMenu menu
: subMenus
) {
2804 menu
.setActive(false);
2808 // See if we should switch menus
2809 for (TMenu menu
: menus
) {
2810 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2811 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2812 + StringUtils
.width(menu
.getTitle()) + 2)
2814 menu
.setActive(true);
2818 if (oldMenu
!= activeMenu
) {
2819 // They switched menus
2820 oldMenu
.setActive(false);
2825 // If a menu is still active, don't switch windows
2826 if (activeMenu
!= null) {
2830 // Only switch if there are multiple windows
2831 if (windows
.size() < 2) {
2835 if (((focusFollowsMouse
== true)
2836 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2837 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2839 synchronized (windows
) {
2840 Collections
.sort(windows
);
2841 if (windows
.get(0).isModal()) {
2842 // Modal windows don't switch
2846 for (TWindow window
: windows
) {
2847 assert (!window
.isModal());
2849 if (window
.isHidden()) {
2850 assert (!window
.isActive());
2854 if (window
.mouseWouldHit(mouse
)) {
2855 if (window
== windows
.get(0)) {
2856 // Clicked on the same window, nothing to do
2857 assert (window
.isActive());
2861 // We will be switching to another window
2862 assert (windows
.get(0).isActive());
2863 assert (windows
.get(0) == activeWindow
);
2864 assert (!window
.isActive());
2865 if (activeWindow
!= null) {
2866 activeWindow
.onUnfocus();
2867 activeWindow
.setActive(false);
2868 activeWindow
.setZ(window
.getZ());
2870 activeWindow
= window
;
2872 window
.setActive(true);
2879 // Clicked on the background, nothing to do
2883 // Nothing to do: this isn't a mouse up, or focus isn't following
2889 * Turn off the menu.
2891 public final void closeMenu() {
2892 if (activeMenu
!= null) {
2893 activeMenu
.setActive(false);
2895 for (TMenu menu
: subMenus
) {
2896 menu
.setActive(false);
2903 * Get a (shallow) copy of the menu list.
2905 * @return a copy of the menu list
2907 public final List
<TMenu
> getAllMenus() {
2908 return new ArrayList
<TMenu
>(menus
);
2912 * Add a top-level menu to the list.
2914 * @param menu the menu to add
2915 * @throws IllegalArgumentException if the menu is already used in
2916 * another TApplication
2918 public final void addMenu(final TMenu menu
) {
2919 if ((menu
.getApplication() != null)
2920 && (menu
.getApplication() != this)
2922 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2923 "part of application " + menu
.getApplication());
2931 * Remove a top-level menu from the list.
2933 * @param menu the menu to remove
2934 * @throws IllegalArgumentException if the menu is already used in
2935 * another TApplication
2937 public final void removeMenu(final TMenu menu
) {
2938 if ((menu
.getApplication() != null)
2939 && (menu
.getApplication() != this)
2941 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2942 "part of application " + menu
.getApplication());
2950 * Turn off a sub-menu.
2952 public final void closeSubMenu() {
2953 assert (activeMenu
!= null);
2954 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2955 assert (item
!= null);
2956 item
.setActive(false);
2957 subMenus
.remove(subMenus
.size() - 1);
2961 * Switch to the next menu.
2963 * @param forward if true, then switch to the next menu in the list,
2964 * otherwise switch to the previous menu in the list
2966 public final void switchMenu(final boolean forward
) {
2967 assert (activeMenu
!= null);
2969 for (TMenu menu
: subMenus
) {
2970 menu
.setActive(false);
2974 for (int i
= 0; i
< menus
.size(); i
++) {
2975 if (activeMenu
== menus
.get(i
)) {
2977 if (i
< menus
.size() - 1) {
2986 i
= menus
.size() - 1;
2989 activeMenu
.setActive(false);
2990 activeMenu
= menus
.get(i
);
2991 activeMenu
.setActive(true);
2998 * Add a menu item to the global list. If it has a keyboard accelerator,
2999 * that will be added the global hash.
3001 * @param item the menu item
3003 public final void addMenuItem(final TMenuItem item
) {
3004 menuItems
.add(item
);
3006 TKeypress key
= item
.getKey();
3008 synchronized (accelerators
) {
3009 assert (accelerators
.get(key
) == null);
3010 accelerators
.put(key
.toLowerCase(), item
);
3016 * Disable one menu item.
3018 * @param id the menu item ID
3020 public final void disableMenuItem(final int id
) {
3021 for (TMenuItem item
: menuItems
) {
3022 if (item
.getId() == id
) {
3023 item
.setEnabled(false);
3029 * Disable the range of menu items with ID's between lower and upper,
3032 * @param lower the lowest menu item ID
3033 * @param upper the highest menu item ID
3035 public final void disableMenuItems(final int lower
, final int upper
) {
3036 for (TMenuItem item
: menuItems
) {
3037 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
3038 item
.setEnabled(false);
3039 item
.getParent().activate(0);
3045 * Enable one menu item.
3047 * @param id the menu item ID
3049 public final void enableMenuItem(final int id
) {
3050 for (TMenuItem item
: menuItems
) {
3051 if (item
.getId() == id
) {
3052 item
.setEnabled(true);
3053 item
.getParent().activate(0);
3059 * Enable the range of menu items with ID's between lower and upper,
3062 * @param lower the lowest menu item ID
3063 * @param upper the highest menu item ID
3065 public final void enableMenuItems(final int lower
, final int upper
) {
3066 for (TMenuItem item
: menuItems
) {
3067 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
3068 item
.setEnabled(true);
3069 item
.getParent().activate(0);
3075 * Get the menu item associated with this ID.
3077 * @param id the menu item ID
3078 * @return the menu item, or null if not found
3080 public final TMenuItem
getMenuItem(final int id
) {
3081 for (TMenuItem item
: menuItems
) {
3082 if (item
.getId() == id
) {
3090 * Recompute menu x positions based on their title length.
3092 public final void recomputeMenuX() {
3094 for (TMenu menu
: menus
) {
3097 x
+= StringUtils
.width(menu
.getTitle()) + 2;
3099 // Don't let the menu window exceed the screen width
3100 int rightEdge
= menu
.getX() + menu
.getWidth();
3101 if (rightEdge
> getScreen().getWidth()) {
3102 menu
.setX(getScreen().getWidth() - menu
.getWidth());
3108 * Post an event to process.
3110 * @param event new event to add to the queue
3112 public final void postEvent(final TInputEvent event
) {
3113 synchronized (this) {
3114 synchronized (fillEventQueue
) {
3115 fillEventQueue
.add(event
);
3118 System
.err
.println(System
.currentTimeMillis() + " " +
3119 Thread
.currentThread() + " postEvent() wake up main");
3126 * Post an event to process and turn off the menu.
3128 * @param event new event to add to the queue
3130 public final void postMenuEvent(final TInputEvent event
) {
3131 synchronized (this) {
3132 synchronized (fillEventQueue
) {
3133 fillEventQueue
.add(event
);
3136 System
.err
.println(System
.currentTimeMillis() + " " +
3137 Thread
.currentThread() + " postMenuEvent() wake up main");
3145 * Add a sub-menu to the list of open sub-menus.
3147 * @param menu sub-menu
3149 public final void addSubMenu(final TMenu menu
) {
3154 * Convenience function to add a top-level menu.
3156 * @param title menu title
3157 * @return the new menu
3159 public final TMenu
addMenu(final String title
) {
3162 TMenu menu
= new TMenu(this, x
, y
, title
);
3169 * Convenience function to add a default tools (hamburger) menu.
3171 * @return the new menu
3173 public final TMenu
addToolMenu() {
3174 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
3175 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
3176 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
3177 toolMenu
.addDefaultItem(TMenu
.MID_SCREEN_OPTIONS
);
3178 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
3179 getString("toolMenuStatus"));
3180 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3185 * Convenience function to add a default "File" menu.
3187 * @return the new menu
3189 public final TMenu
addFileMenu() {
3190 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
3191 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
3192 fileMenu
.addSeparator();
3193 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
3194 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
3195 getString("fileMenuStatus"));
3196 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3201 * Convenience function to add a default "Edit" menu.
3203 * @return the new menu
3205 public final TMenu
addEditMenu() {
3206 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
3207 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
3208 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
3209 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
3210 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
3211 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
3212 getString("editMenuStatus"));
3213 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3218 * Convenience function to add a default "Window" menu.
3220 * @return the new menu
3222 public final TMenu
addWindowMenu() {
3223 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
3224 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
3225 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
3226 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
3227 windowMenu
.addSeparator();
3228 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
3229 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
3230 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3231 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3232 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3233 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3234 getString("windowMenuStatus"));
3235 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3240 * Convenience function to add a default "Help" menu.
3242 * @return the new menu
3244 public final TMenu
addHelpMenu() {
3245 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3246 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3247 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3248 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3249 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3250 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3251 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3252 helpMenu
.addSeparator();
3253 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3254 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3255 getString("helpMenuStatus"));
3256 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3261 * Convenience function to add a default "Table" menu.
3263 * @return the new menu
3265 public final TMenu
addTableMenu() {
3266 TMenu tableMenu
= addMenu(i18n
.getString("tableMenuTitle"));
3267 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_COLUMN
, false);
3268 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_ROW
, false);
3269 tableMenu
.addSeparator();
3271 TSubMenu viewMenu
= tableMenu
.addSubMenu(i18n
.
3272 getString("tableSubMenuView"));
3273 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_ROW_LABELS
, false);
3274 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_COLUMN_LABELS
, false);
3275 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_ROW
, false);
3276 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_COLUMN
, false);
3278 TSubMenu borderMenu
= tableMenu
.addSubMenu(i18n
.
3279 getString("tableSubMenuBorders"));
3280 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_NONE
, false);
3281 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_ALL
, false);
3282 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_NONE
, false);
3283 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_ALL
, false);
3284 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_RIGHT
, false);
3285 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_LEFT
, false);
3286 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_TOP
, false);
3287 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_BOTTOM
, false);
3288 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_DOUBLE_BOTTOM
, false);
3289 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_THICK_BOTTOM
, false);
3290 TSubMenu deleteMenu
= tableMenu
.addSubMenu(i18n
.
3291 getString("tableSubMenuDelete"));
3292 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_LEFT
, false);
3293 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_UP
, false);
3294 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_ROW
, false);
3295 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_COLUMN
, false);
3296 TSubMenu insertMenu
= tableMenu
.addSubMenu(i18n
.
3297 getString("tableSubMenuInsert"));
3298 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_LEFT
, false);
3299 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_RIGHT
, false);
3300 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_ABOVE
, false);
3301 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_BELOW
, false);
3302 TSubMenu columnMenu
= tableMenu
.addSubMenu(i18n
.
3303 getString("tableSubMenuColumn"));
3304 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_NARROW
, false);
3305 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_WIDEN
, false);
3306 TSubMenu fileMenu
= tableMenu
.addSubMenu(i18n
.
3307 getString("tableSubMenuFile"));
3308 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_OPEN_CSV
, false);
3309 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_CSV
, false);
3310 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_TEXT
, false);
3312 TStatusBar statusBar
= tableMenu
.newStatusBar(i18n
.
3313 getString("tableMenuStatus"));
3314 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3318 // ------------------------------------------------------------------------
3319 // TTimer management ------------------------------------------------------
3320 // ------------------------------------------------------------------------
3323 * Get the amount of time I can sleep before missing a Timer tick.
3325 * @param timeout = initial (maximum) timeout in millis
3326 * @return number of milliseconds between now and the next timer event
3328 private long getSleepTime(final long timeout
) {
3329 Date now
= new Date();
3330 long nowTime
= now
.getTime();
3331 long sleepTime
= timeout
;
3333 synchronized (timers
) {
3334 for (TTimer timer
: timers
) {
3335 long nextTickTime
= timer
.getNextTick().getTime();
3336 if (nextTickTime
< nowTime
) {
3340 long timeDifference
= nextTickTime
- nowTime
;
3341 if (timeDifference
< sleepTime
) {
3342 sleepTime
= timeDifference
;
3347 assert (sleepTime
>= 0);
3348 assert (sleepTime
<= timeout
);
3353 * Convenience function to add a timer.
3355 * @param duration number of milliseconds to wait between ticks
3356 * @param recurring if true, re-schedule this timer after every tick
3357 * @param action function to call when button is pressed
3360 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3361 final TAction action
) {
3363 TTimer timer
= new TTimer(duration
, recurring
, action
);
3364 synchronized (timers
) {
3371 * Convenience function to remove a timer.
3373 * @param timer timer to remove
3375 public final void removeTimer(final TTimer timer
) {
3376 synchronized (timers
) {
3377 timers
.remove(timer
);
3381 // ------------------------------------------------------------------------
3382 // Other TWindow constructors ---------------------------------------------
3383 // ------------------------------------------------------------------------
3386 * Convenience function to spawn a message box.
3388 * @param title window title, will be centered along the top border
3389 * @param caption message to display. Use embedded newlines to get a
3391 * @return the new message box
3393 public final TMessageBox
messageBox(final String title
,
3394 final String caption
) {
3396 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3400 * Convenience function to spawn a message box.
3402 * @param title window title, will be centered along the top border
3403 * @param caption message to display. Use embedded newlines to get a
3405 * @param type one of the TMessageBox.Type constants. Default is
3407 * @return the new message box
3409 public final TMessageBox
messageBox(final String title
,
3410 final String caption
, final TMessageBox
.Type type
) {
3412 return new TMessageBox(this, title
, caption
, type
);
3416 * Convenience function to spawn an input box.
3418 * @param title window title, will be centered along the top border
3419 * @param caption message to display. Use embedded newlines to get a
3421 * @return the new input box
3423 public final TInputBox
inputBox(final String title
, final String caption
) {
3425 return new TInputBox(this, title
, caption
);
3429 * Convenience function to spawn an input box.
3431 * @param title window title, will be centered along the top border
3432 * @param caption message to display. Use embedded newlines to get a
3434 * @param text initial text to seed the field with
3435 * @return the new input box
3437 public final TInputBox
inputBox(final String title
, final String caption
,
3438 final String text
) {
3440 return new TInputBox(this, title
, caption
, text
);
3444 * Convenience function to spawn an input box.
3446 * @param title window title, will be centered along the top border
3447 * @param caption message to display. Use embedded newlines to get a
3449 * @param text initial text to seed the field with
3450 * @param type one of the Type constants. Default is Type.OK.
3451 * @return the new input box
3453 public final TInputBox
inputBox(final String title
, final String caption
,
3454 final String text
, final TInputBox
.Type type
) {
3456 return new TInputBox(this, title
, caption
, text
, type
);
3460 * Convenience function to open a terminal window.
3462 * @param x column relative to parent
3463 * @param y row relative to parent
3464 * @return the terminal new window
3466 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3467 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3471 * Convenience function to open a terminal window.
3473 * @param x column relative to parent
3474 * @param y row relative to parent
3475 * @param closeOnExit if true, close the window when the command exits
3476 * @return the terminal new window
3478 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3479 final boolean closeOnExit
) {
3481 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3485 * Convenience function to open a terminal window.
3487 * @param x column relative to parent
3488 * @param y row relative to parent
3489 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3490 * @return the terminal new window
3492 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3495 return new TTerminalWindow(this, x
, y
, flags
);
3499 * Convenience function to open a terminal window.
3501 * @param x column relative to parent
3502 * @param y row relative to parent
3503 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3504 * @param closeOnExit if true, close the window when the command exits
3505 * @return the terminal new window
3507 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3508 final int flags
, final boolean closeOnExit
) {
3510 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3514 * Convenience function to open a terminal window and execute a custom
3515 * command line inside it.
3517 * @param x column relative to parent
3518 * @param y row relative to parent
3519 * @param commandLine the command line to execute
3520 * @return the terminal new window
3522 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3523 final String commandLine
) {
3525 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3529 * Convenience function to open a terminal window and execute a custom
3530 * command line inside it.
3532 * @param x column relative to parent
3533 * @param y row relative to parent
3534 * @param commandLine the command line to execute
3535 * @param closeOnExit if true, close the window when the command exits
3536 * @return the terminal new window
3538 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3539 final String commandLine
, final boolean closeOnExit
) {
3541 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3545 * Convenience function to open a terminal window and execute a custom
3546 * command line inside it.
3548 * @param x column relative to parent
3549 * @param y row relative to parent
3550 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3551 * @param command the command line to execute
3552 * @return the terminal new window
3554 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3555 final int flags
, final String
[] command
) {
3557 return new TTerminalWindow(this, x
, y
, flags
, command
);
3561 * Convenience function to open a terminal window and execute a custom
3562 * command line inside it.
3564 * @param x column relative to parent
3565 * @param y row relative to parent
3566 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3567 * @param command the command line to execute
3568 * @param closeOnExit if true, close the window when the command exits
3569 * @return the terminal new window
3571 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3572 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3574 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3578 * Convenience function to open a terminal window and execute a custom
3579 * command line inside it.
3581 * @param x column relative to parent
3582 * @param y row relative to parent
3583 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3584 * @param commandLine the command line to execute
3585 * @return the terminal new window
3587 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3588 final int flags
, final String commandLine
) {
3590 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"));
3594 * Convenience function to open a terminal window and execute a custom
3595 * command line inside it.
3597 * @param x column relative to parent
3598 * @param y row relative to parent
3599 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3600 * @param commandLine the command line to execute
3601 * @param closeOnExit if true, close the window when the command exits
3602 * @return the terminal new window
3604 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3605 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3607 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"),
3612 * Convenience function to spawn an file open box.
3614 * @param path path of selected file
3615 * @return the result of the new file open box
3616 * @throws IOException if java.io operation throws
3618 public final String
fileOpenBox(final String path
) throws IOException
{
3620 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3621 return box
.getFilename();
3625 * Convenience function to spawn an file open box.
3627 * @param path path of selected file
3628 * @param type one of the Type constants
3629 * @return the result of the new file open box
3630 * @throws IOException if java.io operation throws
3632 public final String
fileOpenBox(final String path
,
3633 final TFileOpenBox
.Type type
) throws IOException
{
3635 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3636 return box
.getFilename();
3640 * Convenience function to spawn a file open box.
3642 * @param path path of selected file
3643 * @param type one of the Type constants
3644 * @param filter a string that files must match to be displayed
3645 * @return the result of the new file open box
3646 * @throws IOException of a java.io operation throws
3648 public final String
fileOpenBox(final String path
,
3649 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3651 ArrayList
<String
> filters
= new ArrayList
<String
>();
3652 filters
.add(filter
);
3654 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3655 return box
.getFilename();
3659 * Convenience function to spawn a file open box.
3661 * @param path path of selected file
3662 * @param type one of the Type constants
3663 * @param filters a list of strings that files must match to be displayed
3664 * @return the result of the new file open box
3665 * @throws IOException of a java.io operation throws
3667 public final String
fileOpenBox(final String path
,
3668 final TFileOpenBox
.Type type
,
3669 final List
<String
> filters
) throws IOException
{
3671 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3672 return box
.getFilename();
3676 * Convenience function to create a new window and make it active.
3677 * Window will be located at (0, 0).
3679 * @param title window title, will be centered along the top border
3680 * @param width width of window
3681 * @param height height of window
3682 * @return the new window
3684 public final TWindow
addWindow(final String title
, final int width
,
3687 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3692 * Convenience function to create a new window and make it active.
3693 * Window will be located at (0, 0).
3695 * @param title window title, will be centered along the top border
3696 * @param width width of window
3697 * @param height height of window
3698 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3699 * @return the new window
3701 public final TWindow
addWindow(final String title
,
3702 final int width
, final int height
, final int flags
) {
3704 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3709 * Convenience function to create a new window and make it active.
3711 * @param title window title, will be centered along the top border
3712 * @param x column relative to parent
3713 * @param y row relative to parent
3714 * @param width width of window
3715 * @param height height of window
3716 * @return the new window
3718 public final TWindow
addWindow(final String title
,
3719 final int x
, final int y
, final int width
, final int height
) {
3721 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3726 * Convenience function to create a new window and make it active.
3728 * @param title window title, will be centered along the top border
3729 * @param x column relative to parent
3730 * @param y row relative to parent
3731 * @param width width of window
3732 * @param height height of window
3733 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3734 * @return the new window
3736 public final TWindow
addWindow(final String title
,
3737 final int x
, final int y
, final int width
, final int height
,
3740 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);