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