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