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