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