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