2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2019 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
32 import java
.io
.InputStream
;
33 import java
.io
.IOException
;
34 import java
.io
.OutputStream
;
35 import java
.io
.PrintWriter
;
36 import java
.io
.Reader
;
37 import java
.io
.UnsupportedEncodingException
;
38 import java
.text
.MessageFormat
;
39 import java
.util
.ArrayList
;
40 import java
.util
.Collections
;
41 import java
.util
.Date
;
42 import java
.util
.HashMap
;
43 import java
.util
.LinkedList
;
44 import java
.util
.List
;
46 import java
.util
.ResourceBundle
;
48 import jexer
.bits
.Cell
;
49 import jexer
.bits
.CellAttributes
;
50 import jexer
.bits
.ColorTheme
;
51 import jexer
.bits
.StringUtils
;
52 import jexer
.event
.TCommandEvent
;
53 import jexer
.event
.TInputEvent
;
54 import jexer
.event
.TKeypressEvent
;
55 import jexer
.event
.TMenuEvent
;
56 import jexer
.event
.TMouseEvent
;
57 import jexer
.event
.TResizeEvent
;
58 import jexer
.backend
.Backend
;
59 import jexer
.backend
.MultiBackend
;
60 import jexer
.backend
.Screen
;
61 import jexer
.backend
.SwingBackend
;
62 import jexer
.backend
.ECMA48Backend
;
63 import jexer
.backend
.TWindowBackend
;
64 import jexer
.menu
.TMenu
;
65 import jexer
.menu
.TMenuItem
;
66 import jexer
.menu
.TSubMenu
;
67 import static jexer
.TCommand
.*;
68 import static jexer
.TKeypress
.*;
71 * TApplication is the main driver class for a full Text User Interface
72 * application. It manages windows, provides a menu bar and status bar, and
73 * processes events received from the user.
75 public class TApplication
implements Runnable
{
80 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
82 // ------------------------------------------------------------------------
83 // Constants --------------------------------------------------------------
84 // ------------------------------------------------------------------------
87 * If true, emit thread stuff to System.err.
89 private static final boolean debugThreads
= false;
92 * If true, emit events being processed to System.err.
94 private static final boolean debugEvents
= false;
97 * If true, do "smart placement" on new windows that are not specified to
100 private static final boolean smartWindowPlacement
= true;
103 * Two backend types are available.
105 public static enum BackendType
{
112 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
117 * Synonym for ECMA48.
122 // ------------------------------------------------------------------------
123 // Variables --------------------------------------------------------------
124 // ------------------------------------------------------------------------
127 * The primary event handler thread.
129 private volatile WidgetEventHandler primaryEventHandler
;
132 * The secondary event handler thread.
134 private volatile WidgetEventHandler secondaryEventHandler
;
137 * The screen handler thread.
139 private volatile ScreenHandler screenHandler
;
142 * The widget receiving events from the secondary event handler thread.
144 private volatile TWidget secondaryEventReceiver
;
147 * Access to the physical screen, keyboard, and mouse.
149 private Backend backend
;
152 * Actual mouse coordinate X.
157 * Actual mouse coordinate Y.
162 * Old version of mouse coordinate X.
164 private int oldMouseX
;
167 * Old version mouse coordinate Y.
169 private int oldMouseY
;
172 * Old drawn version of mouse coordinate X.
174 private int oldDrawnMouseX
;
177 * Old drawn version mouse coordinate Y.
179 private int oldDrawnMouseY
;
182 * Old drawn version mouse cell.
184 private Cell oldDrawnMouseCell
= new Cell();
187 * The last mouse up click time, used to determine if this is a mouse
190 private long lastMouseUpTime
;
193 * The amount of millis between mouse up events to assume a double-click.
195 private long doubleClickTime
= 250;
198 * Event queue that is filled by run().
200 private List
<TInputEvent
> fillEventQueue
;
203 * Event queue that will be drained by either primary or secondary
206 private List
<TInputEvent
> drainEventQueue
;
209 * Top-level menus in this application.
211 private List
<TMenu
> menus
;
214 * Stack of activated sub-menus in this application.
216 private List
<TMenu
> subMenus
;
219 * The currently active menu.
221 private TMenu activeMenu
= null;
224 * Active keyboard accelerators.
226 private Map
<TKeypress
, TMenuItem
> accelerators
;
231 private List
<TMenuItem
> menuItems
;
234 * Windows and widgets pull colors from this ColorTheme.
236 private ColorTheme theme
;
239 * The top-level windows (but not menus).
241 private List
<TWindow
> windows
;
244 * The currently acive window.
246 private TWindow activeWindow
= null;
249 * Timers that are being ticked.
251 private List
<TTimer
> timers
;
254 * When true, the application has been started.
256 private volatile boolean started
= false;
259 * When true, exit the application.
261 private volatile boolean quit
= false;
264 * When true, repaint the entire screen.
266 private volatile boolean repaint
= true;
269 * Y coordinate of the top edge of the desktop. For now this is a
270 * constant. Someday it would be nice to have a multi-line menu or
273 private static final int desktopTop
= 1;
276 * Y coordinate of the bottom edge of the desktop.
278 private int desktopBottom
;
281 * An optional TDesktop background window that is drawn underneath
284 private TDesktop desktop
;
287 * If true, focus follows mouse: windows automatically raised if the
288 * mouse passes over them.
290 private boolean focusFollowsMouse
= false;
293 * The list of commands to run before the next I/O check.
295 private List
<Runnable
> invokeLaters
= new LinkedList
<Runnable
>();
298 * The last time the screen was resized.
300 private long screenResizeTime
= 0;
303 * WidgetEventHandler is the main event consumer loop. There are at most
304 * two such threads in existence: the primary for normal case and a
305 * secondary that is used for TMessageBox, TInputBox, and similar.
307 private class WidgetEventHandler
implements Runnable
{
309 * The main application.
311 private TApplication application
;
314 * Whether or not this WidgetEventHandler is the primary or secondary
317 private boolean primary
= true;
320 * Public constructor.
322 * @param application the main application
323 * @param primary if true, this is the primary event handler thread
325 public WidgetEventHandler(final TApplication application
,
326 final boolean primary
) {
328 this.application
= application
;
329 this.primary
= primary
;
336 // Wrap everything in a try, so that if we go belly up we can let
337 // the user have their terminal back.
340 } catch (Throwable t
) {
341 this.application
.restoreConsole();
343 this.application
.exit();
350 private void runImpl() {
351 boolean first
= true;
354 while (!application
.quit
) {
356 // Wait until application notifies me
357 while (!application
.quit
) {
359 synchronized (application
.drainEventQueue
) {
360 if (application
.drainEventQueue
.size() > 0) {
369 timeout
= application
.getSleepTime(1000);
373 // A timer needs to fire, break out.
378 System
.err
.printf("%d %s %s %s sleep %d millis\n",
379 System
.currentTimeMillis(), this,
380 primary ?
"primary" : "secondary",
381 Thread
.currentThread(), timeout
);
384 synchronized (this) {
389 System
.err
.printf("%d %s %s %s AWAKE\n",
390 System
.currentTimeMillis(), this,
391 primary ?
"primary" : "secondary",
392 Thread
.currentThread());
396 && (application
.secondaryEventReceiver
== null)
398 // Secondary thread, emergency exit. If we got
399 // here then something went wrong with the
400 // handoff between yield() and closeWindow().
401 synchronized (application
.primaryEventHandler
) {
402 application
.primaryEventHandler
.notify();
404 application
.secondaryEventHandler
= null;
405 throw new RuntimeException("secondary exited " +
409 } catch (InterruptedException e
) {
412 } // while (!application.quit)
414 // Pull all events off the queue
416 TInputEvent event
= null;
417 synchronized (application
.drainEventQueue
) {
418 if (application
.drainEventQueue
.size() == 0) {
421 event
= application
.drainEventQueue
.remove(0);
424 // We will have an event to process, so repaint the
425 // screen at the end.
426 application
.repaint
= true;
429 primaryHandleEvent(event
);
431 secondaryHandleEvent(event
);
434 && (application
.secondaryEventReceiver
== null)
436 // Secondary thread, time to exit.
438 // Eliminate my reference so that wakeEventHandler()
439 // resumes working on the primary.
440 application
.secondaryEventHandler
= null;
442 // We are ready to exit, wake up the primary thread.
443 // Remember that it is currently sleeping inside its
444 // primaryHandleEvent().
445 synchronized (application
.primaryEventHandler
) {
446 application
.primaryEventHandler
.notify();
455 // Fire timers, update screen.
457 application
.finishEventProcessing();
460 } // while (true) (main runnable loop)
465 * ScreenHandler pushes screen updates to the physical device.
467 private class ScreenHandler
implements Runnable
{
469 * The main application.
471 private TApplication application
;
476 private boolean dirty
= false;
479 * Public constructor.
481 * @param application the main application
483 public ScreenHandler(final TApplication application
) {
484 this.application
= application
;
488 * The screen update loop.
491 // Wrap everything in a try, so that if we go belly up we can let
492 // the user have their terminal back.
495 } catch (Throwable t
) {
496 this.application
.restoreConsole();
498 this.application
.exit();
505 private void runImpl() {
508 while (!application
.quit
) {
510 // Wait until application notifies me
511 while (!application
.quit
) {
513 synchronized (this) {
519 // Always check within 50 milliseconds.
522 } catch (InterruptedException e
) {
525 } // while (!application.quit)
527 // Flush the screen contents
529 System
.err
.printf("%d %s backend.flushScreen()\n",
530 System
.currentTimeMillis(), Thread
.currentThread());
532 synchronized (getScreen()) {
533 backend
.flushScreen();
535 } // while (true) (main runnable loop)
537 // Shutdown the user I/O thread(s)
542 * Set the dirty flag.
544 public void setDirty() {
545 synchronized (this) {
552 // ------------------------------------------------------------------------
553 // Constructors -----------------------------------------------------------
554 // ------------------------------------------------------------------------
557 * Public constructor.
559 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
561 * @param windowWidth the number of text columns to start with
562 * @param windowHeight the number of text rows to start with
563 * @param fontSize the size in points
564 * @throws UnsupportedEncodingException if an exception is thrown when
565 * creating the InputStreamReader
567 public TApplication(final BackendType backendType
, final int windowWidth
,
568 final int windowHeight
, final int fontSize
)
569 throws UnsupportedEncodingException
{
571 switch (backendType
) {
573 backend
= new SwingBackend(this, windowWidth
, windowHeight
,
579 backend
= new ECMA48Backend(this, null, null, windowWidth
,
580 windowHeight
, fontSize
);
583 throw new IllegalArgumentException("Invalid backend type: "
590 * Public constructor.
592 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
594 * @throws UnsupportedEncodingException if an exception is thrown when
595 * creating the InputStreamReader
597 public TApplication(final BackendType backendType
)
598 throws UnsupportedEncodingException
{
600 switch (backendType
) {
602 // The default SwingBackend is 80x25, 20 pt font. If you want to
603 // change that, you can pass the extra arguments to the
604 // SwingBackend constructor here. For example, if you wanted
605 // 90x30, 16 pt font:
607 // backend = new SwingBackend(this, 90, 30, 16);
608 backend
= new SwingBackend(this);
613 backend
= new ECMA48Backend(this, null, null);
616 throw new IllegalArgumentException("Invalid backend type: "
623 * Public constructor. The backend type will be BackendType.ECMA48.
625 * @param input an InputStream connected to the remote user, or null for
626 * System.in. If System.in is used, then on non-Windows systems it will
627 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
628 * mode. input is always converted to a Reader with UTF-8 encoding.
629 * @param output an OutputStream connected to the remote user, or null
630 * for System.out. output is always converted to a Writer with UTF-8
632 * @throws UnsupportedEncodingException if an exception is thrown when
633 * creating the InputStreamReader
635 public TApplication(final InputStream input
,
636 final OutputStream output
) throws UnsupportedEncodingException
{
638 backend
= new ECMA48Backend(this, input
, output
);
643 * Public constructor. The backend type will be BackendType.ECMA48.
645 * @param input the InputStream underlying 'reader'. Its available()
646 * method is used to determine if reader.read() will block or not.
647 * @param reader a Reader connected to the remote user.
648 * @param writer a PrintWriter connected to the remote user.
649 * @param setRawMode if true, set System.in into raw mode with stty.
650 * This should in general not be used. It is here solely for Demo3,
651 * which uses System.in.
652 * @throws IllegalArgumentException if input, reader, or writer are null.
654 public TApplication(final InputStream input
, final Reader reader
,
655 final PrintWriter writer
, final boolean setRawMode
) {
657 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
662 * Public constructor. The backend type will be BackendType.ECMA48.
664 * @param input the InputStream underlying 'reader'. Its available()
665 * method is used to determine if reader.read() will block or not.
666 * @param reader a Reader connected to the remote user.
667 * @param writer a PrintWriter connected to the remote user.
668 * @throws IllegalArgumentException if input, reader, or writer are null.
670 public TApplication(final InputStream input
, final Reader reader
,
671 final PrintWriter writer
) {
673 this(input
, reader
, writer
, false);
677 * Public constructor. This hook enables use with new non-Jexer
680 * @param backend a Backend that is already ready to go.
682 public TApplication(final Backend backend
) {
683 this.backend
= backend
;
684 backend
.setListener(this);
689 * Finish construction once the backend is set.
691 private void TApplicationImpl() {
692 theme
= new ColorTheme();
693 desktopBottom
= getScreen().getHeight() - 1;
694 fillEventQueue
= new LinkedList
<TInputEvent
>();
695 drainEventQueue
= new LinkedList
<TInputEvent
>();
696 windows
= new LinkedList
<TWindow
>();
697 menus
= new ArrayList
<TMenu
>();
698 subMenus
= new ArrayList
<TMenu
>();
699 timers
= new LinkedList
<TTimer
>();
700 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
701 menuItems
= new LinkedList
<TMenuItem
>();
702 desktop
= new TDesktop(this);
704 // Special case: the Swing backend needs to have a timer to drive its
706 if ((backend
instanceof SwingBackend
)
707 || (backend
instanceof MultiBackend
)
709 // Default to 500 millis, unless a SwingBackend has its own
712 if (backend
instanceof SwingBackend
) {
713 millis
= ((SwingBackend
) backend
).getBlinkMillis();
716 addTimer(millis
, true,
719 TApplication
.this.doRepaint();
727 // ------------------------------------------------------------------------
728 // Runnable ---------------------------------------------------------------
729 // ------------------------------------------------------------------------
732 * Run this application until it exits.
735 // System.err.println("*** TApplication.run() begins ***");
737 // Start the screen updater thread
738 screenHandler
= new ScreenHandler(this);
739 (new Thread(screenHandler
)).start();
741 // Start the main consumer thread
742 primaryEventHandler
= new WidgetEventHandler(this, true);
743 (new Thread(primaryEventHandler
)).start();
748 synchronized (this) {
749 boolean doWait
= false;
751 if (!backend
.hasEvents()) {
752 synchronized (fillEventQueue
) {
753 if (fillEventQueue
.size() == 0) {
760 // No I/O to dispatch, so wait until the backend
764 System
.err
.println(System
.currentTimeMillis() +
765 " " + Thread
.currentThread() + " MAIN sleep");
771 System
.err
.println(System
.currentTimeMillis() +
772 " " + Thread
.currentThread() + " MAIN AWAKE");
774 } catch (InterruptedException e
) {
775 // I'm awake and don't care why, let's see what's
776 // going on out there.
780 } // synchronized (this)
782 synchronized (fillEventQueue
) {
783 // Pull any pending I/O events
784 backend
.getEvents(fillEventQueue
);
786 // Dispatch each event to the appropriate handler, one at a
789 TInputEvent event
= null;
790 if (fillEventQueue
.size() == 0) {
793 event
= fillEventQueue
.remove(0);
794 metaHandleEvent(event
);
798 // Wake a consumer thread if we have any pending events.
799 if (drainEventQueue
.size() > 0) {
805 // Shutdown the event consumer threads
806 if (secondaryEventHandler
!= null) {
807 synchronized (secondaryEventHandler
) {
808 secondaryEventHandler
.notify();
811 if (primaryEventHandler
!= null) {
812 synchronized (primaryEventHandler
) {
813 primaryEventHandler
.notify();
817 // Close all the windows. This gives them an opportunity to release
821 // Give the overarching application an opportunity to release
825 // System.err.println("*** TApplication.run() exits ***");
828 // ------------------------------------------------------------------------
829 // Event handlers ---------------------------------------------------------
830 // ------------------------------------------------------------------------
833 * Method that TApplication subclasses can override to handle menu or
834 * posted command events.
836 * @param command command event
837 * @return if true, this event was consumed
839 protected boolean onCommand(final TCommandEvent command
) {
840 // Default: handle cmExit
841 if (command
.equals(cmExit
)) {
842 if (messageBox(i18n
.getString("exitDialogTitle"),
843 i18n
.getString("exitDialogText"),
844 TMessageBox
.Type
.YESNO
).isYes()) {
851 if (command
.equals(cmShell
)) {
852 openTerminal(0, 0, TWindow
.RESIZABLE
);
856 if (command
.equals(cmTile
)) {
860 if (command
.equals(cmCascade
)) {
864 if (command
.equals(cmCloseAll
)) {
869 if (command
.equals(cmMenu
)) {
870 if (!modalWindowActive() && (activeMenu
== null)) {
871 if (menus
.size() > 0) {
872 menus
.get(0).setActive(true);
873 activeMenu
= menus
.get(0);
883 * Method that TApplication subclasses can override to handle menu
886 * @param menu menu event
887 * @return if true, this event was consumed
889 protected boolean onMenu(final TMenuEvent menu
) {
891 // Default: handle MID_EXIT
892 if (menu
.getId() == TMenu
.MID_EXIT
) {
893 if (messageBox(i18n
.getString("exitDialogTitle"),
894 i18n
.getString("exitDialogText"),
895 TMessageBox
.Type
.YESNO
).isYes()) {
902 if (menu
.getId() == TMenu
.MID_SHELL
) {
903 openTerminal(0, 0, TWindow
.RESIZABLE
);
907 if (menu
.getId() == TMenu
.MID_TILE
) {
911 if (menu
.getId() == TMenu
.MID_CASCADE
) {
915 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
919 if (menu
.getId() == TMenu
.MID_ABOUT
) {
923 if (menu
.getId() == TMenu
.MID_REPAINT
) {
924 getScreen().clearPhysical();
928 if (menu
.getId() == TMenu
.MID_VIEW_IMAGE
) {
932 if (menu
.getId() == TMenu
.MID_SCREEN_OPTIONS
) {
933 new TFontChooserWindow(this);
940 * Method that TApplication subclasses can override to handle keystrokes.
942 * @param keypress keystroke event
943 * @return if true, this event was consumed
945 protected boolean onKeypress(final TKeypressEvent keypress
) {
946 // Default: only menu shortcuts
948 // Process Alt-F, Alt-E, etc. menu shortcut keys
949 if (!keypress
.getKey().isFnKey()
950 && keypress
.getKey().isAlt()
951 && !keypress
.getKey().isCtrl()
952 && (activeMenu
== null)
953 && !modalWindowActive()
956 assert (subMenus
.size() == 0);
958 for (TMenu menu
: menus
) {
959 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
960 == Character
.toLowerCase(keypress
.getKey().getChar())
963 menu
.setActive(true);
973 * Process background events, and update the screen.
975 private void finishEventProcessing() {
977 System
.err
.printf(System
.currentTimeMillis() + " " +
978 Thread
.currentThread() + " finishEventProcessing()\n");
981 // Process timers and call doIdle()'s
985 synchronized (getScreen()) {
989 // Wake up the screen repainter
993 System
.err
.printf(System
.currentTimeMillis() + " " +
994 Thread
.currentThread() + " finishEventProcessing() END\n");
999 * Peek at certain application-level events, add to eventQueue, and wake
1000 * up the consuming Thread.
1002 * @param event the input event to consume
1004 private void metaHandleEvent(final TInputEvent event
) {
1007 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1008 event
)); System
.err
.flush();
1012 // Do no more processing if the application is already trying
1017 // Special application-wide events -------------------------------
1020 if (event
instanceof TCommandEvent
) {
1021 TCommandEvent command
= (TCommandEvent
) event
;
1022 if (command
.equals(cmAbort
)) {
1028 synchronized (drainEventQueue
) {
1030 if (event
instanceof TResizeEvent
) {
1031 TResizeEvent resize
= (TResizeEvent
) event
;
1032 synchronized (getScreen()) {
1033 if ((System
.currentTimeMillis() - screenResizeTime
>= 15)
1034 || (resize
.getWidth() < getScreen().getWidth())
1035 || (resize
.getHeight() < getScreen().getHeight())
1037 getScreen().setDimensions(resize
.getWidth(),
1038 resize
.getHeight());
1039 screenResizeTime
= System
.currentTimeMillis();
1041 desktopBottom
= getScreen().getHeight() - 1;
1047 if (desktop
!= null) {
1048 desktop
.setDimensions(0, 0, resize
.getWidth(),
1049 resize
.getHeight() - 1);
1050 desktop
.onResize(resize
);
1053 // Change menu edges if needed.
1056 // We are dirty, redraw the screen.
1060 System.err.println("New screen: " + resize.getWidth() +
1061 " x " + resize.getHeight());
1066 // Put into the main queue
1067 drainEventQueue
.add(event
);
1072 * Dispatch one event to the appropriate widget or application-level
1073 * event handler. This is the primary event handler, it has the normal
1074 * application-wide event handling.
1076 * @param event the input event to consume
1077 * @see #secondaryHandleEvent(TInputEvent event)
1079 private void primaryHandleEvent(final TInputEvent event
) {
1082 System
.err
.printf("%s primaryHandleEvent: %s\n",
1083 Thread
.currentThread(), event
);
1085 TMouseEvent doubleClick
= null;
1087 // Special application-wide events -----------------------------------
1089 // Peek at the mouse position
1090 if (event
instanceof TMouseEvent
) {
1091 TMouseEvent mouse
= (TMouseEvent
) event
;
1092 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1095 mouseX
= mouse
.getX();
1096 mouseY
= mouse
.getY();
1098 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1099 && (!mouse
.isMouseWheelUp())
1100 && (!mouse
.isMouseWheelDown())
1102 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1105 // This is a double-click.
1106 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1108 mouse
.getX(), mouse
.getY(),
1109 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1110 mouse
.isMouse1(), mouse
.isMouse2(),
1112 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1115 // The first click of a potential double-click.
1116 lastMouseUpTime
= mouse
.getTime().getTime();
1121 // See if we need to switch focus to another window or the menu
1122 checkSwitchFocus((TMouseEvent
) event
);
1125 // Handle menu events
1126 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1127 TMenu menu
= activeMenu
;
1129 if (event
instanceof TMouseEvent
) {
1130 TMouseEvent mouse
= (TMouseEvent
) event
;
1132 while (subMenus
.size() > 0) {
1133 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1134 if (subMenu
.mouseWouldHit(mouse
)) {
1137 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1138 && (!mouse
.isMouse1())
1139 && (!mouse
.isMouse2())
1140 && (!mouse
.isMouse3())
1141 && (!mouse
.isMouseWheelUp())
1142 && (!mouse
.isMouseWheelDown())
1146 // We navigated away from a sub-menu, so close it
1150 // Convert the mouse relative x/y to menu coordinates
1151 assert (mouse
.getX() == mouse
.getAbsoluteX());
1152 assert (mouse
.getY() == mouse
.getAbsoluteY());
1153 if (subMenus
.size() > 0) {
1154 menu
= subMenus
.get(subMenus
.size() - 1);
1156 mouse
.setX(mouse
.getX() - menu
.getX());
1157 mouse
.setY(mouse
.getY() - menu
.getY());
1159 menu
.handleEvent(event
);
1163 if (event
instanceof TKeypressEvent
) {
1164 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1166 // See if this key matches an accelerator, and is not being
1167 // shortcutted by the active window, and if so dispatch the menu
1169 boolean windowWillShortcut
= false;
1170 if (activeWindow
!= null) {
1171 assert (activeWindow
.isShown());
1172 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1173 // We do not process this key, it will be passed to the
1175 windowWillShortcut
= true;
1179 if (!windowWillShortcut
&& !modalWindowActive()) {
1180 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1181 TMenuItem item
= null;
1182 synchronized (accelerators
) {
1183 item
= accelerators
.get(keypressLowercase
);
1186 if (item
.isEnabled()) {
1187 // Let the menu item dispatch
1193 // Handle the keypress
1194 if (onKeypress(keypress
)) {
1200 if (event
instanceof TCommandEvent
) {
1201 if (onCommand((TCommandEvent
) event
)) {
1206 if (event
instanceof TMenuEvent
) {
1207 if (onMenu((TMenuEvent
) event
)) {
1212 // Dispatch events to the active window -------------------------------
1213 boolean dispatchToDesktop
= true;
1214 TWindow window
= activeWindow
;
1215 if (window
!= null) {
1216 assert (window
.isActive());
1217 assert (window
.isShown());
1218 if (event
instanceof TMouseEvent
) {
1219 TMouseEvent mouse
= (TMouseEvent
) event
;
1220 // Convert the mouse relative x/y to window coordinates
1221 assert (mouse
.getX() == mouse
.getAbsoluteX());
1222 assert (mouse
.getY() == mouse
.getAbsoluteY());
1223 mouse
.setX(mouse
.getX() - window
.getX());
1224 mouse
.setY(mouse
.getY() - window
.getY());
1226 if (doubleClick
!= null) {
1227 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1228 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1231 if (window
.mouseWouldHit(mouse
)) {
1232 dispatchToDesktop
= false;
1234 } else if (event
instanceof TKeypressEvent
) {
1235 dispatchToDesktop
= false;
1239 System
.err
.printf("TApplication dispatch event: %s\n",
1242 window
.handleEvent(event
);
1243 if (doubleClick
!= null) {
1244 window
.handleEvent(doubleClick
);
1247 if (dispatchToDesktop
) {
1248 // This event is fair game for the desktop to process.
1249 if (desktop
!= null) {
1250 desktop
.handleEvent(event
);
1251 if (doubleClick
!= null) {
1252 desktop
.handleEvent(doubleClick
);
1259 * Dispatch one event to the appropriate widget or application-level
1260 * event handler. This is the secondary event handler used by certain
1261 * special dialogs (currently TMessageBox and TFileOpenBox).
1263 * @param event the input event to consume
1264 * @see #primaryHandleEvent(TInputEvent event)
1266 private void secondaryHandleEvent(final TInputEvent event
) {
1267 TMouseEvent doubleClick
= null;
1270 System
.err
.printf("%s secondaryHandleEvent: %s\n",
1271 Thread
.currentThread(), event
);
1274 // Peek at the mouse position
1275 if (event
instanceof TMouseEvent
) {
1276 TMouseEvent mouse
= (TMouseEvent
) event
;
1277 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1280 mouseX
= mouse
.getX();
1281 mouseY
= mouse
.getY();
1283 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1284 && (!mouse
.isMouseWheelUp())
1285 && (!mouse
.isMouseWheelDown())
1287 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1290 // This is a double-click.
1291 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1293 mouse
.getX(), mouse
.getY(),
1294 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1295 mouse
.isMouse1(), mouse
.isMouse2(),
1297 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1300 // The first click of a potential double-click.
1301 lastMouseUpTime
= mouse
.getTime().getTime();
1307 secondaryEventReceiver
.handleEvent(event
);
1308 // Note that it is possible for secondaryEventReceiver to be null
1309 // now, because its handleEvent() might have finished out on the
1310 // secondary thread. So put any extra processing inside a null
1312 if (secondaryEventReceiver
!= null) {
1313 if (doubleClick
!= null) {
1314 secondaryEventReceiver
.handleEvent(doubleClick
);
1320 * Enable a widget to override the primary event thread.
1322 * @param widget widget that will receive events
1324 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1326 System
.err
.println(System
.currentTimeMillis() +
1327 " enableSecondaryEventReceiver()");
1330 assert (secondaryEventReceiver
== null);
1331 assert (secondaryEventHandler
== null);
1332 assert ((widget
instanceof TMessageBox
)
1333 || (widget
instanceof TFileOpenBox
));
1334 secondaryEventReceiver
= widget
;
1335 secondaryEventHandler
= new WidgetEventHandler(this, false);
1337 (new Thread(secondaryEventHandler
)).start();
1341 * Yield to the secondary thread.
1343 public final void yield() {
1345 System
.err
.printf(System
.currentTimeMillis() + " " +
1346 Thread
.currentThread() + " yield()\n");
1349 assert (secondaryEventReceiver
!= null);
1351 while (secondaryEventReceiver
!= null) {
1352 synchronized (primaryEventHandler
) {
1354 primaryEventHandler
.wait();
1355 } catch (InterruptedException e
) {
1363 * Do stuff when there is no user input.
1365 private void doIdle() {
1367 System
.err
.printf(System
.currentTimeMillis() + " " +
1368 Thread
.currentThread() + " doIdle()\n");
1371 synchronized (timers
) {
1374 System
.err
.printf(System
.currentTimeMillis() + " " +
1375 Thread
.currentThread() + " doIdle() 2\n");
1378 // Run any timers that have timed out
1379 Date now
= new Date();
1380 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1381 for (TTimer timer
: timers
) {
1382 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1383 // Something might change, so repaint the screen.
1386 if (timer
.recurring
) {
1387 keepTimers
.add(timer
);
1390 keepTimers
.add(timer
);
1394 timers
.addAll(keepTimers
);
1398 for (TWindow window
: windows
) {
1401 if (desktop
!= null) {
1405 // Run any invokeLaters
1406 synchronized (invokeLaters
) {
1407 for (Runnable invoke
: invokeLaters
) {
1410 invokeLaters
.clear();
1416 * Wake the sleeping active event handler.
1418 private void wakeEventHandler() {
1423 if (secondaryEventHandler
!= null) {
1424 synchronized (secondaryEventHandler
) {
1425 secondaryEventHandler
.notify();
1428 assert (primaryEventHandler
!= null);
1429 synchronized (primaryEventHandler
) {
1430 primaryEventHandler
.notify();
1436 * Wake the sleeping screen handler.
1438 private void wakeScreenHandler() {
1443 synchronized (screenHandler
) {
1444 screenHandler
.notify();
1448 // ------------------------------------------------------------------------
1449 // TApplication -----------------------------------------------------------
1450 // ------------------------------------------------------------------------
1453 * Place a command on the run queue, and run it before the next round of
1456 * @param command the command to run later
1458 public void invokeLater(final Runnable command
) {
1459 synchronized (invokeLaters
) {
1460 invokeLaters
.add(command
);
1466 * Restore the console to sane defaults. This is meant to be used for
1467 * improper exits (e.g. a caught exception in main()), and should not be
1468 * necessary for normal program termination.
1470 public void restoreConsole() {
1471 if (backend
!= null) {
1472 if (backend
instanceof ECMA48Backend
) {
1481 * @return the Backend
1483 public final Backend
getBackend() {
1490 * @return the Screen
1492 public final Screen
getScreen() {
1493 if (backend
instanceof TWindowBackend
) {
1494 // We are being rendered to a TWindow. We can't use its
1495 // getScreen() method because that is how it is rendering to a
1496 // hardware backend somewhere. Instead use its getOtherScreen()
1498 return ((TWindowBackend
) backend
).getOtherScreen();
1500 return backend
.getScreen();
1505 * Get the color theme.
1509 public final ColorTheme
getTheme() {
1514 * Repaint the screen on the next update.
1516 public void doRepaint() {
1522 * Get Y coordinate of the top edge of the desktop.
1524 * @return Y coordinate of the top edge of the desktop
1526 public final int getDesktopTop() {
1531 * Get Y coordinate of the bottom edge of the desktop.
1533 * @return Y coordinate of the bottom edge of the desktop
1535 public final int getDesktopBottom() {
1536 return desktopBottom
;
1540 * Set the TDesktop instance.
1542 * @param desktop a TDesktop instance, or null to remove the one that is
1545 public final void setDesktop(final TDesktop desktop
) {
1546 if (this.desktop
!= null) {
1547 this.desktop
.onClose();
1549 this.desktop
= desktop
;
1553 * Get the TDesktop instance.
1555 * @return the desktop, or null if it is not set
1557 public final TDesktop
getDesktop() {
1562 * Get the current active window.
1564 * @return the active window, or null if it is not set
1566 public final TWindow
getActiveWindow() {
1567 return activeWindow
;
1571 * Get a (shallow) copy of the window list.
1573 * @return a copy of the list of windows for this application
1575 public final List
<TWindow
> getAllWindows() {
1576 List
<TWindow
> result
= new ArrayList
<TWindow
>();
1577 result
.addAll(windows
);
1582 * Get focusFollowsMouse flag.
1584 * @return true if focus follows mouse: windows automatically raised if
1585 * the mouse passes over them
1587 public boolean getFocusFollowsMouse() {
1588 return focusFollowsMouse
;
1592 * Set focusFollowsMouse flag.
1594 * @param focusFollowsMouse if true, focus follows mouse: windows
1595 * automatically raised if the mouse passes over them
1597 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
1598 this.focusFollowsMouse
= focusFollowsMouse
;
1602 * Display the about dialog.
1604 protected void showAboutDialog() {
1605 String version
= getClass().getPackage().getImplementationVersion();
1606 if (version
== null) {
1607 // This is Java 9+, use a hardcoded string here.
1610 messageBox(i18n
.getString("aboutDialogTitle"),
1611 MessageFormat
.format(i18n
.getString("aboutDialogText"), version
),
1612 TMessageBox
.Type
.OK
);
1616 * Handle the Tool | Open image menu item.
1618 private void openImage() {
1620 List
<String
> filters
= new ArrayList
<String
>();
1621 filters
.add("^.*\\.[Jj][Pp][Gg]$");
1622 filters
.add("^.*\\.[Jj][Pp][Ee][Gg]$");
1623 filters
.add("^.*\\.[Pp][Nn][Gg]$");
1624 filters
.add("^.*\\.[Gg][Ii][Ff]$");
1625 filters
.add("^.*\\.[Bb][Mm][Pp]$");
1626 String filename
= fileOpenBox(".", TFileOpenBox
.Type
.OPEN
, filters
);
1627 if (filename
!= null) {
1628 new TImageWindow(this, new File(filename
));
1630 } catch (IOException e
) {
1631 // Show this exception to the user.
1632 new TExceptionDialog(this, e
);
1637 * Check if application is still running.
1639 * @return true if the application is running
1641 public final boolean isRunning() {
1648 // ------------------------------------------------------------------------
1649 // Screen refresh loop ----------------------------------------------------
1650 // ------------------------------------------------------------------------
1653 * Invert the cell color at a position. This is used to track the mouse.
1655 * @param x column position
1656 * @param y row position
1658 private void invertCell(final int x
, final int y
) {
1659 invertCell(x
, y
, false);
1663 * Invert the cell color at a position. This is used to track the mouse.
1665 * @param x column position
1666 * @param y row position
1667 * @param onlyThisCell if true, only invert this cell
1669 private void invertCell(final int x
, final int y
,
1670 final boolean onlyThisCell
) {
1673 System
.err
.printf("%d %s invertCell() %d %d\n",
1674 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1676 if (activeWindow
!= null) {
1677 System
.err
.println("activeWindow.hasHiddenMouse() " +
1678 activeWindow
.hasHiddenMouse());
1682 // If this cell is on top of a visible window that has requested a
1683 // hidden mouse, bail out.
1684 if ((activeWindow
!= null) && (activeMenu
== null)) {
1685 if ((activeWindow
.hasHiddenMouse() == true)
1686 && (x
> activeWindow
.getX())
1687 && (x
< activeWindow
.getX() + activeWindow
.getWidth() - 1)
1688 && (y
> activeWindow
.getY())
1689 && (y
< activeWindow
.getY() + activeWindow
.getHeight() - 1)
1695 Cell cell
= getScreen().getCharXY(x
, y
);
1696 if (cell
.isImage()) {
1699 if (cell
.getForeColorRGB() < 0) {
1700 cell
.setForeColor(cell
.getForeColor().invert());
1702 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1704 if (cell
.getBackColorRGB() < 0) {
1705 cell
.setBackColor(cell
.getBackColor().invert());
1707 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1710 getScreen().putCharXY(x
, y
, cell
);
1711 if ((onlyThisCell
== true) || (cell
.getWidth() == Cell
.Width
.SINGLE
)) {
1715 // This cell is one half of a fullwidth glyph. Invert the other
1717 if (cell
.getWidth() == Cell
.Width
.LEFT
) {
1718 if (x
< getScreen().getWidth() - 1) {
1719 Cell rightHalf
= getScreen().getCharXY(x
+ 1, y
);
1720 if (rightHalf
.getWidth() == Cell
.Width
.RIGHT
) {
1721 invertCell(x
+ 1, y
, true);
1726 if (cell
.getWidth() == Cell
.Width
.RIGHT
) {
1728 Cell leftHalf
= getScreen().getCharXY(x
- 1, y
);
1729 if (leftHalf
.getWidth() == Cell
.Width
.LEFT
) {
1730 invertCell(x
- 1, y
, true);
1739 private void drawAll() {
1740 boolean menuIsActive
= false;
1743 System
.err
.printf("%d %s drawAll() enter\n",
1744 System
.currentTimeMillis(), Thread
.currentThread());
1747 // I don't think this does anything useful anymore...
1750 System
.err
.printf("%d %s drawAll() !repaint\n",
1751 System
.currentTimeMillis(), Thread
.currentThread());
1753 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1755 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1756 System
.currentTimeMillis(), Thread
.currentThread());
1759 // The only thing that has happened is the mouse moved.
1761 // Redraw the old cell at that position, and save the cell at
1762 // the new mouse position.
1764 System
.err
.printf("%d %s restoreImage() %d %d\n",
1765 System
.currentTimeMillis(), Thread
.currentThread(),
1766 oldDrawnMouseX
, oldDrawnMouseY
);
1768 oldDrawnMouseCell
.restoreImage();
1769 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1771 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1772 if (backend
instanceof ECMA48Backend
) {
1773 // Special case: the entire row containing the mouse has
1774 // to be re-drawn if it has any image data, AND any rows
1776 if (oldDrawnMouseY
!= mouseY
) {
1777 for (int i
= oldDrawnMouseY
; ;) {
1778 getScreen().unsetImageRow(i
);
1782 if (oldDrawnMouseY
< mouseY
) {
1789 getScreen().unsetImageRow(mouseY
);
1793 // Draw mouse at the new position.
1794 invertCell(mouseX
, mouseY
);
1796 oldDrawnMouseX
= mouseX
;
1797 oldDrawnMouseY
= mouseY
;
1799 if (getScreen().isDirty()) {
1800 screenHandler
.setDirty();
1806 System
.err
.printf("%d %s drawAll() REDRAW\n",
1807 System
.currentTimeMillis(), Thread
.currentThread());
1810 // If true, the cursor is not visible
1811 boolean cursor
= false;
1813 // Start with a clean screen
1814 getScreen().clear();
1817 if (desktop
!= null) {
1818 desktop
.drawChildren();
1821 // Draw each window in reverse Z order
1822 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1823 Collections
.sort(sorted
);
1824 TWindow topLevel
= null;
1825 if (sorted
.size() > 0) {
1826 topLevel
= sorted
.get(0);
1828 Collections
.reverse(sorted
);
1829 for (TWindow window
: sorted
) {
1830 if (window
.isShown()) {
1831 window
.drawChildren();
1835 // Draw the blank menubar line - reset the screen clipping first so
1836 // it won't trim it out.
1837 getScreen().resetClipping();
1838 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1839 theme
.getColor("tmenu"));
1840 // Now draw the menus.
1842 for (TMenu menu
: menus
) {
1843 CellAttributes menuColor
;
1844 CellAttributes menuMnemonicColor
;
1845 if (menu
.isActive()) {
1846 menuIsActive
= true;
1847 menuColor
= theme
.getColor("tmenu.highlighted");
1848 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1851 menuColor
= theme
.getColor("tmenu");
1852 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1854 // Draw the menu title
1855 getScreen().hLineXY(x
, 0, StringUtils
.width(menu
.getTitle()) + 2, ' ',
1857 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1858 // Draw the highlight character
1859 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
1860 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1862 if (menu
.isActive()) {
1863 ((TWindow
) menu
).drawChildren();
1864 // Reset the screen clipping so we can draw the next title.
1865 getScreen().resetClipping();
1867 x
+= StringUtils
.width(menu
.getTitle()) + 2;
1870 for (TMenu menu
: subMenus
) {
1871 // Reset the screen clipping so we can draw the next sub-menu.
1872 getScreen().resetClipping();
1873 ((TWindow
) menu
).drawChildren();
1875 getScreen().resetClipping();
1877 // Draw the status bar of the top-level window
1878 TStatusBar statusBar
= null;
1879 if (topLevel
!= null) {
1880 statusBar
= topLevel
.getStatusBar();
1882 if (statusBar
!= null) {
1883 getScreen().resetClipping();
1884 statusBar
.setWidth(getScreen().getWidth());
1885 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1888 CellAttributes barColor
= new CellAttributes();
1889 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1890 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
1894 // Draw the mouse pointer
1896 System
.err
.printf("%d %s restoreImage() %d %d\n",
1897 System
.currentTimeMillis(), Thread
.currentThread(),
1898 oldDrawnMouseX
, oldDrawnMouseY
);
1900 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1901 if (backend
instanceof ECMA48Backend
) {
1902 // Special case: the entire row containing the mouse has to be
1903 // re-drawn if it has any image data, AND any rows in between.
1904 if (oldDrawnMouseY
!= mouseY
) {
1905 for (int i
= oldDrawnMouseY
; ;) {
1906 getScreen().unsetImageRow(i
);
1910 if (oldDrawnMouseY
< mouseY
) {
1917 getScreen().unsetImageRow(mouseY
);
1920 invertCell(mouseX
, mouseY
);
1921 oldDrawnMouseX
= mouseX
;
1922 oldDrawnMouseY
= mouseY
;
1924 // Place the cursor if it is visible
1925 if (!menuIsActive
) {
1926 TWidget activeWidget
= null;
1927 if (sorted
.size() > 0) {
1928 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
1929 if (activeWidget
.isCursorVisible()) {
1930 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
1931 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
1933 getScreen().putCursor(true,
1934 activeWidget
.getCursorAbsoluteX(),
1935 activeWidget
.getCursorAbsoluteY());
1938 // Turn off the cursor. Also place it at 0,0.
1939 getScreen().putCursor(false, 0, 0);
1948 getScreen().hideCursor();
1951 if (getScreen().isDirty()) {
1952 screenHandler
.setDirty();
1958 * Force this application to exit.
1960 public void exit() {
1962 synchronized (this) {
1968 * Subclasses can use this hook to cleanup resources. Called as the last
1969 * step of TApplication.run().
1971 public void onExit() {
1972 // Default does nothing.
1975 // ------------------------------------------------------------------------
1976 // TWindow management -----------------------------------------------------
1977 // ------------------------------------------------------------------------
1980 * Return the total number of windows.
1982 * @return the total number of windows
1984 public final int windowCount() {
1985 return windows
.size();
1989 * Return the number of windows that are showing.
1991 * @return the number of windows that are showing on screen
1993 public final int shownWindowCount() {
1995 for (TWindow w
: windows
) {
2004 * Return the number of windows that are hidden.
2006 * @return the number of windows that are hidden
2008 public final int hiddenWindowCount() {
2010 for (TWindow w
: windows
) {
2019 * Check if a window instance is in this application's window list.
2021 * @param window window to look for
2022 * @return true if this window is in the list
2024 public final boolean hasWindow(final TWindow window
) {
2025 if (windows
.size() == 0) {
2028 for (TWindow w
: windows
) {
2030 assert (window
.getApplication() == this);
2038 * Activate a window: bring it to the top and have it receive events.
2040 * @param window the window to become the new active window
2042 public void activateWindow(final TWindow window
) {
2043 if (hasWindow(window
) == false) {
2045 * Someone has a handle to a window I don't have. Ignore this
2051 // Whatever window might be moving/dragging, stop it now.
2052 for (TWindow w
: windows
) {
2053 if (w
.inMovements()) {
2058 assert (windows
.size() > 0);
2060 if (window
.isHidden()) {
2061 // Unhiding will also activate.
2065 assert (window
.isShown());
2067 if (windows
.size() == 1) {
2068 assert (window
== windows
.get(0));
2069 if (activeWindow
== null) {
2070 activeWindow
= window
;
2072 activeWindow
.setActive(true);
2073 activeWindow
.onFocus();
2076 assert (window
.isActive());
2077 assert (activeWindow
== window
);
2081 if (activeWindow
== window
) {
2082 assert (window
.isActive());
2084 // Window is already active, do nothing.
2088 assert (!window
.isActive());
2089 if (activeWindow
!= null) {
2090 // TODO: see if this assertion is really necessary.
2091 // assert (activeWindow.getZ() == 0);
2093 activeWindow
.setActive(false);
2095 // Increment every window Z that is on top of window
2096 for (TWindow w
: windows
) {
2100 if (w
.getZ() < window
.getZ()) {
2101 w
.setZ(w
.getZ() + 1);
2105 // Unset activeWindow now before unfocus, so that a window
2106 // lifecycle change inside onUnfocus() doesn't call
2107 // switchWindow() and lead to a stack overflow.
2108 TWindow oldActiveWindow
= activeWindow
;
2109 activeWindow
= null;
2110 oldActiveWindow
.onUnfocus();
2112 activeWindow
= window
;
2113 activeWindow
.setZ(0);
2114 activeWindow
.setActive(true);
2115 activeWindow
.onFocus();
2122 * @param window the window to hide
2124 public void hideWindow(final TWindow window
) {
2125 if (hasWindow(window
) == false) {
2127 * Someone has a handle to a window I don't have. Ignore this
2133 // Whatever window might be moving/dragging, stop it now.
2134 for (TWindow w
: windows
) {
2135 if (w
.inMovements()) {
2140 assert (windows
.size() > 0);
2142 if (!window
.hidden
) {
2143 if (window
== activeWindow
) {
2144 if (shownWindowCount() > 1) {
2147 activeWindow
= null;
2148 window
.setActive(false);
2152 window
.hidden
= true;
2160 * @param window the window to show
2162 public void showWindow(final TWindow window
) {
2163 if (hasWindow(window
) == false) {
2165 * Someone has a handle to a window I don't have. Ignore this
2171 // Whatever window might be moving/dragging, stop it now.
2172 for (TWindow w
: windows
) {
2173 if (w
.inMovements()) {
2178 assert (windows
.size() > 0);
2180 if (window
.hidden
) {
2181 window
.hidden
= false;
2183 activateWindow(window
);
2188 * Close window. Note that the window's destructor is NOT called by this
2189 * method, instead the GC is assumed to do the cleanup.
2191 * @param window the window to remove
2193 public final void closeWindow(final TWindow window
) {
2194 if (hasWindow(window
) == false) {
2196 * Someone has a handle to a window I don't have. Ignore this
2202 // Let window know that it is about to be closed, while it is still
2203 // visible on screen.
2204 window
.onPreClose();
2206 synchronized (windows
) {
2207 // Whatever window might be moving/dragging, stop it now.
2208 for (TWindow w
: windows
) {
2209 if (w
.inMovements()) {
2214 int z
= window
.getZ();
2217 windows
.remove(window
);
2218 Collections
.sort(windows
);
2219 activeWindow
= null;
2221 boolean foundNextWindow
= false;
2223 for (TWindow w
: windows
) {
2227 // Do not activate a hidden window.
2232 if (foundNextWindow
== false) {
2233 foundNextWindow
= true;
2236 assert (activeWindow
== null);
2248 // Perform window cleanup
2251 // Check if we are closing a TMessageBox or similar
2252 if (secondaryEventReceiver
!= null) {
2253 assert (secondaryEventHandler
!= null);
2255 // Do not send events to the secondaryEventReceiver anymore, the
2256 // window is closed.
2257 secondaryEventReceiver
= null;
2259 // Wake the secondary thread, it will wake the primary as it
2261 synchronized (secondaryEventHandler
) {
2262 secondaryEventHandler
.notify();
2266 // Permit desktop to be active if it is the only thing left.
2267 if (desktop
!= null) {
2268 if (windows
.size() == 0) {
2269 desktop
.setActive(true);
2275 * Switch to the next window.
2277 * @param forward if true, then switch to the next window in the list,
2278 * otherwise switch to the previous window in the list
2280 public final void switchWindow(final boolean forward
) {
2281 // Only switch if there are multiple visible windows
2282 if (shownWindowCount() < 2) {
2285 assert (activeWindow
!= null);
2287 synchronized (windows
) {
2288 // Whatever window might be moving/dragging, stop it now.
2289 for (TWindow w
: windows
) {
2290 if (w
.inMovements()) {
2295 // Swap z/active between active window and the next in the list
2296 int activeWindowI
= -1;
2297 for (int i
= 0; i
< windows
.size(); i
++) {
2298 if (windows
.get(i
) == activeWindow
) {
2299 assert (activeWindow
.isActive());
2303 assert (!windows
.get(0).isActive());
2306 assert (activeWindowI
>= 0);
2308 // Do not switch if a window is modal
2309 if (activeWindow
.isModal()) {
2313 int nextWindowI
= activeWindowI
;
2317 nextWindowI
%= windows
.size();
2320 if (nextWindowI
< 0) {
2321 nextWindowI
= windows
.size() - 1;
2325 if (windows
.get(nextWindowI
).isShown()) {
2326 activateWindow(windows
.get(nextWindowI
));
2330 } // synchronized (windows)
2335 * Add a window to my window list and make it active. Note package
2338 * @param window new window to add
2340 final void addWindowToApplication(final TWindow window
) {
2342 // Do not add menu windows to the window list.
2343 if (window
instanceof TMenu
) {
2347 // Do not add the desktop to the window list.
2348 if (window
instanceof TDesktop
) {
2352 synchronized (windows
) {
2353 if (windows
.contains(window
)) {
2354 throw new IllegalArgumentException("Window " + window
+
2355 " is already in window list");
2358 // Whatever window might be moving/dragging, stop it now.
2359 for (TWindow w
: windows
) {
2360 if (w
.inMovements()) {
2365 // Do not allow a modal window to spawn a non-modal window. If a
2366 // modal window is active, then this window will become modal
2368 if (modalWindowActive()) {
2369 window
.flags
|= TWindow
.MODAL
;
2370 window
.flags
|= TWindow
.CENTERED
;
2371 window
.hidden
= false;
2373 if (window
.isShown()) {
2374 for (TWindow w
: windows
) {
2379 w
.setZ(w
.getZ() + 1);
2382 windows
.add(window
);
2383 if (window
.isShown()) {
2384 activeWindow
= window
;
2385 activeWindow
.setZ(0);
2386 activeWindow
.setActive(true);
2387 activeWindow
.onFocus();
2390 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2391 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2392 && (smartWindowPlacement
== true)
2395 doSmartPlacement(window
);
2399 // Desktop cannot be active over any other window.
2400 if (desktop
!= null) {
2401 desktop
.setActive(false);
2406 * Check if there is a system-modal window on top.
2408 * @return true if the active window is modal
2410 private boolean modalWindowActive() {
2411 if (windows
.size() == 0) {
2415 for (TWindow w
: windows
) {
2425 * Check if there is a window with overridden menu flag on top.
2427 * @return true if the active window is overriding the menu
2429 private boolean overrideMenuWindowActive() {
2430 if (activeWindow
!= null) {
2431 if (activeWindow
.hasOverriddenMenu()) {
2440 * Close all open windows.
2442 private void closeAllWindows() {
2443 // Don't do anything if we are in the menu
2444 if (activeMenu
!= null) {
2447 while (windows
.size() > 0) {
2448 closeWindow(windows
.get(0));
2453 * Re-layout the open windows as non-overlapping tiles. This produces
2454 * almost the same results as Turbo Pascal 7.0's IDE.
2456 private void tileWindows() {
2457 synchronized (windows
) {
2458 // Don't do anything if we are in the menu
2459 if (activeMenu
!= null) {
2462 int z
= windows
.size();
2468 a
= (int)(Math
.sqrt(z
));
2472 if (((a
* b
) + c
) == z
) {
2480 int newWidth
= (getScreen().getWidth() / a
);
2481 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2482 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2484 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2485 Collections
.sort(sorted
);
2486 Collections
.reverse(sorted
);
2487 for (int i
= 0; i
< sorted
.size(); i
++) {
2488 int logicalX
= i
/ b
;
2489 int logicalY
= i
% b
;
2490 if (i
>= ((a
- 1) * b
)) {
2492 logicalY
= i
- ((a
- 1) * b
);
2495 TWindow w
= sorted
.get(i
);
2496 int oldWidth
= w
.getWidth();
2497 int oldHeight
= w
.getHeight();
2499 w
.setX(logicalX
* newWidth
);
2500 w
.setWidth(newWidth
);
2501 if (i
>= ((a
- 1) * b
)) {
2502 w
.setY((logicalY
* newHeight2
) + 1);
2503 w
.setHeight(newHeight2
);
2505 w
.setY((logicalY
* newHeight1
) + 1);
2506 w
.setHeight(newHeight1
);
2508 if ((w
.getWidth() != oldWidth
)
2509 || (w
.getHeight() != oldHeight
)
2511 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2512 w
.getWidth(), w
.getHeight()));
2519 * Re-layout the open windows as overlapping cascaded windows.
2521 private void cascadeWindows() {
2522 synchronized (windows
) {
2523 // Don't do anything if we are in the menu
2524 if (activeMenu
!= null) {
2529 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2530 Collections
.sort(sorted
);
2531 Collections
.reverse(sorted
);
2532 for (TWindow window
: sorted
) {
2537 if (x
> getScreen().getWidth()) {
2540 if (y
>= getScreen().getHeight()) {
2548 * Place a window to minimize its overlap with other windows.
2550 * @param window the window to place
2552 public final void doSmartPlacement(final TWindow window
) {
2553 // This is a pretty dumb algorithm, but seems to work. The hardest
2554 // part is computing these "overlap" values seeking a minimum average
2557 int yMin
= desktopTop
;
2558 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2559 int yMax
= desktopBottom
- window
.getHeight() + 1;
2567 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2568 // No work to do, bail out.
2572 // Compute the overlap matrix without the new window.
2573 int width
= getScreen().getWidth();
2574 int height
= getScreen().getHeight();
2575 int overlapMatrix
[][] = new int[width
][height
];
2576 for (TWindow w
: windows
) {
2580 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2587 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2594 overlapMatrix
[x
][y
]++;
2599 long oldOverlapTotal
= 0;
2600 long oldOverlapN
= 0;
2601 for (int x
= 0; x
< width
; x
++) {
2602 for (int y
= 0; y
< height
; y
++) {
2603 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2604 if (overlapMatrix
[x
][y
] > 0) {
2611 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2612 boolean first
= true;
2613 int windowX
= window
.getX();
2614 int windowY
= window
.getY();
2616 // For each possible (x, y) position for the new window, compute a
2617 // new overlap matrix.
2618 for (int x
= xMin
; x
< xMax
; x
++) {
2619 for (int y
= yMin
; y
< yMax
; y
++) {
2621 // Start with the matrix minus this window.
2622 int newMatrix
[][] = new int[width
][height
];
2623 for (int mx
= 0; mx
< width
; mx
++) {
2624 for (int my
= 0; my
< height
; my
++) {
2625 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2629 // Add this window's values to the new overlap matrix.
2630 long newOverlapTotal
= 0;
2631 long newOverlapN
= 0;
2632 // Start by adding each new cell.
2633 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2637 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2641 newMatrix
[wx
][wy
]++;
2644 // Now figure out the new value for total coverage.
2645 for (int mx
= 0; mx
< width
; mx
++) {
2646 for (int my
= 0; my
< height
; my
++) {
2647 newOverlapTotal
+= newMatrix
[x
][y
];
2648 if (newMatrix
[mx
][my
] > 0) {
2653 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2656 // First time: just record what we got.
2657 oldOverlapAvg
= newOverlapAvg
;
2660 // All other times: pick a new best (x, y) and save the
2662 if (newOverlapAvg
< oldOverlapAvg
) {
2665 oldOverlapAvg
= newOverlapAvg
;
2669 } // for (int x = xMin; x < xMax; x++)
2671 } // for (int y = yMin; y < yMax; y++)
2673 // Finally, set the window's new coordinates.
2674 window
.setX(windowX
);
2675 window
.setY(windowY
);
2678 // ------------------------------------------------------------------------
2679 // TMenu management -------------------------------------------------------
2680 // ------------------------------------------------------------------------
2683 * Check if a mouse event would hit either the active menu or any open
2686 * @param mouse mouse event
2687 * @return true if the mouse would hit the active menu or an open
2690 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2691 assert (activeMenu
!= null);
2692 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2693 Collections
.reverse(menus
);
2694 for (TMenu menu
: menus
) {
2695 if (menu
.mouseWouldHit(mouse
)) {
2699 return activeMenu
.mouseWouldHit(mouse
);
2703 * See if we need to switch window or activate the menu based on
2706 * @param mouse mouse event
2708 private void checkSwitchFocus(final TMouseEvent mouse
) {
2710 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2711 && (activeMenu
!= null)
2712 && (mouse
.getAbsoluteY() != 0)
2713 && (!mouseOnMenu(mouse
))
2715 // They clicked outside the active menu, turn it off
2716 activeMenu
.setActive(false);
2718 for (TMenu menu
: subMenus
) {
2719 menu
.setActive(false);
2725 // See if they hit the menu bar
2726 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2727 && (mouse
.isMouse1())
2728 && (!modalWindowActive())
2729 && (!overrideMenuWindowActive())
2730 && (mouse
.getAbsoluteY() == 0)
2733 for (TMenu menu
: subMenus
) {
2734 menu
.setActive(false);
2738 // They selected the menu, go activate it
2739 for (TMenu menu
: menus
) {
2740 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2741 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2742 + StringUtils
.width(menu
.getTitle()) + 2)
2744 menu
.setActive(true);
2747 menu
.setActive(false);
2753 // See if they hit the menu bar
2754 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2755 && (mouse
.isMouse1())
2756 && (activeMenu
!= null)
2757 && (mouse
.getAbsoluteY() == 0)
2760 TMenu oldMenu
= activeMenu
;
2761 for (TMenu menu
: subMenus
) {
2762 menu
.setActive(false);
2766 // See if we should switch menus
2767 for (TMenu menu
: menus
) {
2768 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2769 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2770 + StringUtils
.width(menu
.getTitle()) + 2)
2772 menu
.setActive(true);
2776 if (oldMenu
!= activeMenu
) {
2777 // They switched menus
2778 oldMenu
.setActive(false);
2783 // If a menu is still active, don't switch windows
2784 if (activeMenu
!= null) {
2788 // Only switch if there are multiple windows
2789 if (windows
.size() < 2) {
2793 if (((focusFollowsMouse
== true)
2794 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2795 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2797 synchronized (windows
) {
2798 Collections
.sort(windows
);
2799 if (windows
.get(0).isModal()) {
2800 // Modal windows don't switch
2804 for (TWindow window
: windows
) {
2805 assert (!window
.isModal());
2807 if (window
.isHidden()) {
2808 assert (!window
.isActive());
2812 if (window
.mouseWouldHit(mouse
)) {
2813 if (window
== windows
.get(0)) {
2814 // Clicked on the same window, nothing to do
2815 assert (window
.isActive());
2819 // We will be switching to another window
2820 assert (windows
.get(0).isActive());
2821 assert (windows
.get(0) == activeWindow
);
2822 assert (!window
.isActive());
2823 if (activeWindow
!= null) {
2824 activeWindow
.onUnfocus();
2825 activeWindow
.setActive(false);
2826 activeWindow
.setZ(window
.getZ());
2828 activeWindow
= window
;
2830 window
.setActive(true);
2837 // Clicked on the background, nothing to do
2841 // Nothing to do: this isn't a mouse up, or focus isn't following
2847 * Turn off the menu.
2849 public final void closeMenu() {
2850 if (activeMenu
!= null) {
2851 activeMenu
.setActive(false);
2853 for (TMenu menu
: subMenus
) {
2854 menu
.setActive(false);
2861 * Get a (shallow) copy of the menu list.
2863 * @return a copy of the menu list
2865 public final List
<TMenu
> getAllMenus() {
2866 return new ArrayList
<TMenu
>(menus
);
2870 * Add a top-level menu to the list.
2872 * @param menu the menu to add
2873 * @throws IllegalArgumentException if the menu is already used in
2874 * another TApplication
2876 public final void addMenu(final TMenu menu
) {
2877 if ((menu
.getApplication() != null)
2878 && (menu
.getApplication() != this)
2880 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2881 "part of application " + menu
.getApplication());
2889 * Remove a top-level menu from the list.
2891 * @param menu the menu to remove
2892 * @throws IllegalArgumentException if the menu is already used in
2893 * another TApplication
2895 public final void removeMenu(final TMenu menu
) {
2896 if ((menu
.getApplication() != null)
2897 && (menu
.getApplication() != this)
2899 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2900 "part of application " + menu
.getApplication());
2908 * Turn off a sub-menu.
2910 public final void closeSubMenu() {
2911 assert (activeMenu
!= null);
2912 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2913 assert (item
!= null);
2914 item
.setActive(false);
2915 subMenus
.remove(subMenus
.size() - 1);
2919 * Switch to the next menu.
2921 * @param forward if true, then switch to the next menu in the list,
2922 * otherwise switch to the previous menu in the list
2924 public final void switchMenu(final boolean forward
) {
2925 assert (activeMenu
!= null);
2927 for (TMenu menu
: subMenus
) {
2928 menu
.setActive(false);
2932 for (int i
= 0; i
< menus
.size(); i
++) {
2933 if (activeMenu
== menus
.get(i
)) {
2935 if (i
< menus
.size() - 1) {
2944 i
= menus
.size() - 1;
2947 activeMenu
.setActive(false);
2948 activeMenu
= menus
.get(i
);
2949 activeMenu
.setActive(true);
2956 * Add a menu item to the global list. If it has a keyboard accelerator,
2957 * that will be added the global hash.
2959 * @param item the menu item
2961 public final void addMenuItem(final TMenuItem item
) {
2962 menuItems
.add(item
);
2964 TKeypress key
= item
.getKey();
2966 synchronized (accelerators
) {
2967 assert (accelerators
.get(key
) == null);
2968 accelerators
.put(key
.toLowerCase(), item
);
2974 * Disable one menu item.
2976 * @param id the menu item ID
2978 public final void disableMenuItem(final int id
) {
2979 for (TMenuItem item
: menuItems
) {
2980 if (item
.getId() == id
) {
2981 item
.setEnabled(false);
2987 * Disable the range of menu items with ID's between lower and upper,
2990 * @param lower the lowest menu item ID
2991 * @param upper the highest menu item ID
2993 public final void disableMenuItems(final int lower
, final int upper
) {
2994 for (TMenuItem item
: menuItems
) {
2995 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2996 item
.setEnabled(false);
2997 item
.getParent().activate(0);
3003 * Enable one menu item.
3005 * @param id the menu item ID
3007 public final void enableMenuItem(final int id
) {
3008 for (TMenuItem item
: menuItems
) {
3009 if (item
.getId() == id
) {
3010 item
.setEnabled(true);
3011 item
.getParent().activate(0);
3017 * Enable the range of menu items with ID's between lower and upper,
3020 * @param lower the lowest menu item ID
3021 * @param upper the highest menu item ID
3023 public final void enableMenuItems(final int lower
, final int upper
) {
3024 for (TMenuItem item
: menuItems
) {
3025 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
3026 item
.setEnabled(true);
3027 item
.getParent().activate(0);
3033 * Get the menu item associated with this ID.
3035 * @param id the menu item ID
3036 * @return the menu item, or null if not found
3038 public final TMenuItem
getMenuItem(final int id
) {
3039 for (TMenuItem item
: menuItems
) {
3040 if (item
.getId() == id
) {
3048 * Recompute menu x positions based on their title length.
3050 public final void recomputeMenuX() {
3052 for (TMenu menu
: menus
) {
3055 x
+= StringUtils
.width(menu
.getTitle()) + 2;
3057 // Don't let the menu window exceed the screen width
3058 int rightEdge
= menu
.getX() + menu
.getWidth();
3059 if (rightEdge
> getScreen().getWidth()) {
3060 menu
.setX(getScreen().getWidth() - menu
.getWidth());
3066 * Post an event to process.
3068 * @param event new event to add to the queue
3070 public final void postEvent(final TInputEvent event
) {
3071 synchronized (this) {
3072 synchronized (fillEventQueue
) {
3073 fillEventQueue
.add(event
);
3076 System
.err
.println(System
.currentTimeMillis() + " " +
3077 Thread
.currentThread() + " postEvent() wake up main");
3084 * Post an event to process and turn off the menu.
3086 * @param event new event to add to the queue
3088 public final void postMenuEvent(final TInputEvent event
) {
3089 synchronized (this) {
3090 synchronized (fillEventQueue
) {
3091 fillEventQueue
.add(event
);
3094 System
.err
.println(System
.currentTimeMillis() + " " +
3095 Thread
.currentThread() + " postMenuEvent() wake up main");
3103 * Add a sub-menu to the list of open sub-menus.
3105 * @param menu sub-menu
3107 public final void addSubMenu(final TMenu menu
) {
3112 * Convenience function to add a top-level menu.
3114 * @param title menu title
3115 * @return the new menu
3117 public final TMenu
addMenu(final String title
) {
3120 TMenu menu
= new TMenu(this, x
, y
, title
);
3127 * Convenience function to add a default tools (hamburger) menu.
3129 * @return the new menu
3131 public final TMenu
addToolMenu() {
3132 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
3133 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
3134 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
3135 toolMenu
.addDefaultItem(TMenu
.MID_SCREEN_OPTIONS
);
3136 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
3137 getString("toolMenuStatus"));
3138 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3143 * Convenience function to add a default "File" menu.
3145 * @return the new menu
3147 public final TMenu
addFileMenu() {
3148 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
3149 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
3150 fileMenu
.addSeparator();
3151 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
3152 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
3153 getString("fileMenuStatus"));
3154 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3159 * Convenience function to add a default "Edit" menu.
3161 * @return the new menu
3163 public final TMenu
addEditMenu() {
3164 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
3165 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
3166 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
3167 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
3168 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
3169 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
3170 getString("editMenuStatus"));
3171 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3176 * Convenience function to add a default "Window" menu.
3178 * @return the new menu
3180 public final TMenu
addWindowMenu() {
3181 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
3182 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
3183 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
3184 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
3185 windowMenu
.addSeparator();
3186 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
3187 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
3188 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3189 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3190 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3191 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3192 getString("windowMenuStatus"));
3193 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3198 * Convenience function to add a default "Help" menu.
3200 * @return the new menu
3202 public final TMenu
addHelpMenu() {
3203 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3204 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3205 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3206 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3207 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3208 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3209 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3210 helpMenu
.addSeparator();
3211 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3212 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3213 getString("helpMenuStatus"));
3214 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3219 * Convenience function to add a default "Table" menu.
3221 * @return the new menu
3223 public final TMenu
addTableMenu() {
3224 TMenu tableMenu
= addMenu(i18n
.getString("tableMenuTitle"));
3225 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_COLUMN
, false);
3226 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_ROW
, false);
3227 tableMenu
.addSeparator();
3229 TSubMenu viewMenu
= tableMenu
.addSubMenu(i18n
.
3230 getString("tableSubMenuView"));
3231 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_ROW_LABELS
, false);
3232 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_COLUMN_LABELS
, false);
3233 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_ROW
, false);
3234 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_COLUMN
, false);
3236 TSubMenu borderMenu
= tableMenu
.addSubMenu(i18n
.
3237 getString("tableSubMenuBorders"));
3238 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_NONE
, false);
3239 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_ALL
, false);
3240 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_NONE
, false);
3241 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_ALL
, false);
3242 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_RIGHT
, false);
3243 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_LEFT
, false);
3244 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_TOP
, false);
3245 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_BOTTOM
, false);
3246 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_DOUBLE_BOTTOM
, false);
3247 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_THICK_BOTTOM
, false);
3248 TSubMenu deleteMenu
= tableMenu
.addSubMenu(i18n
.
3249 getString("tableSubMenuDelete"));
3250 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_LEFT
, false);
3251 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_UP
, false);
3252 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_ROW
, false);
3253 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_COLUMN
, false);
3254 TSubMenu insertMenu
= tableMenu
.addSubMenu(i18n
.
3255 getString("tableSubMenuInsert"));
3256 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_LEFT
, false);
3257 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_RIGHT
, false);
3258 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_ABOVE
, false);
3259 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_BELOW
, false);
3260 TSubMenu columnMenu
= tableMenu
.addSubMenu(i18n
.
3261 getString("tableSubMenuColumn"));
3262 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_NARROW
, false);
3263 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_WIDEN
, false);
3264 TSubMenu fileMenu
= tableMenu
.addSubMenu(i18n
.
3265 getString("tableSubMenuFile"));
3266 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_OPEN_CSV
, false);
3267 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_CSV
, false);
3268 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_TEXT
, false);
3270 TStatusBar statusBar
= tableMenu
.newStatusBar(i18n
.
3271 getString("tableMenuStatus"));
3272 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3276 // ------------------------------------------------------------------------
3277 // TTimer management ------------------------------------------------------
3278 // ------------------------------------------------------------------------
3281 * Get the amount of time I can sleep before missing a Timer tick.
3283 * @param timeout = initial (maximum) timeout in millis
3284 * @return number of milliseconds between now and the next timer event
3286 private long getSleepTime(final long timeout
) {
3287 Date now
= new Date();
3288 long nowTime
= now
.getTime();
3289 long sleepTime
= timeout
;
3291 synchronized (timers
) {
3292 for (TTimer timer
: timers
) {
3293 long nextTickTime
= timer
.getNextTick().getTime();
3294 if (nextTickTime
< nowTime
) {
3298 long timeDifference
= nextTickTime
- nowTime
;
3299 if (timeDifference
< sleepTime
) {
3300 sleepTime
= timeDifference
;
3305 assert (sleepTime
>= 0);
3306 assert (sleepTime
<= timeout
);
3311 * Convenience function to add a timer.
3313 * @param duration number of milliseconds to wait between ticks
3314 * @param recurring if true, re-schedule this timer after every tick
3315 * @param action function to call when button is pressed
3318 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3319 final TAction action
) {
3321 TTimer timer
= new TTimer(duration
, recurring
, action
);
3322 synchronized (timers
) {
3329 * Convenience function to remove a timer.
3331 * @param timer timer to remove
3333 public final void removeTimer(final TTimer timer
) {
3334 synchronized (timers
) {
3335 timers
.remove(timer
);
3339 // ------------------------------------------------------------------------
3340 // Other TWindow constructors ---------------------------------------------
3341 // ------------------------------------------------------------------------
3344 * Convenience function to spawn a message box.
3346 * @param title window title, will be centered along the top border
3347 * @param caption message to display. Use embedded newlines to get a
3349 * @return the new message box
3351 public final TMessageBox
messageBox(final String title
,
3352 final String caption
) {
3354 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3358 * Convenience function to spawn a message box.
3360 * @param title window title, will be centered along the top border
3361 * @param caption message to display. Use embedded newlines to get a
3363 * @param type one of the TMessageBox.Type constants. Default is
3365 * @return the new message box
3367 public final TMessageBox
messageBox(final String title
,
3368 final String caption
, final TMessageBox
.Type type
) {
3370 return new TMessageBox(this, title
, caption
, type
);
3374 * Convenience function to spawn an input box.
3376 * @param title window title, will be centered along the top border
3377 * @param caption message to display. Use embedded newlines to get a
3379 * @return the new input box
3381 public final TInputBox
inputBox(final String title
, final String caption
) {
3383 return new TInputBox(this, title
, caption
);
3387 * Convenience function to spawn an input box.
3389 * @param title window title, will be centered along the top border
3390 * @param caption message to display. Use embedded newlines to get a
3392 * @param text initial text to seed the field with
3393 * @return the new input box
3395 public final TInputBox
inputBox(final String title
, final String caption
,
3396 final String text
) {
3398 return new TInputBox(this, title
, caption
, text
);
3402 * Convenience function to spawn an input box.
3404 * @param title window title, will be centered along the top border
3405 * @param caption message to display. Use embedded newlines to get a
3407 * @param text initial text to seed the field with
3408 * @param type one of the Type constants. Default is Type.OK.
3409 * @return the new input box
3411 public final TInputBox
inputBox(final String title
, final String caption
,
3412 final String text
, final TInputBox
.Type type
) {
3414 return new TInputBox(this, title
, caption
, text
, type
);
3418 * Convenience function to open a terminal window.
3420 * @param x column relative to parent
3421 * @param y row relative to parent
3422 * @return the terminal new window
3424 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3425 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3429 * Convenience function to open a terminal window.
3431 * @param x column relative to parent
3432 * @param y row relative to parent
3433 * @param closeOnExit if true, close the window when the command exits
3434 * @return the terminal new window
3436 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3437 final boolean closeOnExit
) {
3439 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3443 * Convenience function to open a terminal window.
3445 * @param x column relative to parent
3446 * @param y row relative to parent
3447 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3448 * @return the terminal new window
3450 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3453 return new TTerminalWindow(this, x
, y
, flags
);
3457 * Convenience function to open a terminal window.
3459 * @param x column relative to parent
3460 * @param y row relative to parent
3461 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3462 * @param closeOnExit if true, close the window when the command exits
3463 * @return the terminal new window
3465 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3466 final int flags
, final boolean closeOnExit
) {
3468 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3472 * Convenience function to open a terminal window and execute a custom
3473 * command line inside it.
3475 * @param x column relative to parent
3476 * @param y row relative to parent
3477 * @param commandLine the command line to execute
3478 * @return the terminal new window
3480 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3481 final String commandLine
) {
3483 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3487 * Convenience function to open a terminal window and execute a custom
3488 * command line inside it.
3490 * @param x column relative to parent
3491 * @param y row relative to parent
3492 * @param commandLine the command line to execute
3493 * @param closeOnExit if true, close the window when the command exits
3494 * @return the terminal new window
3496 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3497 final String commandLine
, final boolean closeOnExit
) {
3499 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3503 * Convenience function to open a terminal window and execute a custom
3504 * command line inside it.
3506 * @param x column relative to parent
3507 * @param y row relative to parent
3508 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3509 * @param command the command line to execute
3510 * @return the terminal new window
3512 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3513 final int flags
, final String
[] command
) {
3515 return new TTerminalWindow(this, x
, y
, flags
, command
);
3519 * Convenience function to open a terminal window and execute a custom
3520 * command line inside it.
3522 * @param x column relative to parent
3523 * @param y row relative to parent
3524 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3525 * @param command the command line to execute
3526 * @param closeOnExit if true, close the window when the command exits
3527 * @return the terminal new window
3529 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3530 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3532 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3536 * Convenience function to open a terminal window and execute a custom
3537 * command line inside it.
3539 * @param x column relative to parent
3540 * @param y row relative to parent
3541 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3542 * @param commandLine the command line to execute
3543 * @return the terminal new window
3545 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3546 final int flags
, final String commandLine
) {
3548 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"));
3552 * Convenience function to open a terminal window and execute a custom
3553 * command line inside it.
3555 * @param x column relative to parent
3556 * @param y row relative to parent
3557 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3558 * @param commandLine the command line to execute
3559 * @param closeOnExit if true, close the window when the command exits
3560 * @return the terminal new window
3562 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3563 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3565 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"),
3570 * Convenience function to spawn an file open box.
3572 * @param path path of selected file
3573 * @return the result of the new file open box
3574 * @throws IOException if java.io operation throws
3576 public final String
fileOpenBox(final String path
) throws IOException
{
3578 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3579 return box
.getFilename();
3583 * Convenience function to spawn an file open box.
3585 * @param path path of selected file
3586 * @param type one of the Type constants
3587 * @return the result of the new file open box
3588 * @throws IOException if java.io operation throws
3590 public final String
fileOpenBox(final String path
,
3591 final TFileOpenBox
.Type type
) throws IOException
{
3593 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3594 return box
.getFilename();
3598 * Convenience function to spawn a file open box.
3600 * @param path path of selected file
3601 * @param type one of the Type constants
3602 * @param filter a string that files must match to be displayed
3603 * @return the result of the new file open box
3604 * @throws IOException of a java.io operation throws
3606 public final String
fileOpenBox(final String path
,
3607 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3609 ArrayList
<String
> filters
= new ArrayList
<String
>();
3610 filters
.add(filter
);
3612 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3613 return box
.getFilename();
3617 * Convenience function to spawn a file open box.
3619 * @param path path of selected file
3620 * @param type one of the Type constants
3621 * @param filters a list of strings that files must match to be displayed
3622 * @return the result of the new file open box
3623 * @throws IOException of a java.io operation throws
3625 public final String
fileOpenBox(final String path
,
3626 final TFileOpenBox
.Type type
,
3627 final List
<String
> filters
) throws IOException
{
3629 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3630 return box
.getFilename();
3634 * Convenience function to create a new window and make it active.
3635 * Window will be located at (0, 0).
3637 * @param title window title, will be centered along the top border
3638 * @param width width of window
3639 * @param height height of window
3640 * @return the new window
3642 public final TWindow
addWindow(final String title
, final int width
,
3645 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3650 * Convenience function to create a new window and make it active.
3651 * Window will be located at (0, 0).
3653 * @param title window title, will be centered along the top border
3654 * @param width width of window
3655 * @param height height of window
3656 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3657 * @return the new window
3659 public final TWindow
addWindow(final String title
,
3660 final int width
, final int height
, final int flags
) {
3662 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3667 * Convenience function to create a new window and make it active.
3669 * @param title window title, will be centered along the top border
3670 * @param x column relative to parent
3671 * @param y row relative to parent
3672 * @param width width of window
3673 * @param height height of window
3674 * @return the new window
3676 public final TWindow
addWindow(final String title
,
3677 final int x
, final int y
, final int width
, final int height
) {
3679 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3684 * Convenience function to create a new window and make it active.
3686 * @param title window title, will be centered along the top border
3687 * @param x column relative to parent
3688 * @param y row relative to parent
3689 * @param width width of window
3690 * @param height height of window
3691 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3692 * @return the new window
3694 public final TWindow
addWindow(final String title
,
3695 final int x
, final int y
, final int width
, final int height
,
3698 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);