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