Cache glyphs, fix vttest test
[fanfix.git] / src / jexer / TApplication.java
CommitLineData
daa4106c 1/*
7b5261bc 2 * Jexer - Java Text User Interface
7d4115a5 3 *
e16dda65 4 * The MIT License (MIT)
7d4115a5 5 *
e16dda65 6 * Copyright (C) 2016 Kevin Lamonte
7d4115a5 7 *
e16dda65
KL
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:
7d4115a5 14 *
e16dda65
KL
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
7d4115a5 17 *
e16dda65
KL
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.
7b5261bc
KL
25 *
26 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
27 * @version 1
7d4115a5
KL
28 */
29package jexer;
30
4328bb42 31import java.io.InputStream;
0d47c546 32import java.io.IOException;
4328bb42 33import java.io.OutputStream;
6985c572
KL
34import java.io.PrintWriter;
35import java.io.Reader;
4328bb42 36import java.io.UnsupportedEncodingException;
a06459bd 37import java.util.Collections;
d502a0e9 38import java.util.Date;
e826b451 39import java.util.HashMap;
c6940ed9 40import java.util.ArrayList;
4328bb42
KL
41import java.util.LinkedList;
42import java.util.List;
e826b451 43import java.util.Map;
4328bb42
KL
44
45import jexer.bits.CellAttributes;
46import jexer.bits.ColorTheme;
47import jexer.bits.GraphicsChars;
48import jexer.event.TCommandEvent;
49import jexer.event.TInputEvent;
50import jexer.event.TKeypressEvent;
fca67db0 51import jexer.event.TMenuEvent;
4328bb42
KL
52import jexer.event.TMouseEvent;
53import jexer.event.TResizeEvent;
54import jexer.backend.Backend;
a4406f4e 55import jexer.backend.SwingBackend;
4328bb42 56import jexer.backend.ECMA48Backend;
48e27807 57import jexer.io.Screen;
928811d8
KL
58import jexer.menu.TMenu;
59import jexer.menu.TMenuItem;
4328bb42 60import static jexer.TCommand.*;
4328bb42 61
7d4115a5
KL
62/**
63 * TApplication sets up a full Text User Interface application.
64 */
a4406f4e 65public class TApplication implements Runnable {
7d4115a5 66
99144c71
KL
67 /**
68 * If true, emit thread stuff to System.err.
69 */
70 private static final boolean debugThreads = false;
71
a83fea2b
KL
72 /**
73 * If true, emit events being processed to System.err.
74 */
75 private static final boolean debugEvents = false;
76
a4406f4e
KL
77 /**
78 * Two backend types are available.
79 */
80 public static enum BackendType {
81 /**
82 * A Swing JFrame.
83 */
84 SWING,
85
86 /**
87 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
88 */
89 ECMA48,
90
91 /**
329fd62e 92 * Synonym for ECMA48.
a4406f4e
KL
93 */
94 XTERM
95 }
96
c6940ed9
KL
97 /**
98 * WidgetEventHandler is the main event consumer loop. There are at most
99 * two such threads in existence: the primary for normal case and a
100 * secondary that is used for TMessageBox, TInputBox, and similar.
101 */
102 private class WidgetEventHandler implements Runnable {
103 /**
104 * The main application.
105 */
106 private TApplication application;
107
108 /**
109 * Whether or not this WidgetEventHandler is the primary or secondary
110 * thread.
111 */
112 private boolean primary = true;
113
114 /**
115 * Public constructor.
116 *
117 * @param application the main application
118 * @param primary if true, this is the primary event handler thread
119 */
120 public WidgetEventHandler(final TApplication application,
121 final boolean primary) {
122
123 this.application = application;
124 this.primary = primary;
125 }
126
127 /**
128 * The consumer loop.
129 */
130 public void run() {
131
132 // Loop forever
133 while (!application.quit) {
134
135 // Wait until application notifies me
136 while (!application.quit) {
137 try {
138 synchronized (application.drainEventQueue) {
139 if (application.drainEventQueue.size() > 0) {
140 break;
141 }
142 }
92554d64
KL
143
144 synchronized (this) {
bd8d51fa
KL
145 if (debugThreads) {
146 System.err.printf("%s %s sleep\n", this,
147 primary ? "primary" : "secondary");
148 }
92554d64
KL
149
150 this.wait();
151
bd8d51fa
KL
152 if (debugThreads) {
153 System.err.printf("%s %s AWAKE\n", this,
154 primary ? "primary" : "secondary");
155 }
92554d64 156
c6940ed9
KL
157 if ((!primary)
158 && (application.secondaryEventReceiver == null)
159 ) {
92554d64
KL
160 // Secondary thread, emergency exit. If we
161 // got here then something went wrong with
162 // the handoff between yield() and
163 // closeWindow().
92554d64
KL
164 synchronized (application.primaryEventHandler) {
165 application.primaryEventHandler.notify();
166 }
167 application.secondaryEventHandler = null;
bd8d51fa
KL
168 throw new RuntimeException(
169 "secondary exited at wrong time");
c6940ed9
KL
170 }
171 break;
172 }
173 } catch (InterruptedException e) {
174 // SQUASH
175 }
176 }
177
ef368bd0
KL
178 // Wait for drawAll() or doIdle() to be done, then handle the
179 // events.
180 boolean oldLock = lockHandleEvent();
181 assert (oldLock == false);
182
c6940ed9
KL
183 // Pull all events off the queue
184 for (;;) {
185 TInputEvent event = null;
186 synchronized (application.drainEventQueue) {
187 if (application.drainEventQueue.size() == 0) {
188 break;
189 }
190 event = application.drainEventQueue.remove(0);
191 }
bd8d51fa 192 application.repaint = true;
c6940ed9
KL
193 if (primary) {
194 primaryHandleEvent(event);
195 } else {
196 secondaryHandleEvent(event);
197 }
198 if ((!primary)
199 && (application.secondaryEventReceiver == null)
200 ) {
99144c71
KL
201 // Secondary thread, time to exit.
202
203 // DO NOT UNLOCK. Primary thread just came back from
204 // primaryHandleEvent() and will unlock in the else
92554d64
KL
205 // block below. Just wake it up.
206 synchronized (application.primaryEventHandler) {
207 application.primaryEventHandler.notify();
208 }
209 // Now eliminate my reference so that
210 // wakeEventHandler() resumes working on the primary.
211 application.secondaryEventHandler = null;
212
213 // All done!
c6940ed9
KL
214 return;
215 }
92554d64
KL
216 } // for (;;)
217
ef368bd0
KL
218 // Unlock. Either I am primary thread, or I am secondary
219 // thread and still running.
220 oldLock = unlockHandleEvent();
221 assert (oldLock == true);
222
92554d64
KL
223 // I have done some work of some kind. Tell the main run()
224 // loop to wake up now.
225 synchronized (application) {
226 application.notify();
c6940ed9 227 }
92554d64 228
c6940ed9
KL
229 } // while (true) (main runnable loop)
230 }
231 }
232
233 /**
234 * The primary event handler thread.
235 */
92554d64 236 private volatile WidgetEventHandler primaryEventHandler;
c6940ed9
KL
237
238 /**
239 * The secondary event handler thread.
240 */
92554d64 241 private volatile WidgetEventHandler secondaryEventHandler;
c6940ed9
KL
242
243 /**
244 * The widget receiving events from the secondary event handler thread.
245 */
92554d64 246 private volatile TWidget secondaryEventReceiver;
c6940ed9 247
99144c71
KL
248 /**
249 * Spinlock for the primary and secondary event handlers.
250 * WidgetEventHandler.run() is responsible for setting this value.
251 */
252 private volatile boolean insideHandleEvent = false;
253
92554d64
KL
254 /**
255 * Wake the sleeping active event handler.
256 */
257 private void wakeEventHandler() {
258 if (secondaryEventHandler != null) {
259 synchronized (secondaryEventHandler) {
260 secondaryEventHandler.notify();
261 }
262 } else {
263 assert (primaryEventHandler != null);
264 synchronized (primaryEventHandler) {
265 primaryEventHandler.notify();
266 }
267 }
268 }
269
99144c71
KL
270 /**
271 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
272 * spin indefinitely until unlockHandleEvent() is called.
273 *
274 * @return the old value of insideHandleEvent
275 */
276 private boolean lockHandleEvent() {
277 if (debugThreads) {
278 System.err.printf(" >> lockHandleEvent(): oldValue %s",
279 insideHandleEvent);
280 }
281 boolean oldValue = true;
282
283 synchronized (this) {
284 // Wait for TApplication.run() to finish using the global state
285 // before allowing further event processing.
ef368bd0
KL
286 while (lockoutHandleEvent == true) {
287 try {
288 // Backoff so that the backend can finish its work.
289 Thread.sleep(5);
290 } catch (InterruptedException e) {
291 // SQUASH
292 }
293 }
99144c71
KL
294
295 oldValue = insideHandleEvent;
296 insideHandleEvent = true;
297 }
298
299 if (debugThreads) {
300 System.err.printf(" ***\n");
301 }
302 return oldValue;
303 }
304
305 /**
306 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
307 * spin indefinitely until unlockHandleEvent() is called.
308 *
309 * @return the old value of insideHandleEvent
310 */
311 private boolean unlockHandleEvent() {
312 if (debugThreads) {
313 System.err.printf(" << unlockHandleEvent(): oldValue %s\n",
314 insideHandleEvent);
315 }
316 synchronized (this) {
317 boolean oldValue = insideHandleEvent;
318 insideHandleEvent = false;
319 return oldValue;
320 }
321 }
322
323 /**
324 * Spinlock for the primary and secondary event handlers. When true, the
325 * event handlers will spinlock wait before calling handleEvent().
326 */
327 private volatile boolean lockoutHandleEvent = false;
328
329 /**
330 * TApplication.run() needs to be able rely on the global data structures
331 * being intact when calling doIdle() and drawAll(). Tell the event
332 * handlers to wait for an unlock before handling their events.
333 */
334 private void stopEventHandlers() {
335 if (debugThreads) {
336 System.err.printf(">> stopEventHandlers()");
337 }
338
339 lockoutHandleEvent = true;
340 // Wait for the last event to finish processing before returning
341 // control to TApplication.run().
ef368bd0
KL
342 while (insideHandleEvent == true) {
343 try {
344 // Backoff so that the event handler can finish its work.
345 Thread.sleep(1);
346 } catch (InterruptedException e) {
347 // SQUASH
348 }
349 }
99144c71
KL
350
351 if (debugThreads) {
352 System.err.printf(" XXX\n");
353 }
354 }
355
356 /**
357 * TApplication.run() needs to be able rely on the global data structures
358 * being intact when calling doIdle() and drawAll(). Tell the event
359 * handlers that it is now OK to handle their events.
360 */
361 private void startEventHandlers() {
362 if (debugThreads) {
363 System.err.printf("<< startEventHandlers()\n");
364 }
365 lockoutHandleEvent = false;
366 }
367
7d4115a5 368 /**
4328bb42
KL
369 * Access to the physical screen, keyboard, and mouse.
370 */
7b5261bc 371 private Backend backend;
4328bb42 372
48e27807
KL
373 /**
374 * Get the Screen.
375 *
376 * @return the Screen
377 */
378 public final Screen getScreen() {
379 return backend.getScreen();
380 }
381
4328bb42 382 /**
7b5261bc 383 * Actual mouse coordinate X.
4328bb42
KL
384 */
385 private int mouseX;
386
387 /**
7b5261bc 388 * Actual mouse coordinate Y.
4328bb42
KL
389 */
390 private int mouseY;
391
bd8d51fa
KL
392 /**
393 * Old version of mouse coordinate X.
394 */
395 private int oldMouseX;
396
397 /**
398 * Old version mouse coordinate Y.
399 */
400 private int oldMouseY;
401
4328bb42 402 /**
8e688b92 403 * Event queue that is filled by run().
4328bb42 404 */
8e688b92
KL
405 private List<TInputEvent> fillEventQueue;
406
407 /**
408 * Event queue that will be drained by either primary or secondary
409 * Thread.
410 */
411 private List<TInputEvent> drainEventQueue;
4328bb42 412
fca67db0
KL
413 /**
414 * Top-level menus in this application.
415 */
416 private List<TMenu> menus;
417
418 /**
419 * Stack of activated sub-menus in this application.
420 */
421 private List<TMenu> subMenus;
422
423 /**
424 * The currently acive menu.
425 */
426 private TMenu activeMenu = null;
427
e826b451
KL
428 /**
429 * Active keyboard accelerators.
430 */
431 private Map<TKeypress, TMenuItem> accelerators;
432
efb7af1f
KL
433 /**
434 * All menu items.
435 */
436 private List<TMenuItem> menuItems;
437
4328bb42
KL
438 /**
439 * Windows and widgets pull colors from this ColorTheme.
440 */
7b5261bc
KL
441 private ColorTheme theme;
442
443 /**
444 * Get the color theme.
445 *
446 * @return the theme
447 */
448 public final ColorTheme getTheme() {
449 return theme;
450 }
4328bb42 451
a06459bd
KL
452 /**
453 * The top-level windows (but not menus).
454 */
fca67db0 455 private List<TWindow> windows;
a06459bd 456
d502a0e9
KL
457 /**
458 * Timers that are being ticked.
459 */
460 private List<TTimer> timers;
461
4328bb42
KL
462 /**
463 * When true, exit the application.
464 */
92554d64 465 private volatile boolean quit = false;
4328bb42
KL
466
467 /**
468 * When true, repaint the entire screen.
469 */
92554d64 470 private volatile boolean repaint = true;
4328bb42 471
4328bb42 472 /**
7b5261bc
KL
473 * Y coordinate of the top edge of the desktop. For now this is a
474 * constant. Someday it would be nice to have a multi-line menu or
475 * toolbars.
4328bb42 476 */
48e27807
KL
477 private static final int desktopTop = 1;
478
479 /**
480 * Get Y coordinate of the top edge of the desktop.
481 *
482 * @return Y coordinate of the top edge of the desktop
483 */
484 public final int getDesktopTop() {
485 return desktopTop;
486 }
4328bb42
KL
487
488 /**
489 * Y coordinate of the bottom edge of the desktop.
490 */
48e27807
KL
491 private int desktopBottom;
492
493 /**
494 * Get Y coordinate of the bottom edge of the desktop.
495 *
496 * @return Y coordinate of the bottom edge of the desktop
497 */
498 public final int getDesktopBottom() {
499 return desktopBottom;
500 }
4328bb42
KL
501
502 /**
503 * Public constructor.
504 *
a4406f4e
KL
505 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
506 * BackendType.SWING
507 * @throws UnsupportedEncodingException if an exception is thrown when
508 * creating the InputStreamReader
509 */
510 public TApplication(final BackendType backendType)
511 throws UnsupportedEncodingException {
512
513 switch (backendType) {
514 case SWING:
515 backend = new SwingBackend(this);
516 break;
517 case XTERM:
518 // Fall through...
519 case ECMA48:
520 backend = new ECMA48Backend(this, null, null);
329fd62e
KL
521 break;
522 default:
523 throw new IllegalArgumentException("Invalid backend type: "
524 + backendType);
a4406f4e
KL
525 }
526 TApplicationImpl();
527 }
528
529 /**
530 * Public constructor. The backend type will be BackendType.ECMA48.
531 *
4328bb42
KL
532 * @param input an InputStream connected to the remote user, or null for
533 * System.in. If System.in is used, then on non-Windows systems it will
534 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
535 * mode. input is always converted to a Reader with UTF-8 encoding.
536 * @param output an OutputStream connected to the remote user, or null
537 * for System.out. output is always converted to a Writer with UTF-8
538 * encoding.
7b5261bc
KL
539 * @throws UnsupportedEncodingException if an exception is thrown when
540 * creating the InputStreamReader
4328bb42 541 */
7b5261bc
KL
542 public TApplication(final InputStream input,
543 final OutputStream output) throws UnsupportedEncodingException {
4328bb42 544
a4406f4e
KL
545 backend = new ECMA48Backend(this, input, output);
546 TApplicationImpl();
547 }
30bd4abd 548
6985c572
KL
549 /**
550 * Public constructor. The backend type will be BackendType.ECMA48.
551 *
552 * @param input the InputStream underlying 'reader'. Its available()
553 * method is used to determine if reader.read() will block or not.
554 * @param reader a Reader connected to the remote user.
555 * @param writer a PrintWriter connected to the remote user.
556 * @param setRawMode if true, set System.in into raw mode with stty.
557 * This should in general not be used. It is here solely for Demo3,
558 * which uses System.in.
559 * @throws IllegalArgumentException if input, reader, or writer are null.
560 */
561 public TApplication(final InputStream input, final Reader reader,
562 final PrintWriter writer, final boolean setRawMode) {
563
564 backend = new ECMA48Backend(this, input, reader, writer, setRawMode);
565 TApplicationImpl();
566 }
567
568 /**
569 * Public constructor. The backend type will be BackendType.ECMA48.
570 *
571 * @param input the InputStream underlying 'reader'. Its available()
572 * method is used to determine if reader.read() will block or not.
573 * @param reader a Reader connected to the remote user.
574 * @param writer a PrintWriter connected to the remote user.
575 * @throws IllegalArgumentException if input, reader, or writer are null.
576 */
577 public TApplication(final InputStream input, final Reader reader,
578 final PrintWriter writer) {
579
580 this(input, reader, writer, false);
581 }
582
a4406f4e
KL
583 /**
584 * Public constructor. This hook enables use with new non-Jexer
585 * backends.
586 *
587 * @param backend a Backend that is already ready to go.
588 */
589 public TApplication(final Backend backend) {
590 this.backend = backend;
591 TApplicationImpl();
592 }
30bd4abd 593
a4406f4e
KL
594 /**
595 * Finish construction once the backend is set.
596 */
597 private void TApplicationImpl() {
8e688b92
KL
598 theme = new ColorTheme();
599 desktopBottom = getScreen().getHeight() - 1;
c6940ed9
KL
600 fillEventQueue = new ArrayList<TInputEvent>();
601 drainEventQueue = new ArrayList<TInputEvent>();
8e688b92
KL
602 windows = new LinkedList<TWindow>();
603 menus = new LinkedList<TMenu>();
604 subMenus = new LinkedList<TMenu>();
d502a0e9 605 timers = new LinkedList<TTimer>();
e826b451 606 accelerators = new HashMap<TKeypress, TMenuItem>();
efb7af1f 607 menuItems = new ArrayList<TMenuItem>();
c6940ed9
KL
608
609 // Setup the main consumer thread
610 primaryEventHandler = new WidgetEventHandler(this, true);
611 (new Thread(primaryEventHandler)).start();
4328bb42
KL
612 }
613
614 /**
bd8d51fa
KL
615 * Invert the cell color at a position. This is used to track the mouse.
616 *
617 * @param x column position
618 * @param y row position
4328bb42 619 */
bd8d51fa 620 private void invertCell(final int x, final int y) {
1d14ffab
KL
621 if (debugThreads) {
622 System.err.printf("invertCell() %d %d\n", x, y);
7b5261bc 623 }
1d14ffab
KL
624 CellAttributes attr = getScreen().getAttrXY(x, y);
625 attr.setForeColor(attr.getForeColor().invert());
626 attr.setBackColor(attr.getBackColor().invert());
627 getScreen().putAttrXY(x, y, attr, false);
4328bb42
KL
628 }
629
630 /**
631 * Draw everything.
632 */
7c870d89 633 private void drawAll() {
99144c71
KL
634 if (debugThreads) {
635 System.err.printf("drawAll() enter\n");
636 }
637
bd8d51fa 638 if (!repaint) {
1d14ffab
KL
639 if (debugThreads) {
640 System.err.printf("drawAll() !repaint\n");
bd8d51fa 641 }
1d14ffab
KL
642 synchronized (getScreen()) {
643 if ((oldMouseX != mouseX) || (oldMouseY != mouseY)) {
644 // The only thing that has happened is the mouse moved.
645 // Clear the old position and draw the new position.
646 invertCell(oldMouseX, oldMouseY);
647 invertCell(mouseX, mouseY);
648 oldMouseX = mouseX;
649 oldMouseY = mouseY;
650 }
651 if (getScreen().isDirty()) {
652 backend.flushScreen();
653 }
654 return;
bd8d51fa 655 }
7b5261bc
KL
656 }
657
99144c71
KL
658 if (debugThreads) {
659 System.err.printf("drawAll() REDRAW\n");
660 }
661
7b5261bc
KL
662 // If true, the cursor is not visible
663 boolean cursor = false;
664
665 // Start with a clean screen
a06459bd 666 getScreen().clear();
7b5261bc
KL
667
668 // Draw the background
669 CellAttributes background = theme.getColor("tapplication.background");
a06459bd 670 getScreen().putAll(GraphicsChars.HATCH, background);
7b5261bc 671
7b5261bc 672 // Draw each window in reverse Z order
a06459bd
KL
673 List<TWindow> sorted = new LinkedList<TWindow>(windows);
674 Collections.sort(sorted);
675 Collections.reverse(sorted);
676 for (TWindow window: sorted) {
677 window.drawChildren();
7b5261bc
KL
678 }
679
680 // Draw the blank menubar line - reset the screen clipping first so
681 // it won't trim it out.
a06459bd
KL
682 getScreen().resetClipping();
683 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
7b5261bc
KL
684 theme.getColor("tmenu"));
685 // Now draw the menus.
686 int x = 1;
fca67db0 687 for (TMenu menu: menus) {
7b5261bc
KL
688 CellAttributes menuColor;
689 CellAttributes menuMnemonicColor;
7c870d89 690 if (menu.isActive()) {
7b5261bc
KL
691 menuColor = theme.getColor("tmenu.highlighted");
692 menuMnemonicColor = theme.getColor("tmenu.mnemonic.highlighted");
693 } else {
694 menuColor = theme.getColor("tmenu");
695 menuMnemonicColor = theme.getColor("tmenu.mnemonic");
696 }
697 // Draw the menu title
fca67db0 698 getScreen().hLineXY(x, 0, menu.getTitle().length() + 2, ' ',
7b5261bc 699 menuColor);
0d47c546 700 getScreen().putStringXY(x + 1, 0, menu.getTitle(), menuColor);
7b5261bc 701 // Draw the highlight character
fca67db0
KL
702 getScreen().putCharXY(x + 1 + menu.getMnemonic().getShortcutIdx(),
703 0, menu.getMnemonic().getShortcut(), menuMnemonicColor);
7b5261bc 704
7c870d89 705 if (menu.isActive()) {
a06459bd 706 menu.drawChildren();
7b5261bc 707 // Reset the screen clipping so we can draw the next title.
a06459bd 708 getScreen().resetClipping();
7b5261bc 709 }
fca67db0 710 x += menu.getTitle().length() + 2;
7b5261bc
KL
711 }
712
a06459bd 713 for (TMenu menu: subMenus) {
7b5261bc 714 // Reset the screen clipping so we can draw the next sub-menu.
a06459bd
KL
715 getScreen().resetClipping();
716 menu.drawChildren();
7b5261bc 717 }
7b5261bc
KL
718
719 // Draw the mouse pointer
bd8d51fa 720 invertCell(mouseX, mouseY);
1d14ffab
KL
721 oldMouseX = mouseX;
722 oldMouseY = mouseY;
7b5261bc 723
7b5261bc
KL
724 // Place the cursor if it is visible
725 TWidget activeWidget = null;
a06459bd
KL
726 if (sorted.size() > 0) {
727 activeWidget = sorted.get(sorted.size() - 1).getActiveChild();
7c870d89 728 if (activeWidget.isCursorVisible()) {
a06459bd 729 getScreen().putCursor(true, activeWidget.getCursorAbsoluteX(),
7b5261bc
KL
730 activeWidget.getCursorAbsoluteY());
731 cursor = true;
732 }
733 }
734
735 // Kill the cursor
fca67db0 736 if (!cursor) {
a06459bd 737 getScreen().hideCursor();
7b5261bc 738 }
7b5261bc
KL
739
740 // Flush the screen contents
1d14ffab
KL
741 if (getScreen().isDirty()) {
742 backend.flushScreen();
743 }
7b5261bc
KL
744
745 repaint = false;
4328bb42
KL
746 }
747
748 /**
7b5261bc 749 * Run this application until it exits.
4328bb42 750 */
a4406f4e 751 public void run() {
7b5261bc
KL
752 while (!quit) {
753 // Timeout is in milliseconds, so default timeout after 1 second
754 // of inactivity.
92554d64
KL
755 long timeout = 0;
756
757 // If I've got no updates to render, wait for something from the
758 // backend or a timer.
bd8d51fa
KL
759 if (!repaint
760 && ((mouseX == oldMouseX) && (mouseY == oldMouseY))
761 ) {
e3dfbd23
KL
762 // Never sleep longer than 50 millis. We need time for
763 // windows with background tasks to update the display, and
764 // still flip buffers reasonably quickly in
765 // backend.flushPhysical().
766 timeout = getSleepTime(50);
8e688b92 767 }
92554d64
KL
768
769 if (timeout > 0) {
770 // As of now, I've got nothing to do: no I/O, nothing from
771 // the consumer threads, no timers that need to run ASAP. So
772 // wait until either the backend or the consumer threads have
773 // something to do.
774 try {
6358f6e5
KL
775 if (debugThreads) {
776 System.err.println("sleep " + timeout + " millis");
777 }
92554d64
KL
778 synchronized (this) {
779 this.wait(timeout);
780 }
781 } catch (InterruptedException e) {
782 // I'm awake and don't care why, let's see what's going
783 // on out there.
8e688b92 784 }
bd8d51fa 785 repaint = true;
7b5261bc
KL
786 }
787
ef368bd0
KL
788 // Prevent stepping on the primary or secondary event handler.
789 stopEventHandlers();
790
8e688b92 791 // Pull any pending I/O events
92554d64 792 backend.getEvents(fillEventQueue);
8e688b92
KL
793
794 // Dispatch each event to the appropriate handler, one at a time.
795 for (;;) {
796 TInputEvent event = null;
ef368bd0
KL
797 if (fillEventQueue.size() == 0) {
798 break;
8e688b92 799 }
ef368bd0 800 event = fillEventQueue.remove(0);
8e688b92
KL
801 metaHandleEvent(event);
802 }
7b5261bc 803
92554d64 804 // Wake a consumer thread if we have any pending events.
ef368bd0
KL
805 if (drainEventQueue.size() > 0) {
806 wakeEventHandler();
92554d64
KL
807 }
808
7b5261bc
KL
809 // Process timers and call doIdle()'s
810 doIdle();
811
812 // Update the screen
87a17f3c
KL
813 synchronized (getScreen()) {
814 drawAll();
815 }
99144c71
KL
816
817 // Let the event handlers run again.
818 startEventHandlers();
7b5261bc 819
92554d64
KL
820 } // while (!quit)
821
822 // Shutdown the event consumer threads
823 if (secondaryEventHandler != null) {
824 synchronized (secondaryEventHandler) {
825 secondaryEventHandler.notify();
826 }
827 }
828 if (primaryEventHandler != null) {
829 synchronized (primaryEventHandler) {
830 primaryEventHandler.notify();
831 }
7b5261bc
KL
832 }
833
92554d64 834 // Shutdown the user I/O thread(s)
7b5261bc 835 backend.shutdown();
92554d64
KL
836
837 // Close all the windows. This gives them an opportunity to release
838 // resources.
839 closeAllWindows();
840
4328bb42
KL
841 }
842
843 /**
844 * Peek at certain application-level events, add to eventQueue, and wake
8e688b92 845 * up the consuming Thread.
4328bb42 846 *
8e688b92 847 * @param event the input event to consume
4328bb42 848 */
8e688b92 849 private void metaHandleEvent(final TInputEvent event) {
7b5261bc 850
a83fea2b
KL
851 if (debugEvents) {
852 System.err.printf(String.format("metaHandleEvents event: %s\n",
853 event)); System.err.flush();
854 }
7b5261bc 855
8e688b92
KL
856 if (quit) {
857 // Do no more processing if the application is already trying
858 // to exit.
859 return;
860 }
7b5261bc 861
8e688b92 862 // Special application-wide events -------------------------------
7b5261bc 863
8e688b92
KL
864 // Abort everything
865 if (event instanceof TCommandEvent) {
866 TCommandEvent command = (TCommandEvent) event;
867 if (command.getCmd().equals(cmAbort)) {
868 quit = true;
869 return;
7b5261bc 870 }
8e688b92 871 }
7b5261bc 872
8e688b92
KL
873 // Screen resize
874 if (event instanceof TResizeEvent) {
875 TResizeEvent resize = (TResizeEvent) event;
bd8d51fa
KL
876 synchronized (getScreen()) {
877 getScreen().setDimensions(resize.getWidth(),
878 resize.getHeight());
879 desktopBottom = getScreen().getHeight() - 1;
880 mouseX = 0;
881 mouseY = 0;
882 oldMouseX = 0;
883 oldMouseY = 0;
884 }
8e688b92
KL
885 return;
886 }
7b5261bc 887
8e688b92
KL
888 // Peek at the mouse position
889 if (event instanceof TMouseEvent) {
890 TMouseEvent mouse = (TMouseEvent) event;
bd8d51fa
KL
891 synchronized (getScreen()) {
892 if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
893 oldMouseX = mouseX;
894 oldMouseY = mouseY;
895 mouseX = mouse.getX();
896 mouseY = mouse.getY();
897 }
7b5261bc 898 }
8e688b92 899 }
7b5261bc 900
bd8d51fa 901 // Put into the main queue
ef368bd0 902 drainEventQueue.add(event);
4328bb42
KL
903 }
904
a06459bd
KL
905 /**
906 * Dispatch one event to the appropriate widget or application-level
fca67db0
KL
907 * event handler. This is the primary event handler, it has the normal
908 * application-wide event handling.
a06459bd
KL
909 *
910 * @param event the input event to consume
fca67db0 911 * @see #secondaryHandleEvent(TInputEvent event)
a06459bd 912 */
fca67db0
KL
913 private void primaryHandleEvent(final TInputEvent event) {
914
a83fea2b
KL
915 if (debugEvents) {
916 System.err.printf("Handle event: %s\n", event);
917 }
fca67db0
KL
918
919 // Special application-wide events -----------------------------------
920
921 // Peek at the mouse position
922 if (event instanceof TMouseEvent) {
923 // See if we need to switch focus to another window or the menu
924 checkSwitchFocus((TMouseEvent) event);
925 }
926
927 // Handle menu events
928 if ((activeMenu != null) && !(event instanceof TCommandEvent)) {
929 TMenu menu = activeMenu;
930
931 if (event instanceof TMouseEvent) {
932 TMouseEvent mouse = (TMouseEvent) event;
933
934 while (subMenus.size() > 0) {
935 TMenu subMenu = subMenus.get(subMenus.size() - 1);
936 if (subMenu.mouseWouldHit(mouse)) {
937 break;
938 }
939 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
7c870d89
KL
940 && (!mouse.isMouse1())
941 && (!mouse.isMouse2())
942 && (!mouse.isMouse3())
943 && (!mouse.isMouseWheelUp())
944 && (!mouse.isMouseWheelDown())
fca67db0
KL
945 ) {
946 break;
947 }
948 // We navigated away from a sub-menu, so close it
949 closeSubMenu();
950 }
951
952 // Convert the mouse relative x/y to menu coordinates
953 assert (mouse.getX() == mouse.getAbsoluteX());
954 assert (mouse.getY() == mouse.getAbsoluteY());
955 if (subMenus.size() > 0) {
956 menu = subMenus.get(subMenus.size() - 1);
957 }
958 mouse.setX(mouse.getX() - menu.getX());
959 mouse.setY(mouse.getY() - menu.getY());
960 }
961 menu.handleEvent(event);
962 return;
963 }
a06459bd 964
fca67db0
KL
965 if (event instanceof TKeypressEvent) {
966 TKeypressEvent keypress = (TKeypressEvent) event;
e826b451 967
fca67db0
KL
968 // See if this key matches an accelerator, and if so dispatch the
969 // menu event.
970 TKeypress keypressLowercase = keypress.getKey().toLowerCase();
e826b451
KL
971 TMenuItem item = null;
972 synchronized (accelerators) {
973 item = accelerators.get(keypressLowercase);
974 }
fca67db0 975 if (item != null) {
7c870d89 976 if (item.isEnabled()) {
bd8d51fa
KL
977 // Let the menu item dispatch
978 item.dispatch();
fca67db0
KL
979 return;
980 }
981 }
bd8d51fa
KL
982 // Handle the keypress
983 if (onKeypress(keypress)) {
984 return;
985 }
fca67db0 986 }
a06459bd 987
fca67db0
KL
988 if (event instanceof TCommandEvent) {
989 if (onCommand((TCommandEvent) event)) {
990 return;
991 }
992 }
993
994 if (event instanceof TMenuEvent) {
995 if (onMenu((TMenuEvent) event)) {
996 return;
997 }
998 }
999
1000 // Dispatch events to the active window -------------------------------
1001 for (TWindow window: windows) {
7c870d89 1002 if (window.isActive()) {
a06459bd
KL
1003 if (event instanceof TMouseEvent) {
1004 TMouseEvent mouse = (TMouseEvent) event;
fca67db0
KL
1005 // Convert the mouse relative x/y to window coordinates
1006 assert (mouse.getX() == mouse.getAbsoluteX());
1007 assert (mouse.getY() == mouse.getAbsoluteY());
1008 mouse.setX(mouse.getX() - window.getX());
1009 mouse.setY(mouse.getY() - window.getY());
1010 }
a83fea2b
KL
1011 if (debugEvents) {
1012 System.err.printf("TApplication dispatch event: %s\n",
1013 event);
1014 }
fca67db0
KL
1015 window.handleEvent(event);
1016 break;
1017 }
1018 }
1019 }
1020 /**
1021 * Dispatch one event to the appropriate widget or application-level
1022 * event handler. This is the secondary event handler used by certain
1023 * special dialogs (currently TMessageBox and TFileOpenBox).
1024 *
1025 * @param event the input event to consume
1026 * @see #primaryHandleEvent(TInputEvent event)
1027 */
1028 private void secondaryHandleEvent(final TInputEvent event) {
c6940ed9
KL
1029 secondaryEventReceiver.handleEvent(event);
1030 }
1031
1032 /**
1033 * Enable a widget to override the primary event thread.
1034 *
1035 * @param widget widget that will receive events
1036 */
1037 public final void enableSecondaryEventReceiver(final TWidget widget) {
1038 assert (secondaryEventReceiver == null);
1039 assert (secondaryEventHandler == null);
a043164f
KL
1040 assert ((widget instanceof TMessageBox)
1041 || (widget instanceof TFileOpenBox));
c6940ed9
KL
1042 secondaryEventReceiver = widget;
1043 secondaryEventHandler = new WidgetEventHandler(this, false);
1044 (new Thread(secondaryEventHandler)).start();
c6940ed9
KL
1045 }
1046
1047 /**
1048 * Yield to the secondary thread.
1049 */
1050 public final void yield() {
1051 assert (secondaryEventReceiver != null);
99144c71
KL
1052 // This is where we handoff the event handler lock from the primary
1053 // to secondary thread. We unlock here, and in a future loop the
1054 // secondary thread locks again. When it gives up, we have the
1055 // single lock back.
1056 boolean oldLock = unlockHandleEvent();
329fd62e 1057 assert (oldLock);
99144c71 1058
c6940ed9 1059 while (secondaryEventReceiver != null) {
92554d64 1060 synchronized (primaryEventHandler) {
c6940ed9 1061 try {
92554d64 1062 primaryEventHandler.wait();
c6940ed9
KL
1063 } catch (InterruptedException e) {
1064 // SQUASH
1065 }
1066 }
1067 }
a06459bd
KL
1068 }
1069
4328bb42
KL
1070 /**
1071 * Do stuff when there is no user input.
1072 */
1073 private void doIdle() {
99144c71
KL
1074 if (debugThreads) {
1075 System.err.printf("doIdle()\n");
1076 }
1077
7b5261bc 1078 // Now run any timers that have timed out
d502a0e9
KL
1079 Date now = new Date();
1080 List<TTimer> keepTimers = new LinkedList<TTimer>();
1081 for (TTimer timer: timers) {
92554d64 1082 if (timer.getNextTick().getTime() <= now.getTime()) {
d502a0e9 1083 timer.tick();
c6940ed9 1084 if (timer.recurring) {
d502a0e9 1085 keepTimers.add(timer);
7b5261bc
KL
1086 }
1087 } else {
d502a0e9 1088 keepTimers.add(timer);
7b5261bc
KL
1089 }
1090 }
1091 timers = keepTimers;
1092
1093 // Call onIdle's
d502a0e9
KL
1094 for (TWindow window: windows) {
1095 window.onIdle();
7b5261bc 1096 }
4328bb42 1097 }
7d4115a5 1098
4328bb42
KL
1099 /**
1100 * Get the amount of time I can sleep before missing a Timer tick.
1101 *
92554d64 1102 * @param timeout = initial (maximum) timeout in millis
4328bb42
KL
1103 * @return number of milliseconds between now and the next timer event
1104 */
bd8d51fa 1105 private long getSleepTime(final long timeout) {
d502a0e9 1106 Date now = new Date();
92554d64 1107 long nowTime = now.getTime();
d502a0e9
KL
1108 long sleepTime = timeout;
1109 for (TTimer timer: timers) {
92554d64
KL
1110 long nextTickTime = timer.getNextTick().getTime();
1111 if (nextTickTime < nowTime) {
7b5261bc
KL
1112 return 0;
1113 }
92554d64
KL
1114
1115 long timeDifference = nextTickTime - nowTime;
1116 if (timeDifference < sleepTime) {
1117 sleepTime = timeDifference;
7b5261bc
KL
1118 }
1119 }
d502a0e9 1120 assert (sleepTime >= 0);
92554d64
KL
1121 assert (sleepTime <= timeout);
1122 return sleepTime;
7d4115a5 1123 }
4328bb42 1124
48e27807
KL
1125 /**
1126 * Close window. Note that the window's destructor is NOT called by this
1127 * method, instead the GC is assumed to do the cleanup.
1128 *
1129 * @param window the window to remove
1130 */
1131 public final void closeWindow(final TWindow window) {
bb35d919
KL
1132 synchronized (windows) {
1133 int z = window.getZ();
1134 window.setZ(-1);
efb7af1f 1135 window.onUnfocus();
bb35d919
KL
1136 Collections.sort(windows);
1137 windows.remove(0);
1138 TWindow activeWindow = null;
1139 for (TWindow w: windows) {
1140 if (w.getZ() > z) {
1141 w.setZ(w.getZ() - 1);
1142 if (w.getZ() == 0) {
1143 w.setActive(true);
efb7af1f 1144 w.onFocus();
bb35d919
KL
1145 assert (activeWindow == null);
1146 activeWindow = w;
1147 } else {
efb7af1f
KL
1148 if (w.isActive()) {
1149 w.setActive(false);
1150 w.onUnfocus();
1151 }
bb35d919 1152 }
48e27807
KL
1153 }
1154 }
1155 }
1156
1157 // Perform window cleanup
1158 window.onClose();
1159
48e27807 1160 // Check if we are closing a TMessageBox or similar
c6940ed9
KL
1161 if (secondaryEventReceiver != null) {
1162 assert (secondaryEventHandler != null);
48e27807
KL
1163
1164 // Do not send events to the secondaryEventReceiver anymore, the
1165 // window is closed.
1166 secondaryEventReceiver = null;
1167
92554d64
KL
1168 // Wake the secondary thread, it will wake the primary as it
1169 // exits.
1170 synchronized (secondaryEventHandler) {
1171 secondaryEventHandler.notify();
48e27807
KL
1172 }
1173 }
48e27807
KL
1174 }
1175
1176 /**
1177 * Switch to the next window.
1178 *
1179 * @param forward if true, then switch to the next window in the list,
1180 * otherwise switch to the previous window in the list
1181 */
1182 public final void switchWindow(final boolean forward) {
48e27807 1183 // Only switch if there are multiple windows
fca67db0 1184 if (windows.size() < 2) {
48e27807
KL
1185 return;
1186 }
1187
bb35d919
KL
1188 synchronized (windows) {
1189
1190 // Swap z/active between active window and the next in the list
1191 int activeWindowI = -1;
1192 for (int i = 0; i < windows.size(); i++) {
7c870d89 1193 if (windows.get(i).isActive()) {
bb35d919
KL
1194 activeWindowI = i;
1195 break;
1196 }
48e27807 1197 }
bb35d919 1198 assert (activeWindowI >= 0);
48e27807 1199
bb35d919
KL
1200 // Do not switch if a window is modal
1201 if (windows.get(activeWindowI).isModal()) {
1202 return;
1203 }
48e27807 1204
bb35d919
KL
1205 int nextWindowI;
1206 if (forward) {
1207 nextWindowI = (activeWindowI + 1) % windows.size();
48e27807 1208 } else {
bb35d919
KL
1209 if (activeWindowI == 0) {
1210 nextWindowI = windows.size() - 1;
1211 } else {
1212 nextWindowI = activeWindowI - 1;
1213 }
48e27807 1214 }
bb35d919
KL
1215 windows.get(activeWindowI).setActive(false);
1216 windows.get(activeWindowI).setZ(windows.get(nextWindowI).getZ());
efb7af1f 1217 windows.get(activeWindowI).onUnfocus();
bb35d919
KL
1218 windows.get(nextWindowI).setZ(0);
1219 windows.get(nextWindowI).setActive(true);
efb7af1f 1220 windows.get(nextWindowI).onFocus();
bb35d919
KL
1221
1222 } // synchronized (windows)
48e27807 1223
48e27807
KL
1224 }
1225
1226 /**
1227 * Add a window to my window list and make it active.
1228 *
1229 * @param window new window to add
1230 */
1231 public final void addWindow(final TWindow window) {
bb35d919
KL
1232 synchronized (windows) {
1233 // Do not allow a modal window to spawn a non-modal window
1234 if ((windows.size() > 0) && (windows.get(0).isModal())) {
1235 assert (window.isModal());
1236 }
1237 for (TWindow w: windows) {
efb7af1f
KL
1238 if (w.isActive()) {
1239 w.setActive(false);
1240 w.onUnfocus();
1241 }
bb35d919
KL
1242 w.setZ(w.getZ() + 1);
1243 }
1244 windows.add(window);
bb35d919 1245 window.setZ(0);
efb7af1f
KL
1246 window.setActive(true);
1247 window.onFocus();
48e27807 1248 }
48e27807
KL
1249 }
1250
fca67db0
KL
1251 /**
1252 * Check if there is a system-modal window on top.
1253 *
1254 * @return true if the active window is modal
1255 */
1256 private boolean modalWindowActive() {
1257 if (windows.size() == 0) {
1258 return false;
1259 }
1260 return windows.get(windows.size() - 1).isModal();
1261 }
1262
1263 /**
1264 * Check if a mouse event would hit either the active menu or any open
1265 * sub-menus.
1266 *
1267 * @param mouse mouse event
1268 * @return true if the mouse would hit the active menu or an open
1269 * sub-menu
1270 */
1271 private boolean mouseOnMenu(final TMouseEvent mouse) {
1272 assert (activeMenu != null);
1273 List<TMenu> menus = new LinkedList<TMenu>(subMenus);
1274 Collections.reverse(menus);
1275 for (TMenu menu: menus) {
1276 if (menu.mouseWouldHit(mouse)) {
1277 return true;
1278 }
1279 }
1280 return activeMenu.mouseWouldHit(mouse);
1281 }
1282
1283 /**
1284 * See if we need to switch window or activate the menu based on
1285 * a mouse click.
1286 *
1287 * @param mouse mouse event
1288 */
1289 private void checkSwitchFocus(final TMouseEvent mouse) {
1290
1291 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1292 && (activeMenu != null)
1293 && (mouse.getAbsoluteY() != 0)
1294 && (!mouseOnMenu(mouse))
1295 ) {
1296 // They clicked outside the active menu, turn it off
1297 activeMenu.setActive(false);
1298 activeMenu = null;
1299 for (TMenu menu: subMenus) {
1300 menu.setActive(false);
1301 }
1302 subMenus.clear();
1303 // Continue checks
1304 }
1305
1306 // See if they hit the menu bar
1307 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
7c870d89 1308 && (mouse.isMouse1())
fca67db0
KL
1309 && (!modalWindowActive())
1310 && (mouse.getAbsoluteY() == 0)
1311 ) {
1312
1313 for (TMenu menu: subMenus) {
1314 menu.setActive(false);
1315 }
1316 subMenus.clear();
1317
1318 // They selected the menu, go activate it
1319 for (TMenu menu: menus) {
1320 if ((mouse.getAbsoluteX() >= menu.getX())
1321 && (mouse.getAbsoluteX() < menu.getX()
1322 + menu.getTitle().length() + 2)
1323 ) {
1324 menu.setActive(true);
1325 activeMenu = menu;
1326 } else {
1327 menu.setActive(false);
1328 }
1329 }
fca67db0
KL
1330 return;
1331 }
1332
1333 // See if they hit the menu bar
1334 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
7c870d89 1335 && (mouse.isMouse1())
fca67db0
KL
1336 && (activeMenu != null)
1337 && (mouse.getAbsoluteY() == 0)
1338 ) {
1339
1340 TMenu oldMenu = activeMenu;
1341 for (TMenu menu: subMenus) {
1342 menu.setActive(false);
1343 }
1344 subMenus.clear();
1345
1346 // See if we should switch menus
1347 for (TMenu menu: menus) {
1348 if ((mouse.getAbsoluteX() >= menu.getX())
1349 && (mouse.getAbsoluteX() < menu.getX()
1350 + menu.getTitle().length() + 2)
1351 ) {
1352 menu.setActive(true);
1353 activeMenu = menu;
1354 }
1355 }
1356 if (oldMenu != activeMenu) {
1357 // They switched menus
1358 oldMenu.setActive(false);
1359 }
fca67db0
KL
1360 return;
1361 }
1362
1363 // Only switch if there are multiple windows
1364 if (windows.size() < 2) {
1365 return;
1366 }
1367
1368 // Switch on the upclick
1369 if (mouse.getType() != TMouseEvent.Type.MOUSE_UP) {
1370 return;
1371 }
1372
bb35d919
KL
1373 synchronized (windows) {
1374 Collections.sort(windows);
1375 if (windows.get(0).isModal()) {
1376 // Modal windows don't switch
1377 return;
1378 }
fca67db0 1379
bb35d919
KL
1380 for (TWindow window: windows) {
1381 assert (!window.isModal());
1382 if (window.mouseWouldHit(mouse)) {
1383 if (window == windows.get(0)) {
1384 // Clicked on the same window, nothing to do
1385 return;
1386 }
1387
1388 // We will be switching to another window
7c870d89
KL
1389 assert (windows.get(0).isActive());
1390 assert (!window.isActive());
efb7af1f 1391 windows.get(0).onUnfocus();
bb35d919
KL
1392 windows.get(0).setActive(false);
1393 windows.get(0).setZ(window.getZ());
1394 window.setZ(0);
1395 window.setActive(true);
efb7af1f 1396 window.onFocus();
fca67db0
KL
1397 return;
1398 }
fca67db0
KL
1399 }
1400 }
1401
1402 // Clicked on the background, nothing to do
1403 return;
1404 }
1405
1406 /**
1407 * Turn off the menu.
1408 */
928811d8 1409 public final void closeMenu() {
fca67db0
KL
1410 if (activeMenu != null) {
1411 activeMenu.setActive(false);
1412 activeMenu = null;
1413 for (TMenu menu: subMenus) {
1414 menu.setActive(false);
1415 }
1416 subMenus.clear();
1417 }
fca67db0
KL
1418 }
1419
1420 /**
1421 * Turn off a sub-menu.
1422 */
928811d8 1423 public final void closeSubMenu() {
fca67db0
KL
1424 assert (activeMenu != null);
1425 TMenu item = subMenus.get(subMenus.size() - 1);
1426 assert (item != null);
1427 item.setActive(false);
1428 subMenus.remove(subMenus.size() - 1);
fca67db0
KL
1429 }
1430
1431 /**
1432 * Switch to the next menu.
1433 *
1434 * @param forward if true, then switch to the next menu in the list,
1435 * otherwise switch to the previous menu in the list
1436 */
928811d8 1437 public final void switchMenu(final boolean forward) {
fca67db0
KL
1438 assert (activeMenu != null);
1439
1440 for (TMenu menu: subMenus) {
1441 menu.setActive(false);
1442 }
1443 subMenus.clear();
1444
1445 for (int i = 0; i < menus.size(); i++) {
1446 if (activeMenu == menus.get(i)) {
1447 if (forward) {
1448 if (i < menus.size() - 1) {
1449 i++;
1450 }
1451 } else {
1452 if (i > 0) {
1453 i--;
1454 }
1455 }
1456 activeMenu.setActive(false);
1457 activeMenu = menus.get(i);
1458 activeMenu.setActive(true);
fca67db0
KL
1459 return;
1460 }
1461 }
1462 }
1463
1464 /**
1465 * Method that TApplication subclasses can override to handle menu or
1466 * posted command events.
1467 *
1468 * @param command command event
1469 * @return if true, this event was consumed
1470 */
1471 protected boolean onCommand(final TCommandEvent command) {
fca67db0
KL
1472 // Default: handle cmExit
1473 if (command.equals(cmExit)) {
1474 if (messageBox("Confirmation", "Exit application?",
c6940ed9 1475 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
fca67db0
KL
1476 quit = true;
1477 }
fca67db0
KL
1478 return true;
1479 }
1480
1481 if (command.equals(cmShell)) {
34a42e78 1482 openTerminal(0, 0, TWindow.RESIZABLE);
fca67db0
KL
1483 return true;
1484 }
1485
1486 if (command.equals(cmTile)) {
1487 tileWindows();
fca67db0
KL
1488 return true;
1489 }
1490 if (command.equals(cmCascade)) {
1491 cascadeWindows();
fca67db0
KL
1492 return true;
1493 }
1494 if (command.equals(cmCloseAll)) {
1495 closeAllWindows();
fca67db0
KL
1496 return true;
1497 }
c6940ed9 1498
fca67db0
KL
1499 return false;
1500 }
1501
1502 /**
1503 * Method that TApplication subclasses can override to handle menu
1504 * events.
1505 *
1506 * @param menu menu event
1507 * @return if true, this event was consumed
1508 */
1509 protected boolean onMenu(final TMenuEvent menu) {
1510
fca67db0 1511 // Default: handle MID_EXIT
8e688b92 1512 if (menu.getId() == TMenu.MID_EXIT) {
fca67db0 1513 if (messageBox("Confirmation", "Exit application?",
c6940ed9 1514 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
fca67db0
KL
1515 quit = true;
1516 }
fca67db0
KL
1517 return true;
1518 }
1519
34a42e78
KL
1520 if (menu.getId() == TMenu.MID_SHELL) {
1521 openTerminal(0, 0, TWindow.RESIZABLE);
fca67db0
KL
1522 return true;
1523 }
1524
8e688b92 1525 if (menu.getId() == TMenu.MID_TILE) {
fca67db0 1526 tileWindows();
fca67db0
KL
1527 return true;
1528 }
8e688b92 1529 if (menu.getId() == TMenu.MID_CASCADE) {
fca67db0 1530 cascadeWindows();
fca67db0
KL
1531 return true;
1532 }
8e688b92 1533 if (menu.getId() == TMenu.MID_CLOSE_ALL) {
fca67db0 1534 closeAllWindows();
fca67db0
KL
1535 return true;
1536 }
fca67db0
KL
1537 return false;
1538 }
1539
1540 /**
1541 * Method that TApplication subclasses can override to handle keystrokes.
1542 *
1543 * @param keypress keystroke event
1544 * @return if true, this event was consumed
1545 */
1546 protected boolean onKeypress(final TKeypressEvent keypress) {
1547 // Default: only menu shortcuts
1548
1549 // Process Alt-F, Alt-E, etc. menu shortcut keys
7c870d89
KL
1550 if (!keypress.getKey().isFnKey()
1551 && keypress.getKey().isAlt()
1552 && !keypress.getKey().isCtrl()
fca67db0
KL
1553 && (activeMenu == null)
1554 ) {
1555
1556 assert (subMenus.size() == 0);
1557
1558 for (TMenu menu: menus) {
1559 if (Character.toLowerCase(menu.getMnemonic().getShortcut())
7c870d89 1560 == Character.toLowerCase(keypress.getKey().getChar())
fca67db0
KL
1561 ) {
1562 activeMenu = menu;
1563 menu.setActive(true);
fca67db0
KL
1564 return true;
1565 }
1566 }
1567 }
1568
1569 return false;
1570 }
48e27807 1571
928811d8 1572 /**
efb7af1f
KL
1573 * Add a menu item to the global list. If it has a keyboard accelerator,
1574 * that will be added the global hash.
928811d8 1575 *
efb7af1f 1576 * @param item the menu item
928811d8 1577 */
efb7af1f
KL
1578 public final void addMenuItem(final TMenuItem item) {
1579 menuItems.add(item);
1580
1581 TKeypress key = item.getKey();
1582 if (key != null) {
1583 synchronized (accelerators) {
1584 assert (accelerators.get(key) == null);
1585 accelerators.put(key.toLowerCase(), item);
1586 }
1587 }
1588 }
1589
1590 /**
1591 * Disable one menu item.
1592 *
1593 * @param id the menu item ID
1594 */
1595 public final void disableMenuItem(final int id) {
1596 for (TMenuItem item: menuItems) {
1597 if (item.getId() == id) {
1598 item.setEnabled(false);
1599 }
1600 }
1601 }
e826b451 1602
efb7af1f
KL
1603 /**
1604 * Disable the range of menu items with ID's between lower and upper,
1605 * inclusive.
1606 *
1607 * @param lower the lowest menu item ID
1608 * @param upper the highest menu item ID
1609 */
1610 public final void disableMenuItems(final int lower, final int upper) {
1611 for (TMenuItem item: menuItems) {
1612 if ((item.getId() >= lower) && (item.getId() <= upper)) {
1613 item.setEnabled(false);
1614 }
1615 }
1616 }
1617
1618 /**
1619 * Enable one menu item.
1620 *
1621 * @param id the menu item ID
1622 */
1623 public final void enableMenuItem(final int id) {
1624 for (TMenuItem item: menuItems) {
1625 if (item.getId() == id) {
1626 item.setEnabled(true);
1627 }
1628 }
1629 }
1630
1631 /**
1632 * Enable the range of menu items with ID's between lower and upper,
1633 * inclusive.
1634 *
1635 * @param lower the lowest menu item ID
1636 * @param upper the highest menu item ID
1637 */
1638 public final void enableMenuItems(final int lower, final int upper) {
1639 for (TMenuItem item: menuItems) {
1640 if ((item.getId() >= lower) && (item.getId() <= upper)) {
1641 item.setEnabled(true);
1642 }
e826b451 1643 }
928811d8
KL
1644 }
1645
1646 /**
1647 * Recompute menu x positions based on their title length.
1648 */
1649 public final void recomputeMenuX() {
1650 int x = 0;
1651 for (TMenu menu: menus) {
1652 menu.setX(x);
1653 x += menu.getTitle().length() + 2;
1654 }
1655 }
1656
1657 /**
1658 * Post an event to process and turn off the menu.
1659 *
1660 * @param event new event to add to the queue
1661 */
1662 public final void addMenuEvent(final TInputEvent event) {
8e688b92
KL
1663 synchronized (fillEventQueue) {
1664 fillEventQueue.add(event);
1665 }
928811d8
KL
1666 closeMenu();
1667 }
1668
1669 /**
1670 * Add a sub-menu to the list of open sub-menus.
1671 *
1672 * @param menu sub-menu
1673 */
1674 public final void addSubMenu(final TMenu menu) {
1675 subMenus.add(menu);
1676 }
1677
8e688b92
KL
1678 /**
1679 * Convenience function to add a top-level menu.
1680 *
1681 * @param title menu title
1682 * @return the new menu
1683 */
87a17f3c 1684 public final TMenu addMenu(final String title) {
8e688b92
KL
1685 int x = 0;
1686 int y = 0;
1687 TMenu menu = new TMenu(this, x, y, title);
1688 menus.add(menu);
1689 recomputeMenuX();
1690 return menu;
1691 }
1692
1693 /**
1694 * Convenience function to add a default "File" menu.
1695 *
1696 * @return the new menu
1697 */
1698 public final TMenu addFileMenu() {
1699 TMenu fileMenu = addMenu("&File");
1700 fileMenu.addDefaultItem(TMenu.MID_OPEN_FILE);
1701 fileMenu.addSeparator();
1702 fileMenu.addDefaultItem(TMenu.MID_SHELL);
1703 fileMenu.addDefaultItem(TMenu.MID_EXIT);
1704 return fileMenu;
1705 }
1706
1707 /**
1708 * Convenience function to add a default "Edit" menu.
1709 *
1710 * @return the new menu
1711 */
1712 public final TMenu addEditMenu() {
1713 TMenu editMenu = addMenu("&Edit");
1714 editMenu.addDefaultItem(TMenu.MID_CUT);
1715 editMenu.addDefaultItem(TMenu.MID_COPY);
1716 editMenu.addDefaultItem(TMenu.MID_PASTE);
1717 editMenu.addDefaultItem(TMenu.MID_CLEAR);
1718 return editMenu;
1719 }
1720
1721 /**
1722 * Convenience function to add a default "Window" menu.
1723 *
1724 * @return the new menu
1725 */
c6940ed9 1726 public final TMenu addWindowMenu() {
8e688b92
KL
1727 TMenu windowMenu = addMenu("&Window");
1728 windowMenu.addDefaultItem(TMenu.MID_TILE);
1729 windowMenu.addDefaultItem(TMenu.MID_CASCADE);
1730 windowMenu.addDefaultItem(TMenu.MID_CLOSE_ALL);
1731 windowMenu.addSeparator();
1732 windowMenu.addDefaultItem(TMenu.MID_WINDOW_MOVE);
1733 windowMenu.addDefaultItem(TMenu.MID_WINDOW_ZOOM);
1734 windowMenu.addDefaultItem(TMenu.MID_WINDOW_NEXT);
1735 windowMenu.addDefaultItem(TMenu.MID_WINDOW_PREVIOUS);
1736 windowMenu.addDefaultItem(TMenu.MID_WINDOW_CLOSE);
1737 return windowMenu;
1738 }
1739
1740 /**
1741 * Close all open windows.
1742 */
1743 private void closeAllWindows() {
1744 // Don't do anything if we are in the menu
1745 if (activeMenu != null) {
1746 return;
1747 }
bb35d919
KL
1748
1749 synchronized (windows) {
1750 for (TWindow window: windows) {
1751 closeWindow(window);
1752 }
8e688b92
KL
1753 }
1754 }
1755
1756 /**
1757 * Re-layout the open windows as non-overlapping tiles. This produces
1758 * almost the same results as Turbo Pascal 7.0's IDE.
1759 */
1760 private void tileWindows() {
bb35d919
KL
1761 synchronized (windows) {
1762 // Don't do anything if we are in the menu
1763 if (activeMenu != null) {
1764 return;
8e688b92 1765 }
bb35d919
KL
1766 int z = windows.size();
1767 if (z == 0) {
1768 return;
1769 }
1770 int a = 0;
1771 int b = 0;
1772 a = (int)(Math.sqrt(z));
1773 int c = 0;
1774 while (c < a) {
1775 b = (z - c) / a;
1776 if (((a * b) + c) == z) {
1777 break;
1778 }
1779 c++;
8e688b92 1780 }
bb35d919
KL
1781 assert (a > 0);
1782 assert (b > 0);
1783 assert (c < a);
1784 int newWidth = (getScreen().getWidth() / a);
1785 int newHeight1 = ((getScreen().getHeight() - 1) / b);
1786 int newHeight2 = ((getScreen().getHeight() - 1) / (b + c));
1787
1788 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1789 Collections.sort(sorted);
1790 Collections.reverse(sorted);
1791 for (int i = 0; i < sorted.size(); i++) {
1792 int logicalX = i / b;
1793 int logicalY = i % b;
1794 if (i >= ((a - 1) * b)) {
1795 logicalX = a - 1;
1796 logicalY = i - ((a - 1) * b);
1797 }
8e688b92 1798
bb35d919
KL
1799 TWindow w = sorted.get(i);
1800 w.setX(logicalX * newWidth);
1801 w.setWidth(newWidth);
1802 if (i >= ((a - 1) * b)) {
1803 w.setY((logicalY * newHeight2) + 1);
1804 w.setHeight(newHeight2);
1805 } else {
1806 w.setY((logicalY * newHeight1) + 1);
1807 w.setHeight(newHeight1);
1808 }
8e688b92
KL
1809 }
1810 }
1811 }
1812
1813 /**
1814 * Re-layout the open windows as overlapping cascaded windows.
1815 */
1816 private void cascadeWindows() {
bb35d919
KL
1817 synchronized (windows) {
1818 // Don't do anything if we are in the menu
1819 if (activeMenu != null) {
1820 return;
8e688b92 1821 }
bb35d919
KL
1822 int x = 0;
1823 int y = 1;
1824 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1825 Collections.sort(sorted);
1826 Collections.reverse(sorted);
1827 for (TWindow window: sorted) {
1828 window.setX(x);
1829 window.setY(y);
1830 x++;
1831 y++;
1832 if (x > getScreen().getWidth()) {
1833 x = 0;
1834 }
1835 if (y >= getScreen().getHeight()) {
1836 y = 1;
1837 }
8e688b92
KL
1838 }
1839 }
1840 }
1841
d502a0e9
KL
1842 /**
1843 * Convenience function to add a timer.
1844 *
1845 * @param duration number of milliseconds to wait between ticks
1846 * @param recurring if true, re-schedule this timer after every tick
1847 * @param action function to call when button is pressed
c6940ed9 1848 * @return the timer
d502a0e9
KL
1849 */
1850 public final TTimer addTimer(final long duration, final boolean recurring,
1851 final TAction action) {
1852
1853 TTimer timer = new TTimer(duration, recurring, action);
1854 synchronized (timers) {
1855 timers.add(timer);
1856 }
1857 return timer;
1858 }
1859
1860 /**
1861 * Convenience function to remove a timer.
1862 *
1863 * @param timer timer to remove
1864 */
1865 public final void removeTimer(final TTimer timer) {
1866 synchronized (timers) {
1867 timers.remove(timer);
1868 }
1869 }
1870
c6940ed9
KL
1871 /**
1872 * Convenience function to spawn a message box.
1873 *
1874 * @param title window title, will be centered along the top border
1875 * @param caption message to display. Use embedded newlines to get a
1876 * multi-line box.
1877 * @return the new message box
1878 */
1879 public final TMessageBox messageBox(final String title,
1880 final String caption) {
1881
1882 return new TMessageBox(this, title, caption, TMessageBox.Type.OK);
1883 }
1884
1885 /**
1886 * Convenience function to spawn a message box.
1887 *
1888 * @param title window title, will be centered along the top border
1889 * @param caption message to display. Use embedded newlines to get a
1890 * multi-line box.
1891 * @param type one of the TMessageBox.Type constants. Default is
1892 * Type.OK.
1893 * @return the new message box
1894 */
1895 public final TMessageBox messageBox(final String title,
1896 final String caption, final TMessageBox.Type type) {
1897
1898 return new TMessageBox(this, title, caption, type);
1899 }
1900
1901 /**
1902 * Convenience function to spawn an input box.
1903 *
1904 * @param title window title, will be centered along the top border
1905 * @param caption message to display. Use embedded newlines to get a
1906 * multi-line box.
1907 * @return the new input box
1908 */
1909 public final TInputBox inputBox(final String title, final String caption) {
1910
1911 return new TInputBox(this, title, caption);
1912 }
1913
1914 /**
1915 * Convenience function to spawn an input box.
1916 *
1917 * @param title window title, will be centered along the top border
1918 * @param caption message to display. Use embedded newlines to get a
1919 * multi-line box.
1920 * @param text initial text to seed the field with
1921 * @return the new input box
1922 */
1923 public final TInputBox inputBox(final String title, final String caption,
1924 final String text) {
1925
1926 return new TInputBox(this, title, caption, text);
1927 }
1ac2ccb1 1928
34a42e78
KL
1929 /**
1930 * Convenience function to open a terminal window.
1931 *
1932 * @param x column relative to parent
1933 * @param y row relative to parent
1934 * @return the terminal new window
1935 */
1936 public final TTerminalWindow openTerminal(final int x, final int y) {
1937 return openTerminal(x, y, TWindow.RESIZABLE);
1938 }
1939
1940 /**
1941 * Convenience function to open a terminal window.
1942 *
1943 * @param x column relative to parent
1944 * @param y row relative to parent
1945 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1946 * @return the terminal new window
1947 */
1948 public final TTerminalWindow openTerminal(final int x, final int y,
1949 final int flags) {
1950
1951 return new TTerminalWindow(this, x, y, flags);
1952 }
1953
0d47c546
KL
1954 /**
1955 * Convenience function to spawn an file open box.
1956 *
1957 * @param path path of selected file
1958 * @return the result of the new file open box
329fd62e 1959 * @throws IOException if java.io operation throws
0d47c546
KL
1960 */
1961 public final String fileOpenBox(final String path) throws IOException {
1962
1963 TFileOpenBox box = new TFileOpenBox(this, path, TFileOpenBox.Type.OPEN);
1964 return box.getFilename();
1965 }
1966
1967 /**
1968 * Convenience function to spawn an file open box.
1969 *
1970 * @param path path of selected file
1971 * @param type one of the Type constants
1972 * @return the result of the new file open box
329fd62e 1973 * @throws IOException if java.io operation throws
0d47c546
KL
1974 */
1975 public final String fileOpenBox(final String path,
1976 final TFileOpenBox.Type type) throws IOException {
1977
1978 TFileOpenBox box = new TFileOpenBox(this, path, type);
1979 return box.getFilename();
1980 }
1981
7d4115a5 1982}