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