2 * Jexer - Java Text User Interface
4 * The MIT License (MIT)
6 * Copyright (C) 2017 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
.Collections
;
40 import java
.util
.Date
;
41 import java
.util
.HashMap
;
42 import java
.util
.ArrayList
;
43 import java
.util
.LinkedList
;
44 import java
.util
.List
;
46 import java
.util
.ResourceBundle
;
48 import jexer
.bits
.CellAttributes
;
49 import jexer
.bits
.ColorTheme
;
50 import jexer
.event
.TCommandEvent
;
51 import jexer
.event
.TInputEvent
;
52 import jexer
.event
.TKeypressEvent
;
53 import jexer
.event
.TMenuEvent
;
54 import jexer
.event
.TMouseEvent
;
55 import jexer
.event
.TResizeEvent
;
56 import jexer
.backend
.Backend
;
57 import jexer
.backend
.Screen
;
58 import jexer
.backend
.MultiBackend
;
59 import jexer
.backend
.SwingBackend
;
60 import jexer
.backend
.ECMA48Backend
;
61 import jexer
.backend
.TWindowBackend
;
62 import jexer
.menu
.TMenu
;
63 import jexer
.menu
.TMenuItem
;
64 import static jexer
.TCommand
.*;
65 import static jexer
.TKeypress
.*;
68 * TApplication is the main driver class for a full Text User Interface
69 * application. It manages windows, provides a menu bar and status bar, and
70 * processes events received from the user.
72 public class TApplication
implements Runnable
{
77 private static final ResourceBundle i18n
= ResourceBundle
.getBundle(TApplication
.class.getName());
79 // ------------------------------------------------------------------------
80 // Public constants -------------------------------------------------------
81 // ------------------------------------------------------------------------
84 * If true, emit thread stuff to System.err.
86 private static final boolean debugThreads
= false;
89 * If true, emit events being processed to System.err.
91 private static final boolean debugEvents
= false;
94 * If true, do "smart placement" on new windows that are not specified to
97 private static final boolean smartWindowPlacement
= true;
100 * Two backend types are available.
102 public static enum BackendType
{
109 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
114 * Synonym for ECMA48.
119 // ------------------------------------------------------------------------
120 // Primary/secondary event handlers ---------------------------------------
121 // ------------------------------------------------------------------------
124 * WidgetEventHandler is the main event consumer loop. There are at most
125 * two such threads in existence: the primary for normal case and a
126 * secondary that is used for TMessageBox, TInputBox, and similar.
128 private class WidgetEventHandler
implements Runnable
{
130 * The main application.
132 private TApplication application
;
135 * Whether or not this WidgetEventHandler is the primary or secondary
138 private boolean primary
= true;
141 * Public constructor.
143 * @param application the main application
144 * @param primary if true, this is the primary event handler thread
146 public WidgetEventHandler(final TApplication application
,
147 final boolean primary
) {
149 this.application
= application
;
150 this.primary
= primary
;
157 boolean first
= true;
160 while (!application
.quit
) {
162 // Wait until application notifies me
163 while (!application
.quit
) {
165 synchronized (application
.drainEventQueue
) {
166 if (application
.drainEventQueue
.size() > 0) {
175 timeout
= application
.getSleepTime(1000);
179 // A timer needs to fire, break out.
184 System
.err
.printf("%d %s %s sleep %d millis\n",
185 System
.currentTimeMillis(), this,
186 primary ?
"primary" : "secondary", timeout
);
189 synchronized (this) {
194 System
.err
.printf("%d %s %s AWAKE\n",
195 System
.currentTimeMillis(), this,
196 primary ?
"primary" : "secondary");
200 && (application
.secondaryEventReceiver
== null)
202 // Secondary thread, emergency exit. If we got
203 // here then something went wrong with the
204 // handoff between yield() and closeWindow().
205 synchronized (application
.primaryEventHandler
) {
206 application
.primaryEventHandler
.notify();
208 application
.secondaryEventHandler
= null;
209 throw new RuntimeException("secondary exited " +
213 } catch (InterruptedException e
) {
216 } // while (!application.quit)
218 // Pull all events off the queue
220 TInputEvent event
= null;
221 synchronized (application
.drainEventQueue
) {
222 if (application
.drainEventQueue
.size() == 0) {
225 event
= application
.drainEventQueue
.remove(0);
228 // We will have an event to process, so repaint the
229 // screen at the end.
230 application
.repaint
= true;
233 primaryHandleEvent(event
);
235 secondaryHandleEvent(event
);
238 && (application
.secondaryEventReceiver
== null)
240 // Secondary thread, time to exit.
242 // DO NOT UNLOCK. Primary thread just came back from
243 // primaryHandleEvent() and will unlock in the else
244 // block below. Just wake it up.
245 synchronized (application
.primaryEventHandler
) {
246 application
.primaryEventHandler
.notify();
248 // Now eliminate my reference so that
249 // wakeEventHandler() resumes working on the primary.
250 application
.secondaryEventHandler
= null;
258 // Fire timers, update screen.
260 application
.finishEventProcessing();
263 } // while (true) (main runnable loop)
268 * The primary event handler thread.
270 private volatile WidgetEventHandler primaryEventHandler
;
273 * The secondary event handler thread.
275 private volatile WidgetEventHandler secondaryEventHandler
;
278 * The widget receiving events from the secondary event handler thread.
280 private volatile TWidget secondaryEventReceiver
;
283 * Wake the sleeping active event handler.
285 private void wakeEventHandler() {
290 if (secondaryEventHandler
!= null) {
291 synchronized (secondaryEventHandler
) {
292 secondaryEventHandler
.notify();
295 assert (primaryEventHandler
!= null);
296 synchronized (primaryEventHandler
) {
297 primaryEventHandler
.notify();
302 // ------------------------------------------------------------------------
303 // TApplication attributes ------------------------------------------------
304 // ------------------------------------------------------------------------
307 * Access to the physical screen, keyboard, and mouse.
309 private Backend backend
;
314 * @return the Backend
316 public final Backend
getBackend() {
325 public final Screen
getScreen() {
326 if (backend
instanceof TWindowBackend
) {
327 // We are being rendered to a TWindow. We can't use its
328 // getScreen() method because that is how it is rendering to a
329 // hardware backend somewhere. Instead use its getOtherScreen()
331 return ((TWindowBackend
) backend
).getOtherScreen();
333 return backend
.getScreen();
338 * Actual mouse coordinate X.
343 * Actual mouse coordinate Y.
348 * Old version of mouse coordinate X.
350 private int oldMouseX
;
353 * Old version mouse coordinate Y.
355 private int oldMouseY
;
358 * The last mouse up click time, used to determine if this is a mouse
361 private long lastMouseUpTime
;
364 * The amount of millis between mouse up events to assume a double-click.
366 private long doubleClickTime
= 250;
369 * Event queue that is filled by run().
371 private List
<TInputEvent
> fillEventQueue
;
374 * Event queue that will be drained by either primary or secondary
377 private List
<TInputEvent
> drainEventQueue
;
380 * Top-level menus in this application.
382 private List
<TMenu
> menus
;
385 * Stack of activated sub-menus in this application.
387 private List
<TMenu
> subMenus
;
390 * The currently active menu.
392 private TMenu activeMenu
= null;
395 * Active keyboard accelerators.
397 private Map
<TKeypress
, TMenuItem
> accelerators
;
402 private List
<TMenuItem
> menuItems
;
405 * Windows and widgets pull colors from this ColorTheme.
407 private ColorTheme theme
;
410 * Get the color theme.
414 public final ColorTheme
getTheme() {
419 * The top-level windows (but not menus).
421 private List
<TWindow
> windows
;
424 * The currently acive window.
426 private TWindow activeWindow
= null;
429 * Timers that are being ticked.
431 private List
<TTimer
> timers
;
434 * When true, the application has been started.
436 private volatile boolean started
= false;
439 * When true, exit the application.
441 private volatile boolean quit
= false;
444 * When true, repaint the entire screen.
446 private volatile boolean repaint
= true;
449 * Repaint the screen on the next update.
451 public void doRepaint() {
457 * Y coordinate of the top edge of the desktop. For now this is a
458 * constant. Someday it would be nice to have a multi-line menu or
461 private static final int desktopTop
= 1;
464 * Get Y coordinate of the top edge of the desktop.
466 * @return Y coordinate of the top edge of the desktop
468 public final int getDesktopTop() {
473 * Y coordinate of the bottom edge of the desktop.
475 private int desktopBottom
;
478 * Get Y coordinate of the bottom edge of the desktop.
480 * @return Y coordinate of the bottom edge of the desktop
482 public final int getDesktopBottom() {
483 return desktopBottom
;
487 * An optional TDesktop background window that is drawn underneath
490 private TDesktop desktop
;
493 * Set the TDesktop instance.
495 * @param desktop a TDesktop instance, or null to remove the one that is
498 public final void setDesktop(final TDesktop desktop
) {
499 if (this.desktop
!= null) {
500 this.desktop
.onClose();
502 this.desktop
= desktop
;
506 * Get the TDesktop instance.
508 * @return the desktop, or null if it is not set
510 public final TDesktop
getDesktop() {
515 * Get the current active window.
517 * @return the active window, or null if it is not set
519 public final TWindow
getActiveWindow() {
524 * Get a (shallow) copy of the window list.
526 * @return a copy of the list of windows for this application
528 public final List
<TWindow
> getAllWindows() {
529 List
<TWindow
> result
= new LinkedList
<TWindow
>();
530 result
.addAll(windows
);
535 * If true, focus follows mouse: windows automatically raised if the
536 * mouse passes over them.
538 private boolean focusFollowsMouse
= false;
541 * Get focusFollowsMouse flag.
543 * @return true if focus follows mouse: windows automatically raised if
544 * the mouse passes over them
546 public boolean getFocusFollowsMouse() {
547 return focusFollowsMouse
;
551 * Set focusFollowsMouse flag.
553 * @param focusFollowsMouse if true, focus follows mouse: windows
554 * automatically raised if the mouse passes over them
556 public void setFocusFollowsMouse(final boolean focusFollowsMouse
) {
557 this.focusFollowsMouse
= focusFollowsMouse
;
560 // ------------------------------------------------------------------------
561 // General behavior -------------------------------------------------------
562 // ------------------------------------------------------------------------
565 * Display the about dialog.
567 protected void showAboutDialog() {
568 messageBox(i18n
.getString("aboutDialogTitle"),
569 MessageFormat
.format(i18n
.getString("aboutDialogText"),
570 this.getClass().getPackage().getImplementationVersion()),
571 TMessageBox
.Type
.OK
);
574 // ------------------------------------------------------------------------
575 // Constructors -----------------------------------------------------------
576 // ------------------------------------------------------------------------
579 * Public constructor.
581 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
583 * @param windowWidth the number of text columns to start with
584 * @param windowHeight the number of text rows to start with
585 * @param fontSize the size in points
586 * @throws UnsupportedEncodingException if an exception is thrown when
587 * creating the InputStreamReader
589 public TApplication(final BackendType backendType
, final int windowWidth
,
590 final int windowHeight
, final int fontSize
)
591 throws UnsupportedEncodingException
{
593 switch (backendType
) {
595 backend
= new SwingBackend(this, windowWidth
, windowHeight
,
601 backend
= new ECMA48Backend(this, null, null, windowWidth
,
602 windowHeight
, fontSize
);
605 throw new IllegalArgumentException("Invalid backend type: "
612 * Public constructor.
614 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
616 * @throws UnsupportedEncodingException if an exception is thrown when
617 * creating the InputStreamReader
619 public TApplication(final BackendType backendType
)
620 throws UnsupportedEncodingException
{
622 switch (backendType
) {
624 // The default SwingBackend is 80x25, 20 pt font. If you want to
625 // change that, you can pass the extra arguments to the
626 // SwingBackend constructor here. For example, if you wanted
627 // 90x30, 16 pt font:
629 // backend = new SwingBackend(this, 90, 30, 16);
630 backend
= new SwingBackend(this);
635 backend
= new ECMA48Backend(this, null, null);
638 throw new IllegalArgumentException("Invalid backend type: "
645 * Public constructor. The backend type will be BackendType.ECMA48.
647 * @param input an InputStream connected to the remote user, or null for
648 * System.in. If System.in is used, then on non-Windows systems it will
649 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
650 * mode. input is always converted to a Reader with UTF-8 encoding.
651 * @param output an OutputStream connected to the remote user, or null
652 * for System.out. output is always converted to a Writer with UTF-8
654 * @throws UnsupportedEncodingException if an exception is thrown when
655 * creating the InputStreamReader
657 public TApplication(final InputStream input
,
658 final OutputStream output
) throws UnsupportedEncodingException
{
660 backend
= new ECMA48Backend(this, input
, output
);
665 * Public constructor. The backend type will be BackendType.ECMA48.
667 * @param input the InputStream underlying 'reader'. Its available()
668 * method is used to determine if reader.read() will block or not.
669 * @param reader a Reader connected to the remote user.
670 * @param writer a PrintWriter connected to the remote user.
671 * @param setRawMode if true, set System.in into raw mode with stty.
672 * This should in general not be used. It is here solely for Demo3,
673 * which uses System.in.
674 * @throws IllegalArgumentException if input, reader, or writer are null.
676 public TApplication(final InputStream input
, final Reader reader
,
677 final PrintWriter writer
, final boolean setRawMode
) {
679 backend
= new ECMA48Backend(this, input
, reader
, writer
, setRawMode
);
684 * Public constructor. The backend type will be BackendType.ECMA48.
686 * @param input the InputStream underlying 'reader'. Its available()
687 * method is used to determine if reader.read() will block or not.
688 * @param reader a Reader connected to the remote user.
689 * @param writer a PrintWriter connected to the remote user.
690 * @throws IllegalArgumentException if input, reader, or writer are null.
692 public TApplication(final InputStream input
, final Reader reader
,
693 final PrintWriter writer
) {
695 this(input
, reader
, writer
, false);
699 * Public constructor. This hook enables use with new non-Jexer
702 * @param backend a Backend that is already ready to go.
704 public TApplication(final Backend backend
) {
705 this.backend
= backend
;
706 backend
.setListener(this);
711 * Finish construction once the backend is set.
713 private void TApplicationImpl() {
714 theme
= new ColorTheme();
715 desktopBottom
= getScreen().getHeight() - 1;
716 fillEventQueue
= new ArrayList
<TInputEvent
>();
717 drainEventQueue
= new ArrayList
<TInputEvent
>();
718 windows
= new LinkedList
<TWindow
>();
719 menus
= new LinkedList
<TMenu
>();
720 subMenus
= new LinkedList
<TMenu
>();
721 timers
= new LinkedList
<TTimer
>();
722 accelerators
= new HashMap
<TKeypress
, TMenuItem
>();
723 menuItems
= new ArrayList
<TMenuItem
>();
724 desktop
= new TDesktop(this);
726 // Special case: the Swing backend needs to have a timer to drive its
728 if ((backend
instanceof SwingBackend
)
729 || (backend
instanceof MultiBackend
)
731 // Default to 500 millis, unless a SwingBackend has its own
734 if (backend
instanceof SwingBackend
) {
735 millis
= ((SwingBackend
) backend
).getBlinkMillis();
738 addTimer(millis
, true,
741 TApplication
.this.doRepaint();
749 // ------------------------------------------------------------------------
750 // Screen refresh loop ----------------------------------------------------
751 // ------------------------------------------------------------------------
754 * Process background events, and update the screen.
756 private void finishEventProcessing() {
758 System
.err
.printf(System
.currentTimeMillis() + " " +
759 Thread
.currentThread() + " finishEventProcessing()\n");
762 // Process timers and call doIdle()'s
766 synchronized (getScreen()) {
771 System
.err
.printf(System
.currentTimeMillis() + " " +
772 Thread
.currentThread() + " finishEventProcessing() END\n");
777 * Invert the cell color at a position. This is used to track the mouse.
779 * @param x column position
780 * @param y row position
782 private void invertCell(final int x
, final int y
) {
784 System
.err
.printf("%d %s invertCell() %d %d\n",
785 System
.currentTimeMillis(), Thread
.currentThread(), x
, y
);
787 CellAttributes attr
= getScreen().getAttrXY(x
, y
);
788 attr
.setForeColor(attr
.getForeColor().invert());
789 attr
.setBackColor(attr
.getBackColor().invert());
790 getScreen().putAttrXY(x
, y
, attr
, false);
796 private void drawAll() {
797 boolean menuIsActive
= false;
800 System
.err
.printf("%d %s drawAll() enter\n",
801 System
.currentTimeMillis(), Thread
.currentThread());
806 System
.err
.printf("%d %s drawAll() !repaint\n",
807 System
.currentTimeMillis(), Thread
.currentThread());
809 synchronized (getScreen()) {
810 if ((oldMouseX
!= mouseX
) || (oldMouseY
!= mouseY
)) {
811 // The only thing that has happened is the mouse moved.
812 // Clear the old position and draw the new position.
813 invertCell(oldMouseX
, oldMouseY
);
814 invertCell(mouseX
, mouseY
);
818 if (getScreen().isDirty()) {
819 backend
.flushScreen();
826 System
.err
.printf("%d %s drawAll() REDRAW\n",
827 System
.currentTimeMillis(), Thread
.currentThread());
830 // If true, the cursor is not visible
831 boolean cursor
= false;
833 // Start with a clean screen
837 if (desktop
!= null) {
838 desktop
.drawChildren();
841 // Draw each window in reverse Z order
842 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
843 Collections
.sort(sorted
);
844 TWindow topLevel
= null;
845 if (sorted
.size() > 0) {
846 topLevel
= sorted
.get(0);
848 Collections
.reverse(sorted
);
849 for (TWindow window
: sorted
) {
850 if (window
.isShown()) {
851 window
.drawChildren();
855 // Draw the blank menubar line - reset the screen clipping first so
856 // it won't trim it out.
857 getScreen().resetClipping();
858 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
859 theme
.getColor("tmenu"));
860 // Now draw the menus.
862 for (TMenu menu
: menus
) {
863 CellAttributes menuColor
;
864 CellAttributes menuMnemonicColor
;
865 if (menu
.isActive()) {
867 menuColor
= theme
.getColor("tmenu.highlighted");
868 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic.highlighted");
871 menuColor
= theme
.getColor("tmenu");
872 menuMnemonicColor
= theme
.getColor("tmenu.mnemonic");
874 // Draw the menu title
875 getScreen().hLineXY(x
, 0, menu
.getTitle().length() + 2, ' ',
877 getScreen().putStringXY(x
+ 1, 0, menu
.getTitle(), menuColor
);
878 // Draw the highlight character
879 getScreen().putCharXY(x
+ 1 + menu
.getMnemonic().getShortcutIdx(),
880 0, menu
.getMnemonic().getShortcut(), menuMnemonicColor
);
882 if (menu
.isActive()) {
884 // Reset the screen clipping so we can draw the next title.
885 getScreen().resetClipping();
887 x
+= menu
.getTitle().length() + 2;
890 for (TMenu menu
: subMenus
) {
891 // Reset the screen clipping so we can draw the next sub-menu.
892 getScreen().resetClipping();
896 // Draw the status bar of the top-level window
897 TStatusBar statusBar
= null;
898 if (topLevel
!= null) {
899 statusBar
= topLevel
.getStatusBar();
901 if (statusBar
!= null) {
902 getScreen().resetClipping();
903 statusBar
.setWidth(getScreen().getWidth());
904 statusBar
.setY(getScreen().getHeight() - topLevel
.getY());
907 CellAttributes barColor
= new CellAttributes();
908 barColor
.setTo(getTheme().getColor("tstatusbar.text"));
909 getScreen().hLineXY(0, desktopBottom
, getScreen().getWidth(), ' ',
913 // Draw the mouse pointer
914 invertCell(mouseX
, mouseY
);
918 // Place the cursor if it is visible
920 TWidget activeWidget
= null;
921 if (sorted
.size() > 0) {
922 activeWidget
= sorted
.get(sorted
.size() - 1).getActiveChild();
923 if (activeWidget
.isCursorVisible()) {
924 if ((activeWidget
.getCursorAbsoluteY() < desktopBottom
)
925 && (activeWidget
.getCursorAbsoluteY() > desktopTop
)
927 getScreen().putCursor(true,
928 activeWidget
.getCursorAbsoluteX(),
929 activeWidget
.getCursorAbsoluteY());
932 getScreen().putCursor(false,
933 activeWidget
.getCursorAbsoluteX(),
934 activeWidget
.getCursorAbsoluteY());
943 getScreen().hideCursor();
946 // Flush the screen contents
947 if (getScreen().isDirty()) {
948 backend
.flushScreen();
954 // ------------------------------------------------------------------------
955 // Main loop --------------------------------------------------------------
956 // ------------------------------------------------------------------------
959 * Force this application to exit.
963 synchronized (this) {
969 * Run this application until it exits.
972 // Start the main consumer thread
973 primaryEventHandler
= new WidgetEventHandler(this, true);
974 (new Thread(primaryEventHandler
)).start();
979 synchronized (this) {
980 boolean doWait
= false;
982 synchronized (fillEventQueue
) {
983 if (fillEventQueue
.size() == 0) {
989 // No I/O to dispatch, so wait until the backend
993 System
.err
.println(System
.currentTimeMillis() +
1000 System
.err
.println(System
.currentTimeMillis() +
1003 } catch (InterruptedException e
) {
1004 // I'm awake and don't care why, let's see what's
1005 // going on out there.
1009 } // synchronized (this)
1011 synchronized (fillEventQueue
) {
1012 // Pull any pending I/O events
1013 backend
.getEvents(fillEventQueue
);
1015 // Dispatch each event to the appropriate handler, one at a
1018 TInputEvent event
= null;
1019 if (fillEventQueue
.size() == 0) {
1022 event
= fillEventQueue
.remove(0);
1023 metaHandleEvent(event
);
1027 // Wake a consumer thread if we have any pending events.
1028 if (drainEventQueue
.size() > 0) {
1034 // Shutdown the event consumer threads
1035 if (secondaryEventHandler
!= null) {
1036 synchronized (secondaryEventHandler
) {
1037 secondaryEventHandler
.notify();
1040 if (primaryEventHandler
!= null) {
1041 synchronized (primaryEventHandler
) {
1042 primaryEventHandler
.notify();
1046 // Shutdown the user I/O thread(s)
1049 // Close all the windows. This gives them an opportunity to release
1056 * Peek at certain application-level events, add to eventQueue, and wake
1057 * up the consuming Thread.
1059 * @param event the input event to consume
1061 private void metaHandleEvent(final TInputEvent event
) {
1064 System
.err
.printf(String
.format("metaHandleEvents event: %s\n",
1065 event
)); System
.err
.flush();
1069 // Do no more processing if the application is already trying
1074 // Special application-wide events -------------------------------
1077 if (event
instanceof TCommandEvent
) {
1078 TCommandEvent command
= (TCommandEvent
) event
;
1079 if (command
.getCmd().equals(cmAbort
)) {
1085 synchronized (drainEventQueue
) {
1087 if (event
instanceof TResizeEvent
) {
1088 TResizeEvent resize
= (TResizeEvent
) event
;
1089 synchronized (getScreen()) {
1090 getScreen().setDimensions(resize
.getWidth(),
1091 resize
.getHeight());
1092 desktopBottom
= getScreen().getHeight() - 1;
1098 if (desktop
!= null) {
1099 desktop
.setDimensions(0, 0, resize
.getWidth(),
1100 resize
.getHeight() - 1);
1103 // Change menu edges if needed.
1106 // We are dirty, redraw the screen.
1111 // Put into the main queue
1112 drainEventQueue
.add(event
);
1117 * Dispatch one event to the appropriate widget or application-level
1118 * event handler. This is the primary event handler, it has the normal
1119 * application-wide event handling.
1121 * @param event the input event to consume
1122 * @see #secondaryHandleEvent(TInputEvent event)
1124 private void primaryHandleEvent(final TInputEvent event
) {
1127 System
.err
.printf("Handle event: %s\n", event
);
1129 TMouseEvent doubleClick
= null;
1131 // Special application-wide events -----------------------------------
1133 // Peek at the mouse position
1134 if (event
instanceof TMouseEvent
) {
1135 TMouseEvent mouse
= (TMouseEvent
) event
;
1136 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1139 mouseX
= mouse
.getX();
1140 mouseY
= mouse
.getY();
1142 if (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
) {
1143 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1146 // This is a double-click.
1147 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1149 mouse
.getX(), mouse
.getY(),
1150 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1151 mouse
.isMouse1(), mouse
.isMouse2(),
1153 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1156 // The first click of a potential double-click.
1157 lastMouseUpTime
= mouse
.getTime().getTime();
1162 // See if we need to switch focus to another window or the menu
1163 checkSwitchFocus((TMouseEvent
) event
);
1166 // Handle menu events
1167 if ((activeMenu
!= null) && !(event
instanceof TCommandEvent
)) {
1168 TMenu menu
= activeMenu
;
1170 if (event
instanceof TMouseEvent
) {
1171 TMouseEvent mouse
= (TMouseEvent
) event
;
1173 while (subMenus
.size() > 0) {
1174 TMenu subMenu
= subMenus
.get(subMenus
.size() - 1);
1175 if (subMenu
.mouseWouldHit(mouse
)) {
1178 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
1179 && (!mouse
.isMouse1())
1180 && (!mouse
.isMouse2())
1181 && (!mouse
.isMouse3())
1182 && (!mouse
.isMouseWheelUp())
1183 && (!mouse
.isMouseWheelDown())
1187 // We navigated away from a sub-menu, so close it
1191 // Convert the mouse relative x/y to menu coordinates
1192 assert (mouse
.getX() == mouse
.getAbsoluteX());
1193 assert (mouse
.getY() == mouse
.getAbsoluteY());
1194 if (subMenus
.size() > 0) {
1195 menu
= subMenus
.get(subMenus
.size() - 1);
1197 mouse
.setX(mouse
.getX() - menu
.getX());
1198 mouse
.setY(mouse
.getY() - menu
.getY());
1200 menu
.handleEvent(event
);
1204 if (event
instanceof TKeypressEvent
) {
1205 TKeypressEvent keypress
= (TKeypressEvent
) event
;
1207 // See if this key matches an accelerator, and is not being
1208 // shortcutted by the active window, and if so dispatch the menu
1210 boolean windowWillShortcut
= false;
1211 if (activeWindow
!= null) {
1212 assert (activeWindow
.isShown());
1213 if (activeWindow
.isShortcutKeypress(keypress
.getKey())) {
1214 // We do not process this key, it will be passed to the
1216 windowWillShortcut
= true;
1220 if (!windowWillShortcut
&& !modalWindowActive()) {
1221 TKeypress keypressLowercase
= keypress
.getKey().toLowerCase();
1222 TMenuItem item
= null;
1223 synchronized (accelerators
) {
1224 item
= accelerators
.get(keypressLowercase
);
1227 if (item
.isEnabled()) {
1228 // Let the menu item dispatch
1234 // Handle the keypress
1235 if (onKeypress(keypress
)) {
1241 if (event
instanceof TCommandEvent
) {
1242 if (onCommand((TCommandEvent
) event
)) {
1247 if (event
instanceof TMenuEvent
) {
1248 if (onMenu((TMenuEvent
) event
)) {
1253 // Dispatch events to the active window -------------------------------
1254 boolean dispatchToDesktop
= true;
1255 TWindow window
= activeWindow
;
1256 if (window
!= null) {
1257 assert (window
.isActive());
1258 assert (window
.isShown());
1259 if (event
instanceof TMouseEvent
) {
1260 TMouseEvent mouse
= (TMouseEvent
) event
;
1261 // Convert the mouse relative x/y to window coordinates
1262 assert (mouse
.getX() == mouse
.getAbsoluteX());
1263 assert (mouse
.getY() == mouse
.getAbsoluteY());
1264 mouse
.setX(mouse
.getX() - window
.getX());
1265 mouse
.setY(mouse
.getY() - window
.getY());
1267 if (doubleClick
!= null) {
1268 doubleClick
.setX(doubleClick
.getX() - window
.getX());
1269 doubleClick
.setY(doubleClick
.getY() - window
.getY());
1272 if (window
.mouseWouldHit(mouse
)) {
1273 dispatchToDesktop
= false;
1275 } else if (event
instanceof TKeypressEvent
) {
1276 dispatchToDesktop
= false;
1280 System
.err
.printf("TApplication dispatch event: %s\n",
1283 window
.handleEvent(event
);
1284 if (doubleClick
!= null) {
1285 window
.handleEvent(doubleClick
);
1288 if (dispatchToDesktop
) {
1289 // This event is fair game for the desktop to process.
1290 if (desktop
!= null) {
1291 desktop
.handleEvent(event
);
1292 if (doubleClick
!= null) {
1293 desktop
.handleEvent(doubleClick
);
1300 * Dispatch one event to the appropriate widget or application-level
1301 * event handler. This is the secondary event handler used by certain
1302 * special dialogs (currently TMessageBox and TFileOpenBox).
1304 * @param event the input event to consume
1305 * @see #primaryHandleEvent(TInputEvent event)
1307 private void secondaryHandleEvent(final TInputEvent event
) {
1308 TMouseEvent doubleClick
= null;
1310 // Peek at the mouse position
1311 if (event
instanceof TMouseEvent
) {
1312 TMouseEvent mouse
= (TMouseEvent
) event
;
1313 if ((mouseX
!= mouse
.getX()) || (mouseY
!= mouse
.getY())) {
1316 mouseX
= mouse
.getX();
1317 mouseY
= mouse
.getY();
1319 if (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
) {
1320 if ((mouse
.getTime().getTime() - lastMouseUpTime
) <
1323 // This is a double-click.
1324 doubleClick
= new TMouseEvent(TMouseEvent
.Type
.
1326 mouse
.getX(), mouse
.getY(),
1327 mouse
.getAbsoluteX(), mouse
.getAbsoluteY(),
1328 mouse
.isMouse1(), mouse
.isMouse2(),
1330 mouse
.isMouseWheelUp(), mouse
.isMouseWheelDown());
1333 // The first click of a potential double-click.
1334 lastMouseUpTime
= mouse
.getTime().getTime();
1340 secondaryEventReceiver
.handleEvent(event
);
1341 if (doubleClick
!= null) {
1342 secondaryEventReceiver
.handleEvent(doubleClick
);
1347 * Enable a widget to override the primary event thread.
1349 * @param widget widget that will receive events
1351 public final void enableSecondaryEventReceiver(final TWidget widget
) {
1353 System
.err
.println(System
.currentTimeMillis() +
1354 " enableSecondaryEventReceiver()");
1357 assert (secondaryEventReceiver
== null);
1358 assert (secondaryEventHandler
== null);
1359 assert ((widget
instanceof TMessageBox
)
1360 || (widget
instanceof TFileOpenBox
));
1361 secondaryEventReceiver
= widget
;
1362 secondaryEventHandler
= new WidgetEventHandler(this, false);
1364 (new Thread(secondaryEventHandler
)).start();
1368 * Yield to the secondary thread.
1370 public final void yield() {
1371 assert (secondaryEventReceiver
!= null);
1373 while (secondaryEventReceiver
!= null) {
1374 synchronized (primaryEventHandler
) {
1376 primaryEventHandler
.wait();
1377 } catch (InterruptedException e
) {
1385 * Do stuff when there is no user input.
1387 private void doIdle() {
1389 System
.err
.printf(System
.currentTimeMillis() + " " +
1390 Thread
.currentThread() + " doIdle()\n");
1393 synchronized (timers
) {
1396 System
.err
.printf(System
.currentTimeMillis() + " " +
1397 Thread
.currentThread() + " doIdle() 2\n");
1400 // Run any timers that have timed out
1401 Date now
= new Date();
1402 List
<TTimer
> keepTimers
= new LinkedList
<TTimer
>();
1403 for (TTimer timer
: timers
) {
1404 if (timer
.getNextTick().getTime() <= now
.getTime()) {
1405 // Something might change, so repaint the screen.
1408 if (timer
.recurring
) {
1409 keepTimers
.add(timer
);
1412 keepTimers
.add(timer
);
1415 timers
= keepTimers
;
1419 for (TWindow window
: windows
) {
1422 if (desktop
!= null) {
1427 // ------------------------------------------------------------------------
1428 // TWindow management -----------------------------------------------------
1429 // ------------------------------------------------------------------------
1432 * Return the total number of windows.
1434 * @return the total number of windows
1436 public final int windowCount() {
1437 return windows
.size();
1441 * Return the number of windows that are showing.
1443 * @return the number of windows that are showing on screen
1445 public final int shownWindowCount() {
1447 for (TWindow w
: windows
) {
1456 * Return the number of windows that are hidden.
1458 * @return the number of windows that are hidden
1460 public final int hiddenWindowCount() {
1462 for (TWindow w
: windows
) {
1471 * Check if a window instance is in this application's window list.
1473 * @param window window to look for
1474 * @return true if this window is in the list
1476 public final boolean hasWindow(final TWindow window
) {
1477 if (windows
.size() == 0) {
1480 for (TWindow w
: windows
) {
1482 assert (window
.getApplication() == this);
1490 * Activate a window: bring it to the top and have it receive events.
1492 * @param window the window to become the new active window
1494 public void activateWindow(final TWindow window
) {
1495 if (hasWindow(window
) == false) {
1497 * Someone has a handle to a window I don't have. Ignore this
1503 // Whatever window might be moving/dragging, stop it now.
1504 for (TWindow w
: windows
) {
1505 if (w
.inMovements()) {
1510 assert (windows
.size() > 0);
1512 if (window
.isHidden()) {
1513 // Unhiding will also activate.
1517 assert (window
.isShown());
1519 if (windows
.size() == 1) {
1520 assert (window
== windows
.get(0));
1521 if (activeWindow
== null) {
1522 activeWindow
= window
;
1524 activeWindow
.setActive(true);
1525 activeWindow
.onFocus();
1528 assert (window
.isActive());
1529 assert (activeWindow
== window
);
1533 if (activeWindow
== window
) {
1534 assert (window
.isActive());
1536 // Window is already active, do nothing.
1540 assert (!window
.isActive());
1541 if (activeWindow
!= null) {
1542 assert (activeWindow
.getZ() == 0);
1544 activeWindow
.setActive(false);
1545 activeWindow
.setZ(window
.getZ());
1547 // Unset activeWindow now before unfocus, so that a window
1548 // lifecycle change inside onUnfocus() doesn't call
1549 // switchWindow() and lead to a stack overflow.
1550 TWindow oldActiveWindow
= activeWindow
;
1551 activeWindow
= null;
1552 oldActiveWindow
.onUnfocus();
1554 activeWindow
= window
;
1555 activeWindow
.setZ(0);
1556 activeWindow
.setActive(true);
1557 activeWindow
.onFocus();
1564 * @param window the window to hide
1566 public void hideWindow(final TWindow window
) {
1567 if (hasWindow(window
) == false) {
1569 * Someone has a handle to a window I don't have. Ignore this
1575 // Whatever window might be moving/dragging, stop it now.
1576 for (TWindow w
: windows
) {
1577 if (w
.inMovements()) {
1582 assert (windows
.size() > 0);
1584 if (!window
.hidden
) {
1585 if (window
== activeWindow
) {
1586 if (shownWindowCount() > 1) {
1589 activeWindow
= null;
1590 window
.setActive(false);
1594 window
.hidden
= true;
1602 * @param window the window to show
1604 public void showWindow(final TWindow window
) {
1605 if (hasWindow(window
) == false) {
1607 * Someone has a handle to a window I don't have. Ignore this
1613 // Whatever window might be moving/dragging, stop it now.
1614 for (TWindow w
: windows
) {
1615 if (w
.inMovements()) {
1620 assert (windows
.size() > 0);
1622 if (window
.hidden
) {
1623 window
.hidden
= false;
1625 activateWindow(window
);
1630 * Close window. Note that the window's destructor is NOT called by this
1631 * method, instead the GC is assumed to do the cleanup.
1633 * @param window the window to remove
1635 public final void closeWindow(final TWindow window
) {
1636 if (hasWindow(window
) == false) {
1638 * Someone has a handle to a window I don't have. Ignore this
1644 synchronized (windows
) {
1645 // Whatever window might be moving/dragging, stop it now.
1646 for (TWindow w
: windows
) {
1647 if (w
.inMovements()) {
1652 int z
= window
.getZ();
1655 Collections
.sort(windows
);
1657 activeWindow
= null;
1658 for (TWindow w
: windows
) {
1660 // Do not activate a hidden window.
1666 w
.setZ(w
.getZ() - 1);
1667 if (w
.getZ() == 0) {
1670 assert (activeWindow
== null);
1682 // Perform window cleanup
1685 // Check if we are closing a TMessageBox or similar
1686 if (secondaryEventReceiver
!= null) {
1687 assert (secondaryEventHandler
!= null);
1689 // Do not send events to the secondaryEventReceiver anymore, the
1690 // window is closed.
1691 secondaryEventReceiver
= null;
1693 // Wake the secondary thread, it will wake the primary as it
1695 synchronized (secondaryEventHandler
) {
1696 secondaryEventHandler
.notify();
1700 // Permit desktop to be active if it is the only thing left.
1701 if (desktop
!= null) {
1702 if (windows
.size() == 0) {
1703 desktop
.setActive(true);
1709 * Switch to the next window.
1711 * @param forward if true, then switch to the next window in the list,
1712 * otherwise switch to the previous window in the list
1714 public final void switchWindow(final boolean forward
) {
1715 // Only switch if there are multiple visible windows
1716 if (shownWindowCount() < 2) {
1719 assert (activeWindow
!= null);
1721 synchronized (windows
) {
1722 // Whatever window might be moving/dragging, stop it now.
1723 for (TWindow w
: windows
) {
1724 if (w
.inMovements()) {
1729 // Swap z/active between active window and the next in the list
1730 int activeWindowI
= -1;
1731 for (int i
= 0; i
< windows
.size(); i
++) {
1732 if (windows
.get(i
) == activeWindow
) {
1733 assert (activeWindow
.isActive());
1737 assert (!windows
.get(0).isActive());
1740 assert (activeWindowI
>= 0);
1742 // Do not switch if a window is modal
1743 if (activeWindow
.isModal()) {
1747 int nextWindowI
= activeWindowI
;
1751 nextWindowI
%= windows
.size();
1754 if (nextWindowI
< 0) {
1755 nextWindowI
= windows
.size() - 1;
1759 if (windows
.get(nextWindowI
).isShown()) {
1760 activateWindow(windows
.get(nextWindowI
));
1764 } // synchronized (windows)
1769 * Add a window to my window list and make it active.
1771 * @param window new window to add
1773 public final void addWindow(final TWindow window
) {
1775 // Do not add menu windows to the window list.
1776 if (window
instanceof TMenu
) {
1780 // Do not add the desktop to the window list.
1781 if (window
instanceof TDesktop
) {
1785 synchronized (windows
) {
1786 // Whatever window might be moving/dragging, stop it now.
1787 for (TWindow w
: windows
) {
1788 if (w
.inMovements()) {
1793 // Do not allow a modal window to spawn a non-modal window. If a
1794 // modal window is active, then this window will become modal
1796 if (modalWindowActive()) {
1797 window
.flags
|= TWindow
.MODAL
;
1798 window
.flags
|= TWindow
.CENTERED
;
1799 window
.hidden
= false;
1801 if (window
.isShown()) {
1802 for (TWindow w
: windows
) {
1807 w
.setZ(w
.getZ() + 1);
1810 windows
.add(window
);
1811 if (window
.isShown()) {
1812 activeWindow
= window
;
1813 activeWindow
.setZ(0);
1814 activeWindow
.setActive(true);
1815 activeWindow
.onFocus();
1818 if (((window
.flags
& TWindow
.CENTERED
) == 0)
1819 && smartWindowPlacement
) {
1821 doSmartPlacement(window
);
1825 // Desktop cannot be active over any other window.
1826 if (desktop
!= null) {
1827 desktop
.setActive(false);
1832 * Check if there is a system-modal window on top.
1834 * @return true if the active window is modal
1836 private boolean modalWindowActive() {
1837 if (windows
.size() == 0) {
1841 for (TWindow w
: windows
) {
1851 * Close all open windows.
1853 private void closeAllWindows() {
1854 // Don't do anything if we are in the menu
1855 if (activeMenu
!= null) {
1858 while (windows
.size() > 0) {
1859 closeWindow(windows
.get(0));
1864 * Re-layout the open windows as non-overlapping tiles. This produces
1865 * almost the same results as Turbo Pascal 7.0's IDE.
1867 private void tileWindows() {
1868 synchronized (windows
) {
1869 // Don't do anything if we are in the menu
1870 if (activeMenu
!= null) {
1873 int z
= windows
.size();
1879 a
= (int)(Math
.sqrt(z
));
1883 if (((a
* b
) + c
) == z
) {
1891 int newWidth
= (getScreen().getWidth() / a
);
1892 int newHeight1
= ((getScreen().getHeight() - 1) / b
);
1893 int newHeight2
= ((getScreen().getHeight() - 1) / (b
+ c
));
1895 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1896 Collections
.sort(sorted
);
1897 Collections
.reverse(sorted
);
1898 for (int i
= 0; i
< sorted
.size(); i
++) {
1899 int logicalX
= i
/ b
;
1900 int logicalY
= i
% b
;
1901 if (i
>= ((a
- 1) * b
)) {
1903 logicalY
= i
- ((a
- 1) * b
);
1906 TWindow w
= sorted
.get(i
);
1907 w
.setX(logicalX
* newWidth
);
1908 w
.setWidth(newWidth
);
1909 if (i
>= ((a
- 1) * b
)) {
1910 w
.setY((logicalY
* newHeight2
) + 1);
1911 w
.setHeight(newHeight2
);
1913 w
.setY((logicalY
* newHeight1
) + 1);
1914 w
.setHeight(newHeight1
);
1921 * Re-layout the open windows as overlapping cascaded windows.
1923 private void cascadeWindows() {
1924 synchronized (windows
) {
1925 // Don't do anything if we are in the menu
1926 if (activeMenu
!= null) {
1931 List
<TWindow
> sorted
= new LinkedList
<TWindow
>(windows
);
1932 Collections
.sort(sorted
);
1933 Collections
.reverse(sorted
);
1934 for (TWindow window
: sorted
) {
1939 if (x
> getScreen().getWidth()) {
1942 if (y
>= getScreen().getHeight()) {
1950 * Place a window to minimize its overlap with other windows.
1952 * @param window the window to place
1954 public final void doSmartPlacement(final TWindow window
) {
1955 // This is a pretty dumb algorithm, but seems to work. The hardest
1956 // part is computing these "overlap" values seeking a minimum average
1959 int yMin
= desktopTop
;
1960 int xMax
= getScreen().getWidth() - window
.getWidth() + 1;
1961 int yMax
= desktopBottom
- window
.getHeight() + 1;
1969 if ((xMin
== xMax
) && (yMin
== yMax
)) {
1970 // No work to do, bail out.
1974 // Compute the overlap matrix without the new window.
1975 int width
= getScreen().getWidth();
1976 int height
= getScreen().getHeight();
1977 int overlapMatrix
[][] = new int[width
][height
];
1978 for (TWindow w
: windows
) {
1982 for (int x
= w
.getX(); x
< w
.getX() + w
.getWidth(); x
++) {
1989 for (int y
= w
.getY(); y
< w
.getY() + w
.getHeight(); y
++) {
1996 overlapMatrix
[x
][y
]++;
2001 long oldOverlapTotal
= 0;
2002 long oldOverlapN
= 0;
2003 for (int x
= 0; x
< width
; x
++) {
2004 for (int y
= 0; y
< height
; y
++) {
2005 oldOverlapTotal
+= overlapMatrix
[x
][y
];
2006 if (overlapMatrix
[x
][y
] > 0) {
2013 double oldOverlapAvg
= (double) oldOverlapTotal
/ (double) oldOverlapN
;
2014 boolean first
= true;
2015 int windowX
= window
.getX();
2016 int windowY
= window
.getY();
2018 // For each possible (x, y) position for the new window, compute a
2019 // new overlap matrix.
2020 for (int x
= xMin
; x
< xMax
; x
++) {
2021 for (int y
= yMin
; y
< yMax
; y
++) {
2023 // Start with the matrix minus this window.
2024 int newMatrix
[][] = new int[width
][height
];
2025 for (int mx
= 0; mx
< width
; mx
++) {
2026 for (int my
= 0; my
< height
; my
++) {
2027 newMatrix
[mx
][my
] = overlapMatrix
[mx
][my
];
2031 // Add this window's values to the new overlap matrix.
2032 long newOverlapTotal
= 0;
2033 long newOverlapN
= 0;
2034 // Start by adding each new cell.
2035 for (int wx
= x
; wx
< x
+ window
.getWidth(); wx
++) {
2039 for (int wy
= y
; wy
< y
+ window
.getHeight(); wy
++) {
2043 newMatrix
[wx
][wy
]++;
2046 // Now figure out the new value for total coverage.
2047 for (int mx
= 0; mx
< width
; mx
++) {
2048 for (int my
= 0; my
< height
; my
++) {
2049 newOverlapTotal
+= newMatrix
[x
][y
];
2050 if (newMatrix
[mx
][my
] > 0) {
2055 double newOverlapAvg
= (double) newOverlapTotal
/ (double) newOverlapN
;
2058 // First time: just record what we got.
2059 oldOverlapAvg
= newOverlapAvg
;
2062 // All other times: pick a new best (x, y) and save the
2064 if (newOverlapAvg
< oldOverlapAvg
) {
2067 oldOverlapAvg
= newOverlapAvg
;
2071 } // for (int x = xMin; x < xMax; x++)
2073 } // for (int y = yMin; y < yMax; y++)
2075 // Finally, set the window's new coordinates.
2076 window
.setX(windowX
);
2077 window
.setY(windowY
);
2080 // ------------------------------------------------------------------------
2081 // TMenu management -------------------------------------------------------
2082 // ------------------------------------------------------------------------
2085 * Check if a mouse event would hit either the active menu or any open
2088 * @param mouse mouse event
2089 * @return true if the mouse would hit the active menu or an open
2092 private boolean mouseOnMenu(final TMouseEvent mouse
) {
2093 assert (activeMenu
!= null);
2094 List
<TMenu
> menus
= new LinkedList
<TMenu
>(subMenus
);
2095 Collections
.reverse(menus
);
2096 for (TMenu menu
: menus
) {
2097 if (menu
.mouseWouldHit(mouse
)) {
2101 return activeMenu
.mouseWouldHit(mouse
);
2105 * See if we need to switch window or activate the menu based on
2108 * @param mouse mouse event
2110 private void checkSwitchFocus(final TMouseEvent mouse
) {
2112 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2113 && (activeMenu
!= null)
2114 && (mouse
.getAbsoluteY() != 0)
2115 && (!mouseOnMenu(mouse
))
2117 // They clicked outside the active menu, turn it off
2118 activeMenu
.setActive(false);
2120 for (TMenu menu
: subMenus
) {
2121 menu
.setActive(false);
2127 // See if they hit the menu bar
2128 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_DOWN
)
2129 && (mouse
.isMouse1())
2130 && (!modalWindowActive())
2131 && (mouse
.getAbsoluteY() == 0)
2134 for (TMenu menu
: subMenus
) {
2135 menu
.setActive(false);
2139 // They selected the menu, go activate it
2140 for (TMenu menu
: menus
) {
2141 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2142 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2143 + menu
.getTitle().length() + 2)
2145 menu
.setActive(true);
2148 menu
.setActive(false);
2154 // See if they hit the menu bar
2155 if ((mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
)
2156 && (mouse
.isMouse1())
2157 && (activeMenu
!= null)
2158 && (mouse
.getAbsoluteY() == 0)
2161 TMenu oldMenu
= activeMenu
;
2162 for (TMenu menu
: subMenus
) {
2163 menu
.setActive(false);
2167 // See if we should switch menus
2168 for (TMenu menu
: menus
) {
2169 if ((mouse
.getAbsoluteX() >= menu
.getTitleX())
2170 && (mouse
.getAbsoluteX() < menu
.getTitleX()
2171 + menu
.getTitle().length() + 2)
2173 menu
.setActive(true);
2177 if (oldMenu
!= activeMenu
) {
2178 // They switched menus
2179 oldMenu
.setActive(false);
2184 // If a menu is still active, don't switch windows
2185 if (activeMenu
!= null) {
2189 // Only switch if there are multiple windows
2190 if (windows
.size() < 2) {
2194 if (((focusFollowsMouse
== true)
2195 && (mouse
.getType() == TMouseEvent
.Type
.MOUSE_MOTION
))
2196 || (mouse
.getType() == TMouseEvent
.Type
.MOUSE_UP
)
2198 synchronized (windows
) {
2199 Collections
.sort(windows
);
2200 if (windows
.get(0).isModal()) {
2201 // Modal windows don't switch
2205 for (TWindow window
: windows
) {
2206 assert (!window
.isModal());
2208 if (window
.isHidden()) {
2209 assert (!window
.isActive());
2213 if (window
.mouseWouldHit(mouse
)) {
2214 if (window
== windows
.get(0)) {
2215 // Clicked on the same window, nothing to do
2216 assert (window
.isActive());
2220 // We will be switching to another window
2221 assert (windows
.get(0).isActive());
2222 assert (windows
.get(0) == activeWindow
);
2223 assert (!window
.isActive());
2224 activeWindow
.onUnfocus();
2225 activeWindow
.setActive(false);
2226 activeWindow
.setZ(window
.getZ());
2227 activeWindow
= window
;
2229 window
.setActive(true);
2236 // Clicked on the background, nothing to do
2240 // Nothing to do: this isn't a mouse up, or focus isn't following
2246 * Turn off the menu.
2248 public final void closeMenu() {
2249 if (activeMenu
!= null) {
2250 activeMenu
.setActive(false);
2252 for (TMenu menu
: subMenus
) {
2253 menu
.setActive(false);
2260 * Get a (shallow) copy of the menu list.
2262 * @return a copy of the menu list
2264 public final List
<TMenu
> getAllMenus() {
2265 return new LinkedList
<TMenu
>(menus
);
2269 * Add a top-level menu to the list.
2271 * @param menu the menu to add
2272 * @throws IllegalArgumentException if the menu is already used in
2273 * another TApplication
2275 public final void addMenu(final TMenu menu
) {
2276 if ((menu
.getApplication() != null)
2277 && (menu
.getApplication() != this)
2279 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2280 "part of application " + menu
.getApplication());
2288 * Remove a top-level menu from the list.
2290 * @param menu the menu to remove
2291 * @throws IllegalArgumentException if the menu is already used in
2292 * another TApplication
2294 public final void removeMenu(final TMenu menu
) {
2295 if ((menu
.getApplication() != null)
2296 && (menu
.getApplication() != this)
2298 throw new IllegalArgumentException("Menu " + menu
+ " is already " +
2299 "part of application " + menu
.getApplication());
2307 * Turn off a sub-menu.
2309 public final void closeSubMenu() {
2310 assert (activeMenu
!= null);
2311 TMenu item
= subMenus
.get(subMenus
.size() - 1);
2312 assert (item
!= null);
2313 item
.setActive(false);
2314 subMenus
.remove(subMenus
.size() - 1);
2318 * Switch to the next menu.
2320 * @param forward if true, then switch to the next menu in the list,
2321 * otherwise switch to the previous menu in the list
2323 public final void switchMenu(final boolean forward
) {
2324 assert (activeMenu
!= null);
2326 for (TMenu menu
: subMenus
) {
2327 menu
.setActive(false);
2331 for (int i
= 0; i
< menus
.size(); i
++) {
2332 if (activeMenu
== menus
.get(i
)) {
2334 if (i
< menus
.size() - 1) {
2342 activeMenu
.setActive(false);
2343 activeMenu
= menus
.get(i
);
2344 activeMenu
.setActive(true);
2351 * Add a menu item to the global list. If it has a keyboard accelerator,
2352 * that will be added the global hash.
2354 * @param item the menu item
2356 public final void addMenuItem(final TMenuItem item
) {
2357 menuItems
.add(item
);
2359 TKeypress key
= item
.getKey();
2361 synchronized (accelerators
) {
2362 assert (accelerators
.get(key
) == null);
2363 accelerators
.put(key
.toLowerCase(), item
);
2369 * Disable one menu item.
2371 * @param id the menu item ID
2373 public final void disableMenuItem(final int id
) {
2374 for (TMenuItem item
: menuItems
) {
2375 if (item
.getId() == id
) {
2376 item
.setEnabled(false);
2382 * Disable the range of menu items with ID's between lower and upper,
2385 * @param lower the lowest menu item ID
2386 * @param upper the highest menu item ID
2388 public final void disableMenuItems(final int lower
, final int upper
) {
2389 for (TMenuItem item
: menuItems
) {
2390 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2391 item
.setEnabled(false);
2397 * Enable one menu item.
2399 * @param id the menu item ID
2401 public final void enableMenuItem(final int id
) {
2402 for (TMenuItem item
: menuItems
) {
2403 if (item
.getId() == id
) {
2404 item
.setEnabled(true);
2410 * Enable the range of menu items with ID's between lower and upper,
2413 * @param lower the lowest menu item ID
2414 * @param upper the highest menu item ID
2416 public final void enableMenuItems(final int lower
, final int upper
) {
2417 for (TMenuItem item
: menuItems
) {
2418 if ((item
.getId() >= lower
) && (item
.getId() <= upper
)) {
2419 item
.setEnabled(true);
2425 * Recompute menu x positions based on their title length.
2427 public final void recomputeMenuX() {
2429 for (TMenu menu
: menus
) {
2432 x
+= menu
.getTitle().length() + 2;
2434 // Don't let the menu window exceed the screen width
2435 int rightEdge
= menu
.getX() + menu
.getWidth();
2436 if (rightEdge
> getScreen().getWidth()) {
2437 menu
.setX(getScreen().getWidth() - menu
.getWidth());
2443 * Post an event to process.
2445 * @param event new event to add to the queue
2447 public final void postEvent(final TInputEvent event
) {
2448 synchronized (this) {
2449 synchronized (fillEventQueue
) {
2450 fillEventQueue
.add(event
);
2453 System
.err
.println(System
.currentTimeMillis() + " " +
2454 Thread
.currentThread() + " postEvent() wake up main");
2461 * Post an event to process and turn off the menu.
2463 * @param event new event to add to the queue
2465 public final void postMenuEvent(final TInputEvent event
) {
2466 synchronized (this) {
2467 synchronized (fillEventQueue
) {
2468 fillEventQueue
.add(event
);
2471 System
.err
.println(System
.currentTimeMillis() + " " +
2472 Thread
.currentThread() + " postMenuEvent() wake up main");
2480 * Add a sub-menu to the list of open sub-menus.
2482 * @param menu sub-menu
2484 public final void addSubMenu(final TMenu menu
) {
2489 * Convenience function to add a top-level menu.
2491 * @param title menu title
2492 * @return the new menu
2494 public final TMenu
addMenu(final String title
) {
2497 TMenu menu
= new TMenu(this, x
, y
, title
);
2504 * Convenience function to add a default "File" menu.
2506 * @return the new menu
2508 public final TMenu
addFileMenu() {
2509 TMenu fileMenu
= addMenu(i18n
.getString("fileMenuTitle"));
2510 fileMenu
.addDefaultItem(TMenu
.MID_OPEN_FILE
);
2511 fileMenu
.addSeparator();
2512 fileMenu
.addDefaultItem(TMenu
.MID_SHELL
);
2513 fileMenu
.addDefaultItem(TMenu
.MID_EXIT
);
2514 TStatusBar statusBar
= fileMenu
.newStatusBar(i18n
.
2515 getString("fileMenuStatus"));
2516 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2521 * Convenience function to add a default "Edit" menu.
2523 * @return the new menu
2525 public final TMenu
addEditMenu() {
2526 TMenu editMenu
= addMenu(i18n
.getString("editMenuTitle"));
2527 editMenu
.addDefaultItem(TMenu
.MID_CUT
);
2528 editMenu
.addDefaultItem(TMenu
.MID_COPY
);
2529 editMenu
.addDefaultItem(TMenu
.MID_PASTE
);
2530 editMenu
.addDefaultItem(TMenu
.MID_CLEAR
);
2531 TStatusBar statusBar
= editMenu
.newStatusBar(i18n
.
2532 getString("editMenuStatus"));
2533 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2538 * Convenience function to add a default "Window" menu.
2540 * @return the new menu
2542 public final TMenu
addWindowMenu() {
2543 TMenu windowMenu
= addMenu(i18n
.getString("windowMenuTitle"));
2544 windowMenu
.addDefaultItem(TMenu
.MID_TILE
);
2545 windowMenu
.addDefaultItem(TMenu
.MID_CASCADE
);
2546 windowMenu
.addDefaultItem(TMenu
.MID_CLOSE_ALL
);
2547 windowMenu
.addSeparator();
2548 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_MOVE
);
2549 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_ZOOM
);
2550 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_NEXT
);
2551 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_PREVIOUS
);
2552 windowMenu
.addDefaultItem(TMenu
.MID_WINDOW_CLOSE
);
2553 TStatusBar statusBar
= windowMenu
.newStatusBar(i18n
.
2554 getString("windowMenuStatus"));
2555 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2560 * Convenience function to add a default "Help" menu.
2562 * @return the new menu
2564 public final TMenu
addHelpMenu() {
2565 TMenu helpMenu
= addMenu(i18n
.getString("helpMenuTitle"));
2566 helpMenu
.addDefaultItem(TMenu
.MID_HELP_CONTENTS
);
2567 helpMenu
.addDefaultItem(TMenu
.MID_HELP_INDEX
);
2568 helpMenu
.addDefaultItem(TMenu
.MID_HELP_SEARCH
);
2569 helpMenu
.addDefaultItem(TMenu
.MID_HELP_PREVIOUS
);
2570 helpMenu
.addDefaultItem(TMenu
.MID_HELP_HELP
);
2571 helpMenu
.addDefaultItem(TMenu
.MID_HELP_ACTIVE_FILE
);
2572 helpMenu
.addSeparator();
2573 helpMenu
.addDefaultItem(TMenu
.MID_ABOUT
);
2574 TStatusBar statusBar
= helpMenu
.newStatusBar(i18n
.
2575 getString("helpMenuStatus"));
2576 statusBar
.addShortcutKeypress(kbF1
, cmHelp
, i18n
.getString("Help"));
2580 // ------------------------------------------------------------------------
2581 // Event handlers ---------------------------------------------------------
2582 // ------------------------------------------------------------------------
2585 * Method that TApplication subclasses can override to handle menu or
2586 * posted command events.
2588 * @param command command event
2589 * @return if true, this event was consumed
2591 protected boolean onCommand(final TCommandEvent command
) {
2592 // Default: handle cmExit
2593 if (command
.equals(cmExit
)) {
2594 if (messageBox(i18n
.getString("exitDialogTitle"),
2595 i18n
.getString("exitDialogText"),
2596 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2602 if (command
.equals(cmShell
)) {
2603 openTerminal(0, 0, TWindow
.RESIZABLE
);
2607 if (command
.equals(cmTile
)) {
2611 if (command
.equals(cmCascade
)) {
2615 if (command
.equals(cmCloseAll
)) {
2620 if (command
.equals(cmMenu
)) {
2621 if (!modalWindowActive() && (activeMenu
== null)) {
2622 if (menus
.size() > 0) {
2623 menus
.get(0).setActive(true);
2624 activeMenu
= menus
.get(0);
2634 * Method that TApplication subclasses can override to handle menu
2637 * @param menu menu event
2638 * @return if true, this event was consumed
2640 protected boolean onMenu(final TMenuEvent menu
) {
2642 // Default: handle MID_EXIT
2643 if (menu
.getId() == TMenu
.MID_EXIT
) {
2644 if (messageBox(i18n
.getString("exitDialogTitle"),
2645 i18n
.getString("exitDialogText"),
2646 TMessageBox
.Type
.YESNO
).getResult() == TMessageBox
.Result
.YES
) {
2652 if (menu
.getId() == TMenu
.MID_SHELL
) {
2653 openTerminal(0, 0, TWindow
.RESIZABLE
);
2657 if (menu
.getId() == TMenu
.MID_TILE
) {
2661 if (menu
.getId() == TMenu
.MID_CASCADE
) {
2665 if (menu
.getId() == TMenu
.MID_CLOSE_ALL
) {
2669 if (menu
.getId() == TMenu
.MID_ABOUT
) {
2673 if (menu
.getId() == TMenu
.MID_REPAINT
) {
2681 * Method that TApplication subclasses can override to handle keystrokes.
2683 * @param keypress keystroke event
2684 * @return if true, this event was consumed
2686 protected boolean onKeypress(final TKeypressEvent keypress
) {
2687 // Default: only menu shortcuts
2689 // Process Alt-F, Alt-E, etc. menu shortcut keys
2690 if (!keypress
.getKey().isFnKey()
2691 && keypress
.getKey().isAlt()
2692 && !keypress
.getKey().isCtrl()
2693 && (activeMenu
== null)
2694 && !modalWindowActive()
2697 assert (subMenus
.size() == 0);
2699 for (TMenu menu
: menus
) {
2700 if (Character
.toLowerCase(menu
.getMnemonic().getShortcut())
2701 == Character
.toLowerCase(keypress
.getKey().getChar())
2704 menu
.setActive(true);
2713 // ------------------------------------------------------------------------
2714 // TTimer management ------------------------------------------------------
2715 // ------------------------------------------------------------------------
2718 * Get the amount of time I can sleep before missing a Timer tick.
2720 * @param timeout = initial (maximum) timeout in millis
2721 * @return number of milliseconds between now and the next timer event
2723 private long getSleepTime(final long timeout
) {
2724 Date now
= new Date();
2725 long nowTime
= now
.getTime();
2726 long sleepTime
= timeout
;
2728 synchronized (timers
) {
2729 for (TTimer timer
: timers
) {
2730 long nextTickTime
= timer
.getNextTick().getTime();
2731 if (nextTickTime
< nowTime
) {
2735 long timeDifference
= nextTickTime
- nowTime
;
2736 if (timeDifference
< sleepTime
) {
2737 sleepTime
= timeDifference
;
2742 assert (sleepTime
>= 0);
2743 assert (sleepTime
<= timeout
);
2748 * Convenience function to add a timer.
2750 * @param duration number of milliseconds to wait between ticks
2751 * @param recurring if true, re-schedule this timer after every tick
2752 * @param action function to call when button is pressed
2755 public final TTimer
addTimer(final long duration
, final boolean recurring
,
2756 final TAction action
) {
2758 TTimer timer
= new TTimer(duration
, recurring
, action
);
2759 synchronized (timers
) {
2766 * Convenience function to remove a timer.
2768 * @param timer timer to remove
2770 public final void removeTimer(final TTimer timer
) {
2771 synchronized (timers
) {
2772 timers
.remove(timer
);
2776 // ------------------------------------------------------------------------
2777 // Other TWindow constructors ---------------------------------------------
2778 // ------------------------------------------------------------------------
2781 * Convenience function to spawn a message box.
2783 * @param title window title, will be centered along the top border
2784 * @param caption message to display. Use embedded newlines to get a
2786 * @return the new message box
2788 public final TMessageBox
messageBox(final String title
,
2789 final String caption
) {
2791 return new TMessageBox(this, title
, caption
, TMessageBox
.Type
.OK
);
2795 * Convenience function to spawn a message box.
2797 * @param title window title, will be centered along the top border
2798 * @param caption message to display. Use embedded newlines to get a
2800 * @param type one of the TMessageBox.Type constants. Default is
2802 * @return the new message box
2804 public final TMessageBox
messageBox(final String title
,
2805 final String caption
, final TMessageBox
.Type type
) {
2807 return new TMessageBox(this, title
, caption
, type
);
2811 * Convenience function to spawn an input box.
2813 * @param title window title, will be centered along the top border
2814 * @param caption message to display. Use embedded newlines to get a
2816 * @return the new input box
2818 public final TInputBox
inputBox(final String title
, final String caption
) {
2820 return new TInputBox(this, title
, caption
);
2824 * Convenience function to spawn an input box.
2826 * @param title window title, will be centered along the top border
2827 * @param caption message to display. Use embedded newlines to get a
2829 * @param text initial text to seed the field with
2830 * @return the new input box
2832 public final TInputBox
inputBox(final String title
, final String caption
,
2833 final String text
) {
2835 return new TInputBox(this, title
, caption
, text
);
2839 * Convenience function to open a terminal window.
2841 * @param x column relative to parent
2842 * @param y row relative to parent
2843 * @return the terminal new window
2845 public final TTerminalWindow
openTerminal(final int x
, final int y
) {
2846 return openTerminal(x
, y
, TWindow
.RESIZABLE
);
2850 * Convenience function to open a terminal window.
2852 * @param x column relative to parent
2853 * @param y row relative to parent
2854 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2855 * @return the terminal new window
2857 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2860 return new TTerminalWindow(this, x
, y
, flags
);
2864 * Convenience function to open a terminal window and execute a custom
2865 * command line inside it.
2867 * @param x column relative to parent
2868 * @param y row relative to parent
2869 * @param commandLine the command line to execute
2870 * @return the terminal new window
2872 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2873 final String commandLine
) {
2875 return openTerminal(x
, y
, TWindow
.RESIZABLE
, commandLine
);
2879 * Convenience function to open a terminal window and execute a custom
2880 * command line inside it.
2882 * @param x column relative to parent
2883 * @param y row relative to parent
2884 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2885 * @param command the command line to execute
2886 * @return the terminal new window
2888 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2889 final int flags
, final String
[] command
) {
2891 return new TTerminalWindow(this, x
, y
, flags
, command
);
2895 * Convenience function to open a terminal window and execute a custom
2896 * command line inside it.
2898 * @param x column relative to parent
2899 * @param y row relative to parent
2900 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2901 * @param commandLine the command line to execute
2902 * @return the terminal new window
2904 public final TTerminalWindow
openTerminal(final int x
, final int y
,
2905 final int flags
, final String commandLine
) {
2907 return new TTerminalWindow(this, x
, y
, flags
, commandLine
.split("\\s"));
2911 * Convenience function to spawn an file open box.
2913 * @param path path of selected file
2914 * @return the result of the new file open box
2915 * @throws IOException if java.io operation throws
2917 public final String
fileOpenBox(final String path
) throws IOException
{
2919 TFileOpenBox box
= new TFileOpenBox(this, path
, TFileOpenBox
.Type
.OPEN
);
2920 return box
.getFilename();
2924 * Convenience function to spawn an file open box.
2926 * @param path path of selected file
2927 * @param type one of the Type constants
2928 * @return the result of the new file open box
2929 * @throws IOException if java.io operation throws
2931 public final String
fileOpenBox(final String path
,
2932 final TFileOpenBox
.Type type
) throws IOException
{
2934 TFileOpenBox box
= new TFileOpenBox(this, path
, type
);
2935 return box
.getFilename();
2939 * Convenience function to create a new window and make it active.
2940 * Window will be located at (0, 0).
2942 * @param title window title, will be centered along the top border
2943 * @param width width of window
2944 * @param height height of window
2946 public final TWindow
addWindow(final String title
, final int width
,
2949 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
);
2954 * Convenience function to create a new window and make it active.
2955 * Window will be located at (0, 0).
2957 * @param title window title, will be centered along the top border
2958 * @param width width of window
2959 * @param height height of window
2960 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2962 public final TWindow
addWindow(final String title
,
2963 final int width
, final int height
, final int flags
) {
2965 TWindow window
= new TWindow(this, title
, 0, 0, width
, height
, flags
);
2970 * Convenience function to create a new window and make it active.
2972 * @param title window title, will be centered along the top border
2973 * @param x column relative to parent
2974 * @param y row relative to parent
2975 * @param width width of window
2976 * @param height height of window
2978 public final TWindow
addWindow(final String title
,
2979 final int x
, final int y
, final int width
, final int height
) {
2981 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
);
2986 * Convenience function to create a new window and make it active.
2988 * @param title window title, will be centered along the top border
2989 * @param x column relative to parent
2990 * @param y row relative to parent
2991 * @param width width of window
2992 * @param height height of window
2993 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2995 public final TWindow
addWindow(final String title
,
2996 final int x
, final int y
, final int width
, final int height
,
2999 TWindow window
= new TWindow(this, title
, x
, y
, width
, height
, flags
);
3004 * Convenience function to open a file in an editor window and make it
3007 * @param file the file to open
3008 * @throws IOException if a java.io operation throws
3010 public final TEditorWindow
addEditor(final File file
) throws IOException
{
3012 TEditorWindow editor
= new TEditorWindow(this, file
);