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