2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2019 Kevin Lamonte
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
32 import java
.io
.InputStream
;
33 import java
.io
.IOException
;
34 import java
.io
.OutputStream
;
35 import java
.io
.PrintWriter
;
36 import java
.io
.Reader
;
37 import java
.io
.UnsupportedEncodingException
;
38 import java
.text
.MessageFormat
;
39 import java
.util
.ArrayList
;
40 import java
.util
.Collections
;
41 import java
.util
.Date
;
42 import java
.util
.HashMap
;
43 import java
.util
.LinkedList
;
44 import java
.util
.List
;
46 import java
.util
.ResourceBundle
;
48 import jexer
.bits
.Cell
;
49 import jexer
.bits
.CellAttributes
;
50 import jexer
.bits
.ColorTheme
;
51 import jexer
.event
.TCommandEvent
;
52 import jexer
.event
.TInputEvent
;
53 import jexer
.event
.TKeypressEvent
;
54 import jexer
.event
.TMenuEvent
;
55 import jexer
.event
.TMouseEvent
;
56 import jexer
.event
.TResizeEvent
;
57 import jexer
.backend
.Backend
;
58 import jexer
.backend
.MultiBackend
;
59 import jexer
.backend
.Screen
;
60 import jexer
.backend
.SwingBackend
;
61 import jexer
.backend
.ECMA48Backend
;
62 import jexer
.backend
.TWindowBackend
;
63 import jexer
.menu
.TMenu
;
64 import jexer
.menu
.TMenuItem
;
65 import jexer
.menu
.TSubMenu
;
66 import static jexer
.TCommand
.*;
67 import static jexer
.TKeypress
.*;
70 * TApplication is the main driver class for a full Text User Interface
71 * application. It manages windows, provides a menu bar and status bar, and
72 * processes events received from the user.
74 public class TApplication
implements Runnable
{
79 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
81 // ------------------------------------------------------------------------
82 // Constants --------------------------------------------------------------
83 // ------------------------------------------------------------------------
86 * If true, emit thread stuff to System.err.
88 private static final boolean debugThreads
= false;
91 * If true, emit events being processed to System.err.
93 private static final boolean debugEvents
= false;
96 * If true, do "smart placement" on new windows that are not specified to
99 private static final boolean smartWindowPlacement
= true;
102 * Two backend types are available.
104 public static enum BackendType
{
111 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
116 * Synonym for ECMA48.
121 // ------------------------------------------------------------------------
122 // Variables --------------------------------------------------------------
123 // ------------------------------------------------------------------------
126 * The primary event handler thread.
128 private volatile WidgetEventHandler primaryEventHandler
;
131 * The secondary event handler thread.
133 private volatile WidgetEventHandler secondaryEventHandler
;
136 * The screen handler thread.
138 private volatile ScreenHandler screenHandler
;
141 * The widget receiving events from the secondary event handler thread.
143 private volatile TWidget secondaryEventReceiver
;
146 * Access to the physical screen, keyboard, and mouse.
148 private Backend backend
;
151 * Actual mouse coordinate X.
156 * Actual mouse coordinate Y.
161 * Old version of mouse coordinate X.
163 private int oldMouseX
;
166 * Old version mouse coordinate Y.
168 private int oldMouseY
;
171 * Old drawn version of mouse coordinate X.
173 private int oldDrawnMouseX
;
176 * Old drawn version mouse coordinate Y.
178 private int oldDrawnMouseY
;
181 * Old drawn version mouse cell.
183 private Cell oldDrawnMouseCell
= new Cell();
186 * The last mouse up click time, used to determine if this is a mouse
189 private long lastMouseUpTime
;
192 * The amount of millis between mouse up events to assume a double-click.
194 private long doubleClickTime
= 250;
197 * Event queue that is filled by run().
199 private List
<TInputEvent
> fillEventQueue
;
202 * Event queue that will be drained by either primary or secondary
205 private List
<TInputEvent
> drainEventQueue
;
208 * Top-level menus in this application.
210 private List
<TMenu
> menus
;
213 * Stack of activated sub-menus in this application.
215 private List
<TMenu
> subMenus
;
218 * The currently active menu.
220 private TMenu activeMenu
= null;
223 * Active keyboard accelerators.
225 private Map
<TKeypress
, TMenuItem
> accelerators
;
230 private List
<TMenuItem
> menuItems
;
233 * Windows and widgets pull colors from this ColorTheme.
235 private ColorTheme theme
;
238 * The top-level windows (but not menus).
240 private List
<TWindow
> windows
;
243 * The currently acive window.
245 private TWindow activeWindow
= null;
248 * Timers that are being ticked.
250 private List
<TTimer
> timers
;
253 * When true, the application has been started.
255 private volatile boolean started
= false;
258 * When true, exit the application.
260 private volatile boolean quit
= false;
263 * When true, repaint the entire screen.
265 private volatile boolean repaint
= true;
268 * Y coordinate of the top edge of the desktop. For now this is a
269 * constant. Someday it would be nice to have a multi-line menu or
272 private static final int desktopTop
= 1;
275 * Y coordinate of the bottom edge of the desktop.
277 private int desktopBottom
;
280 * An optional TDesktop background window that is drawn underneath
283 private TDesktop desktop
;
286 * If true, focus follows mouse: windows automatically raised if the
287 * mouse passes over them.
289 private boolean focusFollowsMouse
= false;
292 * The list of commands to run before the next I/O check.
294 private List
<Runnable
> invokeLaters
= new LinkedList
<Runnable
>();
297 * WidgetEventHandler is the main event consumer loop. There are at most
298 * two such threads in existence: the primary for normal case and a
299 * secondary that is used for TMessageBox, TInputBox, and similar.
301 private class WidgetEventHandler
implements Runnable
{
303 * The main application.
305 private TApplication application
;
308 * Whether or not this WidgetEventHandler is the primary or secondary
311 private boolean primary
= true;
314 * Public constructor.
316 * @param application the main application
317 * @param primary if true, this is the primary event handler thread
319 public WidgetEventHandler(final TApplication application
,
320 final boolean primary
) {
322 this.application
= application
;
323 this.primary
= primary
;
330 // Wrap everything in a try, so that if we go belly up we can let
331 // the user have their terminal back.
334 } catch (Throwable t
) {
335 this.application
.restoreConsole();
337 this.application
.exit();
344 private void runImpl() {
345 boolean first
= true;
348 while (!application
.quit
) {
350 // Wait until application notifies me
351 while (!application
.quit
) {
353 synchronized (application
.drainEventQueue
) {
354 if (application
.drainEventQueue
.size() > 0) {
363 timeout
= application
.getSleepTime(1000);
367 // A timer needs to fire, break out.
372 System
.err
.printf("%d %s %s %s sleep %d millis\n",
373 System
.currentTimeMillis(), this,
374 primary ?
"primary" : "secondary",
375 Thread
.currentThread(), timeout
);
378 synchronized (this) {
383 System
.err
.printf("%d %s %s %s AWAKE\n",
384 System
.currentTimeMillis(), this,
385 primary ?
"primary" : "secondary",
386 Thread
.currentThread());
390 && (application
.secondaryEventReceiver
== null)
392 // Secondary thread, emergency exit. If we got
393 // here then something went wrong with the
394 // handoff between yield() and closeWindow().
395 synchronized (application
.primaryEventHandler
) {
396 application
.primaryEventHandler
.notify();
398 application
.secondaryEventHandler
= null;
399 throw new RuntimeException("secondary exited " +
403 } catch (InterruptedException e
) {
406 } // while (!application.quit)
408 // Pull all events off the queue
410 TInputEvent event
= null;
411 synchronized (application
.drainEventQueue
) {
412 if (application
.drainEventQueue
.size() == 0) {
415 event
= application
.drainEventQueue
.remove(0);
418 // We will have an event to process, so repaint the
419 // screen at the end.
420 application
.repaint
= true;
423 primaryHandleEvent(event
);
425 secondaryHandleEvent(event
);
428 && (application
.secondaryEventReceiver
== null)
430 // Secondary thread, time to exit.
432 // Eliminate my reference so that wakeEventHandler()
433 // resumes working on the primary.
434 application
.secondaryEventHandler
= null;
436 // We are ready to exit, wake up the primary thread.
437 // Remember that it is currently sleeping inside its
438 // primaryHandleEvent().
439 synchronized (application
.primaryEventHandler
) {
440 application
.primaryEventHandler
.notify();
449 // Fire timers, update screen.
451 application
.finishEventProcessing();
454 } // while (true) (main runnable loop)
459 * ScreenHandler pushes screen updates to the physical device.
461 private class ScreenHandler
implements Runnable
{
463 * The main application.
465 private TApplication application
;
470 private boolean dirty
= false;
473 * Public constructor.
475 * @param application the main application
477 public ScreenHandler(final TApplication application
) {
478 this.application
= application
;
482 * The screen update loop.
485 // Wrap everything in a try, so that if we go belly up we can let
486 // the user have their terminal back.
489 } catch (Throwable t
) {
490 this.application
.restoreConsole();
492 this.application
.exit();
499 private void runImpl() {
502 while (!application
.quit
) {
504 // Wait until application notifies me
505 while (!application
.quit
) {
507 synchronized (this) {
513 // Always check within 50 milliseconds.
516 } catch (InterruptedException e
) {
519 } // while (!application.quit)
521 assert (dirty
== true);
523 // Flush the screen contents
525 System
.err
.printf("%d %s backend.flushScreen()\n",
526 System
.currentTimeMillis(), Thread
.currentThread());
528 synchronized (getScreen()) {
529 backend
.flushScreen();
531 } // while (true) (main runnable loop)
533 // Shutdown the user I/O thread(s)
538 * Set the dirty flag.
540 public void setDirty() {
541 synchronized (this) {
548 // ------------------------------------------------------------------------
549 // Constructors -----------------------------------------------------------
550 // ------------------------------------------------------------------------
553 * Public constructor.
555 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
557 * @param windowWidth the number of text columns to start with
558 * @param windowHeight the number of text rows to start with
559 * @param fontSize the size in points
560 * @throws UnsupportedEncodingException if an exception is thrown when
561 * creating the InputStreamReader
563 public TApplication(final BackendType backendType
, final int windowWidth
,
564 final int windowHeight
, final int fontSize
)
565 throws UnsupportedEncodingException
{
567 switch (backendType
) {
569 backend
= new SwingBackend(this, windowWidth
, windowHeight
,
575 backend
= new ECMA48Backend(this, null, null, windowWidth
,
576 windowHeight
, fontSize
);
579 throw new IllegalArgumentException("Invalid backend type: "
586 * Public constructor.
588 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
590 * @throws UnsupportedEncodingException if an exception is thrown when
591 * creating the InputStreamReader
593 public TApplication(final BackendType backendType
)
594 throws UnsupportedEncodingException
{
596 switch (backendType
) {
598 // The default SwingBackend is 80x25, 20 pt font. If you want to
599 // change that, you can pass the extra arguments to the
600 // SwingBackend constructor here. For example, if you wanted
601 // 90x30, 16 pt font:
603 // backend = new SwingBackend(this, 90, 30, 16);
604 backend
= new SwingBackend(this);
609 backend
= new ECMA48Backend(this, null, null);
612 throw new IllegalArgumentException("Invalid backend type: "
619 * Public constructor. The backend type will be BackendType.ECMA48.
621 * @param input an InputStream connected to the remote user, or null for
622 * System.in. If System.in is used, then on non-Windows systems it will
623 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
624 * mode. input is always converted to a Reader with UTF-8 encoding.
625 * @param output an OutputStream connected to the remote user, or null
626 * for System.out. output is always converted to a Writer with UTF-8
628 * @throws UnsupportedEncodingException if an exception is thrown when
629 * creating the InputStreamReader
631 public TApplication(final InputStream input
,
632 final OutputStream output
) throws UnsupportedEncodingException
{
634 backend
= new ECMA48Backend(this, input
, output
);
639 * Public constructor. The backend type will be BackendType.ECMA48.
641 * @param input the InputStream underlying 'reader'. Its available()
642 * method is used to determine if reader.read() will block or not.
643 * @param reader a Reader connected to the remote user.
644 * @param writer a PrintWriter connected to the remote user.
645 * @param setRawMode if true, set System.in into raw mode with stty.
646 * This should in general not be used. It is here solely for Demo3,
647 * which uses System.in.
648 * @throws IllegalArgumentException if input, reader, or writer are null.
650 public TApplication(final InputStream input
, final Reader reader
,
651 final PrintWriter writer
, final boolean setRawMode
) {
653 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
658 * Public constructor. The backend type will be BackendType.ECMA48.
660 * @param input the InputStream underlying 'reader'. Its available()
661 * method is used to determine if reader.read() will block or not.
662 * @param reader a Reader connected to the remote user.
663 * @param writer a PrintWriter connected to the remote user.
664 * @throws IllegalArgumentException if input, reader, or writer are null.
666 public TApplication(final InputStream input
, final Reader reader
,
667 final PrintWriter writer
) {
669 this(input
, reader
, writer
, false);
673 * Public constructor. This hook enables use with new non-Jexer
676 * @param backend a Backend that is already ready to go.
678 public TApplication(final Backend backend
) {
679 this.backend
= backend
;
680 backend
.setListener(this);
685 * Finish construction once the backend is set.
687 private void TApplicationImpl() {
688 theme
= new ColorTheme();
689 desktopBottom
= getScreen().getHeight() - 1;
690 fillEventQueue
= new LinkedList
<TInputEvent
>();
691 drainEventQueue
= new LinkedList
<TInputEvent
>();
692 windows
= new LinkedList
<TWindow
>();
693 menus
= new ArrayList
<TMenu
>();
694 subMenus
= new ArrayList
<TMenu
>();
695 timers
= new LinkedList
<TTimer
>();
696 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
697 menuItems
= new LinkedList
<TMenuItem
>();
698 desktop
= new TDesktop(this);
700 // Special case: the Swing backend needs to have a timer to drive its
702 if ((backend
instanceof SwingBackend
)
703 || (backend
instanceof MultiBackend
)
705 // Default to 500 millis, unless a SwingBackend has its own
708 if (backend
instanceof SwingBackend
) {
709 millis
= ((SwingBackend
) backend
).getBlinkMillis();
712 addTimer(millis
, true,
715 TApplication
.this.doRepaint();
723 // ------------------------------------------------------------------------
724 // Runnable ---------------------------------------------------------------
725 // ------------------------------------------------------------------------
728 * Run this application until it exits.
731 // System.err.println("*** TApplication.run() begins ***");
733 // Start the screen updater thread
734 screenHandler
= new ScreenHandler(this);
735 (new Thread(screenHandler
)).start();
737 // Start the main consumer thread
738 primaryEventHandler
= new WidgetEventHandler(this, true);
739 (new Thread(primaryEventHandler
)).start();
744 synchronized (this) {
745 boolean doWait
= false;
747 if (!backend
.hasEvents()) {
748 synchronized (fillEventQueue
) {
749 if (fillEventQueue
.size() == 0) {
756 // No I/O to dispatch, so wait until the backend
760 System
.err
.println(System
.currentTimeMillis() +
761 " " + Thread
.currentThread() + " MAIN sleep");
767 System
.err
.println(System
.currentTimeMillis() +
768 " " + Thread
.currentThread() + " MAIN AWAKE");
770 } catch (InterruptedException e
) {
771 // I'm awake and don't care why, let's see what's
772 // going on out there.
776 } // synchronized (this)
778 synchronized (fillEventQueue
) {
779 // Pull any pending I/O events
780 backend
.getEvents(fillEventQueue
);
782 // Dispatch each event to the appropriate handler, one at a
785 TInputEvent event
= null;
786 if (fillEventQueue
.size() == 0) {
789 event
= fillEventQueue
.remove(0);
790 metaHandleEvent(event
);
794 // Wake a consumer thread if we have any pending events.
795 if (drainEventQueue
.size() > 0) {
801 // Shutdown the event consumer threads
802 if (secondaryEventHandler
!= null) {
803 synchronized (secondaryEventHandler
) {
804 secondaryEventHandler
.notify();
807 if (primaryEventHandler
!= null) {
808 synchronized (primaryEventHandler
) {
809 primaryEventHandler
.notify();
813 // Close all the windows. This gives them an opportunity to release
817 // Give the overarching application an opportunity to release
821 // System.err.println("*** TApplication.run() exits ***");
824 // ------------------------------------------------------------------------
825 // Event handlers ---------------------------------------------------------
826 // ------------------------------------------------------------------------
829 * Method that TApplication subclasses can override to handle menu or
830 * posted command events.
832 * @param command command event
833 * @return if true, this event was consumed
835 protected boolean onCommand(final TCommandEvent command
) {
836 // Default: handle cmExit
837 if (command
.equals(cmExit
)) {
838 if (messageBox(i18n
.getString("exitDialogTitle"),
839 i18n
.getString("exitDialogText"),
840 TMessageBox
.Type
.YESNO
).isYes()) {
847 if (command
.equals(cmShell
)) {
848 openTerminal(0, 0, TWindow
.RESIZABLE
);
852 if (command
.equals(cmTile
)) {
856 if (command
.equals(cmCascade
)) {
860 if (command
.equals(cmCloseAll
)) {
865 if (command
.equals(cmMenu
)) {
866 if (!modalWindowActive() && (activeMenu
== null)) {
867 if (menus
.size() > 0) {
868 menus
.get(0).setActive(true);
869 activeMenu
= menus
.get(0);
879 * Method that TApplication subclasses can override to handle menu
882 * @param menu menu event
883 * @return if true, this event was consumed
885 protected boolean onMenu(final TMenuEvent menu
) {
887 // Default: handle MID_EXIT
888 if (menu
.getId() == TMenu
.MID_EXIT
) {
889 if (messageBox(i18n
.getString("exitDialogTitle"),
890 i18n
.getString("exitDialogText"),
891 TMessageBox
.Type
.YESNO
).isYes()) {
898 if (menu
.getId() == TMenu
.MID_SHELL
) {
899 openTerminal(0, 0, TWindow
.RESIZABLE
);
903 if (menu
.getId() == TMenu
.MID_TILE
) {
907 if (menu
.getId() == TMenu
.MID_CASCADE
) {
911 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
915 if (menu
.getId() == TMenu
.MID_ABOUT
) {
919 if (menu
.getId() == TMenu
.MID_REPAINT
) {
920 getScreen().clearPhysical();
924 if (menu
.getId() == TMenu
.MID_VIEW_IMAGE
) {
928 if (menu
.getId() == TMenu
.MID_CHANGE_FONT
) {
929 new TFontChooserWindow(this);
936 * Method that TApplication subclasses can override to handle keystrokes.
938 * @param keypress keystroke event
939 * @return if true, this event was consumed
941 protected boolean onKeypress(final TKeypressEvent keypress
) {
942 // Default: only menu shortcuts
944 // Process Alt-F, Alt-E, etc. menu shortcut keys
945 if (!keypress
.getKey().isFnKey()
946 && keypress
.getKey().isAlt()
947 && !keypress
.getKey().isCtrl()
948 && (activeMenu
== null)
949 && !modalWindowActive()
952 assert (subMenus
.size() == 0);
954 for (TMenu menu
: menus
) {
955 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
956 == Character
.toLowerCase(keypress
.getKey().getChar())
959 menu
.setActive(true);
969 * Process background events, and update the screen.
971 private void finishEventProcessing() {
973 System
.err
.printf(System
.currentTimeMillis() + " " +
974 Thread
.currentThread() + " finishEventProcessing()\n");
977 // Process timers and call doIdle()'s
981 synchronized (getScreen()) {
985 // Wake up the screen repainter
989 System
.err
.printf(System
.currentTimeMillis() + " " +
990 Thread
.currentThread() + " finishEventProcessing() END\n");
995 * Peek at certain application-level events, add to eventQueue, and wake
996 * up the consuming Thread.
998 * @param event the input event to consume
1000 private void metaHandleEvent(final TInputEvent event
) {
1003 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1004 event
)); System
.err
.flush();
1008 // Do no more processing if the application is already trying
1013 // Special application-wide events -------------------------------
1016 if (event
instanceof TCommandEvent
) {
1017 TCommandEvent command
= (TCommandEvent
) event
;
1018 if (command
.equals(cmAbort
)) {
1024 synchronized (drainEventQueue
) {
1026 if (event
instanceof TResizeEvent
) {
1027 TResizeEvent resize
= (TResizeEvent
) event
;
1028 synchronized (getScreen()) {
1029 getScreen().setDimensions(resize
.getWidth(),
1030 resize
.getHeight());
1031 desktopBottom
= getScreen().getHeight() - 1;
1037 if (desktop
!= null) {
1038 desktop
.setDimensions(0, 0, resize
.getWidth(),
1039 resize
.getHeight() - 1);
1040 desktop
.onResize(resize
);
1043 // Change menu edges if needed.
1046 // We are dirty, redraw the screen.
1050 System.err.println("New screen: " + resize.getWidth() +
1051 " x " + resize.getHeight());
1056 // Put into the main queue
1057 drainEventQueue
.add(event
);
1062 * Dispatch one event to the appropriate widget or application-level
1063 * event handler. This is the primary event handler, it has the normal
1064 * application-wide event handling.
1066 * @param event the input event to consume
1067 * @see #secondaryHandleEvent(TInputEvent event)
1069 private void primaryHandleEvent(final TInputEvent event
) {
1072 System
.err
.printf("%s primaryHandleEvent: %s\n",
1073 Thread
.currentThread(), event
);
1075 TMouseEvent doubleClick
= null;
1077 // Special application-wide events -----------------------------------
1079 // Peek at the mouse position
1080 if (event
instanceof TMouseEvent
) {
1081 TMouseEvent mouse
= (TMouseEvent
) event
;
1082 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1085 mouseX
= mouse
.getX();
1086 mouseY
= mouse
.getY();
1088 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1089 && (!mouse
.isMouseWheelUp())
1090 && (!mouse
.isMouseWheelDown())
1092 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1095 // This is a double-click.
1096 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1098 mouse
.getX(), mouse
.getY(),
1099 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1100 mouse
.isMouse1(), mouse
.isMouse2(),
1102 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1105 // The first click of a potential double-click.
1106 lastMouseUpTime
= mouse
.getTime().getTime();
1111 // See if we need to switch focus to another window or the menu
1112 checkSwitchFocus((TMouseEvent
) event
);
1115 // Handle menu events
1116 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1117 TMenu menu
= activeMenu
;
1119 if (event
instanceof TMouseEvent
) {
1120 TMouseEvent mouse
= (TMouseEvent
) event
;
1122 while (subMenus
.size() > 0) {
1123 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1124 if (subMenu
.mouseWouldHit(mouse
)) {
1127 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1128 && (!mouse
.isMouse1())
1129 && (!mouse
.isMouse2())
1130 && (!mouse
.isMouse3())
1131 && (!mouse
.isMouseWheelUp())
1132 && (!mouse
.isMouseWheelDown())
1136 // We navigated away from a sub-menu, so close it
1140 // Convert the mouse relative x/y to menu coordinates
1141 assert (mouse
.getX() == mouse
.getAbsoluteX());
1142 assert (mouse
.getY() == mouse
.getAbsoluteY());
1143 if (subMenus
.size() > 0) {
1144 menu
= subMenus
.get(subMenus
.size() - 1);
1146 mouse
.setX(mouse
.getX() - menu
.getX());
1147 mouse
.setY(mouse
.getY() - menu
.getY());
1149 menu
.handleEvent(event
);
1153 if (event
instanceof TKeypressEvent
) {
1154 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1156 // See if this key matches an accelerator, and is not being
1157 // shortcutted by the active window, and if so dispatch the menu
1159 boolean windowWillShortcut
= false;
1160 if (activeWindow
!= null) {
1161 assert (activeWindow
.isShown());
1162 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1163 // We do not process this key, it will be passed to the
1165 windowWillShortcut
= true;
1169 if (!windowWillShortcut
&& !modalWindowActive()) {
1170 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1171 TMenuItem item
= null;
1172 synchronized (accelerators
) {
1173 item
= accelerators
.get(keypressLowercase
);
1176 if (item
.isEnabled()) {
1177 // Let the menu item dispatch
1183 // Handle the keypress
1184 if (onKeypress(keypress
)) {
1190 if (event
instanceof TCommandEvent
) {
1191 if (onCommand((TCommandEvent
) event
)) {
1196 if (event
instanceof TMenuEvent
) {
1197 if (onMenu((TMenuEvent
) event
)) {
1202 // Dispatch events to the active window -------------------------------
1203 boolean dispatchToDesktop
= true;
1204 TWindow window
= activeWindow
;
1205 if (window
!= null) {
1206 assert (window
.isActive());
1207 assert (window
.isShown());
1208 if (event
instanceof TMouseEvent
) {
1209 TMouseEvent mouse
= (TMouseEvent
) event
;
1210 // Convert the mouse relative x/y to window coordinates
1211 assert (mouse
.getX() == mouse
.getAbsoluteX());
1212 assert (mouse
.getY() == mouse
.getAbsoluteY());
1213 mouse
.setX(mouse
.getX() - window
.getX());
1214 mouse
.setY(mouse
.getY() - window
.getY());
1216 if (doubleClick
!= null) {
1217 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1218 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1221 if (window
.mouseWouldHit(mouse
)) {
1222 dispatchToDesktop
= false;
1224 } else if (event
instanceof TKeypressEvent
) {
1225 dispatchToDesktop
= false;
1229 System
.err
.printf("TApplication dispatch event: %s\n",
1232 window
.handleEvent(event
);
1233 if (doubleClick
!= null) {
1234 window
.handleEvent(doubleClick
);
1237 if (dispatchToDesktop
) {
1238 // This event is fair game for the desktop to process.
1239 if (desktop
!= null) {
1240 desktop
.handleEvent(event
);
1241 if (doubleClick
!= null) {
1242 desktop
.handleEvent(doubleClick
);
1249 * Dispatch one event to the appropriate widget or application-level
1250 * event handler. This is the secondary event handler used by certain
1251 * special dialogs (currently TMessageBox and TFileOpenBox).
1253 * @param event the input event to consume
1254 * @see #primaryHandleEvent(TInputEvent event)
1256 private void secondaryHandleEvent(final TInputEvent event
) {
1257 TMouseEvent doubleClick
= null;
1260 System
.err
.printf("%s secondaryHandleEvent: %s\n",
1261 Thread
.currentThread(), event
);
1264 // Peek at the mouse position
1265 if (event
instanceof TMouseEvent
) {
1266 TMouseEvent mouse
= (TMouseEvent
) event
;
1267 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1270 mouseX
= mouse
.getX();
1271 mouseY
= mouse
.getY();
1273 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
1274 && (!mouse
.isMouseWheelUp())
1275 && (!mouse
.isMouseWheelDown())
1277 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1280 // This is a double-click.
1281 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1283 mouse
.getX(), mouse
.getY(),
1284 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1285 mouse
.isMouse1(), mouse
.isMouse2(),
1287 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1290 // The first click of a potential double-click.
1291 lastMouseUpTime
= mouse
.getTime().getTime();
1297 secondaryEventReceiver
.handleEvent(event
);
1298 // Note that it is possible for secondaryEventReceiver to be null
1299 // now, because its handleEvent() might have finished out on the
1300 // secondary thread. So put any extra processing inside a null
1302 if (secondaryEventReceiver
!= null) {
1303 if (doubleClick
!= null) {
1304 secondaryEventReceiver
.handleEvent(doubleClick
);
1310 * Enable a widget to override the primary event thread.
1312 * @param widget widget that will receive events
1314 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1316 System
.err
.println(System
.currentTimeMillis() +
1317 " enableSecondaryEventReceiver()");
1320 assert (secondaryEventReceiver
== null);
1321 assert (secondaryEventHandler
== null);
1322 assert ((widget
instanceof TMessageBox
)
1323 || (widget
instanceof TFileOpenBox
));
1324 secondaryEventReceiver
= widget
;
1325 secondaryEventHandler
= new WidgetEventHandler(this, false);
1327 (new Thread(secondaryEventHandler
)).start();
1331 * Yield to the secondary thread.
1333 public final void yield() {
1335 System
.err
.printf(System
.currentTimeMillis() + " " +
1336 Thread
.currentThread() + " yield()\n");
1339 assert (secondaryEventReceiver
!= null);
1341 while (secondaryEventReceiver
!= null) {
1342 synchronized (primaryEventHandler
) {
1344 primaryEventHandler
.wait();
1345 } catch (InterruptedException e
) {
1353 * Do stuff when there is no user input.
1355 private void doIdle() {
1357 System
.err
.printf(System
.currentTimeMillis() + " " +
1358 Thread
.currentThread() + " doIdle()\n");
1361 synchronized (timers
) {
1364 System
.err
.printf(System
.currentTimeMillis() + " " +
1365 Thread
.currentThread() + " doIdle() 2\n");
1368 // Run any timers that have timed out
1369 Date now
= new Date();
1370 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1371 for (TTimer timer
: timers
) {
1372 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1373 // Something might change, so repaint the screen.
1376 if (timer
.recurring
) {
1377 keepTimers
.add(timer
);
1380 keepTimers
.add(timer
);
1384 timers
.addAll(keepTimers
);
1388 for (TWindow window
: windows
) {
1391 if (desktop
!= null) {
1395 // Run any invokeLaters
1396 synchronized (invokeLaters
) {
1397 for (Runnable invoke
: invokeLaters
) {
1400 invokeLaters
.clear();
1406 * Wake the sleeping active event handler.
1408 private void wakeEventHandler() {
1413 if (secondaryEventHandler
!= null) {
1414 synchronized (secondaryEventHandler
) {
1415 secondaryEventHandler
.notify();
1418 assert (primaryEventHandler
!= null);
1419 synchronized (primaryEventHandler
) {
1420 primaryEventHandler
.notify();
1426 * Wake the sleeping screen handler.
1428 private void wakeScreenHandler() {
1433 synchronized (screenHandler
) {
1434 screenHandler
.notify();
1438 // ------------------------------------------------------------------------
1439 // TApplication -----------------------------------------------------------
1440 // ------------------------------------------------------------------------
1443 * Place a command on the run queue, and run it before the next round of
1446 * @param command the command to run later
1448 public void invokeLater(final Runnable command
) {
1449 synchronized (invokeLaters
) {
1450 invokeLaters
.add(command
);
1456 * Restore the console to sane defaults. This is meant to be used for
1457 * improper exits (e.g. a caught exception in main()), and should not be
1458 * necessary for normal program termination.
1460 public void restoreConsole() {
1461 if (backend
!= null) {
1462 if (backend
instanceof ECMA48Backend
) {
1471 * @return the Backend
1473 public final Backend
getBackend() {
1480 * @return the Screen
1482 public final Screen
getScreen() {
1483 if (backend
instanceof TWindowBackend
) {
1484 // We are being rendered to a TWindow. We can't use its
1485 // getScreen() method because that is how it is rendering to a
1486 // hardware backend somewhere. Instead use its getOtherScreen()
1488 return ((TWindowBackend
) backend
).getOtherScreen();
1490 return backend
.getScreen();
1495 * Get the color theme.
1499 public final ColorTheme
getTheme() {
1504 * Repaint the screen on the next update.
1506 public void doRepaint() {
1512 * Get Y coordinate of the top edge of the desktop.
1514 * @return Y coordinate of the top edge of the desktop
1516 public final int getDesktopTop() {
1521 * Get Y coordinate of the bottom edge of the desktop.
1523 * @return Y coordinate of the bottom edge of the desktop
1525 public final int getDesktopBottom() {
1526 return desktopBottom
;
1530 * Set the TDesktop instance.
1532 * @param desktop a TDesktop instance, or null to remove the one that is
1535 public final void setDesktop(final TDesktop desktop
) {
1536 if (this.desktop
!= null) {
1537 this.desktop
.onClose();
1539 this.desktop
= desktop
;
1543 * Get the TDesktop instance.
1545 * @return the desktop, or null if it is not set
1547 public final TDesktop
getDesktop() {
1552 * Get the current active window.
1554 * @return the active window, or null if it is not set
1556 public final TWindow
getActiveWindow() {
1557 return activeWindow
;
1561 * Get a (shallow) copy of the window list.
1563 * @return a copy of the list of windows for this application
1565 public final List
<TWindow
> getAllWindows() {
1566 List
<TWindow
> result
= new ArrayList
<TWindow
>();
1567 result
.addAll(windows
);
1572 * Get focusFollowsMouse flag.
1574 * @return true if focus follows mouse: windows automatically raised if
1575 * the mouse passes over them
1577 public boolean getFocusFollowsMouse() {
1578 return focusFollowsMouse
;
1582 * Set focusFollowsMouse flag.
1584 * @param focusFollowsMouse if true, focus follows mouse: windows
1585 * automatically raised if the mouse passes over them
1587 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
1588 this.focusFollowsMouse
= focusFollowsMouse
;
1592 * Display the about dialog.
1594 protected void showAboutDialog() {
1595 String version
= getClass().getPackage().getImplementationVersion();
1596 if (version
== null) {
1597 // This is Java 9+, use a hardcoded string here.
1600 messageBox(i18n
.getString("aboutDialogTitle"),
1601 MessageFormat
.format(i18n
.getString("aboutDialogText"), version
),
1602 TMessageBox
.Type
.OK
);
1606 * Handle the Tool | Open image menu item.
1608 private void openImage() {
1610 List
<String
> filters
= new ArrayList
<String
>();
1611 filters
.add("^.*\\.[Jj][Pp][Gg]$");
1612 filters
.add("^.*\\.[Jj][Pp][Ee][Gg]$");
1613 filters
.add("^.*\\.[Pp][Nn][Gg]$");
1614 filters
.add("^.*\\.[Gg][Ii][Ff]$");
1615 filters
.add("^.*\\.[Bb][Mm][Pp]$");
1616 String filename
= fileOpenBox(".", TFileOpenBox
.Type
.OPEN
, filters
);
1617 if (filename
!= null) {
1618 new TImageWindow(this, new File(filename
));
1620 } catch (IOException e
) {
1621 // Show this exception to the user.
1622 new TExceptionDialog(this, e
);
1627 * Check if application is still running.
1629 * @return true if the application is running
1631 public final boolean isRunning() {
1638 // ------------------------------------------------------------------------
1639 // Screen refresh loop ----------------------------------------------------
1640 // ------------------------------------------------------------------------
1643 * Invert the cell color at a position. This is used to track the mouse.
1645 * @param x column position
1646 * @param y row position
1648 private void invertCell(final int x
, final int y
) {
1649 invertCell(x
, y
, false);
1653 * Invert the cell color at a position. This is used to track the mouse.
1655 * @param x column position
1656 * @param y row position
1657 * @param onlyThisCell if true, only invert this cell
1659 private void invertCell(final int x
, final int y
,
1660 final boolean onlyThisCell
) {
1663 System
.err
.printf("%d %s invertCell() %d %d\n",
1664 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
1666 if (activeWindow
!= null) {
1667 System
.err
.println("activeWindow.hasHiddenMouse() " +
1668 activeWindow
.hasHiddenMouse());
1672 // If this cell is on top of a visible window that has requested a
1673 // hidden mouse, bail out.
1674 if ((activeWindow
!= null) && (activeMenu
== null)) {
1675 if ((activeWindow
.hasHiddenMouse() == true)
1676 && (x
> activeWindow
.getX())
1677 && (x
< activeWindow
.getX() + activeWindow
.getWidth() - 1)
1678 && (y
> activeWindow
.getY())
1679 && (y
< activeWindow
.getY() + activeWindow
.getHeight() - 1)
1685 Cell cell
= getScreen().getCharXY(x
, y
);
1686 if (cell
.isImage()) {
1689 if (cell
.getForeColorRGB() < 0) {
1690 cell
.setForeColor(cell
.getForeColor().invert());
1692 cell
.setForeColorRGB(cell
.getForeColorRGB() ^
0x00ffffff);
1694 if (cell
.getBackColorRGB() < 0) {
1695 cell
.setBackColor(cell
.getBackColor().invert());
1697 cell
.setBackColorRGB(cell
.getBackColorRGB() ^
0x00ffffff);
1700 getScreen().putCharXY(x
, y
, cell
);
1701 if ((onlyThisCell
== true) || (cell
.getWidth() == Cell
.Width
.SINGLE
)) {
1705 // This cell is one half of a fullwidth glyph. Invert the other
1707 if (cell
.getWidth() == Cell
.Width
.LEFT
) {
1708 if (x
< getScreen().getWidth() - 1) {
1709 Cell rightHalf
= getScreen().getCharXY(x
+ 1, y
);
1710 if (rightHalf
.getWidth() == Cell
.Width
.RIGHT
) {
1711 invertCell(x
+ 1, y
, true);
1716 assert (cell
.getWidth() == Cell
.Width
.RIGHT
);
1719 Cell leftHalf
= getScreen().getCharXY(x
- 1, y
);
1720 if (leftHalf
.getWidth() == Cell
.Width
.LEFT
) {
1721 invertCell(x
- 1, y
, true);
1729 private void drawAll() {
1730 boolean menuIsActive
= false;
1733 System
.err
.printf("%d %s drawAll() enter\n",
1734 System
.currentTimeMillis(), Thread
.currentThread());
1737 // I don't think this does anything useful anymore...
1740 System
.err
.printf("%d %s drawAll() !repaint\n",
1741 System
.currentTimeMillis(), Thread
.currentThread());
1743 if ((oldDrawnMouseX
!= mouseX
) || (oldDrawnMouseY
!= mouseY
)) {
1745 System
.err
.printf("%d %s drawAll() !repaint MOUSE\n",
1746 System
.currentTimeMillis(), Thread
.currentThread());
1749 // The only thing that has happened is the mouse moved.
1751 // Redraw the old cell at that position, and save the cell at
1752 // the new mouse position.
1754 System
.err
.printf("%d %s restoreImage() %d %d\n",
1755 System
.currentTimeMillis(), Thread
.currentThread(),
1756 oldDrawnMouseX
, oldDrawnMouseY
);
1758 oldDrawnMouseCell
.restoreImage();
1759 getScreen().putCharXY(oldDrawnMouseX
, oldDrawnMouseY
,
1761 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1762 if (backend
instanceof ECMA48Backend
) {
1763 // Special case: the entire row containing the mouse has
1764 // to be re-drawn if it has any image data, AND any rows
1766 if (oldDrawnMouseY
!= mouseY
) {
1767 for (int i
= oldDrawnMouseY
; ;) {
1768 getScreen().unsetImageRow(i
);
1772 if (oldDrawnMouseY
< mouseY
) {
1779 getScreen().unsetImageRow(mouseY
);
1783 // Draw mouse at the new position.
1784 invertCell(mouseX
, mouseY
);
1786 oldDrawnMouseX
= mouseX
;
1787 oldDrawnMouseY
= mouseY
;
1789 if (getScreen().isDirty()) {
1790 screenHandler
.setDirty();
1796 System
.err
.printf("%d %s drawAll() REDRAW\n",
1797 System
.currentTimeMillis(), Thread
.currentThread());
1800 // If true, the cursor is not visible
1801 boolean cursor
= false;
1803 // Start with a clean screen
1804 getScreen().clear();
1807 if (desktop
!= null) {
1808 desktop
.drawChildren();
1811 // Draw each window in reverse Z order
1812 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
1813 Collections
.sort(sorted
);
1814 TWindow topLevel
= null;
1815 if (sorted
.size() > 0) {
1816 topLevel
= sorted
.get(0);
1818 Collections
.reverse(sorted
);
1819 for (TWindow window
: sorted
) {
1820 if (window
.isShown()) {
1821 window
.drawChildren();
1825 // Draw the blank menubar line - reset the screen clipping first so
1826 // it won't trim it out.
1827 getScreen().resetClipping();
1828 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
1829 theme
.getColor("tmenu"));
1830 // Now draw the menus.
1832 for (TMenu menu
: menus
) {
1833 CellAttributes menuColor
;
1834 CellAttributes menuMnemonicColor
;
1835 if (menu
.isActive()) {
1836 menuIsActive
= true;
1837 menuColor
= theme
.getColor("tmenu.highlighted");
1838 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
1841 menuColor
= theme
.getColor("tmenu");
1842 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
1844 // Draw the menu title
1845 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
1847 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
1848 // Draw the highlight character
1849 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
1850 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
1852 if (menu
.isActive()) {
1853 ((TWindow
) menu
).drawChildren();
1854 // Reset the screen clipping so we can draw the next title.
1855 getScreen().resetClipping();
1857 x
+= menu
.getTitle().length() + 2;
1860 for (TMenu menu
: subMenus
) {
1861 // Reset the screen clipping so we can draw the next sub-menu.
1862 getScreen().resetClipping();
1863 ((TWindow
) menu
).drawChildren();
1865 getScreen().resetClipping();
1867 // Draw the status bar of the top-level window
1868 TStatusBar statusBar
= null;
1869 if (topLevel
!= null) {
1870 statusBar
= topLevel
.getStatusBar();
1872 if (statusBar
!= null) {
1873 getScreen().resetClipping();
1874 statusBar
.setWidth(getScreen().getWidth());
1875 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
1878 CellAttributes barColor
= new CellAttributes();
1879 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
1880 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
1884 // Draw the mouse pointer
1886 System
.err
.printf("%d %s restoreImage() %d %d\n",
1887 System
.currentTimeMillis(), Thread
.currentThread(),
1888 oldDrawnMouseX
, oldDrawnMouseY
);
1890 oldDrawnMouseCell
= getScreen().getCharXY(mouseX
, mouseY
);
1891 if (backend
instanceof ECMA48Backend
) {
1892 // Special case: the entire row containing the mouse has to be
1893 // re-drawn if it has any image data, AND any rows in between.
1894 if (oldDrawnMouseY
!= mouseY
) {
1895 for (int i
= oldDrawnMouseY
; ;) {
1896 getScreen().unsetImageRow(i
);
1900 if (oldDrawnMouseY
< mouseY
) {
1907 getScreen().unsetImageRow(mouseY
);
1910 invertCell(mouseX
, mouseY
);
1911 oldDrawnMouseX
= mouseX
;
1912 oldDrawnMouseY
= mouseY
;
1914 // Place the cursor if it is visible
1915 if (!menuIsActive
) {
1916 TWidget activeWidget
= null;
1917 if (sorted
.size() > 0) {
1918 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
1919 if (activeWidget
.isCursorVisible()) {
1920 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
1921 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
1923 getScreen().putCursor(true,
1924 activeWidget
.getCursorAbsoluteX(),
1925 activeWidget
.getCursorAbsoluteY());
1928 // Turn off the cursor. Also place it at 0,0.
1929 getScreen().putCursor(false, 0, 0);
1938 getScreen().hideCursor();
1941 if (getScreen().isDirty()) {
1942 screenHandler
.setDirty();
1948 * Force this application to exit.
1950 public void exit() {
1952 synchronized (this) {
1958 * Subclasses can use this hook to cleanup resources. Called as the last
1959 * step of TApplication.run().
1961 public void onExit() {
1962 // Default does nothing.
1965 // ------------------------------------------------------------------------
1966 // TWindow management -----------------------------------------------------
1967 // ------------------------------------------------------------------------
1970 * Return the total number of windows.
1972 * @return the total number of windows
1974 public final int windowCount() {
1975 return windows
.size();
1979 * Return the number of windows that are showing.
1981 * @return the number of windows that are showing on screen
1983 public final int shownWindowCount() {
1985 for (TWindow w
: windows
) {
1994 * Return the number of windows that are hidden.
1996 * @return the number of windows that are hidden
1998 public final int hiddenWindowCount() {
2000 for (TWindow w
: windows
) {
2009 * Check if a window instance is in this application's window list.
2011 * @param window window to look for
2012 * @return true if this window is in the list
2014 public final boolean hasWindow(final TWindow window
) {
2015 if (windows
.size() == 0) {
2018 for (TWindow w
: windows
) {
2020 assert (window
.getApplication() == this);
2028 * Activate a window: bring it to the top and have it receive events.
2030 * @param window the window to become the new active window
2032 public void activateWindow(final TWindow window
) {
2033 if (hasWindow(window
) == false) {
2035 * Someone has a handle to a window I don't have. Ignore this
2041 // Whatever window might be moving/dragging, stop it now.
2042 for (TWindow w
: windows
) {
2043 if (w
.inMovements()) {
2048 assert (windows
.size() > 0);
2050 if (window
.isHidden()) {
2051 // Unhiding will also activate.
2055 assert (window
.isShown());
2057 if (windows
.size() == 1) {
2058 assert (window
== windows
.get(0));
2059 if (activeWindow
== null) {
2060 activeWindow
= window
;
2062 activeWindow
.setActive(true);
2063 activeWindow
.onFocus();
2066 assert (window
.isActive());
2067 assert (activeWindow
== window
);
2071 if (activeWindow
== window
) {
2072 assert (window
.isActive());
2074 // Window is already active, do nothing.
2078 assert (!window
.isActive());
2079 if (activeWindow
!= null) {
2080 // TODO: see if this assertion is really necessary.
2081 // assert (activeWindow.getZ() == 0);
2083 activeWindow
.setActive(false);
2085 // Increment every window Z that is on top of window
2086 for (TWindow w
: windows
) {
2090 if (w
.getZ() < window
.getZ()) {
2091 w
.setZ(w
.getZ() + 1);
2095 // Unset activeWindow now before unfocus, so that a window
2096 // lifecycle change inside onUnfocus() doesn't call
2097 // switchWindow() and lead to a stack overflow.
2098 TWindow oldActiveWindow
= activeWindow
;
2099 activeWindow
= null;
2100 oldActiveWindow
.onUnfocus();
2102 activeWindow
= window
;
2103 activeWindow
.setZ(0);
2104 activeWindow
.setActive(true);
2105 activeWindow
.onFocus();
2112 * @param window the window to hide
2114 public void hideWindow(final TWindow window
) {
2115 if (hasWindow(window
) == false) {
2117 * Someone has a handle to a window I don't have. Ignore this
2123 // Whatever window might be moving/dragging, stop it now.
2124 for (TWindow w
: windows
) {
2125 if (w
.inMovements()) {
2130 assert (windows
.size() > 0);
2132 if (!window
.hidden
) {
2133 if (window
== activeWindow
) {
2134 if (shownWindowCount() > 1) {
2137 activeWindow
= null;
2138 window
.setActive(false);
2142 window
.hidden
= true;
2150 * @param window the window to show
2152 public void showWindow(final TWindow window
) {
2153 if (hasWindow(window
) == false) {
2155 * Someone has a handle to a window I don't have. Ignore this
2161 // Whatever window might be moving/dragging, stop it now.
2162 for (TWindow w
: windows
) {
2163 if (w
.inMovements()) {
2168 assert (windows
.size() > 0);
2170 if (window
.hidden
) {
2171 window
.hidden
= false;
2173 activateWindow(window
);
2178 * Close window. Note that the window's destructor is NOT called by this
2179 * method, instead the GC is assumed to do the cleanup.
2181 * @param window the window to remove
2183 public final void closeWindow(final TWindow window
) {
2184 if (hasWindow(window
) == false) {
2186 * Someone has a handle to a window I don't have. Ignore this
2192 // Let window know that it is about to be closed, while it is still
2193 // visible on screen.
2194 window
.onPreClose();
2196 synchronized (windows
) {
2197 // Whatever window might be moving/dragging, stop it now.
2198 for (TWindow w
: windows
) {
2199 if (w
.inMovements()) {
2204 int z
= window
.getZ();
2207 windows
.remove(window
);
2208 Collections
.sort(windows
);
2209 activeWindow
= null;
2211 boolean foundNextWindow
= false;
2213 for (TWindow w
: windows
) {
2217 // Do not activate a hidden window.
2222 if (foundNextWindow
== false) {
2223 foundNextWindow
= true;
2226 assert (activeWindow
== null);
2238 // Perform window cleanup
2241 // Check if we are closing a TMessageBox or similar
2242 if (secondaryEventReceiver
!= null) {
2243 assert (secondaryEventHandler
!= null);
2245 // Do not send events to the secondaryEventReceiver anymore, the
2246 // window is closed.
2247 secondaryEventReceiver
= null;
2249 // Wake the secondary thread, it will wake the primary as it
2251 synchronized (secondaryEventHandler
) {
2252 secondaryEventHandler
.notify();
2256 // Permit desktop to be active if it is the only thing left.
2257 if (desktop
!= null) {
2258 if (windows
.size() == 0) {
2259 desktop
.setActive(true);
2265 * Switch to the next window.
2267 * @param forward if true, then switch to the next window in the list,
2268 * otherwise switch to the previous window in the list
2270 public final void switchWindow(final boolean forward
) {
2271 // Only switch if there are multiple visible windows
2272 if (shownWindowCount() < 2) {
2275 assert (activeWindow
!= null);
2277 synchronized (windows
) {
2278 // Whatever window might be moving/dragging, stop it now.
2279 for (TWindow w
: windows
) {
2280 if (w
.inMovements()) {
2285 // Swap z/active between active window and the next in the list
2286 int activeWindowI
= -1;
2287 for (int i
= 0; i
< windows
.size(); i
++) {
2288 if (windows
.get(i
) == activeWindow
) {
2289 assert (activeWindow
.isActive());
2293 assert (!windows
.get(0).isActive());
2296 assert (activeWindowI
>= 0);
2298 // Do not switch if a window is modal
2299 if (activeWindow
.isModal()) {
2303 int nextWindowI
= activeWindowI
;
2307 nextWindowI
%= windows
.size();
2310 if (nextWindowI
< 0) {
2311 nextWindowI
= windows
.size() - 1;
2315 if (windows
.get(nextWindowI
).isShown()) {
2316 activateWindow(windows
.get(nextWindowI
));
2320 } // synchronized (windows)
2325 * Add a window to my window list and make it active. Note package
2328 * @param window new window to add
2330 final void addWindowToApplication(final TWindow window
) {
2332 // Do not add menu windows to the window list.
2333 if (window
instanceof TMenu
) {
2337 // Do not add the desktop to the window list.
2338 if (window
instanceof TDesktop
) {
2342 synchronized (windows
) {
2343 if (windows
.contains(window
)) {
2344 throw new IllegalArgumentException("Window " + window
+
2345 " is already in window list");
2348 // Whatever window might be moving/dragging, stop it now.
2349 for (TWindow w
: windows
) {
2350 if (w
.inMovements()) {
2355 // Do not allow a modal window to spawn a non-modal window. If a
2356 // modal window is active, then this window will become modal
2358 if (modalWindowActive()) {
2359 window
.flags
|= TWindow
.MODAL
;
2360 window
.flags
|= TWindow
.CENTERED
;
2361 window
.hidden
= false;
2363 if (window
.isShown()) {
2364 for (TWindow w
: windows
) {
2369 w
.setZ(w
.getZ() + 1);
2372 windows
.add(window
);
2373 if (window
.isShown()) {
2374 activeWindow
= window
;
2375 activeWindow
.setZ(0);
2376 activeWindow
.setActive(true);
2377 activeWindow
.onFocus();
2380 if (((window
.flags
& TWindow
.CENTERED
) == 0)
2381 && ((window
.flags
& TWindow
.ABSOLUTEXY
) == 0)
2382 && (smartWindowPlacement
== true)
2385 doSmartPlacement(window
);
2389 // Desktop cannot be active over any other window.
2390 if (desktop
!= null) {
2391 desktop
.setActive(false);
2396 * Check if there is a system-modal window on top.
2398 * @return true if the active window is modal
2400 private boolean modalWindowActive() {
2401 if (windows
.size() == 0) {
2405 for (TWindow w
: windows
) {
2415 * Check if there is a window with overridden menu flag on top.
2417 * @return true if the active window is overriding the menu
2419 private boolean overrideMenuWindowActive() {
2420 if (activeWindow
!= null) {
2421 if (activeWindow
.hasOverriddenMenu()) {
2430 * Close all open windows.
2432 private void closeAllWindows() {
2433 // Don't do anything if we are in the menu
2434 if (activeMenu
!= null) {
2437 while (windows
.size() > 0) {
2438 closeWindow(windows
.get(0));
2443 * Re-layout the open windows as non-overlapping tiles. This produces
2444 * almost the same results as Turbo Pascal 7.0's IDE.
2446 private void tileWindows() {
2447 synchronized (windows
) {
2448 // Don't do anything if we are in the menu
2449 if (activeMenu
!= null) {
2452 int z
= windows
.size();
2458 a
= (int)(Math
.sqrt(z
));
2462 if (((a
* b
) + c
) == z
) {
2470 int newWidth
= (getScreen().getWidth() / a
);
2471 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
2472 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
2474 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2475 Collections
.sort(sorted
);
2476 Collections
.reverse(sorted
);
2477 for (int i
= 0; i
< sorted
.size(); i
++) {
2478 int logicalX
= i
/ b
;
2479 int logicalY
= i
% b
;
2480 if (i
>= ((a
- 1) * b
)) {
2482 logicalY
= i
- ((a
- 1) * b
);
2485 TWindow w
= sorted
.get(i
);
2486 int oldWidth
= w
.getWidth();
2487 int oldHeight
= w
.getHeight();
2489 w
.setX(logicalX
* newWidth
);
2490 w
.setWidth(newWidth
);
2491 if (i
>= ((a
- 1) * b
)) {
2492 w
.setY((logicalY
* newHeight2
) + 1);
2493 w
.setHeight(newHeight2
);
2495 w
.setY((logicalY
* newHeight1
) + 1);
2496 w
.setHeight(newHeight1
);
2498 if ((w
.getWidth() != oldWidth
)
2499 || (w
.getHeight() != oldHeight
)
2501 w
.onResize(new TResizeEvent(TResizeEvent
.Type
.WIDGET
,
2502 w
.getWidth(), w
.getHeight()));
2509 * Re-layout the open windows as overlapping cascaded windows.
2511 private void cascadeWindows() {
2512 synchronized (windows
) {
2513 // Don't do anything if we are in the menu
2514 if (activeMenu
!= null) {
2519 List
<TWindow
> sorted
= new ArrayList
<TWindow
>(windows
);
2520 Collections
.sort(sorted
);
2521 Collections
.reverse(sorted
);
2522 for (TWindow window
: sorted
) {
2527 if (x
> getScreen().getWidth()) {
2530 if (y
>= getScreen().getHeight()) {
2538 * Place a window to minimize its overlap with other windows.
2540 * @param window the window to place
2542 public final void doSmartPlacement(final TWindow window
) {
2543 // This is a pretty dumb algorithm, but seems to work. The hardest
2544 // part is computing these "overlap" values seeking a minimum average
2547 int yMin
= desktopTop
;
2548 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
2549 int yMax
= desktopBottom
- window
.getHeight() + 1;
2557 if ((xMin
== xMax
) && (yMin
== yMax
)) {
2558 // No work to do, bail out.
2562 // Compute the overlap matrix without the new window.
2563 int width
= getScreen().getWidth();
2564 int height
= getScreen().getHeight();
2565 int overlapMatrix
[][] = new int[width
][height
];
2566 for (TWindow w
: windows
) {
2570 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
2577 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
2584 overlapMatrix
[x
][y
]++;
2589 long oldOverlapTotal
= 0;
2590 long oldOverlapN
= 0;
2591 for (int x
= 0; x
< width
; x
++) {
2592 for (int y
= 0; y
< height
; y
++) {
2593 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2594 if (overlapMatrix
[x
][y
] > 0) {
2601 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2602 boolean first
= true;
2603 int windowX
= window
.getX();
2604 int windowY
= window
.getY();
2606 // For each possible (x, y) position for the new window, compute a
2607 // new overlap matrix.
2608 for (int x
= xMin
; x
< xMax
; x
++) {
2609 for (int y
= yMin
; y
< yMax
; y
++) {
2611 // Start with the matrix minus this window.
2612 int newMatrix
[][] = new int[width
][height
];
2613 for (int mx
= 0; mx
< width
; mx
++) {
2614 for (int my
= 0; my
< height
; my
++) {
2615 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2619 // Add this window's values to the new overlap matrix.
2620 long newOverlapTotal
= 0;
2621 long newOverlapN
= 0;
2622 // Start by adding each new cell.
2623 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2627 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2631 newMatrix
[wx
][wy
]++;
2634 // Now figure out the new value for total coverage.
2635 for (int mx
= 0; mx
< width
; mx
++) {
2636 for (int my
= 0; my
< height
; my
++) {
2637 newOverlapTotal
+= newMatrix
[x
][y
];
2638 if (newMatrix
[mx
][my
] > 0) {
2643 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2646 // First time: just record what we got.
2647 oldOverlapAvg
= newOverlapAvg
;
2650 // All other times: pick a new best (x, y) and save the
2652 if (newOverlapAvg
< oldOverlapAvg
) {
2655 oldOverlapAvg
= newOverlapAvg
;
2659 } // for (int x = xMin; x < xMax; x++)
2661 } // for (int y = yMin; y < yMax; y++)
2663 // Finally, set the window's new coordinates.
2664 window
.setX(windowX
);
2665 window
.setY(windowY
);
2668 // ------------------------------------------------------------------------
2669 // TMenu management -------------------------------------------------------
2670 // ------------------------------------------------------------------------
2673 * Check if a mouse event would hit either the active menu or any open
2676 * @param mouse mouse event
2677 * @return true if the mouse would hit the active menu or an open
2680 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2681 assert (activeMenu
!= null);
2682 List
<TMenu
> menus
= new ArrayList
<TMenu
>(subMenus
);
2683 Collections
.reverse(menus
);
2684 for (TMenu menu
: menus
) {
2685 if (menu
.mouseWouldHit(mouse
)) {
2689 return activeMenu
.mouseWouldHit(mouse
);
2693 * See if we need to switch window or activate the menu based on
2696 * @param mouse mouse event
2698 private void checkSwitchFocus(final TMouseEvent mouse
) {
2700 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2701 && (activeMenu
!= null)
2702 && (mouse
.getAbsoluteY() != 0)
2703 && (!mouseOnMenu(mouse
))
2705 // They clicked outside the active menu, turn it off
2706 activeMenu
.setActive(false);
2708 for (TMenu menu
: subMenus
) {
2709 menu
.setActive(false);
2715 // See if they hit the menu bar
2716 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2717 && (mouse
.isMouse1())
2718 && (!modalWindowActive())
2719 && (!overrideMenuWindowActive())
2720 && (mouse
.getAbsoluteY() == 0)
2723 for (TMenu menu
: subMenus
) {
2724 menu
.setActive(false);
2728 // They selected the menu, go activate it
2729 for (TMenu menu
: menus
) {
2730 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2731 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2732 + menu
.getTitle().length() + 2)
2734 menu
.setActive(true);
2737 menu
.setActive(false);
2743 // See if they hit the menu bar
2744 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2745 && (mouse
.isMouse1())
2746 && (activeMenu
!= null)
2747 && (mouse
.getAbsoluteY() == 0)
2750 TMenu oldMenu
= activeMenu
;
2751 for (TMenu menu
: subMenus
) {
2752 menu
.setActive(false);
2756 // See if we should switch menus
2757 for (TMenu menu
: menus
) {
2758 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2759 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2760 + menu
.getTitle().length() + 2)
2762 menu
.setActive(true);
2766 if (oldMenu
!= activeMenu
) {
2767 // They switched menus
2768 oldMenu
.setActive(false);
2773 // If a menu is still active, don't switch windows
2774 if (activeMenu
!= null) {
2778 // Only switch if there are multiple windows
2779 if (windows
.size() < 2) {
2783 if (((focusFollowsMouse
== true)
2784 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2785 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2787 synchronized (windows
) {
2788 Collections
.sort(windows
);
2789 if (windows
.get(0).isModal()) {
2790 // Modal windows don't switch
2794 for (TWindow window
: windows
) {
2795 assert (!window
.isModal());
2797 if (window
.isHidden()) {
2798 assert (!window
.isActive());
2802 if (window
.mouseWouldHit(mouse
)) {
2803 if (window
== windows
.get(0)) {
2804 // Clicked on the same window, nothing to do
2805 assert (window
.isActive());
2809 // We will be switching to another window
2810 assert (windows
.get(0).isActive());
2811 assert (windows
.get(0) == activeWindow
);
2812 assert (!window
.isActive());
2813 if (activeWindow
!= null) {
2814 activeWindow
.onUnfocus();
2815 activeWindow
.setActive(false);
2816 activeWindow
.setZ(window
.getZ());
2818 activeWindow
= window
;
2820 window
.setActive(true);
2827 // Clicked on the background, nothing to do
2831 // Nothing to do: this isn't a mouse up, or focus isn't following
2837 * Turn off the menu.
2839 public final void closeMenu() {
2840 if (activeMenu
!= null) {
2841 activeMenu
.setActive(false);
2843 for (TMenu menu
: subMenus
) {
2844 menu
.setActive(false);
2851 * Get a (shallow) copy of the menu list.
2853 * @return a copy of the menu list
2855 public final List
<TMenu
> getAllMenus() {
2856 return new ArrayList
<TMenu
>(menus
);
2860 * Add a top-level menu to the list.
2862 * @param menu the menu to add
2863 * @throws IllegalArgumentException if the menu is already used in
2864 * another TApplication
2866 public final void addMenu(final TMenu menu
) {
2867 if ((menu
.getApplication() != null)
2868 && (menu
.getApplication() != this)
2870 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2871 "part of application " + menu
.getApplication());
2879 * Remove a top-level menu from the list.
2881 * @param menu the menu to remove
2882 * @throws IllegalArgumentException if the menu is already used in
2883 * another TApplication
2885 public final void removeMenu(final TMenu menu
) {
2886 if ((menu
.getApplication() != null)
2887 && (menu
.getApplication() != this)
2889 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2890 "part of application " + menu
.getApplication());
2898 * Turn off a sub-menu.
2900 public final void closeSubMenu() {
2901 assert (activeMenu
!= null);
2902 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2903 assert (item
!= null);
2904 item
.setActive(false);
2905 subMenus
.remove(subMenus
.size() - 1);
2909 * Switch to the next menu.
2911 * @param forward if true, then switch to the next menu in the list,
2912 * otherwise switch to the previous menu in the list
2914 public final void switchMenu(final boolean forward
) {
2915 assert (activeMenu
!= null);
2917 for (TMenu menu
: subMenus
) {
2918 menu
.setActive(false);
2922 for (int i
= 0; i
< menus
.size(); i
++) {
2923 if (activeMenu
== menus
.get(i
)) {
2925 if (i
< menus
.size() - 1) {
2934 i
= menus
.size() - 1;
2937 activeMenu
.setActive(false);
2938 activeMenu
= menus
.get(i
);
2939 activeMenu
.setActive(true);
2946 * Add a menu item to the global list. If it has a keyboard accelerator,
2947 * that will be added the global hash.
2949 * @param item the menu item
2951 public final void addMenuItem(final TMenuItem item
) {
2952 menuItems
.add(item
);
2954 TKeypress key
= item
.getKey();
2956 synchronized (accelerators
) {
2957 assert (accelerators
.get(key
) == null);
2958 accelerators
.put(key
.toLowerCase(), item
);
2964 * Disable one menu item.
2966 * @param id the menu item ID
2968 public final void disableMenuItem(final int id
) {
2969 for (TMenuItem item
: menuItems
) {
2970 if (item
.getId() == id
) {
2971 item
.setEnabled(false);
2977 * Disable the range of menu items with ID's between lower and upper,
2980 * @param lower the lowest menu item ID
2981 * @param upper the highest menu item ID
2983 public final void disableMenuItems(final int lower
, final int upper
) {
2984 for (TMenuItem item
: menuItems
) {
2985 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2986 item
.setEnabled(false);
2987 item
.getParent().activate(0);
2993 * Enable one menu item.
2995 * @param id the menu item ID
2997 public final void enableMenuItem(final int id
) {
2998 for (TMenuItem item
: menuItems
) {
2999 if (item
.getId() == id
) {
3000 item
.setEnabled(true);
3001 item
.getParent().activate(0);
3007 * Enable the range of menu items with ID's between lower and upper,
3010 * @param lower the lowest menu item ID
3011 * @param upper the highest menu item ID
3013 public final void enableMenuItems(final int lower
, final int upper
) {
3014 for (TMenuItem item
: menuItems
) {
3015 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
3016 item
.setEnabled(true);
3017 item
.getParent().activate(0);
3023 * Get the menu item associated with this ID.
3025 * @param id the menu item ID
3026 * @return the menu item, or null if not found
3028 public final TMenuItem
getMenuItem(final int id
) {
3029 for (TMenuItem item
: menuItems
) {
3030 if (item
.getId() == id
) {
3038 * Recompute menu x positions based on their title length.
3040 public final void recomputeMenuX() {
3042 for (TMenu menu
: menus
) {
3045 x
+= menu
.getTitle().length() + 2;
3047 // Don't let the menu window exceed the screen width
3048 int rightEdge
= menu
.getX() + menu
.getWidth();
3049 if (rightEdge
> getScreen().getWidth()) {
3050 menu
.setX(getScreen().getWidth() - menu
.getWidth());
3056 * Post an event to process.
3058 * @param event new event to add to the queue
3060 public final void postEvent(final TInputEvent event
) {
3061 synchronized (this) {
3062 synchronized (fillEventQueue
) {
3063 fillEventQueue
.add(event
);
3066 System
.err
.println(System
.currentTimeMillis() + " " +
3067 Thread
.currentThread() + " postEvent() wake up main");
3074 * Post an event to process and turn off the menu.
3076 * @param event new event to add to the queue
3078 public final void postMenuEvent(final TInputEvent event
) {
3079 synchronized (this) {
3080 synchronized (fillEventQueue
) {
3081 fillEventQueue
.add(event
);
3084 System
.err
.println(System
.currentTimeMillis() + " " +
3085 Thread
.currentThread() + " postMenuEvent() wake up main");
3093 * Add a sub-menu to the list of open sub-menus.
3095 * @param menu sub-menu
3097 public final void addSubMenu(final TMenu menu
) {
3102 * Convenience function to add a top-level menu.
3104 * @param title menu title
3105 * @return the new menu
3107 public final TMenu
addMenu(final String title
) {
3110 TMenu menu
= new TMenu(this, x
, y
, title
);
3117 * Convenience function to add a default tools (hamburger) menu.
3119 * @return the new menu
3121 public final TMenu
addToolMenu() {
3122 TMenu toolMenu
= addMenu(i18n
.getString("toolMenuTitle"));
3123 toolMenu
.addDefaultItem(TMenu
.MID_REPAINT
);
3124 toolMenu
.addDefaultItem(TMenu
.MID_VIEW_IMAGE
);
3125 toolMenu
.addDefaultItem(TMenu
.MID_CHANGE_FONT
);
3126 TStatusBar toolStatusBar
= toolMenu
.newStatusBar(i18n
.
3127 getString("toolMenuStatus"));
3128 toolStatusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3133 * Convenience function to add a default "File" menu.
3135 * @return the new menu
3137 public final TMenu
addFileMenu() {
3138 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
3139 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
3140 fileMenu
.addSeparator();
3141 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
3142 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
3143 getString("fileMenuStatus"));
3144 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3149 * Convenience function to add a default "Edit" menu.
3151 * @return the new menu
3153 public final TMenu
addEditMenu() {
3154 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
3155 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
3156 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
3157 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
3158 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
3159 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
3160 getString("editMenuStatus"));
3161 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3166 * Convenience function to add a default "Window" menu.
3168 * @return the new menu
3170 public final TMenu
addWindowMenu() {
3171 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
3172 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
3173 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
3174 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
3175 windowMenu
.addSeparator();
3176 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
3177 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
3178 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
3179 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
3180 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
3181 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
3182 getString("windowMenuStatus"));
3183 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3188 * Convenience function to add a default "Help" menu.
3190 * @return the new menu
3192 public final TMenu
addHelpMenu() {
3193 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
3194 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
3195 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
3196 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
3197 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
3198 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
3199 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
3200 helpMenu
.addSeparator();
3201 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
3202 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
3203 getString("helpMenuStatus"));
3204 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3209 * Convenience function to add a default "Table" menu.
3211 * @return the new menu
3213 public final TMenu
addTableMenu() {
3214 TMenu tableMenu
= addMenu(i18n
.getString("tableMenuTitle"));
3215 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_COLUMN
, false);
3216 tableMenu
.addDefaultItem(TMenu
.MID_TABLE_RENAME_ROW
, false);
3217 tableMenu
.addSeparator();
3219 TSubMenu viewMenu
= tableMenu
.addSubMenu(i18n
.
3220 getString("tableSubMenuView"));
3221 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_ROW_LABELS
, false);
3222 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_COLUMN_LABELS
, false);
3223 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_ROW
, false);
3224 viewMenu
.addDefaultItem(TMenu
.MID_TABLE_VIEW_HIGHLIGHT_COLUMN
, false);
3226 TSubMenu borderMenu
= tableMenu
.addSubMenu(i18n
.
3227 getString("tableSubMenuBorders"));
3228 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_NONE
, false);
3229 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_ALL
, false);
3230 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_NONE
, false);
3231 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_CELL_ALL
, false);
3232 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_RIGHT
, false);
3233 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_LEFT
, false);
3234 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_TOP
, false);
3235 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_BOTTOM
, false);
3236 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_DOUBLE_BOTTOM
, false);
3237 borderMenu
.addDefaultItem(TMenu
.MID_TABLE_BORDER_THICK_BOTTOM
, false);
3238 TSubMenu deleteMenu
= tableMenu
.addSubMenu(i18n
.
3239 getString("tableSubMenuDelete"));
3240 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_LEFT
, false);
3241 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_UP
, false);
3242 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_ROW
, false);
3243 deleteMenu
.addDefaultItem(TMenu
.MID_TABLE_DELETE_COLUMN
, false);
3244 TSubMenu insertMenu
= tableMenu
.addSubMenu(i18n
.
3245 getString("tableSubMenuInsert"));
3246 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_LEFT
, false);
3247 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_RIGHT
, false);
3248 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_ABOVE
, false);
3249 insertMenu
.addDefaultItem(TMenu
.MID_TABLE_INSERT_BELOW
, false);
3250 TSubMenu columnMenu
= tableMenu
.addSubMenu(i18n
.
3251 getString("tableSubMenuColumn"));
3252 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_NARROW
, false);
3253 columnMenu
.addDefaultItem(TMenu
.MID_TABLE_COLUMN_WIDEN
, false);
3254 TSubMenu fileMenu
= tableMenu
.addSubMenu(i18n
.
3255 getString("tableSubMenuFile"));
3256 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_OPEN_CSV
, false);
3257 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_CSV
, false);
3258 fileMenu
.addDefaultItem(TMenu
.MID_TABLE_FILE_SAVE_TEXT
, false);
3260 TStatusBar statusBar
= tableMenu
.newStatusBar(i18n
.
3261 getString("tableMenuStatus"));
3262 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
3266 // ------------------------------------------------------------------------
3267 // TTimer management ------------------------------------------------------
3268 // ------------------------------------------------------------------------
3271 * Get the amount of time I can sleep before missing a Timer tick.
3273 * @param timeout = initial (maximum) timeout in millis
3274 * @return number of milliseconds between now and the next timer event
3276 private long getSleepTime(final long timeout
) {
3277 Date now
= new Date();
3278 long nowTime
= now
.getTime();
3279 long sleepTime
= timeout
;
3281 synchronized (timers
) {
3282 for (TTimer timer
: timers
) {
3283 long nextTickTime
= timer
.getNextTick().getTime();
3284 if (nextTickTime
< nowTime
) {
3288 long timeDifference
= nextTickTime
- nowTime
;
3289 if (timeDifference
< sleepTime
) {
3290 sleepTime
= timeDifference
;
3295 assert (sleepTime
>= 0);
3296 assert (sleepTime
<= timeout
);
3301 * Convenience function to add a timer.
3303 * @param duration number of milliseconds to wait between ticks
3304 * @param recurring if true, re-schedule this timer after every tick
3305 * @param action function to call when button is pressed
3308 public final TTimer
addTimer(final long duration
, final boolean recurring
,
3309 final TAction action
) {
3311 TTimer timer
= new TTimer(duration
, recurring
, action
);
3312 synchronized (timers
) {
3319 * Convenience function to remove a timer.
3321 * @param timer timer to remove
3323 public final void removeTimer(final TTimer timer
) {
3324 synchronized (timers
) {
3325 timers
.remove(timer
);
3329 // ------------------------------------------------------------------------
3330 // Other TWindow constructors ---------------------------------------------
3331 // ------------------------------------------------------------------------
3334 * Convenience function to spawn a message box.
3336 * @param title window title, will be centered along the top border
3337 * @param caption message to display. Use embedded newlines to get a
3339 * @return the new message box
3341 public final TMessageBox
messageBox(final String title
,
3342 final String caption
) {
3344 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
3348 * Convenience function to spawn a message box.
3350 * @param title window title, will be centered along the top border
3351 * @param caption message to display. Use embedded newlines to get a
3353 * @param type one of the TMessageBox.Type constants. Default is
3355 * @return the new message box
3357 public final TMessageBox
messageBox(final String title
,
3358 final String caption
, final TMessageBox
.Type type
) {
3360 return new TMessageBox(this, title
, caption
, type
);
3364 * Convenience function to spawn an input box.
3366 * @param title window title, will be centered along the top border
3367 * @param caption message to display. Use embedded newlines to get a
3369 * @return the new input box
3371 public final TInputBox
inputBox(final String title
, final String caption
) {
3373 return new TInputBox(this, title
, caption
);
3377 * Convenience function to spawn an input box.
3379 * @param title window title, will be centered along the top border
3380 * @param caption message to display. Use embedded newlines to get a
3382 * @param text initial text to seed the field with
3383 * @return the new input box
3385 public final TInputBox
inputBox(final String title
, final String caption
,
3386 final String text
) {
3388 return new TInputBox(this, title
, caption
, text
);
3392 * Convenience function to spawn an input box.
3394 * @param title window title, will be centered along the top border
3395 * @param caption message to display. Use embedded newlines to get a
3397 * @param text initial text to seed the field with
3398 * @param type one of the Type constants. Default is Type.OK.
3399 * @return the new input box
3401 public final TInputBox
inputBox(final String title
, final String caption
,
3402 final String text
, final TInputBox
.Type type
) {
3404 return new TInputBox(this, title
, caption
, text
, type
);
3408 * Convenience function to open a terminal window.
3410 * @param x column relative to parent
3411 * @param y row relative to parent
3412 * @return the terminal new window
3414 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
3415 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
3419 * Convenience function to open a terminal window.
3421 * @param x column relative to parent
3422 * @param y row relative to parent
3423 * @param closeOnExit if true, close the window when the command exits
3424 * @return the terminal new window
3426 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3427 final boolean closeOnExit
) {
3429 return openTerminal(x
, y
, TWindow
.RESIZABLE
, closeOnExit
);
3433 * Convenience function to open a terminal window.
3435 * @param x column relative to parent
3436 * @param y row relative to parent
3437 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3438 * @return the terminal new window
3440 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3443 return new TTerminalWindow(this, x
, y
, flags
);
3447 * Convenience function to open a terminal window.
3449 * @param x column relative to parent
3450 * @param y row relative to parent
3451 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3452 * @param closeOnExit if true, close the window when the command exits
3453 * @return the terminal new window
3455 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3456 final int flags
, final boolean closeOnExit
) {
3458 return new TTerminalWindow(this, x
, y
, flags
, closeOnExit
);
3462 * Convenience function to open a terminal window and execute a custom
3463 * command line inside it.
3465 * @param x column relative to parent
3466 * @param y row relative to parent
3467 * @param commandLine the command line to execute
3468 * @return the terminal new window
3470 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3471 final String commandLine
) {
3473 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
3477 * Convenience function to open a terminal window and execute a custom
3478 * command line inside it.
3480 * @param x column relative to parent
3481 * @param y row relative to parent
3482 * @param commandLine the command line to execute
3483 * @param closeOnExit if true, close the window when the command exits
3484 * @return the terminal new window
3486 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3487 final String commandLine
, final boolean closeOnExit
) {
3489 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
, closeOnExit
);
3493 * Convenience function to open a terminal window and execute a custom
3494 * command line inside it.
3496 * @param x column relative to parent
3497 * @param y row relative to parent
3498 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3499 * @param command the command line to execute
3500 * @return the terminal new window
3502 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3503 final int flags
, final String
[] command
) {
3505 return new TTerminalWindow(this, x
, y
, flags
, command
);
3509 * Convenience function to open a terminal window and execute a custom
3510 * command line inside it.
3512 * @param x column relative to parent
3513 * @param y row relative to parent
3514 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3515 * @param command the command line to execute
3516 * @param closeOnExit if true, close the window when the command exits
3517 * @return the terminal new window
3519 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3520 final int flags
, final String
[] command
, final boolean closeOnExit
) {
3522 return new TTerminalWindow(this, x
, y
, flags
, command
, closeOnExit
);
3526 * Convenience function to open a terminal window and execute a custom
3527 * command line inside it.
3529 * @param x column relative to parent
3530 * @param y row relative to parent
3531 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3532 * @param commandLine the command line to execute
3533 * @return the terminal new window
3535 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3536 final int flags
, final String commandLine
) {
3538 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"));
3542 * Convenience function to open a terminal window and execute a custom
3543 * command line inside it.
3545 * @param x column relative to parent
3546 * @param y row relative to parent
3547 * @param flags mask of CENTERED, MODAL, or RESIZABLE
3548 * @param commandLine the command line to execute
3549 * @param closeOnExit if true, close the window when the command exits
3550 * @return the terminal new window
3552 public final TTerminalWindow
openTerminal(final int x
, final int y
,
3553 final int flags
, final String commandLine
, final boolean closeOnExit
) {
3555 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s+"),
3560 * Convenience function to spawn an file open box.
3562 * @param path path of selected file
3563 * @return the result of the new file open box
3564 * @throws IOException if java.io operation throws
3566 public final String
fileOpenBox(final String path
) throws IOException
{
3568 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
3569 return box
.getFilename();
3573 * Convenience function to spawn an file open box.
3575 * @param path path of selected file
3576 * @param type one of the Type constants
3577 * @return the result of the new file open box
3578 * @throws IOException if java.io operation throws
3580 public final String
fileOpenBox(final String path
,
3581 final TFileOpenBox
.Type type
) throws IOException
{
3583 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
3584 return box
.getFilename();
3588 * Convenience function to spawn a file open box.
3590 * @param path path of selected file
3591 * @param type one of the Type constants
3592 * @param filter a string that files must match to be displayed
3593 * @return the result of the new file open box
3594 * @throws IOException of a java.io operation throws
3596 public final String
fileOpenBox(final String path
,
3597 final TFileOpenBox
.Type type
, final String filter
) throws IOException
{
3599 ArrayList
<String
> filters
= new ArrayList
<String
>();
3600 filters
.add(filter
);
3602 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3603 return box
.getFilename();
3607 * Convenience function to spawn a file open box.
3609 * @param path path of selected file
3610 * @param type one of the Type constants
3611 * @param filters a list of strings that files must match to be displayed
3612 * @return the result of the new file open box
3613 * @throws IOException of a java.io operation throws
3615 public final String
fileOpenBox(final String path
,
3616 final TFileOpenBox
.Type type
,
3617 final List
<String
> filters
) throws IOException
{
3619 TFileOpenBox box
= new TFileOpenBox(this, path
, type
, filters
);
3620 return box
.getFilename();
3624 * Convenience function to create a new window and make it active.
3625 * Window will be located at (0, 0).
3627 * @param title window title, will be centered along the top border
3628 * @param width width of window
3629 * @param height height of window
3630 * @return the new window
3632 public final TWindow
addWindow(final String title
, final int width
,
3635 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
3640 * Convenience function to create a new window and make it active.
3641 * Window will be located at (0, 0).
3643 * @param title window title, will be centered along the top border
3644 * @param width width of window
3645 * @param height height of window
3646 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
3647 * @return the new window
3649 public final TWindow
addWindow(final String title
,
3650 final int width
, final int height
, final int flags
) {
3652 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
3657 * Convenience function to create a new window and make it active.
3659 * @param title window title, will be centered along the top border
3660 * @param x column relative to parent
3661 * @param y row relative to parent
3662 * @param width width of window
3663 * @param height height of window
3664 * @return the new window
3666 public final TWindow
addWindow(final String title
,
3667 final int x
, final int y
, final int width
, final int height
) {
3669 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
3674 * Convenience function to create a new window and make it active.
3676 * @param title window title, will be centered along the top border
3677 * @param x column relative to parent
3678 * @param y row relative to parent
3679 * @param width width of window
3680 * @param height height of window
3681 * @param flags mask of RESIZABLE, CENTERED, or MODAL
3682 * @return the new window
3684 public final TWindow
addWindow(final String title
,
3685 final int x
, final int y
, final int width
, final int height
,
3688 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);