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