Test commit from within Eclipse
[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 */
7b5261bc 572 public final 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;
fca67db0 626 if (menu.getActive()) {
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
fca67db0 641 if (menu.getActive()) {
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();
662 if (activeWidget.visibleCursor()) {
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 ) {
92554d64
KL
694 // Never sleep longer than 100 millis, to get windows with
695 // background tasks an opportunity to update the display.
696 timeout = getSleepTime(100);
697
698 // See if there are any definitely events waiting to be
699 // processed. If so, do not wait -- either there is I/O
700 // coming in or the primary/secondary threads are still
701 // working.
702 synchronized (drainEventQueue) {
703 if (drainEventQueue.size() > 0) {
704 timeout = 0;
705 }
706 }
707 synchronized (fillEventQueue) {
708 if (fillEventQueue.size() > 0) {
709 timeout = 0;
710 }
8e688b92
KL
711 }
712 }
92554d64
KL
713
714 if (timeout > 0) {
715 // As of now, I've got nothing to do: no I/O, nothing from
716 // the consumer threads, no timers that need to run ASAP. So
717 // wait until either the backend or the consumer threads have
718 // something to do.
719 try {
720 synchronized (this) {
721 this.wait(timeout);
722 }
723 } catch (InterruptedException e) {
724 // I'm awake and don't care why, let's see what's going
725 // on out there.
8e688b92 726 }
bd8d51fa 727 repaint = true;
7b5261bc
KL
728 }
729
8e688b92 730 // Pull any pending I/O events
92554d64 731 backend.getEvents(fillEventQueue);
8e688b92
KL
732
733 // Dispatch each event to the appropriate handler, one at a time.
734 for (;;) {
735 TInputEvent event = null;
736 synchronized (fillEventQueue) {
737 if (fillEventQueue.size() == 0) {
738 break;
739 }
740 event = fillEventQueue.remove(0);
741 }
742 metaHandleEvent(event);
743 }
7b5261bc 744
92554d64
KL
745 // Wake a consumer thread if we have any pending events.
746 synchronized (drainEventQueue) {
747 if (drainEventQueue.size() > 0) {
748 wakeEventHandler();
749 }
750 }
751
99144c71
KL
752 // Prevent stepping on the primary or secondary event handler.
753 stopEventHandlers();
754
7b5261bc
KL
755 // Process timers and call doIdle()'s
756 doIdle();
757
758 // Update the screen
87a17f3c
KL
759 synchronized (getScreen()) {
760 drawAll();
761 }
99144c71
KL
762
763 // Let the event handlers run again.
764 startEventHandlers();
7b5261bc 765
92554d64
KL
766 } // while (!quit)
767
768 // Shutdown the event consumer threads
769 if (secondaryEventHandler != null) {
770 synchronized (secondaryEventHandler) {
771 secondaryEventHandler.notify();
772 }
773 }
774 if (primaryEventHandler != null) {
775 synchronized (primaryEventHandler) {
776 primaryEventHandler.notify();
777 }
7b5261bc
KL
778 }
779
92554d64 780 // Shutdown the user I/O thread(s)
7b5261bc 781 backend.shutdown();
92554d64
KL
782
783 // Close all the windows. This gives them an opportunity to release
784 // resources.
785 closeAllWindows();
786
4328bb42
KL
787 }
788
789 /**
790 * Peek at certain application-level events, add to eventQueue, and wake
8e688b92 791 * up the consuming Thread.
4328bb42 792 *
8e688b92 793 * @param event the input event to consume
4328bb42 794 */
8e688b92 795 private void metaHandleEvent(final TInputEvent event) {
7b5261bc 796
a83fea2b
KL
797 if (debugEvents) {
798 System.err.printf(String.format("metaHandleEvents event: %s\n",
799 event)); System.err.flush();
800 }
7b5261bc 801
8e688b92
KL
802 if (quit) {
803 // Do no more processing if the application is already trying
804 // to exit.
805 return;
806 }
7b5261bc 807
8e688b92 808 // Special application-wide events -------------------------------
7b5261bc 809
8e688b92
KL
810 // Abort everything
811 if (event instanceof TCommandEvent) {
812 TCommandEvent command = (TCommandEvent) event;
813 if (command.getCmd().equals(cmAbort)) {
814 quit = true;
815 return;
7b5261bc 816 }
8e688b92 817 }
7b5261bc 818
8e688b92
KL
819 // Screen resize
820 if (event instanceof TResizeEvent) {
821 TResizeEvent resize = (TResizeEvent) event;
bd8d51fa
KL
822 synchronized (getScreen()) {
823 getScreen().setDimensions(resize.getWidth(),
824 resize.getHeight());
825 desktopBottom = getScreen().getHeight() - 1;
826 mouseX = 0;
827 mouseY = 0;
828 oldMouseX = 0;
829 oldMouseY = 0;
830 }
8e688b92
KL
831 return;
832 }
7b5261bc 833
8e688b92
KL
834 // Peek at the mouse position
835 if (event instanceof TMouseEvent) {
836 TMouseEvent mouse = (TMouseEvent) event;
bd8d51fa
KL
837 synchronized (getScreen()) {
838 if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
839 oldMouseX = mouseX;
840 oldMouseY = mouseY;
841 mouseX = mouse.getX();
842 mouseY = mouse.getY();
843 }
7b5261bc 844 }
8e688b92 845 }
7b5261bc 846
bd8d51fa 847 // Put into the main queue
c6940ed9
KL
848 synchronized (drainEventQueue) {
849 drainEventQueue.add(event);
850 }
4328bb42
KL
851 }
852
a06459bd
KL
853 /**
854 * Dispatch one event to the appropriate widget or application-level
fca67db0
KL
855 * event handler. This is the primary event handler, it has the normal
856 * application-wide event handling.
a06459bd
KL
857 *
858 * @param event the input event to consume
fca67db0 859 * @see #secondaryHandleEvent(TInputEvent event)
a06459bd 860 */
fca67db0
KL
861 private void primaryHandleEvent(final TInputEvent event) {
862
a83fea2b
KL
863 if (debugEvents) {
864 System.err.printf("Handle event: %s\n", event);
865 }
fca67db0
KL
866
867 // Special application-wide events -----------------------------------
868
869 // Peek at the mouse position
870 if (event instanceof TMouseEvent) {
871 // See if we need to switch focus to another window or the menu
872 checkSwitchFocus((TMouseEvent) event);
873 }
874
875 // Handle menu events
876 if ((activeMenu != null) && !(event instanceof TCommandEvent)) {
877 TMenu menu = activeMenu;
878
879 if (event instanceof TMouseEvent) {
880 TMouseEvent mouse = (TMouseEvent) event;
881
882 while (subMenus.size() > 0) {
883 TMenu subMenu = subMenus.get(subMenus.size() - 1);
884 if (subMenu.mouseWouldHit(mouse)) {
885 break;
886 }
887 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
888 && (!mouse.getMouse1())
889 && (!mouse.getMouse2())
890 && (!mouse.getMouse3())
891 && (!mouse.getMouseWheelUp())
892 && (!mouse.getMouseWheelDown())
893 ) {
894 break;
895 }
896 // We navigated away from a sub-menu, so close it
897 closeSubMenu();
898 }
899
900 // Convert the mouse relative x/y to menu coordinates
901 assert (mouse.getX() == mouse.getAbsoluteX());
902 assert (mouse.getY() == mouse.getAbsoluteY());
903 if (subMenus.size() > 0) {
904 menu = subMenus.get(subMenus.size() - 1);
905 }
906 mouse.setX(mouse.getX() - menu.getX());
907 mouse.setY(mouse.getY() - menu.getY());
908 }
909 menu.handleEvent(event);
910 return;
911 }
a06459bd 912
fca67db0
KL
913 if (event instanceof TKeypressEvent) {
914 TKeypressEvent keypress = (TKeypressEvent) event;
e826b451 915
fca67db0
KL
916 // See if this key matches an accelerator, and if so dispatch the
917 // menu event.
918 TKeypress keypressLowercase = keypress.getKey().toLowerCase();
e826b451
KL
919 TMenuItem item = null;
920 synchronized (accelerators) {
921 item = accelerators.get(keypressLowercase);
922 }
fca67db0 923 if (item != null) {
bd8d51fa
KL
924 if (item.getEnabled()) {
925 // Let the menu item dispatch
926 item.dispatch();
fca67db0
KL
927 return;
928 }
929 }
bd8d51fa
KL
930 // Handle the keypress
931 if (onKeypress(keypress)) {
932 return;
933 }
fca67db0 934 }
a06459bd 935
fca67db0
KL
936 if (event instanceof TCommandEvent) {
937 if (onCommand((TCommandEvent) event)) {
938 return;
939 }
940 }
941
942 if (event instanceof TMenuEvent) {
943 if (onMenu((TMenuEvent) event)) {
944 return;
945 }
946 }
947
948 // Dispatch events to the active window -------------------------------
949 for (TWindow window: windows) {
950 if (window.getActive()) {
a06459bd
KL
951 if (event instanceof TMouseEvent) {
952 TMouseEvent mouse = (TMouseEvent) event;
fca67db0
KL
953 // Convert the mouse relative x/y to window coordinates
954 assert (mouse.getX() == mouse.getAbsoluteX());
955 assert (mouse.getY() == mouse.getAbsoluteY());
956 mouse.setX(mouse.getX() - window.getX());
957 mouse.setY(mouse.getY() - window.getY());
958 }
a83fea2b
KL
959 if (debugEvents) {
960 System.err.printf("TApplication dispatch event: %s\n",
961 event);
962 }
fca67db0
KL
963 window.handleEvent(event);
964 break;
965 }
966 }
967 }
968 /**
969 * Dispatch one event to the appropriate widget or application-level
970 * event handler. This is the secondary event handler used by certain
971 * special dialogs (currently TMessageBox and TFileOpenBox).
972 *
973 * @param event the input event to consume
974 * @see #primaryHandleEvent(TInputEvent event)
975 */
976 private void secondaryHandleEvent(final TInputEvent event) {
c6940ed9
KL
977 secondaryEventReceiver.handleEvent(event);
978 }
979
980 /**
981 * Enable a widget to override the primary event thread.
982 *
983 * @param widget widget that will receive events
984 */
985 public final void enableSecondaryEventReceiver(final TWidget widget) {
986 assert (secondaryEventReceiver == null);
987 assert (secondaryEventHandler == null);
988 assert (widget instanceof TMessageBox);
989 secondaryEventReceiver = widget;
990 secondaryEventHandler = new WidgetEventHandler(this, false);
991 (new Thread(secondaryEventHandler)).start();
c6940ed9
KL
992 }
993
994 /**
995 * Yield to the secondary thread.
996 */
997 public final void yield() {
998 assert (secondaryEventReceiver != null);
99144c71
KL
999 // This is where we handoff the event handler lock from the primary
1000 // to secondary thread. We unlock here, and in a future loop the
1001 // secondary thread locks again. When it gives up, we have the
1002 // single lock back.
1003 boolean oldLock = unlockHandleEvent();
1004 assert (oldLock == true);
1005
c6940ed9 1006 while (secondaryEventReceiver != null) {
92554d64 1007 synchronized (primaryEventHandler) {
c6940ed9 1008 try {
92554d64 1009 primaryEventHandler.wait();
c6940ed9
KL
1010 } catch (InterruptedException e) {
1011 // SQUASH
1012 }
1013 }
1014 }
a06459bd
KL
1015 }
1016
4328bb42
KL
1017 /**
1018 * Do stuff when there is no user input.
1019 */
1020 private void doIdle() {
99144c71
KL
1021 if (debugThreads) {
1022 System.err.printf("doIdle()\n");
1023 }
1024
7b5261bc 1025 // Now run any timers that have timed out
d502a0e9
KL
1026 Date now = new Date();
1027 List<TTimer> keepTimers = new LinkedList<TTimer>();
1028 for (TTimer timer: timers) {
92554d64 1029 if (timer.getNextTick().getTime() <= now.getTime()) {
d502a0e9 1030 timer.tick();
c6940ed9 1031 if (timer.recurring) {
d502a0e9 1032 keepTimers.add(timer);
7b5261bc
KL
1033 }
1034 } else {
d502a0e9 1035 keepTimers.add(timer);
7b5261bc
KL
1036 }
1037 }
1038 timers = keepTimers;
1039
1040 // Call onIdle's
d502a0e9
KL
1041 for (TWindow window: windows) {
1042 window.onIdle();
7b5261bc 1043 }
4328bb42 1044 }
7d4115a5 1045
4328bb42
KL
1046 /**
1047 * Get the amount of time I can sleep before missing a Timer tick.
1048 *
92554d64 1049 * @param timeout = initial (maximum) timeout in millis
4328bb42
KL
1050 * @return number of milliseconds between now and the next timer event
1051 */
bd8d51fa 1052 private long getSleepTime(final long timeout) {
d502a0e9 1053 Date now = new Date();
92554d64 1054 long nowTime = now.getTime();
d502a0e9
KL
1055 long sleepTime = timeout;
1056 for (TTimer timer: timers) {
92554d64
KL
1057 long nextTickTime = timer.getNextTick().getTime();
1058 if (nextTickTime < nowTime) {
7b5261bc
KL
1059 return 0;
1060 }
92554d64
KL
1061
1062 long timeDifference = nextTickTime - nowTime;
1063 if (timeDifference < sleepTime) {
1064 sleepTime = timeDifference;
7b5261bc
KL
1065 }
1066 }
d502a0e9 1067 assert (sleepTime >= 0);
92554d64
KL
1068 assert (sleepTime <= timeout);
1069 return sleepTime;
7d4115a5 1070 }
4328bb42 1071
48e27807
KL
1072 /**
1073 * Close window. Note that the window's destructor is NOT called by this
1074 * method, instead the GC is assumed to do the cleanup.
1075 *
1076 * @param window the window to remove
1077 */
1078 public final void closeWindow(final TWindow window) {
bb35d919
KL
1079 synchronized (windows) {
1080 int z = window.getZ();
1081 window.setZ(-1);
1082 Collections.sort(windows);
1083 windows.remove(0);
1084 TWindow activeWindow = null;
1085 for (TWindow w: windows) {
1086 if (w.getZ() > z) {
1087 w.setZ(w.getZ() - 1);
1088 if (w.getZ() == 0) {
1089 w.setActive(true);
1090 assert (activeWindow == null);
1091 activeWindow = w;
1092 } else {
1093 w.setActive(false);
1094 }
48e27807
KL
1095 }
1096 }
1097 }
1098
1099 // Perform window cleanup
1100 window.onClose();
1101
48e27807 1102 // Check if we are closing a TMessageBox or similar
c6940ed9
KL
1103 if (secondaryEventReceiver != null) {
1104 assert (secondaryEventHandler != null);
48e27807
KL
1105
1106 // Do not send events to the secondaryEventReceiver anymore, the
1107 // window is closed.
1108 secondaryEventReceiver = null;
1109
92554d64
KL
1110 // Wake the secondary thread, it will wake the primary as it
1111 // exits.
1112 synchronized (secondaryEventHandler) {
1113 secondaryEventHandler.notify();
48e27807
KL
1114 }
1115 }
48e27807
KL
1116 }
1117
1118 /**
1119 * Switch to the next window.
1120 *
1121 * @param forward if true, then switch to the next window in the list,
1122 * otherwise switch to the previous window in the list
1123 */
1124 public final void switchWindow(final boolean forward) {
48e27807 1125 // Only switch if there are multiple windows
fca67db0 1126 if (windows.size() < 2) {
48e27807
KL
1127 return;
1128 }
1129
bb35d919
KL
1130 synchronized (windows) {
1131
1132 // Swap z/active between active window and the next in the list
1133 int activeWindowI = -1;
1134 for (int i = 0; i < windows.size(); i++) {
1135 if (windows.get(i).getActive()) {
1136 activeWindowI = i;
1137 break;
1138 }
48e27807 1139 }
bb35d919 1140 assert (activeWindowI >= 0);
48e27807 1141
bb35d919
KL
1142 // Do not switch if a window is modal
1143 if (windows.get(activeWindowI).isModal()) {
1144 return;
1145 }
48e27807 1146
bb35d919
KL
1147 int nextWindowI;
1148 if (forward) {
1149 nextWindowI = (activeWindowI + 1) % windows.size();
48e27807 1150 } else {
bb35d919
KL
1151 if (activeWindowI == 0) {
1152 nextWindowI = windows.size() - 1;
1153 } else {
1154 nextWindowI = activeWindowI - 1;
1155 }
48e27807 1156 }
bb35d919
KL
1157 windows.get(activeWindowI).setActive(false);
1158 windows.get(activeWindowI).setZ(windows.get(nextWindowI).getZ());
1159 windows.get(nextWindowI).setZ(0);
1160 windows.get(nextWindowI).setActive(true);
1161
1162 } // synchronized (windows)
48e27807 1163
48e27807
KL
1164 }
1165
1166 /**
1167 * Add a window to my window list and make it active.
1168 *
1169 * @param window new window to add
1170 */
1171 public final void addWindow(final TWindow window) {
bb35d919
KL
1172 synchronized (windows) {
1173 // Do not allow a modal window to spawn a non-modal window
1174 if ((windows.size() > 0) && (windows.get(0).isModal())) {
1175 assert (window.isModal());
1176 }
1177 for (TWindow w: windows) {
1178 w.setActive(false);
1179 w.setZ(w.getZ() + 1);
1180 }
1181 windows.add(window);
1182 window.setActive(true);
1183 window.setZ(0);
48e27807 1184 }
48e27807
KL
1185 }
1186
fca67db0
KL
1187 /**
1188 * Check if there is a system-modal window on top.
1189 *
1190 * @return true if the active window is modal
1191 */
1192 private boolean modalWindowActive() {
1193 if (windows.size() == 0) {
1194 return false;
1195 }
1196 return windows.get(windows.size() - 1).isModal();
1197 }
1198
1199 /**
1200 * Check if a mouse event would hit either the active menu or any open
1201 * sub-menus.
1202 *
1203 * @param mouse mouse event
1204 * @return true if the mouse would hit the active menu or an open
1205 * sub-menu
1206 */
1207 private boolean mouseOnMenu(final TMouseEvent mouse) {
1208 assert (activeMenu != null);
1209 List<TMenu> menus = new LinkedList<TMenu>(subMenus);
1210 Collections.reverse(menus);
1211 for (TMenu menu: menus) {
1212 if (menu.mouseWouldHit(mouse)) {
1213 return true;
1214 }
1215 }
1216 return activeMenu.mouseWouldHit(mouse);
1217 }
1218
1219 /**
1220 * See if we need to switch window or activate the menu based on
1221 * a mouse click.
1222 *
1223 * @param mouse mouse event
1224 */
1225 private void checkSwitchFocus(final TMouseEvent mouse) {
1226
1227 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1228 && (activeMenu != null)
1229 && (mouse.getAbsoluteY() != 0)
1230 && (!mouseOnMenu(mouse))
1231 ) {
1232 // They clicked outside the active menu, turn it off
1233 activeMenu.setActive(false);
1234 activeMenu = null;
1235 for (TMenu menu: subMenus) {
1236 menu.setActive(false);
1237 }
1238 subMenus.clear();
1239 // Continue checks
1240 }
1241
1242 // See if they hit the menu bar
1243 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1244 && (mouse.getMouse1())
1245 && (!modalWindowActive())
1246 && (mouse.getAbsoluteY() == 0)
1247 ) {
1248
1249 for (TMenu menu: subMenus) {
1250 menu.setActive(false);
1251 }
1252 subMenus.clear();
1253
1254 // They selected the menu, go activate it
1255 for (TMenu menu: menus) {
1256 if ((mouse.getAbsoluteX() >= menu.getX())
1257 && (mouse.getAbsoluteX() < menu.getX()
1258 + menu.getTitle().length() + 2)
1259 ) {
1260 menu.setActive(true);
1261 activeMenu = menu;
1262 } else {
1263 menu.setActive(false);
1264 }
1265 }
fca67db0
KL
1266 return;
1267 }
1268
1269 // See if they hit the menu bar
1270 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
1271 && (mouse.getMouse1())
1272 && (activeMenu != null)
1273 && (mouse.getAbsoluteY() == 0)
1274 ) {
1275
1276 TMenu oldMenu = activeMenu;
1277 for (TMenu menu: subMenus) {
1278 menu.setActive(false);
1279 }
1280 subMenus.clear();
1281
1282 // See if we should switch menus
1283 for (TMenu menu: menus) {
1284 if ((mouse.getAbsoluteX() >= menu.getX())
1285 && (mouse.getAbsoluteX() < menu.getX()
1286 + menu.getTitle().length() + 2)
1287 ) {
1288 menu.setActive(true);
1289 activeMenu = menu;
1290 }
1291 }
1292 if (oldMenu != activeMenu) {
1293 // They switched menus
1294 oldMenu.setActive(false);
1295 }
fca67db0
KL
1296 return;
1297 }
1298
1299 // Only switch if there are multiple windows
1300 if (windows.size() < 2) {
1301 return;
1302 }
1303
1304 // Switch on the upclick
1305 if (mouse.getType() != TMouseEvent.Type.MOUSE_UP) {
1306 return;
1307 }
1308
bb35d919
KL
1309 synchronized (windows) {
1310 Collections.sort(windows);
1311 if (windows.get(0).isModal()) {
1312 // Modal windows don't switch
1313 return;
1314 }
fca67db0 1315
bb35d919
KL
1316 for (TWindow window: windows) {
1317 assert (!window.isModal());
1318 if (window.mouseWouldHit(mouse)) {
1319 if (window == windows.get(0)) {
1320 // Clicked on the same window, nothing to do
1321 return;
1322 }
1323
1324 // We will be switching to another window
1325 assert (windows.get(0).getActive());
1326 assert (!window.getActive());
1327 windows.get(0).setActive(false);
1328 windows.get(0).setZ(window.getZ());
1329 window.setZ(0);
1330 window.setActive(true);
fca67db0
KL
1331 return;
1332 }
fca67db0
KL
1333 }
1334 }
1335
1336 // Clicked on the background, nothing to do
1337 return;
1338 }
1339
1340 /**
1341 * Turn off the menu.
1342 */
928811d8 1343 public final void closeMenu() {
fca67db0
KL
1344 if (activeMenu != null) {
1345 activeMenu.setActive(false);
1346 activeMenu = null;
1347 for (TMenu menu: subMenus) {
1348 menu.setActive(false);
1349 }
1350 subMenus.clear();
1351 }
fca67db0
KL
1352 }
1353
1354 /**
1355 * Turn off a sub-menu.
1356 */
928811d8 1357 public final void closeSubMenu() {
fca67db0
KL
1358 assert (activeMenu != null);
1359 TMenu item = subMenus.get(subMenus.size() - 1);
1360 assert (item != null);
1361 item.setActive(false);
1362 subMenus.remove(subMenus.size() - 1);
fca67db0
KL
1363 }
1364
1365 /**
1366 * Switch to the next menu.
1367 *
1368 * @param forward if true, then switch to the next menu in the list,
1369 * otherwise switch to the previous menu in the list
1370 */
928811d8 1371 public final void switchMenu(final boolean forward) {
fca67db0
KL
1372 assert (activeMenu != null);
1373
1374 for (TMenu menu: subMenus) {
1375 menu.setActive(false);
1376 }
1377 subMenus.clear();
1378
1379 for (int i = 0; i < menus.size(); i++) {
1380 if (activeMenu == menus.get(i)) {
1381 if (forward) {
1382 if (i < menus.size() - 1) {
1383 i++;
1384 }
1385 } else {
1386 if (i > 0) {
1387 i--;
1388 }
1389 }
1390 activeMenu.setActive(false);
1391 activeMenu = menus.get(i);
1392 activeMenu.setActive(true);
fca67db0
KL
1393 return;
1394 }
1395 }
1396 }
1397
1398 /**
1399 * Method that TApplication subclasses can override to handle menu or
1400 * posted command events.
1401 *
1402 * @param command command event
1403 * @return if true, this event was consumed
1404 */
1405 protected boolean onCommand(final TCommandEvent command) {
fca67db0
KL
1406 // Default: handle cmExit
1407 if (command.equals(cmExit)) {
1408 if (messageBox("Confirmation", "Exit application?",
c6940ed9 1409 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
fca67db0
KL
1410 quit = true;
1411 }
fca67db0
KL
1412 return true;
1413 }
1414
1415 if (command.equals(cmShell)) {
34a42e78 1416 openTerminal(0, 0, TWindow.RESIZABLE);
fca67db0
KL
1417 return true;
1418 }
1419
1420 if (command.equals(cmTile)) {
1421 tileWindows();
fca67db0
KL
1422 return true;
1423 }
1424 if (command.equals(cmCascade)) {
1425 cascadeWindows();
fca67db0
KL
1426 return true;
1427 }
1428 if (command.equals(cmCloseAll)) {
1429 closeAllWindows();
fca67db0
KL
1430 return true;
1431 }
c6940ed9 1432
fca67db0
KL
1433 return false;
1434 }
1435
1436 /**
1437 * Method that TApplication subclasses can override to handle menu
1438 * events.
1439 *
1440 * @param menu menu event
1441 * @return if true, this event was consumed
1442 */
1443 protected boolean onMenu(final TMenuEvent menu) {
1444
fca67db0 1445 // Default: handle MID_EXIT
8e688b92 1446 if (menu.getId() == TMenu.MID_EXIT) {
fca67db0 1447 if (messageBox("Confirmation", "Exit application?",
c6940ed9 1448 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
fca67db0
KL
1449 quit = true;
1450 }
fca67db0
KL
1451 return true;
1452 }
1453
34a42e78
KL
1454 if (menu.getId() == TMenu.MID_SHELL) {
1455 openTerminal(0, 0, TWindow.RESIZABLE);
fca67db0
KL
1456 return true;
1457 }
1458
8e688b92 1459 if (menu.getId() == TMenu.MID_TILE) {
fca67db0 1460 tileWindows();
fca67db0
KL
1461 return true;
1462 }
8e688b92 1463 if (menu.getId() == TMenu.MID_CASCADE) {
fca67db0 1464 cascadeWindows();
fca67db0
KL
1465 return true;
1466 }
8e688b92 1467 if (menu.getId() == TMenu.MID_CLOSE_ALL) {
fca67db0 1468 closeAllWindows();
fca67db0
KL
1469 return true;
1470 }
fca67db0
KL
1471 return false;
1472 }
1473
1474 /**
1475 * Method that TApplication subclasses can override to handle keystrokes.
1476 *
1477 * @param keypress keystroke event
1478 * @return if true, this event was consumed
1479 */
1480 protected boolean onKeypress(final TKeypressEvent keypress) {
1481 // Default: only menu shortcuts
1482
1483 // Process Alt-F, Alt-E, etc. menu shortcut keys
1484 if (!keypress.getKey().getIsKey()
1485 && keypress.getKey().getAlt()
1486 && !keypress.getKey().getCtrl()
1487 && (activeMenu == null)
1488 ) {
1489
1490 assert (subMenus.size() == 0);
1491
1492 for (TMenu menu: menus) {
1493 if (Character.toLowerCase(menu.getMnemonic().getShortcut())
1494 == Character.toLowerCase(keypress.getKey().getCh())
1495 ) {
1496 activeMenu = menu;
1497 menu.setActive(true);
fca67db0
KL
1498 return true;
1499 }
1500 }
1501 }
1502
1503 return false;
1504 }
48e27807 1505
928811d8
KL
1506 /**
1507 * Add a keyboard accelerator to the global hash.
1508 *
1509 * @param item menu item this accelerator relates to
1510 * @param keypress keypress that will dispatch a TMenuEvent
1511 */
1512 public final void addAccelerator(final TMenuItem item,
1513 final TKeypress keypress) {
e826b451 1514
e826b451
KL
1515 synchronized (accelerators) {
1516 assert (accelerators.get(keypress) == null);
1517 accelerators.put(keypress, item);
1518 }
928811d8
KL
1519 }
1520
1521 /**
1522 * Recompute menu x positions based on their title length.
1523 */
1524 public final void recomputeMenuX() {
1525 int x = 0;
1526 for (TMenu menu: menus) {
1527 menu.setX(x);
1528 x += menu.getTitle().length() + 2;
1529 }
1530 }
1531
1532 /**
1533 * Post an event to process and turn off the menu.
1534 *
1535 * @param event new event to add to the queue
1536 */
1537 public final void addMenuEvent(final TInputEvent event) {
8e688b92
KL
1538 synchronized (fillEventQueue) {
1539 fillEventQueue.add(event);
1540 }
928811d8
KL
1541 closeMenu();
1542 }
1543
1544 /**
1545 * Add a sub-menu to the list of open sub-menus.
1546 *
1547 * @param menu sub-menu
1548 */
1549 public final void addSubMenu(final TMenu menu) {
1550 subMenus.add(menu);
1551 }
1552
8e688b92
KL
1553 /**
1554 * Convenience function to add a top-level menu.
1555 *
1556 * @param title menu title
1557 * @return the new menu
1558 */
87a17f3c 1559 public final TMenu addMenu(final String title) {
8e688b92
KL
1560 int x = 0;
1561 int y = 0;
1562 TMenu menu = new TMenu(this, x, y, title);
1563 menus.add(menu);
1564 recomputeMenuX();
1565 return menu;
1566 }
1567
1568 /**
1569 * Convenience function to add a default "File" menu.
1570 *
1571 * @return the new menu
1572 */
1573 public final TMenu addFileMenu() {
1574 TMenu fileMenu = addMenu("&File");
1575 fileMenu.addDefaultItem(TMenu.MID_OPEN_FILE);
1576 fileMenu.addSeparator();
1577 fileMenu.addDefaultItem(TMenu.MID_SHELL);
1578 fileMenu.addDefaultItem(TMenu.MID_EXIT);
1579 return fileMenu;
1580 }
1581
1582 /**
1583 * Convenience function to add a default "Edit" menu.
1584 *
1585 * @return the new menu
1586 */
1587 public final TMenu addEditMenu() {
1588 TMenu editMenu = addMenu("&Edit");
1589 editMenu.addDefaultItem(TMenu.MID_CUT);
1590 editMenu.addDefaultItem(TMenu.MID_COPY);
1591 editMenu.addDefaultItem(TMenu.MID_PASTE);
1592 editMenu.addDefaultItem(TMenu.MID_CLEAR);
1593 return editMenu;
1594 }
1595
1596 /**
1597 * Convenience function to add a default "Window" menu.
1598 *
1599 * @return the new menu
1600 */
c6940ed9 1601 public final TMenu addWindowMenu() {
8e688b92
KL
1602 TMenu windowMenu = addMenu("&Window");
1603 windowMenu.addDefaultItem(TMenu.MID_TILE);
1604 windowMenu.addDefaultItem(TMenu.MID_CASCADE);
1605 windowMenu.addDefaultItem(TMenu.MID_CLOSE_ALL);
1606 windowMenu.addSeparator();
1607 windowMenu.addDefaultItem(TMenu.MID_WINDOW_MOVE);
1608 windowMenu.addDefaultItem(TMenu.MID_WINDOW_ZOOM);
1609 windowMenu.addDefaultItem(TMenu.MID_WINDOW_NEXT);
1610 windowMenu.addDefaultItem(TMenu.MID_WINDOW_PREVIOUS);
1611 windowMenu.addDefaultItem(TMenu.MID_WINDOW_CLOSE);
1612 return windowMenu;
1613 }
1614
1615 /**
1616 * Close all open windows.
1617 */
1618 private void closeAllWindows() {
1619 // Don't do anything if we are in the menu
1620 if (activeMenu != null) {
1621 return;
1622 }
bb35d919
KL
1623
1624 synchronized (windows) {
1625 for (TWindow window: windows) {
1626 closeWindow(window);
1627 }
8e688b92
KL
1628 }
1629 }
1630
1631 /**
1632 * Re-layout the open windows as non-overlapping tiles. This produces
1633 * almost the same results as Turbo Pascal 7.0's IDE.
1634 */
1635 private void tileWindows() {
bb35d919
KL
1636 synchronized (windows) {
1637 // Don't do anything if we are in the menu
1638 if (activeMenu != null) {
1639 return;
8e688b92 1640 }
bb35d919
KL
1641 int z = windows.size();
1642 if (z == 0) {
1643 return;
1644 }
1645 int a = 0;
1646 int b = 0;
1647 a = (int)(Math.sqrt(z));
1648 int c = 0;
1649 while (c < a) {
1650 b = (z - c) / a;
1651 if (((a * b) + c) == z) {
1652 break;
1653 }
1654 c++;
8e688b92 1655 }
bb35d919
KL
1656 assert (a > 0);
1657 assert (b > 0);
1658 assert (c < a);
1659 int newWidth = (getScreen().getWidth() / a);
1660 int newHeight1 = ((getScreen().getHeight() - 1) / b);
1661 int newHeight2 = ((getScreen().getHeight() - 1) / (b + c));
1662
1663 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1664 Collections.sort(sorted);
1665 Collections.reverse(sorted);
1666 for (int i = 0; i < sorted.size(); i++) {
1667 int logicalX = i / b;
1668 int logicalY = i % b;
1669 if (i >= ((a - 1) * b)) {
1670 logicalX = a - 1;
1671 logicalY = i - ((a - 1) * b);
1672 }
8e688b92 1673
bb35d919
KL
1674 TWindow w = sorted.get(i);
1675 w.setX(logicalX * newWidth);
1676 w.setWidth(newWidth);
1677 if (i >= ((a - 1) * b)) {
1678 w.setY((logicalY * newHeight2) + 1);
1679 w.setHeight(newHeight2);
1680 } else {
1681 w.setY((logicalY * newHeight1) + 1);
1682 w.setHeight(newHeight1);
1683 }
8e688b92
KL
1684 }
1685 }
1686 }
1687
1688 /**
1689 * Re-layout the open windows as overlapping cascaded windows.
1690 */
1691 private void cascadeWindows() {
bb35d919
KL
1692 synchronized (windows) {
1693 // Don't do anything if we are in the menu
1694 if (activeMenu != null) {
1695 return;
8e688b92 1696 }
bb35d919
KL
1697 int x = 0;
1698 int y = 1;
1699 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1700 Collections.sort(sorted);
1701 Collections.reverse(sorted);
1702 for (TWindow window: sorted) {
1703 window.setX(x);
1704 window.setY(y);
1705 x++;
1706 y++;
1707 if (x > getScreen().getWidth()) {
1708 x = 0;
1709 }
1710 if (y >= getScreen().getHeight()) {
1711 y = 1;
1712 }
8e688b92
KL
1713 }
1714 }
1715 }
1716
d502a0e9
KL
1717 /**
1718 * Convenience function to add a timer.
1719 *
1720 * @param duration number of milliseconds to wait between ticks
1721 * @param recurring if true, re-schedule this timer after every tick
1722 * @param action function to call when button is pressed
c6940ed9 1723 * @return the timer
d502a0e9
KL
1724 */
1725 public final TTimer addTimer(final long duration, final boolean recurring,
1726 final TAction action) {
1727
1728 TTimer timer = new TTimer(duration, recurring, action);
1729 synchronized (timers) {
1730 timers.add(timer);
1731 }
1732 return timer;
1733 }
1734
1735 /**
1736 * Convenience function to remove a timer.
1737 *
1738 * @param timer timer to remove
1739 */
1740 public final void removeTimer(final TTimer timer) {
1741 synchronized (timers) {
1742 timers.remove(timer);
1743 }
1744 }
1745
c6940ed9
KL
1746 /**
1747 * Convenience function to spawn a message box.
1748 *
1749 * @param title window title, will be centered along the top border
1750 * @param caption message to display. Use embedded newlines to get a
1751 * multi-line box.
1752 * @return the new message box
1753 */
1754 public final TMessageBox messageBox(final String title,
1755 final String caption) {
1756
1757 return new TMessageBox(this, title, caption, TMessageBox.Type.OK);
1758 }
1759
1760 /**
1761 * Convenience function to spawn a message box.
1762 *
1763 * @param title window title, will be centered along the top border
1764 * @param caption message to display. Use embedded newlines to get a
1765 * multi-line box.
1766 * @param type one of the TMessageBox.Type constants. Default is
1767 * Type.OK.
1768 * @return the new message box
1769 */
1770 public final TMessageBox messageBox(final String title,
1771 final String caption, final TMessageBox.Type type) {
1772
1773 return new TMessageBox(this, title, caption, type);
1774 }
1775
1776 /**
1777 * Convenience function to spawn an input box.
1778 *
1779 * @param title window title, will be centered along the top border
1780 * @param caption message to display. Use embedded newlines to get a
1781 * multi-line box.
1782 * @return the new input box
1783 */
1784 public final TInputBox inputBox(final String title, final String caption) {
1785
1786 return new TInputBox(this, title, caption);
1787 }
1788
1789 /**
1790 * Convenience function to spawn an input box.
1791 *
1792 * @param title window title, will be centered along the top border
1793 * @param caption message to display. Use embedded newlines to get a
1794 * multi-line box.
1795 * @param text initial text to seed the field with
1796 * @return the new input box
1797 */
1798 public final TInputBox inputBox(final String title, final String caption,
1799 final String text) {
1800
1801 return new TInputBox(this, title, caption, text);
1802 }
1ac2ccb1 1803
34a42e78
KL
1804 /**
1805 * Convenience function to open a terminal window.
1806 *
1807 * @param x column relative to parent
1808 * @param y row relative to parent
1809 * @return the terminal new window
1810 */
1811 public final TTerminalWindow openTerminal(final int x, final int y) {
1812 return openTerminal(x, y, TWindow.RESIZABLE);
1813 }
1814
1815 /**
1816 * Convenience function to open a terminal window.
1817 *
1818 * @param x column relative to parent
1819 * @param y row relative to parent
1820 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1821 * @return the terminal new window
1822 */
1823 public final TTerminalWindow openTerminal(final int x, final int y,
1824 final int flags) {
1825
1826 return new TTerminalWindow(this, x, y, flags);
1827 }
1828
7d4115a5 1829}