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