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