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