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