Fix mouse on menu line
[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 }
68c5cd6b
KL
1046
1047 // Change menu edges if needed.
1048 recomputeMenuX();
1049
85c07c5e
KL
1050 // We are dirty, redraw the screen.
1051 doRepaint();
be72cb5c 1052 return;
0ee88b6d 1053 }
7b5261bc 1054
be72cb5c
KL
1055 // Put into the main queue
1056 drainEventQueue.add(event);
1057 }
4328bb42
KL
1058 }
1059
a06459bd
KL
1060 /**
1061 * Dispatch one event to the appropriate widget or application-level
fca67db0
KL
1062 * event handler. This is the primary event handler, it has the normal
1063 * application-wide event handling.
a06459bd
KL
1064 *
1065 * @param event the input event to consume
fca67db0 1066 * @see #secondaryHandleEvent(TInputEvent event)
a06459bd 1067 */
fca67db0
KL
1068 private void primaryHandleEvent(final TInputEvent event) {
1069
a83fea2b
KL
1070 if (debugEvents) {
1071 System.err.printf("Handle event: %s\n", event);
1072 }
fca67db0
KL
1073
1074 // Special application-wide events -----------------------------------
1075
1076 // Peek at the mouse position
1077 if (event instanceof TMouseEvent) {
e8a11f98
KL
1078 TMouseEvent mouse = (TMouseEvent) event;
1079 if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
1080 oldMouseX = mouseX;
1081 oldMouseY = mouseY;
1082 mouseX = mouse.getX();
1083 mouseY = mouse.getY();
1084 }
1085
fca67db0
KL
1086 // See if we need to switch focus to another window or the menu
1087 checkSwitchFocus((TMouseEvent) event);
1088 }
1089
1090 // Handle menu events
1091 if ((activeMenu != null) && !(event instanceof TCommandEvent)) {
1092 TMenu menu = activeMenu;
1093
1094 if (event instanceof TMouseEvent) {
1095 TMouseEvent mouse = (TMouseEvent) event;
1096
1097 while (subMenus.size() > 0) {
1098 TMenu subMenu = subMenus.get(subMenus.size() - 1);
1099 if (subMenu.mouseWouldHit(mouse)) {
1100 break;
1101 }
1102 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
7c870d89
KL
1103 && (!mouse.isMouse1())
1104 && (!mouse.isMouse2())
1105 && (!mouse.isMouse3())
1106 && (!mouse.isMouseWheelUp())
1107 && (!mouse.isMouseWheelDown())
fca67db0
KL
1108 ) {
1109 break;
1110 }
1111 // We navigated away from a sub-menu, so close it
1112 closeSubMenu();
1113 }
1114
1115 // Convert the mouse relative x/y to menu coordinates
1116 assert (mouse.getX() == mouse.getAbsoluteX());
1117 assert (mouse.getY() == mouse.getAbsoluteY());
1118 if (subMenus.size() > 0) {
1119 menu = subMenus.get(subMenus.size() - 1);
1120 }
1121 mouse.setX(mouse.getX() - menu.getX());
1122 mouse.setY(mouse.getY() - menu.getY());
1123 }
1124 menu.handleEvent(event);
1125 return;
1126 }
a06459bd 1127
fca67db0
KL
1128 if (event instanceof TKeypressEvent) {
1129 TKeypressEvent keypress = (TKeypressEvent) event;
e826b451 1130
5dfd1c11
KL
1131 // See if this key matches an accelerator, and is not being
1132 // shortcutted by the active window, and if so dispatch the menu
1133 // event.
1134 boolean windowWillShortcut = false;
92453213
KL
1135 if (activeWindow != null) {
1136 assert (activeWindow.isShown());
1137 if (activeWindow.isShortcutKeypress(keypress.getKey())) {
1138 // We do not process this key, it will be passed to the
1139 // window instead.
1140 windowWillShortcut = true;
5dfd1c11 1141 }
e826b451 1142 }
5dfd1c11 1143
2ce6dab2 1144 if (!windowWillShortcut && !modalWindowActive()) {
5dfd1c11
KL
1145 TKeypress keypressLowercase = keypress.getKey().toLowerCase();
1146 TMenuItem item = null;
1147 synchronized (accelerators) {
1148 item = accelerators.get(keypressLowercase);
1149 }
1150 if (item != null) {
1151 if (item.isEnabled()) {
1152 // Let the menu item dispatch
1153 item.dispatch();
1154 return;
1155 }
fca67db0 1156 }
5dfd1c11 1157
2ce6dab2
KL
1158 // Handle the keypress
1159 if (onKeypress(keypress)) {
1160 return;
1161 }
bd8d51fa 1162 }
fca67db0 1163 }
a06459bd 1164
fca67db0
KL
1165 if (event instanceof TCommandEvent) {
1166 if (onCommand((TCommandEvent) event)) {
1167 return;
1168 }
1169 }
1170
1171 if (event instanceof TMenuEvent) {
1172 if (onMenu((TMenuEvent) event)) {
1173 return;
1174 }
1175 }
1176
1177 // Dispatch events to the active window -------------------------------
0ee88b6d 1178 boolean dispatchToDesktop = true;
92453213
KL
1179 TWindow window = activeWindow;
1180 if (window != null) {
1181 assert (window.isActive());
1182 assert (window.isShown());
1183 if (event instanceof TMouseEvent) {
1184 TMouseEvent mouse = (TMouseEvent) event;
1185 // Convert the mouse relative x/y to window coordinates
1186 assert (mouse.getX() == mouse.getAbsoluteX());
1187 assert (mouse.getY() == mouse.getAbsoluteY());
1188 mouse.setX(mouse.getX() - window.getX());
1189 mouse.setY(mouse.getY() - window.getY());
1190
1191 if (window.mouseWouldHit(mouse)) {
0ee88b6d 1192 dispatchToDesktop = false;
fca67db0 1193 }
92453213
KL
1194 } else if (event instanceof TKeypressEvent) {
1195 dispatchToDesktop = false;
1196 }
0ee88b6d 1197
92453213
KL
1198 if (debugEvents) {
1199 System.err.printf("TApplication dispatch event: %s\n",
1200 event);
fca67db0 1201 }
92453213 1202 window.handleEvent(event);
fca67db0 1203 }
0ee88b6d
KL
1204 if (dispatchToDesktop) {
1205 // This event is fair game for the desktop to process.
1206 if (desktop != null) {
1207 desktop.handleEvent(event);
1208 }
1209 }
fca67db0 1210 }
0ee88b6d 1211
fca67db0
KL
1212 /**
1213 * Dispatch one event to the appropriate widget or application-level
1214 * event handler. This is the secondary event handler used by certain
1215 * special dialogs (currently TMessageBox and TFileOpenBox).
1216 *
1217 * @param event the input event to consume
1218 * @see #primaryHandleEvent(TInputEvent event)
1219 */
1220 private void secondaryHandleEvent(final TInputEvent event) {
e8a11f98
KL
1221 // Peek at the mouse position
1222 if (event instanceof TMouseEvent) {
1223 TMouseEvent mouse = (TMouseEvent) event;
1224 if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
1225 oldMouseX = mouseX;
1226 oldMouseY = mouseY;
1227 mouseX = mouse.getX();
1228 mouseY = mouse.getY();
1229 }
1230 }
1231
c6940ed9
KL
1232 secondaryEventReceiver.handleEvent(event);
1233 }
1234
1235 /**
1236 * Enable a widget to override the primary event thread.
1237 *
1238 * @param widget widget that will receive events
1239 */
1240 public final void enableSecondaryEventReceiver(final TWidget widget) {
be72cb5c
KL
1241 if (debugThreads) {
1242 System.err.println(System.currentTimeMillis() +
1243 " enableSecondaryEventReceiver()");
1244 }
1245
c6940ed9
KL
1246 assert (secondaryEventReceiver == null);
1247 assert (secondaryEventHandler == null);
a043164f
KL
1248 assert ((widget instanceof TMessageBox)
1249 || (widget instanceof TFileOpenBox));
c6940ed9
KL
1250 secondaryEventReceiver = widget;
1251 secondaryEventHandler = new WidgetEventHandler(this, false);
be72cb5c 1252
c6940ed9 1253 (new Thread(secondaryEventHandler)).start();
c6940ed9
KL
1254 }
1255
1256 /**
1257 * Yield to the secondary thread.
1258 */
1259 public final void yield() {
1260 assert (secondaryEventReceiver != null);
99144c71 1261
c6940ed9 1262 while (secondaryEventReceiver != null) {
92554d64 1263 synchronized (primaryEventHandler) {
c6940ed9 1264 try {
92554d64 1265 primaryEventHandler.wait();
c6940ed9
KL
1266 } catch (InterruptedException e) {
1267 // SQUASH
1268 }
1269 }
1270 }
a06459bd
KL
1271 }
1272
4328bb42
KL
1273 /**
1274 * Do stuff when there is no user input.
1275 */
1276 private void doIdle() {
99144c71 1277 if (debugThreads) {
be72cb5c
KL
1278 System.err.printf(System.currentTimeMillis() + " " +
1279 Thread.currentThread() + " doIdle()\n");
99144c71
KL
1280 }
1281
be72cb5c
KL
1282 synchronized (timers) {
1283
1284 if (debugThreads) {
1285 System.err.printf(System.currentTimeMillis() + " " +
1286 Thread.currentThread() + " doIdle() 2\n");
1287 }
1288
1289 // Run any timers that have timed out
1290 Date now = new Date();
1291 List<TTimer> keepTimers = new LinkedList<TTimer>();
1292 for (TTimer timer: timers) {
1293 if (timer.getNextTick().getTime() <= now.getTime()) {
1294 // Something might change, so repaint the screen.
1295 repaint = true;
1296 timer.tick();
1297 if (timer.recurring) {
1298 keepTimers.add(timer);
1299 }
1300 } else {
d502a0e9 1301 keepTimers.add(timer);
7b5261bc 1302 }
7b5261bc 1303 }
be72cb5c 1304 timers = keepTimers;
7b5261bc 1305 }
7b5261bc
KL
1306
1307 // Call onIdle's
d502a0e9
KL
1308 for (TWindow window: windows) {
1309 window.onIdle();
7b5261bc 1310 }
92453213
KL
1311 if (desktop != null) {
1312 desktop.onIdle();
1313 }
4328bb42 1314 }
7d4115a5 1315
2ce6dab2
KL
1316 // ------------------------------------------------------------------------
1317 // TWindow management -----------------------------------------------------
1318 // ------------------------------------------------------------------------
4328bb42 1319
92453213
KL
1320 /**
1321 * Return the total number of windows.
1322 *
1323 * @return the total number of windows
1324 */
1325 public final int windowCount() {
1326 return windows.size();
1327 }
1328
1329 /**
8c236a98 1330 * Return the number of windows that are showing.
92453213 1331 *
8c236a98 1332 * @return the number of windows that are showing on screen
92453213
KL
1333 */
1334 public final int shownWindowCount() {
1335 int n = 0;
1336 for (TWindow w: windows) {
1337 if (w.isShown()) {
1338 n++;
1339 }
1340 }
1341 return n;
1342 }
1343
8c236a98
KL
1344 /**
1345 * Return the number of windows that are hidden.
1346 *
1347 * @return the number of windows that are hidden
1348 */
1349 public final int hiddenWindowCount() {
1350 int n = 0;
1351 for (TWindow w: windows) {
1352 if (w.isHidden()) {
1353 n++;
1354 }
1355 }
1356 return n;
1357 }
1358
92453213
KL
1359 /**
1360 * Check if a window instance is in this application's window list.
1361 *
1362 * @param window window to look for
1363 * @return true if this window is in the list
1364 */
1365 public final boolean hasWindow(final TWindow window) {
1366 if (windows.size() == 0) {
1367 return false;
1368 }
1369 for (TWindow w: windows) {
1370 if (w == window) {
8c236a98 1371 assert (window.getApplication() == this);
92453213
KL
1372 return true;
1373 }
1374 }
1375 return false;
1376 }
1377
1378 /**
1379 * Activate a window: bring it to the top and have it receive events.
1380 *
1381 * @param window the window to become the new active window
1382 */
1383 public void activateWindow(final TWindow window) {
1384 if (hasWindow(window) == false) {
1385 /*
1386 * Someone has a handle to a window I don't have. Ignore this
1387 * request.
1388 */
1389 return;
1390 }
1391
fe0770f9
KL
1392 // Whatever window might be moving/dragging, stop it now.
1393 for (TWindow w: windows) {
1394 if (w.inMovements()) {
1395 w.stopMovements();
1396 }
1397 }
1398
92453213
KL
1399 assert (windows.size() > 0);
1400
1401 if (window.isHidden()) {
1402 // Unhiding will also activate.
1403 showWindow(window);
1404 return;
1405 }
1406 assert (window.isShown());
1407
1408 if (windows.size() == 1) {
1409 assert (window == windows.get(0));
1410 if (activeWindow == null) {
1411 activeWindow = window;
1412 window.setZ(0);
1413 activeWindow.setActive(true);
1414 activeWindow.onFocus();
1415 }
1416
1417 assert (window.isActive());
1418 assert (activeWindow == window);
1419 return;
1420 }
1421
1422 if (activeWindow == window) {
1423 assert (window.isActive());
1424
1425 // Window is already active, do nothing.
1426 return;
1427 }
1428
1429 assert (!window.isActive());
1430 if (activeWindow != null) {
1431 assert (activeWindow.getZ() == 0);
1432
1433 activeWindow.onUnfocus();
1434 activeWindow.setActive(false);
1435 activeWindow.setZ(window.getZ());
1436 }
1437 activeWindow = window;
1438 activeWindow.setZ(0);
1439 activeWindow.setActive(true);
1440 activeWindow.onFocus();
1441 return;
1442 }
1443
1444 /**
1445 * Hide a window.
1446 *
1447 * @param window the window to hide
1448 */
1449 public void hideWindow(final TWindow window) {
1450 if (hasWindow(window) == false) {
1451 /*
1452 * Someone has a handle to a window I don't have. Ignore this
1453 * request.
1454 */
1455 return;
1456 }
1457
fe0770f9
KL
1458 // Whatever window might be moving/dragging, stop it now.
1459 for (TWindow w: windows) {
1460 if (w.inMovements()) {
1461 w.stopMovements();
1462 }
1463 }
1464
92453213
KL
1465 assert (windows.size() > 0);
1466
1467 if (!window.hidden) {
1468 if (window == activeWindow) {
1469 if (shownWindowCount() > 1) {
1470 switchWindow(true);
1471 } else {
1472 activeWindow = null;
1473 window.setActive(false);
1474 window.onUnfocus();
1475 }
1476 }
1477 window.hidden = true;
1478 window.onHide();
1479 }
1480 }
1481
1482 /**
1483 * Show a window.
1484 *
1485 * @param window the window to show
1486 */
1487 public void showWindow(final TWindow window) {
1488 if (hasWindow(window) == false) {
1489 /*
1490 * Someone has a handle to a window I don't have. Ignore this
1491 * request.
1492 */
1493 return;
1494 }
1495
fe0770f9
KL
1496 // Whatever window might be moving/dragging, stop it now.
1497 for (TWindow w: windows) {
1498 if (w.inMovements()) {
1499 w.stopMovements();
1500 }
1501 }
1502
92453213
KL
1503 assert (windows.size() > 0);
1504
1505 if (window.hidden) {
1506 window.hidden = false;
1507 window.onShow();
1508 activateWindow(window);
1509 }
1510 }
1511
48e27807
KL
1512 /**
1513 * Close window. Note that the window's destructor is NOT called by this
1514 * method, instead the GC is assumed to do the cleanup.
1515 *
1516 * @param window the window to remove
1517 */
1518 public final void closeWindow(final TWindow window) {
92453213
KL
1519 if (hasWindow(window) == false) {
1520 /*
1521 * Someone has a handle to a window I don't have. Ignore this
1522 * request.
1523 */
1524 return;
1525 }
1526
bb35d919 1527 synchronized (windows) {
fe0770f9
KL
1528 // Whatever window might be moving/dragging, stop it now.
1529 for (TWindow w: windows) {
1530 if (w.inMovements()) {
1531 w.stopMovements();
1532 }
1533 }
1534
bb35d919
KL
1535 int z = window.getZ();
1536 window.setZ(-1);
efb7af1f 1537 window.onUnfocus();
bb35d919
KL
1538 Collections.sort(windows);
1539 windows.remove(0);
92453213 1540 activeWindow = null;
bb35d919
KL
1541 for (TWindow w: windows) {
1542 if (w.getZ() > z) {
1543 w.setZ(w.getZ() - 1);
1544 if (w.getZ() == 0) {
1545 w.setActive(true);
efb7af1f 1546 w.onFocus();
bb35d919
KL
1547 assert (activeWindow == null);
1548 activeWindow = w;
1549 } else {
efb7af1f
KL
1550 if (w.isActive()) {
1551 w.setActive(false);
1552 w.onUnfocus();
1553 }
bb35d919 1554 }
48e27807
KL
1555 }
1556 }
1557 }
1558
1559 // Perform window cleanup
1560 window.onClose();
1561
48e27807 1562 // Check if we are closing a TMessageBox or similar
c6940ed9
KL
1563 if (secondaryEventReceiver != null) {
1564 assert (secondaryEventHandler != null);
48e27807
KL
1565
1566 // Do not send events to the secondaryEventReceiver anymore, the
1567 // window is closed.
1568 secondaryEventReceiver = null;
1569
92554d64
KL
1570 // Wake the secondary thread, it will wake the primary as it
1571 // exits.
1572 synchronized (secondaryEventHandler) {
1573 secondaryEventHandler.notify();
48e27807
KL
1574 }
1575 }
92453213
KL
1576
1577 // Permit desktop to be active if it is the only thing left.
1578 if (desktop != null) {
1579 if (windows.size() == 0) {
1580 desktop.setActive(true);
1581 }
1582 }
48e27807
KL
1583 }
1584
1585 /**
1586 * Switch to the next window.
1587 *
1588 * @param forward if true, then switch to the next window in the list,
1589 * otherwise switch to the previous window in the list
1590 */
1591 public final void switchWindow(final boolean forward) {
8c236a98
KL
1592 // Only switch if there are multiple visible windows
1593 if (shownWindowCount() < 2) {
48e27807
KL
1594 return;
1595 }
92453213 1596 assert (activeWindow != null);
48e27807 1597
bb35d919 1598 synchronized (windows) {
fe0770f9
KL
1599 // Whatever window might be moving/dragging, stop it now.
1600 for (TWindow w: windows) {
1601 if (w.inMovements()) {
1602 w.stopMovements();
1603 }
1604 }
bb35d919
KL
1605
1606 // Swap z/active between active window and the next in the list
1607 int activeWindowI = -1;
1608 for (int i = 0; i < windows.size(); i++) {
92453213
KL
1609 if (windows.get(i) == activeWindow) {
1610 assert (activeWindow.isActive());
bb35d919
KL
1611 activeWindowI = i;
1612 break;
92453213
KL
1613 } else {
1614 assert (!windows.get(0).isActive());
bb35d919 1615 }
48e27807 1616 }
bb35d919 1617 assert (activeWindowI >= 0);
48e27807 1618
bb35d919 1619 // Do not switch if a window is modal
92453213 1620 if (activeWindow.isModal()) {
bb35d919
KL
1621 return;
1622 }
48e27807 1623
8c236a98
KL
1624 int nextWindowI = activeWindowI;
1625 for (;;) {
1626 if (forward) {
1627 nextWindowI++;
1628 nextWindowI %= windows.size();
bb35d919 1629 } else {
8c236a98
KL
1630 nextWindowI--;
1631 if (nextWindowI < 0) {
1632 nextWindowI = windows.size() - 1;
1633 }
bb35d919 1634 }
bb35d919 1635
8c236a98
KL
1636 if (windows.get(nextWindowI).isShown()) {
1637 activateWindow(windows.get(nextWindowI));
1638 break;
1639 }
1640 }
bb35d919 1641 } // synchronized (windows)
48e27807 1642
48e27807
KL
1643 }
1644
1645 /**
1646 * Add a window to my window list and make it active.
1647 *
1648 * @param window new window to add
1649 */
1650 public final void addWindow(final TWindow window) {
a7986f7b
KL
1651
1652 // Do not add menu windows to the window list.
1653 if (window instanceof TMenu) {
1654 return;
1655 }
1656
0ee88b6d
KL
1657 // Do not add the desktop to the window list.
1658 if (window instanceof TDesktop) {
1659 return;
1660 }
1661
bb35d919 1662 synchronized (windows) {
fe0770f9
KL
1663 // Whatever window might be moving/dragging, stop it now.
1664 for (TWindow w: windows) {
1665 if (w.inMovements()) {
1666 w.stopMovements();
1667 }
1668 }
1669
2ce6dab2
KL
1670 // Do not allow a modal window to spawn a non-modal window. If a
1671 // modal window is active, then this window will become modal
1672 // too.
1673 if (modalWindowActive()) {
1674 window.flags |= TWindow.MODAL;
a7986f7b 1675 window.flags |= TWindow.CENTERED;
92453213 1676 window.hidden = false;
bb35d919 1677 }
92453213
KL
1678 if (window.isShown()) {
1679 for (TWindow w: windows) {
1680 if (w.isActive()) {
1681 w.setActive(false);
1682 w.onUnfocus();
1683 }
1684 w.setZ(w.getZ() + 1);
efb7af1f 1685 }
bb35d919
KL
1686 }
1687 windows.add(window);
92453213
KL
1688 if (window.isShown()) {
1689 activeWindow = window;
1690 activeWindow.setZ(0);
1691 activeWindow.setActive(true);
1692 activeWindow.onFocus();
1693 }
a7986f7b
KL
1694
1695 if (((window.flags & TWindow.CENTERED) == 0)
1696 && smartWindowPlacement) {
1697
1698 doSmartPlacement(window);
1699 }
48e27807 1700 }
92453213
KL
1701
1702 // Desktop cannot be active over any other window.
1703 if (desktop != null) {
1704 desktop.setActive(false);
1705 }
48e27807
KL
1706 }
1707
fca67db0
KL
1708 /**
1709 * Check if there is a system-modal window on top.
1710 *
1711 * @return true if the active window is modal
1712 */
1713 private boolean modalWindowActive() {
1714 if (windows.size() == 0) {
1715 return false;
1716 }
2ce6dab2
KL
1717
1718 for (TWindow w: windows) {
1719 if (w.isModal()) {
1720 return true;
1721 }
1722 }
1723
1724 return false;
1725 }
1726
1727 /**
1728 * Close all open windows.
1729 */
1730 private void closeAllWindows() {
1731 // Don't do anything if we are in the menu
1732 if (activeMenu != null) {
1733 return;
1734 }
1735 while (windows.size() > 0) {
1736 closeWindow(windows.get(0));
1737 }
fca67db0
KL
1738 }
1739
2ce6dab2
KL
1740 /**
1741 * Re-layout the open windows as non-overlapping tiles. This produces
1742 * almost the same results as Turbo Pascal 7.0's IDE.
1743 */
1744 private void tileWindows() {
1745 synchronized (windows) {
1746 // Don't do anything if we are in the menu
1747 if (activeMenu != null) {
1748 return;
1749 }
1750 int z = windows.size();
1751 if (z == 0) {
1752 return;
1753 }
1754 int a = 0;
1755 int b = 0;
1756 a = (int)(Math.sqrt(z));
1757 int c = 0;
1758 while (c < a) {
1759 b = (z - c) / a;
1760 if (((a * b) + c) == z) {
1761 break;
1762 }
1763 c++;
1764 }
1765 assert (a > 0);
1766 assert (b > 0);
1767 assert (c < a);
1768 int newWidth = (getScreen().getWidth() / a);
1769 int newHeight1 = ((getScreen().getHeight() - 1) / b);
1770 int newHeight2 = ((getScreen().getHeight() - 1) / (b + c));
1771
1772 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1773 Collections.sort(sorted);
1774 Collections.reverse(sorted);
1775 for (int i = 0; i < sorted.size(); i++) {
1776 int logicalX = i / b;
1777 int logicalY = i % b;
1778 if (i >= ((a - 1) * b)) {
1779 logicalX = a - 1;
1780 logicalY = i - ((a - 1) * b);
1781 }
1782
1783 TWindow w = sorted.get(i);
1784 w.setX(logicalX * newWidth);
1785 w.setWidth(newWidth);
1786 if (i >= ((a - 1) * b)) {
1787 w.setY((logicalY * newHeight2) + 1);
1788 w.setHeight(newHeight2);
1789 } else {
1790 w.setY((logicalY * newHeight1) + 1);
1791 w.setHeight(newHeight1);
1792 }
1793 }
1794 }
1795 }
1796
1797 /**
1798 * Re-layout the open windows as overlapping cascaded windows.
1799 */
1800 private void cascadeWindows() {
1801 synchronized (windows) {
1802 // Don't do anything if we are in the menu
1803 if (activeMenu != null) {
1804 return;
1805 }
1806 int x = 0;
1807 int y = 1;
1808 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1809 Collections.sort(sorted);
1810 Collections.reverse(sorted);
1811 for (TWindow window: sorted) {
1812 window.setX(x);
1813 window.setY(y);
1814 x++;
1815 y++;
1816 if (x > getScreen().getWidth()) {
1817 x = 0;
1818 }
1819 if (y >= getScreen().getHeight()) {
1820 y = 1;
1821 }
1822 }
1823 }
1824 }
1825
a7986f7b
KL
1826 /**
1827 * Place a window to minimize its overlap with other windows.
1828 *
1829 * @param window the window to place
1830 */
1831 public final void doSmartPlacement(final TWindow window) {
1832 // This is a pretty dumb algorithm, but seems to work. The hardest
1833 // part is computing these "overlap" values seeking a minimum average
1834 // overlap.
1835 int xMin = 0;
1836 int yMin = desktopTop;
1837 int xMax = getScreen().getWidth() - window.getWidth() + 1;
1838 int yMax = desktopBottom - window.getHeight() + 1;
1839 if (xMax < xMin) {
1840 xMax = xMin;
1841 }
1842 if (yMax < yMin) {
1843 yMax = yMin;
1844 }
1845
1846 if ((xMin == xMax) && (yMin == yMax)) {
1847 // No work to do, bail out.
1848 return;
1849 }
1850
1851 // Compute the overlap matrix without the new window.
1852 int width = getScreen().getWidth();
1853 int height = getScreen().getHeight();
1854 int overlapMatrix[][] = new int[width][height];
1855 for (TWindow w: windows) {
1856 if (window == w) {
1857 continue;
1858 }
1859 for (int x = w.getX(); x < w.getX() + w.getWidth(); x++) {
8c236a98 1860 if (x >= width) {
a7986f7b
KL
1861 continue;
1862 }
1863 for (int y = w.getY(); y < w.getY() + w.getHeight(); y++) {
8c236a98 1864 if (y >= height) {
a7986f7b
KL
1865 continue;
1866 }
1867 overlapMatrix[x][y]++;
1868 }
1869 }
1870 }
1871
1872 long oldOverlapTotal = 0;
1873 long oldOverlapN = 0;
1874 for (int x = 0; x < width; x++) {
1875 for (int y = 0; y < height; y++) {
1876 oldOverlapTotal += overlapMatrix[x][y];
1877 if (overlapMatrix[x][y] > 0) {
1878 oldOverlapN++;
1879 }
1880 }
1881 }
1882
1883
1884 double oldOverlapAvg = (double) oldOverlapTotal / (double) oldOverlapN;
1885 boolean first = true;
1886 int windowX = window.getX();
1887 int windowY = window.getY();
1888
1889 // For each possible (x, y) position for the new window, compute a
1890 // new overlap matrix.
1891 for (int x = xMin; x < xMax; x++) {
1892 for (int y = yMin; y < yMax; y++) {
1893
1894 // Start with the matrix minus this window.
1895 int newMatrix[][] = new int[width][height];
1896 for (int mx = 0; mx < width; mx++) {
1897 for (int my = 0; my < height; my++) {
1898 newMatrix[mx][my] = overlapMatrix[mx][my];
1899 }
1900 }
1901
1902 // Add this window's values to the new overlap matrix.
1903 long newOverlapTotal = 0;
1904 long newOverlapN = 0;
1905 // Start by adding each new cell.
1906 for (int wx = x; wx < x + window.getWidth(); wx++) {
8c236a98 1907 if (wx >= width) {
a7986f7b
KL
1908 continue;
1909 }
1910 for (int wy = y; wy < y + window.getHeight(); wy++) {
8c236a98 1911 if (wy >= height) {
a7986f7b
KL
1912 continue;
1913 }
1914 newMatrix[wx][wy]++;
1915 }
1916 }
1917 // Now figure out the new value for total coverage.
1918 for (int mx = 0; mx < width; mx++) {
1919 for (int my = 0; my < height; my++) {
1920 newOverlapTotal += newMatrix[x][y];
1921 if (newMatrix[mx][my] > 0) {
1922 newOverlapN++;
1923 }
1924 }
1925 }
1926 double newOverlapAvg = (double) newOverlapTotal / (double) newOverlapN;
1927
1928 if (first) {
1929 // First time: just record what we got.
1930 oldOverlapAvg = newOverlapAvg;
1931 first = false;
1932 } else {
1933 // All other times: pick a new best (x, y) and save the
1934 // overlap value.
1935 if (newOverlapAvg < oldOverlapAvg) {
1936 windowX = x;
1937 windowY = y;
1938 oldOverlapAvg = newOverlapAvg;
1939 }
1940 }
1941
1942 } // for (int x = xMin; x < xMax; x++)
1943
1944 } // for (int y = yMin; y < yMax; y++)
1945
1946 // Finally, set the window's new coordinates.
1947 window.setX(windowX);
1948 window.setY(windowY);
1949 }
1950
2ce6dab2
KL
1951 // ------------------------------------------------------------------------
1952 // TMenu management -------------------------------------------------------
1953 // ------------------------------------------------------------------------
1954
fca67db0
KL
1955 /**
1956 * Check if a mouse event would hit either the active menu or any open
1957 * sub-menus.
1958 *
1959 * @param mouse mouse event
1960 * @return true if the mouse would hit the active menu or an open
1961 * sub-menu
1962 */
1963 private boolean mouseOnMenu(final TMouseEvent mouse) {
1964 assert (activeMenu != null);
1965 List<TMenu> menus = new LinkedList<TMenu>(subMenus);
1966 Collections.reverse(menus);
1967 for (TMenu menu: menus) {
1968 if (menu.mouseWouldHit(mouse)) {
1969 return true;
1970 }
1971 }
1972 return activeMenu.mouseWouldHit(mouse);
1973 }
1974
1975 /**
1976 * See if we need to switch window or activate the menu based on
1977 * a mouse click.
1978 *
1979 * @param mouse mouse event
1980 */
1981 private void checkSwitchFocus(final TMouseEvent mouse) {
1982
1983 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1984 && (activeMenu != null)
1985 && (mouse.getAbsoluteY() != 0)
1986 && (!mouseOnMenu(mouse))
1987 ) {
1988 // They clicked outside the active menu, turn it off
1989 activeMenu.setActive(false);
1990 activeMenu = null;
1991 for (TMenu menu: subMenus) {
1992 menu.setActive(false);
1993 }
1994 subMenus.clear();
1995 // Continue checks
1996 }
1997
1998 // See if they hit the menu bar
1999 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
7c870d89 2000 && (mouse.isMouse1())
fca67db0
KL
2001 && (!modalWindowActive())
2002 && (mouse.getAbsoluteY() == 0)
2003 ) {
2004
2005 for (TMenu menu: subMenus) {
2006 menu.setActive(false);
2007 }
2008 subMenus.clear();
2009
2010 // They selected the menu, go activate it
2011 for (TMenu menu: menus) {
159f076d
KL
2012 if ((mouse.getAbsoluteX() >= menu.getTitleX())
2013 && (mouse.getAbsoluteX() < menu.getTitleX()
fca67db0
KL
2014 + menu.getTitle().length() + 2)
2015 ) {
2016 menu.setActive(true);
2017 activeMenu = menu;
2018 } else {
2019 menu.setActive(false);
2020 }
2021 }
fca67db0
KL
2022 return;
2023 }
2024
2025 // See if they hit the menu bar
2026 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
7c870d89 2027 && (mouse.isMouse1())
fca67db0
KL
2028 && (activeMenu != null)
2029 && (mouse.getAbsoluteY() == 0)
2030 ) {
2031
2032 TMenu oldMenu = activeMenu;
2033 for (TMenu menu: subMenus) {
2034 menu.setActive(false);
2035 }
2036 subMenus.clear();
2037
2038 // See if we should switch menus
2039 for (TMenu menu: menus) {
159f076d
KL
2040 if ((mouse.getAbsoluteX() >= menu.getTitleX())
2041 && (mouse.getAbsoluteX() < menu.getTitleX()
fca67db0
KL
2042 + menu.getTitle().length() + 2)
2043 ) {
2044 menu.setActive(true);
2045 activeMenu = menu;
2046 }
2047 }
2048 if (oldMenu != activeMenu) {
2049 // They switched menus
2050 oldMenu.setActive(false);
2051 }
fca67db0
KL
2052 return;
2053 }
2054
72fca17b
KL
2055 // If a menu is still active, don't switch windows
2056 if (activeMenu != null) {
fca67db0
KL
2057 return;
2058 }
2059
72fca17b
KL
2060 // Only switch if there are multiple windows
2061 if (windows.size() < 2) {
fca67db0
KL
2062 return;
2063 }
2064
72fca17b
KL
2065 if (((focusFollowsMouse == true)
2066 && (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION))
2067 || (mouse.getType() == TMouseEvent.Type.MOUSE_UP)
2068 ) {
2069 synchronized (windows) {
2070 Collections.sort(windows);
2071 if (windows.get(0).isModal()) {
2072 // Modal windows don't switch
2073 return;
2074 }
fca67db0 2075
72fca17b
KL
2076 for (TWindow window: windows) {
2077 assert (!window.isModal());
92453213 2078
72fca17b
KL
2079 if (window.isHidden()) {
2080 assert (!window.isActive());
2081 continue;
2082 }
92453213 2083
72fca17b
KL
2084 if (window.mouseWouldHit(mouse)) {
2085 if (window == windows.get(0)) {
2086 // Clicked on the same window, nothing to do
2087 assert (window.isActive());
2088 return;
2089 }
2090
2091 // We will be switching to another window
2092 assert (windows.get(0).isActive());
2093 assert (windows.get(0) == activeWindow);
2094 assert (!window.isActive());
2095 activeWindow.onUnfocus();
2096 activeWindow.setActive(false);
2097 activeWindow.setZ(window.getZ());
2098 activeWindow = window;
2099 window.setZ(0);
2100 window.setActive(true);
2101 window.onFocus();
bb35d919
KL
2102 return;
2103 }
fca67db0 2104 }
fca67db0 2105 }
72fca17b
KL
2106
2107 // Clicked on the background, nothing to do
2108 return;
fca67db0
KL
2109 }
2110
72fca17b
KL
2111 // Nothing to do: this isn't a mouse up, or focus isn't following
2112 // mouse.
fca67db0
KL
2113 return;
2114 }
2115
2116 /**
2117 * Turn off the menu.
2118 */
928811d8 2119 public final void closeMenu() {
fca67db0
KL
2120 if (activeMenu != null) {
2121 activeMenu.setActive(false);
2122 activeMenu = null;
2123 for (TMenu menu: subMenus) {
2124 menu.setActive(false);
2125 }
2126 subMenus.clear();
2127 }
fca67db0
KL
2128 }
2129
e8a11f98
KL
2130 /**
2131 * Get a (shallow) copy of the menu list.
2132 *
2133 * @return a copy of the menu list
2134 */
2135 public final List<TMenu> getAllMenus() {
2136 return new LinkedList<TMenu>(menus);
2137 }
2138
2139 /**
2140 * Add a top-level menu to the list.
2141 *
2142 * @param menu the menu to add
2143 * @throws IllegalArgumentException if the menu is already used in
2144 * another TApplication
2145 */
2146 public final void addMenu(final TMenu menu) {
2147 if ((menu.getApplication() != null)
2148 && (menu.getApplication() != this)
2149 ) {
2150 throw new IllegalArgumentException("Menu " + menu + " is already " +
2151 "part of application " + menu.getApplication());
2152 }
2153 closeMenu();
2154 menus.add(menu);
2155 recomputeMenuX();
2156 }
2157
2158 /**
2159 * Remove a top-level menu from the list.
2160 *
2161 * @param menu the menu to remove
2162 * @throws IllegalArgumentException if the menu is already used in
2163 * another TApplication
2164 */
2165 public final void removeMenu(final TMenu menu) {
2166 if ((menu.getApplication() != null)
2167 && (menu.getApplication() != this)
2168 ) {
2169 throw new IllegalArgumentException("Menu " + menu + " is already " +
2170 "part of application " + menu.getApplication());
2171 }
2172 closeMenu();
2173 menus.remove(menu);
2174 recomputeMenuX();
2175 }
2176
fca67db0
KL
2177 /**
2178 * Turn off a sub-menu.
2179 */
928811d8 2180 public final void closeSubMenu() {
fca67db0
KL
2181 assert (activeMenu != null);
2182 TMenu item = subMenus.get(subMenus.size() - 1);
2183 assert (item != null);
2184 item.setActive(false);
2185 subMenus.remove(subMenus.size() - 1);
fca67db0
KL
2186 }
2187
2188 /**
2189 * Switch to the next menu.
2190 *
2191 * @param forward if true, then switch to the next menu in the list,
2192 * otherwise switch to the previous menu in the list
2193 */
928811d8 2194 public final void switchMenu(final boolean forward) {
fca67db0
KL
2195 assert (activeMenu != null);
2196
2197 for (TMenu menu: subMenus) {
2198 menu.setActive(false);
2199 }
2200 subMenus.clear();
2201
2202 for (int i = 0; i < menus.size(); i++) {
2203 if (activeMenu == menus.get(i)) {
2204 if (forward) {
2205 if (i < menus.size() - 1) {
2206 i++;
2207 }
2208 } else {
2209 if (i > 0) {
2210 i--;
2211 }
2212 }
2213 activeMenu.setActive(false);
2214 activeMenu = menus.get(i);
2215 activeMenu.setActive(true);
fca67db0
KL
2216 return;
2217 }
2218 }
2219 }
2220
928811d8 2221 /**
efb7af1f
KL
2222 * Add a menu item to the global list. If it has a keyboard accelerator,
2223 * that will be added the global hash.
928811d8 2224 *
efb7af1f 2225 * @param item the menu item
928811d8 2226 */
efb7af1f
KL
2227 public final void addMenuItem(final TMenuItem item) {
2228 menuItems.add(item);
2229
2230 TKeypress key = item.getKey();
2231 if (key != null) {
2232 synchronized (accelerators) {
2233 assert (accelerators.get(key) == null);
2234 accelerators.put(key.toLowerCase(), item);
2235 }
2236 }
2237 }
2238
2239 /**
2240 * Disable one menu item.
2241 *
2242 * @param id the menu item ID
2243 */
2244 public final void disableMenuItem(final int id) {
2245 for (TMenuItem item: menuItems) {
2246 if (item.getId() == id) {
2247 item.setEnabled(false);
2248 }
2249 }
2250 }
e826b451 2251
efb7af1f
KL
2252 /**
2253 * Disable the range of menu items with ID's between lower and upper,
2254 * inclusive.
2255 *
2256 * @param lower the lowest menu item ID
2257 * @param upper the highest menu item ID
2258 */
2259 public final void disableMenuItems(final int lower, final int upper) {
2260 for (TMenuItem item: menuItems) {
2261 if ((item.getId() >= lower) && (item.getId() <= upper)) {
2262 item.setEnabled(false);
2263 }
2264 }
2265 }
2266
2267 /**
2268 * Enable one menu item.
2269 *
2270 * @param id the menu item ID
2271 */
2272 public final void enableMenuItem(final int id) {
2273 for (TMenuItem item: menuItems) {
2274 if (item.getId() == id) {
2275 item.setEnabled(true);
2276 }
2277 }
2278 }
2279
2280 /**
2281 * Enable the range of menu items with ID's between lower and upper,
2282 * inclusive.
2283 *
2284 * @param lower the lowest menu item ID
2285 * @param upper the highest menu item ID
2286 */
2287 public final void enableMenuItems(final int lower, final int upper) {
2288 for (TMenuItem item: menuItems) {
2289 if ((item.getId() >= lower) && (item.getId() <= upper)) {
2290 item.setEnabled(true);
2291 }
e826b451 2292 }
928811d8
KL
2293 }
2294
2295 /**
2296 * Recompute menu x positions based on their title length.
2297 */
2298 public final void recomputeMenuX() {
2299 int x = 0;
2300 for (TMenu menu: menus) {
2301 menu.setX(x);
159f076d 2302 menu.setTitleX(x);
928811d8 2303 x += menu.getTitle().length() + 2;
68c5cd6b
KL
2304
2305 // Don't let the menu window exceed the screen width
2306 int rightEdge = menu.getX() + menu.getWidth();
2307 if (rightEdge > getScreen().getWidth()) {
2308 menu.setX(getScreen().getWidth() - menu.getWidth());
2309 }
928811d8
KL
2310 }
2311 }
2312
2313 /**
2314 * Post an event to process and turn off the menu.
2315 *
2316 * @param event new event to add to the queue
2317 */
5dfd1c11 2318 public final void postMenuEvent(final TInputEvent event) {
be72cb5c
KL
2319 synchronized (this) {
2320 synchronized (fillEventQueue) {
2321 fillEventQueue.add(event);
2322 }
2323 if (debugThreads) {
2324 System.err.println(System.currentTimeMillis() + " " +
2325 Thread.currentThread() + " postMenuEvent() wake up main");
2326 }
2327 closeMenu();
2328 this.notify();
8e688b92 2329 }
928811d8
KL
2330 }
2331
2332 /**
2333 * Add a sub-menu to the list of open sub-menus.
2334 *
2335 * @param menu sub-menu
2336 */
2337 public final void addSubMenu(final TMenu menu) {
2338 subMenus.add(menu);
2339 }
2340
8e688b92
KL
2341 /**
2342 * Convenience function to add a top-level menu.
2343 *
2344 * @param title menu title
2345 * @return the new menu
2346 */
87a17f3c 2347 public final TMenu addMenu(final String title) {
8e688b92
KL
2348 int x = 0;
2349 int y = 0;
2350 TMenu menu = new TMenu(this, x, y, title);
2351 menus.add(menu);
2352 recomputeMenuX();
2353 return menu;
2354 }
2355
2356 /**
2357 * Convenience function to add a default "File" menu.
2358 *
2359 * @return the new menu
2360 */
2361 public final TMenu addFileMenu() {
339652cc 2362 TMenu fileMenu = addMenu(i18n.getString("fileMenuTitle"));
8e688b92
KL
2363 fileMenu.addDefaultItem(TMenu.MID_OPEN_FILE);
2364 fileMenu.addSeparator();
2365 fileMenu.addDefaultItem(TMenu.MID_SHELL);
2366 fileMenu.addDefaultItem(TMenu.MID_EXIT);
339652cc
KL
2367 TStatusBar statusBar = fileMenu.newStatusBar(i18n.
2368 getString("fileMenuStatus"));
2369 statusBar.addShortcutKeypress(kbF1, cmHelp, i18n.getString("Help"));
8e688b92
KL
2370 return fileMenu;
2371 }
2372
2373 /**
2374 * Convenience function to add a default "Edit" menu.
2375 *
2376 * @return the new menu
2377 */
2378 public final TMenu addEditMenu() {
339652cc 2379 TMenu editMenu = addMenu(i18n.getString("editMenuTitle"));
8e688b92
KL
2380 editMenu.addDefaultItem(TMenu.MID_CUT);
2381 editMenu.addDefaultItem(TMenu.MID_COPY);
2382 editMenu.addDefaultItem(TMenu.MID_PASTE);
2383 editMenu.addDefaultItem(TMenu.MID_CLEAR);
339652cc
KL
2384 TStatusBar statusBar = editMenu.newStatusBar(i18n.
2385 getString("editMenuStatus"));
2386 statusBar.addShortcutKeypress(kbF1, cmHelp, i18n.getString("Help"));
8e688b92
KL
2387 return editMenu;
2388 }
2389
2390 /**
2391 * Convenience function to add a default "Window" menu.
2392 *
2393 * @return the new menu
2394 */
c6940ed9 2395 public final TMenu addWindowMenu() {
339652cc 2396 TMenu windowMenu = addMenu(i18n.getString("windowMenuTitle"));
8e688b92
KL
2397 windowMenu.addDefaultItem(TMenu.MID_TILE);
2398 windowMenu.addDefaultItem(TMenu.MID_CASCADE);
2399 windowMenu.addDefaultItem(TMenu.MID_CLOSE_ALL);
2400 windowMenu.addSeparator();
2401 windowMenu.addDefaultItem(TMenu.MID_WINDOW_MOVE);
2402 windowMenu.addDefaultItem(TMenu.MID_WINDOW_ZOOM);
2403 windowMenu.addDefaultItem(TMenu.MID_WINDOW_NEXT);
2404 windowMenu.addDefaultItem(TMenu.MID_WINDOW_PREVIOUS);
2405 windowMenu.addDefaultItem(TMenu.MID_WINDOW_CLOSE);
339652cc
KL
2406 TStatusBar statusBar = windowMenu.newStatusBar(i18n.
2407 getString("windowMenuStatus"));
2408 statusBar.addShortcutKeypress(kbF1, cmHelp, i18n.getString("Help"));
8e688b92
KL
2409 return windowMenu;
2410 }
2411
55d2b2c2
KL
2412 /**
2413 * Convenience function to add a default "Help" menu.
2414 *
2415 * @return the new menu
2416 */
2417 public final TMenu addHelpMenu() {
339652cc 2418 TMenu helpMenu = addMenu(i18n.getString("helpMenuTitle"));
55d2b2c2
KL
2419 helpMenu.addDefaultItem(TMenu.MID_HELP_CONTENTS);
2420 helpMenu.addDefaultItem(TMenu.MID_HELP_INDEX);
2421 helpMenu.addDefaultItem(TMenu.MID_HELP_SEARCH);
2422 helpMenu.addDefaultItem(TMenu.MID_HELP_PREVIOUS);
2423 helpMenu.addDefaultItem(TMenu.MID_HELP_HELP);
2424 helpMenu.addDefaultItem(TMenu.MID_HELP_ACTIVE_FILE);
2425 helpMenu.addSeparator();
2426 helpMenu.addDefaultItem(TMenu.MID_ABOUT);
339652cc
KL
2427 TStatusBar statusBar = helpMenu.newStatusBar(i18n.
2428 getString("helpMenuStatus"));
2429 statusBar.addShortcutKeypress(kbF1, cmHelp, i18n.getString("Help"));
55d2b2c2
KL
2430 return helpMenu;
2431 }
2432
2ce6dab2
KL
2433 // ------------------------------------------------------------------------
2434 // Event handlers ---------------------------------------------------------
2435 // ------------------------------------------------------------------------
2436
8e688b92 2437 /**
2ce6dab2
KL
2438 * Method that TApplication subclasses can override to handle menu or
2439 * posted command events.
2440 *
2441 * @param command command event
2442 * @return if true, this event was consumed
8e688b92 2443 */
2ce6dab2
KL
2444 protected boolean onCommand(final TCommandEvent command) {
2445 // Default: handle cmExit
2446 if (command.equals(cmExit)) {
339652cc
KL
2447 if (messageBox(i18n.getString("exitDialogTitle"),
2448 i18n.getString("exitDialogText"),
2ce6dab2 2449 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
be72cb5c 2450 exit();
2ce6dab2
KL
2451 }
2452 return true;
8e688b92 2453 }
2ce6dab2
KL
2454
2455 if (command.equals(cmShell)) {
2456 openTerminal(0, 0, TWindow.RESIZABLE);
2457 return true;
2458 }
2459
2460 if (command.equals(cmTile)) {
2461 tileWindows();
2462 return true;
2463 }
2464 if (command.equals(cmCascade)) {
2465 cascadeWindows();
2466 return true;
2467 }
2468 if (command.equals(cmCloseAll)) {
2469 closeAllWindows();
2470 return true;
8e688b92 2471 }
2ce6dab2 2472
71a389c9
KL
2473 if (command.equals(cmMenu)) {
2474 if (!modalWindowActive() && (activeMenu == null)) {
2475 if (menus.size() > 0) {
2476 menus.get(0).setActive(true);
2477 activeMenu = menus.get(0);
2478 return true;
2479 }
2480 }
2481 }
2482
2ce6dab2 2483 return false;
8e688b92
KL
2484 }
2485
2486 /**
2ce6dab2
KL
2487 * Method that TApplication subclasses can override to handle menu
2488 * events.
2489 *
2490 * @param menu menu event
2491 * @return if true, this event was consumed
8e688b92 2492 */
2ce6dab2
KL
2493 protected boolean onMenu(final TMenuEvent menu) {
2494
2495 // Default: handle MID_EXIT
2496 if (menu.getId() == TMenu.MID_EXIT) {
339652cc
KL
2497 if (messageBox(i18n.getString("exitDialogTitle"),
2498 i18n.getString("exitDialogText"),
2ce6dab2 2499 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
be72cb5c 2500 exit();
8e688b92 2501 }
2ce6dab2
KL
2502 return true;
2503 }
bb35d919 2504
2ce6dab2
KL
2505 if (menu.getId() == TMenu.MID_SHELL) {
2506 openTerminal(0, 0, TWindow.RESIZABLE);
2507 return true;
2508 }
8e688b92 2509
2ce6dab2
KL
2510 if (menu.getId() == TMenu.MID_TILE) {
2511 tileWindows();
2512 return true;
2513 }
2514 if (menu.getId() == TMenu.MID_CASCADE) {
2515 cascadeWindows();
2516 return true;
2517 }
2518 if (menu.getId() == TMenu.MID_CLOSE_ALL) {
2519 closeAllWindows();
2520 return true;
2521 }
2522 if (menu.getId() == TMenu.MID_ABOUT) {
2523 showAboutDialog();
2524 return true;
2525 }
1c19fdea
KL
2526 if (menu.getId() == TMenu.MID_REPAINT) {
2527 doRepaint();
2528 return true;
2529 }
2ce6dab2
KL
2530 return false;
2531 }
2532
2533 /**
2534 * Method that TApplication subclasses can override to handle keystrokes.
2535 *
2536 * @param keypress keystroke event
2537 * @return if true, this event was consumed
2538 */
2539 protected boolean onKeypress(final TKeypressEvent keypress) {
2540 // Default: only menu shortcuts
2541
2542 // Process Alt-F, Alt-E, etc. menu shortcut keys
2543 if (!keypress.getKey().isFnKey()
2544 && keypress.getKey().isAlt()
2545 && !keypress.getKey().isCtrl()
2546 && (activeMenu == null)
2547 && !modalWindowActive()
2548 ) {
2549
2550 assert (subMenus.size() == 0);
2551
2552 for (TMenu menu: menus) {
2553 if (Character.toLowerCase(menu.getMnemonic().getShortcut())
2554 == Character.toLowerCase(keypress.getKey().getChar())
2555 ) {
2556 activeMenu = menu;
2557 menu.setActive(true);
2558 return true;
bb35d919 2559 }
8e688b92
KL
2560 }
2561 }
2ce6dab2
KL
2562
2563 return false;
8e688b92
KL
2564 }
2565
2ce6dab2
KL
2566 // ------------------------------------------------------------------------
2567 // TTimer management ------------------------------------------------------
2568 // ------------------------------------------------------------------------
2569
8e688b92 2570 /**
2ce6dab2
KL
2571 * Get the amount of time I can sleep before missing a Timer tick.
2572 *
2573 * @param timeout = initial (maximum) timeout in millis
2574 * @return number of milliseconds between now and the next timer event
8e688b92 2575 */
2ce6dab2
KL
2576 private long getSleepTime(final long timeout) {
2577 Date now = new Date();
2578 long nowTime = now.getTime();
2579 long sleepTime = timeout;
2ce6dab2 2580
be72cb5c
KL
2581 synchronized (timers) {
2582 for (TTimer timer: timers) {
2583 long nextTickTime = timer.getNextTick().getTime();
2584 if (nextTickTime < nowTime) {
2585 return 0;
2586 }
2587
2588 long timeDifference = nextTickTime - nowTime;
2589 if (timeDifference < sleepTime) {
2590 sleepTime = timeDifference;
2591 }
8e688b92
KL
2592 }
2593 }
be72cb5c 2594
2ce6dab2
KL
2595 assert (sleepTime >= 0);
2596 assert (sleepTime <= timeout);
2597 return sleepTime;
8e688b92
KL
2598 }
2599
d502a0e9
KL
2600 /**
2601 * Convenience function to add a timer.
2602 *
2603 * @param duration number of milliseconds to wait between ticks
2604 * @param recurring if true, re-schedule this timer after every tick
2605 * @param action function to call when button is pressed
c6940ed9 2606 * @return the timer
d502a0e9
KL
2607 */
2608 public final TTimer addTimer(final long duration, final boolean recurring,
2609 final TAction action) {
2610
2611 TTimer timer = new TTimer(duration, recurring, action);
2612 synchronized (timers) {
2613 timers.add(timer);
2614 }
2615 return timer;
2616 }
2617
2618 /**
2619 * Convenience function to remove a timer.
2620 *
2621 * @param timer timer to remove
2622 */
2623 public final void removeTimer(final TTimer timer) {
2624 synchronized (timers) {
2625 timers.remove(timer);
2626 }
2627 }
2628
2ce6dab2
KL
2629 // ------------------------------------------------------------------------
2630 // Other TWindow constructors ---------------------------------------------
2631 // ------------------------------------------------------------------------
2632
c6940ed9
KL
2633 /**
2634 * Convenience function to spawn a message box.
2635 *
2636 * @param title window title, will be centered along the top border
2637 * @param caption message to display. Use embedded newlines to get a
2638 * multi-line box.
2639 * @return the new message box
2640 */
2641 public final TMessageBox messageBox(final String title,
2642 final String caption) {
2643
2644 return new TMessageBox(this, title, caption, TMessageBox.Type.OK);
2645 }
2646
2647 /**
2648 * Convenience function to spawn a message box.
2649 *
2650 * @param title window title, will be centered along the top border
2651 * @param caption message to display. Use embedded newlines to get a
2652 * multi-line box.
2653 * @param type one of the TMessageBox.Type constants. Default is
2654 * Type.OK.
2655 * @return the new message box
2656 */
2657 public final TMessageBox messageBox(final String title,
2658 final String caption, final TMessageBox.Type type) {
2659
2660 return new TMessageBox(this, title, caption, type);
2661 }
2662
2663 /**
2664 * Convenience function to spawn an input box.
2665 *
2666 * @param title window title, will be centered along the top border
2667 * @param caption message to display. Use embedded newlines to get a
2668 * multi-line box.
2669 * @return the new input box
2670 */
2671 public final TInputBox inputBox(final String title, final String caption) {
2672
2673 return new TInputBox(this, title, caption);
2674 }
2675
2676 /**
2677 * Convenience function to spawn an input box.
2678 *
2679 * @param title window title, will be centered along the top border
2680 * @param caption message to display. Use embedded newlines to get a
2681 * multi-line box.
2682 * @param text initial text to seed the field with
2683 * @return the new input box
2684 */
2685 public final TInputBox inputBox(final String title, final String caption,
2686 final String text) {
2687
2688 return new TInputBox(this, title, caption, text);
2689 }
1ac2ccb1 2690
34a42e78
KL
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 * @return the terminal new window
2697 */
2698 public final TTerminalWindow openTerminal(final int x, final int y) {
2699 return openTerminal(x, y, TWindow.RESIZABLE);
2700 }
2701
2702 /**
2703 * Convenience function to open a terminal window.
2704 *
2705 * @param x column relative to parent
2706 * @param y row relative to parent
2707 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2708 * @return the terminal new window
2709 */
2710 public final TTerminalWindow openTerminal(final int x, final int y,
2711 final int flags) {
2712
2713 return new TTerminalWindow(this, x, y, flags);
2714 }
2715
0d47c546
KL
2716 /**
2717 * Convenience function to spawn an file open box.
2718 *
2719 * @param path path of selected file
2720 * @return the result of the new file open box
329fd62e 2721 * @throws IOException if java.io operation throws
0d47c546
KL
2722 */
2723 public final String fileOpenBox(final String path) throws IOException {
2724
2725 TFileOpenBox box = new TFileOpenBox(this, path, TFileOpenBox.Type.OPEN);
2726 return box.getFilename();
2727 }
2728
2729 /**
2730 * Convenience function to spawn an file open box.
2731 *
2732 * @param path path of selected file
2733 * @param type one of the Type constants
2734 * @return the result of the new file open box
329fd62e 2735 * @throws IOException if java.io operation throws
0d47c546
KL
2736 */
2737 public final String fileOpenBox(final String path,
2738 final TFileOpenBox.Type type) throws IOException {
2739
2740 TFileOpenBox box = new TFileOpenBox(this, path, type);
2741 return box.getFilename();
2742 }
2743
92453213
KL
2744 /**
2745 * Convenience function to create a new window and make it active.
2746 * Window will be located at (0, 0).
2747 *
2748 * @param title window title, will be centered along the top border
2749 * @param width width of window
2750 * @param height height of window
2751 */
2752 public final TWindow addWindow(final String title, final int width,
2753 final int height) {
2754
2755 TWindow window = new TWindow(this, title, 0, 0, width, height);
2756 return window;
2757 }
2758 /**
2759 * Convenience function to create a new window and make it active.
2760 * Window will be located at (0, 0).
2761 *
2762 * @param title window title, will be centered along the top border
2763 * @param width width of window
2764 * @param height height of window
2765 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2766 */
2767 public final TWindow addWindow(final String title,
2768 final int width, final int height, final int flags) {
2769
2770 TWindow window = new TWindow(this, title, 0, 0, width, height, flags);
2771 return window;
2772 }
2773
2774 /**
2775 * Convenience function to create a new window and make it active.
2776 *
2777 * @param title window title, will be centered along the top border
2778 * @param x column relative to parent
2779 * @param y row relative to parent
2780 * @param width width of window
2781 * @param height height of window
2782 */
2783 public final TWindow addWindow(final String title,
2784 final int x, final int y, final int width, final int height) {
2785
2786 TWindow window = new TWindow(this, title, x, y, width, height);
2787 return window;
2788 }
2789
2790 /**
2791 * Convenience function to create a new window and make it active.
2792 *
92453213
KL
2793 * @param title window title, will be centered along the top border
2794 * @param x column relative to parent
2795 * @param y row relative to parent
2796 * @param width width of window
2797 * @param height height of window
2798 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2799 */
2800 public final TWindow addWindow(final String title,
2801 final int x, final int y, final int width, final int height,
2802 final int flags) {
2803
2804 TWindow window = new TWindow(this, title, x, y, width, height, flags);
2805 return window;
2806 }
2807
7d4115a5 2808}