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 images that might be displayed. Note package private access.
289 private List
<TImage
> images
;
292 * The list of commands to run before the next I/O check.
294 private List
<Runnable
> invokeLaters
= new LinkedList
<Runnable
>();
297 * WidgetEventHandler is the main event consumer loop. There are at most
298 * two such threads in existence: the primary for normal case and a
299 * secondary that is used for TMessageBox, TInputBox, and similar.
301 private class WidgetEventHandler
implements Runnable
{
303 * The main application.
305 private TApplication application
;
308 * Whether or not this WidgetEventHandler is the primary or secondary
311 private boolean primary
= true;
314 * Public constructor.
316 * @param application the main application
317 * @param primary if true, this is the primary event handler thread
319 public WidgetEventHandler(final TApplication application
,
320 final boolean primary
) {
322 this.application
= application
;
323 this.primary
= primary
;
330 // Wrap everything in a try, so that if we go belly up we can let
331 // the user have their terminal back.
334 } catch (Throwable t
) {
335 this.application
.restoreConsole();
337 this.application
.exit();
344 private void runImpl() {
345 boolean first
= true;
348 while (!application
.quit
) {
350 // Wait until application notifies me
351 while (!application
.quit
) {
353 synchronized (application
.drainEventQueue
) {
354 if (application
.drainEventQueue
.size() > 0) {
363 timeout
= application
.getSleepTime(1000);
367 // A timer needs to fire, break out.
372 System
.err
.printf("%d %s %s %s sleep %d millis\n",
373 System
.currentTimeMillis(), this,
374 primary ?
"primary" : "secondary",
375 Thread
.currentThread(), timeout
);
378 synchronized (this) {
383 System
.err
.printf("%d %s %s %s AWAKE\n",
384 System
.currentTimeMillis(), this,
385 primary ?
"primary" : "secondary",
386 Thread
.currentThread());
390 && (application
.secondaryEventReceiver
== null)
392 // Secondary thread, emergency exit. If we got
393 // here then something went wrong with the
394 // handoff between yield() and closeWindow().
395 synchronized (application
.primaryEventHandler
) {
396 application
.primaryEventHandler
.notify();
398 application
.secondaryEventHandler
= null;
399 throw new RuntimeException("secondary exited " +
403 } catch (InterruptedException e
) {
406 } // while (!application.quit)
408 // Pull all events off the queue
410 TInputEvent event
= null;
411 synchronized (application
.drainEventQueue
) {
412 if (application
.drainEventQueue
.size() == 0) {
415 event
= application
.drainEventQueue
.remove(0);
418 // We will have an event to process, so repaint the
419 // screen at the end.
420 application
.repaint
= true;
423 primaryHandleEvent(event
);
425 secondaryHandleEvent(event
);
428 && (application
.secondaryEventReceiver
== null)
430 // Secondary thread, time to exit.
432 // Eliminate my reference so that wakeEventHandler()
433 // resumes working on the primary.
434 application
.secondaryEventHandler
= null;
436 // We are ready to exit, wake up the primary thread.
437 // Remember that it is currently sleeping inside its
438 // primaryHandleEvent().
439 synchronized (application
.primaryEventHandler
) {
440 application
.primaryEventHandler
.notify();
449 // Fire timers, update screen.
451 application
.finishEventProcessing();
454 } // while (true) (main runnable loop)
458 // ------------------------------------------------------------------------
459 // Constructors -----------------------------------------------------------
460 // ------------------------------------------------------------------------
463 * Public constructor.
465 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
467 * @param windowWidth the number of text columns to start with
468 * @param windowHeight the number of text rows to start with
469 * @param fontSize the size in points
470 * @throws UnsupportedEncodingException if an exception is thrown when
471 * creating the InputStreamReader
473 public TApplication(final BackendType backendType
, final int windowWidth
,
474 final int windowHeight
, final int fontSize
)
475 throws UnsupportedEncodingException
{
477 switch (backendType
) {
479 backend
= new SwingBackend(this, windowWidth
, windowHeight
,
485 backend
= new ECMA48Backend(this, null, null, windowWidth
,
486 windowHeight
, fontSize
);
489 throw new IllegalArgumentException("Invalid backend type: "
496 * Public constructor.
498 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
500 * @throws UnsupportedEncodingException if an exception is thrown when
501 * creating the InputStreamReader
503 public TApplication(final BackendType backendType
)
504 throws UnsupportedEncodingException
{
506 switch (backendType
) {
508 // The default SwingBackend is 80x25, 20 pt font. If you want to
509 // change that, you can pass the extra arguments to the
510 // SwingBackend constructor here. For example, if you wanted
511 // 90x30, 16 pt font:
513 // backend = new SwingBackend(this, 90, 30, 16);
514 backend
= new SwingBackend(this);
519 backend
= new ECMA48Backend(this, null, null);
522 throw new IllegalArgumentException("Invalid backend type: "
529 * Public constructor. The backend type will be BackendType.ECMA48.
531 * @param input an InputStream connected to the remote user, or null for
532 * System.in. If System.in is used, then on non-Windows systems it will
533 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
534 * mode. input is always converted to a Reader with UTF-8 encoding.
535 * @param output an OutputStream connected to the remote user, or null
536 * for System.out. output is always converted to a Writer with UTF-8
538 * @throws UnsupportedEncodingException if an exception is thrown when
539 * creating the InputStreamReader
541 public TApplication(final InputStream input
,
542 final OutputStream output
) throws UnsupportedEncodingException
{
544 backend
= new ECMA48Backend(this, input
, output
);
549 * Public constructor. The backend type will be BackendType.ECMA48.
551 * @param input the InputStream underlying 'reader'. Its available()
552 * method is used to determine if reader.read() will block or not.
553 * @param reader a Reader connected to the remote user.
554 * @param writer a PrintWriter connected to the remote user.
555 * @param setRawMode if true, set System.in into raw mode with stty.
556 * This should in general not be used. It is here solely for Demo3,
557 * which uses System.in.
558 * @throws IllegalArgumentException if input, reader, or writer are null.
560 public TApplication(final InputStream input
, final Reader reader
,
561 final PrintWriter writer
, final boolean setRawMode
) {
563 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
568 * Public constructor. The backend type will be BackendType.ECMA48.
570 * @param input the InputStream underlying 'reader'. Its available()
571 * method is used to determine if reader.read() will block or not.
572 * @param reader a Reader connected to the remote user.
573 * @param writer a PrintWriter connected to the remote user.
574 * @throws IllegalArgumentException if input, reader, or writer are null.
576 public TApplication(final InputStream input
, final Reader reader
,
577 final PrintWriter writer
) {
579 this(input
, reader
, writer
, false);
583 * Public constructor. This hook enables use with new non-Jexer
586 * @param backend a Backend that is already ready to go.
588 public TApplication(final Backend backend
) {
589 this.backend
= backend
;
590 backend
.setListener(this);
595 * Finish construction once the backend is set.
597 private void TApplicationImpl() {
598 theme
= new ColorTheme();
599 desktopBottom
= getScreen().getHeight() - 1;
600 fillEventQueue
= new LinkedList
<TInputEvent
>();
601 drainEventQueue
= new LinkedList
<TInputEvent
>();
602 windows
= new LinkedList
<TWindow
>();
603 menus
= new ArrayList
<TMenu
>();
604 subMenus
= new ArrayList
<TMenu
>();
605 timers
= new LinkedList
<TTimer
>();
606 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
607 menuItems
= new LinkedList
<TMenuItem
>();
608 desktop
= new TDesktop(this);
609 images
= new LinkedList
<TImage
>();
611 // Special case: the Swing backend needs to have a timer to drive its
613 if ((backend
instanceof SwingBackend
)
614 || (backend
instanceof MultiBackend
)
616 // Default to 500 millis, unless a SwingBackend has its own
619 if (backend
instanceof SwingBackend
) {
620 millis
= ((SwingBackend
) backend
).getBlinkMillis();
623 addTimer(millis
, true,
626 TApplication
.this.doRepaint();
634 // ------------------------------------------------------------------------
635 // Runnable ---------------------------------------------------------------
636 // ------------------------------------------------------------------------
639 * Run this application until it exits.
642 // System.err.println("*** TApplication.run() begins ***");
644 // Start the main consumer thread
645 primaryEventHandler
= new WidgetEventHandler(this, true);
646 (new Thread(primaryEventHandler
)).start();
651 synchronized (this) {
652 boolean doWait
= false;
654 if (!backend
.hasEvents()) {
655 synchronized (fillEventQueue
) {
656 if (fillEventQueue
.size() == 0) {
663 // No I/O to dispatch, so wait until the backend
667 System
.err
.println(System
.currentTimeMillis() +
668 " " + Thread
.currentThread() + " MAIN sleep");
674 System
.err
.println(System
.currentTimeMillis() +
675 " " + Thread
.currentThread() + " MAIN AWAKE");
677 } catch (InterruptedException e
) {
678 // I'm awake and don't care why, let's see what's
679 // going on out there.
683 } // synchronized (this)
685 synchronized (fillEventQueue
) {
686 // Pull any pending I/O events
687 backend
.getEvents(fillEventQueue
);
689 // Dispatch each event to the appropriate handler, one at a
692 TInputEvent event
= null;
693 if (fillEventQueue
.size() == 0) {
696 event
= fillEventQueue
.remove(0);
697 metaHandleEvent(event
);
701 // Wake a consumer thread if we have any pending events.
702 if (drainEventQueue
.size() > 0) {
708 // Shutdown the event consumer threads
709 if (secondaryEventHandler
!= null) {
710 synchronized (secondaryEventHandler
) {
711 secondaryEventHandler
.notify();
714 if (primaryEventHandler
!= null) {
715 synchronized (primaryEventHandler
) {
716 primaryEventHandler
.notify();
720 // Shutdown the user I/O thread(s)
723 // Close all the windows. This gives them an opportunity to release
727 // Give the overarching application an opportunity to release
731 // System.err.println("*** TApplication.run() exits ***");
734 // ------------------------------------------------------------------------
735 // Event handlers ---------------------------------------------------------
736 // ------------------------------------------------------------------------
739 * Method that TApplication subclasses can override to handle menu or
740 * posted command events.
742 * @param command command event
743 * @return if true, this event was consumed
745 protected boolean onCommand(final TCommandEvent command
) {
746 // Default: handle cmExit
747 if (command
.equals(cmExit
)) {
748 if (messageBox(i18n
.getString("exitDialogTitle"),
749 i18n
.getString("exitDialogText"),
750 TMessageBox
.Type
.YESNO
).isYes()) {
757 if (command
.equals(cmShell
)) {
758 openTerminal(0, 0, TWindow
.RESIZABLE
);
762 if (command
.equals(cmTile
)) {
766 if (command
.equals(cmCascade
)) {
770 if (command
.equals(cmCloseAll
)) {
775 if (command
.equals(cmMenu
)) {
776 if (!modalWindowActive() && (activeMenu
== null)) {
777 if (menus
.size() > 0) {
778 menus
.get(0).setActive(true);
779 activeMenu
= menus
.get(0);
789 * Method that TApplication subclasses can override to handle menu
792 * @param menu menu event
793 * @return if true, this event was consumed
795 protected boolean onMenu(final TMenuEvent menu
) {
797 // Default: handle MID_EXIT
798 if (menu
.getId() == TMenu
.MID_EXIT
) {
799 if (messageBox(i18n
.getString("exitDialogTitle"),
800 i18n
.getString("exitDialogText"),
801 TMessageBox
.Type
.YESNO
).isYes()) {
808 if (menu
.getId() == TMenu
.MID_SHELL
) {
809 openTerminal(0, 0, TWindow
.RESIZABLE
);
813 if (menu
.getId() == TMenu
.MID_TILE
) {
817 if (menu
.getId() == TMenu
.MID_CASCADE
) {
821 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
825 if (menu
.getId() == TMenu
.MID_ABOUT
) {
829 if (menu
.getId() == TMenu
.MID_REPAINT
) {
830 getScreen().clearPhysical();
834 if (menu
.getId() == TMenu
.MID_VIEW_IMAGE
) {
838 if (menu
.getId() == TMenu
.MID_CHANGE_FONT
) {
839 new TFontChooserWindow(this);
846 * Method that TApplication subclasses can override to handle keystrokes.
848 * @param keypress keystroke event
849 * @return if true, this event was consumed
851 protected boolean onKeypress(final TKeypressEvent keypress
) {
852 // Default: only menu shortcuts
854 // Process Alt-F, Alt-E, etc. menu shortcut keys
855 if (!keypress
.getKey().isFnKey()
856 && keypress
.getKey().isAlt()
857 && !keypress
.getKey().isCtrl()
858 && (activeMenu
== null)
859 && !modalWindowActive()
862 assert (subMenus
.size() == 0);
864 for (TMenu menu
: menus
) {
865 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
866 == Character
.toLowerCase(keypress
.getKey().getChar())
869 menu
.setActive(true);
879 * Process background events, and update the screen.
881 private void finishEventProcessing() {
883 System
.err
.printf(System
.currentTimeMillis() + " " +
884 Thread
.currentThread() + " finishEventProcessing()\n");
887 // Process timers and call doIdle()'s
891 synchronized (getScreen()) {
896 System
.err
.printf(System
.currentTimeMillis() + " " +
897 Thread
.currentThread() + " finishEventProcessing() END\n");
902 * Peek at certain application-level events, add to eventQueue, and wake
903 * up the consuming Thread.
905 * @param event the input event to consume
907 private void metaHandleEvent(final TInputEvent event
) {
910 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
911 event
)); System
.err
.flush();
915 // Do no more processing if the application is already trying
920 // Special application-wide events -------------------------------
923 if (event
instanceof TCommandEvent
) {
924 TCommandEvent command
= (TCommandEvent
) event
;
925 if (command
.equals(cmAbort
)) {
931 synchronized (drainEventQueue
) {
933 if (event
instanceof TResizeEvent
) {
934 TResizeEvent resize
= (TResizeEvent
) event
;
935 synchronized (getScreen()) {
936 getScreen().setDimensions(resize
.getWidth(),
938 desktopBottom
= getScreen().getHeight() - 1;
944 if (desktop
!= null) {
945 desktop
.setDimensions(0, 0, resize
.getWidth(),
946 resize
.getHeight() - 1);
947 desktop
.onResize(resize
);
950 // Change menu edges if needed.
953 // We are dirty, redraw the screen.
957 System.err.println("New screen: " + resize.getWidth() +
958 " x " + resize.getHeight());
963 // Put into the main queue
964 drainEventQueue
.add(event
);
969 * Dispatch one event to the appropriate widget or application-level
970 * event handler. This is the primary event handler, it has the normal
971 * application-wide event handling.
973 * @param event the input event to consume
974 * @see #secondaryHandleEvent(TInputEvent event)
976 private void primaryHandleEvent(final TInputEvent event
) {
979 System
.err
.printf("%s primaryHandleEvent: %s\n",
980 Thread
.currentThread(), event
);
982 TMouseEvent doubleClick
= null;
984 // Special application-wide events -----------------------------------
986 // Peek at the mouse position
987 if (event
instanceof TMouseEvent
) {
988 TMouseEvent mouse
= (TMouseEvent
) event
;
989 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
992 mouseX
= mouse
.getX();
993 mouseY
= mouse
.getY();
995 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
996 && (!mouse
.isMouseWheelUp())
997 && (!mouse
.isMouseWheelDown())
999 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1002 // This is a double-click.
1003 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1005 mouse
.getX(), mouse
.getY(),
1006 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1007 mouse
.isMouse1(), mouse
.isMouse2(),
1009 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1012 // The first click of a potential double-click.
1013 lastMouseUpTime
= mouse
.getTime().getTime();
1018 // See if we need to switch focus to another window or the menu
1019 checkSwitchFocus((TMouseEvent
) event
);
1022 // Handle menu events
1023 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1024 TMenu menu
= activeMenu
;
1026 if (event
instanceof TMouseEvent
) {
1027 TMouseEvent mouse
= (TMouseEvent
) event
;
1029 while (subMenus
.size() > 0) {
1030 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1031 if (subMenu
.mouseWouldHit(mouse
)) {
1034 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1035 && (!mouse
.isMouse1())
1036 && (!mouse
.isMouse2())
1037 && (!mouse
.isMouse3())
1038 && (!mouse
.isMouseWheelUp())
1039 && (!mouse
.isMouseWheelDown())
1043 // We navigated away from a sub-menu, so close it
1047 // Convert the mouse relative x/y to menu coordinates
1048 assert (mouse
.getX() == mouse
.getAbsoluteX());
1049 assert (mouse
.getY() == mouse
.getAbsoluteY());
1050 if (subMenus
.size() > 0) {
1051 menu
= subMenus
.get(subMenus
.size() - 1);
1053 mouse
.setX(mouse
.getX() - menu
.getX());
1054 mouse
.setY(mouse
.getY() - menu
.getY());
1056 menu
.handleEvent(event
);
1060 if (event
instanceof TKeypressEvent
) {
1061 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1063 // See if this key matches an accelerator, and is not being
1064 // shortcutted by the active window, and if so dispatch the menu
1066 boolean windowWillShortcut
= false;
1067 if (activeWindow
!= null) {
1068 assert (activeWindow
.isShown());
1069 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1070 // We do not process this key, it will be passed to the
1072 windowWillShortcut
= true;
1076 if (!windowWillShortcut
&& !modalWindowActive()) {
1077 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1078 TMenuItem item
= null;
1079 synchronized (accelerators
) {
1080 item
= accelerators
.get(keypressLowercase
);
1083 if (item
.isEnabled()) {
1084 // Let the menu item dispatch
1090 // Handle the keypress
1091 if (onKeypress(keypress
)) {
1097 if (event
instanceof TCommandEvent
) {
1098 if (onCommand((TCommandEvent
) event
)) {
1103 if (event
instanceof TMenuEvent
) {
1104 if (onMenu((TMenuEvent
) event
)) {
1109 // Dispatch events to the active window -------------------------------
1110 boolean dispatchToDesktop
= true;
1111 TWindow window
= activeWindow
;
1112 if (window
!= null) {
1113 assert (window
.isActive());
1114 assert (window
.isShown());
1115 if (event
instanceof TMouseEvent
) {
1116 TMouseEvent mouse
= (TMouseEvent
) event
;
1117 // Convert the mouse relative x/y to window coordinates
1118 assert (mouse
.getX() == mouse
.getAbsoluteX());
1119 assert (mouse
.getY() == mouse
.getAbsoluteY());
1120 mouse
.setX(mouse
.getX() - window
.getX());
1121 mouse
.setY(mouse
.getY() - window
.getY());
1123 if (doubleClick
!= null) {
1124 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1125 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1128 if (window
.mouseWouldHit(mouse
)) {
1129 dispatchToDesktop
= false;
1131 } else if (event
instanceof TKeypressEvent
) {
1132 dispatchToDesktop
= false;
1136 System
.err
.printf("TApplication dispatch event: %s\n",
1139 window
.handleEvent(event
);
1140 if (doubleClick
!= null) {
1141 window
.handleEvent(doubleClick
);
1144 if (dispatchToDesktop
) {
1145 // This event is fair game for the desktop to process.
1146 if (desktop
!= null) {
1147 desktop
.handleEvent(event
);
1148 if (doubleClick
!= null) {
1149 desktop
.handleEvent(doubleClick
);
1156 * Dispatch one event to the appropriate widget or application-level
1157 * event handler. This is the secondary event handler used by certain
1158 * special dialogs (currently TMessageBox and TFileOpenBox).
1160 * @param event the input event to consume
1161 * @see #primaryHandleEvent(TInputEvent event)
1163 private void secondaryHandleEvent(final TInputEvent event
) {
1164 TMouseEvent doubleClick
= null;
1167 System
.err
.printf("%s secondaryHandleEvent: %s\n",
1168 Thread
.currentThread(), event
);
1171 // Peek at the mouse position
1172 if (event
instanceof TMouseEvent
) {
1173 TMouseEvent mouse
= (TMouseEvent
) event
;
1174 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1177 mouseX
= mouse
.getX();
1178 mouseY
= mouse
.getY();
1180 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1181 && (!mouse
.isMouseWheelUp())
1182 && (!mouse
.isMouseWheelDown())
1184 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1187 // This is a double-click.
1188 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1190 mouse
.getX(), mouse
.getY(),
1191 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1192 mouse
.isMouse1(), mouse
.isMouse2(),
1194 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1197 // The first click of a potential double-click.
1198 lastMouseUpTime
= mouse
.getTime().getTime();
1204 secondaryEventReceiver
.handleEvent(event
);
1205 // Note that it is possible for secondaryEventReceiver to be null
1206 // now, because its handleEvent() might have finished out on the
1207 // secondary thread. So put any extra processing inside a null
1209 if (secondaryEventReceiver
!= null) {
1210 if (doubleClick
!= null) {
1211 secondaryEventReceiver
.handleEvent(doubleClick
);
1217 * Enable a widget to override the primary event thread.
1219 * @param widget widget that will receive events
1221 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1223 System
.err
.println(System
.currentTimeMillis() +
1224 " enableSecondaryEventReceiver()");
1227 assert (secondaryEventReceiver
== null);
1228 assert (secondaryEventHandler
== null);
1229 assert ((widget
instanceof TMessageBox
)
1230 || (widget
instanceof TFileOpenBox
));
1231 secondaryEventReceiver
= widget
;
1232 secondaryEventHandler
= new WidgetEventHandler(this, false);
1234 (new Thread(secondaryEventHandler
)).start();
1238 * Yield to the secondary thread.
1240 public final void yield() {
1242 System
.err
.printf(System
.currentTimeMillis() + " " +
1243 Thread
.currentThread() + " yield()\n");
1246 assert (secondaryEventReceiver
!= null);
1248 while (secondaryEventReceiver
!= null) {
1249 synchronized (primaryEventHandler
) {
1251 primaryEventHandler
.wait();
1252 } catch (InterruptedException e
) {
1260 * Do stuff when there is no user input.
1262 private void doIdle() {
1264 System
.err
.printf(System
.currentTimeMillis() + " " +
1265 Thread
.currentThread() + " doIdle()\n");
1268 synchronized (timers
) {
1271 System
.err
.printf(System
.currentTimeMillis() + " " +
1272 Thread
.currentThread() + " doIdle() 2\n");
1275 // Run any timers that have timed out
1276 Date now
= new Date();
1277 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1278 for (TTimer timer
: timers
) {
1279 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1280 // Something might change, so repaint the screen.
1283 if (timer
.recurring
) {
1284 keepTimers
.add(timer
);
1287 keepTimers
.add(timer
);
1291 timers
.addAll(keepTimers
);
1295 for (TWindow window
: windows
) {
1298 if (desktop
!= null) {
1302 // Run any invokeLaters
1303 synchronized (invokeLaters
) {
1304 for (Runnable invoke
: invokeLaters
) {
1307 invokeLaters
.clear();
1313 * Wake the sleeping active event handler.
1315 private void wakeEventHandler() {
1320 if (secondaryEventHandler
!= null) {
1321 synchronized (secondaryEventHandler
) {
1322 secondaryEventHandler
.notify();
1325 assert (primaryEventHandler
!= null);
1326 synchronized (primaryEventHandler
) {
1327 primaryEventHandler
.notify();
1332 // ------------------------------------------------------------------------
1333 // TApplication -----------------------------------------------------------
1334 // ------------------------------------------------------------------------
1337 * Place a command on the run queue, and run it before the next round of
1340 * @param command the command to run later
1342 public void invokeLater(final Runnable command
) {
1343 synchronized (invokeLaters
) {
1344 invokeLaters
.add(command
);
1350 * Restore the console to sane defaults. This is meant to be used for
1351 * improper exits (e.g. a caught exception in main()), and should not be
1352 * necessary for normal program termination.
1354 public void restoreConsole() {
1355 if (backend
!= null) {
1356 if (backend
instanceof ECMA48Backend
) {
1365 * @return the Backend
1367 public final Backend
getBackend() {
1374 * @return the Screen
1376 public final Screen
getScreen() {
1377 if (backend
instanceof TWindowBackend
) {
1378 // We are being rendered to a TWindow. We can't use its
1379 // getScreen() method because that is how it is rendering to a
1380 // hardware backend somewhere. Instead use its getOtherScreen()
1382 return ((TWindowBackend
) backend
).getOtherScreen();
1384 return backend
.getScreen();
1389 * Get the color theme.
1393 public final ColorTheme
getTheme() {
1398 * Repaint the screen on the next update.
1400 public void doRepaint() {
1406 * Get Y coordinate of the top edge of the desktop.
1408 * @return Y coordinate of the top edge of the desktop
1410 public final int getDesktopTop() {
1415 * Get Y coordinate of the bottom edge of the desktop.
1417 * @return Y coordinate of the bottom edge of the desktop
1419 public final int getDesktopBottom() {
1420 return desktopBottom
;
1424 * Set the TDesktop instance.
1426 * @param desktop a TDesktop instance, or null to remove the one that is
1429 public final void setDesktop(final TDesktop desktop
) {
1430 if (this.desktop
!= null) {
1431 this.desktop
.onClose();
1433 this.desktop
= desktop
;
1437 * Get the TDesktop instance.
1439 * @return the desktop, or null if it is not set
1441 public final TDesktop
getDesktop() {
1446 * Get the current active window.
1448 * @return the active window, or null if it is not set
1450 public final TWindow
getActiveWindow() {
1451 return activeWindow
;
1455 * Get a (shallow) copy of the window list.
1457 * @return a copy of the list of windows for this application
1459 public final List
<TWindow
> getAllWindows() {
1460 List
<TWindow
> result
= new ArrayList
<TWindow
>();
1461 result
.addAll(windows
);
1466 * Get focusFollowsMouse flag.
1468 * @return true if focus follows mouse: windows automatically raised if
1469 * the mouse passes over them
1471 public boolean getFocusFollowsMouse() {
1472 return focusFollowsMouse
;
1476 * Set focusFollowsMouse flag.
1478 * @param focusFollowsMouse if true, focus follows mouse: windows
1479 * automatically raised if the mouse passes over them
1481 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
1482 this.focusFollowsMouse
= focusFollowsMouse
;
1486 * Display the about dialog.
1488 protected void showAboutDialog() {
1489 String version
= getClass().getPackage().getImplementationVersion();
1490 if (version
== null) {
1491 // This is Java 9+, use a hardcoded string here.
1494 messageBox(i18n
.getString("aboutDialogTitle"),
1495 MessageFormat
.format(i18n
.getString("aboutDialogText"), version
),
1496 TMessageBox
.Type
.OK
);
1500 * Handle the Tool | Open image menu item.
1502 private void openImage() {
1504 List
<String
> filters
= new ArrayList
<String
>();
1505 filters
.add("^.*\\.[Jj][Pp][Gg]$");
1506 filters
.add("^.*\\.[Jj][Pp][Ee][Gg]$");
1507 filters
.add("^.*\\.[Pp][Nn][Gg]$");
1508 filters
.add("^.*\\.[Gg][Ii][Ff]$");
1509 filters
.add("^.*\\.[Bb][Mm][Pp]$");
1510 String filename
= fileOpenBox(".", TFileOpenBox
.Type
.OPEN
, filters
);
1511 if (filename
!= null) {
1512 new TImageWindow(this, new File(filename
));
1514 } catch (IOException e
) {
1515 // Show this exception to the user.
1516 new TExceptionDialog(this, e
);
1521 * Check if application is still running.
1523 * @return true if the application is running
1525 public final boolean isRunning() {
1532 // ------------------------------------------------------------------------
1533 // Screen refresh loop ----------------------------------------------------
1534 // ------------------------------------------------------------------------
1537 * Invert the cell color at a position. This is used to track the mouse.
1539 * @param x column position
1540 * @param y row position
1542 private void invertCell(final int x
, final int y
) {
1544 System
.err
.printf("%d %s invertCell() %d %d\n",
1545 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1547 if (activeWindow
!= null) {
1548 System
.err
.println("activeWindow.hasHiddenMouse() " +
1549 activeWindow
.hasHiddenMouse());
1553 // If this cell is on top of a visible window that has requested a
1554 // hidden mouse, bail out.
1555 if ((activeWindow
!= null) && (activeMenu
== null)) {
1556 if ((activeWindow
.hasHiddenMouse() == true)
1557 && (x
> activeWindow
.getX())
1558 && (x
< activeWindow
.getX() + activeWindow
.getWidth() - 1)
1559 && (y
> activeWindow
.getY())
1560 && (y
< activeWindow
.getY() + activeWindow
.getHeight() - 1)
1566 Cell cell
= getScreen().getCharXY(x
, y
);
1567 if (cell
.isImage()) {
1570 if (cell
.getForeColorRGB() < 0) {
1571 cell
.setForeColor(cell
.getForeColor().invert());
1573 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1575 if (cell
.getBackColorRGB() < 0) {
1576 cell
.setBackColor(cell
.getBackColor().invert());
1578 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1581 getScreen().putCharXY(x
, y
, cell
);
1587 private void drawAll() {
1588 boolean menuIsActive
= false;
1591 System
.err
.printf("%d %s drawAll() enter\n",
1592 System
.currentTimeMillis(), Thread
.currentThread());
1595 // I don't think this does anything useful anymore...
1598 System
.err
.printf("%d %s drawAll() !repaint\n",
1599 System
.currentTimeMillis(), Thread
.currentThread());
1601 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1603 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1604 System
.currentTimeMillis(), Thread
.currentThread());
1607 // The only thing that has happened is the mouse moved.
1609 // Redraw the old cell at that position, and save the cell at
1610 // the new mouse position.
1612 System
.err
.printf("%d %s restoreImage() %d %d\n",
1613 System
.currentTimeMillis(), Thread
.currentThread(),
1614 oldDrawnMouseX
, oldDrawnMouseY
);
1616 oldDrawnMouseCell
.restoreImage();
1617 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1619 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1620 if ((images
.size() > 0) && (backend
instanceof ECMA48Backend
)) {
1621 // Special case: the entire row containing the mouse has
1622 // to be re-drawn if it has any image data, AND any rows
1624 if (oldDrawnMouseY
!= mouseY
) {
1625 for (int i
= oldDrawnMouseY
; ;) {
1626 getScreen().unsetImageRow(i
);
1630 if (oldDrawnMouseY
< mouseY
) {
1637 getScreen().unsetImageRow(mouseY
);
1641 // Draw mouse at the new position.
1642 invertCell(mouseX
, mouseY
);
1644 oldDrawnMouseX
= mouseX
;
1645 oldDrawnMouseY
= mouseY
;
1647 if ((images
.size() > 0) || getScreen().isDirty()) {
1648 backend
.flushScreen();
1654 System
.err
.printf("%d %s drawAll() REDRAW\n",
1655 System
.currentTimeMillis(), Thread
.currentThread());
1658 // If true, the cursor is not visible
1659 boolean cursor
= false;
1661 // Start with a clean screen
1662 getScreen().clear();
1665 if (desktop
!= null) {
1666 desktop
.drawChildren();
1669 // Draw each window in reverse Z order
1670 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1671 Collections
.sort(sorted
);
1672 TWindow topLevel
= null;
1673 if (sorted
.size() > 0) {
1674 topLevel
= sorted
.get(0);
1676 Collections
.reverse(sorted
);
1677 for (TWindow window
: sorted
) {
1678 if (window
.isShown()) {
1679 window
.drawChildren();
1683 // Draw the blank menubar line - reset the screen clipping first so
1684 // it won't trim it out.
1685 getScreen().resetClipping();
1686 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1687 theme
.getColor("tmenu"));
1688 // Now draw the menus.
1690 for (TMenu menu
: menus
) {
1691 CellAttributes menuColor
;
1692 CellAttributes menuMnemonicColor
;
1693 if (menu
.isActive()) {
1694 menuIsActive
= true;
1695 menuColor
= theme
.getColor("tmenu.highlighted");
1696 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1699 menuColor
= theme
.getColor("tmenu");
1700 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1702 // Draw the menu title
1703 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
1705 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1706 // Draw the highlight character
1707 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
1708 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1710 if (menu
.isActive()) {
1711 ((TWindow
) menu
).drawChildren();
1712 // Reset the screen clipping so we can draw the next title.
1713 getScreen().resetClipping();
1715 x
+= menu
.getTitle().length() + 2;
1718 for (TMenu menu
: subMenus
) {
1719 // Reset the screen clipping so we can draw the next sub-menu.
1720 getScreen().resetClipping();
1721 ((TWindow
) menu
).drawChildren();
1723 getScreen().resetClipping();
1725 // Draw the status bar of the top-level window
1726 TStatusBar statusBar
= null;
1727 if (topLevel
!= null) {
1728 statusBar
= topLevel
.getStatusBar();
1730 if (statusBar
!= null) {
1731 getScreen().resetClipping();
1732 statusBar
.setWidth(getScreen().getWidth());
1733 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1736 CellAttributes barColor
= new CellAttributes();
1737 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1738 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
1742 // Draw the mouse pointer
1744 System
.err
.printf("%d %s restoreImage() %d %d\n",
1745 System
.currentTimeMillis(), Thread
.currentThread(),
1746 oldDrawnMouseX
, oldDrawnMouseY
);
1748 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1749 if ((images
.size() > 0) && (backend
instanceof ECMA48Backend
)) {
1750 // Special case: the entire row containing the mouse has to be
1751 // re-drawn if it has any image data, AND any rows in between.
1752 if (oldDrawnMouseY
!= mouseY
) {
1753 for (int i
= oldDrawnMouseY
; ;) {
1754 getScreen().unsetImageRow(i
);
1758 if (oldDrawnMouseY
< mouseY
) {
1765 getScreen().unsetImageRow(mouseY
);
1768 invertCell(mouseX
, mouseY
);
1769 oldDrawnMouseX
= mouseX
;
1770 oldDrawnMouseY
= mouseY
;
1772 // Place the cursor if it is visible
1773 if (!menuIsActive
) {
1774 TWidget activeWidget
= null;
1775 if (sorted
.size() > 0) {
1776 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
1777 if (activeWidget
.isCursorVisible()) {
1778 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
1779 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
1781 getScreen().putCursor(true,
1782 activeWidget
.getCursorAbsoluteX(),
1783 activeWidget
.getCursorAbsoluteY());
1786 // Turn off the cursor. Also place it at 0,0.
1787 getScreen().putCursor(false, 0, 0);
1796 getScreen().hideCursor();
1799 // Flush the screen contents
1800 if ((images
.size() > 0) || getScreen().isDirty()) {
1802 System
.err
.printf("%d %s backend.flushScreen()\n",
1803 System
.currentTimeMillis(), Thread
.currentThread());
1805 backend
.flushScreen();
1812 * Force this application to exit.
1814 public void exit() {
1816 synchronized (this) {
1822 * Subclasses can use this hook to cleanup resources. Called as the last
1823 * step of TApplication.run().
1825 public void onExit() {
1826 // Default does nothing.
1829 // ------------------------------------------------------------------------
1830 // TWindow management -----------------------------------------------------
1831 // ------------------------------------------------------------------------
1834 * Return the total number of windows.
1836 * @return the total number of windows
1838 public final int windowCount() {
1839 return windows
.size();
1843 * Return the number of windows that are showing.
1845 * @return the number of windows that are showing on screen
1847 public final int shownWindowCount() {
1849 for (TWindow w
: windows
) {
1858 * Return the number of windows that are hidden.
1860 * @return the number of windows that are hidden
1862 public final int hiddenWindowCount() {
1864 for (TWindow w
: windows
) {
1873 * Check if a window instance is in this application's window list.
1875 * @param window window to look for
1876 * @return true if this window is in the list
1878 public final boolean hasWindow(final TWindow window
) {
1879 if (windows
.size() == 0) {
1882 for (TWindow w
: windows
) {
1884 assert (window
.getApplication() == this);
1892 * Activate a window: bring it to the top and have it receive events.
1894 * @param window the window to become the new active window
1896 public void activateWindow(final TWindow window
) {
1897 if (hasWindow(window
) == false) {
1899 * Someone has a handle to a window I don't have. Ignore this
1905 // Whatever window might be moving/dragging, stop it now.
1906 for (TWindow w
: windows
) {
1907 if (w
.inMovements()) {
1912 assert (windows
.size() > 0);
1914 if (window
.isHidden()) {
1915 // Unhiding will also activate.
1919 assert (window
.isShown());
1921 if (windows
.size() == 1) {
1922 assert (window
== windows
.get(0));
1923 if (activeWindow
== null) {
1924 activeWindow
= window
;
1926 activeWindow
.setActive(true);
1927 activeWindow
.onFocus();
1930 assert (window
.isActive());
1931 assert (activeWindow
== window
);
1935 if (activeWindow
== window
) {
1936 assert (window
.isActive());
1938 // Window is already active, do nothing.
1942 assert (!window
.isActive());
1943 if (activeWindow
!= null) {
1944 // TODO: see if this assertion is really necessary.
1945 // assert (activeWindow.getZ() == 0);
1947 activeWindow
.setActive(false);
1949 // Increment every window Z that is on top of window
1950 for (TWindow w
: windows
) {
1954 if (w
.getZ() < window
.getZ()) {
1955 w
.setZ(w
.getZ() + 1);
1959 // Unset activeWindow now before unfocus, so that a window
1960 // lifecycle change inside onUnfocus() doesn't call
1961 // switchWindow() and lead to a stack overflow.
1962 TWindow oldActiveWindow
= activeWindow
;
1963 activeWindow
= null;
1964 oldActiveWindow
.onUnfocus();
1966 activeWindow
= window
;
1967 activeWindow
.setZ(0);
1968 activeWindow
.setActive(true);
1969 activeWindow
.onFocus();
1976 * @param window the window to hide
1978 public void hideWindow(final TWindow window
) {
1979 if (hasWindow(window
) == false) {
1981 * Someone has a handle to a window I don't have. Ignore this
1987 // Whatever window might be moving/dragging, stop it now.
1988 for (TWindow w
: windows
) {
1989 if (w
.inMovements()) {
1994 assert (windows
.size() > 0);
1996 if (!window
.hidden
) {
1997 if (window
== activeWindow
) {
1998 if (shownWindowCount() > 1) {
2001 activeWindow
= null;
2002 window
.setActive(false);
2006 window
.hidden
= true;
2014 * @param window the window to show
2016 public void showWindow(final TWindow window
) {
2017 if (hasWindow(window
) == false) {
2019 * Someone has a handle to a window I don't have. Ignore this
2025 // Whatever window might be moving/dragging, stop it now.
2026 for (TWindow w
: windows
) {
2027 if (w
.inMovements()) {
2032 assert (windows
.size() > 0);
2034 if (window
.hidden
) {
2035 window
.hidden
= false;
2037 activateWindow(window
);
2042 * Close window. Note that the window's destructor is NOT called by this
2043 * method, instead the GC is assumed to do the cleanup.
2045 * @param window the window to remove
2047 public final void closeWindow(final TWindow window
) {
2048 if (hasWindow(window
) == false) {
2050 * Someone has a handle to a window I don't have. Ignore this
2056 // Let window know that it is about to be closed, while it is still
2057 // visible on screen.
2058 window
.onPreClose();
2060 synchronized (windows
) {
2061 // Whatever window might be moving/dragging, stop it now.
2062 for (TWindow w
: windows
) {
2063 if (w
.inMovements()) {
2068 int z
= window
.getZ();
2071 windows
.remove(window
);
2072 Collections
.sort(windows
);
2073 activeWindow
= null;
2075 boolean foundNextWindow
= false;
2077 for (TWindow w
: windows
) {
2081 // Do not activate a hidden window.
2086 if (foundNextWindow
== false) {
2087 foundNextWindow
= true;
2090 assert (activeWindow
== null);
2102 // Perform window cleanup
2105 // Check if we are closing a TMessageBox or similar
2106 if (secondaryEventReceiver
!= null) {
2107 assert (secondaryEventHandler
!= null);
2109 // Do not send events to the secondaryEventReceiver anymore, the
2110 // window is closed.
2111 secondaryEventReceiver
= null;
2113 // Wake the secondary thread, it will wake the primary as it
2115 synchronized (secondaryEventHandler
) {
2116 secondaryEventHandler
.notify();
2120 // Permit desktop to be active if it is the only thing left.
2121 if (desktop
!= null) {
2122 if (windows
.size() == 0) {
2123 desktop
.setActive(true);
2129 * Switch to the next window.
2131 * @param forward if true, then switch to the next window in the list,
2132 * otherwise switch to the previous window in the list
2134 public final void switchWindow(final boolean forward
) {
2135 // Only switch if there are multiple visible windows
2136 if (shownWindowCount() < 2) {
2139 assert (activeWindow
!= null);
2141 synchronized (windows
) {
2142 // Whatever window might be moving/dragging, stop it now.
2143 for (TWindow w
: windows
) {
2144 if (w
.inMovements()) {
2149 // Swap z/active between active window and the next in the list
2150 int activeWindowI
= -1;
2151 for (int i
= 0; i
< windows
.size(); i
++) {
2152 if (windows
.get(i
) == activeWindow
) {
2153 assert (activeWindow
.isActive());
2157 assert (!windows
.get(0).isActive());
2160 assert (activeWindowI
>= 0);
2162 // Do not switch if a window is modal
2163 if (activeWindow
.isModal()) {
2167 int nextWindowI
= activeWindowI
;
2171 nextWindowI
%= windows
.size();
2174 if (nextWindowI
< 0) {
2175 nextWindowI
= windows
.size() - 1;
2179 if (windows
.get(nextWindowI
).isShown()) {
2180 activateWindow(windows
.get(nextWindowI
));
2184 } // synchronized (windows)
2189 * Add a window to my window list and make it active. Note package
2192 * @param window new window to add
2194 final void addWindowToApplication(final TWindow window
) {
2196 // Do not add menu windows to the window list.
2197 if (window
instanceof TMenu
) {
2201 // Do not add the desktop to the window list.
2202 if (window
instanceof TDesktop
) {
2206 synchronized (windows
) {
2207 if (windows
.contains(window
)) {
2208 throw new IllegalArgumentException("Window " + window
+
2209 " is already in window list");
2212 // Whatever window might be moving/dragging, stop it now.
2213 for (TWindow w
: windows
) {
2214 if (w
.inMovements()) {
2219 // Do not allow a modal window to spawn a non-modal window. If a
2220 // modal window is active, then this window will become modal
2222 if (modalWindowActive()) {
2223 window
.flags
|= TWindow
.MODAL
;
2224 window
.flags
|= TWindow
.CENTERED
;
2225 window
.hidden
= false;
2227 if (window
.isShown()) {
2228 for (TWindow w
: windows
) {
2233 w
.setZ(w
.getZ() + 1);
2236 windows
.add(window
);
2237 if (window
.isShown()) {
2238 activeWindow
= window
;
2239 activeWindow
.setZ(0);
2240 activeWindow
.setActive(true);
2241 activeWindow
.onFocus();
2244 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2245 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2246 && (smartWindowPlacement
== true)
2249 doSmartPlacement(window
);
2253 // Desktop cannot be active over any other window.
2254 if (desktop
!= null) {
2255 desktop
.setActive(false);
2260 * Check if there is a system-modal window on top.
2262 * @return true if the active window is modal
2264 private boolean modalWindowActive() {
2265 if (windows
.size() == 0) {
2269 for (TWindow w
: windows
) {
2279 * Check if there is a window with overridden menu flag on top.
2281 * @return true if the active window is overriding the menu
2283 private boolean overrideMenuWindowActive() {
2284 if (activeWindow
!= null) {
2285 if (activeWindow
.hasOverriddenMenu()) {
2294 * Close all open windows.
2296 private void closeAllWindows() {
2297 // Don't do anything if we are in the menu
2298 if (activeMenu
!= null) {
2301 while (windows
.size() > 0) {
2302 closeWindow(windows
.get(0));
2307 * Re-layout the open windows as non-overlapping tiles. This produces
2308 * almost the same results as Turbo Pascal 7.0's IDE.
2310 private void tileWindows() {
2311 synchronized (windows
) {
2312 // Don't do anything if we are in the menu
2313 if (activeMenu
!= null) {
2316 int z
= windows
.size();
2322 a
= (int)(Math
.sqrt(z
));
2326 if (((a
* b
) + c
) == z
) {
2334 int newWidth
= (getScreen().getWidth() / a
);
2335 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2336 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2338 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2339 Collections
.sort(sorted
);
2340 Collections
.reverse(sorted
);
2341 for (int i
= 0; i
< sorted
.size(); i
++) {
2342 int logicalX
= i
/ b
;
2343 int logicalY
= i
% b
;
2344 if (i
>= ((a
- 1) * b
)) {
2346 logicalY
= i
- ((a
- 1) * b
);
2349 TWindow w
= sorted
.get(i
);
2350 int oldWidth
= w
.getWidth();
2351 int oldHeight
= w
.getHeight();
2353 w
.setX(logicalX
* newWidth
);
2354 w
.setWidth(newWidth
);
2355 if (i
>= ((a
- 1) * b
)) {
2356 w
.setY((logicalY
* newHeight2
) + 1);
2357 w
.setHeight(newHeight2
);
2359 w
.setY((logicalY
* newHeight1
) + 1);
2360 w
.setHeight(newHeight1
);
2362 if ((w
.getWidth() != oldWidth
)
2363 || (w
.getHeight() != oldHeight
)
2365 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2366 w
.getWidth(), w
.getHeight()));
2373 * Re-layout the open windows as overlapping cascaded windows.
2375 private void cascadeWindows() {
2376 synchronized (windows
) {
2377 // Don't do anything if we are in the menu
2378 if (activeMenu
!= null) {
2383 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2384 Collections
.sort(sorted
);
2385 Collections
.reverse(sorted
);
2386 for (TWindow window
: sorted
) {
2391 if (x
> getScreen().getWidth()) {
2394 if (y
>= getScreen().getHeight()) {
2402 * Place a window to minimize its overlap with other windows.
2404 * @param window the window to place
2406 public final void doSmartPlacement(final TWindow window
) {
2407 // This is a pretty dumb algorithm, but seems to work. The hardest
2408 // part is computing these "overlap" values seeking a minimum average
2411 int yMin
= desktopTop
;
2412 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2413 int yMax
= desktopBottom
- window
.getHeight() + 1;
2421 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2422 // No work to do, bail out.
2426 // Compute the overlap matrix without the new window.
2427 int width
= getScreen().getWidth();
2428 int height
= getScreen().getHeight();
2429 int overlapMatrix
[][] = new int[width
][height
];
2430 for (TWindow w
: windows
) {
2434 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2441 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2448 overlapMatrix
[x
][y
]++;
2453 long oldOverlapTotal
= 0;
2454 long oldOverlapN
= 0;
2455 for (int x
= 0; x
< width
; x
++) {
2456 for (int y
= 0; y
< height
; y
++) {
2457 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2458 if (overlapMatrix
[x
][y
] > 0) {
2465 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2466 boolean first
= true;
2467 int windowX
= window
.getX();
2468 int windowY
= window
.getY();
2470 // For each possible (x, y) position for the new window, compute a
2471 // new overlap matrix.
2472 for (int x
= xMin
; x
< xMax
; x
++) {
2473 for (int y
= yMin
; y
< yMax
; y
++) {
2475 // Start with the matrix minus this window.
2476 int newMatrix
[][] = new int[width
][height
];
2477 for (int mx
= 0; mx
< width
; mx
++) {
2478 for (int my
= 0; my
< height
; my
++) {
2479 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2483 // Add this window's values to the new overlap matrix.
2484 long newOverlapTotal
= 0;
2485 long newOverlapN
= 0;
2486 // Start by adding each new cell.
2487 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2491 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2495 newMatrix
[wx
][wy
]++;
2498 // Now figure out the new value for total coverage.
2499 for (int mx
= 0; mx
< width
; mx
++) {
2500 for (int my
= 0; my
< height
; my
++) {
2501 newOverlapTotal
+= newMatrix
[x
][y
];
2502 if (newMatrix
[mx
][my
] > 0) {
2507 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2510 // First time: just record what we got.
2511 oldOverlapAvg
= newOverlapAvg
;
2514 // All other times: pick a new best (x, y) and save the
2516 if (newOverlapAvg
< oldOverlapAvg
) {
2519 oldOverlapAvg
= newOverlapAvg
;
2523 } // for (int x = xMin; x < xMax; x++)
2525 } // for (int y = yMin; y < yMax; y++)
2527 // Finally, set the window's new coordinates.
2528 window
.setX(windowX
);
2529 window
.setY(windowY
);
2532 // ------------------------------------------------------------------------
2533 // TImage management ------------------------------------------------------
2534 // ------------------------------------------------------------------------
2537 * Add an image to the list. Note package private access.
2539 * @param image the image to add
2540 * @throws IllegalArgumentException if the image is already used in
2541 * another TApplication
2543 final void addImage(final TImage image
) {
2544 if ((image
.getApplication() != null)
2545 && (image
.getApplication() != this)
2547 throw new IllegalArgumentException("Image " + image
+
2548 " is already " + "part of application " +
2549 image
.getApplication());
2555 * Remove an image from the list. Note package private access.
2557 * @param image the image to remove
2558 * @throws IllegalArgumentException if the image is already used in
2559 * another TApplication
2561 final void removeImage(final TImage image
) {
2562 if ((image
.getApplication() != null)
2563 && (image
.getApplication() != this)
2565 throw new IllegalArgumentException("Image " + image
+
2566 " is already " + "part of application " +
2567 image
.getApplication());
2569 images
.remove(image
);
2572 // ------------------------------------------------------------------------
2573 // TMenu management -------------------------------------------------------
2574 // ------------------------------------------------------------------------
2577 * Check if a mouse event would hit either the active menu or any open
2580 * @param mouse mouse event
2581 * @return true if the mouse would hit the active menu or an open
2584 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2585 assert (activeMenu
!= null);
2586 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2587 Collections
.reverse(menus
);
2588 for (TMenu menu
: menus
) {
2589 if (menu
.mouseWouldHit(mouse
)) {
2593 return activeMenu
.mouseWouldHit(mouse
);
2597 * See if we need to switch window or activate the menu based on
2600 * @param mouse mouse event
2602 private void checkSwitchFocus(final TMouseEvent mouse
) {
2604 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2605 && (activeMenu
!= null)
2606 && (mouse
.getAbsoluteY() != 0)
2607 && (!mouseOnMenu(mouse
))
2609 // They clicked outside the active menu, turn it off
2610 activeMenu
.setActive(false);
2612 for (TMenu menu
: subMenus
) {
2613 menu
.setActive(false);
2619 // See if they hit the menu bar
2620 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2621 && (mouse
.isMouse1())
2622 && (!modalWindowActive())
2623 && (!overrideMenuWindowActive())
2624 && (mouse
.getAbsoluteY() == 0)
2627 for (TMenu menu
: subMenus
) {
2628 menu
.setActive(false);
2632 // They selected the menu, go activate it
2633 for (TMenu menu
: menus
) {
2634 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2635 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2636 + menu
.getTitle().length() + 2)
2638 menu
.setActive(true);
2641 menu
.setActive(false);
2647 // See if they hit the menu bar
2648 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2649 && (mouse
.isMouse1())
2650 && (activeMenu
!= null)
2651 && (mouse
.getAbsoluteY() == 0)
2654 TMenu oldMenu
= activeMenu
;
2655 for (TMenu menu
: subMenus
) {
2656 menu
.setActive(false);
2660 // See if we should switch menus
2661 for (TMenu menu
: menus
) {
2662 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2663 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2664 + menu
.getTitle().length() + 2)
2666 menu
.setActive(true);
2670 if (oldMenu
!= activeMenu
) {
2671 // They switched menus
2672 oldMenu
.setActive(false);
2677 // If a menu is still active, don't switch windows
2678 if (activeMenu
!= null) {
2682 // Only switch if there are multiple windows
2683 if (windows
.size() < 2) {
2687 if (((focusFollowsMouse
== true)
2688 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2689 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2691 synchronized (windows
) {
2692 Collections
.sort(windows
);
2693 if (windows
.get(0).isModal()) {
2694 // Modal windows don't switch
2698 for (TWindow window
: windows
) {
2699 assert (!window
.isModal());
2701 if (window
.isHidden()) {
2702 assert (!window
.isActive());
2706 if (window
.mouseWouldHit(mouse
)) {
2707 if (window
== windows
.get(0)) {
2708 // Clicked on the same window, nothing to do
2709 assert (window
.isActive());
2713 // We will be switching to another window
2714 assert (windows
.get(0).isActive());
2715 assert (windows
.get(0) == activeWindow
);
2716 assert (!window
.isActive());
2717 if (activeWindow
!= null) {
2718 activeWindow
.onUnfocus();
2719 activeWindow
.setActive(false);
2720 activeWindow
.setZ(window
.getZ());
2722 activeWindow
= window
;
2724 window
.setActive(true);
2731 // Clicked on the background, nothing to do
2735 // Nothing to do: this isn't a mouse up, or focus isn't following
2741 * Turn off the menu.
2743 public final void closeMenu() {
2744 if (activeMenu
!= null) {
2745 activeMenu
.setActive(false);
2747 for (TMenu menu
: subMenus
) {
2748 menu
.setActive(false);
2755 * Get a (shallow) copy of the menu list.
2757 * @return a copy of the menu list
2759 public final List
<TMenu
> getAllMenus() {
2760 return new ArrayList
<TMenu
>(menus
);
2764 * Add a top-level menu to the list.
2766 * @param menu the menu to add
2767 * @throws IllegalArgumentException if the menu is already used in
2768 * another TApplication
2770 public final void addMenu(final TMenu menu
) {
2771 if ((menu
.getApplication() != null)
2772 && (menu
.getApplication() != this)
2774 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2775 "part of application " + menu
.getApplication());
2783 * Remove a top-level menu from the list.
2785 * @param menu the menu to remove
2786 * @throws IllegalArgumentException if the menu is already used in
2787 * another TApplication
2789 public final void removeMenu(final TMenu menu
) {
2790 if ((menu
.getApplication() != null)
2791 && (menu
.getApplication() != this)
2793 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2794 "part of application " + menu
.getApplication());
2802 * Turn off a sub-menu.
2804 public final void closeSubMenu() {
2805 assert (activeMenu
!= null);
2806 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2807 assert (item
!= null);
2808 item
.setActive(false);
2809 subMenus
.remove(subMenus
.size() - 1);
2813 * Switch to the next menu.
2815 * @param forward if true, then switch to the next menu in the list,
2816 * otherwise switch to the previous menu in the list
2818 public final void switchMenu(final boolean forward
) {
2819 assert (activeMenu
!= null);
2821 for (TMenu menu
: subMenus
) {
2822 menu
.setActive(false);
2826 for (int i
= 0; i
< menus
.size(); i
++) {
2827 if (activeMenu
== menus
.get(i
)) {
2829 if (i
< menus
.size() - 1) {
2838 i
= menus
.size() - 1;
2841 activeMenu
.setActive(false);
2842 activeMenu
= menus
.get(i
);
2843 activeMenu
.setActive(true);
2850 * Add a menu item to the global list. If it has a keyboard accelerator,
2851 * that will be added the global hash.
2853 * @param item the menu item
2855 public final void addMenuItem(final TMenuItem item
) {
2856 menuItems
.add(item
);
2858 TKeypress key
= item
.getKey();
2860 synchronized (accelerators
) {
2861 assert (accelerators
.get(key
) == null);
2862 accelerators
.put(key
.toLowerCase(), item
);
2868 * Disable one menu item.
2870 * @param id the menu item ID
2872 public final void disableMenuItem(final int id
) {
2873 for (TMenuItem item
: menuItems
) {
2874 if (item
.getId() == id
) {
2875 item
.setEnabled(false);
2881 * Disable the range of menu items with ID's between lower and upper,
2884 * @param lower the lowest menu item ID
2885 * @param upper the highest menu item ID
2887 public final void disableMenuItems(final int lower
, final int upper
) {
2888 for (TMenuItem item
: menuItems
) {
2889 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2890 item
.setEnabled(false);
2891 item
.getParent().activate(0);
2897 * Enable one menu item.
2899 * @param id the menu item ID
2901 public final void enableMenuItem(final int id
) {
2902 for (TMenuItem item
: menuItems
) {
2903 if (item
.getId() == id
) {
2904 item
.setEnabled(true);
2905 item
.getParent().activate(0);
2911 * Enable the range of menu items with ID's between lower and upper,
2914 * @param lower the lowest menu item ID
2915 * @param upper the highest menu item ID
2917 public final void enableMenuItems(final int lower
, final int upper
) {
2918 for (TMenuItem item
: menuItems
) {
2919 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2920 item
.setEnabled(true);
2921 item
.getParent().activate(0);
2927 * Get the menu item associated with this ID.
2929 * @param id the menu item ID
2930 * @return the menu item, or null if not found
2932 public final TMenuItem
getMenuItem(final int id
) {
2933 for (TMenuItem item
: menuItems
) {
2934 if (item
.getId() == id
) {
2942 * Recompute menu x positions based on their title length.
2944 public final void recomputeMenuX() {
2946 for (TMenu menu
: menus
) {
2949 x
+= menu
.getTitle().length() + 2;
2951 // Don't let the menu window exceed the screen width
2952 int rightEdge
= menu
.getX() + menu
.getWidth();
2953 if (rightEdge
> getScreen().getWidth()) {
2954 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2960 * Post an event to process.
2962 * @param event new event to add to the queue
2964 public final void postEvent(final TInputEvent event
) {
2965 synchronized (this) {
2966 synchronized (fillEventQueue
) {
2967 fillEventQueue
.add(event
);
2970 System
.err
.println(System
.currentTimeMillis() + " " +
2971 Thread
.currentThread() + " postEvent() wake up main");
2978 * Post an event to process and turn off the menu.
2980 * @param event new event to add to the queue
2982 public final void postMenuEvent(final TInputEvent event
) {
2983 synchronized (this) {
2984 synchronized (fillEventQueue
) {
2985 fillEventQueue
.add(event
);
2988 System
.err
.println(System
.currentTimeMillis() + " " +
2989 Thread
.currentThread() + " postMenuEvent() wake up main");
2997 * Add a sub-menu to the list of open sub-menus.
2999 * @param menu sub-menu
3001 public final void addSubMenu(final TMenu menu
) {
3006 * Convenience function to add a top-level menu.
3008 * @param title menu title
3009 * @return the new menu
3011 public final TMenu
addMenu(final String title
) {
3014 TMenu menu
= new TMenu(this, x
, y
, title
);
3021 * Convenience function to add a default tools (hamburger) menu.
3023 * @return the new menu
3025 public final TMenu
addToolMenu() {
3026 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
3027 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
3028 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
3029 toolMenu
.addDefaultItem(TMenu
.MID_CHANGE_FONT
);
3030 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
3031 getString("toolMenuStatus"));
3032 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3037 * Convenience function to add a default "File" menu.
3039 * @return the new menu
3041 public final TMenu
addFileMenu() {
3042 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
3043 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
3044 fileMenu
.addSeparator();
3045 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
3046 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
3047 getString("fileMenuStatus"));
3048 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3053 * Convenience function to add a default "Edit" menu.
3055 * @return the new menu
3057 public final TMenu
addEditMenu() {
3058 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
3059 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
3060 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
3061 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
3062 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
3063 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
3064 getString("editMenuStatus"));
3065 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3070 * Convenience function to add a default "Window" menu.
3072 * @return the new menu
3074 public final TMenu
addWindowMenu() {
3075 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
3076 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
3077 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
3078 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
3079 windowMenu
.addSeparator();
3080 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
3081 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
3082 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3083 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3084 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3085 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3086 getString("windowMenuStatus"));
3087 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3092 * Convenience function to add a default "Help" menu.
3094 * @return the new menu
3096 public final TMenu
addHelpMenu() {
3097 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3098 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3099 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3100 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3101 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3102 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3103 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3104 helpMenu
.addSeparator();
3105 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3106 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3107 getString("helpMenuStatus"));
3108 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3113 * Convenience function to add a default "Table" menu.
3115 * @return the new menu
3117 public final TMenu
addTableMenu() {
3118 TMenu tableMenu
= addMenu(i18n
.getString("tableMenuTitle"));
3119 TSubMenu viewMenu
= tableMenu
.addSubMenu(i18n
.
3120 getString("tableSubMenuView"));
3121 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_ROW_LABELS
, false);
3122 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_COLUMN_LABELS
, false);
3123 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_ROW
, false);
3124 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_COLUMN
, false);
3126 TSubMenu borderMenu
= tableMenu
.addSubMenu(i18n
.
3127 getString("tableSubMenuBorders"));
3128 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_NONE
, false);
3129 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_ALL
, false);
3130 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_NONE
, false);
3131 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_ALL
, false);
3132 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_RIGHT
, false);
3133 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_LEFT
, false);
3134 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_TOP
, false);
3135 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_BOTTOM
, false);
3136 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_DOUBLE_BOTTOM
, false);
3137 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_THICK_BOTTOM
, false);
3138 TSubMenu deleteMenu
= tableMenu
.addSubMenu(i18n
.
3139 getString("tableSubMenuDelete"));
3140 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_LEFT
, false);
3141 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_UP
, false);
3142 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_ROW
, false);
3143 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_COLUMN
, false);
3144 TSubMenu insertMenu
= tableMenu
.addSubMenu(i18n
.
3145 getString("tableSubMenuInsert"));
3146 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_LEFT
, false);
3147 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_RIGHT
, false);
3148 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_ABOVE
, false);
3149 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_BELOW
, false);
3150 TSubMenu columnMenu
= tableMenu
.addSubMenu(i18n
.
3151 getString("tableSubMenuColumn"));
3152 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_NARROW
, false);
3153 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_WIDEN
, false);
3154 TSubMenu fileMenu
= tableMenu
.addSubMenu(i18n
.
3155 getString("tableSubMenuFile"));
3156 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_CSV
, false);
3157 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_TEXT
, false);
3159 TStatusBar statusBar
= tableMenu
.newStatusBar(i18n
.
3160 getString("tableMenuStatus"));
3161 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3165 // ------------------------------------------------------------------------
3166 // TTimer management ------------------------------------------------------
3167 // ------------------------------------------------------------------------
3170 * Get the amount of time I can sleep before missing a Timer tick.
3172 * @param timeout = initial (maximum) timeout in millis
3173 * @return number of milliseconds between now and the next timer event
3175 private long getSleepTime(final long timeout
) {
3176 Date now
= new Date();
3177 long nowTime
= now
.getTime();
3178 long sleepTime
= timeout
;
3180 synchronized (timers
) {
3181 for (TTimer timer
: timers
) {
3182 long nextTickTime
= timer
.getNextTick().getTime();
3183 if (nextTickTime
< nowTime
) {
3187 long timeDifference
= nextTickTime
- nowTime
;
3188 if (timeDifference
< sleepTime
) {
3189 sleepTime
= timeDifference
;
3194 assert (sleepTime
>= 0);
3195 assert (sleepTime
<= timeout
);
3200 * Convenience function to add a timer.
3202 * @param duration number of milliseconds to wait between ticks
3203 * @param recurring if true, re-schedule this timer after every tick
3204 * @param action function to call when button is pressed
3207 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3208 final TAction action
) {
3210 TTimer timer
= new TTimer(duration
, recurring
, action
);
3211 synchronized (timers
) {
3218 * Convenience function to remove a timer.
3220 * @param timer timer to remove
3222 public final void removeTimer(final TTimer timer
) {
3223 synchronized (timers
) {
3224 timers
.remove(timer
);
3228 // ------------------------------------------------------------------------
3229 // Other TWindow constructors ---------------------------------------------
3230 // ------------------------------------------------------------------------
3233 * Convenience function to spawn a message box.
3235 * @param title window title, will be centered along the top border
3236 * @param caption message to display. Use embedded newlines to get a
3238 * @return the new message box
3240 public final TMessageBox
messageBox(final String title
,
3241 final String caption
) {
3243 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3247 * Convenience function to spawn a message box.
3249 * @param title window title, will be centered along the top border
3250 * @param caption message to display. Use embedded newlines to get a
3252 * @param type one of the TMessageBox.Type constants. Default is
3254 * @return the new message box
3256 public final TMessageBox
messageBox(final String title
,
3257 final String caption
, final TMessageBox
.Type type
) {
3259 return new TMessageBox(this, title
, caption
, type
);
3263 * Convenience function to spawn an input box.
3265 * @param title window title, will be centered along the top border
3266 * @param caption message to display. Use embedded newlines to get a
3268 * @return the new input box
3270 public final TInputBox
inputBox(final String title
, final String caption
) {
3272 return new TInputBox(this, title
, caption
);
3276 * Convenience function to spawn an input box.
3278 * @param title window title, will be centered along the top border
3279 * @param caption message to display. Use embedded newlines to get a
3281 * @param text initial text to seed the field with
3282 * @return the new input box
3284 public final TInputBox
inputBox(final String title
, final String caption
,
3285 final String text
) {
3287 return new TInputBox(this, title
, caption
, text
);
3291 * Convenience function to spawn an input box.
3293 * @param title window title, will be centered along the top border
3294 * @param caption message to display. Use embedded newlines to get a
3296 * @param text initial text to seed the field with
3297 * @param type one of the Type constants. Default is Type.OK.
3298 * @return the new input box
3300 public final TInputBox
inputBox(final String title
, final String caption
,
3301 final String text
, final TInputBox
.Type type
) {
3303 return new TInputBox(this, title
, caption
, text
, type
);
3307 * Convenience function to open a terminal window.
3309 * @param x column relative to parent
3310 * @param y row relative to parent
3311 * @return the terminal new window
3313 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3314 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3318 * Convenience function to open a terminal window.
3320 * @param x column relative to parent
3321 * @param y row relative to parent
3322 * @param closeOnExit if true, close the window when the command exits
3323 * @return the terminal new window
3325 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3326 final boolean closeOnExit
) {
3328 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3332 * Convenience function to open a terminal window.
3334 * @param x column relative to parent
3335 * @param y row relative to parent
3336 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3337 * @return the terminal new window
3339 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3342 return new TTerminalWindow(this, x
, y
, flags
);
3346 * Convenience function to open a terminal window.
3348 * @param x column relative to parent
3349 * @param y row relative to parent
3350 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3351 * @param closeOnExit if true, close the window when the command exits
3352 * @return the terminal new window
3354 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3355 final int flags
, final boolean closeOnExit
) {
3357 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3361 * Convenience function to open a terminal window and execute a custom
3362 * command line inside it.
3364 * @param x column relative to parent
3365 * @param y row relative to parent
3366 * @param commandLine the command line to execute
3367 * @return the terminal new window
3369 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3370 final String commandLine
) {
3372 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3376 * Convenience function to open a terminal window and execute a custom
3377 * command line inside it.
3379 * @param x column relative to parent
3380 * @param y row relative to parent
3381 * @param commandLine the command line to execute
3382 * @param closeOnExit if true, close the window when the command exits
3383 * @return the terminal new window
3385 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3386 final String commandLine
, final boolean closeOnExit
) {
3388 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3392 * Convenience function to open a terminal window and execute a custom
3393 * command line inside it.
3395 * @param x column relative to parent
3396 * @param y row relative to parent
3397 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3398 * @param command the command line to execute
3399 * @return the terminal new window
3401 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3402 final int flags
, final String
[] command
) {
3404 return new TTerminalWindow(this, x
, y
, flags
, command
);
3408 * Convenience function to open a terminal window and execute a custom
3409 * command line inside it.
3411 * @param x column relative to parent
3412 * @param y row relative to parent
3413 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3414 * @param command the command line to execute
3415 * @param closeOnExit if true, close the window when the command exits
3416 * @return the terminal new window
3418 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3419 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3421 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3425 * Convenience function to open a terminal window and execute a custom
3426 * command line inside it.
3428 * @param x column relative to parent
3429 * @param y row relative to parent
3430 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3431 * @param commandLine the command line to execute
3432 * @return the terminal new window
3434 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3435 final int flags
, final String commandLine
) {
3437 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"));
3441 * Convenience function to open a terminal window and execute a custom
3442 * command line inside it.
3444 * @param x column relative to parent
3445 * @param y row relative to parent
3446 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3447 * @param commandLine the command line to execute
3448 * @param closeOnExit if true, close the window when the command exits
3449 * @return the terminal new window
3451 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3452 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3454 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"),
3459 * Convenience function to spawn an file open box.
3461 * @param path path of selected file
3462 * @return the result of the new file open box
3463 * @throws IOException if java.io operation throws
3465 public final String
fileOpenBox(final String path
) throws IOException
{
3467 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3468 return box
.getFilename();
3472 * Convenience function to spawn an file open box.
3474 * @param path path of selected file
3475 * @param type one of the Type constants
3476 * @return the result of the new file open box
3477 * @throws IOException if java.io operation throws
3479 public final String
fileOpenBox(final String path
,
3480 final TFileOpenBox
.Type type
) throws IOException
{
3482 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3483 return box
.getFilename();
3487 * Convenience function to spawn a file open box.
3489 * @param path path of selected file
3490 * @param type one of the Type constants
3491 * @param filter a string that files must match to be displayed
3492 * @return the result of the new file open box
3493 * @throws IOException of a java.io operation throws
3495 public final String
fileOpenBox(final String path
,
3496 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3498 ArrayList
<String
> filters
= new ArrayList
<String
>();
3499 filters
.add(filter
);
3501 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3502 return box
.getFilename();
3506 * Convenience function to spawn a file open box.
3508 * @param path path of selected file
3509 * @param type one of the Type constants
3510 * @param filters a list of strings that files must match to be displayed
3511 * @return the result of the new file open box
3512 * @throws IOException of a java.io operation throws
3514 public final String
fileOpenBox(final String path
,
3515 final TFileOpenBox
.Type type
,
3516 final List
<String
> filters
) throws IOException
{
3518 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3519 return box
.getFilename();
3523 * Convenience function to create a new window and make it active.
3524 * Window will be located at (0, 0).
3526 * @param title window title, will be centered along the top border
3527 * @param width width of window
3528 * @param height height of window
3529 * @return the new window
3531 public final TWindow
addWindow(final String title
, final int width
,
3534 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3539 * Convenience function to create a new window and make it active.
3540 * Window will be located at (0, 0).
3542 * @param title window title, will be centered along the top border
3543 * @param width width of window
3544 * @param height height of window
3545 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3546 * @return the new window
3548 public final TWindow
addWindow(final String title
,
3549 final int width
, final int height
, final int flags
) {
3551 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3556 * Convenience function to create a new window and make it active.
3558 * @param title window title, will be centered along the top border
3559 * @param x column relative to parent
3560 * @param y row relative to parent
3561 * @param width width of window
3562 * @param height height of window
3563 * @return the new window
3565 public final TWindow
addWindow(final String title
,
3566 final int x
, final int y
, final int width
, final int height
) {
3568 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3573 * Convenience function to create a new window and make it active.
3575 * @param title window title, will be centered along the top border
3576 * @param x column relative to parent
3577 * @param y row relative to parent
3578 * @param width width of window
3579 * @param height height of window
3580 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3581 * @return the new window
3583 public final TWindow
addWindow(final String title
,
3584 final int x
, final int y
, final int width
, final int height
,
3587 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);