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);
939 desktop
.onResize(resize
);
942 // Change menu edges if needed.
945 // We are dirty, redraw the screen.
949 System.err.println("New screen: " + resize.getWidth() +
950 " x " + resize.getHeight());
955 // Put into the main queue
956 drainEventQueue
.add(event
);
961 * Dispatch one event to the appropriate widget or application-level
962 * event handler. This is the primary event handler, it has the normal
963 * application-wide event handling.
965 * @param event the input event to consume
966 * @see #secondaryHandleEvent(TInputEvent event)
968 private void primaryHandleEvent(final TInputEvent event
) {
971 System
.err
.printf("%s primaryHandleEvent: %s\n",
972 Thread
.currentThread(), event
);
974 TMouseEvent doubleClick
= null;
976 // Special application-wide events -----------------------------------
978 // Peek at the mouse position
979 if (event
instanceof TMouseEvent
) {
980 TMouseEvent mouse
= (TMouseEvent
) event
;
981 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
984 mouseX
= mouse
.getX();
985 mouseY
= mouse
.getY();
987 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
988 && (!mouse
.isMouseWheelUp())
989 && (!mouse
.isMouseWheelDown())
991 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
994 // This is a double-click.
995 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
997 mouse
.getX(), mouse
.getY(),
998 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
999 mouse
.isMouse1(), mouse
.isMouse2(),
1001 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1004 // The first click of a potential double-click.
1005 lastMouseUpTime
= mouse
.getTime().getTime();
1010 // See if we need to switch focus to another window or the menu
1011 checkSwitchFocus((TMouseEvent
) event
);
1014 // Handle menu events
1015 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1016 TMenu menu
= activeMenu
;
1018 if (event
instanceof TMouseEvent
) {
1019 TMouseEvent mouse
= (TMouseEvent
) event
;
1021 while (subMenus
.size() > 0) {
1022 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1023 if (subMenu
.mouseWouldHit(mouse
)) {
1026 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1027 && (!mouse
.isMouse1())
1028 && (!mouse
.isMouse2())
1029 && (!mouse
.isMouse3())
1030 && (!mouse
.isMouseWheelUp())
1031 && (!mouse
.isMouseWheelDown())
1035 // We navigated away from a sub-menu, so close it
1039 // Convert the mouse relative x/y to menu coordinates
1040 assert (mouse
.getX() == mouse
.getAbsoluteX());
1041 assert (mouse
.getY() == mouse
.getAbsoluteY());
1042 if (subMenus
.size() > 0) {
1043 menu
= subMenus
.get(subMenus
.size() - 1);
1045 mouse
.setX(mouse
.getX() - menu
.getX());
1046 mouse
.setY(mouse
.getY() - menu
.getY());
1048 menu
.handleEvent(event
);
1052 if (event
instanceof TKeypressEvent
) {
1053 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1055 // See if this key matches an accelerator, and is not being
1056 // shortcutted by the active window, and if so dispatch the menu
1058 boolean windowWillShortcut
= false;
1059 if (activeWindow
!= null) {
1060 assert (activeWindow
.isShown());
1061 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1062 // We do not process this key, it will be passed to the
1064 windowWillShortcut
= true;
1068 if (!windowWillShortcut
&& !modalWindowActive()) {
1069 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1070 TMenuItem item
= null;
1071 synchronized (accelerators
) {
1072 item
= accelerators
.get(keypressLowercase
);
1075 if (item
.isEnabled()) {
1076 // Let the menu item dispatch
1082 // Handle the keypress
1083 if (onKeypress(keypress
)) {
1089 if (event
instanceof TCommandEvent
) {
1090 if (onCommand((TCommandEvent
) event
)) {
1095 if (event
instanceof TMenuEvent
) {
1096 if (onMenu((TMenuEvent
) event
)) {
1101 // Dispatch events to the active window -------------------------------
1102 boolean dispatchToDesktop
= true;
1103 TWindow window
= activeWindow
;
1104 if (window
!= null) {
1105 assert (window
.isActive());
1106 assert (window
.isShown());
1107 if (event
instanceof TMouseEvent
) {
1108 TMouseEvent mouse
= (TMouseEvent
) event
;
1109 // Convert the mouse relative x/y to window coordinates
1110 assert (mouse
.getX() == mouse
.getAbsoluteX());
1111 assert (mouse
.getY() == mouse
.getAbsoluteY());
1112 mouse
.setX(mouse
.getX() - window
.getX());
1113 mouse
.setY(mouse
.getY() - window
.getY());
1115 if (doubleClick
!= null) {
1116 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1117 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1120 if (window
.mouseWouldHit(mouse
)) {
1121 dispatchToDesktop
= false;
1123 } else if (event
instanceof TKeypressEvent
) {
1124 dispatchToDesktop
= false;
1128 System
.err
.printf("TApplication dispatch event: %s\n",
1131 window
.handleEvent(event
);
1132 if (doubleClick
!= null) {
1133 window
.handleEvent(doubleClick
);
1136 if (dispatchToDesktop
) {
1137 // This event is fair game for the desktop to process.
1138 if (desktop
!= null) {
1139 desktop
.handleEvent(event
);
1140 if (doubleClick
!= null) {
1141 desktop
.handleEvent(doubleClick
);
1148 * Dispatch one event to the appropriate widget or application-level
1149 * event handler. This is the secondary event handler used by certain
1150 * special dialogs (currently TMessageBox and TFileOpenBox).
1152 * @param event the input event to consume
1153 * @see #primaryHandleEvent(TInputEvent event)
1155 private void secondaryHandleEvent(final TInputEvent event
) {
1156 TMouseEvent doubleClick
= null;
1159 System
.err
.printf("%s secondaryHandleEvent: %s\n",
1160 Thread
.currentThread(), event
);
1163 // Peek at the mouse position
1164 if (event
instanceof TMouseEvent
) {
1165 TMouseEvent mouse
= (TMouseEvent
) event
;
1166 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1169 mouseX
= mouse
.getX();
1170 mouseY
= mouse
.getY();
1172 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1173 && (!mouse
.isMouseWheelUp())
1174 && (!mouse
.isMouseWheelDown())
1176 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1179 // This is a double-click.
1180 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1182 mouse
.getX(), mouse
.getY(),
1183 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1184 mouse
.isMouse1(), mouse
.isMouse2(),
1186 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1189 // The first click of a potential double-click.
1190 lastMouseUpTime
= mouse
.getTime().getTime();
1196 secondaryEventReceiver
.handleEvent(event
);
1197 // Note that it is possible for secondaryEventReceiver to be null
1198 // now, because its handleEvent() might have finished out on the
1199 // secondary thread. So put any extra processing inside a null
1201 if (secondaryEventReceiver
!= null) {
1202 if (doubleClick
!= null) {
1203 secondaryEventReceiver
.handleEvent(doubleClick
);
1209 * Enable a widget to override the primary event thread.
1211 * @param widget widget that will receive events
1213 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1215 System
.err
.println(System
.currentTimeMillis() +
1216 " enableSecondaryEventReceiver()");
1219 assert (secondaryEventReceiver
== null);
1220 assert (secondaryEventHandler
== null);
1221 assert ((widget
instanceof TMessageBox
)
1222 || (widget
instanceof TFileOpenBox
));
1223 secondaryEventReceiver
= widget
;
1224 secondaryEventHandler
= new WidgetEventHandler(this, false);
1226 (new Thread(secondaryEventHandler
)).start();
1230 * Yield to the secondary thread.
1232 public final void yield() {
1234 System
.err
.printf(System
.currentTimeMillis() + " " +
1235 Thread
.currentThread() + " yield()\n");
1238 assert (secondaryEventReceiver
!= null);
1240 while (secondaryEventReceiver
!= null) {
1241 synchronized (primaryEventHandler
) {
1243 primaryEventHandler
.wait();
1244 } catch (InterruptedException e
) {
1252 * Do stuff when there is no user input.
1254 private void doIdle() {
1256 System
.err
.printf(System
.currentTimeMillis() + " " +
1257 Thread
.currentThread() + " doIdle()\n");
1260 synchronized (timers
) {
1263 System
.err
.printf(System
.currentTimeMillis() + " " +
1264 Thread
.currentThread() + " doIdle() 2\n");
1267 // Run any timers that have timed out
1268 Date now
= new Date();
1269 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1270 for (TTimer timer
: timers
) {
1271 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1272 // Something might change, so repaint the screen.
1275 if (timer
.recurring
) {
1276 keepTimers
.add(timer
);
1279 keepTimers
.add(timer
);
1283 timers
.addAll(keepTimers
);
1287 for (TWindow window
: windows
) {
1290 if (desktop
!= null) {
1294 // Run any invokeLaters
1295 synchronized (invokeLaters
) {
1296 for (Runnable invoke
: invokeLaters
) {
1299 invokeLaters
.clear();
1305 * Wake the sleeping active event handler.
1307 private void wakeEventHandler() {
1312 if (secondaryEventHandler
!= null) {
1313 synchronized (secondaryEventHandler
) {
1314 secondaryEventHandler
.notify();
1317 assert (primaryEventHandler
!= null);
1318 synchronized (primaryEventHandler
) {
1319 primaryEventHandler
.notify();
1324 // ------------------------------------------------------------------------
1325 // TApplication -----------------------------------------------------------
1326 // ------------------------------------------------------------------------
1329 * Place a command on the run queue, and run it before the next round of
1332 * @param command the command to run later
1334 public void invokeLater(final Runnable command
) {
1335 synchronized (invokeLaters
) {
1336 invokeLaters
.add(command
);
1342 * Restore the console to sane defaults. This is meant to be used for
1343 * improper exits (e.g. a caught exception in main()), and should not be
1344 * necessary for normal program termination.
1346 public void restoreConsole() {
1347 if (backend
!= null) {
1348 if (backend
instanceof ECMA48Backend
) {
1357 * @return the Backend
1359 public final Backend
getBackend() {
1366 * @return the Screen
1368 public final Screen
getScreen() {
1369 if (backend
instanceof TWindowBackend
) {
1370 // We are being rendered to a TWindow. We can't use its
1371 // getScreen() method because that is how it is rendering to a
1372 // hardware backend somewhere. Instead use its getOtherScreen()
1374 return ((TWindowBackend
) backend
).getOtherScreen();
1376 return backend
.getScreen();
1381 * Get the color theme.
1385 public final ColorTheme
getTheme() {
1390 * Repaint the screen on the next update.
1392 public void doRepaint() {
1398 * Get Y coordinate of the top edge of the desktop.
1400 * @return Y coordinate of the top edge of the desktop
1402 public final int getDesktopTop() {
1407 * Get Y coordinate of the bottom edge of the desktop.
1409 * @return Y coordinate of the bottom edge of the desktop
1411 public final int getDesktopBottom() {
1412 return desktopBottom
;
1416 * Set the TDesktop instance.
1418 * @param desktop a TDesktop instance, or null to remove the one that is
1421 public final void setDesktop(final TDesktop desktop
) {
1422 if (this.desktop
!= null) {
1423 this.desktop
.onClose();
1425 this.desktop
= desktop
;
1429 * Get the TDesktop instance.
1431 * @return the desktop, or null if it is not set
1433 public final TDesktop
getDesktop() {
1438 * Get the current active window.
1440 * @return the active window, or null if it is not set
1442 public final TWindow
getActiveWindow() {
1443 return activeWindow
;
1447 * Get a (shallow) copy of the window list.
1449 * @return a copy of the list of windows for this application
1451 public final List
<TWindow
> getAllWindows() {
1452 List
<TWindow
> result
= new ArrayList
<TWindow
>();
1453 result
.addAll(windows
);
1458 * Get focusFollowsMouse flag.
1460 * @return true if focus follows mouse: windows automatically raised if
1461 * the mouse passes over them
1463 public boolean getFocusFollowsMouse() {
1464 return focusFollowsMouse
;
1468 * Set focusFollowsMouse flag.
1470 * @param focusFollowsMouse if true, focus follows mouse: windows
1471 * automatically raised if the mouse passes over them
1473 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
1474 this.focusFollowsMouse
= focusFollowsMouse
;
1478 * Display the about dialog.
1480 protected void showAboutDialog() {
1481 String version
= getClass().getPackage().getImplementationVersion();
1482 if (version
== null) {
1483 // This is Java 9+, use a hardcoded string here.
1486 messageBox(i18n
.getString("aboutDialogTitle"),
1487 MessageFormat
.format(i18n
.getString("aboutDialogText"), version
),
1488 TMessageBox
.Type
.OK
);
1492 * Handle the Tool | Open image menu item.
1494 private void openImage() {
1496 List
<String
> filters
= new ArrayList
<String
>();
1497 filters
.add("^.*\\.[Jj][Pp][Gg]$");
1498 filters
.add("^.*\\.[Jj][Pp][Ee][Gg]$");
1499 filters
.add("^.*\\.[Pp][Nn][Gg]$");
1500 filters
.add("^.*\\.[Gg][Ii][Ff]$");
1501 filters
.add("^.*\\.[Bb][Mm][Pp]$");
1502 String filename
= fileOpenBox(".", TFileOpenBox
.Type
.OPEN
, filters
);
1503 if (filename
!= null) {
1504 new TImageWindow(this, new File(filename
));
1506 } catch (IOException e
) {
1507 // Show this exception to the user.
1508 new TExceptionDialog(this, e
);
1513 * Check if application is still running.
1515 * @return true if the application is running
1517 public final boolean isRunning() {
1524 // ------------------------------------------------------------------------
1525 // Screen refresh loop ----------------------------------------------------
1526 // ------------------------------------------------------------------------
1529 * Invert the cell color at a position. This is used to track the mouse.
1531 * @param x column position
1532 * @param y row position
1534 private void invertCell(final int x
, final int y
) {
1536 System
.err
.printf("%d %s invertCell() %d %d\n",
1537 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1539 if (activeWindow
!= null) {
1540 System
.err
.println("activeWindow.hasHiddenMouse() " +
1541 activeWindow
.hasHiddenMouse());
1545 // If this cell is on top of a visible window that has requested a
1546 // hidden mouse, bail out.
1547 if ((activeWindow
!= null) && (activeMenu
== null)) {
1548 if ((activeWindow
.hasHiddenMouse() == true)
1549 && (x
> activeWindow
.getX())
1550 && (x
< activeWindow
.getX() + activeWindow
.getWidth() - 1)
1551 && (y
> activeWindow
.getY())
1552 && (y
< activeWindow
.getY() + activeWindow
.getHeight() - 1)
1558 Cell cell
= getScreen().getCharXY(x
, y
);
1559 if (cell
.isImage()) {
1562 if (cell
.getForeColorRGB() < 0) {
1563 cell
.setForeColor(cell
.getForeColor().invert());
1565 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1567 if (cell
.getBackColorRGB() < 0) {
1568 cell
.setBackColor(cell
.getBackColor().invert());
1570 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1573 getScreen().putCharXY(x
, y
, cell
);
1579 private void drawAll() {
1580 boolean menuIsActive
= false;
1583 System
.err
.printf("%d %s drawAll() enter\n",
1584 System
.currentTimeMillis(), Thread
.currentThread());
1587 // I don't think this does anything useful anymore...
1590 System
.err
.printf("%d %s drawAll() !repaint\n",
1591 System
.currentTimeMillis(), Thread
.currentThread());
1593 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1595 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1596 System
.currentTimeMillis(), Thread
.currentThread());
1599 // The only thing that has happened is the mouse moved.
1601 // Redraw the old cell at that position, and save the cell at
1602 // the new mouse position.
1604 System
.err
.printf("%d %s restoreImage() %d %d\n",
1605 System
.currentTimeMillis(), Thread
.currentThread(),
1606 oldDrawnMouseX
, oldDrawnMouseY
);
1608 oldDrawnMouseCell
.restoreImage();
1609 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1611 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1612 if ((images
.size() > 0) && (backend
instanceof ECMA48Backend
)) {
1613 // Special case: the entire row containing the mouse has
1614 // to be re-drawn if it has any image data, AND any rows
1616 if (oldDrawnMouseY
!= mouseY
) {
1617 for (int i
= oldDrawnMouseY
; ;) {
1618 getScreen().unsetImageRow(i
);
1622 if (oldDrawnMouseY
< mouseY
) {
1629 getScreen().unsetImageRow(mouseY
);
1633 // Draw mouse at the new position.
1634 invertCell(mouseX
, mouseY
);
1636 oldDrawnMouseX
= mouseX
;
1637 oldDrawnMouseY
= mouseY
;
1639 if ((images
.size() > 0) || getScreen().isDirty()) {
1640 backend
.flushScreen();
1646 System
.err
.printf("%d %s drawAll() REDRAW\n",
1647 System
.currentTimeMillis(), Thread
.currentThread());
1650 // If true, the cursor is not visible
1651 boolean cursor
= false;
1653 // Start with a clean screen
1654 getScreen().clear();
1657 if (desktop
!= null) {
1658 desktop
.drawChildren();
1661 // Draw each window in reverse Z order
1662 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1663 Collections
.sort(sorted
);
1664 TWindow topLevel
= null;
1665 if (sorted
.size() > 0) {
1666 topLevel
= sorted
.get(0);
1668 Collections
.reverse(sorted
);
1669 for (TWindow window
: sorted
) {
1670 if (window
.isShown()) {
1671 window
.drawChildren();
1675 // Draw the blank menubar line - reset the screen clipping first so
1676 // it won't trim it out.
1677 getScreen().resetClipping();
1678 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1679 theme
.getColor("tmenu"));
1680 // Now draw the menus.
1682 for (TMenu menu
: menus
) {
1683 CellAttributes menuColor
;
1684 CellAttributes menuMnemonicColor
;
1685 if (menu
.isActive()) {
1686 menuIsActive
= true;
1687 menuColor
= theme
.getColor("tmenu.highlighted");
1688 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1691 menuColor
= theme
.getColor("tmenu");
1692 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1694 // Draw the menu title
1695 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
1697 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1698 // Draw the highlight character
1699 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
1700 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1702 if (menu
.isActive()) {
1703 ((TWindow
) menu
).drawChildren();
1704 // Reset the screen clipping so we can draw the next title.
1705 getScreen().resetClipping();
1707 x
+= menu
.getTitle().length() + 2;
1710 for (TMenu menu
: subMenus
) {
1711 // Reset the screen clipping so we can draw the next sub-menu.
1712 getScreen().resetClipping();
1713 ((TWindow
) menu
).drawChildren();
1715 getScreen().resetClipping();
1717 // Draw the status bar of the top-level window
1718 TStatusBar statusBar
= null;
1719 if (topLevel
!= null) {
1720 statusBar
= topLevel
.getStatusBar();
1722 if (statusBar
!= null) {
1723 getScreen().resetClipping();
1724 statusBar
.setWidth(getScreen().getWidth());
1725 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1728 CellAttributes barColor
= new CellAttributes();
1729 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1730 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
1734 // Draw the mouse pointer
1736 System
.err
.printf("%d %s restoreImage() %d %d\n",
1737 System
.currentTimeMillis(), Thread
.currentThread(),
1738 oldDrawnMouseX
, oldDrawnMouseY
);
1740 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1741 if ((images
.size() > 0) && (backend
instanceof ECMA48Backend
)) {
1742 // Special case: the entire row containing the mouse has to be
1743 // re-drawn if it has any image data, AND any rows in between.
1744 if (oldDrawnMouseY
!= mouseY
) {
1745 for (int i
= oldDrawnMouseY
; ;) {
1746 getScreen().unsetImageRow(i
);
1750 if (oldDrawnMouseY
< mouseY
) {
1757 getScreen().unsetImageRow(mouseY
);
1760 invertCell(mouseX
, mouseY
);
1761 oldDrawnMouseX
= mouseX
;
1762 oldDrawnMouseY
= mouseY
;
1764 // Place the cursor if it is visible
1765 if (!menuIsActive
) {
1766 TWidget activeWidget
= null;
1767 if (sorted
.size() > 0) {
1768 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
1769 if (activeWidget
.isCursorVisible()) {
1770 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
1771 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
1773 getScreen().putCursor(true,
1774 activeWidget
.getCursorAbsoluteX(),
1775 activeWidget
.getCursorAbsoluteY());
1778 // Turn off the cursor. Also place it at 0,0.
1779 getScreen().putCursor(false, 0, 0);
1788 getScreen().hideCursor();
1791 // Flush the screen contents
1792 if ((images
.size() > 0) || getScreen().isDirty()) {
1794 System
.err
.printf("%d %s backend.flushScreen()\n",
1795 System
.currentTimeMillis(), Thread
.currentThread());
1797 backend
.flushScreen();
1804 * Force this application to exit.
1806 public void exit() {
1808 synchronized (this) {
1813 // ------------------------------------------------------------------------
1814 // TWindow management -----------------------------------------------------
1815 // ------------------------------------------------------------------------
1818 * Return the total number of windows.
1820 * @return the total number of windows
1822 public final int windowCount() {
1823 return windows
.size();
1827 * Return the number of windows that are showing.
1829 * @return the number of windows that are showing on screen
1831 public final int shownWindowCount() {
1833 for (TWindow w
: windows
) {
1842 * Return the number of windows that are hidden.
1844 * @return the number of windows that are hidden
1846 public final int hiddenWindowCount() {
1848 for (TWindow w
: windows
) {
1857 * Check if a window instance is in this application's window list.
1859 * @param window window to look for
1860 * @return true if this window is in the list
1862 public final boolean hasWindow(final TWindow window
) {
1863 if (windows
.size() == 0) {
1866 for (TWindow w
: windows
) {
1868 assert (window
.getApplication() == this);
1876 * Activate a window: bring it to the top and have it receive events.
1878 * @param window the window to become the new active window
1880 public void activateWindow(final TWindow window
) {
1881 if (hasWindow(window
) == false) {
1883 * Someone has a handle to a window I don't have. Ignore this
1889 // Whatever window might be moving/dragging, stop it now.
1890 for (TWindow w
: windows
) {
1891 if (w
.inMovements()) {
1896 assert (windows
.size() > 0);
1898 if (window
.isHidden()) {
1899 // Unhiding will also activate.
1903 assert (window
.isShown());
1905 if (windows
.size() == 1) {
1906 assert (window
== windows
.get(0));
1907 if (activeWindow
== null) {
1908 activeWindow
= window
;
1910 activeWindow
.setActive(true);
1911 activeWindow
.onFocus();
1914 assert (window
.isActive());
1915 assert (activeWindow
== window
);
1919 if (activeWindow
== window
) {
1920 assert (window
.isActive());
1922 // Window is already active, do nothing.
1926 assert (!window
.isActive());
1927 if (activeWindow
!= null) {
1928 // TODO: see if this assertion is really necessary.
1929 // assert (activeWindow.getZ() == 0);
1931 activeWindow
.setActive(false);
1933 // Increment every window Z that is on top of window
1934 for (TWindow w
: windows
) {
1938 if (w
.getZ() < window
.getZ()) {
1939 w
.setZ(w
.getZ() + 1);
1943 // Unset activeWindow now before unfocus, so that a window
1944 // lifecycle change inside onUnfocus() doesn't call
1945 // switchWindow() and lead to a stack overflow.
1946 TWindow oldActiveWindow
= activeWindow
;
1947 activeWindow
= null;
1948 oldActiveWindow
.onUnfocus();
1950 activeWindow
= window
;
1951 activeWindow
.setZ(0);
1952 activeWindow
.setActive(true);
1953 activeWindow
.onFocus();
1960 * @param window the window to hide
1962 public void hideWindow(final TWindow window
) {
1963 if (hasWindow(window
) == false) {
1965 * Someone has a handle to a window I don't have. Ignore this
1971 // Whatever window might be moving/dragging, stop it now.
1972 for (TWindow w
: windows
) {
1973 if (w
.inMovements()) {
1978 assert (windows
.size() > 0);
1980 if (!window
.hidden
) {
1981 if (window
== activeWindow
) {
1982 if (shownWindowCount() > 1) {
1985 activeWindow
= null;
1986 window
.setActive(false);
1990 window
.hidden
= true;
1998 * @param window the window to show
2000 public void showWindow(final TWindow window
) {
2001 if (hasWindow(window
) == false) {
2003 * Someone has a handle to a window I don't have. Ignore this
2009 // Whatever window might be moving/dragging, stop it now.
2010 for (TWindow w
: windows
) {
2011 if (w
.inMovements()) {
2016 assert (windows
.size() > 0);
2018 if (window
.hidden
) {
2019 window
.hidden
= false;
2021 activateWindow(window
);
2026 * Close window. Note that the window's destructor is NOT called by this
2027 * method, instead the GC is assumed to do the cleanup.
2029 * @param window the window to remove
2031 public final void closeWindow(final TWindow window
) {
2032 if (hasWindow(window
) == false) {
2034 * Someone has a handle to a window I don't have. Ignore this
2040 // Let window know that it is about to be closed, while it is still
2041 // visible on screen.
2042 window
.onPreClose();
2044 synchronized (windows
) {
2045 // Whatever window might be moving/dragging, stop it now.
2046 for (TWindow w
: windows
) {
2047 if (w
.inMovements()) {
2052 int z
= window
.getZ();
2055 windows
.remove(window
);
2056 Collections
.sort(windows
);
2057 activeWindow
= null;
2059 boolean foundNextWindow
= false;
2061 for (TWindow w
: windows
) {
2065 // Do not activate a hidden window.
2070 if (foundNextWindow
== false) {
2071 foundNextWindow
= true;
2074 assert (activeWindow
== null);
2086 // Perform window cleanup
2089 // Check if we are closing a TMessageBox or similar
2090 if (secondaryEventReceiver
!= null) {
2091 assert (secondaryEventHandler
!= null);
2093 // Do not send events to the secondaryEventReceiver anymore, the
2094 // window is closed.
2095 secondaryEventReceiver
= null;
2097 // Wake the secondary thread, it will wake the primary as it
2099 synchronized (secondaryEventHandler
) {
2100 secondaryEventHandler
.notify();
2104 // Permit desktop to be active if it is the only thing left.
2105 if (desktop
!= null) {
2106 if (windows
.size() == 0) {
2107 desktop
.setActive(true);
2113 * Switch to the next window.
2115 * @param forward if true, then switch to the next window in the list,
2116 * otherwise switch to the previous window in the list
2118 public final void switchWindow(final boolean forward
) {
2119 // Only switch if there are multiple visible windows
2120 if (shownWindowCount() < 2) {
2123 assert (activeWindow
!= null);
2125 synchronized (windows
) {
2126 // Whatever window might be moving/dragging, stop it now.
2127 for (TWindow w
: windows
) {
2128 if (w
.inMovements()) {
2133 // Swap z/active between active window and the next in the list
2134 int activeWindowI
= -1;
2135 for (int i
= 0; i
< windows
.size(); i
++) {
2136 if (windows
.get(i
) == activeWindow
) {
2137 assert (activeWindow
.isActive());
2141 assert (!windows
.get(0).isActive());
2144 assert (activeWindowI
>= 0);
2146 // Do not switch if a window is modal
2147 if (activeWindow
.isModal()) {
2151 int nextWindowI
= activeWindowI
;
2155 nextWindowI
%= windows
.size();
2158 if (nextWindowI
< 0) {
2159 nextWindowI
= windows
.size() - 1;
2163 if (windows
.get(nextWindowI
).isShown()) {
2164 activateWindow(windows
.get(nextWindowI
));
2168 } // synchronized (windows)
2173 * Add a window to my window list and make it active. Note package
2176 * @param window new window to add
2178 final void addWindowToApplication(final TWindow window
) {
2180 // Do not add menu windows to the window list.
2181 if (window
instanceof TMenu
) {
2185 // Do not add the desktop to the window list.
2186 if (window
instanceof TDesktop
) {
2190 synchronized (windows
) {
2191 if (windows
.contains(window
)) {
2192 throw new IllegalArgumentException("Window " + window
+
2193 " is already in window list");
2196 // Whatever window might be moving/dragging, stop it now.
2197 for (TWindow w
: windows
) {
2198 if (w
.inMovements()) {
2203 // Do not allow a modal window to spawn a non-modal window. If a
2204 // modal window is active, then this window will become modal
2206 if (modalWindowActive()) {
2207 window
.flags
|= TWindow
.MODAL
;
2208 window
.flags
|= TWindow
.CENTERED
;
2209 window
.hidden
= false;
2211 if (window
.isShown()) {
2212 for (TWindow w
: windows
) {
2217 w
.setZ(w
.getZ() + 1);
2220 windows
.add(window
);
2221 if (window
.isShown()) {
2222 activeWindow
= window
;
2223 activeWindow
.setZ(0);
2224 activeWindow
.setActive(true);
2225 activeWindow
.onFocus();
2228 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2229 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2230 && (smartWindowPlacement
== true)
2233 doSmartPlacement(window
);
2237 // Desktop cannot be active over any other window.
2238 if (desktop
!= null) {
2239 desktop
.setActive(false);
2244 * Check if there is a system-modal window on top.
2246 * @return true if the active window is modal
2248 private boolean modalWindowActive() {
2249 if (windows
.size() == 0) {
2253 for (TWindow w
: windows
) {
2263 * Check if there is a window with overridden menu flag on top.
2265 * @return true if the active window is overriding the menu
2267 private boolean overrideMenuWindowActive() {
2268 if (activeWindow
!= null) {
2269 if (activeWindow
.hasOverriddenMenu()) {
2278 * Close all open windows.
2280 private void closeAllWindows() {
2281 // Don't do anything if we are in the menu
2282 if (activeMenu
!= null) {
2285 while (windows
.size() > 0) {
2286 closeWindow(windows
.get(0));
2291 * Re-layout the open windows as non-overlapping tiles. This produces
2292 * almost the same results as Turbo Pascal 7.0's IDE.
2294 private void tileWindows() {
2295 synchronized (windows
) {
2296 // Don't do anything if we are in the menu
2297 if (activeMenu
!= null) {
2300 int z
= windows
.size();
2306 a
= (int)(Math
.sqrt(z
));
2310 if (((a
* b
) + c
) == z
) {
2318 int newWidth
= (getScreen().getWidth() / a
);
2319 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2320 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2322 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2323 Collections
.sort(sorted
);
2324 Collections
.reverse(sorted
);
2325 for (int i
= 0; i
< sorted
.size(); i
++) {
2326 int logicalX
= i
/ b
;
2327 int logicalY
= i
% b
;
2328 if (i
>= ((a
- 1) * b
)) {
2330 logicalY
= i
- ((a
- 1) * b
);
2333 TWindow w
= sorted
.get(i
);
2334 int oldWidth
= w
.getWidth();
2335 int oldHeight
= w
.getHeight();
2337 w
.setX(logicalX
* newWidth
);
2338 w
.setWidth(newWidth
);
2339 if (i
>= ((a
- 1) * b
)) {
2340 w
.setY((logicalY
* newHeight2
) + 1);
2341 w
.setHeight(newHeight2
);
2343 w
.setY((logicalY
* newHeight1
) + 1);
2344 w
.setHeight(newHeight1
);
2346 if ((w
.getWidth() != oldWidth
)
2347 || (w
.getHeight() != oldHeight
)
2349 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2350 w
.getWidth(), w
.getHeight()));
2357 * Re-layout the open windows as overlapping cascaded windows.
2359 private void cascadeWindows() {
2360 synchronized (windows
) {
2361 // Don't do anything if we are in the menu
2362 if (activeMenu
!= null) {
2367 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2368 Collections
.sort(sorted
);
2369 Collections
.reverse(sorted
);
2370 for (TWindow window
: sorted
) {
2375 if (x
> getScreen().getWidth()) {
2378 if (y
>= getScreen().getHeight()) {
2386 * Place a window to minimize its overlap with other windows.
2388 * @param window the window to place
2390 public final void doSmartPlacement(final TWindow window
) {
2391 // This is a pretty dumb algorithm, but seems to work. The hardest
2392 // part is computing these "overlap" values seeking a minimum average
2395 int yMin
= desktopTop
;
2396 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2397 int yMax
= desktopBottom
- window
.getHeight() + 1;
2405 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2406 // No work to do, bail out.
2410 // Compute the overlap matrix without the new window.
2411 int width
= getScreen().getWidth();
2412 int height
= getScreen().getHeight();
2413 int overlapMatrix
[][] = new int[width
][height
];
2414 for (TWindow w
: windows
) {
2418 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2425 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2432 overlapMatrix
[x
][y
]++;
2437 long oldOverlapTotal
= 0;
2438 long oldOverlapN
= 0;
2439 for (int x
= 0; x
< width
; x
++) {
2440 for (int y
= 0; y
< height
; y
++) {
2441 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2442 if (overlapMatrix
[x
][y
] > 0) {
2449 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2450 boolean first
= true;
2451 int windowX
= window
.getX();
2452 int windowY
= window
.getY();
2454 // For each possible (x, y) position for the new window, compute a
2455 // new overlap matrix.
2456 for (int x
= xMin
; x
< xMax
; x
++) {
2457 for (int y
= yMin
; y
< yMax
; y
++) {
2459 // Start with the matrix minus this window.
2460 int newMatrix
[][] = new int[width
][height
];
2461 for (int mx
= 0; mx
< width
; mx
++) {
2462 for (int my
= 0; my
< height
; my
++) {
2463 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2467 // Add this window's values to the new overlap matrix.
2468 long newOverlapTotal
= 0;
2469 long newOverlapN
= 0;
2470 // Start by adding each new cell.
2471 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2475 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2479 newMatrix
[wx
][wy
]++;
2482 // Now figure out the new value for total coverage.
2483 for (int mx
= 0; mx
< width
; mx
++) {
2484 for (int my
= 0; my
< height
; my
++) {
2485 newOverlapTotal
+= newMatrix
[x
][y
];
2486 if (newMatrix
[mx
][my
] > 0) {
2491 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2494 // First time: just record what we got.
2495 oldOverlapAvg
= newOverlapAvg
;
2498 // All other times: pick a new best (x, y) and save the
2500 if (newOverlapAvg
< oldOverlapAvg
) {
2503 oldOverlapAvg
= newOverlapAvg
;
2507 } // for (int x = xMin; x < xMax; x++)
2509 } // for (int y = yMin; y < yMax; y++)
2511 // Finally, set the window's new coordinates.
2512 window
.setX(windowX
);
2513 window
.setY(windowY
);
2516 // ------------------------------------------------------------------------
2517 // TImage management ------------------------------------------------------
2518 // ------------------------------------------------------------------------
2521 * Add an image to the list. Note package private access.
2523 * @param image the image to add
2524 * @throws IllegalArgumentException if the image is already used in
2525 * another TApplication
2527 final void addImage(final TImage image
) {
2528 if ((image
.getApplication() != null)
2529 && (image
.getApplication() != this)
2531 throw new IllegalArgumentException("Image " + image
+
2532 " is already " + "part of application " +
2533 image
.getApplication());
2539 * Remove an image from the list. Note package private access.
2541 * @param image the image to remove
2542 * @throws IllegalArgumentException if the image is already used in
2543 * another TApplication
2545 final void removeImage(final TImage image
) {
2546 if ((image
.getApplication() != null)
2547 && (image
.getApplication() != this)
2549 throw new IllegalArgumentException("Image " + image
+
2550 " is already " + "part of application " +
2551 image
.getApplication());
2553 images
.remove(image
);
2556 // ------------------------------------------------------------------------
2557 // TMenu management -------------------------------------------------------
2558 // ------------------------------------------------------------------------
2561 * Check if a mouse event would hit either the active menu or any open
2564 * @param mouse mouse event
2565 * @return true if the mouse would hit the active menu or an open
2568 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2569 assert (activeMenu
!= null);
2570 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2571 Collections
.reverse(menus
);
2572 for (TMenu menu
: menus
) {
2573 if (menu
.mouseWouldHit(mouse
)) {
2577 return activeMenu
.mouseWouldHit(mouse
);
2581 * See if we need to switch window or activate the menu based on
2584 * @param mouse mouse event
2586 private void checkSwitchFocus(final TMouseEvent mouse
) {
2588 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2589 && (activeMenu
!= null)
2590 && (mouse
.getAbsoluteY() != 0)
2591 && (!mouseOnMenu(mouse
))
2593 // They clicked outside the active menu, turn it off
2594 activeMenu
.setActive(false);
2596 for (TMenu menu
: subMenus
) {
2597 menu
.setActive(false);
2603 // See if they hit the menu bar
2604 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2605 && (mouse
.isMouse1())
2606 && (!modalWindowActive())
2607 && (!overrideMenuWindowActive())
2608 && (mouse
.getAbsoluteY() == 0)
2611 for (TMenu menu
: subMenus
) {
2612 menu
.setActive(false);
2616 // They selected the menu, go activate it
2617 for (TMenu menu
: menus
) {
2618 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2619 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2620 + menu
.getTitle().length() + 2)
2622 menu
.setActive(true);
2625 menu
.setActive(false);
2631 // See if they hit the menu bar
2632 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2633 && (mouse
.isMouse1())
2634 && (activeMenu
!= null)
2635 && (mouse
.getAbsoluteY() == 0)
2638 TMenu oldMenu
= activeMenu
;
2639 for (TMenu menu
: subMenus
) {
2640 menu
.setActive(false);
2644 // See if we should switch menus
2645 for (TMenu menu
: menus
) {
2646 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2647 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2648 + menu
.getTitle().length() + 2)
2650 menu
.setActive(true);
2654 if (oldMenu
!= activeMenu
) {
2655 // They switched menus
2656 oldMenu
.setActive(false);
2661 // If a menu is still active, don't switch windows
2662 if (activeMenu
!= null) {
2666 // Only switch if there are multiple windows
2667 if (windows
.size() < 2) {
2671 if (((focusFollowsMouse
== true)
2672 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2673 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2675 synchronized (windows
) {
2676 Collections
.sort(windows
);
2677 if (windows
.get(0).isModal()) {
2678 // Modal windows don't switch
2682 for (TWindow window
: windows
) {
2683 assert (!window
.isModal());
2685 if (window
.isHidden()) {
2686 assert (!window
.isActive());
2690 if (window
.mouseWouldHit(mouse
)) {
2691 if (window
== windows
.get(0)) {
2692 // Clicked on the same window, nothing to do
2693 assert (window
.isActive());
2697 // We will be switching to another window
2698 assert (windows
.get(0).isActive());
2699 assert (windows
.get(0) == activeWindow
);
2700 assert (!window
.isActive());
2701 if (activeWindow
!= null) {
2702 activeWindow
.onUnfocus();
2703 activeWindow
.setActive(false);
2704 activeWindow
.setZ(window
.getZ());
2706 activeWindow
= window
;
2708 window
.setActive(true);
2715 // Clicked on the background, nothing to do
2719 // Nothing to do: this isn't a mouse up, or focus isn't following
2725 * Turn off the menu.
2727 public final void closeMenu() {
2728 if (activeMenu
!= null) {
2729 activeMenu
.setActive(false);
2731 for (TMenu menu
: subMenus
) {
2732 menu
.setActive(false);
2739 * Get a (shallow) copy of the menu list.
2741 * @return a copy of the menu list
2743 public final List
<TMenu
> getAllMenus() {
2744 return new ArrayList
<TMenu
>(menus
);
2748 * Add a top-level menu to the list.
2750 * @param menu the menu to add
2751 * @throws IllegalArgumentException if the menu is already used in
2752 * another TApplication
2754 public final void addMenu(final TMenu menu
) {
2755 if ((menu
.getApplication() != null)
2756 && (menu
.getApplication() != this)
2758 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2759 "part of application " + menu
.getApplication());
2767 * Remove a top-level menu from the list.
2769 * @param menu the menu to remove
2770 * @throws IllegalArgumentException if the menu is already used in
2771 * another TApplication
2773 public final void removeMenu(final TMenu menu
) {
2774 if ((menu
.getApplication() != null)
2775 && (menu
.getApplication() != this)
2777 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2778 "part of application " + menu
.getApplication());
2786 * Turn off a sub-menu.
2788 public final void closeSubMenu() {
2789 assert (activeMenu
!= null);
2790 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2791 assert (item
!= null);
2792 item
.setActive(false);
2793 subMenus
.remove(subMenus
.size() - 1);
2797 * Switch to the next menu.
2799 * @param forward if true, then switch to the next menu in the list,
2800 * otherwise switch to the previous menu in the list
2802 public final void switchMenu(final boolean forward
) {
2803 assert (activeMenu
!= null);
2805 for (TMenu menu
: subMenus
) {
2806 menu
.setActive(false);
2810 for (int i
= 0; i
< menus
.size(); i
++) {
2811 if (activeMenu
== menus
.get(i
)) {
2813 if (i
< menus
.size() - 1) {
2822 i
= menus
.size() - 1;
2825 activeMenu
.setActive(false);
2826 activeMenu
= menus
.get(i
);
2827 activeMenu
.setActive(true);
2834 * Add a menu item to the global list. If it has a keyboard accelerator,
2835 * that will be added the global hash.
2837 * @param item the menu item
2839 public final void addMenuItem(final TMenuItem item
) {
2840 menuItems
.add(item
);
2842 TKeypress key
= item
.getKey();
2844 synchronized (accelerators
) {
2845 assert (accelerators
.get(key
) == null);
2846 accelerators
.put(key
.toLowerCase(), item
);
2852 * Disable one menu item.
2854 * @param id the menu item ID
2856 public final void disableMenuItem(final int id
) {
2857 for (TMenuItem item
: menuItems
) {
2858 if (item
.getId() == id
) {
2859 item
.setEnabled(false);
2865 * Disable the range of menu items with ID's between lower and upper,
2868 * @param lower the lowest menu item ID
2869 * @param upper the highest menu item ID
2871 public final void disableMenuItems(final int lower
, final int upper
) {
2872 for (TMenuItem item
: menuItems
) {
2873 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2874 item
.setEnabled(false);
2875 item
.getParent().activate(0);
2881 * Enable one menu item.
2883 * @param id the menu item ID
2885 public final void enableMenuItem(final int id
) {
2886 for (TMenuItem item
: menuItems
) {
2887 if (item
.getId() == id
) {
2888 item
.setEnabled(true);
2889 item
.getParent().activate(0);
2895 * Enable the range of menu items with ID's between lower and upper,
2898 * @param lower the lowest menu item ID
2899 * @param upper the highest menu item ID
2901 public final void enableMenuItems(final int lower
, final int upper
) {
2902 for (TMenuItem item
: menuItems
) {
2903 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2904 item
.setEnabled(true);
2905 item
.getParent().activate(0);
2911 * Recompute menu x positions based on their title length.
2913 public final void recomputeMenuX() {
2915 for (TMenu menu
: menus
) {
2918 x
+= menu
.getTitle().length() + 2;
2920 // Don't let the menu window exceed the screen width
2921 int rightEdge
= menu
.getX() + menu
.getWidth();
2922 if (rightEdge
> getScreen().getWidth()) {
2923 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2929 * Post an event to process.
2931 * @param event new event to add to the queue
2933 public final void postEvent(final TInputEvent event
) {
2934 synchronized (this) {
2935 synchronized (fillEventQueue
) {
2936 fillEventQueue
.add(event
);
2939 System
.err
.println(System
.currentTimeMillis() + " " +
2940 Thread
.currentThread() + " postEvent() wake up main");
2947 * Post an event to process and turn off the menu.
2949 * @param event new event to add to the queue
2951 public final void postMenuEvent(final TInputEvent event
) {
2952 synchronized (this) {
2953 synchronized (fillEventQueue
) {
2954 fillEventQueue
.add(event
);
2957 System
.err
.println(System
.currentTimeMillis() + " " +
2958 Thread
.currentThread() + " postMenuEvent() wake up main");
2966 * Add a sub-menu to the list of open sub-menus.
2968 * @param menu sub-menu
2970 public final void addSubMenu(final TMenu menu
) {
2975 * Convenience function to add a top-level menu.
2977 * @param title menu title
2978 * @return the new menu
2980 public final TMenu
addMenu(final String title
) {
2983 TMenu menu
= new TMenu(this, x
, y
, title
);
2990 * Convenience function to add a default tools (hamburger) menu.
2992 * @return the new menu
2994 public final TMenu
addToolMenu() {
2995 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
2996 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
2997 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
2998 toolMenu
.addDefaultItem(TMenu
.MID_CHANGE_FONT
);
2999 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
3000 getString("toolMenuStatus"));
3001 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3006 * Convenience function to add a default "File" menu.
3008 * @return the new menu
3010 public final TMenu
addFileMenu() {
3011 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
3012 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
3013 fileMenu
.addSeparator();
3014 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
3015 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
3016 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
3017 getString("fileMenuStatus"));
3018 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3023 * Convenience function to add a default "Edit" menu.
3025 * @return the new menu
3027 public final TMenu
addEditMenu() {
3028 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
3029 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
3030 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
3031 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
3032 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
3033 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
3034 getString("editMenuStatus"));
3035 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3040 * Convenience function to add a default "Window" menu.
3042 * @return the new menu
3044 public final TMenu
addWindowMenu() {
3045 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
3046 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
3047 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
3048 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
3049 windowMenu
.addSeparator();
3050 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
3051 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
3052 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3053 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3054 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3055 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3056 getString("windowMenuStatus"));
3057 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3062 * Convenience function to add a default "Help" menu.
3064 * @return the new menu
3066 public final TMenu
addHelpMenu() {
3067 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3068 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3069 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3070 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3071 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3072 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3073 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3074 helpMenu
.addSeparator();
3075 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3076 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3077 getString("helpMenuStatus"));
3078 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3082 // ------------------------------------------------------------------------
3083 // TTimer management ------------------------------------------------------
3084 // ------------------------------------------------------------------------
3087 * Get the amount of time I can sleep before missing a Timer tick.
3089 * @param timeout = initial (maximum) timeout in millis
3090 * @return number of milliseconds between now and the next timer event
3092 private long getSleepTime(final long timeout
) {
3093 Date now
= new Date();
3094 long nowTime
= now
.getTime();
3095 long sleepTime
= timeout
;
3097 synchronized (timers
) {
3098 for (TTimer timer
: timers
) {
3099 long nextTickTime
= timer
.getNextTick().getTime();
3100 if (nextTickTime
< nowTime
) {
3104 long timeDifference
= nextTickTime
- nowTime
;
3105 if (timeDifference
< sleepTime
) {
3106 sleepTime
= timeDifference
;
3111 assert (sleepTime
>= 0);
3112 assert (sleepTime
<= timeout
);
3117 * Convenience function to add a timer.
3119 * @param duration number of milliseconds to wait between ticks
3120 * @param recurring if true, re-schedule this timer after every tick
3121 * @param action function to call when button is pressed
3124 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3125 final TAction action
) {
3127 TTimer timer
= new TTimer(duration
, recurring
, action
);
3128 synchronized (timers
) {
3135 * Convenience function to remove a timer.
3137 * @param timer timer to remove
3139 public final void removeTimer(final TTimer timer
) {
3140 synchronized (timers
) {
3141 timers
.remove(timer
);
3145 // ------------------------------------------------------------------------
3146 // Other TWindow constructors ---------------------------------------------
3147 // ------------------------------------------------------------------------
3150 * Convenience function to spawn a message box.
3152 * @param title window title, will be centered along the top border
3153 * @param caption message to display. Use embedded newlines to get a
3155 * @return the new message box
3157 public final TMessageBox
messageBox(final String title
,
3158 final String caption
) {
3160 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3164 * Convenience function to spawn a message box.
3166 * @param title window title, will be centered along the top border
3167 * @param caption message to display. Use embedded newlines to get a
3169 * @param type one of the TMessageBox.Type constants. Default is
3171 * @return the new message box
3173 public final TMessageBox
messageBox(final String title
,
3174 final String caption
, final TMessageBox
.Type type
) {
3176 return new TMessageBox(this, title
, caption
, type
);
3180 * Convenience function to spawn an input box.
3182 * @param title window title, will be centered along the top border
3183 * @param caption message to display. Use embedded newlines to get a
3185 * @return the new input box
3187 public final TInputBox
inputBox(final String title
, final String caption
) {
3189 return new TInputBox(this, title
, caption
);
3193 * Convenience function to spawn an input box.
3195 * @param title window title, will be centered along the top border
3196 * @param caption message to display. Use embedded newlines to get a
3198 * @param text initial text to seed the field with
3199 * @return the new input box
3201 public final TInputBox
inputBox(final String title
, final String caption
,
3202 final String text
) {
3204 return new TInputBox(this, title
, caption
, text
);
3208 * Convenience function to spawn an input box.
3210 * @param title window title, will be centered along the top border
3211 * @param caption message to display. Use embedded newlines to get a
3213 * @param text initial text to seed the field with
3214 * @param type one of the Type constants. Default is Type.OK.
3215 * @return the new input box
3217 public final TInputBox
inputBox(final String title
, final String caption
,
3218 final String text
, final TInputBox
.Type type
) {
3220 return new TInputBox(this, title
, caption
, text
, type
);
3224 * Convenience function to open a terminal window.
3226 * @param x column relative to parent
3227 * @param y row relative to parent
3228 * @return the terminal new window
3230 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3231 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3235 * Convenience function to open a terminal window.
3237 * @param x column relative to parent
3238 * @param y row relative to parent
3239 * @param closeOnExit if true, close the window when the command exits
3240 * @return the terminal new window
3242 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3243 final boolean closeOnExit
) {
3245 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3249 * Convenience function to open a terminal window.
3251 * @param x column relative to parent
3252 * @param y row relative to parent
3253 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3254 * @return the terminal new window
3256 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3259 return new TTerminalWindow(this, x
, y
, flags
);
3263 * Convenience function to open a terminal window.
3265 * @param x column relative to parent
3266 * @param y row relative to parent
3267 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3268 * @param closeOnExit if true, close the window when the command exits
3269 * @return the terminal new window
3271 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3272 final int flags
, final boolean closeOnExit
) {
3274 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3278 * Convenience function to open a terminal window and execute a custom
3279 * command line inside it.
3281 * @param x column relative to parent
3282 * @param y row relative to parent
3283 * @param commandLine the command line to execute
3284 * @return the terminal new window
3286 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3287 final String commandLine
) {
3289 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3293 * Convenience function to open a terminal window and execute a custom
3294 * command line inside it.
3296 * @param x column relative to parent
3297 * @param y row relative to parent
3298 * @param commandLine the command line to execute
3299 * @param closeOnExit if true, close the window when the command exits
3300 * @return the terminal new window
3302 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3303 final String commandLine
, final boolean closeOnExit
) {
3305 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3309 * Convenience function to open a terminal window and execute a custom
3310 * command line inside it.
3312 * @param x column relative to parent
3313 * @param y row relative to parent
3314 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3315 * @param command the command line to execute
3316 * @return the terminal new window
3318 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3319 final int flags
, final String
[] command
) {
3321 return new TTerminalWindow(this, x
, y
, flags
, command
);
3325 * Convenience function to open a terminal window and execute a custom
3326 * command line inside it.
3328 * @param x column relative to parent
3329 * @param y row relative to parent
3330 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3331 * @param command the command line to execute
3332 * @param closeOnExit if true, close the window when the command exits
3333 * @return the terminal new window
3335 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3336 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3338 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3342 * Convenience function to open a terminal window and execute a custom
3343 * command line inside it.
3345 * @param x column relative to parent
3346 * @param y row relative to parent
3347 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3348 * @param commandLine the command line to execute
3349 * @return the terminal new window
3351 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3352 final int flags
, final String commandLine
) {
3354 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"));
3358 * Convenience function to open a terminal window and execute a custom
3359 * command line inside it.
3361 * @param x column relative to parent
3362 * @param y row relative to parent
3363 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3364 * @param commandLine the command line to execute
3365 * @param closeOnExit if true, close the window when the command exits
3366 * @return the terminal new window
3368 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3369 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3371 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"),
3376 * Convenience function to spawn an file open box.
3378 * @param path path of selected file
3379 * @return the result of the new file open box
3380 * @throws IOException if java.io operation throws
3382 public final String
fileOpenBox(final String path
) throws IOException
{
3384 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3385 return box
.getFilename();
3389 * Convenience function to spawn an file open box.
3391 * @param path path of selected file
3392 * @param type one of the Type constants
3393 * @return the result of the new file open box
3394 * @throws IOException if java.io operation throws
3396 public final String
fileOpenBox(final String path
,
3397 final TFileOpenBox
.Type type
) throws IOException
{
3399 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3400 return box
.getFilename();
3404 * Convenience function to spawn a file open box.
3406 * @param path path of selected file
3407 * @param type one of the Type constants
3408 * @param filter a string that files must match to be displayed
3409 * @return the result of the new file open box
3410 * @throws IOException of a java.io operation throws
3412 public final String
fileOpenBox(final String path
,
3413 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3415 ArrayList
<String
> filters
= new ArrayList
<String
>();
3416 filters
.add(filter
);
3418 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3419 return box
.getFilename();
3423 * Convenience function to spawn a file open box.
3425 * @param path path of selected file
3426 * @param type one of the Type constants
3427 * @param filters a list of strings that files must match to be displayed
3428 * @return the result of the new file open box
3429 * @throws IOException of a java.io operation throws
3431 public final String
fileOpenBox(final String path
,
3432 final TFileOpenBox
.Type type
,
3433 final List
<String
> filters
) throws IOException
{
3435 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3436 return box
.getFilename();
3440 * Convenience function to create a new window and make it active.
3441 * Window will be located at (0, 0).
3443 * @param title window title, will be centered along the top border
3444 * @param width width of window
3445 * @param height height of window
3446 * @return the new window
3448 public final TWindow
addWindow(final String title
, final int width
,
3451 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3456 * Convenience function to create a new window and make it active.
3457 * Window will be located at (0, 0).
3459 * @param title window title, will be centered along the top border
3460 * @param width width of window
3461 * @param height height of window
3462 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3463 * @return the new window
3465 public final TWindow
addWindow(final String title
,
3466 final int width
, final int height
, final int flags
) {
3468 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3473 * Convenience function to create a new window and make it active.
3475 * @param title window title, will be centered along the top border
3476 * @param x column relative to parent
3477 * @param y row relative to parent
3478 * @param width width of window
3479 * @param height height of window
3480 * @return the new window
3482 public final TWindow
addWindow(final String title
,
3483 final int x
, final int y
, final int width
, final int height
) {
3485 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3490 * Convenience function to create a new window and make it active.
3492 * @param title window title, will be centered along the top border
3493 * @param x column relative to parent
3494 * @param y row relative to parent
3495 * @param width width of window
3496 * @param height height of window
3497 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3498 * @return the new window
3500 public final TWindow
addWindow(final String title
,
3501 final int x
, final int y
, final int width
, final int height
,
3504 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);