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
) {
1538 System
.err
.printf("%d %s invertCell() %d %d\n",
1539 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1541 if (activeWindow
!= null) {
1542 System
.err
.println("activeWindow.hasHiddenMouse() " +
1543 activeWindow
.hasHiddenMouse());
1547 // If this cell is on top of a visible window that has requested a
1548 // hidden mouse, bail out.
1549 if ((activeWindow
!= null) && (activeMenu
== null)) {
1550 if ((activeWindow
.hasHiddenMouse() == true)
1551 && (x
> activeWindow
.getX())
1552 && (x
< activeWindow
.getX() + activeWindow
.getWidth() - 1)
1553 && (y
> activeWindow
.getY())
1554 && (y
< activeWindow
.getY() + activeWindow
.getHeight() - 1)
1560 Cell cell
= getScreen().getCharXY(x
, y
);
1561 if (cell
.isImage()) {
1564 if (cell
.getForeColorRGB() < 0) {
1565 cell
.setForeColor(cell
.getForeColor().invert());
1567 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1569 if (cell
.getBackColorRGB() < 0) {
1570 cell
.setBackColor(cell
.getBackColor().invert());
1572 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1575 getScreen().putCharXY(x
, y
, cell
);
1581 private void drawAll() {
1582 boolean menuIsActive
= false;
1585 System
.err
.printf("%d %s drawAll() enter\n",
1586 System
.currentTimeMillis(), Thread
.currentThread());
1589 // I don't think this does anything useful anymore...
1592 System
.err
.printf("%d %s drawAll() !repaint\n",
1593 System
.currentTimeMillis(), Thread
.currentThread());
1595 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1597 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1598 System
.currentTimeMillis(), Thread
.currentThread());
1601 // The only thing that has happened is the mouse moved.
1603 // Redraw the old cell at that position, and save the cell at
1604 // the new mouse position.
1606 System
.err
.printf("%d %s restoreImage() %d %d\n",
1607 System
.currentTimeMillis(), Thread
.currentThread(),
1608 oldDrawnMouseX
, oldDrawnMouseY
);
1610 oldDrawnMouseCell
.restoreImage();
1611 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1613 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1614 if (backend
instanceof ECMA48Backend
) {
1615 // Special case: the entire row containing the mouse has
1616 // to be re-drawn if it has any image data, AND any rows
1618 if (oldDrawnMouseY
!= mouseY
) {
1619 for (int i
= oldDrawnMouseY
; ;) {
1620 getScreen().unsetImageRow(i
);
1624 if (oldDrawnMouseY
< mouseY
) {
1631 getScreen().unsetImageRow(mouseY
);
1635 // Draw mouse at the new position.
1636 invertCell(mouseX
, mouseY
);
1638 oldDrawnMouseX
= mouseX
;
1639 oldDrawnMouseY
= mouseY
;
1641 if (getScreen().isDirty()) {
1642 backend
.flushScreen();
1648 System
.err
.printf("%d %s drawAll() REDRAW\n",
1649 System
.currentTimeMillis(), Thread
.currentThread());
1652 // If true, the cursor is not visible
1653 boolean cursor
= false;
1655 // Start with a clean screen
1656 getScreen().clear();
1659 if (desktop
!= null) {
1660 desktop
.drawChildren();
1663 // Draw each window in reverse Z order
1664 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1665 Collections
.sort(sorted
);
1666 TWindow topLevel
= null;
1667 if (sorted
.size() > 0) {
1668 topLevel
= sorted
.get(0);
1670 Collections
.reverse(sorted
);
1671 for (TWindow window
: sorted
) {
1672 if (window
.isShown()) {
1673 window
.drawChildren();
1677 // Draw the blank menubar line - reset the screen clipping first so
1678 // it won't trim it out.
1679 getScreen().resetClipping();
1680 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1681 theme
.getColor("tmenu"));
1682 // Now draw the menus.
1684 for (TMenu menu
: menus
) {
1685 CellAttributes menuColor
;
1686 CellAttributes menuMnemonicColor
;
1687 if (menu
.isActive()) {
1688 menuIsActive
= true;
1689 menuColor
= theme
.getColor("tmenu.highlighted");
1690 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1693 menuColor
= theme
.getColor("tmenu");
1694 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1696 // Draw the menu title
1697 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
1699 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1700 // Draw the highlight character
1701 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
1702 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1704 if (menu
.isActive()) {
1705 ((TWindow
) menu
).drawChildren();
1706 // Reset the screen clipping so we can draw the next title.
1707 getScreen().resetClipping();
1709 x
+= menu
.getTitle().length() + 2;
1712 for (TMenu menu
: subMenus
) {
1713 // Reset the screen clipping so we can draw the next sub-menu.
1714 getScreen().resetClipping();
1715 ((TWindow
) menu
).drawChildren();
1717 getScreen().resetClipping();
1719 // Draw the status bar of the top-level window
1720 TStatusBar statusBar
= null;
1721 if (topLevel
!= null) {
1722 statusBar
= topLevel
.getStatusBar();
1724 if (statusBar
!= null) {
1725 getScreen().resetClipping();
1726 statusBar
.setWidth(getScreen().getWidth());
1727 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1730 CellAttributes barColor
= new CellAttributes();
1731 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1732 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
1736 // Draw the mouse pointer
1738 System
.err
.printf("%d %s restoreImage() %d %d\n",
1739 System
.currentTimeMillis(), Thread
.currentThread(),
1740 oldDrawnMouseX
, oldDrawnMouseY
);
1742 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1743 if (backend
instanceof ECMA48Backend
) {
1744 // Special case: the entire row containing the mouse has to be
1745 // re-drawn if it has any image data, AND any rows in between.
1746 if (oldDrawnMouseY
!= mouseY
) {
1747 for (int i
= oldDrawnMouseY
; ;) {
1748 getScreen().unsetImageRow(i
);
1752 if (oldDrawnMouseY
< mouseY
) {
1759 getScreen().unsetImageRow(mouseY
);
1762 invertCell(mouseX
, mouseY
);
1763 oldDrawnMouseX
= mouseX
;
1764 oldDrawnMouseY
= mouseY
;
1766 // Place the cursor if it is visible
1767 if (!menuIsActive
) {
1768 TWidget activeWidget
= null;
1769 if (sorted
.size() > 0) {
1770 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
1771 if (activeWidget
.isCursorVisible()) {
1772 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
1773 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
1775 getScreen().putCursor(true,
1776 activeWidget
.getCursorAbsoluteX(),
1777 activeWidget
.getCursorAbsoluteY());
1780 // Turn off the cursor. Also place it at 0,0.
1781 getScreen().putCursor(false, 0, 0);
1790 getScreen().hideCursor();
1793 // Flush the screen contents
1794 if (getScreen().isDirty()) {
1796 System
.err
.printf("%d %s backend.flushScreen()\n",
1797 System
.currentTimeMillis(), Thread
.currentThread());
1799 backend
.flushScreen();
1806 * Force this application to exit.
1808 public void exit() {
1810 synchronized (this) {
1816 * Subclasses can use this hook to cleanup resources. Called as the last
1817 * step of TApplication.run().
1819 public void onExit() {
1820 // Default does nothing.
1823 // ------------------------------------------------------------------------
1824 // TWindow management -----------------------------------------------------
1825 // ------------------------------------------------------------------------
1828 * Return the total number of windows.
1830 * @return the total number of windows
1832 public final int windowCount() {
1833 return windows
.size();
1837 * Return the number of windows that are showing.
1839 * @return the number of windows that are showing on screen
1841 public final int shownWindowCount() {
1843 for (TWindow w
: windows
) {
1852 * Return the number of windows that are hidden.
1854 * @return the number of windows that are hidden
1856 public final int hiddenWindowCount() {
1858 for (TWindow w
: windows
) {
1867 * Check if a window instance is in this application's window list.
1869 * @param window window to look for
1870 * @return true if this window is in the list
1872 public final boolean hasWindow(final TWindow window
) {
1873 if (windows
.size() == 0) {
1876 for (TWindow w
: windows
) {
1878 assert (window
.getApplication() == this);
1886 * Activate a window: bring it to the top and have it receive events.
1888 * @param window the window to become the new active window
1890 public void activateWindow(final TWindow window
) {
1891 if (hasWindow(window
) == false) {
1893 * Someone has a handle to a window I don't have. Ignore this
1899 // Whatever window might be moving/dragging, stop it now.
1900 for (TWindow w
: windows
) {
1901 if (w
.inMovements()) {
1906 assert (windows
.size() > 0);
1908 if (window
.isHidden()) {
1909 // Unhiding will also activate.
1913 assert (window
.isShown());
1915 if (windows
.size() == 1) {
1916 assert (window
== windows
.get(0));
1917 if (activeWindow
== null) {
1918 activeWindow
= window
;
1920 activeWindow
.setActive(true);
1921 activeWindow
.onFocus();
1924 assert (window
.isActive());
1925 assert (activeWindow
== window
);
1929 if (activeWindow
== window
) {
1930 assert (window
.isActive());
1932 // Window is already active, do nothing.
1936 assert (!window
.isActive());
1937 if (activeWindow
!= null) {
1938 // TODO: see if this assertion is really necessary.
1939 // assert (activeWindow.getZ() == 0);
1941 activeWindow
.setActive(false);
1943 // Increment every window Z that is on top of window
1944 for (TWindow w
: windows
) {
1948 if (w
.getZ() < window
.getZ()) {
1949 w
.setZ(w
.getZ() + 1);
1953 // Unset activeWindow now before unfocus, so that a window
1954 // lifecycle change inside onUnfocus() doesn't call
1955 // switchWindow() and lead to a stack overflow.
1956 TWindow oldActiveWindow
= activeWindow
;
1957 activeWindow
= null;
1958 oldActiveWindow
.onUnfocus();
1960 activeWindow
= window
;
1961 activeWindow
.setZ(0);
1962 activeWindow
.setActive(true);
1963 activeWindow
.onFocus();
1970 * @param window the window to hide
1972 public void hideWindow(final TWindow window
) {
1973 if (hasWindow(window
) == false) {
1975 * Someone has a handle to a window I don't have. Ignore this
1981 // Whatever window might be moving/dragging, stop it now.
1982 for (TWindow w
: windows
) {
1983 if (w
.inMovements()) {
1988 assert (windows
.size() > 0);
1990 if (!window
.hidden
) {
1991 if (window
== activeWindow
) {
1992 if (shownWindowCount() > 1) {
1995 activeWindow
= null;
1996 window
.setActive(false);
2000 window
.hidden
= true;
2008 * @param window the window to show
2010 public void showWindow(final TWindow window
) {
2011 if (hasWindow(window
) == false) {
2013 * Someone has a handle to a window I don't have. Ignore this
2019 // Whatever window might be moving/dragging, stop it now.
2020 for (TWindow w
: windows
) {
2021 if (w
.inMovements()) {
2026 assert (windows
.size() > 0);
2028 if (window
.hidden
) {
2029 window
.hidden
= false;
2031 activateWindow(window
);
2036 * Close window. Note that the window's destructor is NOT called by this
2037 * method, instead the GC is assumed to do the cleanup.
2039 * @param window the window to remove
2041 public final void closeWindow(final TWindow window
) {
2042 if (hasWindow(window
) == false) {
2044 * Someone has a handle to a window I don't have. Ignore this
2050 // Let window know that it is about to be closed, while it is still
2051 // visible on screen.
2052 window
.onPreClose();
2054 synchronized (windows
) {
2055 // Whatever window might be moving/dragging, stop it now.
2056 for (TWindow w
: windows
) {
2057 if (w
.inMovements()) {
2062 int z
= window
.getZ();
2065 windows
.remove(window
);
2066 Collections
.sort(windows
);
2067 activeWindow
= null;
2069 boolean foundNextWindow
= false;
2071 for (TWindow w
: windows
) {
2075 // Do not activate a hidden window.
2080 if (foundNextWindow
== false) {
2081 foundNextWindow
= true;
2084 assert (activeWindow
== null);
2096 // Perform window cleanup
2099 // Check if we are closing a TMessageBox or similar
2100 if (secondaryEventReceiver
!= null) {
2101 assert (secondaryEventHandler
!= null);
2103 // Do not send events to the secondaryEventReceiver anymore, the
2104 // window is closed.
2105 secondaryEventReceiver
= null;
2107 // Wake the secondary thread, it will wake the primary as it
2109 synchronized (secondaryEventHandler
) {
2110 secondaryEventHandler
.notify();
2114 // Permit desktop to be active if it is the only thing left.
2115 if (desktop
!= null) {
2116 if (windows
.size() == 0) {
2117 desktop
.setActive(true);
2123 * Switch to the next window.
2125 * @param forward if true, then switch to the next window in the list,
2126 * otherwise switch to the previous window in the list
2128 public final void switchWindow(final boolean forward
) {
2129 // Only switch if there are multiple visible windows
2130 if (shownWindowCount() < 2) {
2133 assert (activeWindow
!= null);
2135 synchronized (windows
) {
2136 // Whatever window might be moving/dragging, stop it now.
2137 for (TWindow w
: windows
) {
2138 if (w
.inMovements()) {
2143 // Swap z/active between active window and the next in the list
2144 int activeWindowI
= -1;
2145 for (int i
= 0; i
< windows
.size(); i
++) {
2146 if (windows
.get(i
) == activeWindow
) {
2147 assert (activeWindow
.isActive());
2151 assert (!windows
.get(0).isActive());
2154 assert (activeWindowI
>= 0);
2156 // Do not switch if a window is modal
2157 if (activeWindow
.isModal()) {
2161 int nextWindowI
= activeWindowI
;
2165 nextWindowI
%= windows
.size();
2168 if (nextWindowI
< 0) {
2169 nextWindowI
= windows
.size() - 1;
2173 if (windows
.get(nextWindowI
).isShown()) {
2174 activateWindow(windows
.get(nextWindowI
));
2178 } // synchronized (windows)
2183 * Add a window to my window list and make it active. Note package
2186 * @param window new window to add
2188 final void addWindowToApplication(final TWindow window
) {
2190 // Do not add menu windows to the window list.
2191 if (window
instanceof TMenu
) {
2195 // Do not add the desktop to the window list.
2196 if (window
instanceof TDesktop
) {
2200 synchronized (windows
) {
2201 if (windows
.contains(window
)) {
2202 throw new IllegalArgumentException("Window " + window
+
2203 " is already in window list");
2206 // Whatever window might be moving/dragging, stop it now.
2207 for (TWindow w
: windows
) {
2208 if (w
.inMovements()) {
2213 // Do not allow a modal window to spawn a non-modal window. If a
2214 // modal window is active, then this window will become modal
2216 if (modalWindowActive()) {
2217 window
.flags
|= TWindow
.MODAL
;
2218 window
.flags
|= TWindow
.CENTERED
;
2219 window
.hidden
= false;
2221 if (window
.isShown()) {
2222 for (TWindow w
: windows
) {
2227 w
.setZ(w
.getZ() + 1);
2230 windows
.add(window
);
2231 if (window
.isShown()) {
2232 activeWindow
= window
;
2233 activeWindow
.setZ(0);
2234 activeWindow
.setActive(true);
2235 activeWindow
.onFocus();
2238 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2239 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2240 && (smartWindowPlacement
== true)
2243 doSmartPlacement(window
);
2247 // Desktop cannot be active over any other window.
2248 if (desktop
!= null) {
2249 desktop
.setActive(false);
2254 * Check if there is a system-modal window on top.
2256 * @return true if the active window is modal
2258 private boolean modalWindowActive() {
2259 if (windows
.size() == 0) {
2263 for (TWindow w
: windows
) {
2273 * Check if there is a window with overridden menu flag on top.
2275 * @return true if the active window is overriding the menu
2277 private boolean overrideMenuWindowActive() {
2278 if (activeWindow
!= null) {
2279 if (activeWindow
.hasOverriddenMenu()) {
2288 * Close all open windows.
2290 private void closeAllWindows() {
2291 // Don't do anything if we are in the menu
2292 if (activeMenu
!= null) {
2295 while (windows
.size() > 0) {
2296 closeWindow(windows
.get(0));
2301 * Re-layout the open windows as non-overlapping tiles. This produces
2302 * almost the same results as Turbo Pascal 7.0's IDE.
2304 private void tileWindows() {
2305 synchronized (windows
) {
2306 // Don't do anything if we are in the menu
2307 if (activeMenu
!= null) {
2310 int z
= windows
.size();
2316 a
= (int)(Math
.sqrt(z
));
2320 if (((a
* b
) + c
) == z
) {
2328 int newWidth
= (getScreen().getWidth() / a
);
2329 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2330 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2332 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2333 Collections
.sort(sorted
);
2334 Collections
.reverse(sorted
);
2335 for (int i
= 0; i
< sorted
.size(); i
++) {
2336 int logicalX
= i
/ b
;
2337 int logicalY
= i
% b
;
2338 if (i
>= ((a
- 1) * b
)) {
2340 logicalY
= i
- ((a
- 1) * b
);
2343 TWindow w
= sorted
.get(i
);
2344 int oldWidth
= w
.getWidth();
2345 int oldHeight
= w
.getHeight();
2347 w
.setX(logicalX
* newWidth
);
2348 w
.setWidth(newWidth
);
2349 if (i
>= ((a
- 1) * b
)) {
2350 w
.setY((logicalY
* newHeight2
) + 1);
2351 w
.setHeight(newHeight2
);
2353 w
.setY((logicalY
* newHeight1
) + 1);
2354 w
.setHeight(newHeight1
);
2356 if ((w
.getWidth() != oldWidth
)
2357 || (w
.getHeight() != oldHeight
)
2359 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2360 w
.getWidth(), w
.getHeight()));
2367 * Re-layout the open windows as overlapping cascaded windows.
2369 private void cascadeWindows() {
2370 synchronized (windows
) {
2371 // Don't do anything if we are in the menu
2372 if (activeMenu
!= null) {
2377 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2378 Collections
.sort(sorted
);
2379 Collections
.reverse(sorted
);
2380 for (TWindow window
: sorted
) {
2385 if (x
> getScreen().getWidth()) {
2388 if (y
>= getScreen().getHeight()) {
2396 * Place a window to minimize its overlap with other windows.
2398 * @param window the window to place
2400 public final void doSmartPlacement(final TWindow window
) {
2401 // This is a pretty dumb algorithm, but seems to work. The hardest
2402 // part is computing these "overlap" values seeking a minimum average
2405 int yMin
= desktopTop
;
2406 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2407 int yMax
= desktopBottom
- window
.getHeight() + 1;
2415 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2416 // No work to do, bail out.
2420 // Compute the overlap matrix without the new window.
2421 int width
= getScreen().getWidth();
2422 int height
= getScreen().getHeight();
2423 int overlapMatrix
[][] = new int[width
][height
];
2424 for (TWindow w
: windows
) {
2428 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2435 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2442 overlapMatrix
[x
][y
]++;
2447 long oldOverlapTotal
= 0;
2448 long oldOverlapN
= 0;
2449 for (int x
= 0; x
< width
; x
++) {
2450 for (int y
= 0; y
< height
; y
++) {
2451 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2452 if (overlapMatrix
[x
][y
] > 0) {
2459 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2460 boolean first
= true;
2461 int windowX
= window
.getX();
2462 int windowY
= window
.getY();
2464 // For each possible (x, y) position for the new window, compute a
2465 // new overlap matrix.
2466 for (int x
= xMin
; x
< xMax
; x
++) {
2467 for (int y
= yMin
; y
< yMax
; y
++) {
2469 // Start with the matrix minus this window.
2470 int newMatrix
[][] = new int[width
][height
];
2471 for (int mx
= 0; mx
< width
; mx
++) {
2472 for (int my
= 0; my
< height
; my
++) {
2473 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2477 // Add this window's values to the new overlap matrix.
2478 long newOverlapTotal
= 0;
2479 long newOverlapN
= 0;
2480 // Start by adding each new cell.
2481 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2485 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2489 newMatrix
[wx
][wy
]++;
2492 // Now figure out the new value for total coverage.
2493 for (int mx
= 0; mx
< width
; mx
++) {
2494 for (int my
= 0; my
< height
; my
++) {
2495 newOverlapTotal
+= newMatrix
[x
][y
];
2496 if (newMatrix
[mx
][my
] > 0) {
2501 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2504 // First time: just record what we got.
2505 oldOverlapAvg
= newOverlapAvg
;
2508 // All other times: pick a new best (x, y) and save the
2510 if (newOverlapAvg
< oldOverlapAvg
) {
2513 oldOverlapAvg
= newOverlapAvg
;
2517 } // for (int x = xMin; x < xMax; x++)
2519 } // for (int y = yMin; y < yMax; y++)
2521 // Finally, set the window's new coordinates.
2522 window
.setX(windowX
);
2523 window
.setY(windowY
);
2526 // ------------------------------------------------------------------------
2527 // TMenu management -------------------------------------------------------
2528 // ------------------------------------------------------------------------
2531 * Check if a mouse event would hit either the active menu or any open
2534 * @param mouse mouse event
2535 * @return true if the mouse would hit the active menu or an open
2538 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2539 assert (activeMenu
!= null);
2540 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2541 Collections
.reverse(menus
);
2542 for (TMenu menu
: menus
) {
2543 if (menu
.mouseWouldHit(mouse
)) {
2547 return activeMenu
.mouseWouldHit(mouse
);
2551 * See if we need to switch window or activate the menu based on
2554 * @param mouse mouse event
2556 private void checkSwitchFocus(final TMouseEvent mouse
) {
2558 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2559 && (activeMenu
!= null)
2560 && (mouse
.getAbsoluteY() != 0)
2561 && (!mouseOnMenu(mouse
))
2563 // They clicked outside the active menu, turn it off
2564 activeMenu
.setActive(false);
2566 for (TMenu menu
: subMenus
) {
2567 menu
.setActive(false);
2573 // See if they hit the menu bar
2574 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2575 && (mouse
.isMouse1())
2576 && (!modalWindowActive())
2577 && (!overrideMenuWindowActive())
2578 && (mouse
.getAbsoluteY() == 0)
2581 for (TMenu menu
: subMenus
) {
2582 menu
.setActive(false);
2586 // They selected the menu, go activate it
2587 for (TMenu menu
: menus
) {
2588 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2589 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2590 + menu
.getTitle().length() + 2)
2592 menu
.setActive(true);
2595 menu
.setActive(false);
2601 // See if they hit the menu bar
2602 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2603 && (mouse
.isMouse1())
2604 && (activeMenu
!= null)
2605 && (mouse
.getAbsoluteY() == 0)
2608 TMenu oldMenu
= activeMenu
;
2609 for (TMenu menu
: subMenus
) {
2610 menu
.setActive(false);
2614 // See if we should switch menus
2615 for (TMenu menu
: menus
) {
2616 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2617 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2618 + menu
.getTitle().length() + 2)
2620 menu
.setActive(true);
2624 if (oldMenu
!= activeMenu
) {
2625 // They switched menus
2626 oldMenu
.setActive(false);
2631 // If a menu is still active, don't switch windows
2632 if (activeMenu
!= null) {
2636 // Only switch if there are multiple windows
2637 if (windows
.size() < 2) {
2641 if (((focusFollowsMouse
== true)
2642 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2643 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2645 synchronized (windows
) {
2646 Collections
.sort(windows
);
2647 if (windows
.get(0).isModal()) {
2648 // Modal windows don't switch
2652 for (TWindow window
: windows
) {
2653 assert (!window
.isModal());
2655 if (window
.isHidden()) {
2656 assert (!window
.isActive());
2660 if (window
.mouseWouldHit(mouse
)) {
2661 if (window
== windows
.get(0)) {
2662 // Clicked on the same window, nothing to do
2663 assert (window
.isActive());
2667 // We will be switching to another window
2668 assert (windows
.get(0).isActive());
2669 assert (windows
.get(0) == activeWindow
);
2670 assert (!window
.isActive());
2671 if (activeWindow
!= null) {
2672 activeWindow
.onUnfocus();
2673 activeWindow
.setActive(false);
2674 activeWindow
.setZ(window
.getZ());
2676 activeWindow
= window
;
2678 window
.setActive(true);
2685 // Clicked on the background, nothing to do
2689 // Nothing to do: this isn't a mouse up, or focus isn't following
2695 * Turn off the menu.
2697 public final void closeMenu() {
2698 if (activeMenu
!= null) {
2699 activeMenu
.setActive(false);
2701 for (TMenu menu
: subMenus
) {
2702 menu
.setActive(false);
2709 * Get a (shallow) copy of the menu list.
2711 * @return a copy of the menu list
2713 public final List
<TMenu
> getAllMenus() {
2714 return new ArrayList
<TMenu
>(menus
);
2718 * Add a top-level menu to the list.
2720 * @param menu the menu to add
2721 * @throws IllegalArgumentException if the menu is already used in
2722 * another TApplication
2724 public final void addMenu(final TMenu menu
) {
2725 if ((menu
.getApplication() != null)
2726 && (menu
.getApplication() != this)
2728 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2729 "part of application " + menu
.getApplication());
2737 * Remove a top-level menu from the list.
2739 * @param menu the menu to remove
2740 * @throws IllegalArgumentException if the menu is already used in
2741 * another TApplication
2743 public final void removeMenu(final TMenu menu
) {
2744 if ((menu
.getApplication() != null)
2745 && (menu
.getApplication() != this)
2747 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2748 "part of application " + menu
.getApplication());
2756 * Turn off a sub-menu.
2758 public final void closeSubMenu() {
2759 assert (activeMenu
!= null);
2760 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2761 assert (item
!= null);
2762 item
.setActive(false);
2763 subMenus
.remove(subMenus
.size() - 1);
2767 * Switch to the next menu.
2769 * @param forward if true, then switch to the next menu in the list,
2770 * otherwise switch to the previous menu in the list
2772 public final void switchMenu(final boolean forward
) {
2773 assert (activeMenu
!= null);
2775 for (TMenu menu
: subMenus
) {
2776 menu
.setActive(false);
2780 for (int i
= 0; i
< menus
.size(); i
++) {
2781 if (activeMenu
== menus
.get(i
)) {
2783 if (i
< menus
.size() - 1) {
2792 i
= menus
.size() - 1;
2795 activeMenu
.setActive(false);
2796 activeMenu
= menus
.get(i
);
2797 activeMenu
.setActive(true);
2804 * Add a menu item to the global list. If it has a keyboard accelerator,
2805 * that will be added the global hash.
2807 * @param item the menu item
2809 public final void addMenuItem(final TMenuItem item
) {
2810 menuItems
.add(item
);
2812 TKeypress key
= item
.getKey();
2814 synchronized (accelerators
) {
2815 assert (accelerators
.get(key
) == null);
2816 accelerators
.put(key
.toLowerCase(), item
);
2822 * Disable one menu item.
2824 * @param id the menu item ID
2826 public final void disableMenuItem(final int id
) {
2827 for (TMenuItem item
: menuItems
) {
2828 if (item
.getId() == id
) {
2829 item
.setEnabled(false);
2835 * Disable the range of menu items with ID's between lower and upper,
2838 * @param lower the lowest menu item ID
2839 * @param upper the highest menu item ID
2841 public final void disableMenuItems(final int lower
, final int upper
) {
2842 for (TMenuItem item
: menuItems
) {
2843 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2844 item
.setEnabled(false);
2845 item
.getParent().activate(0);
2851 * Enable one menu item.
2853 * @param id the menu item ID
2855 public final void enableMenuItem(final int id
) {
2856 for (TMenuItem item
: menuItems
) {
2857 if (item
.getId() == id
) {
2858 item
.setEnabled(true);
2859 item
.getParent().activate(0);
2865 * Enable the range of menu items with ID's between lower and upper,
2868 * @param lower the lowest menu item ID
2869 * @param upper the highest menu item ID
2871 public final void enableMenuItems(final int lower
, final int upper
) {
2872 for (TMenuItem item
: menuItems
) {
2873 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2874 item
.setEnabled(true);
2875 item
.getParent().activate(0);
2881 * Get the menu item associated with this ID.
2883 * @param id the menu item ID
2884 * @return the menu item, or null if not found
2886 public final TMenuItem
getMenuItem(final int id
) {
2887 for (TMenuItem item
: menuItems
) {
2888 if (item
.getId() == id
) {
2896 * Recompute menu x positions based on their title length.
2898 public final void recomputeMenuX() {
2900 for (TMenu menu
: menus
) {
2903 x
+= menu
.getTitle().length() + 2;
2905 // Don't let the menu window exceed the screen width
2906 int rightEdge
= menu
.getX() + menu
.getWidth();
2907 if (rightEdge
> getScreen().getWidth()) {
2908 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2914 * Post an event to process.
2916 * @param event new event to add to the queue
2918 public final void postEvent(final TInputEvent event
) {
2919 synchronized (this) {
2920 synchronized (fillEventQueue
) {
2921 fillEventQueue
.add(event
);
2924 System
.err
.println(System
.currentTimeMillis() + " " +
2925 Thread
.currentThread() + " postEvent() wake up main");
2932 * Post an event to process and turn off the menu.
2934 * @param event new event to add to the queue
2936 public final void postMenuEvent(final TInputEvent event
) {
2937 synchronized (this) {
2938 synchronized (fillEventQueue
) {
2939 fillEventQueue
.add(event
);
2942 System
.err
.println(System
.currentTimeMillis() + " " +
2943 Thread
.currentThread() + " postMenuEvent() wake up main");
2951 * Add a sub-menu to the list of open sub-menus.
2953 * @param menu sub-menu
2955 public final void addSubMenu(final TMenu menu
) {
2960 * Convenience function to add a top-level menu.
2962 * @param title menu title
2963 * @return the new menu
2965 public final TMenu
addMenu(final String title
) {
2968 TMenu menu
= new TMenu(this, x
, y
, title
);
2975 * Convenience function to add a default tools (hamburger) menu.
2977 * @return the new menu
2979 public final TMenu
addToolMenu() {
2980 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
2981 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
2982 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
2983 toolMenu
.addDefaultItem(TMenu
.MID_CHANGE_FONT
);
2984 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
2985 getString("toolMenuStatus"));
2986 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2991 * Convenience function to add a default "File" menu.
2993 * @return the new menu
2995 public final TMenu
addFileMenu() {
2996 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
2997 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2998 fileMenu
.addSeparator();
2999 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
3000 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
3001 getString("fileMenuStatus"));
3002 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3007 * Convenience function to add a default "Edit" menu.
3009 * @return the new menu
3011 public final TMenu
addEditMenu() {
3012 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
3013 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
3014 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
3015 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
3016 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
3017 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
3018 getString("editMenuStatus"));
3019 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3024 * Convenience function to add a default "Window" menu.
3026 * @return the new menu
3028 public final TMenu
addWindowMenu() {
3029 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
3030 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
3031 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
3032 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
3033 windowMenu
.addSeparator();
3034 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
3035 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
3036 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3037 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3038 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3039 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3040 getString("windowMenuStatus"));
3041 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3046 * Convenience function to add a default "Help" menu.
3048 * @return the new menu
3050 public final TMenu
addHelpMenu() {
3051 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3052 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3053 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3054 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3055 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3056 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3057 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3058 helpMenu
.addSeparator();
3059 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3060 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3061 getString("helpMenuStatus"));
3062 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3067 * Convenience function to add a default "Table" menu.
3069 * @return the new menu
3071 public final TMenu
addTableMenu() {
3072 TMenu tableMenu
= addMenu(i18n
.getString("tableMenuTitle"));
3073 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_COLUMN
, false);
3074 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_ROW
, false);
3075 tableMenu
.addSeparator();
3077 TSubMenu viewMenu
= tableMenu
.addSubMenu(i18n
.
3078 getString("tableSubMenuView"));
3079 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_ROW_LABELS
, false);
3080 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_COLUMN_LABELS
, false);
3081 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_ROW
, false);
3082 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_COLUMN
, false);
3084 TSubMenu borderMenu
= tableMenu
.addSubMenu(i18n
.
3085 getString("tableSubMenuBorders"));
3086 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_NONE
, false);
3087 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_ALL
, false);
3088 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_NONE
, false);
3089 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_ALL
, false);
3090 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_RIGHT
, false);
3091 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_LEFT
, false);
3092 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_TOP
, false);
3093 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_BOTTOM
, false);
3094 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_DOUBLE_BOTTOM
, false);
3095 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_THICK_BOTTOM
, false);
3096 TSubMenu deleteMenu
= tableMenu
.addSubMenu(i18n
.
3097 getString("tableSubMenuDelete"));
3098 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_LEFT
, false);
3099 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_UP
, false);
3100 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_ROW
, false);
3101 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_COLUMN
, false);
3102 TSubMenu insertMenu
= tableMenu
.addSubMenu(i18n
.
3103 getString("tableSubMenuInsert"));
3104 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_LEFT
, false);
3105 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_RIGHT
, false);
3106 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_ABOVE
, false);
3107 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_BELOW
, false);
3108 TSubMenu columnMenu
= tableMenu
.addSubMenu(i18n
.
3109 getString("tableSubMenuColumn"));
3110 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_NARROW
, false);
3111 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_WIDEN
, false);
3112 TSubMenu fileMenu
= tableMenu
.addSubMenu(i18n
.
3113 getString("tableSubMenuFile"));
3114 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_OPEN_CSV
, false);
3115 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_CSV
, false);
3116 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_TEXT
, false);
3118 TStatusBar statusBar
= tableMenu
.newStatusBar(i18n
.
3119 getString("tableMenuStatus"));
3120 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3124 // ------------------------------------------------------------------------
3125 // TTimer management ------------------------------------------------------
3126 // ------------------------------------------------------------------------
3129 * Get the amount of time I can sleep before missing a Timer tick.
3131 * @param timeout = initial (maximum) timeout in millis
3132 * @return number of milliseconds between now and the next timer event
3134 private long getSleepTime(final long timeout
) {
3135 Date now
= new Date();
3136 long nowTime
= now
.getTime();
3137 long sleepTime
= timeout
;
3139 synchronized (timers
) {
3140 for (TTimer timer
: timers
) {
3141 long nextTickTime
= timer
.getNextTick().getTime();
3142 if (nextTickTime
< nowTime
) {
3146 long timeDifference
= nextTickTime
- nowTime
;
3147 if (timeDifference
< sleepTime
) {
3148 sleepTime
= timeDifference
;
3153 assert (sleepTime
>= 0);
3154 assert (sleepTime
<= timeout
);
3159 * Convenience function to add a timer.
3161 * @param duration number of milliseconds to wait between ticks
3162 * @param recurring if true, re-schedule this timer after every tick
3163 * @param action function to call when button is pressed
3166 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3167 final TAction action
) {
3169 TTimer timer
= new TTimer(duration
, recurring
, action
);
3170 synchronized (timers
) {
3177 * Convenience function to remove a timer.
3179 * @param timer timer to remove
3181 public final void removeTimer(final TTimer timer
) {
3182 synchronized (timers
) {
3183 timers
.remove(timer
);
3187 // ------------------------------------------------------------------------
3188 // Other TWindow constructors ---------------------------------------------
3189 // ------------------------------------------------------------------------
3192 * Convenience function to spawn a message box.
3194 * @param title window title, will be centered along the top border
3195 * @param caption message to display. Use embedded newlines to get a
3197 * @return the new message box
3199 public final TMessageBox
messageBox(final String title
,
3200 final String caption
) {
3202 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3206 * Convenience function to spawn a message box.
3208 * @param title window title, will be centered along the top border
3209 * @param caption message to display. Use embedded newlines to get a
3211 * @param type one of the TMessageBox.Type constants. Default is
3213 * @return the new message box
3215 public final TMessageBox
messageBox(final String title
,
3216 final String caption
, final TMessageBox
.Type type
) {
3218 return new TMessageBox(this, title
, caption
, type
);
3222 * Convenience function to spawn an input box.
3224 * @param title window title, will be centered along the top border
3225 * @param caption message to display. Use embedded newlines to get a
3227 * @return the new input box
3229 public final TInputBox
inputBox(final String title
, final String caption
) {
3231 return new TInputBox(this, title
, caption
);
3235 * Convenience function to spawn an input box.
3237 * @param title window title, will be centered along the top border
3238 * @param caption message to display. Use embedded newlines to get a
3240 * @param text initial text to seed the field with
3241 * @return the new input box
3243 public final TInputBox
inputBox(final String title
, final String caption
,
3244 final String text
) {
3246 return new TInputBox(this, title
, caption
, text
);
3250 * Convenience function to spawn an input box.
3252 * @param title window title, will be centered along the top border
3253 * @param caption message to display. Use embedded newlines to get a
3255 * @param text initial text to seed the field with
3256 * @param type one of the Type constants. Default is Type.OK.
3257 * @return the new input box
3259 public final TInputBox
inputBox(final String title
, final String caption
,
3260 final String text
, final TInputBox
.Type type
) {
3262 return new TInputBox(this, title
, caption
, text
, type
);
3266 * Convenience function to open a terminal window.
3268 * @param x column relative to parent
3269 * @param y row relative to parent
3270 * @return the terminal new window
3272 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3273 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3277 * Convenience function to open a terminal window.
3279 * @param x column relative to parent
3280 * @param y row relative to parent
3281 * @param closeOnExit if true, close the window when the command exits
3282 * @return the terminal new window
3284 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3285 final boolean closeOnExit
) {
3287 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3291 * Convenience function to open a terminal window.
3293 * @param x column relative to parent
3294 * @param y row relative to parent
3295 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3296 * @return the terminal new window
3298 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3301 return new TTerminalWindow(this, x
, y
, flags
);
3305 * Convenience function to open a terminal window.
3307 * @param x column relative to parent
3308 * @param y row relative to parent
3309 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3310 * @param closeOnExit if true, close the window when the command exits
3311 * @return the terminal new window
3313 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3314 final int flags
, final boolean closeOnExit
) {
3316 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3320 * Convenience function to open a terminal window and execute a custom
3321 * command line inside it.
3323 * @param x column relative to parent
3324 * @param y row relative to parent
3325 * @param commandLine the command line to execute
3326 * @return the terminal new window
3328 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3329 final String commandLine
) {
3331 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3335 * Convenience function to open a terminal window and execute a custom
3336 * command line inside it.
3338 * @param x column relative to parent
3339 * @param y row relative to parent
3340 * @param commandLine the command line to execute
3341 * @param closeOnExit if true, close the window when the command exits
3342 * @return the terminal new window
3344 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3345 final String commandLine
, final boolean closeOnExit
) {
3347 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3351 * Convenience function to open a terminal window and execute a custom
3352 * command line inside it.
3354 * @param x column relative to parent
3355 * @param y row relative to parent
3356 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3357 * @param command the command line to execute
3358 * @return the terminal new window
3360 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3361 final int flags
, final String
[] command
) {
3363 return new TTerminalWindow(this, x
, y
, flags
, command
);
3367 * Convenience function to open a terminal window and execute a custom
3368 * command line inside it.
3370 * @param x column relative to parent
3371 * @param y row relative to parent
3372 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3373 * @param command the command line to execute
3374 * @param closeOnExit if true, close the window when the command exits
3375 * @return the terminal new window
3377 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3378 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3380 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3384 * Convenience function to open a terminal window and execute a custom
3385 * command line inside it.
3387 * @param x column relative to parent
3388 * @param y row relative to parent
3389 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3390 * @param commandLine the command line to execute
3391 * @return the terminal new window
3393 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3394 final int flags
, final String commandLine
) {
3396 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"));
3400 * Convenience function to open a terminal window and execute a custom
3401 * command line inside it.
3403 * @param x column relative to parent
3404 * @param y row relative to parent
3405 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3406 * @param commandLine the command line to execute
3407 * @param closeOnExit if true, close the window when the command exits
3408 * @return the terminal new window
3410 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3411 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3413 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"),
3418 * Convenience function to spawn an file open box.
3420 * @param path path of selected file
3421 * @return the result of the new file open box
3422 * @throws IOException if java.io operation throws
3424 public final String
fileOpenBox(final String path
) throws IOException
{
3426 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3427 return box
.getFilename();
3431 * Convenience function to spawn an file open box.
3433 * @param path path of selected file
3434 * @param type one of the Type constants
3435 * @return the result of the new file open box
3436 * @throws IOException if java.io operation throws
3438 public final String
fileOpenBox(final String path
,
3439 final TFileOpenBox
.Type type
) throws IOException
{
3441 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3442 return box
.getFilename();
3446 * Convenience function to spawn a file open box.
3448 * @param path path of selected file
3449 * @param type one of the Type constants
3450 * @param filter a string that files must match to be displayed
3451 * @return the result of the new file open box
3452 * @throws IOException of a java.io operation throws
3454 public final String
fileOpenBox(final String path
,
3455 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3457 ArrayList
<String
> filters
= new ArrayList
<String
>();
3458 filters
.add(filter
);
3460 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3461 return box
.getFilename();
3465 * Convenience function to spawn a file open box.
3467 * @param path path of selected file
3468 * @param type one of the Type constants
3469 * @param filters a list of strings that files must match to be displayed
3470 * @return the result of the new file open box
3471 * @throws IOException of a java.io operation throws
3473 public final String
fileOpenBox(final String path
,
3474 final TFileOpenBox
.Type type
,
3475 final List
<String
> filters
) throws IOException
{
3477 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3478 return box
.getFilename();
3482 * Convenience function to create a new window and make it active.
3483 * Window will be located at (0, 0).
3485 * @param title window title, will be centered along the top border
3486 * @param width width of window
3487 * @param height height of window
3488 * @return the new window
3490 public final TWindow
addWindow(final String title
, final int width
,
3493 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3498 * Convenience function to create a new window and make it active.
3499 * Window will be located at (0, 0).
3501 * @param title window title, will be centered along the top border
3502 * @param width width of window
3503 * @param height height of window
3504 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3505 * @return the new window
3507 public final TWindow
addWindow(final String title
,
3508 final int width
, final int height
, final int flags
) {
3510 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3515 * Convenience function to create a new window and make it active.
3517 * @param title window title, will be centered along the top border
3518 * @param x column relative to parent
3519 * @param y row relative to parent
3520 * @param width width of window
3521 * @param height height of window
3522 * @return the new window
3524 public final TWindow
addWindow(final String title
,
3525 final int x
, final int y
, final int width
, final int height
) {
3527 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3532 * Convenience function to create a new window and make it active.
3534 * @param title window title, will be centered along the top border
3535 * @param x column relative to parent
3536 * @param y row relative to parent
3537 * @param width width of window
3538 * @param height height of window
3539 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3540 * @return the new window
3542 public final TWindow
addWindow(final String title
,
3543 final int x
, final int y
, final int width
, final int height
,
3546 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);