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