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