#13 focusFollowsMouse
[nikiroo-utils.git] / src / jexer / TApplication.java
1 /*
2 * Jexer - Java Text User Interface
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (C) 2017 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.InputStream;
32 import java.io.IOException;
33 import java.io.OutputStream;
34 import java.io.PrintWriter;
35 import java.io.Reader;
36 import java.io.UnsupportedEncodingException;
37 import java.util.Collections;
38 import java.util.Date;
39 import java.util.HashMap;
40 import java.util.ArrayList;
41 import java.util.LinkedList;
42 import java.util.List;
43 import java.util.Map;
44
45 import jexer.bits.CellAttributes;
46 import jexer.bits.ColorTheme;
47 import jexer.bits.GraphicsChars;
48 import jexer.event.TCommandEvent;
49 import jexer.event.TInputEvent;
50 import jexer.event.TKeypressEvent;
51 import jexer.event.TMenuEvent;
52 import jexer.event.TMouseEvent;
53 import jexer.event.TResizeEvent;
54 import jexer.backend.Backend;
55 import jexer.backend.SwingBackend;
56 import jexer.backend.ECMA48Backend;
57 import jexer.io.Screen;
58 import jexer.menu.TMenu;
59 import jexer.menu.TMenuItem;
60 import static jexer.TCommand.*;
61 import static jexer.TKeypress.*;
62
63 /**
64 * TApplication sets up a full Text User Interface application.
65 */
66 public class TApplication implements Runnable {
67
68 // ------------------------------------------------------------------------
69 // Public constants -------------------------------------------------------
70 // ------------------------------------------------------------------------
71
72 /**
73 * If true, emit thread stuff to System.err.
74 */
75 private static final boolean debugThreads = false;
76
77 /**
78 * If true, emit events being processed to System.err.
79 */
80 private static final boolean debugEvents = false;
81
82 /**
83 * If true, do "smart placement" on new windows that are not specified to
84 * be centered.
85 */
86 private static final boolean smartWindowPlacement = true;
87
88 /**
89 * Two backend types are available.
90 */
91 public static enum BackendType {
92 /**
93 * A Swing JFrame.
94 */
95 SWING,
96
97 /**
98 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
99 */
100 ECMA48,
101
102 /**
103 * Synonym for ECMA48.
104 */
105 XTERM
106 }
107
108 // ------------------------------------------------------------------------
109 // Primary/secondary event handlers ---------------------------------------
110 // ------------------------------------------------------------------------
111
112 /**
113 * WidgetEventHandler is the main event consumer loop. There are at most
114 * two such threads in existence: the primary for normal case and a
115 * secondary that is used for TMessageBox, TInputBox, and similar.
116 */
117 private class WidgetEventHandler implements Runnable {
118 /**
119 * The main application.
120 */
121 private TApplication application;
122
123 /**
124 * Whether or not this WidgetEventHandler is the primary or secondary
125 * thread.
126 */
127 private boolean primary = true;
128
129 /**
130 * Public constructor.
131 *
132 * @param application the main application
133 * @param primary if true, this is the primary event handler thread
134 */
135 public WidgetEventHandler(final TApplication application,
136 final boolean primary) {
137
138 this.application = application;
139 this.primary = primary;
140 }
141
142 /**
143 * The consumer loop.
144 */
145 public void run() {
146
147 // Loop forever
148 while (!application.quit) {
149
150 // Wait until application notifies me
151 while (!application.quit) {
152 try {
153 synchronized (application.drainEventQueue) {
154 if (application.drainEventQueue.size() > 0) {
155 break;
156 }
157 }
158
159 synchronized (this) {
160 if (debugThreads) {
161 System.err.printf("%s %s sleep\n", this,
162 primary ? "primary" : "secondary");
163 }
164
165 this.wait();
166
167 if (debugThreads) {
168 System.err.printf("%s %s AWAKE\n", this,
169 primary ? "primary" : "secondary");
170 }
171
172 if ((!primary)
173 && (application.secondaryEventReceiver == null)
174 ) {
175 // Secondary thread, emergency exit. If we
176 // got here then something went wrong with
177 // the handoff between yield() and
178 // closeWindow().
179 synchronized (application.primaryEventHandler) {
180 application.primaryEventHandler.notify();
181 }
182 application.secondaryEventHandler = null;
183 throw new RuntimeException(
184 "secondary exited at wrong time");
185 }
186 break;
187 }
188 } catch (InterruptedException e) {
189 // SQUASH
190 }
191 }
192
193 // Wait for drawAll() or doIdle() to be done, then handle the
194 // events.
195 boolean oldLock = lockHandleEvent();
196 assert (oldLock == false);
197
198 // Pull all events off the queue
199 for (;;) {
200 TInputEvent event = null;
201 synchronized (application.drainEventQueue) {
202 if (application.drainEventQueue.size() == 0) {
203 break;
204 }
205 event = application.drainEventQueue.remove(0);
206 }
207 application.repaint = true;
208 if (primary) {
209 primaryHandleEvent(event);
210 } else {
211 secondaryHandleEvent(event);
212 }
213 if ((!primary)
214 && (application.secondaryEventReceiver == null)
215 ) {
216 // Secondary thread, time to exit.
217
218 // DO NOT UNLOCK. Primary thread just came back from
219 // primaryHandleEvent() and will unlock in the else
220 // block below. Just wake it up.
221 synchronized (application.primaryEventHandler) {
222 application.primaryEventHandler.notify();
223 }
224 // Now eliminate my reference so that
225 // wakeEventHandler() resumes working on the primary.
226 application.secondaryEventHandler = null;
227
228 // All done!
229 return;
230 }
231 } // for (;;)
232
233 // Unlock. Either I am primary thread, or I am secondary
234 // thread and still running.
235 oldLock = unlockHandleEvent();
236 assert (oldLock == true);
237
238 // I have done some work of some kind. Tell the main run()
239 // loop to wake up now.
240 synchronized (application) {
241 application.notify();
242 }
243
244 } // while (true) (main runnable loop)
245 }
246 }
247
248 /**
249 * The primary event handler thread.
250 */
251 private volatile WidgetEventHandler primaryEventHandler;
252
253 /**
254 * The secondary event handler thread.
255 */
256 private volatile WidgetEventHandler secondaryEventHandler;
257
258 /**
259 * The widget receiving events from the secondary event handler thread.
260 */
261 private volatile TWidget secondaryEventReceiver;
262
263 /**
264 * Spinlock for the primary and secondary event handlers.
265 * WidgetEventHandler.run() is responsible for setting this value.
266 */
267 private volatile boolean insideHandleEvent = false;
268
269 /**
270 * Wake the sleeping active event handler.
271 */
272 private void wakeEventHandler() {
273 if (secondaryEventHandler != null) {
274 synchronized (secondaryEventHandler) {
275 secondaryEventHandler.notify();
276 }
277 } else {
278 assert (primaryEventHandler != null);
279 synchronized (primaryEventHandler) {
280 primaryEventHandler.notify();
281 }
282 }
283 }
284
285 /**
286 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
287 * spin indefinitely until unlockHandleEvent() is called.
288 *
289 * @return the old value of insideHandleEvent
290 */
291 private boolean lockHandleEvent() {
292 if (debugThreads) {
293 System.err.printf(" >> lockHandleEvent(): oldValue %s",
294 insideHandleEvent);
295 }
296 boolean oldValue = true;
297
298 synchronized (this) {
299 // Wait for TApplication.run() to finish using the global state
300 // before allowing further event processing.
301 while (lockoutHandleEvent == true) {
302 try {
303 // Backoff so that the backend can finish its work.
304 Thread.sleep(5);
305 } catch (InterruptedException e) {
306 // SQUASH
307 }
308 }
309
310 oldValue = insideHandleEvent;
311 insideHandleEvent = true;
312 }
313
314 if (debugThreads) {
315 System.err.printf(" ***\n");
316 }
317 return oldValue;
318 }
319
320 /**
321 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
322 * spin indefinitely until unlockHandleEvent() is called.
323 *
324 * @return the old value of insideHandleEvent
325 */
326 private boolean unlockHandleEvent() {
327 if (debugThreads) {
328 System.err.printf(" << unlockHandleEvent(): oldValue %s\n",
329 insideHandleEvent);
330 }
331 synchronized (this) {
332 boolean oldValue = insideHandleEvent;
333 insideHandleEvent = false;
334 return oldValue;
335 }
336 }
337
338 /**
339 * Spinlock for the primary and secondary event handlers. When true, the
340 * event handlers will spinlock wait before calling handleEvent().
341 */
342 private volatile boolean lockoutHandleEvent = false;
343
344 /**
345 * TApplication.run() needs to be able rely on the global data structures
346 * being intact when calling doIdle() and drawAll(). Tell the event
347 * handlers to wait for an unlock before handling their events.
348 */
349 private void stopEventHandlers() {
350 if (debugThreads) {
351 System.err.printf(">> stopEventHandlers()");
352 }
353
354 lockoutHandleEvent = true;
355 // Wait for the last event to finish processing before returning
356 // control to TApplication.run().
357 while (insideHandleEvent == true) {
358 try {
359 // Backoff so that the event handler can finish its work.
360 Thread.sleep(1);
361 } catch (InterruptedException e) {
362 // SQUASH
363 }
364 }
365
366 if (debugThreads) {
367 System.err.printf(" XXX\n");
368 }
369 }
370
371 /**
372 * TApplication.run() needs to be able rely on the global data structures
373 * being intact when calling doIdle() and drawAll(). Tell the event
374 * handlers that it is now OK to handle their events.
375 */
376 private void startEventHandlers() {
377 if (debugThreads) {
378 System.err.printf("<< startEventHandlers()\n");
379 }
380 lockoutHandleEvent = false;
381 }
382
383 // ------------------------------------------------------------------------
384 // TApplication attributes ------------------------------------------------
385 // ------------------------------------------------------------------------
386
387 /**
388 * Access to the physical screen, keyboard, and mouse.
389 */
390 private Backend backend;
391
392 /**
393 * Get the Backend.
394 *
395 * @return the Backend
396 */
397 public final Backend getBackend() {
398 return backend;
399 }
400
401 /**
402 * Get the Screen.
403 *
404 * @return the Screen
405 */
406 public final Screen getScreen() {
407 return backend.getScreen();
408 }
409
410 /**
411 * Actual mouse coordinate X.
412 */
413 private int mouseX;
414
415 /**
416 * Actual mouse coordinate Y.
417 */
418 private int mouseY;
419
420 /**
421 * Old version of mouse coordinate X.
422 */
423 private int oldMouseX;
424
425 /**
426 * Old version mouse coordinate Y.
427 */
428 private int oldMouseY;
429
430 /**
431 * Event queue that is filled by run().
432 */
433 private List<TInputEvent> fillEventQueue;
434
435 /**
436 * Event queue that will be drained by either primary or secondary
437 * Thread.
438 */
439 private List<TInputEvent> drainEventQueue;
440
441 /**
442 * Top-level menus in this application.
443 */
444 private List<TMenu> menus;
445
446 /**
447 * Stack of activated sub-menus in this application.
448 */
449 private List<TMenu> subMenus;
450
451 /**
452 * The currently active menu.
453 */
454 private TMenu activeMenu = null;
455
456 /**
457 * Active keyboard accelerators.
458 */
459 private Map<TKeypress, TMenuItem> accelerators;
460
461 /**
462 * All menu items.
463 */
464 private List<TMenuItem> menuItems;
465
466 /**
467 * Windows and widgets pull colors from this ColorTheme.
468 */
469 private ColorTheme theme;
470
471 /**
472 * Get the color theme.
473 *
474 * @return the theme
475 */
476 public final ColorTheme getTheme() {
477 return theme;
478 }
479
480 /**
481 * The top-level windows (but not menus).
482 */
483 private List<TWindow> windows;
484
485 /**
486 * The currently acive window.
487 */
488 private TWindow activeWindow = null;
489
490 /**
491 * Timers that are being ticked.
492 */
493 private List<TTimer> timers;
494
495 /**
496 * When true, exit the application.
497 */
498 private volatile boolean quit = false;
499
500 /**
501 * When true, repaint the entire screen.
502 */
503 private volatile boolean repaint = true;
504
505 /**
506 * Y coordinate of the top edge of the desktop. For now this is a
507 * constant. Someday it would be nice to have a multi-line menu or
508 * toolbars.
509 */
510 private static final int desktopTop = 1;
511
512 /**
513 * Get Y coordinate of the top edge of the desktop.
514 *
515 * @return Y coordinate of the top edge of the desktop
516 */
517 public final int getDesktopTop() {
518 return desktopTop;
519 }
520
521 /**
522 * Y coordinate of the bottom edge of the desktop.
523 */
524 private int desktopBottom;
525
526 /**
527 * Get Y coordinate of the bottom edge of the desktop.
528 *
529 * @return Y coordinate of the bottom edge of the desktop
530 */
531 public final int getDesktopBottom() {
532 return desktopBottom;
533 }
534
535 /**
536 * An optional TDesktop background window that is drawn underneath
537 * everything else.
538 */
539 private TDesktop desktop;
540
541 /**
542 * Set the TDesktop instance.
543 *
544 * @param desktop a TDesktop instance, or null to remove the one that is
545 * set
546 */
547 public final void setDesktop(final TDesktop desktop) {
548 if (this.desktop != null) {
549 this.desktop.onClose();
550 }
551 this.desktop = desktop;
552 }
553
554 /**
555 * Get the TDesktop instance.
556 *
557 * @return the desktop, or null if it is not set
558 */
559 public final TDesktop getDesktop() {
560 return desktop;
561 }
562
563 /**
564 * Get the current active window.
565 *
566 * @return the active window, or null if it is not set
567 */
568 public final TWindow getActiveWindow() {
569 return activeWindow;
570 }
571
572 /**
573 * Get the list of windows.
574 *
575 * @return a copy of the list of windows for this application
576 */
577 public final List<TWindow> getAllWindows() {
578 List<TWindow> result = new LinkedList<TWindow>();
579 result.addAll(windows);
580 return result;
581 }
582
583 /**
584 * If true, focus follows mouse: windows automatically raised if the
585 * mouse passes over them.
586 */
587 private boolean focusFollowsMouse = false;
588
589 /**
590 * Get focusFollowsMouse flag.
591 *
592 * @return true if focus follows mouse: windows automatically raised if
593 * the mouse passes over them
594 */
595 public boolean getFocusFollowsMouse() {
596 return focusFollowsMouse;
597 }
598
599 /**
600 * Set focusFollowsMouse flag.
601 *
602 * @param focusFollowsMouse if true, focus follows mouse: windows
603 * automatically raised if the mouse passes over them
604 */
605 public void setFocusFollowsMouse(final boolean focusFollowsMouse) {
606 this.focusFollowsMouse = focusFollowsMouse;
607 }
608
609 // ------------------------------------------------------------------------
610 // General behavior -------------------------------------------------------
611 // ------------------------------------------------------------------------
612
613 /**
614 * Display the about dialog.
615 */
616 protected void showAboutDialog() {
617 messageBox("About", "Jexer Version " +
618 this.getClass().getPackage().getImplementationVersion(),
619 TMessageBox.Type.OK);
620 }
621
622 // ------------------------------------------------------------------------
623 // Constructors -----------------------------------------------------------
624 // ------------------------------------------------------------------------
625
626 /**
627 * Public constructor.
628 *
629 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
630 * BackendType.SWING
631 * @throws UnsupportedEncodingException if an exception is thrown when
632 * creating the InputStreamReader
633 */
634 public TApplication(final BackendType backendType)
635 throws UnsupportedEncodingException {
636
637 switch (backendType) {
638 case SWING:
639 backend = new SwingBackend(this);
640 break;
641 case XTERM:
642 // Fall through...
643 case ECMA48:
644 backend = new ECMA48Backend(this, null, null);
645 break;
646 default:
647 throw new IllegalArgumentException("Invalid backend type: "
648 + backendType);
649 }
650 TApplicationImpl();
651 }
652
653 /**
654 * Public constructor. The backend type will be BackendType.ECMA48.
655 *
656 * @param input an InputStream connected to the remote user, or null for
657 * System.in. If System.in is used, then on non-Windows systems it will
658 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
659 * mode. input is always converted to a Reader with UTF-8 encoding.
660 * @param output an OutputStream connected to the remote user, or null
661 * for System.out. output is always converted to a Writer with UTF-8
662 * encoding.
663 * @throws UnsupportedEncodingException if an exception is thrown when
664 * creating the InputStreamReader
665 */
666 public TApplication(final InputStream input,
667 final OutputStream output) throws UnsupportedEncodingException {
668
669 backend = new ECMA48Backend(this, input, output);
670 TApplicationImpl();
671 }
672
673 /**
674 * Public constructor. The backend type will be BackendType.ECMA48.
675 *
676 * @param input the InputStream underlying 'reader'. Its available()
677 * method is used to determine if reader.read() will block or not.
678 * @param reader a Reader connected to the remote user.
679 * @param writer a PrintWriter connected to the remote user.
680 * @param setRawMode if true, set System.in into raw mode with stty.
681 * This should in general not be used. It is here solely for Demo3,
682 * which uses System.in.
683 * @throws IllegalArgumentException if input, reader, or writer are null.
684 */
685 public TApplication(final InputStream input, final Reader reader,
686 final PrintWriter writer, final boolean setRawMode) {
687
688 backend = new ECMA48Backend(this, input, reader, writer, setRawMode);
689 TApplicationImpl();
690 }
691
692 /**
693 * Public constructor. The backend type will be BackendType.ECMA48.
694 *
695 * @param input the InputStream underlying 'reader'. Its available()
696 * method is used to determine if reader.read() will block or not.
697 * @param reader a Reader connected to the remote user.
698 * @param writer a PrintWriter connected to the remote user.
699 * @throws IllegalArgumentException if input, reader, or writer are null.
700 */
701 public TApplication(final InputStream input, final Reader reader,
702 final PrintWriter writer) {
703
704 this(input, reader, writer, false);
705 }
706
707 /**
708 * Public constructor. This hook enables use with new non-Jexer
709 * backends.
710 *
711 * @param backend a Backend that is already ready to go.
712 */
713 public TApplication(final Backend backend) {
714 this.backend = backend;
715 TApplicationImpl();
716 }
717
718 /**
719 * Finish construction once the backend is set.
720 */
721 private void TApplicationImpl() {
722 theme = new ColorTheme();
723 desktopBottom = getScreen().getHeight() - 1;
724 fillEventQueue = new ArrayList<TInputEvent>();
725 drainEventQueue = new ArrayList<TInputEvent>();
726 windows = new LinkedList<TWindow>();
727 menus = new LinkedList<TMenu>();
728 subMenus = new LinkedList<TMenu>();
729 timers = new LinkedList<TTimer>();
730 accelerators = new HashMap<TKeypress, TMenuItem>();
731 menuItems = new ArrayList<TMenuItem>();
732 desktop = new TDesktop(this);
733
734 // Setup the main consumer thread
735 primaryEventHandler = new WidgetEventHandler(this, true);
736 (new Thread(primaryEventHandler)).start();
737 }
738
739 // ------------------------------------------------------------------------
740 // Screen refresh loop ----------------------------------------------------
741 // ------------------------------------------------------------------------
742
743 /**
744 * Invert the cell color at a position. This is used to track the mouse.
745 *
746 * @param x column position
747 * @param y row position
748 */
749 private void invertCell(final int x, final int y) {
750 if (debugThreads) {
751 System.err.printf("invertCell() %d %d\n", x, y);
752 }
753 CellAttributes attr = getScreen().getAttrXY(x, y);
754 attr.setForeColor(attr.getForeColor().invert());
755 attr.setBackColor(attr.getBackColor().invert());
756 getScreen().putAttrXY(x, y, attr, false);
757 }
758
759 /**
760 * Draw everything.
761 */
762 private void drawAll() {
763 if (debugThreads) {
764 System.err.printf("drawAll() enter\n");
765 }
766
767 if (!repaint) {
768 if (debugThreads) {
769 System.err.printf("drawAll() !repaint\n");
770 }
771 synchronized (getScreen()) {
772 if ((oldMouseX != mouseX) || (oldMouseY != mouseY)) {
773 // The only thing that has happened is the mouse moved.
774 // Clear the old position and draw the new position.
775 invertCell(oldMouseX, oldMouseY);
776 invertCell(mouseX, mouseY);
777 oldMouseX = mouseX;
778 oldMouseY = mouseY;
779 }
780 if (getScreen().isDirty()) {
781 backend.flushScreen();
782 }
783 return;
784 }
785 }
786
787 if (debugThreads) {
788 System.err.printf("drawAll() REDRAW\n");
789 }
790
791 // If true, the cursor is not visible
792 boolean cursor = false;
793
794 // Start with a clean screen
795 getScreen().clear();
796
797 // Draw the desktop
798 if (desktop != null) {
799 desktop.drawChildren();
800 }
801
802 // Draw each window in reverse Z order
803 List<TWindow> sorted = new LinkedList<TWindow>(windows);
804 Collections.sort(sorted);
805 TWindow topLevel = null;
806 if (sorted.size() > 0) {
807 topLevel = sorted.get(0);
808 }
809 Collections.reverse(sorted);
810 for (TWindow window: sorted) {
811 if (window.isShown()) {
812 window.drawChildren();
813 }
814 }
815
816 // Draw the blank menubar line - reset the screen clipping first so
817 // it won't trim it out.
818 getScreen().resetClipping();
819 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
820 theme.getColor("tmenu"));
821 // Now draw the menus.
822 int x = 1;
823 for (TMenu menu: menus) {
824 CellAttributes menuColor;
825 CellAttributes menuMnemonicColor;
826 if (menu.isActive()) {
827 menuColor = theme.getColor("tmenu.highlighted");
828 menuMnemonicColor = theme.getColor("tmenu.mnemonic.highlighted");
829 topLevel = menu;
830 } else {
831 menuColor = theme.getColor("tmenu");
832 menuMnemonicColor = theme.getColor("tmenu.mnemonic");
833 }
834 // Draw the menu title
835 getScreen().hLineXY(x, 0, menu.getTitle().length() + 2, ' ',
836 menuColor);
837 getScreen().putStringXY(x + 1, 0, menu.getTitle(), menuColor);
838 // Draw the highlight character
839 getScreen().putCharXY(x + 1 + menu.getMnemonic().getShortcutIdx(),
840 0, menu.getMnemonic().getShortcut(), menuMnemonicColor);
841
842 if (menu.isActive()) {
843 menu.drawChildren();
844 // Reset the screen clipping so we can draw the next title.
845 getScreen().resetClipping();
846 }
847 x += menu.getTitle().length() + 2;
848 }
849
850 for (TMenu menu: subMenus) {
851 // Reset the screen clipping so we can draw the next sub-menu.
852 getScreen().resetClipping();
853 menu.drawChildren();
854 }
855
856 // Draw the status bar of the top-level window
857 TStatusBar statusBar = null;
858 if (topLevel != null) {
859 statusBar = topLevel.getStatusBar();
860 }
861 if (statusBar != null) {
862 getScreen().resetClipping();
863 statusBar.setWidth(getScreen().getWidth());
864 statusBar.setY(getScreen().getHeight() - topLevel.getY());
865 statusBar.draw();
866 } else {
867 CellAttributes barColor = new CellAttributes();
868 barColor.setTo(getTheme().getColor("tstatusbar.text"));
869 getScreen().hLineXY(0, desktopBottom, getScreen().getWidth(), ' ',
870 barColor);
871 }
872
873 // Draw the mouse pointer
874 invertCell(mouseX, mouseY);
875 oldMouseX = mouseX;
876 oldMouseY = mouseY;
877
878 // Place the cursor if it is visible
879 TWidget activeWidget = null;
880 if (sorted.size() > 0) {
881 activeWidget = sorted.get(sorted.size() - 1).getActiveChild();
882 if (activeWidget.isCursorVisible()) {
883 getScreen().putCursor(true, activeWidget.getCursorAbsoluteX(),
884 activeWidget.getCursorAbsoluteY());
885 cursor = true;
886 }
887 }
888
889 // Kill the cursor
890 if (!cursor) {
891 getScreen().hideCursor();
892 }
893
894 // Flush the screen contents
895 if (getScreen().isDirty()) {
896 backend.flushScreen();
897 }
898
899 repaint = false;
900 }
901
902 // ------------------------------------------------------------------------
903 // Main loop --------------------------------------------------------------
904 // ------------------------------------------------------------------------
905
906 /**
907 * Run this application until it exits.
908 */
909 public void run() {
910 while (!quit) {
911 // Timeout is in milliseconds, so default timeout after 1 second
912 // of inactivity.
913 long timeout = 1000;
914
915 // If I've got no updates to render, wait for something from the
916 // backend or a timer.
917 if (!repaint
918 && ((mouseX == oldMouseX) && (mouseY == oldMouseY))
919 ) {
920 // Never sleep longer than 50 millis. We need time for
921 // windows with background tasks to update the display, and
922 // still flip buffers reasonably quickly in
923 // backend.flushPhysical().
924 timeout = getSleepTime(50);
925 }
926
927 if (timeout > 0) {
928 // As of now, I've got nothing to do: no I/O, nothing from
929 // the consumer threads, no timers that need to run ASAP. So
930 // wait until either the backend or the consumer threads have
931 // something to do.
932 try {
933 if (debugThreads) {
934 System.err.println("sleep " + timeout + " millis");
935 }
936 synchronized (this) {
937 this.wait(timeout);
938 }
939 } catch (InterruptedException e) {
940 // I'm awake and don't care why, let's see what's going
941 // on out there.
942 }
943 repaint = true;
944 }
945
946 // Prevent stepping on the primary or secondary event handler.
947 stopEventHandlers();
948
949 // Pull any pending I/O events
950 backend.getEvents(fillEventQueue);
951
952 // Dispatch each event to the appropriate handler, one at a time.
953 for (;;) {
954 TInputEvent event = null;
955 if (fillEventQueue.size() == 0) {
956 break;
957 }
958 event = fillEventQueue.remove(0);
959 metaHandleEvent(event);
960 }
961
962 // Wake a consumer thread if we have any pending events.
963 if (drainEventQueue.size() > 0) {
964 wakeEventHandler();
965 }
966
967 // Process timers and call doIdle()'s
968 doIdle();
969
970 // Update the screen
971 synchronized (getScreen()) {
972 drawAll();
973 }
974
975 // Let the event handlers run again.
976 startEventHandlers();
977
978 } // while (!quit)
979
980 // Shutdown the event consumer threads
981 if (secondaryEventHandler != null) {
982 synchronized (secondaryEventHandler) {
983 secondaryEventHandler.notify();
984 }
985 }
986 if (primaryEventHandler != null) {
987 synchronized (primaryEventHandler) {
988 primaryEventHandler.notify();
989 }
990 }
991
992 // Shutdown the user I/O thread(s)
993 backend.shutdown();
994
995 // Close all the windows. This gives them an opportunity to release
996 // resources.
997 closeAllWindows();
998
999 }
1000
1001 /**
1002 * Peek at certain application-level events, add to eventQueue, and wake
1003 * up the consuming Thread.
1004 *
1005 * @param event the input event to consume
1006 */
1007 private void metaHandleEvent(final TInputEvent event) {
1008
1009 if (debugEvents) {
1010 System.err.printf(String.format("metaHandleEvents event: %s\n",
1011 event)); System.err.flush();
1012 }
1013
1014 if (quit) {
1015 // Do no more processing if the application is already trying
1016 // to exit.
1017 return;
1018 }
1019
1020 // Special application-wide events -------------------------------
1021
1022 // Abort everything
1023 if (event instanceof TCommandEvent) {
1024 TCommandEvent command = (TCommandEvent) event;
1025 if (command.getCmd().equals(cmAbort)) {
1026 quit = true;
1027 return;
1028 }
1029 }
1030
1031 // Screen resize
1032 if (event instanceof TResizeEvent) {
1033 TResizeEvent resize = (TResizeEvent) event;
1034 synchronized (getScreen()) {
1035 getScreen().setDimensions(resize.getWidth(),
1036 resize.getHeight());
1037 desktopBottom = getScreen().getHeight() - 1;
1038 mouseX = 0;
1039 mouseY = 0;
1040 oldMouseX = 0;
1041 oldMouseY = 0;
1042 }
1043 if (desktop != null) {
1044 desktop.setDimensions(0, 0, resize.getWidth(),
1045 resize.getHeight() - 1);
1046 }
1047 return;
1048 }
1049
1050 // Peek at the mouse position
1051 if (event instanceof TMouseEvent) {
1052 TMouseEvent mouse = (TMouseEvent) event;
1053 synchronized (getScreen()) {
1054 if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
1055 oldMouseX = mouseX;
1056 oldMouseY = mouseY;
1057 mouseX = mouse.getX();
1058 mouseY = mouse.getY();
1059 }
1060 }
1061 }
1062
1063 // Put into the main queue
1064 drainEventQueue.add(event);
1065 }
1066
1067 /**
1068 * Dispatch one event to the appropriate widget or application-level
1069 * event handler. This is the primary event handler, it has the normal
1070 * application-wide event handling.
1071 *
1072 * @param event the input event to consume
1073 * @see #secondaryHandleEvent(TInputEvent event)
1074 */
1075 private void primaryHandleEvent(final TInputEvent event) {
1076
1077 if (debugEvents) {
1078 System.err.printf("Handle event: %s\n", event);
1079 }
1080
1081 // Special application-wide events -----------------------------------
1082
1083 // Peek at the mouse position
1084 if (event instanceof TMouseEvent) {
1085 // See if we need to switch focus to another window or the menu
1086 checkSwitchFocus((TMouseEvent) event);
1087 }
1088
1089 // Handle menu events
1090 if ((activeMenu != null) && !(event instanceof TCommandEvent)) {
1091 TMenu menu = activeMenu;
1092
1093 if (event instanceof TMouseEvent) {
1094 TMouseEvent mouse = (TMouseEvent) event;
1095
1096 while (subMenus.size() > 0) {
1097 TMenu subMenu = subMenus.get(subMenus.size() - 1);
1098 if (subMenu.mouseWouldHit(mouse)) {
1099 break;
1100 }
1101 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
1102 && (!mouse.isMouse1())
1103 && (!mouse.isMouse2())
1104 && (!mouse.isMouse3())
1105 && (!mouse.isMouseWheelUp())
1106 && (!mouse.isMouseWheelDown())
1107 ) {
1108 break;
1109 }
1110 // We navigated away from a sub-menu, so close it
1111 closeSubMenu();
1112 }
1113
1114 // Convert the mouse relative x/y to menu coordinates
1115 assert (mouse.getX() == mouse.getAbsoluteX());
1116 assert (mouse.getY() == mouse.getAbsoluteY());
1117 if (subMenus.size() > 0) {
1118 menu = subMenus.get(subMenus.size() - 1);
1119 }
1120 mouse.setX(mouse.getX() - menu.getX());
1121 mouse.setY(mouse.getY() - menu.getY());
1122 }
1123 menu.handleEvent(event);
1124 return;
1125 }
1126
1127 if (event instanceof TKeypressEvent) {
1128 TKeypressEvent keypress = (TKeypressEvent) event;
1129
1130 // See if this key matches an accelerator, and is not being
1131 // shortcutted by the active window, and if so dispatch the menu
1132 // event.
1133 boolean windowWillShortcut = false;
1134 if (activeWindow != null) {
1135 assert (activeWindow.isShown());
1136 if (activeWindow.isShortcutKeypress(keypress.getKey())) {
1137 // We do not process this key, it will be passed to the
1138 // window instead.
1139 windowWillShortcut = true;
1140 }
1141 }
1142
1143 if (!windowWillShortcut && !modalWindowActive()) {
1144 TKeypress keypressLowercase = keypress.getKey().toLowerCase();
1145 TMenuItem item = null;
1146 synchronized (accelerators) {
1147 item = accelerators.get(keypressLowercase);
1148 }
1149 if (item != null) {
1150 if (item.isEnabled()) {
1151 // Let the menu item dispatch
1152 item.dispatch();
1153 return;
1154 }
1155 }
1156
1157 // Handle the keypress
1158 if (onKeypress(keypress)) {
1159 return;
1160 }
1161 }
1162 }
1163
1164 if (event instanceof TCommandEvent) {
1165 if (onCommand((TCommandEvent) event)) {
1166 return;
1167 }
1168 }
1169
1170 if (event instanceof TMenuEvent) {
1171 if (onMenu((TMenuEvent) event)) {
1172 return;
1173 }
1174 }
1175
1176 // Dispatch events to the active window -------------------------------
1177 boolean dispatchToDesktop = true;
1178 TWindow window = activeWindow;
1179 if (window != null) {
1180 assert (window.isActive());
1181 assert (window.isShown());
1182 if (event instanceof TMouseEvent) {
1183 TMouseEvent mouse = (TMouseEvent) event;
1184 // Convert the mouse relative x/y to window coordinates
1185 assert (mouse.getX() == mouse.getAbsoluteX());
1186 assert (mouse.getY() == mouse.getAbsoluteY());
1187 mouse.setX(mouse.getX() - window.getX());
1188 mouse.setY(mouse.getY() - window.getY());
1189
1190 if (window.mouseWouldHit(mouse)) {
1191 dispatchToDesktop = false;
1192 }
1193 } else if (event instanceof TKeypressEvent) {
1194 dispatchToDesktop = false;
1195 }
1196
1197 if (debugEvents) {
1198 System.err.printf("TApplication dispatch event: %s\n",
1199 event);
1200 }
1201 window.handleEvent(event);
1202 }
1203 if (dispatchToDesktop) {
1204 // This event is fair game for the desktop to process.
1205 if (desktop != null) {
1206 desktop.handleEvent(event);
1207 }
1208 }
1209 }
1210
1211 /**
1212 * Dispatch one event to the appropriate widget or application-level
1213 * event handler. This is the secondary event handler used by certain
1214 * special dialogs (currently TMessageBox and TFileOpenBox).
1215 *
1216 * @param event the input event to consume
1217 * @see #primaryHandleEvent(TInputEvent event)
1218 */
1219 private void secondaryHandleEvent(final TInputEvent event) {
1220 secondaryEventReceiver.handleEvent(event);
1221 }
1222
1223 /**
1224 * Enable a widget to override the primary event thread.
1225 *
1226 * @param widget widget that will receive events
1227 */
1228 public final void enableSecondaryEventReceiver(final TWidget widget) {
1229 assert (secondaryEventReceiver == null);
1230 assert (secondaryEventHandler == null);
1231 assert ((widget instanceof TMessageBox)
1232 || (widget instanceof TFileOpenBox));
1233 secondaryEventReceiver = widget;
1234 secondaryEventHandler = new WidgetEventHandler(this, false);
1235 (new Thread(secondaryEventHandler)).start();
1236 }
1237
1238 /**
1239 * Yield to the secondary thread.
1240 */
1241 public final void yield() {
1242 assert (secondaryEventReceiver != null);
1243 // This is where we handoff the event handler lock from the primary
1244 // to secondary thread. We unlock here, and in a future loop the
1245 // secondary thread locks again. When it gives up, we have the
1246 // single lock back.
1247 boolean oldLock = unlockHandleEvent();
1248 assert (oldLock);
1249
1250 while (secondaryEventReceiver != null) {
1251 synchronized (primaryEventHandler) {
1252 try {
1253 primaryEventHandler.wait();
1254 } catch (InterruptedException e) {
1255 // SQUASH
1256 }
1257 }
1258 }
1259 }
1260
1261 /**
1262 * Do stuff when there is no user input.
1263 */
1264 private void doIdle() {
1265 if (debugThreads) {
1266 System.err.printf("doIdle()\n");
1267 }
1268
1269 // Now run any timers that have timed out
1270 Date now = new Date();
1271 List<TTimer> keepTimers = new LinkedList<TTimer>();
1272 for (TTimer timer: timers) {
1273 if (timer.getNextTick().getTime() <= now.getTime()) {
1274 timer.tick();
1275 if (timer.recurring) {
1276 keepTimers.add(timer);
1277 }
1278 } else {
1279 keepTimers.add(timer);
1280 }
1281 }
1282 timers = keepTimers;
1283
1284 // Call onIdle's
1285 for (TWindow window: windows) {
1286 window.onIdle();
1287 }
1288 if (desktop != null) {
1289 desktop.onIdle();
1290 }
1291 }
1292
1293 // ------------------------------------------------------------------------
1294 // TWindow management -----------------------------------------------------
1295 // ------------------------------------------------------------------------
1296
1297 /**
1298 * Return the total number of windows.
1299 *
1300 * @return the total number of windows
1301 */
1302 public final int windowCount() {
1303 return windows.size();
1304 }
1305
1306 /**
1307 * Return the number of windows that are showing.
1308 *
1309 * @return the number of windows that are showing on screen
1310 */
1311 public final int shownWindowCount() {
1312 int n = 0;
1313 for (TWindow w: windows) {
1314 if (w.isShown()) {
1315 n++;
1316 }
1317 }
1318 return n;
1319 }
1320
1321 /**
1322 * Return the number of windows that are hidden.
1323 *
1324 * @return the number of windows that are hidden
1325 */
1326 public final int hiddenWindowCount() {
1327 int n = 0;
1328 for (TWindow w: windows) {
1329 if (w.isHidden()) {
1330 n++;
1331 }
1332 }
1333 return n;
1334 }
1335
1336 /**
1337 * Check if a window instance is in this application's window list.
1338 *
1339 * @param window window to look for
1340 * @return true if this window is in the list
1341 */
1342 public final boolean hasWindow(final TWindow window) {
1343 if (windows.size() == 0) {
1344 return false;
1345 }
1346 for (TWindow w: windows) {
1347 if (w == window) {
1348 assert (window.getApplication() == this);
1349 return true;
1350 }
1351 }
1352 return false;
1353 }
1354
1355 /**
1356 * Activate a window: bring it to the top and have it receive events.
1357 *
1358 * @param window the window to become the new active window
1359 */
1360 public void activateWindow(final TWindow window) {
1361 if (hasWindow(window) == false) {
1362 /*
1363 * Someone has a handle to a window I don't have. Ignore this
1364 * request.
1365 */
1366 return;
1367 }
1368
1369 assert (windows.size() > 0);
1370
1371 if (window.isHidden()) {
1372 // Unhiding will also activate.
1373 showWindow(window);
1374 return;
1375 }
1376 assert (window.isShown());
1377
1378 if (windows.size() == 1) {
1379 assert (window == windows.get(0));
1380 if (activeWindow == null) {
1381 activeWindow = window;
1382 window.setZ(0);
1383 activeWindow.setActive(true);
1384 activeWindow.onFocus();
1385 }
1386
1387 assert (window.isActive());
1388 assert (activeWindow == window);
1389 return;
1390 }
1391
1392 if (activeWindow == window) {
1393 assert (window.isActive());
1394
1395 // Window is already active, do nothing.
1396 return;
1397 }
1398
1399 assert (!window.isActive());
1400 if (activeWindow != null) {
1401 assert (activeWindow.getZ() == 0);
1402
1403 activeWindow.onUnfocus();
1404 activeWindow.setActive(false);
1405 activeWindow.setZ(window.getZ());
1406 }
1407 activeWindow = window;
1408 activeWindow.setZ(0);
1409 activeWindow.setActive(true);
1410 activeWindow.onFocus();
1411 return;
1412 }
1413
1414 /**
1415 * Hide a window.
1416 *
1417 * @param window the window to hide
1418 */
1419 public void hideWindow(final TWindow window) {
1420 if (hasWindow(window) == false) {
1421 /*
1422 * Someone has a handle to a window I don't have. Ignore this
1423 * request.
1424 */
1425 return;
1426 }
1427
1428 assert (windows.size() > 0);
1429
1430 if (!window.hidden) {
1431 if (window == activeWindow) {
1432 if (shownWindowCount() > 1) {
1433 switchWindow(true);
1434 } else {
1435 activeWindow = null;
1436 window.setActive(false);
1437 window.onUnfocus();
1438 }
1439 }
1440 window.hidden = true;
1441 window.onHide();
1442 }
1443 }
1444
1445 /**
1446 * Show a window.
1447 *
1448 * @param window the window to show
1449 */
1450 public void showWindow(final TWindow window) {
1451 if (hasWindow(window) == false) {
1452 /*
1453 * Someone has a handle to a window I don't have. Ignore this
1454 * request.
1455 */
1456 return;
1457 }
1458
1459 assert (windows.size() > 0);
1460
1461 if (window.hidden) {
1462 window.hidden = false;
1463 window.onShow();
1464 activateWindow(window);
1465 }
1466 }
1467
1468 /**
1469 * Close window. Note that the window's destructor is NOT called by this
1470 * method, instead the GC is assumed to do the cleanup.
1471 *
1472 * @param window the window to remove
1473 */
1474 public final void closeWindow(final TWindow window) {
1475 if (hasWindow(window) == false) {
1476 /*
1477 * Someone has a handle to a window I don't have. Ignore this
1478 * request.
1479 */
1480 return;
1481 }
1482
1483 synchronized (windows) {
1484 int z = window.getZ();
1485 window.setZ(-1);
1486 window.onUnfocus();
1487 Collections.sort(windows);
1488 windows.remove(0);
1489 activeWindow = null;
1490 for (TWindow w: windows) {
1491 if (w.getZ() > z) {
1492 w.setZ(w.getZ() - 1);
1493 if (w.getZ() == 0) {
1494 w.setActive(true);
1495 w.onFocus();
1496 assert (activeWindow == null);
1497 activeWindow = w;
1498 } else {
1499 if (w.isActive()) {
1500 w.setActive(false);
1501 w.onUnfocus();
1502 }
1503 }
1504 }
1505 }
1506 }
1507
1508 // Perform window cleanup
1509 window.onClose();
1510
1511 // Check if we are closing a TMessageBox or similar
1512 if (secondaryEventReceiver != null) {
1513 assert (secondaryEventHandler != null);
1514
1515 // Do not send events to the secondaryEventReceiver anymore, the
1516 // window is closed.
1517 secondaryEventReceiver = null;
1518
1519 // Wake the secondary thread, it will wake the primary as it
1520 // exits.
1521 synchronized (secondaryEventHandler) {
1522 secondaryEventHandler.notify();
1523 }
1524 }
1525
1526 // Permit desktop to be active if it is the only thing left.
1527 if (desktop != null) {
1528 if (windows.size() == 0) {
1529 desktop.setActive(true);
1530 }
1531 }
1532 }
1533
1534 /**
1535 * Switch to the next window.
1536 *
1537 * @param forward if true, then switch to the next window in the list,
1538 * otherwise switch to the previous window in the list
1539 */
1540 public final void switchWindow(final boolean forward) {
1541 // Only switch if there are multiple visible windows
1542 if (shownWindowCount() < 2) {
1543 return;
1544 }
1545 assert (activeWindow != null);
1546
1547 synchronized (windows) {
1548
1549 // Swap z/active between active window and the next in the list
1550 int activeWindowI = -1;
1551 for (int i = 0; i < windows.size(); i++) {
1552 if (windows.get(i) == activeWindow) {
1553 assert (activeWindow.isActive());
1554 activeWindowI = i;
1555 break;
1556 } else {
1557 assert (!windows.get(0).isActive());
1558 }
1559 }
1560 assert (activeWindowI >= 0);
1561
1562 // Do not switch if a window is modal
1563 if (activeWindow.isModal()) {
1564 return;
1565 }
1566
1567 int nextWindowI = activeWindowI;
1568 for (;;) {
1569 if (forward) {
1570 nextWindowI++;
1571 nextWindowI %= windows.size();
1572 } else {
1573 nextWindowI--;
1574 if (nextWindowI < 0) {
1575 nextWindowI = windows.size() - 1;
1576 }
1577 }
1578
1579 if (windows.get(nextWindowI).isShown()) {
1580 activateWindow(windows.get(nextWindowI));
1581 break;
1582 }
1583 }
1584 } // synchronized (windows)
1585
1586 }
1587
1588 /**
1589 * Add a window to my window list and make it active.
1590 *
1591 * @param window new window to add
1592 */
1593 public final void addWindow(final TWindow window) {
1594
1595 // Do not add menu windows to the window list.
1596 if (window instanceof TMenu) {
1597 return;
1598 }
1599
1600 // Do not add the desktop to the window list.
1601 if (window instanceof TDesktop) {
1602 return;
1603 }
1604
1605 synchronized (windows) {
1606 // Do not allow a modal window to spawn a non-modal window. If a
1607 // modal window is active, then this window will become modal
1608 // too.
1609 if (modalWindowActive()) {
1610 window.flags |= TWindow.MODAL;
1611 window.flags |= TWindow.CENTERED;
1612 window.hidden = false;
1613 }
1614 if (window.isShown()) {
1615 for (TWindow w: windows) {
1616 if (w.isActive()) {
1617 w.setActive(false);
1618 w.onUnfocus();
1619 }
1620 w.setZ(w.getZ() + 1);
1621 }
1622 }
1623 windows.add(window);
1624 if (window.isShown()) {
1625 activeWindow = window;
1626 activeWindow.setZ(0);
1627 activeWindow.setActive(true);
1628 activeWindow.onFocus();
1629 }
1630
1631 if (((window.flags & TWindow.CENTERED) == 0)
1632 && smartWindowPlacement) {
1633
1634 doSmartPlacement(window);
1635 }
1636 }
1637
1638 // Desktop cannot be active over any other window.
1639 if (desktop != null) {
1640 desktop.setActive(false);
1641 }
1642 }
1643
1644 /**
1645 * Check if there is a system-modal window on top.
1646 *
1647 * @return true if the active window is modal
1648 */
1649 private boolean modalWindowActive() {
1650 if (windows.size() == 0) {
1651 return false;
1652 }
1653
1654 for (TWindow w: windows) {
1655 if (w.isModal()) {
1656 return true;
1657 }
1658 }
1659
1660 return false;
1661 }
1662
1663 /**
1664 * Close all open windows.
1665 */
1666 private void closeAllWindows() {
1667 // Don't do anything if we are in the menu
1668 if (activeMenu != null) {
1669 return;
1670 }
1671 while (windows.size() > 0) {
1672 closeWindow(windows.get(0));
1673 }
1674 }
1675
1676 /**
1677 * Re-layout the open windows as non-overlapping tiles. This produces
1678 * almost the same results as Turbo Pascal 7.0's IDE.
1679 */
1680 private void tileWindows() {
1681 synchronized (windows) {
1682 // Don't do anything if we are in the menu
1683 if (activeMenu != null) {
1684 return;
1685 }
1686 int z = windows.size();
1687 if (z == 0) {
1688 return;
1689 }
1690 int a = 0;
1691 int b = 0;
1692 a = (int)(Math.sqrt(z));
1693 int c = 0;
1694 while (c < a) {
1695 b = (z - c) / a;
1696 if (((a * b) + c) == z) {
1697 break;
1698 }
1699 c++;
1700 }
1701 assert (a > 0);
1702 assert (b > 0);
1703 assert (c < a);
1704 int newWidth = (getScreen().getWidth() / a);
1705 int newHeight1 = ((getScreen().getHeight() - 1) / b);
1706 int newHeight2 = ((getScreen().getHeight() - 1) / (b + c));
1707
1708 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1709 Collections.sort(sorted);
1710 Collections.reverse(sorted);
1711 for (int i = 0; i < sorted.size(); i++) {
1712 int logicalX = i / b;
1713 int logicalY = i % b;
1714 if (i >= ((a - 1) * b)) {
1715 logicalX = a - 1;
1716 logicalY = i - ((a - 1) * b);
1717 }
1718
1719 TWindow w = sorted.get(i);
1720 w.setX(logicalX * newWidth);
1721 w.setWidth(newWidth);
1722 if (i >= ((a - 1) * b)) {
1723 w.setY((logicalY * newHeight2) + 1);
1724 w.setHeight(newHeight2);
1725 } else {
1726 w.setY((logicalY * newHeight1) + 1);
1727 w.setHeight(newHeight1);
1728 }
1729 }
1730 }
1731 }
1732
1733 /**
1734 * Re-layout the open windows as overlapping cascaded windows.
1735 */
1736 private void cascadeWindows() {
1737 synchronized (windows) {
1738 // Don't do anything if we are in the menu
1739 if (activeMenu != null) {
1740 return;
1741 }
1742 int x = 0;
1743 int y = 1;
1744 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1745 Collections.sort(sorted);
1746 Collections.reverse(sorted);
1747 for (TWindow window: sorted) {
1748 window.setX(x);
1749 window.setY(y);
1750 x++;
1751 y++;
1752 if (x > getScreen().getWidth()) {
1753 x = 0;
1754 }
1755 if (y >= getScreen().getHeight()) {
1756 y = 1;
1757 }
1758 }
1759 }
1760 }
1761
1762 /**
1763 * Place a window to minimize its overlap with other windows.
1764 *
1765 * @param window the window to place
1766 */
1767 public final void doSmartPlacement(final TWindow window) {
1768 // This is a pretty dumb algorithm, but seems to work. The hardest
1769 // part is computing these "overlap" values seeking a minimum average
1770 // overlap.
1771 int xMin = 0;
1772 int yMin = desktopTop;
1773 int xMax = getScreen().getWidth() - window.getWidth() + 1;
1774 int yMax = desktopBottom - window.getHeight() + 1;
1775 if (xMax < xMin) {
1776 xMax = xMin;
1777 }
1778 if (yMax < yMin) {
1779 yMax = yMin;
1780 }
1781
1782 if ((xMin == xMax) && (yMin == yMax)) {
1783 // No work to do, bail out.
1784 return;
1785 }
1786
1787 // Compute the overlap matrix without the new window.
1788 int width = getScreen().getWidth();
1789 int height = getScreen().getHeight();
1790 int overlapMatrix[][] = new int[width][height];
1791 for (TWindow w: windows) {
1792 if (window == w) {
1793 continue;
1794 }
1795 for (int x = w.getX(); x < w.getX() + w.getWidth(); x++) {
1796 if (x >= width) {
1797 continue;
1798 }
1799 for (int y = w.getY(); y < w.getY() + w.getHeight(); y++) {
1800 if (y >= height) {
1801 continue;
1802 }
1803 overlapMatrix[x][y]++;
1804 }
1805 }
1806 }
1807
1808 long oldOverlapTotal = 0;
1809 long oldOverlapN = 0;
1810 for (int x = 0; x < width; x++) {
1811 for (int y = 0; y < height; y++) {
1812 oldOverlapTotal += overlapMatrix[x][y];
1813 if (overlapMatrix[x][y] > 0) {
1814 oldOverlapN++;
1815 }
1816 }
1817 }
1818
1819
1820 double oldOverlapAvg = (double) oldOverlapTotal / (double) oldOverlapN;
1821 boolean first = true;
1822 int windowX = window.getX();
1823 int windowY = window.getY();
1824
1825 // For each possible (x, y) position for the new window, compute a
1826 // new overlap matrix.
1827 for (int x = xMin; x < xMax; x++) {
1828 for (int y = yMin; y < yMax; y++) {
1829
1830 // Start with the matrix minus this window.
1831 int newMatrix[][] = new int[width][height];
1832 for (int mx = 0; mx < width; mx++) {
1833 for (int my = 0; my < height; my++) {
1834 newMatrix[mx][my] = overlapMatrix[mx][my];
1835 }
1836 }
1837
1838 // Add this window's values to the new overlap matrix.
1839 long newOverlapTotal = 0;
1840 long newOverlapN = 0;
1841 // Start by adding each new cell.
1842 for (int wx = x; wx < x + window.getWidth(); wx++) {
1843 if (wx >= width) {
1844 continue;
1845 }
1846 for (int wy = y; wy < y + window.getHeight(); wy++) {
1847 if (wy >= height) {
1848 continue;
1849 }
1850 newMatrix[wx][wy]++;
1851 }
1852 }
1853 // Now figure out the new value for total coverage.
1854 for (int mx = 0; mx < width; mx++) {
1855 for (int my = 0; my < height; my++) {
1856 newOverlapTotal += newMatrix[x][y];
1857 if (newMatrix[mx][my] > 0) {
1858 newOverlapN++;
1859 }
1860 }
1861 }
1862 double newOverlapAvg = (double) newOverlapTotal / (double) newOverlapN;
1863
1864 if (first) {
1865 // First time: just record what we got.
1866 oldOverlapAvg = newOverlapAvg;
1867 first = false;
1868 } else {
1869 // All other times: pick a new best (x, y) and save the
1870 // overlap value.
1871 if (newOverlapAvg < oldOverlapAvg) {
1872 windowX = x;
1873 windowY = y;
1874 oldOverlapAvg = newOverlapAvg;
1875 }
1876 }
1877
1878 } // for (int x = xMin; x < xMax; x++)
1879
1880 } // for (int y = yMin; y < yMax; y++)
1881
1882 // Finally, set the window's new coordinates.
1883 window.setX(windowX);
1884 window.setY(windowY);
1885 }
1886
1887 // ------------------------------------------------------------------------
1888 // TMenu management -------------------------------------------------------
1889 // ------------------------------------------------------------------------
1890
1891 /**
1892 * Check if a mouse event would hit either the active menu or any open
1893 * sub-menus.
1894 *
1895 * @param mouse mouse event
1896 * @return true if the mouse would hit the active menu or an open
1897 * sub-menu
1898 */
1899 private boolean mouseOnMenu(final TMouseEvent mouse) {
1900 assert (activeMenu != null);
1901 List<TMenu> menus = new LinkedList<TMenu>(subMenus);
1902 Collections.reverse(menus);
1903 for (TMenu menu: menus) {
1904 if (menu.mouseWouldHit(mouse)) {
1905 return true;
1906 }
1907 }
1908 return activeMenu.mouseWouldHit(mouse);
1909 }
1910
1911 /**
1912 * See if we need to switch window or activate the menu based on
1913 * a mouse click.
1914 *
1915 * @param mouse mouse event
1916 */
1917 private void checkSwitchFocus(final TMouseEvent mouse) {
1918
1919 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1920 && (activeMenu != null)
1921 && (mouse.getAbsoluteY() != 0)
1922 && (!mouseOnMenu(mouse))
1923 ) {
1924 // They clicked outside the active menu, turn it off
1925 activeMenu.setActive(false);
1926 activeMenu = null;
1927 for (TMenu menu: subMenus) {
1928 menu.setActive(false);
1929 }
1930 subMenus.clear();
1931 // Continue checks
1932 }
1933
1934 // See if they hit the menu bar
1935 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1936 && (mouse.isMouse1())
1937 && (!modalWindowActive())
1938 && (mouse.getAbsoluteY() == 0)
1939 ) {
1940
1941 for (TMenu menu: subMenus) {
1942 menu.setActive(false);
1943 }
1944 subMenus.clear();
1945
1946 // They selected the menu, go activate it
1947 for (TMenu menu: menus) {
1948 if ((mouse.getAbsoluteX() >= menu.getX())
1949 && (mouse.getAbsoluteX() < menu.getX()
1950 + menu.getTitle().length() + 2)
1951 ) {
1952 menu.setActive(true);
1953 activeMenu = menu;
1954 } else {
1955 menu.setActive(false);
1956 }
1957 }
1958 return;
1959 }
1960
1961 // See if they hit the menu bar
1962 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
1963 && (mouse.isMouse1())
1964 && (activeMenu != null)
1965 && (mouse.getAbsoluteY() == 0)
1966 ) {
1967
1968 TMenu oldMenu = activeMenu;
1969 for (TMenu menu: subMenus) {
1970 menu.setActive(false);
1971 }
1972 subMenus.clear();
1973
1974 // See if we should switch menus
1975 for (TMenu menu: menus) {
1976 if ((mouse.getAbsoluteX() >= menu.getX())
1977 && (mouse.getAbsoluteX() < menu.getX()
1978 + menu.getTitle().length() + 2)
1979 ) {
1980 menu.setActive(true);
1981 activeMenu = menu;
1982 }
1983 }
1984 if (oldMenu != activeMenu) {
1985 // They switched menus
1986 oldMenu.setActive(false);
1987 }
1988 return;
1989 }
1990
1991 // If a menu is still active, don't switch windows
1992 if (activeMenu != null) {
1993 return;
1994 }
1995
1996 // Only switch if there are multiple windows
1997 if (windows.size() < 2) {
1998 return;
1999 }
2000
2001 if (((focusFollowsMouse == true)
2002 && (mouse.getType() == TMouseEvent.Type.MOUSE_MOTION))
2003 || (mouse.getType() == TMouseEvent.Type.MOUSE_UP)
2004 ) {
2005 synchronized (windows) {
2006 Collections.sort(windows);
2007 if (windows.get(0).isModal()) {
2008 // Modal windows don't switch
2009 return;
2010 }
2011
2012 for (TWindow window: windows) {
2013 assert (!window.isModal());
2014
2015 if (window.isHidden()) {
2016 assert (!window.isActive());
2017 continue;
2018 }
2019
2020 if (window.mouseWouldHit(mouse)) {
2021 if (window == windows.get(0)) {
2022 // Clicked on the same window, nothing to do
2023 assert (window.isActive());
2024 return;
2025 }
2026
2027 // We will be switching to another window
2028 assert (windows.get(0).isActive());
2029 assert (windows.get(0) == activeWindow);
2030 assert (!window.isActive());
2031 activeWindow.onUnfocus();
2032 activeWindow.setActive(false);
2033 activeWindow.setZ(window.getZ());
2034 activeWindow = window;
2035 window.setZ(0);
2036 window.setActive(true);
2037 window.onFocus();
2038 return;
2039 }
2040 }
2041 }
2042
2043 // Clicked on the background, nothing to do
2044 return;
2045 }
2046
2047 // Nothing to do: this isn't a mouse up, or focus isn't following
2048 // mouse.
2049 return;
2050 }
2051
2052 /**
2053 * Turn off the menu.
2054 */
2055 public final void closeMenu() {
2056 if (activeMenu != null) {
2057 activeMenu.setActive(false);
2058 activeMenu = null;
2059 for (TMenu menu: subMenus) {
2060 menu.setActive(false);
2061 }
2062 subMenus.clear();
2063 }
2064 }
2065
2066 /**
2067 * Turn off a sub-menu.
2068 */
2069 public final void closeSubMenu() {
2070 assert (activeMenu != null);
2071 TMenu item = subMenus.get(subMenus.size() - 1);
2072 assert (item != null);
2073 item.setActive(false);
2074 subMenus.remove(subMenus.size() - 1);
2075 }
2076
2077 /**
2078 * Switch to the next menu.
2079 *
2080 * @param forward if true, then switch to the next menu in the list,
2081 * otherwise switch to the previous menu in the list
2082 */
2083 public final void switchMenu(final boolean forward) {
2084 assert (activeMenu != null);
2085
2086 for (TMenu menu: subMenus) {
2087 menu.setActive(false);
2088 }
2089 subMenus.clear();
2090
2091 for (int i = 0; i < menus.size(); i++) {
2092 if (activeMenu == menus.get(i)) {
2093 if (forward) {
2094 if (i < menus.size() - 1) {
2095 i++;
2096 }
2097 } else {
2098 if (i > 0) {
2099 i--;
2100 }
2101 }
2102 activeMenu.setActive(false);
2103 activeMenu = menus.get(i);
2104 activeMenu.setActive(true);
2105 return;
2106 }
2107 }
2108 }
2109
2110 /**
2111 * Add a menu item to the global list. If it has a keyboard accelerator,
2112 * that will be added the global hash.
2113 *
2114 * @param item the menu item
2115 */
2116 public final void addMenuItem(final TMenuItem item) {
2117 menuItems.add(item);
2118
2119 TKeypress key = item.getKey();
2120 if (key != null) {
2121 synchronized (accelerators) {
2122 assert (accelerators.get(key) == null);
2123 accelerators.put(key.toLowerCase(), item);
2124 }
2125 }
2126 }
2127
2128 /**
2129 * Disable one menu item.
2130 *
2131 * @param id the menu item ID
2132 */
2133 public final void disableMenuItem(final int id) {
2134 for (TMenuItem item: menuItems) {
2135 if (item.getId() == id) {
2136 item.setEnabled(false);
2137 }
2138 }
2139 }
2140
2141 /**
2142 * Disable the range of menu items with ID's between lower and upper,
2143 * inclusive.
2144 *
2145 * @param lower the lowest menu item ID
2146 * @param upper the highest menu item ID
2147 */
2148 public final void disableMenuItems(final int lower, final int upper) {
2149 for (TMenuItem item: menuItems) {
2150 if ((item.getId() >= lower) && (item.getId() <= upper)) {
2151 item.setEnabled(false);
2152 }
2153 }
2154 }
2155
2156 /**
2157 * Enable one menu item.
2158 *
2159 * @param id the menu item ID
2160 */
2161 public final void enableMenuItem(final int id) {
2162 for (TMenuItem item: menuItems) {
2163 if (item.getId() == id) {
2164 item.setEnabled(true);
2165 }
2166 }
2167 }
2168
2169 /**
2170 * Enable the range of menu items with ID's between lower and upper,
2171 * inclusive.
2172 *
2173 * @param lower the lowest menu item ID
2174 * @param upper the highest menu item ID
2175 */
2176 public final void enableMenuItems(final int lower, final int upper) {
2177 for (TMenuItem item: menuItems) {
2178 if ((item.getId() >= lower) && (item.getId() <= upper)) {
2179 item.setEnabled(true);
2180 }
2181 }
2182 }
2183
2184 /**
2185 * Recompute menu x positions based on their title length.
2186 */
2187 public final void recomputeMenuX() {
2188 int x = 0;
2189 for (TMenu menu: menus) {
2190 menu.setX(x);
2191 x += menu.getTitle().length() + 2;
2192 }
2193 }
2194
2195 /**
2196 * Post an event to process and turn off the menu.
2197 *
2198 * @param event new event to add to the queue
2199 */
2200 public final void postMenuEvent(final TInputEvent event) {
2201 synchronized (fillEventQueue) {
2202 fillEventQueue.add(event);
2203 }
2204 closeMenu();
2205 }
2206
2207 /**
2208 * Add a sub-menu to the list of open sub-menus.
2209 *
2210 * @param menu sub-menu
2211 */
2212 public final void addSubMenu(final TMenu menu) {
2213 subMenus.add(menu);
2214 }
2215
2216 /**
2217 * Convenience function to add a top-level menu.
2218 *
2219 * @param title menu title
2220 * @return the new menu
2221 */
2222 public final TMenu addMenu(final String title) {
2223 int x = 0;
2224 int y = 0;
2225 TMenu menu = new TMenu(this, x, y, title);
2226 menus.add(menu);
2227 recomputeMenuX();
2228 return menu;
2229 }
2230
2231 /**
2232 * Convenience function to add a default "File" menu.
2233 *
2234 * @return the new menu
2235 */
2236 public final TMenu addFileMenu() {
2237 TMenu fileMenu = addMenu("&File");
2238 fileMenu.addDefaultItem(TMenu.MID_OPEN_FILE);
2239 fileMenu.addSeparator();
2240 fileMenu.addDefaultItem(TMenu.MID_SHELL);
2241 fileMenu.addDefaultItem(TMenu.MID_EXIT);
2242 TStatusBar statusBar = fileMenu.newStatusBar("File-management " +
2243 "commands (Open, Save, Print, etc.)");
2244 statusBar.addShortcutKeypress(kbF1, cmHelp, "Help");
2245 return fileMenu;
2246 }
2247
2248 /**
2249 * Convenience function to add a default "Edit" menu.
2250 *
2251 * @return the new menu
2252 */
2253 public final TMenu addEditMenu() {
2254 TMenu editMenu = addMenu("&Edit");
2255 editMenu.addDefaultItem(TMenu.MID_CUT);
2256 editMenu.addDefaultItem(TMenu.MID_COPY);
2257 editMenu.addDefaultItem(TMenu.MID_PASTE);
2258 editMenu.addDefaultItem(TMenu.MID_CLEAR);
2259 TStatusBar statusBar = editMenu.newStatusBar("Editor operations, " +
2260 "undo, and Clipboard access");
2261 statusBar.addShortcutKeypress(kbF1, cmHelp, "Help");
2262 return editMenu;
2263 }
2264
2265 /**
2266 * Convenience function to add a default "Window" menu.
2267 *
2268 * @return the new menu
2269 */
2270 public final TMenu addWindowMenu() {
2271 TMenu windowMenu = addMenu("&Window");
2272 windowMenu.addDefaultItem(TMenu.MID_TILE);
2273 windowMenu.addDefaultItem(TMenu.MID_CASCADE);
2274 windowMenu.addDefaultItem(TMenu.MID_CLOSE_ALL);
2275 windowMenu.addSeparator();
2276 windowMenu.addDefaultItem(TMenu.MID_WINDOW_MOVE);
2277 windowMenu.addDefaultItem(TMenu.MID_WINDOW_ZOOM);
2278 windowMenu.addDefaultItem(TMenu.MID_WINDOW_NEXT);
2279 windowMenu.addDefaultItem(TMenu.MID_WINDOW_PREVIOUS);
2280 windowMenu.addDefaultItem(TMenu.MID_WINDOW_CLOSE);
2281 TStatusBar statusBar = windowMenu.newStatusBar("Open, arrange, and " +
2282 "list windows");
2283 statusBar.addShortcutKeypress(kbF1, cmHelp, "Help");
2284 return windowMenu;
2285 }
2286
2287 /**
2288 * Convenience function to add a default "Help" menu.
2289 *
2290 * @return the new menu
2291 */
2292 public final TMenu addHelpMenu() {
2293 TMenu helpMenu = addMenu("&Help");
2294 helpMenu.addDefaultItem(TMenu.MID_HELP_CONTENTS);
2295 helpMenu.addDefaultItem(TMenu.MID_HELP_INDEX);
2296 helpMenu.addDefaultItem(TMenu.MID_HELP_SEARCH);
2297 helpMenu.addDefaultItem(TMenu.MID_HELP_PREVIOUS);
2298 helpMenu.addDefaultItem(TMenu.MID_HELP_HELP);
2299 helpMenu.addDefaultItem(TMenu.MID_HELP_ACTIVE_FILE);
2300 helpMenu.addSeparator();
2301 helpMenu.addDefaultItem(TMenu.MID_ABOUT);
2302 TStatusBar statusBar = helpMenu.newStatusBar("Access online help");
2303 statusBar.addShortcutKeypress(kbF1, cmHelp, "Help");
2304 return helpMenu;
2305 }
2306
2307 // ------------------------------------------------------------------------
2308 // Event handlers ---------------------------------------------------------
2309 // ------------------------------------------------------------------------
2310
2311 /**
2312 * Method that TApplication subclasses can override to handle menu or
2313 * posted command events.
2314 *
2315 * @param command command event
2316 * @return if true, this event was consumed
2317 */
2318 protected boolean onCommand(final TCommandEvent command) {
2319 // Default: handle cmExit
2320 if (command.equals(cmExit)) {
2321 if (messageBox("Confirmation", "Exit application?",
2322 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
2323 quit = true;
2324 }
2325 return true;
2326 }
2327
2328 if (command.equals(cmShell)) {
2329 openTerminal(0, 0, TWindow.RESIZABLE);
2330 return true;
2331 }
2332
2333 if (command.equals(cmTile)) {
2334 tileWindows();
2335 return true;
2336 }
2337 if (command.equals(cmCascade)) {
2338 cascadeWindows();
2339 return true;
2340 }
2341 if (command.equals(cmCloseAll)) {
2342 closeAllWindows();
2343 return true;
2344 }
2345
2346 return false;
2347 }
2348
2349 /**
2350 * Method that TApplication subclasses can override to handle menu
2351 * events.
2352 *
2353 * @param menu menu event
2354 * @return if true, this event was consumed
2355 */
2356 protected boolean onMenu(final TMenuEvent menu) {
2357
2358 // Default: handle MID_EXIT
2359 if (menu.getId() == TMenu.MID_EXIT) {
2360 if (messageBox("Confirmation", "Exit application?",
2361 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
2362 quit = true;
2363 }
2364 return true;
2365 }
2366
2367 if (menu.getId() == TMenu.MID_SHELL) {
2368 openTerminal(0, 0, TWindow.RESIZABLE);
2369 return true;
2370 }
2371
2372 if (menu.getId() == TMenu.MID_TILE) {
2373 tileWindows();
2374 return true;
2375 }
2376 if (menu.getId() == TMenu.MID_CASCADE) {
2377 cascadeWindows();
2378 return true;
2379 }
2380 if (menu.getId() == TMenu.MID_CLOSE_ALL) {
2381 closeAllWindows();
2382 return true;
2383 }
2384 if (menu.getId() == TMenu.MID_ABOUT) {
2385 showAboutDialog();
2386 return true;
2387 }
2388 return false;
2389 }
2390
2391 /**
2392 * Method that TApplication subclasses can override to handle keystrokes.
2393 *
2394 * @param keypress keystroke event
2395 * @return if true, this event was consumed
2396 */
2397 protected boolean onKeypress(final TKeypressEvent keypress) {
2398 // Default: only menu shortcuts
2399
2400 // Process Alt-F, Alt-E, etc. menu shortcut keys
2401 if (!keypress.getKey().isFnKey()
2402 && keypress.getKey().isAlt()
2403 && !keypress.getKey().isCtrl()
2404 && (activeMenu == null)
2405 && !modalWindowActive()
2406 ) {
2407
2408 assert (subMenus.size() == 0);
2409
2410 for (TMenu menu: menus) {
2411 if (Character.toLowerCase(menu.getMnemonic().getShortcut())
2412 == Character.toLowerCase(keypress.getKey().getChar())
2413 ) {
2414 activeMenu = menu;
2415 menu.setActive(true);
2416 return true;
2417 }
2418 }
2419 }
2420
2421 return false;
2422 }
2423
2424 // ------------------------------------------------------------------------
2425 // TTimer management ------------------------------------------------------
2426 // ------------------------------------------------------------------------
2427
2428 /**
2429 * Get the amount of time I can sleep before missing a Timer tick.
2430 *
2431 * @param timeout = initial (maximum) timeout in millis
2432 * @return number of milliseconds between now and the next timer event
2433 */
2434 private long getSleepTime(final long timeout) {
2435 Date now = new Date();
2436 long nowTime = now.getTime();
2437 long sleepTime = timeout;
2438 for (TTimer timer: timers) {
2439 long nextTickTime = timer.getNextTick().getTime();
2440 if (nextTickTime < nowTime) {
2441 return 0;
2442 }
2443
2444 long timeDifference = nextTickTime - nowTime;
2445 if (timeDifference < sleepTime) {
2446 sleepTime = timeDifference;
2447 }
2448 }
2449 assert (sleepTime >= 0);
2450 assert (sleepTime <= timeout);
2451 return sleepTime;
2452 }
2453
2454 /**
2455 * Convenience function to add a timer.
2456 *
2457 * @param duration number of milliseconds to wait between ticks
2458 * @param recurring if true, re-schedule this timer after every tick
2459 * @param action function to call when button is pressed
2460 * @return the timer
2461 */
2462 public final TTimer addTimer(final long duration, final boolean recurring,
2463 final TAction action) {
2464
2465 TTimer timer = new TTimer(duration, recurring, action);
2466 synchronized (timers) {
2467 timers.add(timer);
2468 }
2469 return timer;
2470 }
2471
2472 /**
2473 * Convenience function to remove a timer.
2474 *
2475 * @param timer timer to remove
2476 */
2477 public final void removeTimer(final TTimer timer) {
2478 synchronized (timers) {
2479 timers.remove(timer);
2480 }
2481 }
2482
2483 // ------------------------------------------------------------------------
2484 // Other TWindow constructors ---------------------------------------------
2485 // ------------------------------------------------------------------------
2486
2487 /**
2488 * Convenience function to spawn a message box.
2489 *
2490 * @param title window title, will be centered along the top border
2491 * @param caption message to display. Use embedded newlines to get a
2492 * multi-line box.
2493 * @return the new message box
2494 */
2495 public final TMessageBox messageBox(final String title,
2496 final String caption) {
2497
2498 return new TMessageBox(this, title, caption, TMessageBox.Type.OK);
2499 }
2500
2501 /**
2502 * Convenience function to spawn a message box.
2503 *
2504 * @param title window title, will be centered along the top border
2505 * @param caption message to display. Use embedded newlines to get a
2506 * multi-line box.
2507 * @param type one of the TMessageBox.Type constants. Default is
2508 * Type.OK.
2509 * @return the new message box
2510 */
2511 public final TMessageBox messageBox(final String title,
2512 final String caption, final TMessageBox.Type type) {
2513
2514 return new TMessageBox(this, title, caption, type);
2515 }
2516
2517 /**
2518 * Convenience function to spawn an input box.
2519 *
2520 * @param title window title, will be centered along the top border
2521 * @param caption message to display. Use embedded newlines to get a
2522 * multi-line box.
2523 * @return the new input box
2524 */
2525 public final TInputBox inputBox(final String title, final String caption) {
2526
2527 return new TInputBox(this, title, caption);
2528 }
2529
2530 /**
2531 * Convenience function to spawn an input box.
2532 *
2533 * @param title window title, will be centered along the top border
2534 * @param caption message to display. Use embedded newlines to get a
2535 * multi-line box.
2536 * @param text initial text to seed the field with
2537 * @return the new input box
2538 */
2539 public final TInputBox inputBox(final String title, final String caption,
2540 final String text) {
2541
2542 return new TInputBox(this, title, caption, text);
2543 }
2544
2545 /**
2546 * Convenience function to open a terminal window.
2547 *
2548 * @param x column relative to parent
2549 * @param y row relative to parent
2550 * @return the terminal new window
2551 */
2552 public final TTerminalWindow openTerminal(final int x, final int y) {
2553 return openTerminal(x, y, TWindow.RESIZABLE);
2554 }
2555
2556 /**
2557 * Convenience function to open a terminal window.
2558 *
2559 * @param x column relative to parent
2560 * @param y row relative to parent
2561 * @param flags mask of CENTERED, MODAL, or RESIZABLE
2562 * @return the terminal new window
2563 */
2564 public final TTerminalWindow openTerminal(final int x, final int y,
2565 final int flags) {
2566
2567 return new TTerminalWindow(this, x, y, flags);
2568 }
2569
2570 /**
2571 * Convenience function to spawn an file open box.
2572 *
2573 * @param path path of selected file
2574 * @return the result of the new file open box
2575 * @throws IOException if java.io operation throws
2576 */
2577 public final String fileOpenBox(final String path) throws IOException {
2578
2579 TFileOpenBox box = new TFileOpenBox(this, path, TFileOpenBox.Type.OPEN);
2580 return box.getFilename();
2581 }
2582
2583 /**
2584 * Convenience function to spawn an file open box.
2585 *
2586 * @param path path of selected file
2587 * @param type one of the Type constants
2588 * @return the result of the new file open box
2589 * @throws IOException if java.io operation throws
2590 */
2591 public final String fileOpenBox(final String path,
2592 final TFileOpenBox.Type type) throws IOException {
2593
2594 TFileOpenBox box = new TFileOpenBox(this, path, type);
2595 return box.getFilename();
2596 }
2597
2598 /**
2599 * Convenience function to create a new window and make it active.
2600 * Window will be located at (0, 0).
2601 *
2602 * @param title window title, will be centered along the top border
2603 * @param width width of window
2604 * @param height height of window
2605 */
2606 public final TWindow addWindow(final String title, final int width,
2607 final int height) {
2608
2609 TWindow window = new TWindow(this, title, 0, 0, width, height);
2610 return window;
2611 }
2612 /**
2613 * Convenience function to create a new window and make it active.
2614 * Window will be located at (0, 0).
2615 *
2616 * @param title window title, will be centered along the top border
2617 * @param width width of window
2618 * @param height height of window
2619 * @param flags bitmask of RESIZABLE, CENTERED, or MODAL
2620 */
2621 public final TWindow addWindow(final String title,
2622 final int width, final int height, final int flags) {
2623
2624 TWindow window = new TWindow(this, title, 0, 0, width, height, flags);
2625 return window;
2626 }
2627
2628 /**
2629 * Convenience function to create a new window and make it active.
2630 *
2631 * @param title window title, will be centered along the top border
2632 * @param x column relative to parent
2633 * @param y row relative to parent
2634 * @param width width of window
2635 * @param height height of window
2636 */
2637 public final TWindow addWindow(final String title,
2638 final int x, final int y, final int width, final int height) {
2639
2640 TWindow window = new TWindow(this, title, x, y, width, height);
2641 return window;
2642 }
2643
2644 /**
2645 * Convenience function to create a new window and make it active.
2646 *
2647 * @param title window title, will be centered along the top border
2648 * @param x column relative to parent
2649 * @param y row relative to parent
2650 * @param width width of window
2651 * @param height height of window
2652 * @param flags mask of RESIZABLE, CENTERED, or MODAL
2653 */
2654 public final TWindow addWindow(final String title,
2655 final int x, final int y, final int width, final int height,
2656 final int flags) {
2657
2658 TWindow window = new TWindow(this, title, x, y, width, height, flags);
2659 return window;
2660 }
2661
2662 }