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