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
.event
.TCommandEvent
;
52 import jexer
.event
.TInputEvent
;
53 import jexer
.event
.TKeypressEvent
;
54 import jexer
.event
.TMenuEvent
;
55 import jexer
.event
.TMouseEvent
;
56 import jexer
.event
.TResizeEvent
;
57 import jexer
.backend
.Backend
;
58 import jexer
.backend
.MultiBackend
;
59 import jexer
.backend
.Screen
;
60 import jexer
.backend
.SwingBackend
;
61 import jexer
.backend
.ECMA48Backend
;
62 import jexer
.backend
.TWindowBackend
;
63 import jexer
.menu
.TMenu
;
64 import jexer
.menu
.TMenuItem
;
65 import jexer
.menu
.TSubMenu
;
66 import static jexer
.TCommand
.*;
67 import static jexer
.TKeypress
.*;
70 * TApplication is the main driver class for a full Text User Interface
71 * application. It manages windows, provides a menu bar and status bar, and
72 * processes events received from the user.
74 public class TApplication
implements Runnable
{
79 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
81 // ------------------------------------------------------------------------
82 // Constants --------------------------------------------------------------
83 // ------------------------------------------------------------------------
86 * If true, emit thread stuff to System.err.
88 private static final boolean debugThreads
= false;
91 * If true, emit events being processed to System.err.
93 private static final boolean debugEvents
= false;
96 * If true, do "smart placement" on new windows that are not specified to
99 private static final boolean smartWindowPlacement
= true;
102 * Two backend types are available.
104 public static enum BackendType
{
111 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
116 * Synonym for ECMA48.
121 // ------------------------------------------------------------------------
122 // Variables --------------------------------------------------------------
123 // ------------------------------------------------------------------------
126 * The primary event handler thread.
128 private volatile WidgetEventHandler primaryEventHandler
;
131 * The secondary event handler thread.
133 private volatile WidgetEventHandler secondaryEventHandler
;
136 * The widget receiving events from the secondary event handler thread.
138 private volatile TWidget secondaryEventReceiver
;
141 * Access to the physical screen, keyboard, and mouse.
143 private Backend backend
;
146 * Actual mouse coordinate X.
151 * Actual mouse coordinate Y.
156 * Old version of mouse coordinate X.
158 private int oldMouseX
;
161 * Old version mouse coordinate Y.
163 private int oldMouseY
;
166 * Old drawn version of mouse coordinate X.
168 private int oldDrawnMouseX
;
171 * Old drawn version mouse coordinate Y.
173 private int oldDrawnMouseY
;
176 * Old drawn version mouse cell.
178 private Cell oldDrawnMouseCell
= new Cell();
181 * The last mouse up click time, used to determine if this is a mouse
184 private long lastMouseUpTime
;
187 * The amount of millis between mouse up events to assume a double-click.
189 private long doubleClickTime
= 250;
192 * Event queue that is filled by run().
194 private List
<TInputEvent
> fillEventQueue
;
197 * Event queue that will be drained by either primary or secondary
200 private List
<TInputEvent
> drainEventQueue
;
203 * Top-level menus in this application.
205 private List
<TMenu
> menus
;
208 * Stack of activated sub-menus in this application.
210 private List
<TMenu
> subMenus
;
213 * The currently active menu.
215 private TMenu activeMenu
= null;
218 * Active keyboard accelerators.
220 private Map
<TKeypress
, TMenuItem
> accelerators
;
225 private List
<TMenuItem
> menuItems
;
228 * Windows and widgets pull colors from this ColorTheme.
230 private ColorTheme theme
;
233 * The top-level windows (but not menus).
235 private List
<TWindow
> windows
;
238 * The currently acive window.
240 private TWindow activeWindow
= null;
243 * Timers that are being ticked.
245 private List
<TTimer
> timers
;
248 * When true, the application has been started.
250 private volatile boolean started
= false;
253 * When true, exit the application.
255 private volatile boolean quit
= false;
258 * When true, repaint the entire screen.
260 private volatile boolean repaint
= true;
263 * Y coordinate of the top edge of the desktop. For now this is a
264 * constant. Someday it would be nice to have a multi-line menu or
267 private static final int desktopTop
= 1;
270 * Y coordinate of the bottom edge of the desktop.
272 private int desktopBottom
;
275 * An optional TDesktop background window that is drawn underneath
278 private TDesktop desktop
;
281 * If true, focus follows mouse: windows automatically raised if the
282 * mouse passes over them.
284 private boolean focusFollowsMouse
= false;
287 * The list of commands to run before the next I/O check.
289 private List
<Runnable
> invokeLaters
= new LinkedList
<Runnable
>();
292 * WidgetEventHandler is the main event consumer loop. There are at most
293 * two such threads in existence: the primary for normal case and a
294 * secondary that is used for TMessageBox, TInputBox, and similar.
296 private class WidgetEventHandler
implements Runnable
{
298 * The main application.
300 private TApplication application
;
303 * Whether or not this WidgetEventHandler is the primary or secondary
306 private boolean primary
= true;
309 * Public constructor.
311 * @param application the main application
312 * @param primary if true, this is the primary event handler thread
314 public WidgetEventHandler(final TApplication application
,
315 final boolean primary
) {
317 this.application
= application
;
318 this.primary
= primary
;
325 // Wrap everything in a try, so that if we go belly up we can let
326 // the user have their terminal back.
329 } catch (Throwable t
) {
330 this.application
.restoreConsole();
332 this.application
.exit();
339 private void runImpl() {
340 boolean first
= true;
343 while (!application
.quit
) {
345 // Wait until application notifies me
346 while (!application
.quit
) {
348 synchronized (application
.drainEventQueue
) {
349 if (application
.drainEventQueue
.size() > 0) {
358 timeout
= application
.getSleepTime(1000);
362 // A timer needs to fire, break out.
367 System
.err
.printf("%d %s %s %s sleep %d millis\n",
368 System
.currentTimeMillis(), this,
369 primary ?
"primary" : "secondary",
370 Thread
.currentThread(), timeout
);
373 synchronized (this) {
378 System
.err
.printf("%d %s %s %s AWAKE\n",
379 System
.currentTimeMillis(), this,
380 primary ?
"primary" : "secondary",
381 Thread
.currentThread());
385 && (application
.secondaryEventReceiver
== null)
387 // Secondary thread, emergency exit. If we got
388 // here then something went wrong with the
389 // handoff between yield() and closeWindow().
390 synchronized (application
.primaryEventHandler
) {
391 application
.primaryEventHandler
.notify();
393 application
.secondaryEventHandler
= null;
394 throw new RuntimeException("secondary exited " +
398 } catch (InterruptedException e
) {
401 } // while (!application.quit)
403 // Pull all events off the queue
405 TInputEvent event
= null;
406 synchronized (application
.drainEventQueue
) {
407 if (application
.drainEventQueue
.size() == 0) {
410 event
= application
.drainEventQueue
.remove(0);
413 // We will have an event to process, so repaint the
414 // screen at the end.
415 application
.repaint
= true;
418 primaryHandleEvent(event
);
420 secondaryHandleEvent(event
);
423 && (application
.secondaryEventReceiver
== null)
425 // Secondary thread, time to exit.
427 // Eliminate my reference so that wakeEventHandler()
428 // resumes working on the primary.
429 application
.secondaryEventHandler
= null;
431 // We are ready to exit, wake up the primary thread.
432 // Remember that it is currently sleeping inside its
433 // primaryHandleEvent().
434 synchronized (application
.primaryEventHandler
) {
435 application
.primaryEventHandler
.notify();
444 // Fire timers, update screen.
446 application
.finishEventProcessing();
449 } // while (true) (main runnable loop)
453 // ------------------------------------------------------------------------
454 // Constructors -----------------------------------------------------------
455 // ------------------------------------------------------------------------
458 * Public constructor.
460 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
462 * @param windowWidth the number of text columns to start with
463 * @param windowHeight the number of text rows to start with
464 * @param fontSize the size in points
465 * @throws UnsupportedEncodingException if an exception is thrown when
466 * creating the InputStreamReader
468 public TApplication(final BackendType backendType
, final int windowWidth
,
469 final int windowHeight
, final int fontSize
)
470 throws UnsupportedEncodingException
{
472 switch (backendType
) {
474 backend
= new SwingBackend(this, windowWidth
, windowHeight
,
480 backend
= new ECMA48Backend(this, null, null, windowWidth
,
481 windowHeight
, fontSize
);
484 throw new IllegalArgumentException("Invalid backend type: "
491 * Public constructor.
493 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
495 * @throws UnsupportedEncodingException if an exception is thrown when
496 * creating the InputStreamReader
498 public TApplication(final BackendType backendType
)
499 throws UnsupportedEncodingException
{
501 switch (backendType
) {
503 // The default SwingBackend is 80x25, 20 pt font. If you want to
504 // change that, you can pass the extra arguments to the
505 // SwingBackend constructor here. For example, if you wanted
506 // 90x30, 16 pt font:
508 // backend = new SwingBackend(this, 90, 30, 16);
509 backend
= new SwingBackend(this);
514 backend
= new ECMA48Backend(this, null, null);
517 throw new IllegalArgumentException("Invalid backend type: "
524 * Public constructor. The backend type will be BackendType.ECMA48.
526 * @param input an InputStream connected to the remote user, or null for
527 * System.in. If System.in is used, then on non-Windows systems it will
528 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
529 * mode. input is always converted to a Reader with UTF-8 encoding.
530 * @param output an OutputStream connected to the remote user, or null
531 * for System.out. output is always converted to a Writer with UTF-8
533 * @throws UnsupportedEncodingException if an exception is thrown when
534 * creating the InputStreamReader
536 public TApplication(final InputStream input
,
537 final OutputStream output
) throws UnsupportedEncodingException
{
539 backend
= new ECMA48Backend(this, input
, output
);
544 * Public constructor. The backend type will be BackendType.ECMA48.
546 * @param input the InputStream underlying 'reader'. Its available()
547 * method is used to determine if reader.read() will block or not.
548 * @param reader a Reader connected to the remote user.
549 * @param writer a PrintWriter connected to the remote user.
550 * @param setRawMode if true, set System.in into raw mode with stty.
551 * This should in general not be used. It is here solely for Demo3,
552 * which uses System.in.
553 * @throws IllegalArgumentException if input, reader, or writer are null.
555 public TApplication(final InputStream input
, final Reader reader
,
556 final PrintWriter writer
, final boolean setRawMode
) {
558 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
563 * Public constructor. The backend type will be BackendType.ECMA48.
565 * @param input the InputStream underlying 'reader'. Its available()
566 * method is used to determine if reader.read() will block or not.
567 * @param reader a Reader connected to the remote user.
568 * @param writer a PrintWriter connected to the remote user.
569 * @throws IllegalArgumentException if input, reader, or writer are null.
571 public TApplication(final InputStream input
, final Reader reader
,
572 final PrintWriter writer
) {
574 this(input
, reader
, writer
, false);
578 * Public constructor. This hook enables use with new non-Jexer
581 * @param backend a Backend that is already ready to go.
583 public TApplication(final Backend backend
) {
584 this.backend
= backend
;
585 backend
.setListener(this);
590 * Finish construction once the backend is set.
592 private void TApplicationImpl() {
593 theme
= new ColorTheme();
594 desktopBottom
= getScreen().getHeight() - 1;
595 fillEventQueue
= new LinkedList
<TInputEvent
>();
596 drainEventQueue
= new LinkedList
<TInputEvent
>();
597 windows
= new LinkedList
<TWindow
>();
598 menus
= new ArrayList
<TMenu
>();
599 subMenus
= new ArrayList
<TMenu
>();
600 timers
= new LinkedList
<TTimer
>();
601 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
602 menuItems
= new LinkedList
<TMenuItem
>();
603 desktop
= new TDesktop(this);
605 // Special case: the Swing backend needs to have a timer to drive its
607 if ((backend
instanceof SwingBackend
)
608 || (backend
instanceof MultiBackend
)
610 // Default to 500 millis, unless a SwingBackend has its own
613 if (backend
instanceof SwingBackend
) {
614 millis
= ((SwingBackend
) backend
).getBlinkMillis();
617 addTimer(millis
, true,
620 TApplication
.this.doRepaint();
628 // ------------------------------------------------------------------------
629 // Runnable ---------------------------------------------------------------
630 // ------------------------------------------------------------------------
633 * Run this application until it exits.
636 // System.err.println("*** TApplication.run() begins ***");
638 // Start the main consumer thread
639 primaryEventHandler
= new WidgetEventHandler(this, true);
640 (new Thread(primaryEventHandler
)).start();
645 synchronized (this) {
646 boolean doWait
= false;
648 if (!backend
.hasEvents()) {
649 synchronized (fillEventQueue
) {
650 if (fillEventQueue
.size() == 0) {
657 // No I/O to dispatch, so wait until the backend
661 System
.err
.println(System
.currentTimeMillis() +
662 " " + Thread
.currentThread() + " MAIN sleep");
668 System
.err
.println(System
.currentTimeMillis() +
669 " " + Thread
.currentThread() + " MAIN AWAKE");
671 } catch (InterruptedException e
) {
672 // I'm awake and don't care why, let's see what's
673 // going on out there.
677 } // synchronized (this)
679 synchronized (fillEventQueue
) {
680 // Pull any pending I/O events
681 backend
.getEvents(fillEventQueue
);
683 // Dispatch each event to the appropriate handler, one at a
686 TInputEvent event
= null;
687 if (fillEventQueue
.size() == 0) {
690 event
= fillEventQueue
.remove(0);
691 metaHandleEvent(event
);
695 // Wake a consumer thread if we have any pending events.
696 if (drainEventQueue
.size() > 0) {
702 // Shutdown the event consumer threads
703 if (secondaryEventHandler
!= null) {
704 synchronized (secondaryEventHandler
) {
705 secondaryEventHandler
.notify();
708 if (primaryEventHandler
!= null) {
709 synchronized (primaryEventHandler
) {
710 primaryEventHandler
.notify();
714 // Shutdown the user I/O thread(s)
717 // Close all the windows. This gives them an opportunity to release
721 // Give the overarching application an opportunity to release
725 // System.err.println("*** TApplication.run() exits ***");
728 // ------------------------------------------------------------------------
729 // Event handlers ---------------------------------------------------------
730 // ------------------------------------------------------------------------
733 * Method that TApplication subclasses can override to handle menu or
734 * posted command events.
736 * @param command command event
737 * @return if true, this event was consumed
739 protected boolean onCommand(final TCommandEvent command
) {
740 // Default: handle cmExit
741 if (command
.equals(cmExit
)) {
742 if (messageBox(i18n
.getString("exitDialogTitle"),
743 i18n
.getString("exitDialogText"),
744 TMessageBox
.Type
.YESNO
).isYes()) {
751 if (command
.equals(cmShell
)) {
752 openTerminal(0, 0, TWindow
.RESIZABLE
);
756 if (command
.equals(cmTile
)) {
760 if (command
.equals(cmCascade
)) {
764 if (command
.equals(cmCloseAll
)) {
769 if (command
.equals(cmMenu
)) {
770 if (!modalWindowActive() && (activeMenu
== null)) {
771 if (menus
.size() > 0) {
772 menus
.get(0).setActive(true);
773 activeMenu
= menus
.get(0);
783 * Method that TApplication subclasses can override to handle menu
786 * @param menu menu event
787 * @return if true, this event was consumed
789 protected boolean onMenu(final TMenuEvent menu
) {
791 // Default: handle MID_EXIT
792 if (menu
.getId() == TMenu
.MID_EXIT
) {
793 if (messageBox(i18n
.getString("exitDialogTitle"),
794 i18n
.getString("exitDialogText"),
795 TMessageBox
.Type
.YESNO
).isYes()) {
802 if (menu
.getId() == TMenu
.MID_SHELL
) {
803 openTerminal(0, 0, TWindow
.RESIZABLE
);
807 if (menu
.getId() == TMenu
.MID_TILE
) {
811 if (menu
.getId() == TMenu
.MID_CASCADE
) {
815 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
819 if (menu
.getId() == TMenu
.MID_ABOUT
) {
823 if (menu
.getId() == TMenu
.MID_REPAINT
) {
824 getScreen().clearPhysical();
828 if (menu
.getId() == TMenu
.MID_VIEW_IMAGE
) {
832 if (menu
.getId() == TMenu
.MID_CHANGE_FONT
) {
833 new TFontChooserWindow(this);
840 * Method that TApplication subclasses can override to handle keystrokes.
842 * @param keypress keystroke event
843 * @return if true, this event was consumed
845 protected boolean onKeypress(final TKeypressEvent keypress
) {
846 // Default: only menu shortcuts
848 // Process Alt-F, Alt-E, etc. menu shortcut keys
849 if (!keypress
.getKey().isFnKey()
850 && keypress
.getKey().isAlt()
851 && !keypress
.getKey().isCtrl()
852 && (activeMenu
== null)
853 && !modalWindowActive()
856 assert (subMenus
.size() == 0);
858 for (TMenu menu
: menus
) {
859 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
860 == Character
.toLowerCase(keypress
.getKey().getChar())
863 menu
.setActive(true);
873 * Process background events, and update the screen.
875 private void finishEventProcessing() {
877 System
.err
.printf(System
.currentTimeMillis() + " " +
878 Thread
.currentThread() + " finishEventProcessing()\n");
881 // Process timers and call doIdle()'s
885 synchronized (getScreen()) {
890 System
.err
.printf(System
.currentTimeMillis() + " " +
891 Thread
.currentThread() + " finishEventProcessing() END\n");
896 * Peek at certain application-level events, add to eventQueue, and wake
897 * up the consuming Thread.
899 * @param event the input event to consume
901 private void metaHandleEvent(final TInputEvent event
) {
904 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
905 event
)); System
.err
.flush();
909 // Do no more processing if the application is already trying
914 // Special application-wide events -------------------------------
917 if (event
instanceof TCommandEvent
) {
918 TCommandEvent command
= (TCommandEvent
) event
;
919 if (command
.equals(cmAbort
)) {
925 synchronized (drainEventQueue
) {
927 if (event
instanceof TResizeEvent
) {
928 TResizeEvent resize
= (TResizeEvent
) event
;
929 synchronized (getScreen()) {
930 getScreen().setDimensions(resize
.getWidth(),
932 desktopBottom
= getScreen().getHeight() - 1;
938 if (desktop
!= null) {
939 desktop
.setDimensions(0, 0, resize
.getWidth(),
940 resize
.getHeight() - 1);
941 desktop
.onResize(resize
);
944 // Change menu edges if needed.
947 // We are dirty, redraw the screen.
951 System.err.println("New screen: " + resize.getWidth() +
952 " x " + resize.getHeight());
957 // Put into the main queue
958 drainEventQueue
.add(event
);
963 * Dispatch one event to the appropriate widget or application-level
964 * event handler. This is the primary event handler, it has the normal
965 * application-wide event handling.
967 * @param event the input event to consume
968 * @see #secondaryHandleEvent(TInputEvent event)
970 private void primaryHandleEvent(final TInputEvent event
) {
973 System
.err
.printf("%s primaryHandleEvent: %s\n",
974 Thread
.currentThread(), event
);
976 TMouseEvent doubleClick
= null;
978 // Special application-wide events -----------------------------------
980 // Peek at the mouse position
981 if (event
instanceof TMouseEvent
) {
982 TMouseEvent mouse
= (TMouseEvent
) event
;
983 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
986 mouseX
= mouse
.getX();
987 mouseY
= mouse
.getY();
989 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
990 && (!mouse
.isMouseWheelUp())
991 && (!mouse
.isMouseWheelDown())
993 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
996 // This is a double-click.
997 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
999 mouse
.getX(), mouse
.getY(),
1000 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1001 mouse
.isMouse1(), mouse
.isMouse2(),
1003 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1006 // The first click of a potential double-click.
1007 lastMouseUpTime
= mouse
.getTime().getTime();
1012 // See if we need to switch focus to another window or the menu
1013 checkSwitchFocus((TMouseEvent
) event
);
1016 // Handle menu events
1017 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1018 TMenu menu
= activeMenu
;
1020 if (event
instanceof TMouseEvent
) {
1021 TMouseEvent mouse
= (TMouseEvent
) event
;
1023 while (subMenus
.size() > 0) {
1024 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1025 if (subMenu
.mouseWouldHit(mouse
)) {
1028 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1029 && (!mouse
.isMouse1())
1030 && (!mouse
.isMouse2())
1031 && (!mouse
.isMouse3())
1032 && (!mouse
.isMouseWheelUp())
1033 && (!mouse
.isMouseWheelDown())
1037 // We navigated away from a sub-menu, so close it
1041 // Convert the mouse relative x/y to menu coordinates
1042 assert (mouse
.getX() == mouse
.getAbsoluteX());
1043 assert (mouse
.getY() == mouse
.getAbsoluteY());
1044 if (subMenus
.size() > 0) {
1045 menu
= subMenus
.get(subMenus
.size() - 1);
1047 mouse
.setX(mouse
.getX() - menu
.getX());
1048 mouse
.setY(mouse
.getY() - menu
.getY());
1050 menu
.handleEvent(event
);
1054 if (event
instanceof TKeypressEvent
) {
1055 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1057 // See if this key matches an accelerator, and is not being
1058 // shortcutted by the active window, and if so dispatch the menu
1060 boolean windowWillShortcut
= false;
1061 if (activeWindow
!= null) {
1062 assert (activeWindow
.isShown());
1063 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1064 // We do not process this key, it will be passed to the
1066 windowWillShortcut
= true;
1070 if (!windowWillShortcut
&& !modalWindowActive()) {
1071 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1072 TMenuItem item
= null;
1073 synchronized (accelerators
) {
1074 item
= accelerators
.get(keypressLowercase
);
1077 if (item
.isEnabled()) {
1078 // Let the menu item dispatch
1084 // Handle the keypress
1085 if (onKeypress(keypress
)) {
1091 if (event
instanceof TCommandEvent
) {
1092 if (onCommand((TCommandEvent
) event
)) {
1097 if (event
instanceof TMenuEvent
) {
1098 if (onMenu((TMenuEvent
) event
)) {
1103 // Dispatch events to the active window -------------------------------
1104 boolean dispatchToDesktop
= true;
1105 TWindow window
= activeWindow
;
1106 if (window
!= null) {
1107 assert (window
.isActive());
1108 assert (window
.isShown());
1109 if (event
instanceof TMouseEvent
) {
1110 TMouseEvent mouse
= (TMouseEvent
) event
;
1111 // Convert the mouse relative x/y to window coordinates
1112 assert (mouse
.getX() == mouse
.getAbsoluteX());
1113 assert (mouse
.getY() == mouse
.getAbsoluteY());
1114 mouse
.setX(mouse
.getX() - window
.getX());
1115 mouse
.setY(mouse
.getY() - window
.getY());
1117 if (doubleClick
!= null) {
1118 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1119 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1122 if (window
.mouseWouldHit(mouse
)) {
1123 dispatchToDesktop
= false;
1125 } else if (event
instanceof TKeypressEvent
) {
1126 dispatchToDesktop
= false;
1130 System
.err
.printf("TApplication dispatch event: %s\n",
1133 window
.handleEvent(event
);
1134 if (doubleClick
!= null) {
1135 window
.handleEvent(doubleClick
);
1138 if (dispatchToDesktop
) {
1139 // This event is fair game for the desktop to process.
1140 if (desktop
!= null) {
1141 desktop
.handleEvent(event
);
1142 if (doubleClick
!= null) {
1143 desktop
.handleEvent(doubleClick
);
1150 * Dispatch one event to the appropriate widget or application-level
1151 * event handler. This is the secondary event handler used by certain
1152 * special dialogs (currently TMessageBox and TFileOpenBox).
1154 * @param event the input event to consume
1155 * @see #primaryHandleEvent(TInputEvent event)
1157 private void secondaryHandleEvent(final TInputEvent event
) {
1158 TMouseEvent doubleClick
= null;
1161 System
.err
.printf("%s secondaryHandleEvent: %s\n",
1162 Thread
.currentThread(), event
);
1165 // Peek at the mouse position
1166 if (event
instanceof TMouseEvent
) {
1167 TMouseEvent mouse
= (TMouseEvent
) event
;
1168 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1171 mouseX
= mouse
.getX();
1172 mouseY
= mouse
.getY();
1174 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1175 && (!mouse
.isMouseWheelUp())
1176 && (!mouse
.isMouseWheelDown())
1178 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1181 // This is a double-click.
1182 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1184 mouse
.getX(), mouse
.getY(),
1185 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1186 mouse
.isMouse1(), mouse
.isMouse2(),
1188 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1191 // The first click of a potential double-click.
1192 lastMouseUpTime
= mouse
.getTime().getTime();
1198 secondaryEventReceiver
.handleEvent(event
);
1199 // Note that it is possible for secondaryEventReceiver to be null
1200 // now, because its handleEvent() might have finished out on the
1201 // secondary thread. So put any extra processing inside a null
1203 if (secondaryEventReceiver
!= null) {
1204 if (doubleClick
!= null) {
1205 secondaryEventReceiver
.handleEvent(doubleClick
);
1211 * Enable a widget to override the primary event thread.
1213 * @param widget widget that will receive events
1215 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1217 System
.err
.println(System
.currentTimeMillis() +
1218 " enableSecondaryEventReceiver()");
1221 assert (secondaryEventReceiver
== null);
1222 assert (secondaryEventHandler
== null);
1223 assert ((widget
instanceof TMessageBox
)
1224 || (widget
instanceof TFileOpenBox
));
1225 secondaryEventReceiver
= widget
;
1226 secondaryEventHandler
= new WidgetEventHandler(this, false);
1228 (new Thread(secondaryEventHandler
)).start();
1232 * Yield to the secondary thread.
1234 public final void yield() {
1236 System
.err
.printf(System
.currentTimeMillis() + " " +
1237 Thread
.currentThread() + " yield()\n");
1240 assert (secondaryEventReceiver
!= null);
1242 while (secondaryEventReceiver
!= null) {
1243 synchronized (primaryEventHandler
) {
1245 primaryEventHandler
.wait();
1246 } catch (InterruptedException e
) {
1254 * Do stuff when there is no user input.
1256 private void doIdle() {
1258 System
.err
.printf(System
.currentTimeMillis() + " " +
1259 Thread
.currentThread() + " doIdle()\n");
1262 synchronized (timers
) {
1265 System
.err
.printf(System
.currentTimeMillis() + " " +
1266 Thread
.currentThread() + " doIdle() 2\n");
1269 // Run any timers that have timed out
1270 Date now
= new Date();
1271 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1272 for (TTimer timer
: timers
) {
1273 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1274 // Something might change, so repaint the screen.
1277 if (timer
.recurring
) {
1278 keepTimers
.add(timer
);
1281 keepTimers
.add(timer
);
1285 timers
.addAll(keepTimers
);
1289 for (TWindow window
: windows
) {
1292 if (desktop
!= null) {
1296 // Run any invokeLaters
1297 synchronized (invokeLaters
) {
1298 for (Runnable invoke
: invokeLaters
) {
1301 invokeLaters
.clear();
1307 * Wake the sleeping active event handler.
1309 private void wakeEventHandler() {
1314 if (secondaryEventHandler
!= null) {
1315 synchronized (secondaryEventHandler
) {
1316 secondaryEventHandler
.notify();
1319 assert (primaryEventHandler
!= null);
1320 synchronized (primaryEventHandler
) {
1321 primaryEventHandler
.notify();
1326 // ------------------------------------------------------------------------
1327 // TApplication -----------------------------------------------------------
1328 // ------------------------------------------------------------------------
1331 * Place a command on the run queue, and run it before the next round of
1334 * @param command the command to run later
1336 public void invokeLater(final Runnable command
) {
1337 synchronized (invokeLaters
) {
1338 invokeLaters
.add(command
);
1344 * Restore the console to sane defaults. This is meant to be used for
1345 * improper exits (e.g. a caught exception in main()), and should not be
1346 * necessary for normal program termination.
1348 public void restoreConsole() {
1349 if (backend
!= null) {
1350 if (backend
instanceof ECMA48Backend
) {
1359 * @return the Backend
1361 public final Backend
getBackend() {
1368 * @return the Screen
1370 public final Screen
getScreen() {
1371 if (backend
instanceof TWindowBackend
) {
1372 // We are being rendered to a TWindow. We can't use its
1373 // getScreen() method because that is how it is rendering to a
1374 // hardware backend somewhere. Instead use its getOtherScreen()
1376 return ((TWindowBackend
) backend
).getOtherScreen();
1378 return backend
.getScreen();
1383 * Get the color theme.
1387 public final ColorTheme
getTheme() {
1392 * Repaint the screen on the next update.
1394 public void doRepaint() {
1400 * Get Y coordinate of the top edge of the desktop.
1402 * @return Y coordinate of the top edge of the desktop
1404 public final int getDesktopTop() {
1409 * Get Y coordinate of the bottom edge of the desktop.
1411 * @return Y coordinate of the bottom edge of the desktop
1413 public final int getDesktopBottom() {
1414 return desktopBottom
;
1418 * Set the TDesktop instance.
1420 * @param desktop a TDesktop instance, or null to remove the one that is
1423 public final void setDesktop(final TDesktop desktop
) {
1424 if (this.desktop
!= null) {
1425 this.desktop
.onClose();
1427 this.desktop
= desktop
;
1431 * Get the TDesktop instance.
1433 * @return the desktop, or null if it is not set
1435 public final TDesktop
getDesktop() {
1440 * Get the current active window.
1442 * @return the active window, or null if it is not set
1444 public final TWindow
getActiveWindow() {
1445 return activeWindow
;
1449 * Get a (shallow) copy of the window list.
1451 * @return a copy of the list of windows for this application
1453 public final List
<TWindow
> getAllWindows() {
1454 List
<TWindow
> result
= new ArrayList
<TWindow
>();
1455 result
.addAll(windows
);
1460 * Get focusFollowsMouse flag.
1462 * @return true if focus follows mouse: windows automatically raised if
1463 * the mouse passes over them
1465 public boolean getFocusFollowsMouse() {
1466 return focusFollowsMouse
;
1470 * Set focusFollowsMouse flag.
1472 * @param focusFollowsMouse if true, focus follows mouse: windows
1473 * automatically raised if the mouse passes over them
1475 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
1476 this.focusFollowsMouse
= focusFollowsMouse
;
1480 * Display the about dialog.
1482 protected void showAboutDialog() {
1483 String version
= getClass().getPackage().getImplementationVersion();
1484 if (version
== null) {
1485 // This is Java 9+, use a hardcoded string here.
1488 messageBox(i18n
.getString("aboutDialogTitle"),
1489 MessageFormat
.format(i18n
.getString("aboutDialogText"), version
),
1490 TMessageBox
.Type
.OK
);
1494 * Handle the Tool | Open image menu item.
1496 private void openImage() {
1498 List
<String
> filters
= new ArrayList
<String
>();
1499 filters
.add("^.*\\.[Jj][Pp][Gg]$");
1500 filters
.add("^.*\\.[Jj][Pp][Ee][Gg]$");
1501 filters
.add("^.*\\.[Pp][Nn][Gg]$");
1502 filters
.add("^.*\\.[Gg][Ii][Ff]$");
1503 filters
.add("^.*\\.[Bb][Mm][Pp]$");
1504 String filename
= fileOpenBox(".", TFileOpenBox
.Type
.OPEN
, filters
);
1505 if (filename
!= null) {
1506 new TImageWindow(this, new File(filename
));
1508 } catch (IOException e
) {
1509 // Show this exception to the user.
1510 new TExceptionDialog(this, e
);
1515 * Check if application is still running.
1517 * @return true if the application is running
1519 public final boolean isRunning() {
1526 // ------------------------------------------------------------------------
1527 // Screen refresh loop ----------------------------------------------------
1528 // ------------------------------------------------------------------------
1531 * Invert the cell color at a position. This is used to track the mouse.
1533 * @param x column position
1534 * @param y row position
1536 private void invertCell(final int x
, final int y
) {
1537 invertCell(x
, y
, false);
1541 * Invert the cell color at a position. This is used to track the mouse.
1543 * @param x column position
1544 * @param y row position
1545 * @param onlyThisCell if true, only invert this cell
1547 private void invertCell(final int x
, final int y
,
1548 final boolean onlyThisCell
) {
1551 System
.err
.printf("%d %s invertCell() %d %d\n",
1552 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1554 if (activeWindow
!= null) {
1555 System
.err
.println("activeWindow.hasHiddenMouse() " +
1556 activeWindow
.hasHiddenMouse());
1560 // If this cell is on top of a visible window that has requested a
1561 // hidden mouse, bail out.
1562 if ((activeWindow
!= null) && (activeMenu
== null)) {
1563 if ((activeWindow
.hasHiddenMouse() == true)
1564 && (x
> activeWindow
.getX())
1565 && (x
< activeWindow
.getX() + activeWindow
.getWidth() - 1)
1566 && (y
> activeWindow
.getY())
1567 && (y
< activeWindow
.getY() + activeWindow
.getHeight() - 1)
1573 Cell cell
= getScreen().getCharXY(x
, y
);
1574 if (cell
.isImage()) {
1577 if (cell
.getForeColorRGB() < 0) {
1578 cell
.setForeColor(cell
.getForeColor().invert());
1580 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1582 if (cell
.getBackColorRGB() < 0) {
1583 cell
.setBackColor(cell
.getBackColor().invert());
1585 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1588 getScreen().putCharXY(x
, y
, cell
);
1589 if ((onlyThisCell
== true) || (cell
.getWidth() == Cell
.Width
.SINGLE
)) {
1593 // This cell is one half of a fullwidth glyph. Invert the other
1595 if (cell
.getWidth() == Cell
.Width
.LEFT
) {
1596 if (x
< getScreen().getWidth() - 1) {
1597 Cell rightHalf
= getScreen().getCharXY(x
+ 1, y
);
1598 if (rightHalf
.getWidth() == Cell
.Width
.RIGHT
) {
1599 invertCell(x
+ 1, y
, true);
1604 assert (cell
.getWidth() == Cell
.Width
.RIGHT
);
1607 Cell leftHalf
= getScreen().getCharXY(x
- 1, y
);
1608 if (leftHalf
.getWidth() == Cell
.Width
.LEFT
) {
1609 invertCell(x
- 1, y
, true);
1617 private void drawAll() {
1618 boolean menuIsActive
= false;
1621 System
.err
.printf("%d %s drawAll() enter\n",
1622 System
.currentTimeMillis(), Thread
.currentThread());
1625 // I don't think this does anything useful anymore...
1628 System
.err
.printf("%d %s drawAll() !repaint\n",
1629 System
.currentTimeMillis(), Thread
.currentThread());
1631 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1633 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1634 System
.currentTimeMillis(), Thread
.currentThread());
1637 // The only thing that has happened is the mouse moved.
1639 // Redraw the old cell at that position, and save the cell at
1640 // the new mouse position.
1642 System
.err
.printf("%d %s restoreImage() %d %d\n",
1643 System
.currentTimeMillis(), Thread
.currentThread(),
1644 oldDrawnMouseX
, oldDrawnMouseY
);
1646 oldDrawnMouseCell
.restoreImage();
1647 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1649 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1650 if (backend
instanceof ECMA48Backend
) {
1651 // Special case: the entire row containing the mouse has
1652 // to be re-drawn if it has any image data, AND any rows
1654 if (oldDrawnMouseY
!= mouseY
) {
1655 for (int i
= oldDrawnMouseY
; ;) {
1656 getScreen().unsetImageRow(i
);
1660 if (oldDrawnMouseY
< mouseY
) {
1667 getScreen().unsetImageRow(mouseY
);
1671 // Draw mouse at the new position.
1672 invertCell(mouseX
, mouseY
);
1674 oldDrawnMouseX
= mouseX
;
1675 oldDrawnMouseY
= mouseY
;
1677 if (getScreen().isDirty()) {
1678 backend
.flushScreen();
1684 System
.err
.printf("%d %s drawAll() REDRAW\n",
1685 System
.currentTimeMillis(), Thread
.currentThread());
1688 // If true, the cursor is not visible
1689 boolean cursor
= false;
1691 // Start with a clean screen
1692 getScreen().clear();
1695 if (desktop
!= null) {
1696 desktop
.drawChildren();
1699 // Draw each window in reverse Z order
1700 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1701 Collections
.sort(sorted
);
1702 TWindow topLevel
= null;
1703 if (sorted
.size() > 0) {
1704 topLevel
= sorted
.get(0);
1706 Collections
.reverse(sorted
);
1707 for (TWindow window
: sorted
) {
1708 if (window
.isShown()) {
1709 window
.drawChildren();
1713 // Draw the blank menubar line - reset the screen clipping first so
1714 // it won't trim it out.
1715 getScreen().resetClipping();
1716 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1717 theme
.getColor("tmenu"));
1718 // Now draw the menus.
1720 for (TMenu menu
: menus
) {
1721 CellAttributes menuColor
;
1722 CellAttributes menuMnemonicColor
;
1723 if (menu
.isActive()) {
1724 menuIsActive
= true;
1725 menuColor
= theme
.getColor("tmenu.highlighted");
1726 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1729 menuColor
= theme
.getColor("tmenu");
1730 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1732 // Draw the menu title
1733 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
1735 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1736 // Draw the highlight character
1737 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
1738 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1740 if (menu
.isActive()) {
1741 ((TWindow
) menu
).drawChildren();
1742 // Reset the screen clipping so we can draw the next title.
1743 getScreen().resetClipping();
1745 x
+= menu
.getTitle().length() + 2;
1748 for (TMenu menu
: subMenus
) {
1749 // Reset the screen clipping so we can draw the next sub-menu.
1750 getScreen().resetClipping();
1751 ((TWindow
) menu
).drawChildren();
1753 getScreen().resetClipping();
1755 // Draw the status bar of the top-level window
1756 TStatusBar statusBar
= null;
1757 if (topLevel
!= null) {
1758 statusBar
= topLevel
.getStatusBar();
1760 if (statusBar
!= null) {
1761 getScreen().resetClipping();
1762 statusBar
.setWidth(getScreen().getWidth());
1763 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1766 CellAttributes barColor
= new CellAttributes();
1767 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1768 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
1772 // Draw the mouse pointer
1774 System
.err
.printf("%d %s restoreImage() %d %d\n",
1775 System
.currentTimeMillis(), Thread
.currentThread(),
1776 oldDrawnMouseX
, oldDrawnMouseY
);
1778 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1779 if (backend
instanceof ECMA48Backend
) {
1780 // Special case: the entire row containing the mouse has to be
1781 // re-drawn if it has any image data, AND any rows in between.
1782 if (oldDrawnMouseY
!= mouseY
) {
1783 for (int i
= oldDrawnMouseY
; ;) {
1784 getScreen().unsetImageRow(i
);
1788 if (oldDrawnMouseY
< mouseY
) {
1795 getScreen().unsetImageRow(mouseY
);
1798 invertCell(mouseX
, mouseY
);
1799 oldDrawnMouseX
= mouseX
;
1800 oldDrawnMouseY
= mouseY
;
1802 // Place the cursor if it is visible
1803 if (!menuIsActive
) {
1804 TWidget activeWidget
= null;
1805 if (sorted
.size() > 0) {
1806 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
1807 if (activeWidget
.isCursorVisible()) {
1808 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
1809 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
1811 getScreen().putCursor(true,
1812 activeWidget
.getCursorAbsoluteX(),
1813 activeWidget
.getCursorAbsoluteY());
1816 // Turn off the cursor. Also place it at 0,0.
1817 getScreen().putCursor(false, 0, 0);
1826 getScreen().hideCursor();
1829 // Flush the screen contents
1830 if (getScreen().isDirty()) {
1832 System
.err
.printf("%d %s backend.flushScreen()\n",
1833 System
.currentTimeMillis(), Thread
.currentThread());
1835 backend
.flushScreen();
1842 * Force this application to exit.
1844 public void exit() {
1846 synchronized (this) {
1852 * Subclasses can use this hook to cleanup resources. Called as the last
1853 * step of TApplication.run().
1855 public void onExit() {
1856 // Default does nothing.
1859 // ------------------------------------------------------------------------
1860 // TWindow management -----------------------------------------------------
1861 // ------------------------------------------------------------------------
1864 * Return the total number of windows.
1866 * @return the total number of windows
1868 public final int windowCount() {
1869 return windows
.size();
1873 * Return the number of windows that are showing.
1875 * @return the number of windows that are showing on screen
1877 public final int shownWindowCount() {
1879 for (TWindow w
: windows
) {
1888 * Return the number of windows that are hidden.
1890 * @return the number of windows that are hidden
1892 public final int hiddenWindowCount() {
1894 for (TWindow w
: windows
) {
1903 * Check if a window instance is in this application's window list.
1905 * @param window window to look for
1906 * @return true if this window is in the list
1908 public final boolean hasWindow(final TWindow window
) {
1909 if (windows
.size() == 0) {
1912 for (TWindow w
: windows
) {
1914 assert (window
.getApplication() == this);
1922 * Activate a window: bring it to the top and have it receive events.
1924 * @param window the window to become the new active window
1926 public void activateWindow(final TWindow window
) {
1927 if (hasWindow(window
) == false) {
1929 * Someone has a handle to a window I don't have. Ignore this
1935 // Whatever window might be moving/dragging, stop it now.
1936 for (TWindow w
: windows
) {
1937 if (w
.inMovements()) {
1942 assert (windows
.size() > 0);
1944 if (window
.isHidden()) {
1945 // Unhiding will also activate.
1949 assert (window
.isShown());
1951 if (windows
.size() == 1) {
1952 assert (window
== windows
.get(0));
1953 if (activeWindow
== null) {
1954 activeWindow
= window
;
1956 activeWindow
.setActive(true);
1957 activeWindow
.onFocus();
1960 assert (window
.isActive());
1961 assert (activeWindow
== window
);
1965 if (activeWindow
== window
) {
1966 assert (window
.isActive());
1968 // Window is already active, do nothing.
1972 assert (!window
.isActive());
1973 if (activeWindow
!= null) {
1974 // TODO: see if this assertion is really necessary.
1975 // assert (activeWindow.getZ() == 0);
1977 activeWindow
.setActive(false);
1979 // Increment every window Z that is on top of window
1980 for (TWindow w
: windows
) {
1984 if (w
.getZ() < window
.getZ()) {
1985 w
.setZ(w
.getZ() + 1);
1989 // Unset activeWindow now before unfocus, so that a window
1990 // lifecycle change inside onUnfocus() doesn't call
1991 // switchWindow() and lead to a stack overflow.
1992 TWindow oldActiveWindow
= activeWindow
;
1993 activeWindow
= null;
1994 oldActiveWindow
.onUnfocus();
1996 activeWindow
= window
;
1997 activeWindow
.setZ(0);
1998 activeWindow
.setActive(true);
1999 activeWindow
.onFocus();
2006 * @param window the window to hide
2008 public void hideWindow(final TWindow window
) {
2009 if (hasWindow(window
) == false) {
2011 * Someone has a handle to a window I don't have. Ignore this
2017 // Whatever window might be moving/dragging, stop it now.
2018 for (TWindow w
: windows
) {
2019 if (w
.inMovements()) {
2024 assert (windows
.size() > 0);
2026 if (!window
.hidden
) {
2027 if (window
== activeWindow
) {
2028 if (shownWindowCount() > 1) {
2031 activeWindow
= null;
2032 window
.setActive(false);
2036 window
.hidden
= true;
2044 * @param window the window to show
2046 public void showWindow(final TWindow window
) {
2047 if (hasWindow(window
) == false) {
2049 * Someone has a handle to a window I don't have. Ignore this
2055 // Whatever window might be moving/dragging, stop it now.
2056 for (TWindow w
: windows
) {
2057 if (w
.inMovements()) {
2062 assert (windows
.size() > 0);
2064 if (window
.hidden
) {
2065 window
.hidden
= false;
2067 activateWindow(window
);
2072 * Close window. Note that the window's destructor is NOT called by this
2073 * method, instead the GC is assumed to do the cleanup.
2075 * @param window the window to remove
2077 public final void closeWindow(final TWindow window
) {
2078 if (hasWindow(window
) == false) {
2080 * Someone has a handle to a window I don't have. Ignore this
2086 // Let window know that it is about to be closed, while it is still
2087 // visible on screen.
2088 window
.onPreClose();
2090 synchronized (windows
) {
2091 // Whatever window might be moving/dragging, stop it now.
2092 for (TWindow w
: windows
) {
2093 if (w
.inMovements()) {
2098 int z
= window
.getZ();
2101 windows
.remove(window
);
2102 Collections
.sort(windows
);
2103 activeWindow
= null;
2105 boolean foundNextWindow
= false;
2107 for (TWindow w
: windows
) {
2111 // Do not activate a hidden window.
2116 if (foundNextWindow
== false) {
2117 foundNextWindow
= true;
2120 assert (activeWindow
== null);
2132 // Perform window cleanup
2135 // Check if we are closing a TMessageBox or similar
2136 if (secondaryEventReceiver
!= null) {
2137 assert (secondaryEventHandler
!= null);
2139 // Do not send events to the secondaryEventReceiver anymore, the
2140 // window is closed.
2141 secondaryEventReceiver
= null;
2143 // Wake the secondary thread, it will wake the primary as it
2145 synchronized (secondaryEventHandler
) {
2146 secondaryEventHandler
.notify();
2150 // Permit desktop to be active if it is the only thing left.
2151 if (desktop
!= null) {
2152 if (windows
.size() == 0) {
2153 desktop
.setActive(true);
2159 * Switch to the next window.
2161 * @param forward if true, then switch to the next window in the list,
2162 * otherwise switch to the previous window in the list
2164 public final void switchWindow(final boolean forward
) {
2165 // Only switch if there are multiple visible windows
2166 if (shownWindowCount() < 2) {
2169 assert (activeWindow
!= null);
2171 synchronized (windows
) {
2172 // Whatever window might be moving/dragging, stop it now.
2173 for (TWindow w
: windows
) {
2174 if (w
.inMovements()) {
2179 // Swap z/active between active window and the next in the list
2180 int activeWindowI
= -1;
2181 for (int i
= 0; i
< windows
.size(); i
++) {
2182 if (windows
.get(i
) == activeWindow
) {
2183 assert (activeWindow
.isActive());
2187 assert (!windows
.get(0).isActive());
2190 assert (activeWindowI
>= 0);
2192 // Do not switch if a window is modal
2193 if (activeWindow
.isModal()) {
2197 int nextWindowI
= activeWindowI
;
2201 nextWindowI
%= windows
.size();
2204 if (nextWindowI
< 0) {
2205 nextWindowI
= windows
.size() - 1;
2209 if (windows
.get(nextWindowI
).isShown()) {
2210 activateWindow(windows
.get(nextWindowI
));
2214 } // synchronized (windows)
2219 * Add a window to my window list and make it active. Note package
2222 * @param window new window to add
2224 final void addWindowToApplication(final TWindow window
) {
2226 // Do not add menu windows to the window list.
2227 if (window
instanceof TMenu
) {
2231 // Do not add the desktop to the window list.
2232 if (window
instanceof TDesktop
) {
2236 synchronized (windows
) {
2237 if (windows
.contains(window
)) {
2238 throw new IllegalArgumentException("Window " + window
+
2239 " is already in window list");
2242 // Whatever window might be moving/dragging, stop it now.
2243 for (TWindow w
: windows
) {
2244 if (w
.inMovements()) {
2249 // Do not allow a modal window to spawn a non-modal window. If a
2250 // modal window is active, then this window will become modal
2252 if (modalWindowActive()) {
2253 window
.flags
|= TWindow
.MODAL
;
2254 window
.flags
|= TWindow
.CENTERED
;
2255 window
.hidden
= false;
2257 if (window
.isShown()) {
2258 for (TWindow w
: windows
) {
2263 w
.setZ(w
.getZ() + 1);
2266 windows
.add(window
);
2267 if (window
.isShown()) {
2268 activeWindow
= window
;
2269 activeWindow
.setZ(0);
2270 activeWindow
.setActive(true);
2271 activeWindow
.onFocus();
2274 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2275 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2276 && (smartWindowPlacement
== true)
2279 doSmartPlacement(window
);
2283 // Desktop cannot be active over any other window.
2284 if (desktop
!= null) {
2285 desktop
.setActive(false);
2290 * Check if there is a system-modal window on top.
2292 * @return true if the active window is modal
2294 private boolean modalWindowActive() {
2295 if (windows
.size() == 0) {
2299 for (TWindow w
: windows
) {
2309 * Check if there is a window with overridden menu flag on top.
2311 * @return true if the active window is overriding the menu
2313 private boolean overrideMenuWindowActive() {
2314 if (activeWindow
!= null) {
2315 if (activeWindow
.hasOverriddenMenu()) {
2324 * Close all open windows.
2326 private void closeAllWindows() {
2327 // Don't do anything if we are in the menu
2328 if (activeMenu
!= null) {
2331 while (windows
.size() > 0) {
2332 closeWindow(windows
.get(0));
2337 * Re-layout the open windows as non-overlapping tiles. This produces
2338 * almost the same results as Turbo Pascal 7.0's IDE.
2340 private void tileWindows() {
2341 synchronized (windows
) {
2342 // Don't do anything if we are in the menu
2343 if (activeMenu
!= null) {
2346 int z
= windows
.size();
2352 a
= (int)(Math
.sqrt(z
));
2356 if (((a
* b
) + c
) == z
) {
2364 int newWidth
= (getScreen().getWidth() / a
);
2365 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2366 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2368 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2369 Collections
.sort(sorted
);
2370 Collections
.reverse(sorted
);
2371 for (int i
= 0; i
< sorted
.size(); i
++) {
2372 int logicalX
= i
/ b
;
2373 int logicalY
= i
% b
;
2374 if (i
>= ((a
- 1) * b
)) {
2376 logicalY
= i
- ((a
- 1) * b
);
2379 TWindow w
= sorted
.get(i
);
2380 int oldWidth
= w
.getWidth();
2381 int oldHeight
= w
.getHeight();
2383 w
.setX(logicalX
* newWidth
);
2384 w
.setWidth(newWidth
);
2385 if (i
>= ((a
- 1) * b
)) {
2386 w
.setY((logicalY
* newHeight2
) + 1);
2387 w
.setHeight(newHeight2
);
2389 w
.setY((logicalY
* newHeight1
) + 1);
2390 w
.setHeight(newHeight1
);
2392 if ((w
.getWidth() != oldWidth
)
2393 || (w
.getHeight() != oldHeight
)
2395 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2396 w
.getWidth(), w
.getHeight()));
2403 * Re-layout the open windows as overlapping cascaded windows.
2405 private void cascadeWindows() {
2406 synchronized (windows
) {
2407 // Don't do anything if we are in the menu
2408 if (activeMenu
!= null) {
2413 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2414 Collections
.sort(sorted
);
2415 Collections
.reverse(sorted
);
2416 for (TWindow window
: sorted
) {
2421 if (x
> getScreen().getWidth()) {
2424 if (y
>= getScreen().getHeight()) {
2432 * Place a window to minimize its overlap with other windows.
2434 * @param window the window to place
2436 public final void doSmartPlacement(final TWindow window
) {
2437 // This is a pretty dumb algorithm, but seems to work. The hardest
2438 // part is computing these "overlap" values seeking a minimum average
2441 int yMin
= desktopTop
;
2442 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2443 int yMax
= desktopBottom
- window
.getHeight() + 1;
2451 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2452 // No work to do, bail out.
2456 // Compute the overlap matrix without the new window.
2457 int width
= getScreen().getWidth();
2458 int height
= getScreen().getHeight();
2459 int overlapMatrix
[][] = new int[width
][height
];
2460 for (TWindow w
: windows
) {
2464 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2471 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2478 overlapMatrix
[x
][y
]++;
2483 long oldOverlapTotal
= 0;
2484 long oldOverlapN
= 0;
2485 for (int x
= 0; x
< width
; x
++) {
2486 for (int y
= 0; y
< height
; y
++) {
2487 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2488 if (overlapMatrix
[x
][y
] > 0) {
2495 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2496 boolean first
= true;
2497 int windowX
= window
.getX();
2498 int windowY
= window
.getY();
2500 // For each possible (x, y) position for the new window, compute a
2501 // new overlap matrix.
2502 for (int x
= xMin
; x
< xMax
; x
++) {
2503 for (int y
= yMin
; y
< yMax
; y
++) {
2505 // Start with the matrix minus this window.
2506 int newMatrix
[][] = new int[width
][height
];
2507 for (int mx
= 0; mx
< width
; mx
++) {
2508 for (int my
= 0; my
< height
; my
++) {
2509 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2513 // Add this window's values to the new overlap matrix.
2514 long newOverlapTotal
= 0;
2515 long newOverlapN
= 0;
2516 // Start by adding each new cell.
2517 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2521 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2525 newMatrix
[wx
][wy
]++;
2528 // Now figure out the new value for total coverage.
2529 for (int mx
= 0; mx
< width
; mx
++) {
2530 for (int my
= 0; my
< height
; my
++) {
2531 newOverlapTotal
+= newMatrix
[x
][y
];
2532 if (newMatrix
[mx
][my
] > 0) {
2537 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2540 // First time: just record what we got.
2541 oldOverlapAvg
= newOverlapAvg
;
2544 // All other times: pick a new best (x, y) and save the
2546 if (newOverlapAvg
< oldOverlapAvg
) {
2549 oldOverlapAvg
= newOverlapAvg
;
2553 } // for (int x = xMin; x < xMax; x++)
2555 } // for (int y = yMin; y < yMax; y++)
2557 // Finally, set the window's new coordinates.
2558 window
.setX(windowX
);
2559 window
.setY(windowY
);
2562 // ------------------------------------------------------------------------
2563 // TMenu management -------------------------------------------------------
2564 // ------------------------------------------------------------------------
2567 * Check if a mouse event would hit either the active menu or any open
2570 * @param mouse mouse event
2571 * @return true if the mouse would hit the active menu or an open
2574 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2575 assert (activeMenu
!= null);
2576 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2577 Collections
.reverse(menus
);
2578 for (TMenu menu
: menus
) {
2579 if (menu
.mouseWouldHit(mouse
)) {
2583 return activeMenu
.mouseWouldHit(mouse
);
2587 * See if we need to switch window or activate the menu based on
2590 * @param mouse mouse event
2592 private void checkSwitchFocus(final TMouseEvent mouse
) {
2594 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2595 && (activeMenu
!= null)
2596 && (mouse
.getAbsoluteY() != 0)
2597 && (!mouseOnMenu(mouse
))
2599 // They clicked outside the active menu, turn it off
2600 activeMenu
.setActive(false);
2602 for (TMenu menu
: subMenus
) {
2603 menu
.setActive(false);
2609 // See if they hit the menu bar
2610 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2611 && (mouse
.isMouse1())
2612 && (!modalWindowActive())
2613 && (!overrideMenuWindowActive())
2614 && (mouse
.getAbsoluteY() == 0)
2617 for (TMenu menu
: subMenus
) {
2618 menu
.setActive(false);
2622 // They selected the menu, go activate it
2623 for (TMenu menu
: menus
) {
2624 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2625 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2626 + menu
.getTitle().length() + 2)
2628 menu
.setActive(true);
2631 menu
.setActive(false);
2637 // See if they hit the menu bar
2638 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2639 && (mouse
.isMouse1())
2640 && (activeMenu
!= null)
2641 && (mouse
.getAbsoluteY() == 0)
2644 TMenu oldMenu
= activeMenu
;
2645 for (TMenu menu
: subMenus
) {
2646 menu
.setActive(false);
2650 // See if we should switch menus
2651 for (TMenu menu
: menus
) {
2652 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2653 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2654 + menu
.getTitle().length() + 2)
2656 menu
.setActive(true);
2660 if (oldMenu
!= activeMenu
) {
2661 // They switched menus
2662 oldMenu
.setActive(false);
2667 // If a menu is still active, don't switch windows
2668 if (activeMenu
!= null) {
2672 // Only switch if there are multiple windows
2673 if (windows
.size() < 2) {
2677 if (((focusFollowsMouse
== true)
2678 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2679 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2681 synchronized (windows
) {
2682 Collections
.sort(windows
);
2683 if (windows
.get(0).isModal()) {
2684 // Modal windows don't switch
2688 for (TWindow window
: windows
) {
2689 assert (!window
.isModal());
2691 if (window
.isHidden()) {
2692 assert (!window
.isActive());
2696 if (window
.mouseWouldHit(mouse
)) {
2697 if (window
== windows
.get(0)) {
2698 // Clicked on the same window, nothing to do
2699 assert (window
.isActive());
2703 // We will be switching to another window
2704 assert (windows
.get(0).isActive());
2705 assert (windows
.get(0) == activeWindow
);
2706 assert (!window
.isActive());
2707 if (activeWindow
!= null) {
2708 activeWindow
.onUnfocus();
2709 activeWindow
.setActive(false);
2710 activeWindow
.setZ(window
.getZ());
2712 activeWindow
= window
;
2714 window
.setActive(true);
2721 // Clicked on the background, nothing to do
2725 // Nothing to do: this isn't a mouse up, or focus isn't following
2731 * Turn off the menu.
2733 public final void closeMenu() {
2734 if (activeMenu
!= null) {
2735 activeMenu
.setActive(false);
2737 for (TMenu menu
: subMenus
) {
2738 menu
.setActive(false);
2745 * Get a (shallow) copy of the menu list.
2747 * @return a copy of the menu list
2749 public final List
<TMenu
> getAllMenus() {
2750 return new ArrayList
<TMenu
>(menus
);
2754 * Add a top-level menu to the list.
2756 * @param menu the menu to add
2757 * @throws IllegalArgumentException if the menu is already used in
2758 * another TApplication
2760 public final void addMenu(final TMenu menu
) {
2761 if ((menu
.getApplication() != null)
2762 && (menu
.getApplication() != this)
2764 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2765 "part of application " + menu
.getApplication());
2773 * Remove a top-level menu from the list.
2775 * @param menu the menu to remove
2776 * @throws IllegalArgumentException if the menu is already used in
2777 * another TApplication
2779 public final void removeMenu(final TMenu menu
) {
2780 if ((menu
.getApplication() != null)
2781 && (menu
.getApplication() != this)
2783 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2784 "part of application " + menu
.getApplication());
2792 * Turn off a sub-menu.
2794 public final void closeSubMenu() {
2795 assert (activeMenu
!= null);
2796 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2797 assert (item
!= null);
2798 item
.setActive(false);
2799 subMenus
.remove(subMenus
.size() - 1);
2803 * Switch to the next menu.
2805 * @param forward if true, then switch to the next menu in the list,
2806 * otherwise switch to the previous menu in the list
2808 public final void switchMenu(final boolean forward
) {
2809 assert (activeMenu
!= null);
2811 for (TMenu menu
: subMenus
) {
2812 menu
.setActive(false);
2816 for (int i
= 0; i
< menus
.size(); i
++) {
2817 if (activeMenu
== menus
.get(i
)) {
2819 if (i
< menus
.size() - 1) {
2828 i
= menus
.size() - 1;
2831 activeMenu
.setActive(false);
2832 activeMenu
= menus
.get(i
);
2833 activeMenu
.setActive(true);
2840 * Add a menu item to the global list. If it has a keyboard accelerator,
2841 * that will be added the global hash.
2843 * @param item the menu item
2845 public final void addMenuItem(final TMenuItem item
) {
2846 menuItems
.add(item
);
2848 TKeypress key
= item
.getKey();
2850 synchronized (accelerators
) {
2851 assert (accelerators
.get(key
) == null);
2852 accelerators
.put(key
.toLowerCase(), item
);
2858 * Disable one menu item.
2860 * @param id the menu item ID
2862 public final void disableMenuItem(final int id
) {
2863 for (TMenuItem item
: menuItems
) {
2864 if (item
.getId() == id
) {
2865 item
.setEnabled(false);
2871 * Disable the range of menu items with ID's between lower and upper,
2874 * @param lower the lowest menu item ID
2875 * @param upper the highest menu item ID
2877 public final void disableMenuItems(final int lower
, final int upper
) {
2878 for (TMenuItem item
: menuItems
) {
2879 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2880 item
.setEnabled(false);
2881 item
.getParent().activate(0);
2887 * Enable one menu item.
2889 * @param id the menu item ID
2891 public final void enableMenuItem(final int id
) {
2892 for (TMenuItem item
: menuItems
) {
2893 if (item
.getId() == id
) {
2894 item
.setEnabled(true);
2895 item
.getParent().activate(0);
2901 * Enable the range of menu items with ID's between lower and upper,
2904 * @param lower the lowest menu item ID
2905 * @param upper the highest menu item ID
2907 public final void enableMenuItems(final int lower
, final int upper
) {
2908 for (TMenuItem item
: menuItems
) {
2909 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2910 item
.setEnabled(true);
2911 item
.getParent().activate(0);
2917 * Get the menu item associated with this ID.
2919 * @param id the menu item ID
2920 * @return the menu item, or null if not found
2922 public final TMenuItem
getMenuItem(final int id
) {
2923 for (TMenuItem item
: menuItems
) {
2924 if (item
.getId() == id
) {
2932 * Recompute menu x positions based on their title length.
2934 public final void recomputeMenuX() {
2936 for (TMenu menu
: menus
) {
2939 x
+= menu
.getTitle().length() + 2;
2941 // Don't let the menu window exceed the screen width
2942 int rightEdge
= menu
.getX() + menu
.getWidth();
2943 if (rightEdge
> getScreen().getWidth()) {
2944 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2950 * Post an event to process.
2952 * @param event new event to add to the queue
2954 public final void postEvent(final TInputEvent event
) {
2955 synchronized (this) {
2956 synchronized (fillEventQueue
) {
2957 fillEventQueue
.add(event
);
2960 System
.err
.println(System
.currentTimeMillis() + " " +
2961 Thread
.currentThread() + " postEvent() wake up main");
2968 * Post an event to process and turn off the menu.
2970 * @param event new event to add to the queue
2972 public final void postMenuEvent(final TInputEvent event
) {
2973 synchronized (this) {
2974 synchronized (fillEventQueue
) {
2975 fillEventQueue
.add(event
);
2978 System
.err
.println(System
.currentTimeMillis() + " " +
2979 Thread
.currentThread() + " postMenuEvent() wake up main");
2987 * Add a sub-menu to the list of open sub-menus.
2989 * @param menu sub-menu
2991 public final void addSubMenu(final TMenu menu
) {
2996 * Convenience function to add a top-level menu.
2998 * @param title menu title
2999 * @return the new menu
3001 public final TMenu
addMenu(final String title
) {
3004 TMenu menu
= new TMenu(this, x
, y
, title
);
3011 * Convenience function to add a default tools (hamburger) menu.
3013 * @return the new menu
3015 public final TMenu
addToolMenu() {
3016 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
3017 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
3018 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
3019 toolMenu
.addDefaultItem(TMenu
.MID_CHANGE_FONT
);
3020 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
3021 getString("toolMenuStatus"));
3022 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3027 * Convenience function to add a default "File" menu.
3029 * @return the new menu
3031 public final TMenu
addFileMenu() {
3032 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
3033 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
3034 fileMenu
.addSeparator();
3035 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
3036 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
3037 getString("fileMenuStatus"));
3038 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3043 * Convenience function to add a default "Edit" menu.
3045 * @return the new menu
3047 public final TMenu
addEditMenu() {
3048 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
3049 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
3050 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
3051 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
3052 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
3053 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
3054 getString("editMenuStatus"));
3055 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3060 * Convenience function to add a default "Window" menu.
3062 * @return the new menu
3064 public final TMenu
addWindowMenu() {
3065 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
3066 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
3067 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
3068 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
3069 windowMenu
.addSeparator();
3070 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
3071 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
3072 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3073 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3074 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3075 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3076 getString("windowMenuStatus"));
3077 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3082 * Convenience function to add a default "Help" menu.
3084 * @return the new menu
3086 public final TMenu
addHelpMenu() {
3087 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3088 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3089 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3090 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3091 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3092 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3093 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3094 helpMenu
.addSeparator();
3095 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3096 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3097 getString("helpMenuStatus"));
3098 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3103 * Convenience function to add a default "Table" menu.
3105 * @return the new menu
3107 public final TMenu
addTableMenu() {
3108 TMenu tableMenu
= addMenu(i18n
.getString("tableMenuTitle"));
3109 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_COLUMN
, false);
3110 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_ROW
, false);
3111 tableMenu
.addSeparator();
3113 TSubMenu viewMenu
= tableMenu
.addSubMenu(i18n
.
3114 getString("tableSubMenuView"));
3115 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_ROW_LABELS
, false);
3116 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_COLUMN_LABELS
, false);
3117 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_ROW
, false);
3118 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_COLUMN
, false);
3120 TSubMenu borderMenu
= tableMenu
.addSubMenu(i18n
.
3121 getString("tableSubMenuBorders"));
3122 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_NONE
, false);
3123 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_ALL
, false);
3124 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_NONE
, false);
3125 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_ALL
, false);
3126 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_RIGHT
, false);
3127 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_LEFT
, false);
3128 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_TOP
, false);
3129 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_BOTTOM
, false);
3130 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_DOUBLE_BOTTOM
, false);
3131 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_THICK_BOTTOM
, false);
3132 TSubMenu deleteMenu
= tableMenu
.addSubMenu(i18n
.
3133 getString("tableSubMenuDelete"));
3134 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_LEFT
, false);
3135 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_UP
, false);
3136 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_ROW
, false);
3137 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_COLUMN
, false);
3138 TSubMenu insertMenu
= tableMenu
.addSubMenu(i18n
.
3139 getString("tableSubMenuInsert"));
3140 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_LEFT
, false);
3141 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_RIGHT
, false);
3142 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_ABOVE
, false);
3143 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_BELOW
, false);
3144 TSubMenu columnMenu
= tableMenu
.addSubMenu(i18n
.
3145 getString("tableSubMenuColumn"));
3146 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_NARROW
, false);
3147 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_WIDEN
, false);
3148 TSubMenu fileMenu
= tableMenu
.addSubMenu(i18n
.
3149 getString("tableSubMenuFile"));
3150 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_OPEN_CSV
, false);
3151 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_CSV
, false);
3152 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_TEXT
, false);
3154 TStatusBar statusBar
= tableMenu
.newStatusBar(i18n
.
3155 getString("tableMenuStatus"));
3156 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3160 // ------------------------------------------------------------------------
3161 // TTimer management ------------------------------------------------------
3162 // ------------------------------------------------------------------------
3165 * Get the amount of time I can sleep before missing a Timer tick.
3167 * @param timeout = initial (maximum) timeout in millis
3168 * @return number of milliseconds between now and the next timer event
3170 private long getSleepTime(final long timeout
) {
3171 Date now
= new Date();
3172 long nowTime
= now
.getTime();
3173 long sleepTime
= timeout
;
3175 synchronized (timers
) {
3176 for (TTimer timer
: timers
) {
3177 long nextTickTime
= timer
.getNextTick().getTime();
3178 if (nextTickTime
< nowTime
) {
3182 long timeDifference
= nextTickTime
- nowTime
;
3183 if (timeDifference
< sleepTime
) {
3184 sleepTime
= timeDifference
;
3189 assert (sleepTime
>= 0);
3190 assert (sleepTime
<= timeout
);
3195 * Convenience function to add a timer.
3197 * @param duration number of milliseconds to wait between ticks
3198 * @param recurring if true, re-schedule this timer after every tick
3199 * @param action function to call when button is pressed
3202 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3203 final TAction action
) {
3205 TTimer timer
= new TTimer(duration
, recurring
, action
);
3206 synchronized (timers
) {
3213 * Convenience function to remove a timer.
3215 * @param timer timer to remove
3217 public final void removeTimer(final TTimer timer
) {
3218 synchronized (timers
) {
3219 timers
.remove(timer
);
3223 // ------------------------------------------------------------------------
3224 // Other TWindow constructors ---------------------------------------------
3225 // ------------------------------------------------------------------------
3228 * Convenience function to spawn a message box.
3230 * @param title window title, will be centered along the top border
3231 * @param caption message to display. Use embedded newlines to get a
3233 * @return the new message box
3235 public final TMessageBox
messageBox(final String title
,
3236 final String caption
) {
3238 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3242 * Convenience function to spawn a message box.
3244 * @param title window title, will be centered along the top border
3245 * @param caption message to display. Use embedded newlines to get a
3247 * @param type one of the TMessageBox.Type constants. Default is
3249 * @return the new message box
3251 public final TMessageBox
messageBox(final String title
,
3252 final String caption
, final TMessageBox
.Type type
) {
3254 return new TMessageBox(this, title
, caption
, type
);
3258 * Convenience function to spawn an input box.
3260 * @param title window title, will be centered along the top border
3261 * @param caption message to display. Use embedded newlines to get a
3263 * @return the new input box
3265 public final TInputBox
inputBox(final String title
, final String caption
) {
3267 return new TInputBox(this, title
, caption
);
3271 * Convenience function to spawn an input box.
3273 * @param title window title, will be centered along the top border
3274 * @param caption message to display. Use embedded newlines to get a
3276 * @param text initial text to seed the field with
3277 * @return the new input box
3279 public final TInputBox
inputBox(final String title
, final String caption
,
3280 final String text
) {
3282 return new TInputBox(this, title
, caption
, text
);
3286 * Convenience function to spawn an input box.
3288 * @param title window title, will be centered along the top border
3289 * @param caption message to display. Use embedded newlines to get a
3291 * @param text initial text to seed the field with
3292 * @param type one of the Type constants. Default is Type.OK.
3293 * @return the new input box
3295 public final TInputBox
inputBox(final String title
, final String caption
,
3296 final String text
, final TInputBox
.Type type
) {
3298 return new TInputBox(this, title
, caption
, text
, type
);
3302 * Convenience function to open a terminal window.
3304 * @param x column relative to parent
3305 * @param y row relative to parent
3306 * @return the terminal new window
3308 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3309 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3313 * Convenience function to open a terminal window.
3315 * @param x column relative to parent
3316 * @param y row relative to parent
3317 * @param closeOnExit if true, close the window when the command exits
3318 * @return the terminal new window
3320 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3321 final boolean closeOnExit
) {
3323 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3327 * Convenience function to open a terminal window.
3329 * @param x column relative to parent
3330 * @param y row relative to parent
3331 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3332 * @return the terminal new window
3334 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3337 return new TTerminalWindow(this, x
, y
, flags
);
3341 * Convenience function to open a terminal window.
3343 * @param x column relative to parent
3344 * @param y row relative to parent
3345 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3346 * @param closeOnExit if true, close the window when the command exits
3347 * @return the terminal new window
3349 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3350 final int flags
, final boolean closeOnExit
) {
3352 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3356 * Convenience function to open a terminal window and execute a custom
3357 * command line inside it.
3359 * @param x column relative to parent
3360 * @param y row relative to parent
3361 * @param commandLine the command line to execute
3362 * @return the terminal new window
3364 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3365 final String commandLine
) {
3367 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3371 * Convenience function to open a terminal window and execute a custom
3372 * command line inside it.
3374 * @param x column relative to parent
3375 * @param y row relative to parent
3376 * @param commandLine the command line to execute
3377 * @param closeOnExit if true, close the window when the command exits
3378 * @return the terminal new window
3380 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3381 final String commandLine
, final boolean closeOnExit
) {
3383 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3387 * Convenience function to open a terminal window and execute a custom
3388 * command line inside it.
3390 * @param x column relative to parent
3391 * @param y row relative to parent
3392 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3393 * @param command the command line to execute
3394 * @return the terminal new window
3396 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3397 final int flags
, final String
[] command
) {
3399 return new TTerminalWindow(this, x
, y
, flags
, command
);
3403 * Convenience function to open a terminal window and execute a custom
3404 * command line inside it.
3406 * @param x column relative to parent
3407 * @param y row relative to parent
3408 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3409 * @param command the command line to execute
3410 * @param closeOnExit if true, close the window when the command exits
3411 * @return the terminal new window
3413 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3414 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3416 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3420 * Convenience function to open a terminal window and execute a custom
3421 * command line inside it.
3423 * @param x column relative to parent
3424 * @param y row relative to parent
3425 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3426 * @param commandLine the command line to execute
3427 * @return the terminal new window
3429 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3430 final int flags
, final String commandLine
) {
3432 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"));
3436 * Convenience function to open a terminal window and execute a custom
3437 * command line inside it.
3439 * @param x column relative to parent
3440 * @param y row relative to parent
3441 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3442 * @param commandLine the command line to execute
3443 * @param closeOnExit if true, close the window when the command exits
3444 * @return the terminal new window
3446 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3447 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3449 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"),
3454 * Convenience function to spawn an file open box.
3456 * @param path path of selected file
3457 * @return the result of the new file open box
3458 * @throws IOException if java.io operation throws
3460 public final String
fileOpenBox(final String path
) throws IOException
{
3462 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3463 return box
.getFilename();
3467 * Convenience function to spawn an file open box.
3469 * @param path path of selected file
3470 * @param type one of the Type constants
3471 * @return the result of the new file open box
3472 * @throws IOException if java.io operation throws
3474 public final String
fileOpenBox(final String path
,
3475 final TFileOpenBox
.Type type
) throws IOException
{
3477 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3478 return box
.getFilename();
3482 * Convenience function to spawn a file open box.
3484 * @param path path of selected file
3485 * @param type one of the Type constants
3486 * @param filter a string that files must match to be displayed
3487 * @return the result of the new file open box
3488 * @throws IOException of a java.io operation throws
3490 public final String
fileOpenBox(final String path
,
3491 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3493 ArrayList
<String
> filters
= new ArrayList
<String
>();
3494 filters
.add(filter
);
3496 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3497 return box
.getFilename();
3501 * Convenience function to spawn a file open box.
3503 * @param path path of selected file
3504 * @param type one of the Type constants
3505 * @param filters a list of strings that files must match to be displayed
3506 * @return the result of the new file open box
3507 * @throws IOException of a java.io operation throws
3509 public final String
fileOpenBox(final String path
,
3510 final TFileOpenBox
.Type type
,
3511 final List
<String
> filters
) throws IOException
{
3513 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3514 return box
.getFilename();
3518 * Convenience function to create a new window and make it active.
3519 * Window will be located at (0, 0).
3521 * @param title window title, will be centered along the top border
3522 * @param width width of window
3523 * @param height height of window
3524 * @return the new window
3526 public final TWindow
addWindow(final String title
, final int width
,
3529 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3534 * Convenience function to create a new window and make it active.
3535 * Window will be located at (0, 0).
3537 * @param title window title, will be centered along the top border
3538 * @param width width of window
3539 * @param height height of window
3540 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3541 * @return the new window
3543 public final TWindow
addWindow(final String title
,
3544 final int width
, final int height
, final int flags
) {
3546 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3551 * Convenience function to create a new window and make it active.
3553 * @param title window title, will be centered along the top border
3554 * @param x column relative to parent
3555 * @param y row relative to parent
3556 * @param width width of window
3557 * @param height height of window
3558 * @return the new window
3560 public final TWindow
addWindow(final String title
,
3561 final int x
, final int y
, final int width
, final int height
) {
3563 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3568 * Convenience function to create a new window and make it active.
3570 * @param title window title, will be centered along the top border
3571 * @param x column relative to parent
3572 * @param y row relative to parent
3573 * @param width width of window
3574 * @param height height of window
3575 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3576 * @return the new window
3578 public final TWindow
addWindow(final String title
,
3579 final int x
, final int y
, final int width
, final int height
,
3582 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);