d0c34bf0303adbe99e917f6afbcd278032915af6
[fanfix.git] / src / jexer / TApplication.java
1 /**
2 * Jexer - Java Text User Interface
3 *
4 * License: LGPLv3 or later
5 *
6 * This module is licensed under the GNU Lesser General Public License
7 * Version 3. Please see the file "COPYING" in this directory for more
8 * information about the GNU Lesser General Public License Version 3.
9 *
10 * Copyright (C) 2015 Kevin Lamonte
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 3 of
15 * the License, or (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this program; if not, see
24 * http://www.gnu.org/licenses/, or write to the Free Software
25 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 * 02110-1301 USA
27 *
28 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
29 * @version 1
30 */
31 package jexer;
32
33 import java.io.InputStream;
34 import java.io.IOException;
35 import java.io.OutputStream;
36 import java.io.UnsupportedEncodingException;
37 import java.util.Collections;
38 import java.util.Date;
39 import java.util.HashMap;
40 import java.util.ArrayList;
41 import java.util.LinkedList;
42 import java.util.List;
43 import java.util.Map;
44
45 import jexer.bits.CellAttributes;
46 import jexer.bits.ColorTheme;
47 import jexer.bits.GraphicsChars;
48 import jexer.event.TCommandEvent;
49 import jexer.event.TInputEvent;
50 import jexer.event.TKeypressEvent;
51 import jexer.event.TMenuEvent;
52 import jexer.event.TMouseEvent;
53 import jexer.event.TResizeEvent;
54 import jexer.backend.Backend;
55 import jexer.backend.SwingBackend;
56 import jexer.backend.ECMA48Backend;
57 import jexer.io.Screen;
58 import jexer.menu.TMenu;
59 import jexer.menu.TMenuItem;
60 import static jexer.TCommand.*;
61
62 /**
63 * TApplication sets up a full Text User Interface application.
64 */
65 public class TApplication implements Runnable {
66
67 /**
68 * If true, emit thread stuff to System.err.
69 */
70 private static final boolean debugThreads = false;
71
72 /**
73 * If true, emit events being processed to System.err.
74 */
75 private static final boolean debugEvents = false;
76
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 /**
92 * Synonym for ECMA48
93 */
94 XTERM
95 }
96
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 }
143
144 synchronized (this) {
145 if (debugThreads) {
146 System.err.printf("%s %s sleep\n", this,
147 primary ? "primary" : "secondary");
148 }
149
150 this.wait();
151
152 if (debugThreads) {
153 System.err.printf("%s %s AWAKE\n", this,
154 primary ? "primary" : "secondary");
155 }
156
157 if ((!primary)
158 && (application.secondaryEventReceiver == null)
159 ) {
160 // Secondary thread, emergency exit. If we
161 // got here then something went wrong with
162 // the handoff between yield() and
163 // closeWindow().
164 synchronized (application.primaryEventHandler) {
165 application.primaryEventHandler.notify();
166 }
167 application.secondaryEventHandler = null;
168 throw new RuntimeException(
169 "secondary exited at wrong time");
170 }
171 break;
172 }
173 } catch (InterruptedException e) {
174 // SQUASH
175 }
176 }
177
178 // Wait for drawAll() or doIdle() to be done, then handle the
179 // events.
180 boolean oldLock = lockHandleEvent();
181 assert (oldLock == false);
182
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 }
192 application.repaint = true;
193 if (primary) {
194 primaryHandleEvent(event);
195 } else {
196 secondaryHandleEvent(event);
197 }
198 if ((!primary)
199 && (application.secondaryEventReceiver == null)
200 ) {
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
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!
214 return;
215 }
216 } // for (;;)
217
218 // Unlock. Either I am primary thread, or I am secondary
219 // thread and still running.
220 oldLock = unlockHandleEvent();
221 assert (oldLock == true);
222
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();
227 }
228
229 } // while (true) (main runnable loop)
230 }
231 }
232
233 /**
234 * The primary event handler thread.
235 */
236 private volatile WidgetEventHandler primaryEventHandler;
237
238 /**
239 * The secondary event handler thread.
240 */
241 private volatile WidgetEventHandler secondaryEventHandler;
242
243 /**
244 * The widget receiving events from the secondary event handler thread.
245 */
246 private volatile TWidget secondaryEventReceiver;
247
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
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
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.
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 }
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().
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 }
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
368 /**
369 * Access to the physical screen, keyboard, and mouse.
370 */
371 private Backend backend;
372
373 /**
374 * Get the Screen.
375 *
376 * @return the Screen
377 */
378 public final Screen getScreen() {
379 return backend.getScreen();
380 }
381
382 /**
383 * Actual mouse coordinate X.
384 */
385 private int mouseX;
386
387 /**
388 * Actual mouse coordinate Y.
389 */
390 private int mouseY;
391
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
402 /**
403 * Event queue that is filled by run().
404 */
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;
412
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
428 /**
429 * Active keyboard accelerators.
430 */
431 private Map<TKeypress, TMenuItem> accelerators;
432
433 /**
434 * Windows and widgets pull colors from this ColorTheme.
435 */
436 private ColorTheme theme;
437
438 /**
439 * Get the color theme.
440 *
441 * @return the theme
442 */
443 public final ColorTheme getTheme() {
444 return theme;
445 }
446
447 /**
448 * The top-level windows (but not menus).
449 */
450 private List<TWindow> windows;
451
452 /**
453 * Timers that are being ticked.
454 */
455 private List<TTimer> timers;
456
457 /**
458 * When true, exit the application.
459 */
460 private volatile boolean quit = false;
461
462 /**
463 * When true, repaint the entire screen.
464 */
465 private volatile boolean repaint = true;
466
467 /**
468 * Y coordinate of the top edge of the desktop. For now this is a
469 * constant. Someday it would be nice to have a multi-line menu or
470 * toolbars.
471 */
472 private static final int desktopTop = 1;
473
474 /**
475 * Get Y coordinate of the top edge of the desktop.
476 *
477 * @return Y coordinate of the top edge of the desktop
478 */
479 public final int getDesktopTop() {
480 return desktopTop;
481 }
482
483 /**
484 * Y coordinate of the bottom edge of the desktop.
485 */
486 private int desktopBottom;
487
488 /**
489 * Get Y coordinate of the bottom edge of the desktop.
490 *
491 * @return Y coordinate of the bottom edge of the desktop
492 */
493 public final int getDesktopBottom() {
494 return desktopBottom;
495 }
496
497 /**
498 * Public constructor.
499 *
500 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
501 * BackendType.SWING
502 * @throws UnsupportedEncodingException if an exception is thrown when
503 * creating the InputStreamReader
504 */
505 public TApplication(final BackendType backendType)
506 throws UnsupportedEncodingException {
507
508 switch (backendType) {
509 case SWING:
510 backend = new SwingBackend(this);
511 break;
512 case XTERM:
513 // Fall through...
514 case ECMA48:
515 backend = new ECMA48Backend(this, null, null);
516 }
517 TApplicationImpl();
518 }
519
520 /**
521 * Public constructor. The backend type will be BackendType.ECMA48.
522 *
523 * @param input an InputStream connected to the remote user, or null for
524 * System.in. If System.in is used, then on non-Windows systems it will
525 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
526 * mode. input is always converted to a Reader with UTF-8 encoding.
527 * @param output an OutputStream connected to the remote user, or null
528 * for System.out. output is always converted to a Writer with UTF-8
529 * encoding.
530 * @throws UnsupportedEncodingException if an exception is thrown when
531 * creating the InputStreamReader
532 */
533 public TApplication(final InputStream input,
534 final OutputStream output) throws UnsupportedEncodingException {
535
536 backend = new ECMA48Backend(this, input, output);
537 TApplicationImpl();
538 }
539
540 /**
541 * Public constructor. This hook enables use with new non-Jexer
542 * backends.
543 *
544 * @param backend a Backend that is already ready to go.
545 */
546 public TApplication(final Backend backend) {
547 this.backend = backend;
548 TApplicationImpl();
549 }
550
551 /**
552 * Finish construction once the backend is set.
553 */
554 private void TApplicationImpl() {
555 theme = new ColorTheme();
556 desktopBottom = getScreen().getHeight() - 1;
557 fillEventQueue = new ArrayList<TInputEvent>();
558 drainEventQueue = new ArrayList<TInputEvent>();
559 windows = new LinkedList<TWindow>();
560 menus = new LinkedList<TMenu>();
561 subMenus = new LinkedList<TMenu>();
562 timers = new LinkedList<TTimer>();
563 accelerators = new HashMap<TKeypress, TMenuItem>();
564
565 // Setup the main consumer thread
566 primaryEventHandler = new WidgetEventHandler(this, true);
567 (new Thread(primaryEventHandler)).start();
568 }
569
570 /**
571 * Invert the cell color at a position. This is used to track the mouse.
572 *
573 * @param x column position
574 * @param y row position
575 */
576 private void invertCell(final int x, final int y) {
577 synchronized (getScreen()) {
578 CellAttributes attr = getScreen().getAttrXY(x, y);
579 attr.setForeColor(attr.getForeColor().invert());
580 attr.setBackColor(attr.getBackColor().invert());
581 getScreen().putAttrXY(x, y, attr, false);
582 }
583 }
584
585 /**
586 * Draw everything.
587 */
588 private void drawAll() {
589 if (debugThreads) {
590 System.err.printf("drawAll() enter\n");
591 }
592
593 if (!repaint) {
594 if ((oldMouseX != mouseX) || (oldMouseY != mouseY)) {
595 // The only thing that has happened is the mouse moved.
596 // Clear the old position and draw the new position.
597 invertCell(oldMouseX, oldMouseY);
598 invertCell(mouseX, mouseY);
599 oldMouseX = mouseX;
600 oldMouseY = mouseY;
601 }
602 if (getScreen().isDirty()) {
603 backend.flushScreen();
604 }
605 return;
606 }
607
608 if (debugThreads) {
609 System.err.printf("drawAll() REDRAW\n");
610 }
611
612 // If true, the cursor is not visible
613 boolean cursor = false;
614
615 // Start with a clean screen
616 getScreen().clear();
617
618 // Draw the background
619 CellAttributes background = theme.getColor("tapplication.background");
620 getScreen().putAll(GraphicsChars.HATCH, background);
621
622 // Draw each window in reverse Z order
623 List<TWindow> sorted = new LinkedList<TWindow>(windows);
624 Collections.sort(sorted);
625 Collections.reverse(sorted);
626 for (TWindow window: sorted) {
627 window.drawChildren();
628 }
629
630 // Draw the blank menubar line - reset the screen clipping first so
631 // it won't trim it out.
632 getScreen().resetClipping();
633 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
634 theme.getColor("tmenu"));
635 // Now draw the menus.
636 int x = 1;
637 for (TMenu menu: menus) {
638 CellAttributes menuColor;
639 CellAttributes menuMnemonicColor;
640 if (menu.isActive()) {
641 menuColor = theme.getColor("tmenu.highlighted");
642 menuMnemonicColor = theme.getColor("tmenu.mnemonic.highlighted");
643 } else {
644 menuColor = theme.getColor("tmenu");
645 menuMnemonicColor = theme.getColor("tmenu.mnemonic");
646 }
647 // Draw the menu title
648 getScreen().hLineXY(x, 0, menu.getTitle().length() + 2, ' ',
649 menuColor);
650 getScreen().putStringXY(x + 1, 0, menu.getTitle(), menuColor);
651 // Draw the highlight character
652 getScreen().putCharXY(x + 1 + menu.getMnemonic().getShortcutIdx(),
653 0, menu.getMnemonic().getShortcut(), menuMnemonicColor);
654
655 if (menu.isActive()) {
656 menu.drawChildren();
657 // Reset the screen clipping so we can draw the next title.
658 getScreen().resetClipping();
659 }
660 x += menu.getTitle().length() + 2;
661 }
662
663 for (TMenu menu: subMenus) {
664 // Reset the screen clipping so we can draw the next sub-menu.
665 getScreen().resetClipping();
666 menu.drawChildren();
667 }
668
669 // Draw the mouse pointer
670 invertCell(mouseX, mouseY);
671
672 // Place the cursor if it is visible
673 TWidget activeWidget = null;
674 if (sorted.size() > 0) {
675 activeWidget = sorted.get(sorted.size() - 1).getActiveChild();
676 if (activeWidget.isCursorVisible()) {
677 getScreen().putCursor(true, activeWidget.getCursorAbsoluteX(),
678 activeWidget.getCursorAbsoluteY());
679 cursor = true;
680 }
681 }
682
683 // Kill the cursor
684 if (!cursor) {
685 getScreen().hideCursor();
686 }
687
688 // Flush the screen contents
689 backend.flushScreen();
690
691 repaint = false;
692 }
693
694 /**
695 * Run this application until it exits.
696 */
697 public void run() {
698 while (!quit) {
699 // Timeout is in milliseconds, so default timeout after 1 second
700 // of inactivity.
701 long timeout = 0;
702
703 // If I've got no updates to render, wait for something from the
704 // backend or a timer.
705 if (!repaint
706 && ((mouseX == oldMouseX) && (mouseY == oldMouseY))
707 ) {
708 // Never sleep longer than 50 millis. We need time for
709 // windows with background tasks to update the display, and
710 // still flip buffers reasonably quickly in
711 // backend.flushPhysical().
712 timeout = getSleepTime(50);
713 }
714
715 if (timeout > 0) {
716 // As of now, I've got nothing to do: no I/O, nothing from
717 // the consumer threads, no timers that need to run ASAP. So
718 // wait until either the backend or the consumer threads have
719 // something to do.
720 try {
721 synchronized (this) {
722 this.wait(timeout);
723 }
724 } catch (InterruptedException e) {
725 // I'm awake and don't care why, let's see what's going
726 // on out there.
727 }
728 repaint = true;
729 }
730
731 // Prevent stepping on the primary or secondary event handler.
732 stopEventHandlers();
733
734 // Pull any pending I/O events
735 backend.getEvents(fillEventQueue);
736
737 // Dispatch each event to the appropriate handler, one at a time.
738 for (;;) {
739 TInputEvent event = null;
740 if (fillEventQueue.size() == 0) {
741 break;
742 }
743 event = fillEventQueue.remove(0);
744 metaHandleEvent(event);
745 }
746
747 // Wake a consumer thread if we have any pending events.
748 if (drainEventQueue.size() > 0) {
749 wakeEventHandler();
750 }
751
752 // Process timers and call doIdle()'s
753 doIdle();
754
755 // Update the screen
756 synchronized (getScreen()) {
757 drawAll();
758 }
759
760 // Let the event handlers run again.
761 startEventHandlers();
762
763 } // while (!quit)
764
765 // Shutdown the event consumer threads
766 if (secondaryEventHandler != null) {
767 synchronized (secondaryEventHandler) {
768 secondaryEventHandler.notify();
769 }
770 }
771 if (primaryEventHandler != null) {
772 synchronized (primaryEventHandler) {
773 primaryEventHandler.notify();
774 }
775 }
776
777 // Shutdown the user I/O thread(s)
778 backend.shutdown();
779
780 // Close all the windows. This gives them an opportunity to release
781 // resources.
782 closeAllWindows();
783
784 }
785
786 /**
787 * Peek at certain application-level events, add to eventQueue, and wake
788 * up the consuming Thread.
789 *
790 * @param event the input event to consume
791 */
792 private void metaHandleEvent(final TInputEvent event) {
793
794 if (debugEvents) {
795 System.err.printf(String.format("metaHandleEvents event: %s\n",
796 event)); System.err.flush();
797 }
798
799 if (quit) {
800 // Do no more processing if the application is already trying
801 // to exit.
802 return;
803 }
804
805 // Special application-wide events -------------------------------
806
807 // Abort everything
808 if (event instanceof TCommandEvent) {
809 TCommandEvent command = (TCommandEvent) event;
810 if (command.getCmd().equals(cmAbort)) {
811 quit = true;
812 return;
813 }
814 }
815
816 // Screen resize
817 if (event instanceof TResizeEvent) {
818 TResizeEvent resize = (TResizeEvent) event;
819 synchronized (getScreen()) {
820 getScreen().setDimensions(resize.getWidth(),
821 resize.getHeight());
822 desktopBottom = getScreen().getHeight() - 1;
823 mouseX = 0;
824 mouseY = 0;
825 oldMouseX = 0;
826 oldMouseY = 0;
827 }
828 return;
829 }
830
831 // Peek at the mouse position
832 if (event instanceof TMouseEvent) {
833 TMouseEvent mouse = (TMouseEvent) event;
834 synchronized (getScreen()) {
835 if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
836 oldMouseX = mouseX;
837 oldMouseY = mouseY;
838 mouseX = mouse.getX();
839 mouseY = mouse.getY();
840 }
841 }
842 }
843
844 // Put into the main queue
845 drainEventQueue.add(event);
846 }
847
848 /**
849 * Dispatch one event to the appropriate widget or application-level
850 * event handler. This is the primary event handler, it has the normal
851 * application-wide event handling.
852 *
853 * @param event the input event to consume
854 * @see #secondaryHandleEvent(TInputEvent event)
855 */
856 private void primaryHandleEvent(final TInputEvent event) {
857
858 if (debugEvents) {
859 System.err.printf("Handle event: %s\n", event);
860 }
861
862 // Special application-wide events -----------------------------------
863
864 // Peek at the mouse position
865 if (event instanceof TMouseEvent) {
866 // See if we need to switch focus to another window or the menu
867 checkSwitchFocus((TMouseEvent) event);
868 }
869
870 // Handle menu events
871 if ((activeMenu != null) && !(event instanceof TCommandEvent)) {
872 TMenu menu = activeMenu;
873
874 if (event instanceof TMouseEvent) {
875 TMouseEvent mouse = (TMouseEvent) event;
876
877 while (subMenus.size() > 0) {
878 TMenu subMenu = subMenus.get(subMenus.size() - 1);
879 if (subMenu.mouseWouldHit(mouse)) {
880 break;
881 }
882 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
883 && (!mouse.isMouse1())
884 && (!mouse.isMouse2())
885 && (!mouse.isMouse3())
886 && (!mouse.isMouseWheelUp())
887 && (!mouse.isMouseWheelDown())
888 ) {
889 break;
890 }
891 // We navigated away from a sub-menu, so close it
892 closeSubMenu();
893 }
894
895 // Convert the mouse relative x/y to menu coordinates
896 assert (mouse.getX() == mouse.getAbsoluteX());
897 assert (mouse.getY() == mouse.getAbsoluteY());
898 if (subMenus.size() > 0) {
899 menu = subMenus.get(subMenus.size() - 1);
900 }
901 mouse.setX(mouse.getX() - menu.getX());
902 mouse.setY(mouse.getY() - menu.getY());
903 }
904 menu.handleEvent(event);
905 return;
906 }
907
908 if (event instanceof TKeypressEvent) {
909 TKeypressEvent keypress = (TKeypressEvent) event;
910
911 // See if this key matches an accelerator, and if so dispatch the
912 // menu event.
913 TKeypress keypressLowercase = keypress.getKey().toLowerCase();
914 TMenuItem item = null;
915 synchronized (accelerators) {
916 item = accelerators.get(keypressLowercase);
917 }
918 if (item != null) {
919 if (item.isEnabled()) {
920 // Let the menu item dispatch
921 item.dispatch();
922 return;
923 }
924 }
925 // Handle the keypress
926 if (onKeypress(keypress)) {
927 return;
928 }
929 }
930
931 if (event instanceof TCommandEvent) {
932 if (onCommand((TCommandEvent) event)) {
933 return;
934 }
935 }
936
937 if (event instanceof TMenuEvent) {
938 if (onMenu((TMenuEvent) event)) {
939 return;
940 }
941 }
942
943 // Dispatch events to the active window -------------------------------
944 for (TWindow window: windows) {
945 if (window.isActive()) {
946 if (event instanceof TMouseEvent) {
947 TMouseEvent mouse = (TMouseEvent) event;
948 // Convert the mouse relative x/y to window coordinates
949 assert (mouse.getX() == mouse.getAbsoluteX());
950 assert (mouse.getY() == mouse.getAbsoluteY());
951 mouse.setX(mouse.getX() - window.getX());
952 mouse.setY(mouse.getY() - window.getY());
953 }
954 if (debugEvents) {
955 System.err.printf("TApplication dispatch event: %s\n",
956 event);
957 }
958 window.handleEvent(event);
959 break;
960 }
961 }
962 }
963 /**
964 * Dispatch one event to the appropriate widget or application-level
965 * event handler. This is the secondary event handler used by certain
966 * special dialogs (currently TMessageBox and TFileOpenBox).
967 *
968 * @param event the input event to consume
969 * @see #primaryHandleEvent(TInputEvent event)
970 */
971 private void secondaryHandleEvent(final TInputEvent event) {
972 secondaryEventReceiver.handleEvent(event);
973 }
974
975 /**
976 * Enable a widget to override the primary event thread.
977 *
978 * @param widget widget that will receive events
979 */
980 public final void enableSecondaryEventReceiver(final TWidget widget) {
981 assert (secondaryEventReceiver == null);
982 assert (secondaryEventHandler == null);
983 assert (widget instanceof TMessageBox);
984 secondaryEventReceiver = widget;
985 secondaryEventHandler = new WidgetEventHandler(this, false);
986 (new Thread(secondaryEventHandler)).start();
987 }
988
989 /**
990 * Yield to the secondary thread.
991 */
992 public final void yield() {
993 assert (secondaryEventReceiver != null);
994 // This is where we handoff the event handler lock from the primary
995 // to secondary thread. We unlock here, and in a future loop the
996 // secondary thread locks again. When it gives up, we have the
997 // single lock back.
998 boolean oldLock = unlockHandleEvent();
999 assert (oldLock == true);
1000
1001 while (secondaryEventReceiver != null) {
1002 synchronized (primaryEventHandler) {
1003 try {
1004 primaryEventHandler.wait();
1005 } catch (InterruptedException e) {
1006 // SQUASH
1007 }
1008 }
1009 }
1010 }
1011
1012 /**
1013 * Do stuff when there is no user input.
1014 */
1015 private void doIdle() {
1016 if (debugThreads) {
1017 System.err.printf("doIdle()\n");
1018 }
1019
1020 // Now run any timers that have timed out
1021 Date now = new Date();
1022 List<TTimer> keepTimers = new LinkedList<TTimer>();
1023 for (TTimer timer: timers) {
1024 if (timer.getNextTick().getTime() <= now.getTime()) {
1025 timer.tick();
1026 if (timer.recurring) {
1027 keepTimers.add(timer);
1028 }
1029 } else {
1030 keepTimers.add(timer);
1031 }
1032 }
1033 timers = keepTimers;
1034
1035 // Call onIdle's
1036 for (TWindow window: windows) {
1037 window.onIdle();
1038 }
1039 }
1040
1041 /**
1042 * Get the amount of time I can sleep before missing a Timer tick.
1043 *
1044 * @param timeout = initial (maximum) timeout in millis
1045 * @return number of milliseconds between now and the next timer event
1046 */
1047 private long getSleepTime(final long timeout) {
1048 Date now = new Date();
1049 long nowTime = now.getTime();
1050 long sleepTime = timeout;
1051 for (TTimer timer: timers) {
1052 long nextTickTime = timer.getNextTick().getTime();
1053 if (nextTickTime < nowTime) {
1054 return 0;
1055 }
1056
1057 long timeDifference = nextTickTime - nowTime;
1058 if (timeDifference < sleepTime) {
1059 sleepTime = timeDifference;
1060 }
1061 }
1062 assert (sleepTime >= 0);
1063 assert (sleepTime <= timeout);
1064 return sleepTime;
1065 }
1066
1067 /**
1068 * Close window. Note that the window's destructor is NOT called by this
1069 * method, instead the GC is assumed to do the cleanup.
1070 *
1071 * @param window the window to remove
1072 */
1073 public final void closeWindow(final TWindow window) {
1074 synchronized (windows) {
1075 int z = window.getZ();
1076 window.setZ(-1);
1077 Collections.sort(windows);
1078 windows.remove(0);
1079 TWindow activeWindow = null;
1080 for (TWindow w: windows) {
1081 if (w.getZ() > z) {
1082 w.setZ(w.getZ() - 1);
1083 if (w.getZ() == 0) {
1084 w.setActive(true);
1085 assert (activeWindow == null);
1086 activeWindow = w;
1087 } else {
1088 w.setActive(false);
1089 }
1090 }
1091 }
1092 }
1093
1094 // Perform window cleanup
1095 window.onClose();
1096
1097 // Check if we are closing a TMessageBox or similar
1098 if (secondaryEventReceiver != null) {
1099 assert (secondaryEventHandler != null);
1100
1101 // Do not send events to the secondaryEventReceiver anymore, the
1102 // window is closed.
1103 secondaryEventReceiver = null;
1104
1105 // Wake the secondary thread, it will wake the primary as it
1106 // exits.
1107 synchronized (secondaryEventHandler) {
1108 secondaryEventHandler.notify();
1109 }
1110 }
1111 }
1112
1113 /**
1114 * Switch to the next window.
1115 *
1116 * @param forward if true, then switch to the next window in the list,
1117 * otherwise switch to the previous window in the list
1118 */
1119 public final void switchWindow(final boolean forward) {
1120 // Only switch if there are multiple windows
1121 if (windows.size() < 2) {
1122 return;
1123 }
1124
1125 synchronized (windows) {
1126
1127 // Swap z/active between active window and the next in the list
1128 int activeWindowI = -1;
1129 for (int i = 0; i < windows.size(); i++) {
1130 if (windows.get(i).isActive()) {
1131 activeWindowI = i;
1132 break;
1133 }
1134 }
1135 assert (activeWindowI >= 0);
1136
1137 // Do not switch if a window is modal
1138 if (windows.get(activeWindowI).isModal()) {
1139 return;
1140 }
1141
1142 int nextWindowI;
1143 if (forward) {
1144 nextWindowI = (activeWindowI + 1) % windows.size();
1145 } else {
1146 if (activeWindowI == 0) {
1147 nextWindowI = windows.size() - 1;
1148 } else {
1149 nextWindowI = activeWindowI - 1;
1150 }
1151 }
1152 windows.get(activeWindowI).setActive(false);
1153 windows.get(activeWindowI).setZ(windows.get(nextWindowI).getZ());
1154 windows.get(nextWindowI).setZ(0);
1155 windows.get(nextWindowI).setActive(true);
1156
1157 } // synchronized (windows)
1158
1159 }
1160
1161 /**
1162 * Add a window to my window list and make it active.
1163 *
1164 * @param window new window to add
1165 */
1166 public final void addWindow(final TWindow window) {
1167 synchronized (windows) {
1168 // Do not allow a modal window to spawn a non-modal window
1169 if ((windows.size() > 0) && (windows.get(0).isModal())) {
1170 assert (window.isModal());
1171 }
1172 for (TWindow w: windows) {
1173 w.setActive(false);
1174 w.setZ(w.getZ() + 1);
1175 }
1176 windows.add(window);
1177 window.setActive(true);
1178 window.setZ(0);
1179 }
1180 }
1181
1182 /**
1183 * Check if there is a system-modal window on top.
1184 *
1185 * @return true if the active window is modal
1186 */
1187 private boolean modalWindowActive() {
1188 if (windows.size() == 0) {
1189 return false;
1190 }
1191 return windows.get(windows.size() - 1).isModal();
1192 }
1193
1194 /**
1195 * Check if a mouse event would hit either the active menu or any open
1196 * sub-menus.
1197 *
1198 * @param mouse mouse event
1199 * @return true if the mouse would hit the active menu or an open
1200 * sub-menu
1201 */
1202 private boolean mouseOnMenu(final TMouseEvent mouse) {
1203 assert (activeMenu != null);
1204 List<TMenu> menus = new LinkedList<TMenu>(subMenus);
1205 Collections.reverse(menus);
1206 for (TMenu menu: menus) {
1207 if (menu.mouseWouldHit(mouse)) {
1208 return true;
1209 }
1210 }
1211 return activeMenu.mouseWouldHit(mouse);
1212 }
1213
1214 /**
1215 * See if we need to switch window or activate the menu based on
1216 * a mouse click.
1217 *
1218 * @param mouse mouse event
1219 */
1220 private void checkSwitchFocus(final TMouseEvent mouse) {
1221
1222 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1223 && (activeMenu != null)
1224 && (mouse.getAbsoluteY() != 0)
1225 && (!mouseOnMenu(mouse))
1226 ) {
1227 // They clicked outside the active menu, turn it off
1228 activeMenu.setActive(false);
1229 activeMenu = null;
1230 for (TMenu menu: subMenus) {
1231 menu.setActive(false);
1232 }
1233 subMenus.clear();
1234 // Continue checks
1235 }
1236
1237 // See if they hit the menu bar
1238 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1239 && (mouse.isMouse1())
1240 && (!modalWindowActive())
1241 && (mouse.getAbsoluteY() == 0)
1242 ) {
1243
1244 for (TMenu menu: subMenus) {
1245 menu.setActive(false);
1246 }
1247 subMenus.clear();
1248
1249 // They selected the menu, go activate it
1250 for (TMenu menu: menus) {
1251 if ((mouse.getAbsoluteX() >= menu.getX())
1252 && (mouse.getAbsoluteX() < menu.getX()
1253 + menu.getTitle().length() + 2)
1254 ) {
1255 menu.setActive(true);
1256 activeMenu = menu;
1257 } else {
1258 menu.setActive(false);
1259 }
1260 }
1261 return;
1262 }
1263
1264 // See if they hit the menu bar
1265 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
1266 && (mouse.isMouse1())
1267 && (activeMenu != null)
1268 && (mouse.getAbsoluteY() == 0)
1269 ) {
1270
1271 TMenu oldMenu = activeMenu;
1272 for (TMenu menu: subMenus) {
1273 menu.setActive(false);
1274 }
1275 subMenus.clear();
1276
1277 // See if we should switch menus
1278 for (TMenu menu: menus) {
1279 if ((mouse.getAbsoluteX() >= menu.getX())
1280 && (mouse.getAbsoluteX() < menu.getX()
1281 + menu.getTitle().length() + 2)
1282 ) {
1283 menu.setActive(true);
1284 activeMenu = menu;
1285 }
1286 }
1287 if (oldMenu != activeMenu) {
1288 // They switched menus
1289 oldMenu.setActive(false);
1290 }
1291 return;
1292 }
1293
1294 // Only switch if there are multiple windows
1295 if (windows.size() < 2) {
1296 return;
1297 }
1298
1299 // Switch on the upclick
1300 if (mouse.getType() != TMouseEvent.Type.MOUSE_UP) {
1301 return;
1302 }
1303
1304 synchronized (windows) {
1305 Collections.sort(windows);
1306 if (windows.get(0).isModal()) {
1307 // Modal windows don't switch
1308 return;
1309 }
1310
1311 for (TWindow window: windows) {
1312 assert (!window.isModal());
1313 if (window.mouseWouldHit(mouse)) {
1314 if (window == windows.get(0)) {
1315 // Clicked on the same window, nothing to do
1316 return;
1317 }
1318
1319 // We will be switching to another window
1320 assert (windows.get(0).isActive());
1321 assert (!window.isActive());
1322 windows.get(0).setActive(false);
1323 windows.get(0).setZ(window.getZ());
1324 window.setZ(0);
1325 window.setActive(true);
1326 return;
1327 }
1328 }
1329 }
1330
1331 // Clicked on the background, nothing to do
1332 return;
1333 }
1334
1335 /**
1336 * Turn off the menu.
1337 */
1338 public final void closeMenu() {
1339 if (activeMenu != null) {
1340 activeMenu.setActive(false);
1341 activeMenu = null;
1342 for (TMenu menu: subMenus) {
1343 menu.setActive(false);
1344 }
1345 subMenus.clear();
1346 }
1347 }
1348
1349 /**
1350 * Turn off a sub-menu.
1351 */
1352 public final void closeSubMenu() {
1353 assert (activeMenu != null);
1354 TMenu item = subMenus.get(subMenus.size() - 1);
1355 assert (item != null);
1356 item.setActive(false);
1357 subMenus.remove(subMenus.size() - 1);
1358 }
1359
1360 /**
1361 * Switch to the next menu.
1362 *
1363 * @param forward if true, then switch to the next menu in the list,
1364 * otherwise switch to the previous menu in the list
1365 */
1366 public final void switchMenu(final boolean forward) {
1367 assert (activeMenu != null);
1368
1369 for (TMenu menu: subMenus) {
1370 menu.setActive(false);
1371 }
1372 subMenus.clear();
1373
1374 for (int i = 0; i < menus.size(); i++) {
1375 if (activeMenu == menus.get(i)) {
1376 if (forward) {
1377 if (i < menus.size() - 1) {
1378 i++;
1379 }
1380 } else {
1381 if (i > 0) {
1382 i--;
1383 }
1384 }
1385 activeMenu.setActive(false);
1386 activeMenu = menus.get(i);
1387 activeMenu.setActive(true);
1388 return;
1389 }
1390 }
1391 }
1392
1393 /**
1394 * Method that TApplication subclasses can override to handle menu or
1395 * posted command events.
1396 *
1397 * @param command command event
1398 * @return if true, this event was consumed
1399 */
1400 protected boolean onCommand(final TCommandEvent command) {
1401 // Default: handle cmExit
1402 if (command.equals(cmExit)) {
1403 if (messageBox("Confirmation", "Exit application?",
1404 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
1405 quit = true;
1406 }
1407 return true;
1408 }
1409
1410 if (command.equals(cmShell)) {
1411 openTerminal(0, 0, TWindow.RESIZABLE);
1412 return true;
1413 }
1414
1415 if (command.equals(cmTile)) {
1416 tileWindows();
1417 return true;
1418 }
1419 if (command.equals(cmCascade)) {
1420 cascadeWindows();
1421 return true;
1422 }
1423 if (command.equals(cmCloseAll)) {
1424 closeAllWindows();
1425 return true;
1426 }
1427
1428 return false;
1429 }
1430
1431 /**
1432 * Method that TApplication subclasses can override to handle menu
1433 * events.
1434 *
1435 * @param menu menu event
1436 * @return if true, this event was consumed
1437 */
1438 protected boolean onMenu(final TMenuEvent menu) {
1439
1440 // Default: handle MID_EXIT
1441 if (menu.getId() == TMenu.MID_EXIT) {
1442 if (messageBox("Confirmation", "Exit application?",
1443 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
1444 quit = true;
1445 }
1446 return true;
1447 }
1448
1449 if (menu.getId() == TMenu.MID_SHELL) {
1450 openTerminal(0, 0, TWindow.RESIZABLE);
1451 return true;
1452 }
1453
1454 if (menu.getId() == TMenu.MID_TILE) {
1455 tileWindows();
1456 return true;
1457 }
1458 if (menu.getId() == TMenu.MID_CASCADE) {
1459 cascadeWindows();
1460 return true;
1461 }
1462 if (menu.getId() == TMenu.MID_CLOSE_ALL) {
1463 closeAllWindows();
1464 return true;
1465 }
1466 return false;
1467 }
1468
1469 /**
1470 * Method that TApplication subclasses can override to handle keystrokes.
1471 *
1472 * @param keypress keystroke event
1473 * @return if true, this event was consumed
1474 */
1475 protected boolean onKeypress(final TKeypressEvent keypress) {
1476 // Default: only menu shortcuts
1477
1478 // Process Alt-F, Alt-E, etc. menu shortcut keys
1479 if (!keypress.getKey().isFnKey()
1480 && keypress.getKey().isAlt()
1481 && !keypress.getKey().isCtrl()
1482 && (activeMenu == null)
1483 ) {
1484
1485 assert (subMenus.size() == 0);
1486
1487 for (TMenu menu: menus) {
1488 if (Character.toLowerCase(menu.getMnemonic().getShortcut())
1489 == Character.toLowerCase(keypress.getKey().getChar())
1490 ) {
1491 activeMenu = menu;
1492 menu.setActive(true);
1493 return true;
1494 }
1495 }
1496 }
1497
1498 return false;
1499 }
1500
1501 /**
1502 * Add a keyboard accelerator to the global hash.
1503 *
1504 * @param item menu item this accelerator relates to
1505 * @param keypress keypress that will dispatch a TMenuEvent
1506 */
1507 public final void addAccelerator(final TMenuItem item,
1508 final TKeypress keypress) {
1509
1510 synchronized (accelerators) {
1511 assert (accelerators.get(keypress) == null);
1512 accelerators.put(keypress, item);
1513 }
1514 }
1515
1516 /**
1517 * Recompute menu x positions based on their title length.
1518 */
1519 public final void recomputeMenuX() {
1520 int x = 0;
1521 for (TMenu menu: menus) {
1522 menu.setX(x);
1523 x += menu.getTitle().length() + 2;
1524 }
1525 }
1526
1527 /**
1528 * Post an event to process and turn off the menu.
1529 *
1530 * @param event new event to add to the queue
1531 */
1532 public final void addMenuEvent(final TInputEvent event) {
1533 synchronized (fillEventQueue) {
1534 fillEventQueue.add(event);
1535 }
1536 closeMenu();
1537 }
1538
1539 /**
1540 * Add a sub-menu to the list of open sub-menus.
1541 *
1542 * @param menu sub-menu
1543 */
1544 public final void addSubMenu(final TMenu menu) {
1545 subMenus.add(menu);
1546 }
1547
1548 /**
1549 * Convenience function to add a top-level menu.
1550 *
1551 * @param title menu title
1552 * @return the new menu
1553 */
1554 public final TMenu addMenu(final String title) {
1555 int x = 0;
1556 int y = 0;
1557 TMenu menu = new TMenu(this, x, y, title);
1558 menus.add(menu);
1559 recomputeMenuX();
1560 return menu;
1561 }
1562
1563 /**
1564 * Convenience function to add a default "File" menu.
1565 *
1566 * @return the new menu
1567 */
1568 public final TMenu addFileMenu() {
1569 TMenu fileMenu = addMenu("&File");
1570 fileMenu.addDefaultItem(TMenu.MID_OPEN_FILE);
1571 fileMenu.addSeparator();
1572 fileMenu.addDefaultItem(TMenu.MID_SHELL);
1573 fileMenu.addDefaultItem(TMenu.MID_EXIT);
1574 return fileMenu;
1575 }
1576
1577 /**
1578 * Convenience function to add a default "Edit" menu.
1579 *
1580 * @return the new menu
1581 */
1582 public final TMenu addEditMenu() {
1583 TMenu editMenu = addMenu("&Edit");
1584 editMenu.addDefaultItem(TMenu.MID_CUT);
1585 editMenu.addDefaultItem(TMenu.MID_COPY);
1586 editMenu.addDefaultItem(TMenu.MID_PASTE);
1587 editMenu.addDefaultItem(TMenu.MID_CLEAR);
1588 return editMenu;
1589 }
1590
1591 /**
1592 * Convenience function to add a default "Window" menu.
1593 *
1594 * @return the new menu
1595 */
1596 public final TMenu addWindowMenu() {
1597 TMenu windowMenu = addMenu("&Window");
1598 windowMenu.addDefaultItem(TMenu.MID_TILE);
1599 windowMenu.addDefaultItem(TMenu.MID_CASCADE);
1600 windowMenu.addDefaultItem(TMenu.MID_CLOSE_ALL);
1601 windowMenu.addSeparator();
1602 windowMenu.addDefaultItem(TMenu.MID_WINDOW_MOVE);
1603 windowMenu.addDefaultItem(TMenu.MID_WINDOW_ZOOM);
1604 windowMenu.addDefaultItem(TMenu.MID_WINDOW_NEXT);
1605 windowMenu.addDefaultItem(TMenu.MID_WINDOW_PREVIOUS);
1606 windowMenu.addDefaultItem(TMenu.MID_WINDOW_CLOSE);
1607 return windowMenu;
1608 }
1609
1610 /**
1611 * Close all open windows.
1612 */
1613 private void closeAllWindows() {
1614 // Don't do anything if we are in the menu
1615 if (activeMenu != null) {
1616 return;
1617 }
1618
1619 synchronized (windows) {
1620 for (TWindow window: windows) {
1621 closeWindow(window);
1622 }
1623 }
1624 }
1625
1626 /**
1627 * Re-layout the open windows as non-overlapping tiles. This produces
1628 * almost the same results as Turbo Pascal 7.0's IDE.
1629 */
1630 private void tileWindows() {
1631 synchronized (windows) {
1632 // Don't do anything if we are in the menu
1633 if (activeMenu != null) {
1634 return;
1635 }
1636 int z = windows.size();
1637 if (z == 0) {
1638 return;
1639 }
1640 int a = 0;
1641 int b = 0;
1642 a = (int)(Math.sqrt(z));
1643 int c = 0;
1644 while (c < a) {
1645 b = (z - c) / a;
1646 if (((a * b) + c) == z) {
1647 break;
1648 }
1649 c++;
1650 }
1651 assert (a > 0);
1652 assert (b > 0);
1653 assert (c < a);
1654 int newWidth = (getScreen().getWidth() / a);
1655 int newHeight1 = ((getScreen().getHeight() - 1) / b);
1656 int newHeight2 = ((getScreen().getHeight() - 1) / (b + c));
1657
1658 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1659 Collections.sort(sorted);
1660 Collections.reverse(sorted);
1661 for (int i = 0; i < sorted.size(); i++) {
1662 int logicalX = i / b;
1663 int logicalY = i % b;
1664 if (i >= ((a - 1) * b)) {
1665 logicalX = a - 1;
1666 logicalY = i - ((a - 1) * b);
1667 }
1668
1669 TWindow w = sorted.get(i);
1670 w.setX(logicalX * newWidth);
1671 w.setWidth(newWidth);
1672 if (i >= ((a - 1) * b)) {
1673 w.setY((logicalY * newHeight2) + 1);
1674 w.setHeight(newHeight2);
1675 } else {
1676 w.setY((logicalY * newHeight1) + 1);
1677 w.setHeight(newHeight1);
1678 }
1679 }
1680 }
1681 }
1682
1683 /**
1684 * Re-layout the open windows as overlapping cascaded windows.
1685 */
1686 private void cascadeWindows() {
1687 synchronized (windows) {
1688 // Don't do anything if we are in the menu
1689 if (activeMenu != null) {
1690 return;
1691 }
1692 int x = 0;
1693 int y = 1;
1694 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1695 Collections.sort(sorted);
1696 Collections.reverse(sorted);
1697 for (TWindow window: sorted) {
1698 window.setX(x);
1699 window.setY(y);
1700 x++;
1701 y++;
1702 if (x > getScreen().getWidth()) {
1703 x = 0;
1704 }
1705 if (y >= getScreen().getHeight()) {
1706 y = 1;
1707 }
1708 }
1709 }
1710 }
1711
1712 /**
1713 * Convenience function to add a timer.
1714 *
1715 * @param duration number of milliseconds to wait between ticks
1716 * @param recurring if true, re-schedule this timer after every tick
1717 * @param action function to call when button is pressed
1718 * @return the timer
1719 */
1720 public final TTimer addTimer(final long duration, final boolean recurring,
1721 final TAction action) {
1722
1723 TTimer timer = new TTimer(duration, recurring, action);
1724 synchronized (timers) {
1725 timers.add(timer);
1726 }
1727 return timer;
1728 }
1729
1730 /**
1731 * Convenience function to remove a timer.
1732 *
1733 * @param timer timer to remove
1734 */
1735 public final void removeTimer(final TTimer timer) {
1736 synchronized (timers) {
1737 timers.remove(timer);
1738 }
1739 }
1740
1741 /**
1742 * Convenience function to spawn a message box.
1743 *
1744 * @param title window title, will be centered along the top border
1745 * @param caption message to display. Use embedded newlines to get a
1746 * multi-line box.
1747 * @return the new message box
1748 */
1749 public final TMessageBox messageBox(final String title,
1750 final String caption) {
1751
1752 return new TMessageBox(this, title, caption, TMessageBox.Type.OK);
1753 }
1754
1755 /**
1756 * Convenience function to spawn a message box.
1757 *
1758 * @param title window title, will be centered along the top border
1759 * @param caption message to display. Use embedded newlines to get a
1760 * multi-line box.
1761 * @param type one of the TMessageBox.Type constants. Default is
1762 * Type.OK.
1763 * @return the new message box
1764 */
1765 public final TMessageBox messageBox(final String title,
1766 final String caption, final TMessageBox.Type type) {
1767
1768 return new TMessageBox(this, title, caption, type);
1769 }
1770
1771 /**
1772 * Convenience function to spawn an input box.
1773 *
1774 * @param title window title, will be centered along the top border
1775 * @param caption message to display. Use embedded newlines to get a
1776 * multi-line box.
1777 * @return the new input box
1778 */
1779 public final TInputBox inputBox(final String title, final String caption) {
1780
1781 return new TInputBox(this, title, caption);
1782 }
1783
1784 /**
1785 * Convenience function to spawn an input box.
1786 *
1787 * @param title window title, will be centered along the top border
1788 * @param caption message to display. Use embedded newlines to get a
1789 * multi-line box.
1790 * @param text initial text to seed the field with
1791 * @return the new input box
1792 */
1793 public final TInputBox inputBox(final String title, final String caption,
1794 final String text) {
1795
1796 return new TInputBox(this, title, caption, text);
1797 }
1798
1799 /**
1800 * Convenience function to open a terminal window.
1801 *
1802 * @param x column relative to parent
1803 * @param y row relative to parent
1804 * @return the terminal new window
1805 */
1806 public final TTerminalWindow openTerminal(final int x, final int y) {
1807 return openTerminal(x, y, TWindow.RESIZABLE);
1808 }
1809
1810 /**
1811 * Convenience function to open a terminal window.
1812 *
1813 * @param x column relative to parent
1814 * @param y row relative to parent
1815 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1816 * @return the terminal new window
1817 */
1818 public final TTerminalWindow openTerminal(final int x, final int y,
1819 final int flags) {
1820
1821 return new TTerminalWindow(this, x, y, flags);
1822 }
1823
1824 /**
1825 * Convenience function to spawn an file open box.
1826 *
1827 * @param path path of selected file
1828 * @return the result of the new file open box
1829 */
1830 public final String fileOpenBox(final String path) throws IOException {
1831
1832 TFileOpenBox box = new TFileOpenBox(this, path, TFileOpenBox.Type.OPEN);
1833 return box.getFilename();
1834 }
1835
1836 /**
1837 * Convenience function to spawn an file open box.
1838 *
1839 * @param path path of selected file
1840 * @param type one of the Type constants
1841 * @return the result of the new file open box
1842 */
1843 public final String fileOpenBox(final String path,
1844 final TFileOpenBox.Type type) throws IOException {
1845
1846 TFileOpenBox box = new TFileOpenBox(this, path, type);
1847 return box.getFilename();
1848 }
1849
1850 }