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