stubs for TFileOpenBox, cleanup putStringXY
[nikiroo-utils.git] / src / jexer / TApplication.java
CommitLineData
7d4115a5 1/**
7b5261bc 2 * Jexer - Java Text User Interface
7d4115a5
KL
3 *
4 * License: LGPLv3 or later
5 *
7b5261bc
KL
6 * This module is licensed under the GNU Lesser General Public License
7 * Version 3. Please see the file "COPYING" in this directory for more
8 * information about the GNU Lesser General Public License Version 3.
7d4115a5
KL
9 *
10 * Copyright (C) 2015 Kevin Lamonte
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 3 of
15 * the License, or (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this program; if not, see
24 * http://www.gnu.org/licenses/, or write to the Free Software
25 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 * 02110-1301 USA
7b5261bc
KL
27 *
28 * @author Kevin Lamonte [kevin.lamonte@gmail.com]
29 * @version 1
7d4115a5
KL
30 */
31package jexer;
32
4328bb42 33import java.io.InputStream;
0d47c546 34import java.io.IOException;
4328bb42
KL
35import java.io.OutputStream;
36import java.io.UnsupportedEncodingException;
a06459bd 37import java.util.Collections;
d502a0e9 38import java.util.Date;
e826b451 39import java.util.HashMap;
c6940ed9 40import java.util.ArrayList;
4328bb42
KL
41import java.util.LinkedList;
42import java.util.List;
e826b451 43import java.util.Map;
4328bb42
KL
44
45import jexer.bits.CellAttributes;
46import jexer.bits.ColorTheme;
47import jexer.bits.GraphicsChars;
48import jexer.event.TCommandEvent;
49import jexer.event.TInputEvent;
50import jexer.event.TKeypressEvent;
fca67db0 51import jexer.event.TMenuEvent;
4328bb42
KL
52import jexer.event.TMouseEvent;
53import jexer.event.TResizeEvent;
54import jexer.backend.Backend;
a4406f4e 55import jexer.backend.SwingBackend;
4328bb42 56import jexer.backend.ECMA48Backend;
48e27807 57import jexer.io.Screen;
928811d8
KL
58import jexer.menu.TMenu;
59import jexer.menu.TMenuItem;
4328bb42 60import static jexer.TCommand.*;
4328bb42 61
7d4115a5
KL
62/**
63 * TApplication sets up a full Text User Interface application.
64 */
a4406f4e 65public class TApplication implements Runnable {
7d4115a5 66
99144c71
KL
67 /**
68 * If true, emit thread stuff to System.err.
69 */
70 private static final boolean debugThreads = false;
71
a83fea2b
KL
72 /**
73 * If true, emit events being processed to System.err.
74 */
75 private static final boolean debugEvents = false;
76
a4406f4e
KL
77 /**
78 * Two backend types are available.
79 */
80 public static enum BackendType {
81 /**
82 * A Swing JFrame.
83 */
84 SWING,
85
86 /**
87 * An ECMA48 / ANSI X3.64 / XTERM style terminal.
88 */
89 ECMA48,
90
91 /**
92 * Synonym for ECMA48
93 */
94 XTERM
95 }
96
c6940ed9
KL
97 /**
98 * WidgetEventHandler is the main event consumer loop. There are at most
99 * two such threads in existence: the primary for normal case and a
100 * secondary that is used for TMessageBox, TInputBox, and similar.
101 */
102 private class WidgetEventHandler implements Runnable {
103 /**
104 * The main application.
105 */
106 private TApplication application;
107
108 /**
109 * Whether or not this WidgetEventHandler is the primary or secondary
110 * thread.
111 */
112 private boolean primary = true;
113
114 /**
115 * Public constructor.
116 *
117 * @param application the main application
118 * @param primary if true, this is the primary event handler thread
119 */
120 public WidgetEventHandler(final TApplication application,
121 final boolean primary) {
122
123 this.application = application;
124 this.primary = primary;
125 }
126
127 /**
128 * The consumer loop.
129 */
130 public void run() {
131
132 // Loop forever
133 while (!application.quit) {
134
135 // Wait until application notifies me
136 while (!application.quit) {
137 try {
138 synchronized (application.drainEventQueue) {
139 if (application.drainEventQueue.size() > 0) {
140 break;
141 }
142 }
92554d64
KL
143
144 synchronized (this) {
bd8d51fa
KL
145 if (debugThreads) {
146 System.err.printf("%s %s sleep\n", this,
147 primary ? "primary" : "secondary");
148 }
92554d64
KL
149
150 this.wait();
151
bd8d51fa
KL
152 if (debugThreads) {
153 System.err.printf("%s %s AWAKE\n", this,
154 primary ? "primary" : "secondary");
155 }
92554d64 156
c6940ed9
KL
157 if ((!primary)
158 && (application.secondaryEventReceiver == null)
159 ) {
92554d64
KL
160 // Secondary thread, emergency exit. If we
161 // got here then something went wrong with
162 // the handoff between yield() and
163 // closeWindow().
92554d64
KL
164 synchronized (application.primaryEventHandler) {
165 application.primaryEventHandler.notify();
166 }
167 application.secondaryEventHandler = null;
bd8d51fa
KL
168 throw new RuntimeException(
169 "secondary exited at wrong time");
c6940ed9
KL
170 }
171 break;
172 }
173 } catch (InterruptedException e) {
174 // SQUASH
175 }
176 }
177
ef368bd0
KL
178 // Wait for drawAll() or doIdle() to be done, then handle the
179 // events.
180 boolean oldLock = lockHandleEvent();
181 assert (oldLock == false);
182
c6940ed9
KL
183 // Pull all events off the queue
184 for (;;) {
185 TInputEvent event = null;
186 synchronized (application.drainEventQueue) {
187 if (application.drainEventQueue.size() == 0) {
188 break;
189 }
190 event = application.drainEventQueue.remove(0);
191 }
bd8d51fa 192 application.repaint = true;
c6940ed9
KL
193 if (primary) {
194 primaryHandleEvent(event);
195 } else {
196 secondaryHandleEvent(event);
197 }
198 if ((!primary)
199 && (application.secondaryEventReceiver == null)
200 ) {
99144c71
KL
201 // Secondary thread, time to exit.
202
203 // DO NOT UNLOCK. Primary thread just came back from
204 // primaryHandleEvent() and will unlock in the else
92554d64
KL
205 // block below. Just wake it up.
206 synchronized (application.primaryEventHandler) {
207 application.primaryEventHandler.notify();
208 }
209 // Now eliminate my reference so that
210 // wakeEventHandler() resumes working on the primary.
211 application.secondaryEventHandler = null;
212
213 // All done!
c6940ed9
KL
214 return;
215 }
92554d64
KL
216 } // for (;;)
217
ef368bd0
KL
218 // Unlock. Either I am primary thread, or I am secondary
219 // thread and still running.
220 oldLock = unlockHandleEvent();
221 assert (oldLock == true);
222
92554d64
KL
223 // I have done some work of some kind. Tell the main run()
224 // loop to wake up now.
225 synchronized (application) {
226 application.notify();
c6940ed9 227 }
92554d64 228
c6940ed9
KL
229 } // while (true) (main runnable loop)
230 }
231 }
232
233 /**
234 * The primary event handler thread.
235 */
92554d64 236 private volatile WidgetEventHandler primaryEventHandler;
c6940ed9
KL
237
238 /**
239 * The secondary event handler thread.
240 */
92554d64 241 private volatile WidgetEventHandler secondaryEventHandler;
c6940ed9
KL
242
243 /**
244 * The widget receiving events from the secondary event handler thread.
245 */
92554d64 246 private volatile TWidget secondaryEventReceiver;
c6940ed9 247
99144c71
KL
248 /**
249 * Spinlock for the primary and secondary event handlers.
250 * WidgetEventHandler.run() is responsible for setting this value.
251 */
252 private volatile boolean insideHandleEvent = false;
253
92554d64
KL
254 /**
255 * Wake the sleeping active event handler.
256 */
257 private void wakeEventHandler() {
258 if (secondaryEventHandler != null) {
259 synchronized (secondaryEventHandler) {
260 secondaryEventHandler.notify();
261 }
262 } else {
263 assert (primaryEventHandler != null);
264 synchronized (primaryEventHandler) {
265 primaryEventHandler.notify();
266 }
267 }
268 }
269
99144c71
KL
270 /**
271 * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
272 * spin indefinitely until unlockHandleEvent() is called.
273 *
274 * @return the old value of insideHandleEvent
275 */
276 private boolean lockHandleEvent() {
277 if (debugThreads) {
278 System.err.printf(" >> lockHandleEvent(): oldValue %s",
279 insideHandleEvent);
280 }
281 boolean oldValue = true;
282
283 synchronized (this) {
284 // Wait for TApplication.run() to finish using the global state
285 // before allowing further event processing.
ef368bd0
KL
286 while (lockoutHandleEvent == true) {
287 try {
288 // Backoff so that the backend can finish its work.
289 Thread.sleep(5);
290 } catch (InterruptedException e) {
291 // SQUASH
292 }
293 }
99144c71
KL
294
295 oldValue = insideHandleEvent;
296 insideHandleEvent = true;
297 }
298
299 if (debugThreads) {
300 System.err.printf(" ***\n");
301 }
302 return oldValue;
303 }
304
305 /**
306 * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
307 * spin indefinitely until unlockHandleEvent() is called.
308 *
309 * @return the old value of insideHandleEvent
310 */
311 private boolean unlockHandleEvent() {
312 if (debugThreads) {
313 System.err.printf(" << unlockHandleEvent(): oldValue %s\n",
314 insideHandleEvent);
315 }
316 synchronized (this) {
317 boolean oldValue = insideHandleEvent;
318 insideHandleEvent = false;
319 return oldValue;
320 }
321 }
322
323 /**
324 * Spinlock for the primary and secondary event handlers. When true, the
325 * event handlers will spinlock wait before calling handleEvent().
326 */
327 private volatile boolean lockoutHandleEvent = false;
328
329 /**
330 * TApplication.run() needs to be able rely on the global data structures
331 * being intact when calling doIdle() and drawAll(). Tell the event
332 * handlers to wait for an unlock before handling their events.
333 */
334 private void stopEventHandlers() {
335 if (debugThreads) {
336 System.err.printf(">> stopEventHandlers()");
337 }
338
339 lockoutHandleEvent = true;
340 // Wait for the last event to finish processing before returning
341 // control to TApplication.run().
ef368bd0
KL
342 while (insideHandleEvent == true) {
343 try {
344 // Backoff so that the event handler can finish its work.
345 Thread.sleep(1);
346 } catch (InterruptedException e) {
347 // SQUASH
348 }
349 }
99144c71
KL
350
351 if (debugThreads) {
352 System.err.printf(" XXX\n");
353 }
354 }
355
356 /**
357 * TApplication.run() needs to be able rely on the global data structures
358 * being intact when calling doIdle() and drawAll(). Tell the event
359 * handlers that it is now OK to handle their events.
360 */
361 private void startEventHandlers() {
362 if (debugThreads) {
363 System.err.printf("<< startEventHandlers()\n");
364 }
365 lockoutHandleEvent = false;
366 }
367
7d4115a5 368 /**
4328bb42
KL
369 * Access to the physical screen, keyboard, and mouse.
370 */
7b5261bc 371 private Backend backend;
4328bb42 372
48e27807
KL
373 /**
374 * Get the Screen.
375 *
376 * @return the Screen
377 */
378 public final Screen getScreen() {
379 return backend.getScreen();
380 }
381
4328bb42 382 /**
7b5261bc 383 * Actual mouse coordinate X.
4328bb42
KL
384 */
385 private int mouseX;
386
387 /**
7b5261bc 388 * Actual mouse coordinate Y.
4328bb42
KL
389 */
390 private int mouseY;
391
bd8d51fa
KL
392 /**
393 * Old version of mouse coordinate X.
394 */
395 private int oldMouseX;
396
397 /**
398 * Old version mouse coordinate Y.
399 */
400 private int oldMouseY;
401
4328bb42 402 /**
8e688b92 403 * Event queue that is filled by run().
4328bb42 404 */
8e688b92
KL
405 private List<TInputEvent> fillEventQueue;
406
407 /**
408 * Event queue that will be drained by either primary or secondary
409 * Thread.
410 */
411 private List<TInputEvent> drainEventQueue;
4328bb42 412
fca67db0
KL
413 /**
414 * Top-level menus in this application.
415 */
416 private List<TMenu> menus;
417
418 /**
419 * Stack of activated sub-menus in this application.
420 */
421 private List<TMenu> subMenus;
422
423 /**
424 * The currently acive menu.
425 */
426 private TMenu activeMenu = null;
427
e826b451
KL
428 /**
429 * Active keyboard accelerators.
430 */
431 private Map<TKeypress, TMenuItem> accelerators;
432
4328bb42
KL
433 /**
434 * Windows and widgets pull colors from this ColorTheme.
435 */
7b5261bc
KL
436 private ColorTheme theme;
437
438 /**
439 * Get the color theme.
440 *
441 * @return the theme
442 */
443 public final ColorTheme getTheme() {
444 return theme;
445 }
4328bb42 446
a06459bd
KL
447 /**
448 * The top-level windows (but not menus).
449 */
fca67db0 450 private List<TWindow> windows;
a06459bd 451
d502a0e9
KL
452 /**
453 * Timers that are being ticked.
454 */
455 private List<TTimer> timers;
456
4328bb42
KL
457 /**
458 * When true, exit the application.
459 */
92554d64 460 private volatile boolean quit = false;
4328bb42
KL
461
462 /**
463 * When true, repaint the entire screen.
464 */
92554d64 465 private volatile boolean repaint = true;
4328bb42 466
4328bb42 467 /**
7b5261bc
KL
468 * Y coordinate of the top edge of the desktop. For now this is a
469 * constant. Someday it would be nice to have a multi-line menu or
470 * toolbars.
4328bb42 471 */
48e27807
KL
472 private static final int desktopTop = 1;
473
474 /**
475 * Get Y coordinate of the top edge of the desktop.
476 *
477 * @return Y coordinate of the top edge of the desktop
478 */
479 public final int getDesktopTop() {
480 return desktopTop;
481 }
4328bb42
KL
482
483 /**
484 * Y coordinate of the bottom edge of the desktop.
485 */
48e27807
KL
486 private int desktopBottom;
487
488 /**
489 * Get Y coordinate of the bottom edge of the desktop.
490 *
491 * @return Y coordinate of the bottom edge of the desktop
492 */
493 public final int getDesktopBottom() {
494 return desktopBottom;
495 }
4328bb42
KL
496
497 /**
498 * Public constructor.
499 *
a4406f4e
KL
500 * @param backendType BackendType.XTERM, BackendType.ECMA48 or
501 * BackendType.SWING
502 * @throws UnsupportedEncodingException if an exception is thrown when
503 * creating the InputStreamReader
504 */
505 public TApplication(final BackendType backendType)
506 throws UnsupportedEncodingException {
507
508 switch (backendType) {
509 case SWING:
510 backend = new SwingBackend(this);
511 break;
512 case XTERM:
513 // Fall through...
514 case ECMA48:
515 backend = new ECMA48Backend(this, null, null);
516 }
517 TApplicationImpl();
518 }
519
520 /**
521 * Public constructor. The backend type will be BackendType.ECMA48.
522 *
4328bb42
KL
523 * @param input an InputStream connected to the remote user, or null for
524 * System.in. If System.in is used, then on non-Windows systems it will
525 * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
526 * mode. input is always converted to a Reader with UTF-8 encoding.
527 * @param output an OutputStream connected to the remote user, or null
528 * for System.out. output is always converted to a Writer with UTF-8
529 * encoding.
7b5261bc
KL
530 * @throws UnsupportedEncodingException if an exception is thrown when
531 * creating the InputStreamReader
4328bb42 532 */
7b5261bc
KL
533 public TApplication(final InputStream input,
534 final OutputStream output) throws UnsupportedEncodingException {
4328bb42 535
a4406f4e
KL
536 backend = new ECMA48Backend(this, input, output);
537 TApplicationImpl();
538 }
30bd4abd 539
a4406f4e
KL
540 /**
541 * Public constructor. This hook enables use with new non-Jexer
542 * backends.
543 *
544 * @param backend a Backend that is already ready to go.
545 */
546 public TApplication(final Backend backend) {
547 this.backend = backend;
548 TApplicationImpl();
549 }
30bd4abd 550
a4406f4e
KL
551 /**
552 * Finish construction once the backend is set.
553 */
554 private void TApplicationImpl() {
8e688b92
KL
555 theme = new ColorTheme();
556 desktopBottom = getScreen().getHeight() - 1;
c6940ed9
KL
557 fillEventQueue = new ArrayList<TInputEvent>();
558 drainEventQueue = new ArrayList<TInputEvent>();
8e688b92
KL
559 windows = new LinkedList<TWindow>();
560 menus = new LinkedList<TMenu>();
561 subMenus = new LinkedList<TMenu>();
d502a0e9 562 timers = new LinkedList<TTimer>();
e826b451 563 accelerators = new HashMap<TKeypress, TMenuItem>();
c6940ed9
KL
564
565 // Setup the main consumer thread
566 primaryEventHandler = new WidgetEventHandler(this, true);
567 (new Thread(primaryEventHandler)).start();
4328bb42
KL
568 }
569
570 /**
bd8d51fa
KL
571 * Invert the cell color at a position. This is used to track the mouse.
572 *
573 * @param x column position
574 * @param y row position
4328bb42 575 */
bd8d51fa
KL
576 private void invertCell(final int x, final int y) {
577 synchronized (getScreen()) {
578 CellAttributes attr = getScreen().getAttrXY(x, y);
579 attr.setForeColor(attr.getForeColor().invert());
580 attr.setBackColor(attr.getBackColor().invert());
581 getScreen().putAttrXY(x, y, attr, false);
7b5261bc 582 }
4328bb42
KL
583 }
584
585 /**
586 * Draw everything.
587 */
7c870d89 588 private void drawAll() {
99144c71
KL
589 if (debugThreads) {
590 System.err.printf("drawAll() enter\n");
591 }
592
bd8d51fa 593 if (!repaint) {
ef368bd0
KL
594 if ((oldMouseX != mouseX) || (oldMouseY != mouseY)) {
595 // The only thing that has happened is the mouse moved.
596 // Clear the old position and draw the new position.
597 invertCell(oldMouseX, oldMouseY);
598 invertCell(mouseX, mouseY);
599 oldMouseX = mouseX;
600 oldMouseY = mouseY;
bd8d51fa
KL
601 }
602 if (getScreen().isDirty()) {
603 backend.flushScreen();
604 }
7b5261bc
KL
605 return;
606 }
607
99144c71
KL
608 if (debugThreads) {
609 System.err.printf("drawAll() REDRAW\n");
610 }
611
7b5261bc
KL
612 // If true, the cursor is not visible
613 boolean cursor = false;
614
615 // Start with a clean screen
a06459bd 616 getScreen().clear();
7b5261bc
KL
617
618 // Draw the background
619 CellAttributes background = theme.getColor("tapplication.background");
a06459bd 620 getScreen().putAll(GraphicsChars.HATCH, background);
7b5261bc 621
7b5261bc 622 // Draw each window in reverse Z order
a06459bd
KL
623 List<TWindow> sorted = new LinkedList<TWindow>(windows);
624 Collections.sort(sorted);
625 Collections.reverse(sorted);
626 for (TWindow window: sorted) {
627 window.drawChildren();
7b5261bc
KL
628 }
629
630 // Draw the blank menubar line - reset the screen clipping first so
631 // it won't trim it out.
a06459bd
KL
632 getScreen().resetClipping();
633 getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
7b5261bc
KL
634 theme.getColor("tmenu"));
635 // Now draw the menus.
636 int x = 1;
fca67db0 637 for (TMenu menu: menus) {
7b5261bc
KL
638 CellAttributes menuColor;
639 CellAttributes menuMnemonicColor;
7c870d89 640 if (menu.isActive()) {
7b5261bc
KL
641 menuColor = theme.getColor("tmenu.highlighted");
642 menuMnemonicColor = theme.getColor("tmenu.mnemonic.highlighted");
643 } else {
644 menuColor = theme.getColor("tmenu");
645 menuMnemonicColor = theme.getColor("tmenu.mnemonic");
646 }
647 // Draw the menu title
fca67db0 648 getScreen().hLineXY(x, 0, menu.getTitle().length() + 2, ' ',
7b5261bc 649 menuColor);
0d47c546 650 getScreen().putStringXY(x + 1, 0, menu.getTitle(), menuColor);
7b5261bc 651 // Draw the highlight character
fca67db0
KL
652 getScreen().putCharXY(x + 1 + menu.getMnemonic().getShortcutIdx(),
653 0, menu.getMnemonic().getShortcut(), menuMnemonicColor);
7b5261bc 654
7c870d89 655 if (menu.isActive()) {
a06459bd 656 menu.drawChildren();
7b5261bc 657 // Reset the screen clipping so we can draw the next title.
a06459bd 658 getScreen().resetClipping();
7b5261bc 659 }
fca67db0 660 x += menu.getTitle().length() + 2;
7b5261bc
KL
661 }
662
a06459bd 663 for (TMenu menu: subMenus) {
7b5261bc 664 // Reset the screen clipping so we can draw the next sub-menu.
a06459bd
KL
665 getScreen().resetClipping();
666 menu.drawChildren();
7b5261bc 667 }
7b5261bc
KL
668
669 // Draw the mouse pointer
bd8d51fa 670 invertCell(mouseX, mouseY);
7b5261bc 671
7b5261bc
KL
672 // Place the cursor if it is visible
673 TWidget activeWidget = null;
a06459bd
KL
674 if (sorted.size() > 0) {
675 activeWidget = sorted.get(sorted.size() - 1).getActiveChild();
7c870d89 676 if (activeWidget.isCursorVisible()) {
a06459bd 677 getScreen().putCursor(true, activeWidget.getCursorAbsoluteX(),
7b5261bc
KL
678 activeWidget.getCursorAbsoluteY());
679 cursor = true;
680 }
681 }
682
683 // Kill the cursor
fca67db0 684 if (!cursor) {
a06459bd 685 getScreen().hideCursor();
7b5261bc 686 }
7b5261bc
KL
687
688 // Flush the screen contents
689 backend.flushScreen();
690
691 repaint = false;
4328bb42
KL
692 }
693
694 /**
7b5261bc 695 * Run this application until it exits.
4328bb42 696 */
a4406f4e 697 public void run() {
7b5261bc
KL
698 while (!quit) {
699 // Timeout is in milliseconds, so default timeout after 1 second
700 // of inactivity.
92554d64
KL
701 long timeout = 0;
702
703 // If I've got no updates to render, wait for something from the
704 // backend or a timer.
bd8d51fa
KL
705 if (!repaint
706 && ((mouseX == oldMouseX) && (mouseY == oldMouseY))
707 ) {
e3dfbd23
KL
708 // Never sleep longer than 50 millis. We need time for
709 // windows with background tasks to update the display, and
710 // still flip buffers reasonably quickly in
711 // backend.flushPhysical().
712 timeout = getSleepTime(50);
8e688b92 713 }
92554d64
KL
714
715 if (timeout > 0) {
716 // As of now, I've got nothing to do: no I/O, nothing from
717 // the consumer threads, no timers that need to run ASAP. So
718 // wait until either the backend or the consumer threads have
719 // something to do.
720 try {
721 synchronized (this) {
722 this.wait(timeout);
723 }
724 } catch (InterruptedException e) {
725 // I'm awake and don't care why, let's see what's going
726 // on out there.
8e688b92 727 }
bd8d51fa 728 repaint = true;
7b5261bc
KL
729 }
730
ef368bd0
KL
731 // Prevent stepping on the primary or secondary event handler.
732 stopEventHandlers();
733
8e688b92 734 // Pull any pending I/O events
92554d64 735 backend.getEvents(fillEventQueue);
8e688b92
KL
736
737 // Dispatch each event to the appropriate handler, one at a time.
738 for (;;) {
739 TInputEvent event = null;
ef368bd0
KL
740 if (fillEventQueue.size() == 0) {
741 break;
8e688b92 742 }
ef368bd0 743 event = fillEventQueue.remove(0);
8e688b92
KL
744 metaHandleEvent(event);
745 }
7b5261bc 746
92554d64 747 // Wake a consumer thread if we have any pending events.
ef368bd0
KL
748 if (drainEventQueue.size() > 0) {
749 wakeEventHandler();
92554d64
KL
750 }
751
7b5261bc
KL
752 // Process timers and call doIdle()'s
753 doIdle();
754
755 // Update the screen
87a17f3c
KL
756 synchronized (getScreen()) {
757 drawAll();
758 }
99144c71
KL
759
760 // Let the event handlers run again.
761 startEventHandlers();
7b5261bc 762
92554d64
KL
763 } // while (!quit)
764
765 // Shutdown the event consumer threads
766 if (secondaryEventHandler != null) {
767 synchronized (secondaryEventHandler) {
768 secondaryEventHandler.notify();
769 }
770 }
771 if (primaryEventHandler != null) {
772 synchronized (primaryEventHandler) {
773 primaryEventHandler.notify();
774 }
7b5261bc
KL
775 }
776
92554d64 777 // Shutdown the user I/O thread(s)
7b5261bc 778 backend.shutdown();
92554d64
KL
779
780 // Close all the windows. This gives them an opportunity to release
781 // resources.
782 closeAllWindows();
783
4328bb42
KL
784 }
785
786 /**
787 * Peek at certain application-level events, add to eventQueue, and wake
8e688b92 788 * up the consuming Thread.
4328bb42 789 *
8e688b92 790 * @param event the input event to consume
4328bb42 791 */
8e688b92 792 private void metaHandleEvent(final TInputEvent event) {
7b5261bc 793
a83fea2b
KL
794 if (debugEvents) {
795 System.err.printf(String.format("metaHandleEvents event: %s\n",
796 event)); System.err.flush();
797 }
7b5261bc 798
8e688b92
KL
799 if (quit) {
800 // Do no more processing if the application is already trying
801 // to exit.
802 return;
803 }
7b5261bc 804
8e688b92 805 // Special application-wide events -------------------------------
7b5261bc 806
8e688b92
KL
807 // Abort everything
808 if (event instanceof TCommandEvent) {
809 TCommandEvent command = (TCommandEvent) event;
810 if (command.getCmd().equals(cmAbort)) {
811 quit = true;
812 return;
7b5261bc 813 }
8e688b92 814 }
7b5261bc 815
8e688b92
KL
816 // Screen resize
817 if (event instanceof TResizeEvent) {
818 TResizeEvent resize = (TResizeEvent) event;
bd8d51fa
KL
819 synchronized (getScreen()) {
820 getScreen().setDimensions(resize.getWidth(),
821 resize.getHeight());
822 desktopBottom = getScreen().getHeight() - 1;
823 mouseX = 0;
824 mouseY = 0;
825 oldMouseX = 0;
826 oldMouseY = 0;
827 }
8e688b92
KL
828 return;
829 }
7b5261bc 830
8e688b92
KL
831 // Peek at the mouse position
832 if (event instanceof TMouseEvent) {
833 TMouseEvent mouse = (TMouseEvent) event;
bd8d51fa
KL
834 synchronized (getScreen()) {
835 if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
836 oldMouseX = mouseX;
837 oldMouseY = mouseY;
838 mouseX = mouse.getX();
839 mouseY = mouse.getY();
840 }
7b5261bc 841 }
8e688b92 842 }
7b5261bc 843
bd8d51fa 844 // Put into the main queue
ef368bd0 845 drainEventQueue.add(event);
4328bb42
KL
846 }
847
a06459bd
KL
848 /**
849 * Dispatch one event to the appropriate widget or application-level
fca67db0
KL
850 * event handler. This is the primary event handler, it has the normal
851 * application-wide event handling.
a06459bd
KL
852 *
853 * @param event the input event to consume
fca67db0 854 * @see #secondaryHandleEvent(TInputEvent event)
a06459bd 855 */
fca67db0
KL
856 private void primaryHandleEvent(final TInputEvent event) {
857
a83fea2b
KL
858 if (debugEvents) {
859 System.err.printf("Handle event: %s\n", event);
860 }
fca67db0
KL
861
862 // Special application-wide events -----------------------------------
863
864 // Peek at the mouse position
865 if (event instanceof TMouseEvent) {
866 // See if we need to switch focus to another window or the menu
867 checkSwitchFocus((TMouseEvent) event);
868 }
869
870 // Handle menu events
871 if ((activeMenu != null) && !(event instanceof TCommandEvent)) {
872 TMenu menu = activeMenu;
873
874 if (event instanceof TMouseEvent) {
875 TMouseEvent mouse = (TMouseEvent) event;
876
877 while (subMenus.size() > 0) {
878 TMenu subMenu = subMenus.get(subMenus.size() - 1);
879 if (subMenu.mouseWouldHit(mouse)) {
880 break;
881 }
882 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
7c870d89
KL
883 && (!mouse.isMouse1())
884 && (!mouse.isMouse2())
885 && (!mouse.isMouse3())
886 && (!mouse.isMouseWheelUp())
887 && (!mouse.isMouseWheelDown())
fca67db0
KL
888 ) {
889 break;
890 }
891 // We navigated away from a sub-menu, so close it
892 closeSubMenu();
893 }
894
895 // Convert the mouse relative x/y to menu coordinates
896 assert (mouse.getX() == mouse.getAbsoluteX());
897 assert (mouse.getY() == mouse.getAbsoluteY());
898 if (subMenus.size() > 0) {
899 menu = subMenus.get(subMenus.size() - 1);
900 }
901 mouse.setX(mouse.getX() - menu.getX());
902 mouse.setY(mouse.getY() - menu.getY());
903 }
904 menu.handleEvent(event);
905 return;
906 }
a06459bd 907
fca67db0
KL
908 if (event instanceof TKeypressEvent) {
909 TKeypressEvent keypress = (TKeypressEvent) event;
e826b451 910
fca67db0
KL
911 // See if this key matches an accelerator, and if so dispatch the
912 // menu event.
913 TKeypress keypressLowercase = keypress.getKey().toLowerCase();
e826b451
KL
914 TMenuItem item = null;
915 synchronized (accelerators) {
916 item = accelerators.get(keypressLowercase);
917 }
fca67db0 918 if (item != null) {
7c870d89 919 if (item.isEnabled()) {
bd8d51fa
KL
920 // Let the menu item dispatch
921 item.dispatch();
fca67db0
KL
922 return;
923 }
924 }
bd8d51fa
KL
925 // Handle the keypress
926 if (onKeypress(keypress)) {
927 return;
928 }
fca67db0 929 }
a06459bd 930
fca67db0
KL
931 if (event instanceof TCommandEvent) {
932 if (onCommand((TCommandEvent) event)) {
933 return;
934 }
935 }
936
937 if (event instanceof TMenuEvent) {
938 if (onMenu((TMenuEvent) event)) {
939 return;
940 }
941 }
942
943 // Dispatch events to the active window -------------------------------
944 for (TWindow window: windows) {
7c870d89 945 if (window.isActive()) {
a06459bd
KL
946 if (event instanceof TMouseEvent) {
947 TMouseEvent mouse = (TMouseEvent) event;
fca67db0
KL
948 // Convert the mouse relative x/y to window coordinates
949 assert (mouse.getX() == mouse.getAbsoluteX());
950 assert (mouse.getY() == mouse.getAbsoluteY());
951 mouse.setX(mouse.getX() - window.getX());
952 mouse.setY(mouse.getY() - window.getY());
953 }
a83fea2b
KL
954 if (debugEvents) {
955 System.err.printf("TApplication dispatch event: %s\n",
956 event);
957 }
fca67db0
KL
958 window.handleEvent(event);
959 break;
960 }
961 }
962 }
963 /**
964 * Dispatch one event to the appropriate widget or application-level
965 * event handler. This is the secondary event handler used by certain
966 * special dialogs (currently TMessageBox and TFileOpenBox).
967 *
968 * @param event the input event to consume
969 * @see #primaryHandleEvent(TInputEvent event)
970 */
971 private void secondaryHandleEvent(final TInputEvent event) {
c6940ed9
KL
972 secondaryEventReceiver.handleEvent(event);
973 }
974
975 /**
976 * Enable a widget to override the primary event thread.
977 *
978 * @param widget widget that will receive events
979 */
980 public final void enableSecondaryEventReceiver(final TWidget widget) {
981 assert (secondaryEventReceiver == null);
982 assert (secondaryEventHandler == null);
983 assert (widget instanceof TMessageBox);
984 secondaryEventReceiver = widget;
985 secondaryEventHandler = new WidgetEventHandler(this, false);
986 (new Thread(secondaryEventHandler)).start();
c6940ed9
KL
987 }
988
989 /**
990 * Yield to the secondary thread.
991 */
992 public final void yield() {
993 assert (secondaryEventReceiver != null);
99144c71
KL
994 // This is where we handoff the event handler lock from the primary
995 // to secondary thread. We unlock here, and in a future loop the
996 // secondary thread locks again. When it gives up, we have the
997 // single lock back.
998 boolean oldLock = unlockHandleEvent();
999 assert (oldLock == true);
1000
c6940ed9 1001 while (secondaryEventReceiver != null) {
92554d64 1002 synchronized (primaryEventHandler) {
c6940ed9 1003 try {
92554d64 1004 primaryEventHandler.wait();
c6940ed9
KL
1005 } catch (InterruptedException e) {
1006 // SQUASH
1007 }
1008 }
1009 }
a06459bd
KL
1010 }
1011
4328bb42
KL
1012 /**
1013 * Do stuff when there is no user input.
1014 */
1015 private void doIdle() {
99144c71
KL
1016 if (debugThreads) {
1017 System.err.printf("doIdle()\n");
1018 }
1019
7b5261bc 1020 // Now run any timers that have timed out
d502a0e9
KL
1021 Date now = new Date();
1022 List<TTimer> keepTimers = new LinkedList<TTimer>();
1023 for (TTimer timer: timers) {
92554d64 1024 if (timer.getNextTick().getTime() <= now.getTime()) {
d502a0e9 1025 timer.tick();
c6940ed9 1026 if (timer.recurring) {
d502a0e9 1027 keepTimers.add(timer);
7b5261bc
KL
1028 }
1029 } else {
d502a0e9 1030 keepTimers.add(timer);
7b5261bc
KL
1031 }
1032 }
1033 timers = keepTimers;
1034
1035 // Call onIdle's
d502a0e9
KL
1036 for (TWindow window: windows) {
1037 window.onIdle();
7b5261bc 1038 }
4328bb42 1039 }
7d4115a5 1040
4328bb42
KL
1041 /**
1042 * Get the amount of time I can sleep before missing a Timer tick.
1043 *
92554d64 1044 * @param timeout = initial (maximum) timeout in millis
4328bb42
KL
1045 * @return number of milliseconds between now and the next timer event
1046 */
bd8d51fa 1047 private long getSleepTime(final long timeout) {
d502a0e9 1048 Date now = new Date();
92554d64 1049 long nowTime = now.getTime();
d502a0e9
KL
1050 long sleepTime = timeout;
1051 for (TTimer timer: timers) {
92554d64
KL
1052 long nextTickTime = timer.getNextTick().getTime();
1053 if (nextTickTime < nowTime) {
7b5261bc
KL
1054 return 0;
1055 }
92554d64
KL
1056
1057 long timeDifference = nextTickTime - nowTime;
1058 if (timeDifference < sleepTime) {
1059 sleepTime = timeDifference;
7b5261bc
KL
1060 }
1061 }
d502a0e9 1062 assert (sleepTime >= 0);
92554d64
KL
1063 assert (sleepTime <= timeout);
1064 return sleepTime;
7d4115a5 1065 }
4328bb42 1066
48e27807
KL
1067 /**
1068 * Close window. Note that the window's destructor is NOT called by this
1069 * method, instead the GC is assumed to do the cleanup.
1070 *
1071 * @param window the window to remove
1072 */
1073 public final void closeWindow(final TWindow window) {
bb35d919
KL
1074 synchronized (windows) {
1075 int z = window.getZ();
1076 window.setZ(-1);
1077 Collections.sort(windows);
1078 windows.remove(0);
1079 TWindow activeWindow = null;
1080 for (TWindow w: windows) {
1081 if (w.getZ() > z) {
1082 w.setZ(w.getZ() - 1);
1083 if (w.getZ() == 0) {
1084 w.setActive(true);
1085 assert (activeWindow == null);
1086 activeWindow = w;
1087 } else {
1088 w.setActive(false);
1089 }
48e27807
KL
1090 }
1091 }
1092 }
1093
1094 // Perform window cleanup
1095 window.onClose();
1096
48e27807 1097 // Check if we are closing a TMessageBox or similar
c6940ed9
KL
1098 if (secondaryEventReceiver != null) {
1099 assert (secondaryEventHandler != null);
48e27807
KL
1100
1101 // Do not send events to the secondaryEventReceiver anymore, the
1102 // window is closed.
1103 secondaryEventReceiver = null;
1104
92554d64
KL
1105 // Wake the secondary thread, it will wake the primary as it
1106 // exits.
1107 synchronized (secondaryEventHandler) {
1108 secondaryEventHandler.notify();
48e27807
KL
1109 }
1110 }
48e27807
KL
1111 }
1112
1113 /**
1114 * Switch to the next window.
1115 *
1116 * @param forward if true, then switch to the next window in the list,
1117 * otherwise switch to the previous window in the list
1118 */
1119 public final void switchWindow(final boolean forward) {
48e27807 1120 // Only switch if there are multiple windows
fca67db0 1121 if (windows.size() < 2) {
48e27807
KL
1122 return;
1123 }
1124
bb35d919
KL
1125 synchronized (windows) {
1126
1127 // Swap z/active between active window and the next in the list
1128 int activeWindowI = -1;
1129 for (int i = 0; i < windows.size(); i++) {
7c870d89 1130 if (windows.get(i).isActive()) {
bb35d919
KL
1131 activeWindowI = i;
1132 break;
1133 }
48e27807 1134 }
bb35d919 1135 assert (activeWindowI >= 0);
48e27807 1136
bb35d919
KL
1137 // Do not switch if a window is modal
1138 if (windows.get(activeWindowI).isModal()) {
1139 return;
1140 }
48e27807 1141
bb35d919
KL
1142 int nextWindowI;
1143 if (forward) {
1144 nextWindowI = (activeWindowI + 1) % windows.size();
48e27807 1145 } else {
bb35d919
KL
1146 if (activeWindowI == 0) {
1147 nextWindowI = windows.size() - 1;
1148 } else {
1149 nextWindowI = activeWindowI - 1;
1150 }
48e27807 1151 }
bb35d919
KL
1152 windows.get(activeWindowI).setActive(false);
1153 windows.get(activeWindowI).setZ(windows.get(nextWindowI).getZ());
1154 windows.get(nextWindowI).setZ(0);
1155 windows.get(nextWindowI).setActive(true);
1156
1157 } // synchronized (windows)
48e27807 1158
48e27807
KL
1159 }
1160
1161 /**
1162 * Add a window to my window list and make it active.
1163 *
1164 * @param window new window to add
1165 */
1166 public final void addWindow(final TWindow window) {
bb35d919
KL
1167 synchronized (windows) {
1168 // Do not allow a modal window to spawn a non-modal window
1169 if ((windows.size() > 0) && (windows.get(0).isModal())) {
1170 assert (window.isModal());
1171 }
1172 for (TWindow w: windows) {
1173 w.setActive(false);
1174 w.setZ(w.getZ() + 1);
1175 }
1176 windows.add(window);
1177 window.setActive(true);
1178 window.setZ(0);
48e27807 1179 }
48e27807
KL
1180 }
1181
fca67db0
KL
1182 /**
1183 * Check if there is a system-modal window on top.
1184 *
1185 * @return true if the active window is modal
1186 */
1187 private boolean modalWindowActive() {
1188 if (windows.size() == 0) {
1189 return false;
1190 }
1191 return windows.get(windows.size() - 1).isModal();
1192 }
1193
1194 /**
1195 * Check if a mouse event would hit either the active menu or any open
1196 * sub-menus.
1197 *
1198 * @param mouse mouse event
1199 * @return true if the mouse would hit the active menu or an open
1200 * sub-menu
1201 */
1202 private boolean mouseOnMenu(final TMouseEvent mouse) {
1203 assert (activeMenu != null);
1204 List<TMenu> menus = new LinkedList<TMenu>(subMenus);
1205 Collections.reverse(menus);
1206 for (TMenu menu: menus) {
1207 if (menu.mouseWouldHit(mouse)) {
1208 return true;
1209 }
1210 }
1211 return activeMenu.mouseWouldHit(mouse);
1212 }
1213
1214 /**
1215 * See if we need to switch window or activate the menu based on
1216 * a mouse click.
1217 *
1218 * @param mouse mouse event
1219 */
1220 private void checkSwitchFocus(final TMouseEvent mouse) {
1221
1222 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
1223 && (activeMenu != null)
1224 && (mouse.getAbsoluteY() != 0)
1225 && (!mouseOnMenu(mouse))
1226 ) {
1227 // They clicked outside the active menu, turn it off
1228 activeMenu.setActive(false);
1229 activeMenu = null;
1230 for (TMenu menu: subMenus) {
1231 menu.setActive(false);
1232 }
1233 subMenus.clear();
1234 // Continue checks
1235 }
1236
1237 // See if they hit the menu bar
1238 if ((mouse.getType() == TMouseEvent.Type.MOUSE_DOWN)
7c870d89 1239 && (mouse.isMouse1())
fca67db0
KL
1240 && (!modalWindowActive())
1241 && (mouse.getAbsoluteY() == 0)
1242 ) {
1243
1244 for (TMenu menu: subMenus) {
1245 menu.setActive(false);
1246 }
1247 subMenus.clear();
1248
1249 // They selected the menu, go activate it
1250 for (TMenu menu: menus) {
1251 if ((mouse.getAbsoluteX() >= menu.getX())
1252 && (mouse.getAbsoluteX() < menu.getX()
1253 + menu.getTitle().length() + 2)
1254 ) {
1255 menu.setActive(true);
1256 activeMenu = menu;
1257 } else {
1258 menu.setActive(false);
1259 }
1260 }
fca67db0
KL
1261 return;
1262 }
1263
1264 // See if they hit the menu bar
1265 if ((mouse.getType() == TMouseEvent.Type.MOUSE_MOTION)
7c870d89 1266 && (mouse.isMouse1())
fca67db0
KL
1267 && (activeMenu != null)
1268 && (mouse.getAbsoluteY() == 0)
1269 ) {
1270
1271 TMenu oldMenu = activeMenu;
1272 for (TMenu menu: subMenus) {
1273 menu.setActive(false);
1274 }
1275 subMenus.clear();
1276
1277 // See if we should switch menus
1278 for (TMenu menu: menus) {
1279 if ((mouse.getAbsoluteX() >= menu.getX())
1280 && (mouse.getAbsoluteX() < menu.getX()
1281 + menu.getTitle().length() + 2)
1282 ) {
1283 menu.setActive(true);
1284 activeMenu = menu;
1285 }
1286 }
1287 if (oldMenu != activeMenu) {
1288 // They switched menus
1289 oldMenu.setActive(false);
1290 }
fca67db0
KL
1291 return;
1292 }
1293
1294 // Only switch if there are multiple windows
1295 if (windows.size() < 2) {
1296 return;
1297 }
1298
1299 // Switch on the upclick
1300 if (mouse.getType() != TMouseEvent.Type.MOUSE_UP) {
1301 return;
1302 }
1303
bb35d919
KL
1304 synchronized (windows) {
1305 Collections.sort(windows);
1306 if (windows.get(0).isModal()) {
1307 // Modal windows don't switch
1308 return;
1309 }
fca67db0 1310
bb35d919
KL
1311 for (TWindow window: windows) {
1312 assert (!window.isModal());
1313 if (window.mouseWouldHit(mouse)) {
1314 if (window == windows.get(0)) {
1315 // Clicked on the same window, nothing to do
1316 return;
1317 }
1318
1319 // We will be switching to another window
7c870d89
KL
1320 assert (windows.get(0).isActive());
1321 assert (!window.isActive());
bb35d919
KL
1322 windows.get(0).setActive(false);
1323 windows.get(0).setZ(window.getZ());
1324 window.setZ(0);
1325 window.setActive(true);
fca67db0
KL
1326 return;
1327 }
fca67db0
KL
1328 }
1329 }
1330
1331 // Clicked on the background, nothing to do
1332 return;
1333 }
1334
1335 /**
1336 * Turn off the menu.
1337 */
928811d8 1338 public final void closeMenu() {
fca67db0
KL
1339 if (activeMenu != null) {
1340 activeMenu.setActive(false);
1341 activeMenu = null;
1342 for (TMenu menu: subMenus) {
1343 menu.setActive(false);
1344 }
1345 subMenus.clear();
1346 }
fca67db0
KL
1347 }
1348
1349 /**
1350 * Turn off a sub-menu.
1351 */
928811d8 1352 public final void closeSubMenu() {
fca67db0
KL
1353 assert (activeMenu != null);
1354 TMenu item = subMenus.get(subMenus.size() - 1);
1355 assert (item != null);
1356 item.setActive(false);
1357 subMenus.remove(subMenus.size() - 1);
fca67db0
KL
1358 }
1359
1360 /**
1361 * Switch to the next menu.
1362 *
1363 * @param forward if true, then switch to the next menu in the list,
1364 * otherwise switch to the previous menu in the list
1365 */
928811d8 1366 public final void switchMenu(final boolean forward) {
fca67db0
KL
1367 assert (activeMenu != null);
1368
1369 for (TMenu menu: subMenus) {
1370 menu.setActive(false);
1371 }
1372 subMenus.clear();
1373
1374 for (int i = 0; i < menus.size(); i++) {
1375 if (activeMenu == menus.get(i)) {
1376 if (forward) {
1377 if (i < menus.size() - 1) {
1378 i++;
1379 }
1380 } else {
1381 if (i > 0) {
1382 i--;
1383 }
1384 }
1385 activeMenu.setActive(false);
1386 activeMenu = menus.get(i);
1387 activeMenu.setActive(true);
fca67db0
KL
1388 return;
1389 }
1390 }
1391 }
1392
1393 /**
1394 * Method that TApplication subclasses can override to handle menu or
1395 * posted command events.
1396 *
1397 * @param command command event
1398 * @return if true, this event was consumed
1399 */
1400 protected boolean onCommand(final TCommandEvent command) {
fca67db0
KL
1401 // Default: handle cmExit
1402 if (command.equals(cmExit)) {
1403 if (messageBox("Confirmation", "Exit application?",
c6940ed9 1404 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
fca67db0
KL
1405 quit = true;
1406 }
fca67db0
KL
1407 return true;
1408 }
1409
1410 if (command.equals(cmShell)) {
34a42e78 1411 openTerminal(0, 0, TWindow.RESIZABLE);
fca67db0
KL
1412 return true;
1413 }
1414
1415 if (command.equals(cmTile)) {
1416 tileWindows();
fca67db0
KL
1417 return true;
1418 }
1419 if (command.equals(cmCascade)) {
1420 cascadeWindows();
fca67db0
KL
1421 return true;
1422 }
1423 if (command.equals(cmCloseAll)) {
1424 closeAllWindows();
fca67db0
KL
1425 return true;
1426 }
c6940ed9 1427
fca67db0
KL
1428 return false;
1429 }
1430
1431 /**
1432 * Method that TApplication subclasses can override to handle menu
1433 * events.
1434 *
1435 * @param menu menu event
1436 * @return if true, this event was consumed
1437 */
1438 protected boolean onMenu(final TMenuEvent menu) {
1439
fca67db0 1440 // Default: handle MID_EXIT
8e688b92 1441 if (menu.getId() == TMenu.MID_EXIT) {
fca67db0 1442 if (messageBox("Confirmation", "Exit application?",
c6940ed9 1443 TMessageBox.Type.YESNO).getResult() == TMessageBox.Result.YES) {
fca67db0
KL
1444 quit = true;
1445 }
fca67db0
KL
1446 return true;
1447 }
1448
34a42e78
KL
1449 if (menu.getId() == TMenu.MID_SHELL) {
1450 openTerminal(0, 0, TWindow.RESIZABLE);
fca67db0
KL
1451 return true;
1452 }
1453
8e688b92 1454 if (menu.getId() == TMenu.MID_TILE) {
fca67db0 1455 tileWindows();
fca67db0
KL
1456 return true;
1457 }
8e688b92 1458 if (menu.getId() == TMenu.MID_CASCADE) {
fca67db0 1459 cascadeWindows();
fca67db0
KL
1460 return true;
1461 }
8e688b92 1462 if (menu.getId() == TMenu.MID_CLOSE_ALL) {
fca67db0 1463 closeAllWindows();
fca67db0
KL
1464 return true;
1465 }
fca67db0
KL
1466 return false;
1467 }
1468
1469 /**
1470 * Method that TApplication subclasses can override to handle keystrokes.
1471 *
1472 * @param keypress keystroke event
1473 * @return if true, this event was consumed
1474 */
1475 protected boolean onKeypress(final TKeypressEvent keypress) {
1476 // Default: only menu shortcuts
1477
1478 // Process Alt-F, Alt-E, etc. menu shortcut keys
7c870d89
KL
1479 if (!keypress.getKey().isFnKey()
1480 && keypress.getKey().isAlt()
1481 && !keypress.getKey().isCtrl()
fca67db0
KL
1482 && (activeMenu == null)
1483 ) {
1484
1485 assert (subMenus.size() == 0);
1486
1487 for (TMenu menu: menus) {
1488 if (Character.toLowerCase(menu.getMnemonic().getShortcut())
7c870d89 1489 == Character.toLowerCase(keypress.getKey().getChar())
fca67db0
KL
1490 ) {
1491 activeMenu = menu;
1492 menu.setActive(true);
fca67db0
KL
1493 return true;
1494 }
1495 }
1496 }
1497
1498 return false;
1499 }
48e27807 1500
928811d8
KL
1501 /**
1502 * Add a keyboard accelerator to the global hash.
1503 *
1504 * @param item menu item this accelerator relates to
1505 * @param keypress keypress that will dispatch a TMenuEvent
1506 */
1507 public final void addAccelerator(final TMenuItem item,
1508 final TKeypress keypress) {
e826b451 1509
e826b451
KL
1510 synchronized (accelerators) {
1511 assert (accelerators.get(keypress) == null);
1512 accelerators.put(keypress, item);
1513 }
928811d8
KL
1514 }
1515
1516 /**
1517 * Recompute menu x positions based on their title length.
1518 */
1519 public final void recomputeMenuX() {
1520 int x = 0;
1521 for (TMenu menu: menus) {
1522 menu.setX(x);
1523 x += menu.getTitle().length() + 2;
1524 }
1525 }
1526
1527 /**
1528 * Post an event to process and turn off the menu.
1529 *
1530 * @param event new event to add to the queue
1531 */
1532 public final void addMenuEvent(final TInputEvent event) {
8e688b92
KL
1533 synchronized (fillEventQueue) {
1534 fillEventQueue.add(event);
1535 }
928811d8
KL
1536 closeMenu();
1537 }
1538
1539 /**
1540 * Add a sub-menu to the list of open sub-menus.
1541 *
1542 * @param menu sub-menu
1543 */
1544 public final void addSubMenu(final TMenu menu) {
1545 subMenus.add(menu);
1546 }
1547
8e688b92
KL
1548 /**
1549 * Convenience function to add a top-level menu.
1550 *
1551 * @param title menu title
1552 * @return the new menu
1553 */
87a17f3c 1554 public final TMenu addMenu(final String title) {
8e688b92
KL
1555 int x = 0;
1556 int y = 0;
1557 TMenu menu = new TMenu(this, x, y, title);
1558 menus.add(menu);
1559 recomputeMenuX();
1560 return menu;
1561 }
1562
1563 /**
1564 * Convenience function to add a default "File" menu.
1565 *
1566 * @return the new menu
1567 */
1568 public final TMenu addFileMenu() {
1569 TMenu fileMenu = addMenu("&File");
1570 fileMenu.addDefaultItem(TMenu.MID_OPEN_FILE);
1571 fileMenu.addSeparator();
1572 fileMenu.addDefaultItem(TMenu.MID_SHELL);
1573 fileMenu.addDefaultItem(TMenu.MID_EXIT);
1574 return fileMenu;
1575 }
1576
1577 /**
1578 * Convenience function to add a default "Edit" menu.
1579 *
1580 * @return the new menu
1581 */
1582 public final TMenu addEditMenu() {
1583 TMenu editMenu = addMenu("&Edit");
1584 editMenu.addDefaultItem(TMenu.MID_CUT);
1585 editMenu.addDefaultItem(TMenu.MID_COPY);
1586 editMenu.addDefaultItem(TMenu.MID_PASTE);
1587 editMenu.addDefaultItem(TMenu.MID_CLEAR);
1588 return editMenu;
1589 }
1590
1591 /**
1592 * Convenience function to add a default "Window" menu.
1593 *
1594 * @return the new menu
1595 */
c6940ed9 1596 public final TMenu addWindowMenu() {
8e688b92
KL
1597 TMenu windowMenu = addMenu("&Window");
1598 windowMenu.addDefaultItem(TMenu.MID_TILE);
1599 windowMenu.addDefaultItem(TMenu.MID_CASCADE);
1600 windowMenu.addDefaultItem(TMenu.MID_CLOSE_ALL);
1601 windowMenu.addSeparator();
1602 windowMenu.addDefaultItem(TMenu.MID_WINDOW_MOVE);
1603 windowMenu.addDefaultItem(TMenu.MID_WINDOW_ZOOM);
1604 windowMenu.addDefaultItem(TMenu.MID_WINDOW_NEXT);
1605 windowMenu.addDefaultItem(TMenu.MID_WINDOW_PREVIOUS);
1606 windowMenu.addDefaultItem(TMenu.MID_WINDOW_CLOSE);
1607 return windowMenu;
1608 }
1609
1610 /**
1611 * Close all open windows.
1612 */
1613 private void closeAllWindows() {
1614 // Don't do anything if we are in the menu
1615 if (activeMenu != null) {
1616 return;
1617 }
bb35d919
KL
1618
1619 synchronized (windows) {
1620 for (TWindow window: windows) {
1621 closeWindow(window);
1622 }
8e688b92
KL
1623 }
1624 }
1625
1626 /**
1627 * Re-layout the open windows as non-overlapping tiles. This produces
1628 * almost the same results as Turbo Pascal 7.0's IDE.
1629 */
1630 private void tileWindows() {
bb35d919
KL
1631 synchronized (windows) {
1632 // Don't do anything if we are in the menu
1633 if (activeMenu != null) {
1634 return;
8e688b92 1635 }
bb35d919
KL
1636 int z = windows.size();
1637 if (z == 0) {
1638 return;
1639 }
1640 int a = 0;
1641 int b = 0;
1642 a = (int)(Math.sqrt(z));
1643 int c = 0;
1644 while (c < a) {
1645 b = (z - c) / a;
1646 if (((a * b) + c) == z) {
1647 break;
1648 }
1649 c++;
8e688b92 1650 }
bb35d919
KL
1651 assert (a > 0);
1652 assert (b > 0);
1653 assert (c < a);
1654 int newWidth = (getScreen().getWidth() / a);
1655 int newHeight1 = ((getScreen().getHeight() - 1) / b);
1656 int newHeight2 = ((getScreen().getHeight() - 1) / (b + c));
1657
1658 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1659 Collections.sort(sorted);
1660 Collections.reverse(sorted);
1661 for (int i = 0; i < sorted.size(); i++) {
1662 int logicalX = i / b;
1663 int logicalY = i % b;
1664 if (i >= ((a - 1) * b)) {
1665 logicalX = a - 1;
1666 logicalY = i - ((a - 1) * b);
1667 }
8e688b92 1668
bb35d919
KL
1669 TWindow w = sorted.get(i);
1670 w.setX(logicalX * newWidth);
1671 w.setWidth(newWidth);
1672 if (i >= ((a - 1) * b)) {
1673 w.setY((logicalY * newHeight2) + 1);
1674 w.setHeight(newHeight2);
1675 } else {
1676 w.setY((logicalY * newHeight1) + 1);
1677 w.setHeight(newHeight1);
1678 }
8e688b92
KL
1679 }
1680 }
1681 }
1682
1683 /**
1684 * Re-layout the open windows as overlapping cascaded windows.
1685 */
1686 private void cascadeWindows() {
bb35d919
KL
1687 synchronized (windows) {
1688 // Don't do anything if we are in the menu
1689 if (activeMenu != null) {
1690 return;
8e688b92 1691 }
bb35d919
KL
1692 int x = 0;
1693 int y = 1;
1694 List<TWindow> sorted = new LinkedList<TWindow>(windows);
1695 Collections.sort(sorted);
1696 Collections.reverse(sorted);
1697 for (TWindow window: sorted) {
1698 window.setX(x);
1699 window.setY(y);
1700 x++;
1701 y++;
1702 if (x > getScreen().getWidth()) {
1703 x = 0;
1704 }
1705 if (y >= getScreen().getHeight()) {
1706 y = 1;
1707 }
8e688b92
KL
1708 }
1709 }
1710 }
1711
d502a0e9
KL
1712 /**
1713 * Convenience function to add a timer.
1714 *
1715 * @param duration number of milliseconds to wait between ticks
1716 * @param recurring if true, re-schedule this timer after every tick
1717 * @param action function to call when button is pressed
c6940ed9 1718 * @return the timer
d502a0e9
KL
1719 */
1720 public final TTimer addTimer(final long duration, final boolean recurring,
1721 final TAction action) {
1722
1723 TTimer timer = new TTimer(duration, recurring, action);
1724 synchronized (timers) {
1725 timers.add(timer);
1726 }
1727 return timer;
1728 }
1729
1730 /**
1731 * Convenience function to remove a timer.
1732 *
1733 * @param timer timer to remove
1734 */
1735 public final void removeTimer(final TTimer timer) {
1736 synchronized (timers) {
1737 timers.remove(timer);
1738 }
1739 }
1740
c6940ed9
KL
1741 /**
1742 * Convenience function to spawn a message box.
1743 *
1744 * @param title window title, will be centered along the top border
1745 * @param caption message to display. Use embedded newlines to get a
1746 * multi-line box.
1747 * @return the new message box
1748 */
1749 public final TMessageBox messageBox(final String title,
1750 final String caption) {
1751
1752 return new TMessageBox(this, title, caption, TMessageBox.Type.OK);
1753 }
1754
1755 /**
1756 * Convenience function to spawn a message box.
1757 *
1758 * @param title window title, will be centered along the top border
1759 * @param caption message to display. Use embedded newlines to get a
1760 * multi-line box.
1761 * @param type one of the TMessageBox.Type constants. Default is
1762 * Type.OK.
1763 * @return the new message box
1764 */
1765 public final TMessageBox messageBox(final String title,
1766 final String caption, final TMessageBox.Type type) {
1767
1768 return new TMessageBox(this, title, caption, type);
1769 }
1770
1771 /**
1772 * Convenience function to spawn an input box.
1773 *
1774 * @param title window title, will be centered along the top border
1775 * @param caption message to display. Use embedded newlines to get a
1776 * multi-line box.
1777 * @return the new input box
1778 */
1779 public final TInputBox inputBox(final String title, final String caption) {
1780
1781 return new TInputBox(this, title, caption);
1782 }
1783
1784 /**
1785 * Convenience function to spawn an input box.
1786 *
1787 * @param title window title, will be centered along the top border
1788 * @param caption message to display. Use embedded newlines to get a
1789 * multi-line box.
1790 * @param text initial text to seed the field with
1791 * @return the new input box
1792 */
1793 public final TInputBox inputBox(final String title, final String caption,
1794 final String text) {
1795
1796 return new TInputBox(this, title, caption, text);
1797 }
1ac2ccb1 1798
34a42e78
KL
1799 /**
1800 * Convenience function to open a terminal window.
1801 *
1802 * @param x column relative to parent
1803 * @param y row relative to parent
1804 * @return the terminal new window
1805 */
1806 public final TTerminalWindow openTerminal(final int x, final int y) {
1807 return openTerminal(x, y, TWindow.RESIZABLE);
1808 }
1809
1810 /**
1811 * Convenience function to open a terminal window.
1812 *
1813 * @param x column relative to parent
1814 * @param y row relative to parent
1815 * @param flags mask of CENTERED, MODAL, or RESIZABLE
1816 * @return the terminal new window
1817 */
1818 public final TTerminalWindow openTerminal(final int x, final int y,
1819 final int flags) {
1820
1821 return new TTerminalWindow(this, x, y, flags);
1822 }
1823
0d47c546
KL
1824 /**
1825 * Convenience function to spawn an file open box.
1826 *
1827 * @param path path of selected file
1828 * @return the result of the new file open box
1829 */
1830 public final String fileOpenBox(final String path) throws IOException {
1831
1832 TFileOpenBox box = new TFileOpenBox(this, path, TFileOpenBox.Type.OPEN);
1833 return box.getFilename();
1834 }
1835
1836 /**
1837 * Convenience function to spawn an file open box.
1838 *
1839 * @param path path of selected file
1840 * @param type one of the Type constants
1841 * @return the result of the new file open box
1842 */
1843 public final String fileOpenBox(final String path,
1844 final TFileOpenBox.Type type) throws IOException {
1845
1846 TFileOpenBox box = new TFileOpenBox(this, path, type);
1847 return box.getFilename();
1848 }
1849
7d4115a5 1850}