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