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 static jexer
.TCommand
.*;
66 import static jexer
.TKeypress
.*;
69 * TApplication is the main driver class for a full Text User Interface
70 * application. It manages windows, provides a menu bar and status bar, and
71 * processes events received from the user.
73 public class TApplication
implements Runnable
{
78 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
80 // ------------------------------------------------------------------------
81 // Constants --------------------------------------------------------------
82 // ------------------------------------------------------------------------
85 * If true, emit thread stuff to System.err.
87 private static final boolean debugThreads
= false;
90 * If true, emit events being processed to System.err.
92 private static final boolean debugEvents
= false;
95 * If true, do "smart placement" on new windows that are not specified to
98 private static final boolean smartWindowPlacement
= true;
101 * Two backend types are available.
103 public static enum BackendType
{
110 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
115 * Synonym for ECMA48.
120 // ------------------------------------------------------------------------
121 // Variables --------------------------------------------------------------
122 // ------------------------------------------------------------------------
125 * The primary event handler thread.
127 private volatile WidgetEventHandler primaryEventHandler
;
130 * The secondary event handler thread.
132 private volatile WidgetEventHandler secondaryEventHandler
;
135 * The widget receiving events from the secondary event handler thread.
137 private volatile TWidget secondaryEventReceiver
;
140 * Access to the physical screen, keyboard, and mouse.
142 private Backend backend
;
145 * Actual mouse coordinate X.
150 * Actual mouse coordinate Y.
155 * Old version of mouse coordinate X.
157 private int oldMouseX
;
160 * Old version mouse coordinate Y.
162 private int oldMouseY
;
165 * Old drawn version of mouse coordinate X.
167 private int oldDrawnMouseX
;
170 * Old drawn version mouse coordinate Y.
172 private int oldDrawnMouseY
;
175 * Old drawn version mouse cell.
177 private Cell oldDrawnMouseCell
= new Cell();
180 * The last mouse up click time, used to determine if this is a mouse
183 private long lastMouseUpTime
;
186 * The amount of millis between mouse up events to assume a double-click.
188 private long doubleClickTime
= 250;
191 * Event queue that is filled by run().
193 private List
<TInputEvent
> fillEventQueue
;
196 * Event queue that will be drained by either primary or secondary
199 private List
<TInputEvent
> drainEventQueue
;
202 * Top-level menus in this application.
204 private List
<TMenu
> menus
;
207 * Stack of activated sub-menus in this application.
209 private List
<TMenu
> subMenus
;
212 * The currently active menu.
214 private TMenu activeMenu
= null;
217 * Active keyboard accelerators.
219 private Map
<TKeypress
, TMenuItem
> accelerators
;
224 private List
<TMenuItem
> menuItems
;
227 * Windows and widgets pull colors from this ColorTheme.
229 private ColorTheme theme
;
232 * The top-level windows (but not menus).
234 private List
<TWindow
> windows
;
237 * The currently acive window.
239 private TWindow activeWindow
= null;
242 * Timers that are being ticked.
244 private List
<TTimer
> timers
;
247 * When true, the application has been started.
249 private volatile boolean started
= false;
252 * When true, exit the application.
254 private volatile boolean quit
= false;
257 * When true, repaint the entire screen.
259 private volatile boolean repaint
= true;
262 * Y coordinate of the top edge of the desktop. For now this is a
263 * constant. Someday it would be nice to have a multi-line menu or
266 private static final int desktopTop
= 1;
269 * Y coordinate of the bottom edge of the desktop.
271 private int desktopBottom
;
274 * An optional TDesktop background window that is drawn underneath
277 private TDesktop desktop
;
280 * If true, focus follows mouse: windows automatically raised if the
281 * mouse passes over them.
283 private boolean focusFollowsMouse
= false;
286 * The images that might be displayed. Note package private access.
288 private List
<TImage
> images
;
291 * The list of commands to run before the next I/O check.
293 private List
<Runnable
> invokeLaters
= new LinkedList
<Runnable
>();
296 * WidgetEventHandler is the main event consumer loop. There are at most
297 * two such threads in existence: the primary for normal case and a
298 * secondary that is used for TMessageBox, TInputBox, and similar.
300 private class WidgetEventHandler
implements Runnable
{
302 * The main application.
304 private TApplication application
;
307 * Whether or not this WidgetEventHandler is the primary or secondary
310 private boolean primary
= true;
313 * Public constructor.
315 * @param application the main application
316 * @param primary if true, this is the primary event handler thread
318 public WidgetEventHandler(final TApplication application
,
319 final boolean primary
) {
321 this.application
= application
;
322 this.primary
= primary
;
329 // Wrap everything in a try, so that if we go belly up we can let
330 // the user have their terminal back.
333 } catch (Throwable t
) {
334 this.application
.restoreConsole();
336 this.application
.exit();
343 private void runImpl() {
344 boolean first
= true;
347 while (!application
.quit
) {
349 // Wait until application notifies me
350 while (!application
.quit
) {
352 synchronized (application
.drainEventQueue
) {
353 if (application
.drainEventQueue
.size() > 0) {
362 timeout
= application
.getSleepTime(1000);
366 // A timer needs to fire, break out.
371 System
.err
.printf("%d %s %s %s sleep %d millis\n",
372 System
.currentTimeMillis(), this,
373 primary ?
"primary" : "secondary",
374 Thread
.currentThread(), timeout
);
377 synchronized (this) {
382 System
.err
.printf("%d %s %s %s AWAKE\n",
383 System
.currentTimeMillis(), this,
384 primary ?
"primary" : "secondary",
385 Thread
.currentThread());
389 && (application
.secondaryEventReceiver
== null)
391 // Secondary thread, emergency exit. If we got
392 // here then something went wrong with the
393 // handoff between yield() and closeWindow().
394 synchronized (application
.primaryEventHandler
) {
395 application
.primaryEventHandler
.notify();
397 application
.secondaryEventHandler
= null;
398 throw new RuntimeException("secondary exited " +
402 } catch (InterruptedException e
) {
405 } // while (!application.quit)
407 // Pull all events off the queue
409 TInputEvent event
= null;
410 synchronized (application
.drainEventQueue
) {
411 if (application
.drainEventQueue
.size() == 0) {
414 event
= application
.drainEventQueue
.remove(0);
417 // We will have an event to process, so repaint the
418 // screen at the end.
419 application
.repaint
= true;
422 primaryHandleEvent(event
);
424 secondaryHandleEvent(event
);
427 && (application
.secondaryEventReceiver
== null)
429 // Secondary thread, time to exit.
431 // Eliminate my reference so that wakeEventHandler()
432 // resumes working on the primary.
433 application
.secondaryEventHandler
= null;
435 // DO NOT UNLOCK. Primary thread just came back from
436 // primaryHandleEvent() and will unlock in the else
437 // block below. Just wake it up.
438 synchronized (application
.primaryEventHandler
) {
439 application
.primaryEventHandler
.notify();
448 // Fire timers, update screen.
450 application
.finishEventProcessing();
453 } // while (true) (main runnable loop)
457 // ------------------------------------------------------------------------
458 // Constructors -----------------------------------------------------------
459 // ------------------------------------------------------------------------
462 * Public constructor.
464 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
466 * @param windowWidth the number of text columns to start with
467 * @param windowHeight the number of text rows to start with
468 * @param fontSize the size in points
469 * @throws UnsupportedEncodingException if an exception is thrown when
470 * creating the InputStreamReader
472 public TApplication(final BackendType backendType
, final int windowWidth
,
473 final int windowHeight
, final int fontSize
)
474 throws UnsupportedEncodingException
{
476 switch (backendType
) {
478 backend
= new SwingBackend(this, windowWidth
, windowHeight
,
484 backend
= new ECMA48Backend(this, null, null, windowWidth
,
485 windowHeight
, fontSize
);
488 throw new IllegalArgumentException("Invalid backend type: "
495 * Public constructor.
497 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
499 * @throws UnsupportedEncodingException if an exception is thrown when
500 * creating the InputStreamReader
502 public TApplication(final BackendType backendType
)
503 throws UnsupportedEncodingException
{
505 switch (backendType
) {
507 // The default SwingBackend is 80x25, 20 pt font. If you want to
508 // change that, you can pass the extra arguments to the
509 // SwingBackend constructor here. For example, if you wanted
510 // 90x30, 16 pt font:
512 // backend = new SwingBackend(this, 90, 30, 16);
513 backend
= new SwingBackend(this);
518 backend
= new ECMA48Backend(this, null, null);
521 throw new IllegalArgumentException("Invalid backend type: "
528 * Public constructor. The backend type will be BackendType.ECMA48.
530 * @param input an InputStream connected to the remote user, or null for
531 * System.in. If System.in is used, then on non-Windows systems it will
532 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
533 * mode. input is always converted to a Reader with UTF-8 encoding.
534 * @param output an OutputStream connected to the remote user, or null
535 * for System.out. output is always converted to a Writer with UTF-8
537 * @throws UnsupportedEncodingException if an exception is thrown when
538 * creating the InputStreamReader
540 public TApplication(final InputStream input
,
541 final OutputStream output
) throws UnsupportedEncodingException
{
543 backend
= new ECMA48Backend(this, input
, output
);
548 * Public constructor. The backend type will be BackendType.ECMA48.
550 * @param input the InputStream underlying 'reader'. Its available()
551 * method is used to determine if reader.read() will block or not.
552 * @param reader a Reader connected to the remote user.
553 * @param writer a PrintWriter connected to the remote user.
554 * @param setRawMode if true, set System.in into raw mode with stty.
555 * This should in general not be used. It is here solely for Demo3,
556 * which uses System.in.
557 * @throws IllegalArgumentException if input, reader, or writer are null.
559 public TApplication(final InputStream input
, final Reader reader
,
560 final PrintWriter writer
, final boolean setRawMode
) {
562 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
567 * Public constructor. The backend type will be BackendType.ECMA48.
569 * @param input the InputStream underlying 'reader'. Its available()
570 * method is used to determine if reader.read() will block or not.
571 * @param reader a Reader connected to the remote user.
572 * @param writer a PrintWriter connected to the remote user.
573 * @throws IllegalArgumentException if input, reader, or writer are null.
575 public TApplication(final InputStream input
, final Reader reader
,
576 final PrintWriter writer
) {
578 this(input
, reader
, writer
, false);
582 * Public constructor. This hook enables use with new non-Jexer
585 * @param backend a Backend that is already ready to go.
587 public TApplication(final Backend backend
) {
588 this.backend
= backend
;
589 backend
.setListener(this);
594 * Finish construction once the backend is set.
596 private void TApplicationImpl() {
597 theme
= new ColorTheme();
598 desktopBottom
= getScreen().getHeight() - 1;
599 fillEventQueue
= new LinkedList
<TInputEvent
>();
600 drainEventQueue
= new LinkedList
<TInputEvent
>();
601 windows
= new LinkedList
<TWindow
>();
602 menus
= new ArrayList
<TMenu
>();
603 subMenus
= new ArrayList
<TMenu
>();
604 timers
= new LinkedList
<TTimer
>();
605 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
606 menuItems
= new LinkedList
<TMenuItem
>();
607 desktop
= new TDesktop(this);
608 images
= new LinkedList
<TImage
>();
610 // Special case: the Swing backend needs to have a timer to drive its
612 if ((backend
instanceof SwingBackend
)
613 || (backend
instanceof MultiBackend
)
615 // Default to 500 millis, unless a SwingBackend has its own
618 if (backend
instanceof SwingBackend
) {
619 millis
= ((SwingBackend
) backend
).getBlinkMillis();
622 addTimer(millis
, true,
625 TApplication
.this.doRepaint();
633 // ------------------------------------------------------------------------
634 // Runnable ---------------------------------------------------------------
635 // ------------------------------------------------------------------------
638 * Run this application until it exits.
641 // Start the main consumer thread
642 primaryEventHandler
= new WidgetEventHandler(this, true);
643 (new Thread(primaryEventHandler
)).start();
648 synchronized (this) {
649 boolean doWait
= false;
651 if (!backend
.hasEvents()) {
652 synchronized (fillEventQueue
) {
653 if (fillEventQueue
.size() == 0) {
660 // No I/O to dispatch, so wait until the backend
664 System
.err
.println(System
.currentTimeMillis() +
665 " " + Thread
.currentThread() + " MAIN sleep");
671 System
.err
.println(System
.currentTimeMillis() +
672 " " + Thread
.currentThread() + " MAIN AWAKE");
674 } catch (InterruptedException e
) {
675 // I'm awake and don't care why, let's see what's
676 // going on out there.
680 } // synchronized (this)
682 synchronized (fillEventQueue
) {
683 // Pull any pending I/O events
684 backend
.getEvents(fillEventQueue
);
686 // Dispatch each event to the appropriate handler, one at a
689 TInputEvent event
= null;
690 if (fillEventQueue
.size() == 0) {
693 event
= fillEventQueue
.remove(0);
694 metaHandleEvent(event
);
698 // Wake a consumer thread if we have any pending events.
699 if (drainEventQueue
.size() > 0) {
705 // Shutdown the event consumer threads
706 if (secondaryEventHandler
!= null) {
707 synchronized (secondaryEventHandler
) {
708 secondaryEventHandler
.notify();
711 if (primaryEventHandler
!= null) {
712 synchronized (primaryEventHandler
) {
713 primaryEventHandler
.notify();
717 // Shutdown the user I/O thread(s)
720 // Close all the windows. This gives them an opportunity to release
726 // ------------------------------------------------------------------------
727 // Event handlers ---------------------------------------------------------
728 // ------------------------------------------------------------------------
731 * Method that TApplication subclasses can override to handle menu or
732 * posted command events.
734 * @param command command event
735 * @return if true, this event was consumed
737 protected boolean onCommand(final TCommandEvent command
) {
738 // Default: handle cmExit
739 if (command
.equals(cmExit
)) {
740 if (messageBox(i18n
.getString("exitDialogTitle"),
741 i18n
.getString("exitDialogText"),
742 TMessageBox
.Type
.YESNO
).isYes()) {
749 if (command
.equals(cmShell
)) {
750 openTerminal(0, 0, TWindow
.RESIZABLE
);
754 if (command
.equals(cmTile
)) {
758 if (command
.equals(cmCascade
)) {
762 if (command
.equals(cmCloseAll
)) {
767 if (command
.equals(cmMenu
)) {
768 if (!modalWindowActive() && (activeMenu
== null)) {
769 if (menus
.size() > 0) {
770 menus
.get(0).setActive(true);
771 activeMenu
= menus
.get(0);
781 * Method that TApplication subclasses can override to handle menu
784 * @param menu menu event
785 * @return if true, this event was consumed
787 protected boolean onMenu(final TMenuEvent menu
) {
789 // Default: handle MID_EXIT
790 if (menu
.getId() == TMenu
.MID_EXIT
) {
791 if (messageBox(i18n
.getString("exitDialogTitle"),
792 i18n
.getString("exitDialogText"),
793 TMessageBox
.Type
.YESNO
).isYes()) {
800 if (menu
.getId() == TMenu
.MID_SHELL
) {
801 openTerminal(0, 0, TWindow
.RESIZABLE
);
805 if (menu
.getId() == TMenu
.MID_TILE
) {
809 if (menu
.getId() == TMenu
.MID_CASCADE
) {
813 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
817 if (menu
.getId() == TMenu
.MID_ABOUT
) {
821 if (menu
.getId() == TMenu
.MID_REPAINT
) {
822 getScreen().clearPhysical();
826 if (menu
.getId() == TMenu
.MID_VIEW_IMAGE
) {
830 if (menu
.getId() == TMenu
.MID_CHANGE_FONT
) {
831 new TFontChooserWindow(this);
838 * Method that TApplication subclasses can override to handle keystrokes.
840 * @param keypress keystroke event
841 * @return if true, this event was consumed
843 protected boolean onKeypress(final TKeypressEvent keypress
) {
844 // Default: only menu shortcuts
846 // Process Alt-F, Alt-E, etc. menu shortcut keys
847 if (!keypress
.getKey().isFnKey()
848 && keypress
.getKey().isAlt()
849 && !keypress
.getKey().isCtrl()
850 && (activeMenu
== null)
851 && !modalWindowActive()
854 assert (subMenus
.size() == 0);
856 for (TMenu menu
: menus
) {
857 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
858 == Character
.toLowerCase(keypress
.getKey().getChar())
861 menu
.setActive(true);
871 * Process background events, and update the screen.
873 private void finishEventProcessing() {
875 System
.err
.printf(System
.currentTimeMillis() + " " +
876 Thread
.currentThread() + " finishEventProcessing()\n");
879 // Process timers and call doIdle()'s
883 synchronized (getScreen()) {
888 System
.err
.printf(System
.currentTimeMillis() + " " +
889 Thread
.currentThread() + " finishEventProcessing() END\n");
894 * Peek at certain application-level events, add to eventQueue, and wake
895 * up the consuming Thread.
897 * @param event the input event to consume
899 private void metaHandleEvent(final TInputEvent event
) {
902 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
903 event
)); System
.err
.flush();
907 // Do no more processing if the application is already trying
912 // Special application-wide events -------------------------------
915 if (event
instanceof TCommandEvent
) {
916 TCommandEvent command
= (TCommandEvent
) event
;
917 if (command
.getCmd().equals(cmAbort
)) {
923 synchronized (drainEventQueue
) {
925 if (event
instanceof TResizeEvent
) {
926 TResizeEvent resize
= (TResizeEvent
) event
;
927 synchronized (getScreen()) {
928 getScreen().setDimensions(resize
.getWidth(),
930 desktopBottom
= getScreen().getHeight() - 1;
936 if (desktop
!= null) {
937 desktop
.setDimensions(0, 0, resize
.getWidth(),
938 resize
.getHeight() - 1);
941 // Change menu edges if needed.
944 // We are dirty, redraw the screen.
948 System.err.println("New screen: " + resize.getWidth() +
949 " x " + resize.getHeight());
954 // Put into the main queue
955 drainEventQueue
.add(event
);
960 * Dispatch one event to the appropriate widget or application-level
961 * event handler. This is the primary event handler, it has the normal
962 * application-wide event handling.
964 * @param event the input event to consume
965 * @see #secondaryHandleEvent(TInputEvent event)
967 private void primaryHandleEvent(final TInputEvent event
) {
970 System
.err
.printf("%s primaryHandleEvent: %s\n",
971 Thread
.currentThread(), event
);
973 TMouseEvent doubleClick
= null;
975 // Special application-wide events -----------------------------------
977 // Peek at the mouse position
978 if (event
instanceof TMouseEvent
) {
979 TMouseEvent mouse
= (TMouseEvent
) event
;
980 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
983 mouseX
= mouse
.getX();
984 mouseY
= mouse
.getY();
986 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
987 && (!mouse
.isMouseWheelUp())
988 && (!mouse
.isMouseWheelDown())
990 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
993 // This is a double-click.
994 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
996 mouse
.getX(), mouse
.getY(),
997 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
998 mouse
.isMouse1(), mouse
.isMouse2(),
1000 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1003 // The first click of a potential double-click.
1004 lastMouseUpTime
= mouse
.getTime().getTime();
1009 // See if we need to switch focus to another window or the menu
1010 checkSwitchFocus((TMouseEvent
) event
);
1013 // Handle menu events
1014 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1015 TMenu menu
= activeMenu
;
1017 if (event
instanceof TMouseEvent
) {
1018 TMouseEvent mouse
= (TMouseEvent
) event
;
1020 while (subMenus
.size() > 0) {
1021 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1022 if (subMenu
.mouseWouldHit(mouse
)) {
1025 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1026 && (!mouse
.isMouse1())
1027 && (!mouse
.isMouse2())
1028 && (!mouse
.isMouse3())
1029 && (!mouse
.isMouseWheelUp())
1030 && (!mouse
.isMouseWheelDown())
1034 // We navigated away from a sub-menu, so close it
1038 // Convert the mouse relative x/y to menu coordinates
1039 assert (mouse
.getX() == mouse
.getAbsoluteX());
1040 assert (mouse
.getY() == mouse
.getAbsoluteY());
1041 if (subMenus
.size() > 0) {
1042 menu
= subMenus
.get(subMenus
.size() - 1);
1044 mouse
.setX(mouse
.getX() - menu
.getX());
1045 mouse
.setY(mouse
.getY() - menu
.getY());
1047 menu
.handleEvent(event
);
1051 if (event
instanceof TKeypressEvent
) {
1052 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1054 // See if this key matches an accelerator, and is not being
1055 // shortcutted by the active window, and if so dispatch the menu
1057 boolean windowWillShortcut
= false;
1058 if (activeWindow
!= null) {
1059 assert (activeWindow
.isShown());
1060 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1061 // We do not process this key, it will be passed to the
1063 windowWillShortcut
= true;
1067 if (!windowWillShortcut
&& !modalWindowActive()) {
1068 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1069 TMenuItem item
= null;
1070 synchronized (accelerators
) {
1071 item
= accelerators
.get(keypressLowercase
);
1074 if (item
.isEnabled()) {
1075 // Let the menu item dispatch
1081 // Handle the keypress
1082 if (onKeypress(keypress
)) {
1088 if (event
instanceof TCommandEvent
) {
1089 if (onCommand((TCommandEvent
) event
)) {
1094 if (event
instanceof TMenuEvent
) {
1095 if (onMenu((TMenuEvent
) event
)) {
1100 // Dispatch events to the active window -------------------------------
1101 boolean dispatchToDesktop
= true;
1102 TWindow window
= activeWindow
;
1103 if (window
!= null) {
1104 assert (window
.isActive());
1105 assert (window
.isShown());
1106 if (event
instanceof TMouseEvent
) {
1107 TMouseEvent mouse
= (TMouseEvent
) event
;
1108 // Convert the mouse relative x/y to window coordinates
1109 assert (mouse
.getX() == mouse
.getAbsoluteX());
1110 assert (mouse
.getY() == mouse
.getAbsoluteY());
1111 mouse
.setX(mouse
.getX() - window
.getX());
1112 mouse
.setY(mouse
.getY() - window
.getY());
1114 if (doubleClick
!= null) {
1115 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1116 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1119 if (window
.mouseWouldHit(mouse
)) {
1120 dispatchToDesktop
= false;
1122 } else if (event
instanceof TKeypressEvent
) {
1123 dispatchToDesktop
= false;
1127 System
.err
.printf("TApplication dispatch event: %s\n",
1130 window
.handleEvent(event
);
1131 if (doubleClick
!= null) {
1132 window
.handleEvent(doubleClick
);
1135 if (dispatchToDesktop
) {
1136 // This event is fair game for the desktop to process.
1137 if (desktop
!= null) {
1138 desktop
.handleEvent(event
);
1139 if (doubleClick
!= null) {
1140 desktop
.handleEvent(doubleClick
);
1147 * Dispatch one event to the appropriate widget or application-level
1148 * event handler. This is the secondary event handler used by certain
1149 * special dialogs (currently TMessageBox and TFileOpenBox).
1151 * @param event the input event to consume
1152 * @see #primaryHandleEvent(TInputEvent event)
1154 private void secondaryHandleEvent(final TInputEvent event
) {
1155 TMouseEvent doubleClick
= null;
1158 System
.err
.printf("%s secondaryHandleEvent: %s\n",
1159 Thread
.currentThread(), event
);
1162 // Peek at the mouse position
1163 if (event
instanceof TMouseEvent
) {
1164 TMouseEvent mouse
= (TMouseEvent
) event
;
1165 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1168 mouseX
= mouse
.getX();
1169 mouseY
= mouse
.getY();
1171 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1172 && (!mouse
.isMouseWheelUp())
1173 && (!mouse
.isMouseWheelDown())
1175 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1178 // This is a double-click.
1179 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1181 mouse
.getX(), mouse
.getY(),
1182 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1183 mouse
.isMouse1(), mouse
.isMouse2(),
1185 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1188 // The first click of a potential double-click.
1189 lastMouseUpTime
= mouse
.getTime().getTime();
1195 secondaryEventReceiver
.handleEvent(event
);
1196 // Note that it is possible for secondaryEventReceiver to be null
1197 // now, because its handleEvent() might have finished out on the
1198 // secondary thread. So put any extra processing inside a null
1200 if (secondaryEventReceiver
!= null) {
1201 if (doubleClick
!= null) {
1202 secondaryEventReceiver
.handleEvent(doubleClick
);
1208 * Enable a widget to override the primary event thread.
1210 * @param widget widget that will receive events
1212 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1214 System
.err
.println(System
.currentTimeMillis() +
1215 " enableSecondaryEventReceiver()");
1218 assert (secondaryEventReceiver
== null);
1219 assert (secondaryEventHandler
== null);
1220 assert ((widget
instanceof TMessageBox
)
1221 || (widget
instanceof TFileOpenBox
));
1222 secondaryEventReceiver
= widget
;
1223 secondaryEventHandler
= new WidgetEventHandler(this, false);
1225 (new Thread(secondaryEventHandler
)).start();
1229 * Yield to the secondary thread.
1231 public final void yield() {
1233 System
.err
.printf(System
.currentTimeMillis() + " " +
1234 Thread
.currentThread() + " yield()\n");
1237 assert (secondaryEventReceiver
!= null);
1239 while (secondaryEventReceiver
!= null) {
1240 synchronized (primaryEventHandler
) {
1242 primaryEventHandler
.wait();
1243 } catch (InterruptedException e
) {
1251 * Do stuff when there is no user input.
1253 private void doIdle() {
1255 System
.err
.printf(System
.currentTimeMillis() + " " +
1256 Thread
.currentThread() + " doIdle()\n");
1259 synchronized (timers
) {
1262 System
.err
.printf(System
.currentTimeMillis() + " " +
1263 Thread
.currentThread() + " doIdle() 2\n");
1266 // Run any timers that have timed out
1267 Date now
= new Date();
1268 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1269 for (TTimer timer
: timers
) {
1270 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1271 // Something might change, so repaint the screen.
1274 if (timer
.recurring
) {
1275 keepTimers
.add(timer
);
1278 keepTimers
.add(timer
);
1282 timers
.addAll(keepTimers
);
1286 for (TWindow window
: windows
) {
1289 if (desktop
!= null) {
1293 // Run any invokeLaters
1294 synchronized (invokeLaters
) {
1295 for (Runnable invoke
: invokeLaters
) {
1298 invokeLaters
.clear();
1304 * Wake the sleeping active event handler.
1306 private void wakeEventHandler() {
1311 if (secondaryEventHandler
!= null) {
1312 synchronized (secondaryEventHandler
) {
1313 secondaryEventHandler
.notify();
1316 assert (primaryEventHandler
!= null);
1317 synchronized (primaryEventHandler
) {
1318 primaryEventHandler
.notify();
1323 // ------------------------------------------------------------------------
1324 // TApplication -----------------------------------------------------------
1325 // ------------------------------------------------------------------------
1328 * Place a command on the run queue, and run it before the next round of
1331 * @param command the command to run later
1333 public void invokeLater(final Runnable command
) {
1334 synchronized (invokeLaters
) {
1335 invokeLaters
.add(command
);
1341 * Restore the console to sane defaults. This is meant to be used for
1342 * improper exits (e.g. a caught exception in main()), and should not be
1343 * necessary for normal program termination.
1345 public void restoreConsole() {
1346 if (backend
!= null) {
1347 if (backend
instanceof ECMA48Backend
) {
1356 * @return the Backend
1358 public final Backend
getBackend() {
1365 * @return the Screen
1367 public final Screen
getScreen() {
1368 if (backend
instanceof TWindowBackend
) {
1369 // We are being rendered to a TWindow. We can't use its
1370 // getScreen() method because that is how it is rendering to a
1371 // hardware backend somewhere. Instead use its getOtherScreen()
1373 return ((TWindowBackend
) backend
).getOtherScreen();
1375 return backend
.getScreen();
1380 * Get the color theme.
1384 public final ColorTheme
getTheme() {
1389 * Repaint the screen on the next update.
1391 public void doRepaint() {
1397 * Get Y coordinate of the top edge of the desktop.
1399 * @return Y coordinate of the top edge of the desktop
1401 public final int getDesktopTop() {
1406 * Get Y coordinate of the bottom edge of the desktop.
1408 * @return Y coordinate of the bottom edge of the desktop
1410 public final int getDesktopBottom() {
1411 return desktopBottom
;
1415 * Set the TDesktop instance.
1417 * @param desktop a TDesktop instance, or null to remove the one that is
1420 public final void setDesktop(final TDesktop desktop
) {
1421 if (this.desktop
!= null) {
1422 this.desktop
.onClose();
1424 this.desktop
= desktop
;
1428 * Get the TDesktop instance.
1430 * @return the desktop, or null if it is not set
1432 public final TDesktop
getDesktop() {
1437 * Get the current active window.
1439 * @return the active window, or null if it is not set
1441 public final TWindow
getActiveWindow() {
1442 return activeWindow
;
1446 * Get a (shallow) copy of the window list.
1448 * @return a copy of the list of windows for this application
1450 public final List
<TWindow
> getAllWindows() {
1451 List
<TWindow
> result
= new ArrayList
<TWindow
>();
1452 result
.addAll(windows
);
1457 * Get focusFollowsMouse flag.
1459 * @return true if focus follows mouse: windows automatically raised if
1460 * the mouse passes over them
1462 public boolean getFocusFollowsMouse() {
1463 return focusFollowsMouse
;
1467 * Set focusFollowsMouse flag.
1469 * @param focusFollowsMouse if true, focus follows mouse: windows
1470 * automatically raised if the mouse passes over them
1472 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
1473 this.focusFollowsMouse
= focusFollowsMouse
;
1477 * Display the about dialog.
1479 protected void showAboutDialog() {
1480 String version
= getClass().getPackage().getImplementationVersion();
1481 if (version
== null) {
1482 // This is Java 9+, use a hardcoded string here.
1485 messageBox(i18n
.getString("aboutDialogTitle"),
1486 MessageFormat
.format(i18n
.getString("aboutDialogText"), version
),
1487 TMessageBox
.Type
.OK
);
1491 * Handle the Tool | Open image menu item.
1493 private void openImage() {
1495 List
<String
> filters
= new ArrayList
<String
>();
1496 filters
.add("^.*\\.[Jj][Pp][Gg]$");
1497 filters
.add("^.*\\.[Jj][Pp][Ee][Gg]$");
1498 filters
.add("^.*\\.[Pp][Nn][Gg]$");
1499 filters
.add("^.*\\.[Gg][Ii][Ff]$");
1500 filters
.add("^.*\\.[Bb][Mm][Pp]$");
1501 String filename
= fileOpenBox(".", TFileOpenBox
.Type
.OPEN
, filters
);
1502 if (filename
!= null) {
1503 new TImageWindow(this, new File(filename
));
1505 } catch (IOException e
) {
1506 // Show this exception to the user.
1507 new TExceptionDialog(this, e
);
1511 // ------------------------------------------------------------------------
1512 // Screen refresh loop ----------------------------------------------------
1513 // ------------------------------------------------------------------------
1516 * Invert the cell color at a position. This is used to track the mouse.
1518 * @param x column position
1519 * @param y row position
1521 private void invertCell(final int x
, final int y
) {
1523 System
.err
.printf("%d %s invertCell() %d %d\n",
1524 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1526 Cell cell
= getScreen().getCharXY(x
, y
);
1527 if (cell
.isImage()) {
1530 if (cell
.getForeColorRGB() < 0) {
1531 cell
.setForeColor(cell
.getForeColor().invert());
1533 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1535 if (cell
.getBackColorRGB() < 0) {
1536 cell
.setBackColor(cell
.getBackColor().invert());
1538 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1541 getScreen().putCharXY(x
, y
, cell
);
1547 private void drawAll() {
1548 boolean menuIsActive
= false;
1551 System
.err
.printf("%d %s drawAll() enter\n",
1552 System
.currentTimeMillis(), Thread
.currentThread());
1555 // I don't think this does anything useful anymore...
1558 System
.err
.printf("%d %s drawAll() !repaint\n",
1559 System
.currentTimeMillis(), Thread
.currentThread());
1561 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1563 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1564 System
.currentTimeMillis(), Thread
.currentThread());
1567 // The only thing that has happened is the mouse moved.
1569 // Redraw the old cell at that position, and save the cell at
1570 // the new mouse position.
1572 System
.err
.printf("%d %s restoreImage() %d %d\n",
1573 System
.currentTimeMillis(), Thread
.currentThread(),
1574 oldDrawnMouseX
, oldDrawnMouseY
);
1576 oldDrawnMouseCell
.restoreImage();
1577 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1579 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1580 if ((images
.size() > 0) && (backend
instanceof ECMA48Backend
)) {
1581 // Special case: the entire row containing the mouse has
1582 // to be re-drawn if it has any image data, AND any rows
1584 if (oldDrawnMouseY
!= mouseY
) {
1585 for (int i
= oldDrawnMouseY
; ;) {
1586 getScreen().unsetImageRow(i
);
1590 if (oldDrawnMouseY
< mouseY
) {
1597 getScreen().unsetImageRow(mouseY
);
1601 // Draw mouse at the new position.
1602 invertCell(mouseX
, mouseY
);
1604 oldDrawnMouseX
= mouseX
;
1605 oldDrawnMouseY
= mouseY
;
1607 if ((images
.size() > 0) || getScreen().isDirty()) {
1608 backend
.flushScreen();
1614 System
.err
.printf("%d %s drawAll() REDRAW\n",
1615 System
.currentTimeMillis(), Thread
.currentThread());
1618 // If true, the cursor is not visible
1619 boolean cursor
= false;
1621 // Start with a clean screen
1622 getScreen().clear();
1625 if (desktop
!= null) {
1626 desktop
.drawChildren();
1629 // Draw each window in reverse Z order
1630 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1631 Collections
.sort(sorted
);
1632 TWindow topLevel
= null;
1633 if (sorted
.size() > 0) {
1634 topLevel
= sorted
.get(0);
1636 Collections
.reverse(sorted
);
1637 for (TWindow window
: sorted
) {
1638 if (window
.isShown()) {
1639 window
.drawChildren();
1643 // Draw the blank menubar line - reset the screen clipping first so
1644 // it won't trim it out.
1645 getScreen().resetClipping();
1646 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1647 theme
.getColor("tmenu"));
1648 // Now draw the menus.
1650 for (TMenu menu
: menus
) {
1651 CellAttributes menuColor
;
1652 CellAttributes menuMnemonicColor
;
1653 if (menu
.isActive()) {
1654 menuIsActive
= true;
1655 menuColor
= theme
.getColor("tmenu.highlighted");
1656 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1659 menuColor
= theme
.getColor("tmenu");
1660 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1662 // Draw the menu title
1663 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
1665 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1666 // Draw the highlight character
1667 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
1668 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1670 if (menu
.isActive()) {
1671 ((TWindow
) menu
).drawChildren();
1672 // Reset the screen clipping so we can draw the next title.
1673 getScreen().resetClipping();
1675 x
+= menu
.getTitle().length() + 2;
1678 for (TMenu menu
: subMenus
) {
1679 // Reset the screen clipping so we can draw the next sub-menu.
1680 getScreen().resetClipping();
1681 ((TWindow
) menu
).drawChildren();
1683 getScreen().resetClipping();
1685 // Draw the status bar of the top-level window
1686 TStatusBar statusBar
= null;
1687 if (topLevel
!= null) {
1688 statusBar
= topLevel
.getStatusBar();
1690 if (statusBar
!= null) {
1691 getScreen().resetClipping();
1692 statusBar
.setWidth(getScreen().getWidth());
1693 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1696 CellAttributes barColor
= new CellAttributes();
1697 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1698 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
1702 // Draw the mouse pointer
1704 System
.err
.printf("%d %s restoreImage() %d %d\n",
1705 System
.currentTimeMillis(), Thread
.currentThread(),
1706 oldDrawnMouseX
, oldDrawnMouseY
);
1708 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1709 if ((images
.size() > 0) && (backend
instanceof ECMA48Backend
)) {
1710 // Special case: the entire row containing the mouse has to be
1711 // re-drawn if it has any image data, AND any rows in between.
1712 if (oldDrawnMouseY
!= mouseY
) {
1713 for (int i
= oldDrawnMouseY
; ;) {
1714 getScreen().unsetImageRow(i
);
1718 if (oldDrawnMouseY
< mouseY
) {
1725 getScreen().unsetImageRow(mouseY
);
1728 invertCell(mouseX
, mouseY
);
1729 oldDrawnMouseX
= mouseX
;
1730 oldDrawnMouseY
= mouseY
;
1732 // Place the cursor if it is visible
1733 if (!menuIsActive
) {
1734 TWidget activeWidget
= null;
1735 if (sorted
.size() > 0) {
1736 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
1737 if (activeWidget
.isCursorVisible()) {
1738 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
1739 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
1741 getScreen().putCursor(true,
1742 activeWidget
.getCursorAbsoluteX(),
1743 activeWidget
.getCursorAbsoluteY());
1746 // Turn off the cursor. Also place it at 0,0.
1747 getScreen().putCursor(false, 0, 0);
1756 getScreen().hideCursor();
1759 // Flush the screen contents
1760 if ((images
.size() > 0) || getScreen().isDirty()) {
1761 backend
.flushScreen();
1768 * Force this application to exit.
1770 public void exit() {
1772 synchronized (this) {
1777 // ------------------------------------------------------------------------
1778 // TWindow management -----------------------------------------------------
1779 // ------------------------------------------------------------------------
1782 * Return the total number of windows.
1784 * @return the total number of windows
1786 public final int windowCount() {
1787 return windows
.size();
1791 * Return the number of windows that are showing.
1793 * @return the number of windows that are showing on screen
1795 public final int shownWindowCount() {
1797 for (TWindow w
: windows
) {
1806 * Return the number of windows that are hidden.
1808 * @return the number of windows that are hidden
1810 public final int hiddenWindowCount() {
1812 for (TWindow w
: windows
) {
1821 * Check if a window instance is in this application's window list.
1823 * @param window window to look for
1824 * @return true if this window is in the list
1826 public final boolean hasWindow(final TWindow window
) {
1827 if (windows
.size() == 0) {
1830 for (TWindow w
: windows
) {
1832 assert (window
.getApplication() == this);
1840 * Activate a window: bring it to the top and have it receive events.
1842 * @param window the window to become the new active window
1844 public void activateWindow(final TWindow window
) {
1845 if (hasWindow(window
) == false) {
1847 * Someone has a handle to a window I don't have. Ignore this
1853 // Whatever window might be moving/dragging, stop it now.
1854 for (TWindow w
: windows
) {
1855 if (w
.inMovements()) {
1860 assert (windows
.size() > 0);
1862 if (window
.isHidden()) {
1863 // Unhiding will also activate.
1867 assert (window
.isShown());
1869 if (windows
.size() == 1) {
1870 assert (window
== windows
.get(0));
1871 if (activeWindow
== null) {
1872 activeWindow
= window
;
1874 activeWindow
.setActive(true);
1875 activeWindow
.onFocus();
1878 assert (window
.isActive());
1879 assert (activeWindow
== window
);
1883 if (activeWindow
== window
) {
1884 assert (window
.isActive());
1886 // Window is already active, do nothing.
1890 assert (!window
.isActive());
1891 if (activeWindow
!= null) {
1892 assert (activeWindow
.getZ() == 0);
1894 activeWindow
.setActive(false);
1896 // Increment every window Z that is on top of window
1897 for (TWindow w
: windows
) {
1901 if (w
.getZ() < window
.getZ()) {
1902 w
.setZ(w
.getZ() + 1);
1906 // Unset activeWindow now before unfocus, so that a window
1907 // lifecycle change inside onUnfocus() doesn't call
1908 // switchWindow() and lead to a stack overflow.
1909 TWindow oldActiveWindow
= activeWindow
;
1910 activeWindow
= null;
1911 oldActiveWindow
.onUnfocus();
1913 activeWindow
= window
;
1914 activeWindow
.setZ(0);
1915 activeWindow
.setActive(true);
1916 activeWindow
.onFocus();
1923 * @param window the window to hide
1925 public void hideWindow(final TWindow window
) {
1926 if (hasWindow(window
) == false) {
1928 * Someone has a handle to a window I don't have. Ignore this
1934 // Whatever window might be moving/dragging, stop it now.
1935 for (TWindow w
: windows
) {
1936 if (w
.inMovements()) {
1941 assert (windows
.size() > 0);
1943 if (!window
.hidden
) {
1944 if (window
== activeWindow
) {
1945 if (shownWindowCount() > 1) {
1948 activeWindow
= null;
1949 window
.setActive(false);
1953 window
.hidden
= true;
1961 * @param window the window to show
1963 public void showWindow(final TWindow window
) {
1964 if (hasWindow(window
) == false) {
1966 * Someone has a handle to a window I don't have. Ignore this
1972 // Whatever window might be moving/dragging, stop it now.
1973 for (TWindow w
: windows
) {
1974 if (w
.inMovements()) {
1979 assert (windows
.size() > 0);
1981 if (window
.hidden
) {
1982 window
.hidden
= false;
1984 activateWindow(window
);
1989 * Close window. Note that the window's destructor is NOT called by this
1990 * method, instead the GC is assumed to do the cleanup.
1992 * @param window the window to remove
1994 public final void closeWindow(final TWindow window
) {
1995 if (hasWindow(window
) == false) {
1997 * Someone has a handle to a window I don't have. Ignore this
2003 // Let window know that it is about to be closed, while it is still
2004 // visible on screen.
2005 window
.onPreClose();
2007 synchronized (windows
) {
2008 // Whatever window might be moving/dragging, stop it now.
2009 for (TWindow w
: windows
) {
2010 if (w
.inMovements()) {
2015 int z
= window
.getZ();
2018 windows
.remove(window
);
2019 Collections
.sort(windows
);
2020 activeWindow
= null;
2022 boolean foundNextWindow
= false;
2024 for (TWindow w
: windows
) {
2028 // Do not activate a hidden window.
2033 if (foundNextWindow
== false) {
2034 foundNextWindow
= true;
2037 assert (activeWindow
== null);
2049 // Perform window cleanup
2052 // Check if we are closing a TMessageBox or similar
2053 if (secondaryEventReceiver
!= null) {
2054 assert (secondaryEventHandler
!= null);
2056 // Do not send events to the secondaryEventReceiver anymore, the
2057 // window is closed.
2058 secondaryEventReceiver
= null;
2060 // Wake the secondary thread, it will wake the primary as it
2062 synchronized (secondaryEventHandler
) {
2063 secondaryEventHandler
.notify();
2067 // Permit desktop to be active if it is the only thing left.
2068 if (desktop
!= null) {
2069 if (windows
.size() == 0) {
2070 desktop
.setActive(true);
2076 * Switch to the next window.
2078 * @param forward if true, then switch to the next window in the list,
2079 * otherwise switch to the previous window in the list
2081 public final void switchWindow(final boolean forward
) {
2082 // Only switch if there are multiple visible windows
2083 if (shownWindowCount() < 2) {
2086 assert (activeWindow
!= null);
2088 synchronized (windows
) {
2089 // Whatever window might be moving/dragging, stop it now.
2090 for (TWindow w
: windows
) {
2091 if (w
.inMovements()) {
2096 // Swap z/active between active window and the next in the list
2097 int activeWindowI
= -1;
2098 for (int i
= 0; i
< windows
.size(); i
++) {
2099 if (windows
.get(i
) == activeWindow
) {
2100 assert (activeWindow
.isActive());
2104 assert (!windows
.get(0).isActive());
2107 assert (activeWindowI
>= 0);
2109 // Do not switch if a window is modal
2110 if (activeWindow
.isModal()) {
2114 int nextWindowI
= activeWindowI
;
2118 nextWindowI
%= windows
.size();
2121 if (nextWindowI
< 0) {
2122 nextWindowI
= windows
.size() - 1;
2126 if (windows
.get(nextWindowI
).isShown()) {
2127 activateWindow(windows
.get(nextWindowI
));
2131 } // synchronized (windows)
2136 * Add a window to my window list and make it active. Note package
2139 * @param window new window to add
2141 final void addWindowToApplication(final TWindow window
) {
2143 // Do not add menu windows to the window list.
2144 if (window
instanceof TMenu
) {
2148 // Do not add the desktop to the window list.
2149 if (window
instanceof TDesktop
) {
2153 synchronized (windows
) {
2154 if (windows
.contains(window
)) {
2155 throw new IllegalArgumentException("Window " + window
+
2156 " is already in window list");
2159 // Whatever window might be moving/dragging, stop it now.
2160 for (TWindow w
: windows
) {
2161 if (w
.inMovements()) {
2166 // Do not allow a modal window to spawn a non-modal window. If a
2167 // modal window is active, then this window will become modal
2169 if (modalWindowActive()) {
2170 window
.flags
|= TWindow
.MODAL
;
2171 window
.flags
|= TWindow
.CENTERED
;
2172 window
.hidden
= false;
2174 if (window
.isShown()) {
2175 for (TWindow w
: windows
) {
2180 w
.setZ(w
.getZ() + 1);
2183 windows
.add(window
);
2184 if (window
.isShown()) {
2185 activeWindow
= window
;
2186 activeWindow
.setZ(0);
2187 activeWindow
.setActive(true);
2188 activeWindow
.onFocus();
2191 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2192 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2193 && (smartWindowPlacement
== true)
2196 doSmartPlacement(window
);
2200 // Desktop cannot be active over any other window.
2201 if (desktop
!= null) {
2202 desktop
.setActive(false);
2207 * Check if there is a system-modal window on top.
2209 * @return true if the active window is modal
2211 private boolean modalWindowActive() {
2212 if (windows
.size() == 0) {
2216 for (TWindow w
: windows
) {
2226 * Close all open windows.
2228 private void closeAllWindows() {
2229 // Don't do anything if we are in the menu
2230 if (activeMenu
!= null) {
2233 while (windows
.size() > 0) {
2234 closeWindow(windows
.get(0));
2239 * Re-layout the open windows as non-overlapping tiles. This produces
2240 * almost the same results as Turbo Pascal 7.0's IDE.
2242 private void tileWindows() {
2243 synchronized (windows
) {
2244 // Don't do anything if we are in the menu
2245 if (activeMenu
!= null) {
2248 int z
= windows
.size();
2254 a
= (int)(Math
.sqrt(z
));
2258 if (((a
* b
) + c
) == z
) {
2266 int newWidth
= (getScreen().getWidth() / a
);
2267 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2268 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2270 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2271 Collections
.sort(sorted
);
2272 Collections
.reverse(sorted
);
2273 for (int i
= 0; i
< sorted
.size(); i
++) {
2274 int logicalX
= i
/ b
;
2275 int logicalY
= i
% b
;
2276 if (i
>= ((a
- 1) * b
)) {
2278 logicalY
= i
- ((a
- 1) * b
);
2281 TWindow w
= sorted
.get(i
);
2282 int oldWidth
= w
.getWidth();
2283 int oldHeight
= w
.getHeight();
2285 w
.setX(logicalX
* newWidth
);
2286 w
.setWidth(newWidth
);
2287 if (i
>= ((a
- 1) * b
)) {
2288 w
.setY((logicalY
* newHeight2
) + 1);
2289 w
.setHeight(newHeight2
);
2291 w
.setY((logicalY
* newHeight1
) + 1);
2292 w
.setHeight(newHeight1
);
2294 if ((w
.getWidth() != oldWidth
)
2295 || (w
.getHeight() != oldHeight
)
2297 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2298 w
.getWidth(), w
.getHeight()));
2305 * Re-layout the open windows as overlapping cascaded windows.
2307 private void cascadeWindows() {
2308 synchronized (windows
) {
2309 // Don't do anything if we are in the menu
2310 if (activeMenu
!= null) {
2315 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2316 Collections
.sort(sorted
);
2317 Collections
.reverse(sorted
);
2318 for (TWindow window
: sorted
) {
2323 if (x
> getScreen().getWidth()) {
2326 if (y
>= getScreen().getHeight()) {
2334 * Place a window to minimize its overlap with other windows.
2336 * @param window the window to place
2338 public final void doSmartPlacement(final TWindow window
) {
2339 // This is a pretty dumb algorithm, but seems to work. The hardest
2340 // part is computing these "overlap" values seeking a minimum average
2343 int yMin
= desktopTop
;
2344 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2345 int yMax
= desktopBottom
- window
.getHeight() + 1;
2353 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2354 // No work to do, bail out.
2358 // Compute the overlap matrix without the new window.
2359 int width
= getScreen().getWidth();
2360 int height
= getScreen().getHeight();
2361 int overlapMatrix
[][] = new int[width
][height
];
2362 for (TWindow w
: windows
) {
2366 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2373 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2380 overlapMatrix
[x
][y
]++;
2385 long oldOverlapTotal
= 0;
2386 long oldOverlapN
= 0;
2387 for (int x
= 0; x
< width
; x
++) {
2388 for (int y
= 0; y
< height
; y
++) {
2389 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2390 if (overlapMatrix
[x
][y
] > 0) {
2397 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2398 boolean first
= true;
2399 int windowX
= window
.getX();
2400 int windowY
= window
.getY();
2402 // For each possible (x, y) position for the new window, compute a
2403 // new overlap matrix.
2404 for (int x
= xMin
; x
< xMax
; x
++) {
2405 for (int y
= yMin
; y
< yMax
; y
++) {
2407 // Start with the matrix minus this window.
2408 int newMatrix
[][] = new int[width
][height
];
2409 for (int mx
= 0; mx
< width
; mx
++) {
2410 for (int my
= 0; my
< height
; my
++) {
2411 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2415 // Add this window's values to the new overlap matrix.
2416 long newOverlapTotal
= 0;
2417 long newOverlapN
= 0;
2418 // Start by adding each new cell.
2419 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2423 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2427 newMatrix
[wx
][wy
]++;
2430 // Now figure out the new value for total coverage.
2431 for (int mx
= 0; mx
< width
; mx
++) {
2432 for (int my
= 0; my
< height
; my
++) {
2433 newOverlapTotal
+= newMatrix
[x
][y
];
2434 if (newMatrix
[mx
][my
] > 0) {
2439 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2442 // First time: just record what we got.
2443 oldOverlapAvg
= newOverlapAvg
;
2446 // All other times: pick a new best (x, y) and save the
2448 if (newOverlapAvg
< oldOverlapAvg
) {
2451 oldOverlapAvg
= newOverlapAvg
;
2455 } // for (int x = xMin; x < xMax; x++)
2457 } // for (int y = yMin; y < yMax; y++)
2459 // Finally, set the window's new coordinates.
2460 window
.setX(windowX
);
2461 window
.setY(windowY
);
2464 // ------------------------------------------------------------------------
2465 // TImage management ------------------------------------------------------
2466 // ------------------------------------------------------------------------
2469 * Add an image to the list. Note package private access.
2471 * @param image the image to add
2472 * @throws IllegalArgumentException if the image is already used in
2473 * another TApplication
2475 final void addImage(final TImage image
) {
2476 if ((image
.getApplication() != null)
2477 && (image
.getApplication() != this)
2479 throw new IllegalArgumentException("Image " + image
+
2480 " is already " + "part of application " +
2481 image
.getApplication());
2487 * Remove an image from the list. Note package private access.
2489 * @param image the image to remove
2490 * @throws IllegalArgumentException if the image is already used in
2491 * another TApplication
2493 final void removeImage(final TImage image
) {
2494 if ((image
.getApplication() != null)
2495 && (image
.getApplication() != this)
2497 throw new IllegalArgumentException("Image " + image
+
2498 " is already " + "part of application " +
2499 image
.getApplication());
2501 images
.remove(image
);
2504 // ------------------------------------------------------------------------
2505 // TMenu management -------------------------------------------------------
2506 // ------------------------------------------------------------------------
2509 * Check if a mouse event would hit either the active menu or any open
2512 * @param mouse mouse event
2513 * @return true if the mouse would hit the active menu or an open
2516 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2517 assert (activeMenu
!= null);
2518 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2519 Collections
.reverse(menus
);
2520 for (TMenu menu
: menus
) {
2521 if (menu
.mouseWouldHit(mouse
)) {
2525 return activeMenu
.mouseWouldHit(mouse
);
2529 * See if we need to switch window or activate the menu based on
2532 * @param mouse mouse event
2534 private void checkSwitchFocus(final TMouseEvent mouse
) {
2536 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2537 && (activeMenu
!= null)
2538 && (mouse
.getAbsoluteY() != 0)
2539 && (!mouseOnMenu(mouse
))
2541 // They clicked outside the active menu, turn it off
2542 activeMenu
.setActive(false);
2544 for (TMenu menu
: subMenus
) {
2545 menu
.setActive(false);
2551 // See if they hit the menu bar
2552 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2553 && (mouse
.isMouse1())
2554 && (!modalWindowActive())
2555 && (mouse
.getAbsoluteY() == 0)
2558 for (TMenu menu
: subMenus
) {
2559 menu
.setActive(false);
2563 // They selected the menu, go activate it
2564 for (TMenu menu
: menus
) {
2565 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2566 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2567 + menu
.getTitle().length() + 2)
2569 menu
.setActive(true);
2572 menu
.setActive(false);
2578 // See if they hit the menu bar
2579 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2580 && (mouse
.isMouse1())
2581 && (activeMenu
!= null)
2582 && (mouse
.getAbsoluteY() == 0)
2585 TMenu oldMenu
= activeMenu
;
2586 for (TMenu menu
: subMenus
) {
2587 menu
.setActive(false);
2591 // See if we should switch menus
2592 for (TMenu menu
: menus
) {
2593 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2594 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2595 + menu
.getTitle().length() + 2)
2597 menu
.setActive(true);
2601 if (oldMenu
!= activeMenu
) {
2602 // They switched menus
2603 oldMenu
.setActive(false);
2608 // If a menu is still active, don't switch windows
2609 if (activeMenu
!= null) {
2613 // Only switch if there are multiple windows
2614 if (windows
.size() < 2) {
2618 if (((focusFollowsMouse
== true)
2619 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2620 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2622 synchronized (windows
) {
2623 Collections
.sort(windows
);
2624 if (windows
.get(0).isModal()) {
2625 // Modal windows don't switch
2629 for (TWindow window
: windows
) {
2630 assert (!window
.isModal());
2632 if (window
.isHidden()) {
2633 assert (!window
.isActive());
2637 if (window
.mouseWouldHit(mouse
)) {
2638 if (window
== windows
.get(0)) {
2639 // Clicked on the same window, nothing to do
2640 assert (window
.isActive());
2644 // We will be switching to another window
2645 assert (windows
.get(0).isActive());
2646 assert (windows
.get(0) == activeWindow
);
2647 assert (!window
.isActive());
2648 if (activeWindow
!= null) {
2649 activeWindow
.onUnfocus();
2650 activeWindow
.setActive(false);
2651 activeWindow
.setZ(window
.getZ());
2653 activeWindow
= window
;
2655 window
.setActive(true);
2662 // Clicked on the background, nothing to do
2666 // Nothing to do: this isn't a mouse up, or focus isn't following
2672 * Turn off the menu.
2674 public final void closeMenu() {
2675 if (activeMenu
!= null) {
2676 activeMenu
.setActive(false);
2678 for (TMenu menu
: subMenus
) {
2679 menu
.setActive(false);
2686 * Get a (shallow) copy of the menu list.
2688 * @return a copy of the menu list
2690 public final List
<TMenu
> getAllMenus() {
2691 return new ArrayList
<TMenu
>(menus
);
2695 * Add a top-level menu to the list.
2697 * @param menu the menu to add
2698 * @throws IllegalArgumentException if the menu is already used in
2699 * another TApplication
2701 public final void addMenu(final TMenu menu
) {
2702 if ((menu
.getApplication() != null)
2703 && (menu
.getApplication() != this)
2705 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2706 "part of application " + menu
.getApplication());
2714 * Remove a top-level menu from the list.
2716 * @param menu the menu to remove
2717 * @throws IllegalArgumentException if the menu is already used in
2718 * another TApplication
2720 public final void removeMenu(final TMenu menu
) {
2721 if ((menu
.getApplication() != null)
2722 && (menu
.getApplication() != this)
2724 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2725 "part of application " + menu
.getApplication());
2733 * Turn off a sub-menu.
2735 public final void closeSubMenu() {
2736 assert (activeMenu
!= null);
2737 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2738 assert (item
!= null);
2739 item
.setActive(false);
2740 subMenus
.remove(subMenus
.size() - 1);
2744 * Switch to the next menu.
2746 * @param forward if true, then switch to the next menu in the list,
2747 * otherwise switch to the previous menu in the list
2749 public final void switchMenu(final boolean forward
) {
2750 assert (activeMenu
!= null);
2752 for (TMenu menu
: subMenus
) {
2753 menu
.setActive(false);
2757 for (int i
= 0; i
< menus
.size(); i
++) {
2758 if (activeMenu
== menus
.get(i
)) {
2760 if (i
< menus
.size() - 1) {
2769 i
= menus
.size() - 1;
2772 activeMenu
.setActive(false);
2773 activeMenu
= menus
.get(i
);
2774 activeMenu
.setActive(true);
2781 * Add a menu item to the global list. If it has a keyboard accelerator,
2782 * that will be added the global hash.
2784 * @param item the menu item
2786 public final void addMenuItem(final TMenuItem item
) {
2787 menuItems
.add(item
);
2789 TKeypress key
= item
.getKey();
2791 synchronized (accelerators
) {
2792 assert (accelerators
.get(key
) == null);
2793 accelerators
.put(key
.toLowerCase(), item
);
2799 * Disable one menu item.
2801 * @param id the menu item ID
2803 public final void disableMenuItem(final int id
) {
2804 for (TMenuItem item
: menuItems
) {
2805 if (item
.getId() == id
) {
2806 item
.setEnabled(false);
2812 * Disable the range of menu items with ID's between lower and upper,
2815 * @param lower the lowest menu item ID
2816 * @param upper the highest menu item ID
2818 public final void disableMenuItems(final int lower
, final int upper
) {
2819 for (TMenuItem item
: menuItems
) {
2820 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2821 item
.setEnabled(false);
2822 item
.getParent().activate(0);
2828 * Enable one menu item.
2830 * @param id the menu item ID
2832 public final void enableMenuItem(final int id
) {
2833 for (TMenuItem item
: menuItems
) {
2834 if (item
.getId() == id
) {
2835 item
.setEnabled(true);
2836 item
.getParent().activate(0);
2842 * Enable the range of menu items with ID's between lower and upper,
2845 * @param lower the lowest menu item ID
2846 * @param upper the highest menu item ID
2848 public final void enableMenuItems(final int lower
, final int upper
) {
2849 for (TMenuItem item
: menuItems
) {
2850 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2851 item
.setEnabled(true);
2852 item
.getParent().activate(0);
2858 * Recompute menu x positions based on their title length.
2860 public final void recomputeMenuX() {
2862 for (TMenu menu
: menus
) {
2865 x
+= menu
.getTitle().length() + 2;
2867 // Don't let the menu window exceed the screen width
2868 int rightEdge
= menu
.getX() + menu
.getWidth();
2869 if (rightEdge
> getScreen().getWidth()) {
2870 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2876 * Post an event to process.
2878 * @param event new event to add to the queue
2880 public final void postEvent(final TInputEvent event
) {
2881 synchronized (this) {
2882 synchronized (fillEventQueue
) {
2883 fillEventQueue
.add(event
);
2886 System
.err
.println(System
.currentTimeMillis() + " " +
2887 Thread
.currentThread() + " postEvent() wake up main");
2894 * Post an event to process and turn off the menu.
2896 * @param event new event to add to the queue
2898 public final void postMenuEvent(final TInputEvent event
) {
2899 synchronized (this) {
2900 synchronized (fillEventQueue
) {
2901 fillEventQueue
.add(event
);
2904 System
.err
.println(System
.currentTimeMillis() + " " +
2905 Thread
.currentThread() + " postMenuEvent() wake up main");
2913 * Add a sub-menu to the list of open sub-menus.
2915 * @param menu sub-menu
2917 public final void addSubMenu(final TMenu menu
) {
2922 * Convenience function to add a top-level menu.
2924 * @param title menu title
2925 * @return the new menu
2927 public final TMenu
addMenu(final String title
) {
2930 TMenu menu
= new TMenu(this, x
, y
, title
);
2937 * Convenience function to add a default tools (hamburger) menu.
2939 * @return the new menu
2941 public final TMenu
addToolMenu() {
2942 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
2943 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
2944 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
2945 toolMenu
.addDefaultItem(TMenu
.MID_CHANGE_FONT
);
2946 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
2947 getString("toolMenuStatus"));
2948 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2953 * Convenience function to add a default "File" menu.
2955 * @return the new menu
2957 public final TMenu
addFileMenu() {
2958 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
2959 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2960 fileMenu
.addSeparator();
2961 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2962 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2963 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
2964 getString("fileMenuStatus"));
2965 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2970 * Convenience function to add a default "Edit" menu.
2972 * @return the new menu
2974 public final TMenu
addEditMenu() {
2975 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
2976 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2977 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2978 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2979 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2980 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
2981 getString("editMenuStatus"));
2982 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2987 * Convenience function to add a default "Window" menu.
2989 * @return the new menu
2991 public final TMenu
addWindowMenu() {
2992 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
2993 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2994 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2995 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2996 windowMenu
.addSeparator();
2997 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2998 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2999 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3000 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3001 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3002 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3003 getString("windowMenuStatus"));
3004 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3009 * Convenience function to add a default "Help" menu.
3011 * @return the new menu
3013 public final TMenu
addHelpMenu() {
3014 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3015 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3016 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3017 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3018 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3019 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3020 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3021 helpMenu
.addSeparator();
3022 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3023 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3024 getString("helpMenuStatus"));
3025 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3029 // ------------------------------------------------------------------------
3030 // TTimer management ------------------------------------------------------
3031 // ------------------------------------------------------------------------
3034 * Get the amount of time I can sleep before missing a Timer tick.
3036 * @param timeout = initial (maximum) timeout in millis
3037 * @return number of milliseconds between now and the next timer event
3039 private long getSleepTime(final long timeout
) {
3040 Date now
= new Date();
3041 long nowTime
= now
.getTime();
3042 long sleepTime
= timeout
;
3044 synchronized (timers
) {
3045 for (TTimer timer
: timers
) {
3046 long nextTickTime
= timer
.getNextTick().getTime();
3047 if (nextTickTime
< nowTime
) {
3051 long timeDifference
= nextTickTime
- nowTime
;
3052 if (timeDifference
< sleepTime
) {
3053 sleepTime
= timeDifference
;
3058 assert (sleepTime
>= 0);
3059 assert (sleepTime
<= timeout
);
3064 * Convenience function to add a timer.
3066 * @param duration number of milliseconds to wait between ticks
3067 * @param recurring if true, re-schedule this timer after every tick
3068 * @param action function to call when button is pressed
3071 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3072 final TAction action
) {
3074 TTimer timer
= new TTimer(duration
, recurring
, action
);
3075 synchronized (timers
) {
3082 * Convenience function to remove a timer.
3084 * @param timer timer to remove
3086 public final void removeTimer(final TTimer timer
) {
3087 synchronized (timers
) {
3088 timers
.remove(timer
);
3092 // ------------------------------------------------------------------------
3093 // Other TWindow constructors ---------------------------------------------
3094 // ------------------------------------------------------------------------
3097 * Convenience function to spawn a message box.
3099 * @param title window title, will be centered along the top border
3100 * @param caption message to display. Use embedded newlines to get a
3102 * @return the new message box
3104 public final TMessageBox
messageBox(final String title
,
3105 final String caption
) {
3107 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3111 * Convenience function to spawn a message box.
3113 * @param title window title, will be centered along the top border
3114 * @param caption message to display. Use embedded newlines to get a
3116 * @param type one of the TMessageBox.Type constants. Default is
3118 * @return the new message box
3120 public final TMessageBox
messageBox(final String title
,
3121 final String caption
, final TMessageBox
.Type type
) {
3123 return new TMessageBox(this, title
, caption
, type
);
3127 * Convenience function to spawn an input box.
3129 * @param title window title, will be centered along the top border
3130 * @param caption message to display. Use embedded newlines to get a
3132 * @return the new input box
3134 public final TInputBox
inputBox(final String title
, final String caption
) {
3136 return new TInputBox(this, title
, caption
);
3140 * Convenience function to spawn an input box.
3142 * @param title window title, will be centered along the top border
3143 * @param caption message to display. Use embedded newlines to get a
3145 * @param text initial text to seed the field with
3146 * @return the new input box
3148 public final TInputBox
inputBox(final String title
, final String caption
,
3149 final String text
) {
3151 return new TInputBox(this, title
, caption
, text
);
3155 * Convenience function to spawn an input box.
3157 * @param title window title, will be centered along the top border
3158 * @param caption message to display. Use embedded newlines to get a
3160 * @param text initial text to seed the field with
3161 * @param type one of the Type constants. Default is Type.OK.
3162 * @return the new input box
3164 public final TInputBox
inputBox(final String title
, final String caption
,
3165 final String text
, final TInputBox
.Type type
) {
3167 return new TInputBox(this, title
, caption
, text
, type
);
3171 * Convenience function to open a terminal window.
3173 * @param x column relative to parent
3174 * @param y row relative to parent
3175 * @return the terminal new window
3177 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3178 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3182 * Convenience function to open a terminal window.
3184 * @param x column relative to parent
3185 * @param y row relative to parent
3186 * @param closeOnExit if true, close the window when the command exits
3187 * @return the terminal new window
3189 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3190 final boolean closeOnExit
) {
3192 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3196 * Convenience function to open a terminal window.
3198 * @param x column relative to parent
3199 * @param y row relative to parent
3200 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3201 * @return the terminal new window
3203 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3206 return new TTerminalWindow(this, x
, y
, flags
);
3210 * Convenience function to open a terminal window.
3212 * @param x column relative to parent
3213 * @param y row relative to parent
3214 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3215 * @param closeOnExit if true, close the window when the command exits
3216 * @return the terminal new window
3218 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3219 final int flags
, final boolean closeOnExit
) {
3221 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3225 * Convenience function to open a terminal window and execute a custom
3226 * command line inside it.
3228 * @param x column relative to parent
3229 * @param y row relative to parent
3230 * @param commandLine the command line to execute
3231 * @return the terminal new window
3233 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3234 final String commandLine
) {
3236 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3240 * Convenience function to open a terminal window and execute a custom
3241 * command line inside it.
3243 * @param x column relative to parent
3244 * @param y row relative to parent
3245 * @param commandLine the command line to execute
3246 * @param closeOnExit if true, close the window when the command exits
3247 * @return the terminal new window
3249 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3250 final String commandLine
, final boolean closeOnExit
) {
3252 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3256 * Convenience function to open a terminal window and execute a custom
3257 * command line inside it.
3259 * @param x column relative to parent
3260 * @param y row relative to parent
3261 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3262 * @param command the command line to execute
3263 * @return the terminal new window
3265 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3266 final int flags
, final String
[] command
) {
3268 return new TTerminalWindow(this, x
, y
, flags
, command
);
3272 * Convenience function to open a terminal window and execute a custom
3273 * command line inside it.
3275 * @param x column relative to parent
3276 * @param y row relative to parent
3277 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3278 * @param command the command line to execute
3279 * @param closeOnExit if true, close the window when the command exits
3280 * @return the terminal new window
3282 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3283 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3285 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3289 * Convenience function to open a terminal window and execute a custom
3290 * command line inside it.
3292 * @param x column relative to parent
3293 * @param y row relative to parent
3294 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3295 * @param commandLine the command line to execute
3296 * @return the terminal new window
3298 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3299 final int flags
, final String commandLine
) {
3301 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s"));
3305 * Convenience function to open a terminal window and execute a custom
3306 * command line inside it.
3308 * @param x column relative to parent
3309 * @param y row relative to parent
3310 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3311 * @param commandLine the command line to execute
3312 * @param closeOnExit if true, close the window when the command exits
3313 * @return the terminal new window
3315 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3316 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3318 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s"),
3323 * Convenience function to spawn an file open box.
3325 * @param path path of selected file
3326 * @return the result of the new file open box
3327 * @throws IOException if java.io operation throws
3329 public final String
fileOpenBox(final String path
) throws IOException
{
3331 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3332 return box
.getFilename();
3336 * Convenience function to spawn an file open box.
3338 * @param path path of selected file
3339 * @param type one of the Type constants
3340 * @return the result of the new file open box
3341 * @throws IOException if java.io operation throws
3343 public final String
fileOpenBox(final String path
,
3344 final TFileOpenBox
.Type type
) throws IOException
{
3346 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3347 return box
.getFilename();
3351 * Convenience function to spawn a file open box.
3353 * @param path path of selected file
3354 * @param type one of the Type constants
3355 * @param filter a string that files must match to be displayed
3356 * @return the result of the new file open box
3357 * @throws IOException of a java.io operation throws
3359 public final String
fileOpenBox(final String path
,
3360 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3362 ArrayList
<String
> filters
= new ArrayList
<String
>();
3363 filters
.add(filter
);
3365 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3366 return box
.getFilename();
3370 * Convenience function to spawn a file open box.
3372 * @param path path of selected file
3373 * @param type one of the Type constants
3374 * @param filters a list of strings that files must match to be displayed
3375 * @return the result of the new file open box
3376 * @throws IOException of a java.io operation throws
3378 public final String
fileOpenBox(final String path
,
3379 final TFileOpenBox
.Type type
,
3380 final List
<String
> filters
) throws IOException
{
3382 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3383 return box
.getFilename();
3387 * Convenience function to create a new window and make it active.
3388 * Window will be located at (0, 0).
3390 * @param title window title, will be centered along the top border
3391 * @param width width of window
3392 * @param height height of window
3393 * @return the new window
3395 public final TWindow
addWindow(final String title
, final int width
,
3398 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3403 * Convenience function to create a new window and make it active.
3404 * Window will be located at (0, 0).
3406 * @param title window title, will be centered along the top border
3407 * @param width width of window
3408 * @param height height of window
3409 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3410 * @return the new window
3412 public final TWindow
addWindow(final String title
,
3413 final int width
, final int height
, final int flags
) {
3415 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3420 * Convenience function to create a new window and make it active.
3422 * @param title window title, will be centered along the top border
3423 * @param x column relative to parent
3424 * @param y row relative to parent
3425 * @param width width of window
3426 * @param height height of window
3427 * @return the new window
3429 public final TWindow
addWindow(final String title
,
3430 final int x
, final int y
, final int width
, final int height
) {
3432 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3437 * Convenience function to create a new window and make it active.
3439 * @param title window title, will be centered along the top border
3440 * @param x column relative to parent
3441 * @param y row relative to parent
3442 * @param width width of window
3443 * @param height height of window
3444 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3445 * @return the new window
3447 public final TWindow
addWindow(final String title
,
3448 final int x
, final int y
, final int width
, final int height
,
3451 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);