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