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