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