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