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