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