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