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