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