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