#7 fix whitespace
[fanfix.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 = null;
725 if (sorted.size() > 0) {
726 topLevel = sorted.get(0);
727 }
728 Collections.reverse(sorted);
729 for (TWindow window: sorted) {
730 window.drawChildren();
731 }
732
733 // Draw the blank menubar line - reset the screen clipping first so
734 // it won't trim it out.
735 getScreen().resetClipping();
736 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
737 theme.getColor("tmenu"));
738 // Now draw the menus.
739 int x = 1;
740 for (TMenu menu: menus) {
741 CellAttributes menuColor;
742 CellAttributes menuMnemonicColor;
743 if (menu.isActive()) {
744 menuColor = theme.getColor("tmenu.highlighted");
745 menuMnemonicColor = theme.getColor("tmenu.mnemonic.highlighted");
746 topLevel = menu;
747 } else {
748 menuColor = theme.getColor("tmenu");
749 menuMnemonicColor = theme.getColor("tmenu.mnemonic");
750 }
751 // Draw the menu title
752 getScreen().hLineXY(x, 0, menu.getTitle().length() + 2, ' ',
753 menuColor);
754 getScreen().putStringXY(x + 1, 0, menu.getTitle(), menuColor);
755 // Draw the highlight character
756 getScreen().putCharXY(x + 1 + menu.getMnemonic().getShortcutIdx(),
757 0, menu.getMnemonic().getShortcut(), menuMnemonicColor);
758
759 if (menu.isActive()) {
760 menu.drawChildren();
761 // Reset the screen clipping so we can draw the next title.
762 getScreen().resetClipping();
763 }
764 x += menu.getTitle().length() + 2;
765 }
766
767 for (TMenu menu: subMenus) {
768 // Reset the screen clipping so we can draw the next sub-menu.
769 getScreen().resetClipping();
770 menu.drawChildren();
771 }
772
773 // Draw the status bar of the top-level window
774 TStatusBar statusBar = null;
775 if (topLevel != null) {
776 statusBar = topLevel.getStatusBar();
777 }
778 if (statusBar != null) {
779 getScreen().resetClipping();
780 statusBar.setWidth(getScreen().getWidth());
781 statusBar.setY(getScreen().getHeight() - topLevel.getY());
782 statusBar.draw();
783 } else {
784 CellAttributes barColor = new CellAttributes();
785 barColor.setTo(getTheme().getColor("tstatusbar.text"));
786 getScreen().hLineXY(0, desktopBottom, getScreen().getWidth(), ' ',
787 barColor);
788 }
789
790 // Draw the mouse pointer
791 invertCell(mouseX, mouseY);
792 oldMouseX = mouseX;
793 oldMouseY = mouseY;
794
795 // Place the cursor if it is visible
796 TWidget activeWidget = null;
797 if (sorted.size() > 0) {
798 activeWidget = sorted.get(sorted.size() - 1).getActiveChild();
799 if (activeWidget.isCursorVisible()) {
800 getScreen().putCursor(true, activeWidget.getCursorAbsoluteX(),
801 activeWidget.getCursorAbsoluteY());
802 cursor = true;
803 }
804 }
805
806 // Kill the cursor
807 if (!cursor) {
808 getScreen().hideCursor();
809 }
810
811 // Flush the screen contents
812 if (getScreen().isDirty()) {
813 backend.flushScreen();
814 }
815
816 repaint = false;
817 }
818
819 // ------------------------------------------------------------------------
820 // Main loop --------------------------------------------------------------
821 // ------------------------------------------------------------------------
822
823 /**
824 * Run this application until it exits.
825 */
826 public void run() {
827 while (!quit) {
828 // Timeout is in milliseconds, so default timeout after 1 second
829 // of inactivity.
830 long timeout = 0;
831
832 // If I've got no updates to render, wait for something from the
833 // backend or a timer.
834 if (!repaint
835 && ((mouseX == oldMouseX) && (mouseY == oldMouseY))
836 ) {
837 // Never sleep longer than 50 millis. We need time for
838 // windows with background tasks to update the display, and
839 // still flip buffers reasonably quickly in
840 // backend.flushPhysical().
841 timeout = getSleepTime(50);
842 }
843
844 if (timeout > 0) {
845 // As of now, I've got nothing to do: no I/O, nothing from
846 // the consumer threads, no timers that need to run ASAP. So
847 // wait until either the backend or the consumer threads have
848 // something to do.
849 try {
850 if (debugThreads) {
851 System.err.println("sleep " + timeout + " millis");
852 }
853 synchronized (this) {
854 this.wait(timeout);
855 }
856 } catch (InterruptedException e) {
857 // I'm awake and don't care why, let's see what's going
858 // on out there.
859 }
860 repaint = true;
861 }
862
863 // Prevent stepping on the primary or secondary event handler.
864 stopEventHandlers();
865
866 // Pull any pending I/O events
867 backend.getEvents(fillEventQueue);
868
869 // Dispatch each event to the appropriate handler, one at a time.
870 for (;;) {
871 TInputEvent event = null;
872 if (fillEventQueue.size() == 0) {
873 break;
874 }
875 event = fillEventQueue.remove(0);
876 metaHandleEvent(event);
877 }
878
879 // Wake a consumer thread if we have any pending events.
880 if (drainEventQueue.size() > 0) {
881 wakeEventHandler();
882 }
883
884 // Process timers and call doIdle()'s
885 doIdle();
886
887 // Update the screen
888 synchronized (getScreen()) {
889 drawAll();
890 }
891
892 // Let the event handlers run again.
893 startEventHandlers();
894
895 } // while (!quit)
896
897 // Shutdown the event consumer threads
898 if (secondaryEventHandler != null) {
899 synchronized (secondaryEventHandler) {
900 secondaryEventHandler.notify();
901 }
902 }
903 if (primaryEventHandler != null) {
904 synchronized (primaryEventHandler) {
905 primaryEventHandler.notify();
906 }
907 }
908
909 // Shutdown the user I/O thread(s)
910 backend.shutdown();
911
912 // Close all the windows. This gives them an opportunity to release
913 // resources.
914 closeAllWindows();
915
916 }
917
918 /**
919 * Peek at certain application-level events, add to eventQueue, and wake
920 * up the consuming Thread.
921 *
922 * @param event the input event to consume
923 */
924 private void metaHandleEvent(final TInputEvent event) {
925
926 if (debugEvents) {
927 System.err.printf(String.format("metaHandleEvents event: %s\n",
928 event)); System.err.flush();
929 }
930
931 if (quit) {
932 // Do no more processing if the application is already trying
933 // to exit.
934 return;
935 }
936
937 // Special application-wide events -------------------------------
938
939 // Abort everything
940 if (event instanceof TCommandEvent) {
941 TCommandEvent command = (TCommandEvent) event;
942 if (command.getCmd().equals(cmAbort)) {
943 quit = true;
944 return;
945 }
946 }
947
948 // Screen resize
949 if (event instanceof TResizeEvent) {
950 TResizeEvent resize = (TResizeEvent) event;
951 synchronized (getScreen()) {
952 getScreen().setDimensions(resize.getWidth(),
953 resize.getHeight());
954 desktopBottom = getScreen().getHeight() - 1;
955 mouseX = 0;
956 mouseY = 0;
957 oldMouseX = 0;
958 oldMouseY = 0;
959 }
960 return;
961 }
962
963 // Peek at the mouse position
964 if (event instanceof TMouseEvent) {
965 TMouseEvent mouse = (TMouseEvent) event;
966 synchronized (getScreen()) {
967 if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
968 oldMouseX = mouseX;
969 oldMouseY = mouseY;
970 mouseX = mouse.getX();
971 mouseY = mouse.getY();
972 }
973 }
974 }
975
976 // Put into the main queue
977 drainEventQueue.add(event);
978 }
979
980 /**
981 * Dispatch one event to the appropriate widget or application-level
982 * event handler. This is the primary event handler, it has the normal
983 * application-wide event handling.
984 *
985 * @param event the input event to consume
986 * @see #secondaryHandleEvent(TInputEvent event)
987 */
988 private void primaryHandleEvent(final TInputEvent event) {
989
990 if (debugEvents) {
991 System.err.printf("Handle event: %s\n", event);
992 }
993
994 // Special application-wide events -----------------------------------
995
996 // Peek at the mouse position
997 if (event instanceof TMouseEvent) {
998 // See if we need to switch focus to another window or the menu
999 checkSwitchFocus((TMouseEvent) event);
1000 }
1001
1002 // Handle menu events
1003 if ((activeMenu != null) && !(event instanceof TCommandEvent)) {
1004 TMenu menu = activeMenu;
1005
1006 if (event instanceof TMouseEvent) {
1007 TMouseEvent mouse = (TMouseEvent) event;
1008
1009 while (subMenus.size() > 0) {
1010 TMenu subMenu = subMenus.get(subMenus.size() - 1);
1011 if (subMenu.mouseWouldHit(mouse)) {
1012 break;
1013 }
1014 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
1015 && (!mouse.isMouse1())
1016 && (!mouse.isMouse2())
1017 && (!mouse.isMouse3())
1018 && (!mouse.isMouseWheelUp())
1019 && (!mouse.isMouseWheelDown())
1020 ) {
1021 break;
1022 }
1023 // We navigated away from a sub-menu, so close it
1024 closeSubMenu();
1025 }
1026
1027 // Convert the mouse relative x/y to menu coordinates
1028 assert (mouse.getX() == mouse.getAbsoluteX());
1029 assert (mouse.getY() == mouse.getAbsoluteY());
1030 if (subMenus.size() > 0) {
1031 menu = subMenus.get(subMenus.size() - 1);
1032 }
1033 mouse.setX(mouse.getX() - menu.getX());
1034 mouse.setY(mouse.getY() - menu.getY());
1035 }
1036 menu.handleEvent(event);
1037 return;
1038 }
1039
1040 if (event instanceof TKeypressEvent) {
1041 TKeypressEvent keypress = (TKeypressEvent) event;
1042
1043 // See if this key matches an accelerator, and is not being
1044 // shortcutted by the active window, and if so dispatch the menu
1045 // event.
1046 boolean windowWillShortcut = false;
1047 for (TWindow window: windows) {
1048 if (window.isActive()) {
1049 if (window.isShortcutKeypress(keypress.getKey())) {
1050 // We do not process this key, it will be passed to
1051 // the window instead.
1052 windowWillShortcut = true;
1053 }
1054 }
1055 }
1056
1057 if (!windowWillShortcut && !modalWindowActive()) {
1058 TKeypress keypressLowercase = keypress.getKey().toLowerCase();
1059 TMenuItem item = null;
1060 synchronized (accelerators) {
1061 item = accelerators.get(keypressLowercase);
1062 }
1063 if (item != null) {
1064 if (item.isEnabled()) {
1065 // Let the menu item dispatch
1066 item.dispatch();
1067 return;
1068 }
1069 }
1070
1071 // Handle the keypress
1072 if (onKeypress(keypress)) {
1073 return;
1074 }
1075 }
1076 }
1077
1078 if (event instanceof TCommandEvent) {
1079 if (onCommand((TCommandEvent) event)) {
1080 return;
1081 }
1082 }
1083
1084 if (event instanceof TMenuEvent) {
1085 if (onMenu((TMenuEvent) event)) {
1086 return;
1087 }
1088 }
1089
1090 // Dispatch events to the active window -------------------------------
1091 for (TWindow window: windows) {
1092 if (window.isActive()) {
1093 if (event instanceof TMouseEvent) {
1094 TMouseEvent mouse = (TMouseEvent) event;
1095 // Convert the mouse relative x/y to window coordinates
1096 assert (mouse.getX() == mouse.getAbsoluteX());
1097 assert (mouse.getY() == mouse.getAbsoluteY());
1098 mouse.setX(mouse.getX() - window.getX());
1099 mouse.setY(mouse.getY() - window.getY());
1100 }
1101 if (debugEvents) {
1102 System.err.printf("TApplication dispatch event: %s\n",
1103 event);
1104 }
1105 window.handleEvent(event);
1106 break;
1107 }
1108 }
1109 }
1110 /**
1111 * Dispatch one event to the appropriate widget or application-level
1112 * event handler. This is the secondary event handler used by certain
1113 * special dialogs (currently TMessageBox and TFileOpenBox).
1114 *
1115 * @param event the input event to consume
1116 * @see #primaryHandleEvent(TInputEvent event)
1117 */
1118 private void secondaryHandleEvent(final TInputEvent event) {
1119 secondaryEventReceiver.handleEvent(event);
1120 }
1121
1122 /**
1123 * Enable a widget to override the primary event thread.
1124 *
1125 * @param widget widget that will receive events
1126 */
1127 public final void enableSecondaryEventReceiver(final TWidget widget) {
1128 assert (secondaryEventReceiver == null);
1129 assert (secondaryEventHandler == null);
1130 assert ((widget instanceof TMessageBox)
1131 || (widget instanceof TFileOpenBox));
1132 secondaryEventReceiver = widget;
1133 secondaryEventHandler = new WidgetEventHandler(this, false);
1134 (new Thread(secondaryEventHandler)).start();
1135 }
1136
1137 /**
1138 * Yield to the secondary thread.
1139 */
1140 public final void yield() {
1141 assert (secondaryEventReceiver != null);
1142 // This is where we handoff the event handler lock from the primary
1143 // to secondary thread. We unlock here, and in a future loop the
1144 // secondary thread locks again. When it gives up, we have the
1145 // single lock back.
1146 boolean oldLock = unlockHandleEvent();
1147 assert (oldLock);
1148
1149 while (secondaryEventReceiver != null) {
1150 synchronized (primaryEventHandler) {
1151 try {
1152 primaryEventHandler.wait();
1153 } catch (InterruptedException e) {
1154 // SQUASH
1155 }
1156 }
1157 }
1158 }
1159
1160 /**
1161 * Do stuff when there is no user input.
1162 */
1163 private void doIdle() {
1164 if (debugThreads) {
1165 System.err.printf("doIdle()\n");
1166 }
1167
1168 // Now run any timers that have timed out
1169 Date now = new Date();
1170 List<TTimer> keepTimers = new LinkedList<TTimer>();
1171 for (TTimer timer: timers) {
1172 if (timer.getNextTick().getTime() <= now.getTime()) {
1173 timer.tick();
1174 if (timer.recurring) {
1175 keepTimers.add(timer);
1176 }
1177 } else {
1178 keepTimers.add(timer);
1179 }
1180 }
1181 timers = keepTimers;
1182
1183 // Call onIdle's
1184 for (TWindow window: windows) {
1185 window.onIdle();
1186 }
1187 }
1188
1189 // ------------------------------------------------------------------------
1190 // TWindow management -----------------------------------------------------
1191 // ------------------------------------------------------------------------
1192
1193 /**
1194 * Close window. Note that the window's destructor is NOT called by this
1195 * method, instead the GC is assumed to do the cleanup.
1196 *
1197 * @param window the window to remove
1198 */
1199 public final void closeWindow(final TWindow window) {
1200 synchronized (windows) {
1201 int z = window.getZ();
1202 window.setZ(-1);
1203 window.onUnfocus();
1204 Collections.sort(windows);
1205 windows.remove(0);
1206 TWindow activeWindow = null;
1207 for (TWindow w: windows) {
1208 if (w.getZ() > z) {
1209 w.setZ(w.getZ() - 1);
1210 if (w.getZ() == 0) {
1211 w.setActive(true);
1212 w.onFocus();
1213 assert (activeWindow == null);
1214 activeWindow = w;
1215 } else {
1216 if (w.isActive()) {
1217 w.setActive(false);
1218 w.onUnfocus();
1219 }
1220 }
1221 }
1222 }
1223 }
1224
1225 // Perform window cleanup
1226 window.onClose();
1227
1228 // Check if we are closing a TMessageBox or similar
1229 if (secondaryEventReceiver != null) {
1230 assert (secondaryEventHandler != null);
1231
1232 // Do not send events to the secondaryEventReceiver anymore, the
1233 // window is closed.
1234 secondaryEventReceiver = null;
1235
1236 // Wake the secondary thread, it will wake the primary as it
1237 // exits.
1238 synchronized (secondaryEventHandler) {
1239 secondaryEventHandler.notify();
1240 }
1241 }
1242 }
1243
1244 /**
1245 * Switch to the next window.
1246 *
1247 * @param forward if true, then switch to the next window in the list,
1248 * otherwise switch to the previous window in the list
1249 */
1250 public final void switchWindow(final boolean forward) {
1251 // Only switch if there are multiple windows
1252 if (windows.size() < 2) {
1253 return;
1254 }
1255
1256 synchronized (windows) {
1257
1258 // Swap z/active between active window and the next in the list
1259 int activeWindowI = -1;
1260 for (int i = 0; i < windows.size(); i++) {
1261 if (windows.get(i).isActive()) {
1262 activeWindowI = i;
1263 break;
1264 }
1265 }
1266 assert (activeWindowI >= 0);
1267
1268 // Do not switch if a window is modal
1269 if (windows.get(activeWindowI).isModal()) {
1270 return;
1271 }
1272
1273 int nextWindowI;
1274 if (forward) {
1275 nextWindowI = (activeWindowI + 1) % windows.size();
1276 } else {
1277 if (activeWindowI == 0) {
1278 nextWindowI = windows.size() - 1;
1279 } else {
1280 nextWindowI = activeWindowI - 1;
1281 }
1282 }
1283 windows.get(activeWindowI).setActive(false);
1284 windows.get(activeWindowI).setZ(windows.get(nextWindowI).getZ());
1285 windows.get(activeWindowI).onUnfocus();
1286 windows.get(nextWindowI).setZ(0);
1287 windows.get(nextWindowI).setActive(true);
1288 windows.get(nextWindowI).onFocus();
1289
1290 } // synchronized (windows)
1291
1292 }
1293
1294 /**
1295 * Add a window to my window list and make it active.
1296 *
1297 * @param window new window to add
1298 */
1299 public final void addWindow(final TWindow window) {
1300
1301 // Do not add menu windows to the window list.
1302 if (window instanceof TMenu) {
1303 return;
1304 }
1305
1306 synchronized (windows) {
1307 // Do not allow a modal window to spawn a non-modal window. If a
1308 // modal window is active, then this window will become modal
1309 // too.
1310 if (modalWindowActive()) {
1311 window.flags |= TWindow.MODAL;
1312 window.flags |= TWindow.CENTERED;
1313 }
1314 for (TWindow w: windows) {
1315 if (w.isActive()) {
1316 w.setActive(false);
1317 w.onUnfocus();
1318 }
1319 w.setZ(w.getZ() + 1);
1320 }
1321 windows.add(window);
1322 window.setZ(0);
1323 window.setActive(true);
1324 window.onFocus();
1325
1326 if (((window.flags & TWindow.CENTERED) == 0)
1327 && smartWindowPlacement) {
1328
1329 doSmartPlacement(window);
1330 }
1331 }
1332 }
1333
1334 /**
1335 * Check if there is a system-modal window on top.
1336 *
1337 * @return true if the active window is modal
1338 */
1339 private boolean modalWindowActive() {
1340 if (windows.size() == 0) {
1341 return false;
1342 }
1343
1344 for (TWindow w: windows) {
1345 if (w.isModal()) {
1346 return true;
1347 }
1348 }
1349
1350 return false;
1351 }
1352
1353 /**
1354 * Close all open windows.
1355 */
1356 private void closeAllWindows() {
1357 // Don't do anything if we are in the menu
1358 if (activeMenu != null) {
1359 return;
1360 }
1361 while (windows.size() > 0) {
1362 closeWindow(windows.get(0));
1363 }
1364 }
1365
1366 /**
1367 * Re-layout the open windows as non-overlapping tiles. This produces
1368 * almost the same results as Turbo Pascal 7.0's IDE.
1369 */
1370 private void tileWindows() {
1371 synchronized (windows) {
1372 // Don't do anything if we are in the menu
1373 if (activeMenu != null) {
1374 return;
1375 }
1376 int z = windows.size();
1377 if (z == 0) {
1378 return;
1379 }
1380 int a = 0;
1381 int b = 0;
1382 a = (int)(Math.sqrt(z));
1383 int c = 0;
1384 while (c < a) {
1385 b = (z - c) / a;
1386 if (((a * b) + c) == z) {
1387 break;
1388 }
1389 c++;
1390 }
1391 assert (a > 0);
1392 assert (b > 0);
1393 assert (c < a);
1394 int newWidth = (getScreen().getWidth() / a);
1395 int newHeight1 = ((getScreen().getHeight() - 1) / b);
1396 int newHeight2 = ((getScreen().getHeight() - 1) / (b + c));
1397
1398 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1399 Collections.sort(sorted);
1400 Collections.reverse(sorted);
1401 for (int i = 0; i < sorted.size(); i++) {
1402 int logicalX = i / b;
1403 int logicalY = i % b;
1404 if (i >= ((a - 1) * b)) {
1405 logicalX = a - 1;
1406 logicalY = i - ((a - 1) * b);
1407 }
1408
1409 TWindow w = sorted.get(i);
1410 w.setX(logicalX * newWidth);
1411 w.setWidth(newWidth);
1412 if (i >= ((a - 1) * b)) {
1413 w.setY((logicalY * newHeight2) + 1);
1414 w.setHeight(newHeight2);
1415 } else {
1416 w.setY((logicalY * newHeight1) + 1);
1417 w.setHeight(newHeight1);
1418 }
1419 }
1420 }
1421 }
1422
1423 /**
1424 * Re-layout the open windows as overlapping cascaded windows.
1425 */
1426 private void cascadeWindows() {
1427 synchronized (windows) {
1428 // Don't do anything if we are in the menu
1429 if (activeMenu != null) {
1430 return;
1431 }
1432 int x = 0;
1433 int y = 1;
1434 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1435 Collections.sort(sorted);
1436 Collections.reverse(sorted);
1437 for (TWindow window: sorted) {
1438 window.setX(x);
1439 window.setY(y);
1440 x++;
1441 y++;
1442 if (x > getScreen().getWidth()) {
1443 x = 0;
1444 }
1445 if (y >= getScreen().getHeight()) {
1446 y = 1;
1447 }
1448 }
1449 }
1450 }
1451
1452 /**
1453 * Place a window to minimize its overlap with other windows.
1454 *
1455 * @param window the window to place
1456 */
1457 public final void doSmartPlacement(final TWindow window) {
1458 // This is a pretty dumb algorithm, but seems to work. The hardest
1459 // part is computing these "overlap" values seeking a minimum average
1460 // overlap.
1461 int xMin = 0;
1462 int yMin = desktopTop;
1463 int xMax = getScreen().getWidth() - window.getWidth() + 1;
1464 int yMax = desktopBottom - window.getHeight() + 1;
1465 if (xMax < xMin) {
1466 xMax = xMin;
1467 }
1468 if (yMax < yMin) {
1469 yMax = yMin;
1470 }
1471
1472 if ((xMin == xMax) && (yMin == yMax)) {
1473 // No work to do, bail out.
1474 return;
1475 }
1476
1477 // Compute the overlap matrix without the new window.
1478 int width = getScreen().getWidth();
1479 int height = getScreen().getHeight();
1480 int overlapMatrix[][] = new int[width][height];
1481 for (TWindow w: windows) {
1482 if (window == w) {
1483 continue;
1484 }
1485 for (int x = w.getX(); x < w.getX() + w.getWidth(); x++) {
1486 if (x == width) {
1487 continue;
1488 }
1489 for (int y = w.getY(); y < w.getY() + w.getHeight(); y++) {
1490 if (y == height) {
1491 continue;
1492 }
1493 overlapMatrix[x][y]++;
1494 }
1495 }
1496 }
1497
1498 long oldOverlapTotal = 0;
1499 long oldOverlapN = 0;
1500 for (int x = 0; x < width; x++) {
1501 for (int y = 0; y < height; y++) {
1502 oldOverlapTotal += overlapMatrix[x][y];
1503 if (overlapMatrix[x][y] > 0) {
1504 oldOverlapN++;
1505 }
1506 }
1507 }
1508
1509
1510 double oldOverlapAvg = (double) oldOverlapTotal / (double) oldOverlapN;
1511 boolean first = true;
1512 int windowX = window.getX();
1513 int windowY = window.getY();
1514
1515 // For each possible (x, y) position for the new window, compute a
1516 // new overlap matrix.
1517 for (int x = xMin; x < xMax; x++) {
1518 for (int y = yMin; y < yMax; y++) {
1519
1520 // Start with the matrix minus this window.
1521 int newMatrix[][] = new int[width][height];
1522 for (int mx = 0; mx < width; mx++) {
1523 for (int my = 0; my < height; my++) {
1524 newMatrix[mx][my] = overlapMatrix[mx][my];
1525 }
1526 }
1527
1528 // Add this window's values to the new overlap matrix.
1529 long newOverlapTotal = 0;
1530 long newOverlapN = 0;
1531 // Start by adding each new cell.
1532 for (int wx = x; wx < x + window.getWidth(); wx++) {
1533 if (wx == width) {
1534 continue;
1535 }
1536 for (int wy = y; wy < y + window.getHeight(); wy++) {
1537 if (wy == height) {
1538 continue;
1539 }
1540 newMatrix[wx][wy]++;
1541 }
1542 }
1543 // Now figure out the new value for total coverage.
1544 for (int mx = 0; mx < width; mx++) {
1545 for (int my = 0; my < height; my++) {
1546 newOverlapTotal += newMatrix[x][y];
1547 if (newMatrix[mx][my] > 0) {
1548 newOverlapN++;
1549 }
1550 }
1551 }
1552 double newOverlapAvg = (double) newOverlapTotal / (double) newOverlapN;
1553
1554 if (first) {
1555 // First time: just record what we got.
1556 oldOverlapAvg = newOverlapAvg;
1557 first = false;
1558 } else {
1559 // All other times: pick a new best (x, y) and save the
1560 // overlap value.
1561 if (newOverlapAvg < oldOverlapAvg) {
1562 windowX = x;
1563 windowY = y;
1564 oldOverlapAvg = newOverlapAvg;
1565 }
1566 }
1567
1568 } // for (int x = xMin; x < xMax; x++)
1569
1570 } // for (int y = yMin; y < yMax; y++)
1571
1572 // Finally, set the window's new coordinates.
1573 window.setX(windowX);
1574 window.setY(windowY);
1575 }
1576
1577 // ------------------------------------------------------------------------
1578 // TMenu management -------------------------------------------------------
1579 // ------------------------------------------------------------------------
1580
1581 /**
1582 * Check if a mouse event would hit either the active menu or any open
1583 * sub-menus.
1584 *
1585 * @param mouse mouse event
1586 * @return true if the mouse would hit the active menu or an open
1587 * sub-menu
1588 */
1589 private boolean mouseOnMenu(final TMouseEvent mouse) {
1590 assert (activeMenu != null);
1591 List<TMenu> menus = new LinkedList<TMenu>(subMenus);
1592 Collections.reverse(menus);
1593 for (TMenu menu: menus) {
1594 if (menu.mouseWouldHit(mouse)) {
1595 return true;
1596 }
1597 }
1598 return activeMenu.mouseWouldHit(mouse);
1599 }
1600
1601 /**
1602 * See if we need to switch window or activate the menu based on
1603 * a mouse click.
1604 *
1605 * @param mouse mouse event
1606 */
1607 private void checkSwitchFocus(final TMouseEvent mouse) {
1608
1609 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1610 && (activeMenu != null)
1611 && (mouse.getAbsoluteY() != 0)
1612 && (!mouseOnMenu(mouse))
1613 ) {
1614 // They clicked outside the active menu, turn it off
1615 activeMenu.setActive(false);
1616 activeMenu = null;
1617 for (TMenu menu: subMenus) {
1618 menu.setActive(false);
1619 }
1620 subMenus.clear();
1621 // Continue checks
1622 }
1623
1624 // See if they hit the menu bar
1625 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1626 && (mouse.isMouse1())
1627 && (!modalWindowActive())
1628 && (mouse.getAbsoluteY() == 0)
1629 ) {
1630
1631 for (TMenu menu: subMenus) {
1632 menu.setActive(false);
1633 }
1634 subMenus.clear();
1635
1636 // They selected the menu, go activate it
1637 for (TMenu menu: menus) {
1638 if ((mouse.getAbsoluteX() >= menu.getX())
1639 && (mouse.getAbsoluteX() < menu.getX()
1640 + menu.getTitle().length() + 2)
1641 ) {
1642 menu.setActive(true);
1643 activeMenu = menu;
1644 } else {
1645 menu.setActive(false);
1646 }
1647 }
1648 return;
1649 }
1650
1651 // See if they hit the menu bar
1652 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
1653 && (mouse.isMouse1())
1654 && (activeMenu != null)
1655 && (mouse.getAbsoluteY() == 0)
1656 ) {
1657
1658 TMenu oldMenu = activeMenu;
1659 for (TMenu menu: subMenus) {
1660 menu.setActive(false);
1661 }
1662 subMenus.clear();
1663
1664 // See if we should switch menus
1665 for (TMenu menu: menus) {
1666 if ((mouse.getAbsoluteX() >= menu.getX())
1667 && (mouse.getAbsoluteX() < menu.getX()
1668 + menu.getTitle().length() + 2)
1669 ) {
1670 menu.setActive(true);
1671 activeMenu = menu;
1672 }
1673 }
1674 if (oldMenu != activeMenu) {
1675 // They switched menus
1676 oldMenu.setActive(false);
1677 }
1678 return;
1679 }
1680
1681 // Only switch if there are multiple windows
1682 if (windows.size() < 2) {
1683 return;
1684 }
1685
1686 // Switch on the upclick
1687 if (mouse.getType() != TMouseEvent.Type.MOUSE_UP) {
1688 return;
1689 }
1690
1691 synchronized (windows) {
1692 Collections.sort(windows);
1693 if (windows.get(0).isModal()) {
1694 // Modal windows don't switch
1695 return;
1696 }
1697
1698 for (TWindow window: windows) {
1699 assert (!window.isModal());
1700 if (window.mouseWouldHit(mouse)) {
1701 if (window == windows.get(0)) {
1702 // Clicked on the same window, nothing to do
1703 return;
1704 }
1705
1706 // We will be switching to another window
1707 assert (windows.get(0).isActive());
1708 assert (!window.isActive());
1709 windows.get(0).onUnfocus();
1710 windows.get(0).setActive(false);
1711 windows.get(0).setZ(window.getZ());
1712 window.setZ(0);
1713 window.setActive(true);
1714 window.onFocus();
1715 return;
1716 }
1717 }
1718 }
1719
1720 // Clicked on the background, nothing to do
1721 return;
1722 }
1723
1724 /**
1725 * Turn off the menu.
1726 */
1727 public final void closeMenu() {
1728 if (activeMenu != null) {
1729 activeMenu.setActive(false);
1730 activeMenu = null;
1731 for (TMenu menu: subMenus) {
1732 menu.setActive(false);
1733 }
1734 subMenus.clear();
1735 }
1736 }
1737
1738 /**
1739 * Turn off a sub-menu.
1740 */
1741 public final void closeSubMenu() {
1742 assert (activeMenu != null);
1743 TMenu item = subMenus.get(subMenus.size() - 1);
1744 assert (item != null);
1745 item.setActive(false);
1746 subMenus.remove(subMenus.size() - 1);
1747 }
1748
1749 /**
1750 * Switch to the next menu.
1751 *
1752 * @param forward if true, then switch to the next menu in the list,
1753 * otherwise switch to the previous menu in the list
1754 */
1755 public final void switchMenu(final boolean forward) {
1756 assert (activeMenu != null);
1757
1758 for (TMenu menu: subMenus) {
1759 menu.setActive(false);
1760 }
1761 subMenus.clear();
1762
1763 for (int i = 0; i < menus.size(); i++) {
1764 if (activeMenu == menus.get(i)) {
1765 if (forward) {
1766 if (i < menus.size() - 1) {
1767 i++;
1768 }
1769 } else {
1770 if (i > 0) {
1771 i--;
1772 }
1773 }
1774 activeMenu.setActive(false);
1775 activeMenu = menus.get(i);
1776 activeMenu.setActive(true);
1777 return;
1778 }
1779 }
1780 }
1781
1782 /**
1783 * Add a menu item to the global list. If it has a keyboard accelerator,
1784 * that will be added the global hash.
1785 *
1786 * @param item the menu item
1787 */
1788 public final void addMenuItem(final TMenuItem item) {
1789 menuItems.add(item);
1790
1791 TKeypress key = item.getKey();
1792 if (key != null) {
1793 synchronized (accelerators) {
1794 assert (accelerators.get(key) == null);
1795 accelerators.put(key.toLowerCase(), item);
1796 }
1797 }
1798 }
1799
1800 /**
1801 * Disable one menu item.
1802 *
1803 * @param id the menu item ID
1804 */
1805 public final void disableMenuItem(final int id) {
1806 for (TMenuItem item: menuItems) {
1807 if (item.getId() == id) {
1808 item.setEnabled(false);
1809 }
1810 }
1811 }
1812
1813 /**
1814 * Disable the range of menu items with ID's between lower and upper,
1815 * inclusive.
1816 *
1817 * @param lower the lowest menu item ID
1818 * @param upper the highest menu item ID
1819 */
1820 public final void disableMenuItems(final int lower, final int upper) {
1821 for (TMenuItem item: menuItems) {
1822 if ((item.getId() >= lower) && (item.getId() <= upper)) {
1823 item.setEnabled(false);
1824 }
1825 }
1826 }
1827
1828 /**
1829 * Enable one menu item.
1830 *
1831 * @param id the menu item ID
1832 */
1833 public final void enableMenuItem(final int id) {
1834 for (TMenuItem item: menuItems) {
1835 if (item.getId() == id) {
1836 item.setEnabled(true);
1837 }
1838 }
1839 }
1840
1841 /**
1842 * Enable the range of menu items with ID's between lower and upper,
1843 * inclusive.
1844 *
1845 * @param lower the lowest menu item ID
1846 * @param upper the highest menu item ID
1847 */
1848 public final void enableMenuItems(final int lower, final int upper) {
1849 for (TMenuItem item: menuItems) {
1850 if ((item.getId() >= lower) && (item.getId() <= upper)) {
1851 item.setEnabled(true);
1852 }
1853 }
1854 }
1855
1856 /**
1857 * Recompute menu x positions based on their title length.
1858 */
1859 public final void recomputeMenuX() {
1860 int x = 0;
1861 for (TMenu menu: menus) {
1862 menu.setX(x);
1863 x += menu.getTitle().length() + 2;
1864 }
1865 }
1866
1867 /**
1868 * Post an event to process and turn off the menu.
1869 *
1870 * @param event new event to add to the queue
1871 */
1872 public final void postMenuEvent(final TInputEvent event) {
1873 synchronized (fillEventQueue) {
1874 fillEventQueue.add(event);
1875 }
1876 closeMenu();
1877 }
1878
1879 /**
1880 * Add a sub-menu to the list of open sub-menus.
1881 *
1882 * @param menu sub-menu
1883 */
1884 public final void addSubMenu(final TMenu menu) {
1885 subMenus.add(menu);
1886 }
1887
1888 /**
1889 * Convenience function to add a top-level menu.
1890 *
1891 * @param title menu title
1892 * @return the new menu
1893 */
1894 public final TMenu addMenu(final String title) {
1895 int x = 0;
1896 int y = 0;
1897 TMenu menu = new TMenu(this, x, y, title);
1898 menus.add(menu);
1899 recomputeMenuX();
1900 return menu;
1901 }
1902
1903 /**
1904 * Convenience function to add a default "File" menu.
1905 *
1906 * @return the new menu
1907 */
1908 public final TMenu addFileMenu() {
1909 TMenu fileMenu = addMenu("&File");
1910 fileMenu.addDefaultItem(TMenu.MID_OPEN_FILE);
1911 fileMenu.addSeparator();
1912 fileMenu.addDefaultItem(TMenu.MID_SHELL);
1913 fileMenu.addDefaultItem(TMenu.MID_EXIT);
1914 TStatusBar statusBar = fileMenu.newStatusBar("File-management " +
1915 "commands (Open, Save, Print, etc.)");
1916 statusBar.addShortcutKeypress(kbF1, cmHelp, "Help");
1917 return fileMenu;
1918 }
1919
1920 /**
1921 * Convenience function to add a default "Edit" menu.
1922 *
1923 * @return the new menu
1924 */
1925 public final TMenu addEditMenu() {
1926 TMenu editMenu = addMenu("&Edit");
1927 editMenu.addDefaultItem(TMenu.MID_CUT);
1928 editMenu.addDefaultItem(TMenu.MID_COPY);
1929 editMenu.addDefaultItem(TMenu.MID_PASTE);
1930 editMenu.addDefaultItem(TMenu.MID_CLEAR);
1931 TStatusBar statusBar = editMenu.newStatusBar("Editor operations, " +
1932 "undo, and Clipboard access");
1933 statusBar.addShortcutKeypress(kbF1, cmHelp, "Help");
1934 return editMenu;
1935 }
1936
1937 /**
1938 * Convenience function to add a default "Window" menu.
1939 *
1940 * @return the new menu
1941 */
1942 public final TMenu addWindowMenu() {
1943 TMenu windowMenu = addMenu("&Window");
1944 windowMenu.addDefaultItem(TMenu.MID_TILE);
1945 windowMenu.addDefaultItem(TMenu.MID_CASCADE);
1946 windowMenu.addDefaultItem(TMenu.MID_CLOSE_ALL);
1947 windowMenu.addSeparator();
1948 windowMenu.addDefaultItem(TMenu.MID_WINDOW_MOVE);
1949 windowMenu.addDefaultItem(TMenu.MID_WINDOW_ZOOM);
1950 windowMenu.addDefaultItem(TMenu.MID_WINDOW_NEXT);
1951 windowMenu.addDefaultItem(TMenu.MID_WINDOW_PREVIOUS);
1952 windowMenu.addDefaultItem(TMenu.MID_WINDOW_CLOSE);
1953 TStatusBar statusBar = windowMenu.newStatusBar("Open, arrange, and " +
1954 "list windows");
1955 statusBar.addShortcutKeypress(kbF1, cmHelp, "Help");
1956 return windowMenu;
1957 }
1958
1959 /**
1960 * Convenience function to add a default "Help" menu.
1961 *
1962 * @return the new menu
1963 */
1964 public final TMenu addHelpMenu() {
1965 TMenu helpMenu = addMenu("&Help");
1966 helpMenu.addDefaultItem(TMenu.MID_HELP_CONTENTS);
1967 helpMenu.addDefaultItem(TMenu.MID_HELP_INDEX);
1968 helpMenu.addDefaultItem(TMenu.MID_HELP_SEARCH);
1969 helpMenu.addDefaultItem(TMenu.MID_HELP_PREVIOUS);
1970 helpMenu.addDefaultItem(TMenu.MID_HELP_HELP);
1971 helpMenu.addDefaultItem(TMenu.MID_HELP_ACTIVE_FILE);
1972 helpMenu.addSeparator();
1973 helpMenu.addDefaultItem(TMenu.MID_ABOUT);
1974 TStatusBar statusBar = helpMenu.newStatusBar("Access online help");
1975 statusBar.addShortcutKeypress(kbF1, cmHelp, "Help");
1976 return helpMenu;
1977 }
1978
1979 // ------------------------------------------------------------------------
1980 // Event handlers ---------------------------------------------------------
1981 // ------------------------------------------------------------------------
1982
1983 /**
1984 * Method that TApplication subclasses can override to handle menu or
1985 * posted command events.
1986 *
1987 * @param command command event
1988 * @return if true, this event was consumed
1989 */
1990 protected boolean onCommand(final TCommandEvent command) {
1991 // Default: handle cmExit
1992 if (command.equals(cmExit)) {
1993 if (messageBox("Confirmation", "Exit application?",
1994 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
1995 quit = true;
1996 }
1997 return true;
1998 }
1999
2000 if (command.equals(cmShell)) {
2001 openTerminal(0, 0, TWindow.RESIZABLE);
2002 return true;
2003 }
2004
2005 if (command.equals(cmTile)) {
2006 tileWindows();
2007 return true;
2008 }
2009 if (command.equals(cmCascade)) {
2010 cascadeWindows();
2011 return true;
2012 }
2013 if (command.equals(cmCloseAll)) {
2014 closeAllWindows();
2015 return true;
2016 }
2017
2018 return false;
2019 }
2020
2021 /**
2022 * Method that TApplication subclasses can override to handle menu
2023 * events.
2024 *
2025 * @param menu menu event
2026 * @return if true, this event was consumed
2027 */
2028 protected boolean onMenu(final TMenuEvent menu) {
2029
2030 // Default: handle MID_EXIT
2031 if (menu.getId() == TMenu.MID_EXIT) {
2032 if (messageBox("Confirmation", "Exit application?",
2033 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
2034 quit = true;
2035 }
2036 return true;
2037 }
2038
2039 if (menu.getId() == TMenu.MID_SHELL) {
2040 openTerminal(0, 0, TWindow.RESIZABLE);
2041 return true;
2042 }
2043
2044 if (menu.getId() == TMenu.MID_TILE) {
2045 tileWindows();
2046 return true;
2047 }
2048 if (menu.getId() == TMenu.MID_CASCADE) {
2049 cascadeWindows();
2050 return true;
2051 }
2052 if (menu.getId() == TMenu.MID_CLOSE_ALL) {
2053 closeAllWindows();
2054 return true;
2055 }
2056 if (menu.getId() == TMenu.MID_ABOUT) {
2057 showAboutDialog();
2058 return true;
2059 }
2060 return false;
2061 }
2062
2063 /**
2064 * Method that TApplication subclasses can override to handle keystrokes.
2065 *
2066 * @param keypress keystroke event
2067 * @return if true, this event was consumed
2068 */
2069 protected boolean onKeypress(final TKeypressEvent keypress) {
2070 // Default: only menu shortcuts
2071
2072 // Process Alt-F, Alt-E, etc. menu shortcut keys
2073 if (!keypress.getKey().isFnKey()
2074 && keypress.getKey().isAlt()
2075 && !keypress.getKey().isCtrl()
2076 && (activeMenu == null)
2077 && !modalWindowActive()
2078 ) {
2079
2080 assert (subMenus.size() == 0);
2081
2082 for (TMenu menu: menus) {
2083 if (Character.toLowerCase(menu.getMnemonic().getShortcut())
2084 == Character.toLowerCase(keypress.getKey().getChar())
2085 ) {
2086 activeMenu = menu;
2087 menu.setActive(true);
2088 return true;
2089 }
2090 }
2091 }
2092
2093 return false;
2094 }
2095
2096 // ------------------------------------------------------------------------
2097 // TTimer management ------------------------------------------------------
2098 // ------------------------------------------------------------------------
2099
2100 /**
2101 * Get the amount of time I can sleep before missing a Timer tick.
2102 *
2103 * @param timeout = initial (maximum) timeout in millis
2104 * @return number of milliseconds between now and the next timer event
2105 */
2106 private long getSleepTime(final long timeout) {
2107 Date now = new Date();
2108 long nowTime = now.getTime();
2109 long sleepTime = timeout;
2110 for (TTimer timer: timers) {
2111 long nextTickTime = timer.getNextTick().getTime();
2112 if (nextTickTime < nowTime) {
2113 return 0;
2114 }
2115
2116 long timeDifference = nextTickTime - nowTime;
2117 if (timeDifference < sleepTime) {
2118 sleepTime = timeDifference;
2119 }
2120 }
2121 assert (sleepTime >= 0);
2122 assert (sleepTime <= timeout);
2123 return sleepTime;
2124 }
2125
2126 /**
2127 * Convenience function to add a timer.
2128 *
2129 * @param duration number of milliseconds to wait between ticks
2130 * @param recurring if true, re-schedule this timer after every tick
2131 * @param action function to call when button is pressed
2132 * @return the timer
2133 */
2134 public final TTimer addTimer(final long duration, final boolean recurring,
2135 final TAction action) {
2136
2137 TTimer timer = new TTimer(duration, recurring, action);
2138 synchronized (timers) {
2139 timers.add(timer);
2140 }
2141 return timer;
2142 }
2143
2144 /**
2145 * Convenience function to remove a timer.
2146 *
2147 * @param timer timer to remove
2148 */
2149 public final void removeTimer(final TTimer timer) {
2150 synchronized (timers) {
2151 timers.remove(timer);
2152 }
2153 }
2154
2155 // ------------------------------------------------------------------------
2156 // Other TWindow constructors ---------------------------------------------
2157 // ------------------------------------------------------------------------
2158
2159 /**
2160 * Convenience function to spawn a message box.
2161 *
2162 * @param title window title, will be centered along the top border
2163 * @param caption message to display. Use embedded newlines to get a
2164 * multi-line box.
2165 * @return the new message box
2166 */
2167 public final TMessageBox messageBox(final String title,
2168 final String caption) {
2169
2170 return new TMessageBox(this, title, caption, TMessageBox.Type.OK);
2171 }
2172
2173 /**
2174 * Convenience function to spawn a message box.
2175 *
2176 * @param title window title, will be centered along the top border
2177 * @param caption message to display. Use embedded newlines to get a
2178 * multi-line box.
2179 * @param type one of the TMessageBox.Type constants. Default is
2180 * Type.OK.
2181 * @return the new message box
2182 */
2183 public final TMessageBox messageBox(final String title,
2184 final String caption, final TMessageBox.Type type) {
2185
2186 return new TMessageBox(this, title, caption, type);
2187 }
2188
2189 /**
2190 * Convenience function to spawn an input box.
2191 *
2192 * @param title window title, will be centered along the top border
2193 * @param caption message to display. Use embedded newlines to get a
2194 * multi-line box.
2195 * @return the new input box
2196 */
2197 public final TInputBox inputBox(final String title, final String caption) {
2198
2199 return new TInputBox(this, title, caption);
2200 }
2201
2202 /**
2203 * Convenience function to spawn an input box.
2204 *
2205 * @param title window title, will be centered along the top border
2206 * @param caption message to display. Use embedded newlines to get a
2207 * multi-line box.
2208 * @param text initial text to seed the field with
2209 * @return the new input box
2210 */
2211 public final TInputBox inputBox(final String title, final String caption,
2212 final String text) {
2213
2214 return new TInputBox(this, title, caption, text);
2215 }
2216
2217 /**
2218 * Convenience function to open a terminal window.
2219 *
2220 * @param x column relative to parent
2221 * @param y row relative to parent
2222 * @return the terminal new window
2223 */
2224 public final TTerminalWindow openTerminal(final int x, final int y) {
2225 return openTerminal(x, y, TWindow.RESIZABLE);
2226 }
2227
2228 /**
2229 * Convenience function to open a terminal window.
2230 *
2231 * @param x column relative to parent
2232 * @param y row relative to parent
2233 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2234 * @return the terminal new window
2235 */
2236 public final TTerminalWindow openTerminal(final int x, final int y,
2237 final int flags) {
2238
2239 return new TTerminalWindow(this, x, y, flags);
2240 }
2241
2242 /**
2243 * Convenience function to spawn an file open box.
2244 *
2245 * @param path path of selected file
2246 * @return the result of the new file open box
2247 * @throws IOException if java.io operation throws
2248 */
2249 public final String fileOpenBox(final String path) throws IOException {
2250
2251 TFileOpenBox box = new TFileOpenBox(this, path, TFileOpenBox.Type.OPEN);
2252 return box.getFilename();
2253 }
2254
2255 /**
2256 * Convenience function to spawn an file open box.
2257 *
2258 * @param path path of selected file
2259 * @param type one of the Type constants
2260 * @return the result of the new file open box
2261 * @throws IOException if java.io operation throws
2262 */
2263 public final String fileOpenBox(final String path,
2264 final TFileOpenBox.Type type) throws IOException {
2265
2266 TFileOpenBox box = new TFileOpenBox(this, path, type);
2267 return box.getFilename();
2268 }
2269
2270 }