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