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