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