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