+public class TApplication implements Runnable {
+
+ /**
+ * If true, emit thread stuff to System.err.
+ */
+ private static final boolean debugThreads = false;
+
+ /**
+ * If true, emit events being processed to System.err.
+ */
+ private static final boolean debugEvents = false;
+
+ /**
+ * Two backend types are available.
+ */
+ public static enum BackendType {
+ /**
+ * A Swing JFrame.
+ */
+ SWING,
+
+ /**
+ * An ECMA48 / ANSI X3.64 / XTERM style terminal.
+ */
+ ECMA48,
+
+ /**
+ * Synonym for ECMA48.
+ */
+ XTERM
+ }
+
+ /**
+ * WidgetEventHandler is the main event consumer loop. There are at most
+ * two such threads in existence: the primary for normal case and a
+ * secondary that is used for TMessageBox, TInputBox, and similar.
+ */
+ private class WidgetEventHandler implements Runnable {
+ /**
+ * The main application.
+ */
+ private TApplication application;
+
+ /**
+ * Whether or not this WidgetEventHandler is the primary or secondary
+ * thread.
+ */
+ private boolean primary = true;
+
+ /**
+ * Public constructor.
+ *
+ * @param application the main application
+ * @param primary if true, this is the primary event handler thread
+ */
+ public WidgetEventHandler(final TApplication application,
+ final boolean primary) {
+
+ this.application = application;
+ this.primary = primary;
+ }
+
+ /**
+ * The consumer loop.
+ */
+ public void run() {
+
+ // Loop forever
+ while (!application.quit) {
+
+ // Wait until application notifies me
+ while (!application.quit) {
+ try {
+ synchronized (application.drainEventQueue) {
+ if (application.drainEventQueue.size() > 0) {
+ break;
+ }
+ }
+
+ synchronized (this) {
+ if (debugThreads) {
+ System.err.printf("%s %s sleep\n", this,
+ primary ? "primary" : "secondary");
+ }
+
+ this.wait();
+
+ if (debugThreads) {
+ System.err.printf("%s %s AWAKE\n", this,
+ primary ? "primary" : "secondary");
+ }
+
+ if ((!primary)
+ && (application.secondaryEventReceiver == null)
+ ) {
+ // Secondary thread, emergency exit. If we
+ // got here then something went wrong with
+ // the handoff between yield() and
+ // closeWindow().
+ synchronized (application.primaryEventHandler) {
+ application.primaryEventHandler.notify();
+ }
+ application.secondaryEventHandler = null;
+ throw new RuntimeException(
+ "secondary exited at wrong time");
+ }
+ break;
+ }
+ } catch (InterruptedException e) {
+ // SQUASH
+ }
+ }
+
+ // Wait for drawAll() or doIdle() to be done, then handle the
+ // events.
+ boolean oldLock = lockHandleEvent();
+ assert (oldLock == false);
+
+ // Pull all events off the queue
+ for (;;) {
+ TInputEvent event = null;
+ synchronized (application.drainEventQueue) {
+ if (application.drainEventQueue.size() == 0) {
+ break;
+ }
+ event = application.drainEventQueue.remove(0);
+ }
+ application.repaint = true;
+ if (primary) {
+ primaryHandleEvent(event);
+ } else {
+ secondaryHandleEvent(event);
+ }
+ if ((!primary)
+ && (application.secondaryEventReceiver == null)
+ ) {
+ // Secondary thread, time to exit.
+
+ // DO NOT UNLOCK. Primary thread just came back from
+ // primaryHandleEvent() and will unlock in the else
+ // block below. Just wake it up.
+ synchronized (application.primaryEventHandler) {
+ application.primaryEventHandler.notify();
+ }
+ // Now eliminate my reference so that
+ // wakeEventHandler() resumes working on the primary.
+ application.secondaryEventHandler = null;
+
+ // All done!
+ return;
+ }
+ } // for (;;)
+
+ // Unlock. Either I am primary thread, or I am secondary
+ // thread and still running.
+ oldLock = unlockHandleEvent();
+ assert (oldLock == true);
+
+ // I have done some work of some kind. Tell the main run()
+ // loop to wake up now.
+ synchronized (application) {
+ application.notify();
+ }
+
+ } // while (true) (main runnable loop)
+ }
+ }
+
+ /**
+ * The primary event handler thread.
+ */
+ private volatile WidgetEventHandler primaryEventHandler;
+
+ /**
+ * The secondary event handler thread.
+ */
+ private volatile WidgetEventHandler secondaryEventHandler;
+
+ /**
+ * The widget receiving events from the secondary event handler thread.
+ */
+ private volatile TWidget secondaryEventReceiver;
+
+ /**
+ * Spinlock for the primary and secondary event handlers.
+ * WidgetEventHandler.run() is responsible for setting this value.
+ */
+ private volatile boolean insideHandleEvent = false;
+
+ /**
+ * Wake the sleeping active event handler.
+ */
+ private void wakeEventHandler() {
+ if (secondaryEventHandler != null) {
+ synchronized (secondaryEventHandler) {
+ secondaryEventHandler.notify();
+ }
+ } else {
+ assert (primaryEventHandler != null);
+ synchronized (primaryEventHandler) {
+ primaryEventHandler.notify();
+ }
+ }
+ }
+
+ /**
+ * Set the insideHandleEvent flag to true. lockoutEventHandlers() will
+ * spin indefinitely until unlockHandleEvent() is called.
+ *
+ * @return the old value of insideHandleEvent
+ */
+ private boolean lockHandleEvent() {
+ if (debugThreads) {
+ System.err.printf(" >> lockHandleEvent(): oldValue %s",
+ insideHandleEvent);
+ }
+ boolean oldValue = true;
+
+ synchronized (this) {
+ // Wait for TApplication.run() to finish using the global state
+ // before allowing further event processing.
+ while (lockoutHandleEvent == true) {
+ try {
+ // Backoff so that the backend can finish its work.
+ Thread.sleep(5);
+ } catch (InterruptedException e) {
+ // SQUASH
+ }
+ }
+
+ oldValue = insideHandleEvent;
+ insideHandleEvent = true;
+ }
+
+ if (debugThreads) {
+ System.err.printf(" ***\n");
+ }
+ return oldValue;
+ }
+
+ /**
+ * Set the insideHandleEvent flag to false. lockoutEventHandlers() will
+ * spin indefinitely until unlockHandleEvent() is called.
+ *
+ * @return the old value of insideHandleEvent
+ */
+ private boolean unlockHandleEvent() {
+ if (debugThreads) {
+ System.err.printf(" << unlockHandleEvent(): oldValue %s\n",
+ insideHandleEvent);
+ }
+ synchronized (this) {
+ boolean oldValue = insideHandleEvent;
+ insideHandleEvent = false;
+ return oldValue;
+ }
+ }
+
+ /**
+ * Spinlock for the primary and secondary event handlers. When true, the
+ * event handlers will spinlock wait before calling handleEvent().
+ */
+ private volatile boolean lockoutHandleEvent = false;
+
+ /**
+ * TApplication.run() needs to be able rely on the global data structures
+ * being intact when calling doIdle() and drawAll(). Tell the event
+ * handlers to wait for an unlock before handling their events.
+ */
+ private void stopEventHandlers() {
+ if (debugThreads) {
+ System.err.printf(">> stopEventHandlers()");
+ }
+
+ lockoutHandleEvent = true;
+ // Wait for the last event to finish processing before returning
+ // control to TApplication.run().
+ while (insideHandleEvent == true) {
+ try {
+ // Backoff so that the event handler can finish its work.
+ Thread.sleep(1);
+ } catch (InterruptedException e) {
+ // SQUASH
+ }
+ }
+
+ if (debugThreads) {
+ System.err.printf(" XXX\n");
+ }
+ }
+
+ /**
+ * TApplication.run() needs to be able rely on the global data structures
+ * being intact when calling doIdle() and drawAll(). Tell the event
+ * handlers that it is now OK to handle their events.
+ */
+ private void startEventHandlers() {
+ if (debugThreads) {
+ System.err.printf("<< startEventHandlers()\n");
+ }
+ lockoutHandleEvent = false;
+ }
+
+ /**
+ * Access to the physical screen, keyboard, and mouse.
+ */
+ private Backend backend;
+
+ /**
+ * Get the Screen.
+ *
+ * @return the Screen
+ */
+ public final Screen getScreen() {
+ return backend.getScreen();
+ }
+
+ /**
+ * Actual mouse coordinate X.
+ */
+ private int mouseX;
+
+ /**
+ * Actual mouse coordinate Y.
+ */
+ private int mouseY;
+
+ /**
+ * Old version of mouse coordinate X.
+ */
+ private int oldMouseX;
+
+ /**
+ * Old version mouse coordinate Y.
+ */
+ private int oldMouseY;
+
+ /**
+ * Event queue that is filled by run().
+ */
+ private List<TInputEvent> fillEventQueue;
+
+ /**
+ * Event queue that will be drained by either primary or secondary
+ * Thread.
+ */
+ private List<TInputEvent> drainEventQueue;
+
+ /**
+ * Top-level menus in this application.
+ */
+ private List<TMenu> menus;
+
+ /**
+ * Stack of activated sub-menus in this application.
+ */
+ private List<TMenu> subMenus;
+
+ /**
+ * The currently acive menu.
+ */
+ private TMenu activeMenu = null;
+
+ /**
+ * Active keyboard accelerators.
+ */
+ private Map<TKeypress, TMenuItem> accelerators;
+
+ /**
+ * All menu items.
+ */
+ private List<TMenuItem> menuItems;
+
+ /**
+ * Windows and widgets pull colors from this ColorTheme.
+ */
+ private ColorTheme theme;
+
+ /**
+ * Get the color theme.
+ *
+ * @return the theme
+ */
+ public final ColorTheme getTheme() {
+ return theme;
+ }
+
+ /**
+ * The top-level windows (but not menus).
+ */
+ private List<TWindow> windows;
+
+ /**
+ * Timers that are being ticked.
+ */
+ private List<TTimer> timers;
+
+ /**
+ * When true, exit the application.
+ */
+ private volatile boolean quit = false;
+
+ /**
+ * When true, repaint the entire screen.
+ */
+ private volatile boolean repaint = true;
+
+ /**
+ * Y coordinate of the top edge of the desktop. For now this is a
+ * constant. Someday it would be nice to have a multi-line menu or
+ * toolbars.
+ */
+ private static final int desktopTop = 1;
+
+ /**
+ * Get Y coordinate of the top edge of the desktop.
+ *
+ * @return Y coordinate of the top edge of the desktop
+ */
+ public final int getDesktopTop() {
+ return desktopTop;
+ }
+
+ /**
+ * Y coordinate of the bottom edge of the desktop.
+ */
+ private int desktopBottom;
+
+ /**
+ * Get Y coordinate of the bottom edge of the desktop.
+ *
+ * @return Y coordinate of the bottom edge of the desktop
+ */
+ public final int getDesktopBottom() {
+ return desktopBottom;
+ }
+
+ /**
+ * Public constructor.
+ *
+ * @param backendType BackendType.XTERM, BackendType.ECMA48 or
+ * BackendType.SWING
+ * @throws UnsupportedEncodingException if an exception is thrown when
+ * creating the InputStreamReader
+ */
+ public TApplication(final BackendType backendType)
+ throws UnsupportedEncodingException {
+
+ switch (backendType) {
+ case SWING:
+ backend = new SwingBackend(this);
+ break;
+ case XTERM:
+ // Fall through...
+ case ECMA48:
+ backend = new ECMA48Backend(this, null, null);
+ break;
+ default:
+ throw new IllegalArgumentException("Invalid backend type: "
+ + backendType);
+ }
+ TApplicationImpl();
+ }
+
+ /**
+ * Public constructor. The backend type will be BackendType.ECMA48.
+ *
+ * @param input an InputStream connected to the remote user, or null for
+ * System.in. If System.in is used, then on non-Windows systems it will
+ * be put in raw mode; shutdown() will (blindly!) put System.in in cooked
+ * mode. input is always converted to a Reader with UTF-8 encoding.
+ * @param output an OutputStream connected to the remote user, or null
+ * for System.out. output is always converted to a Writer with UTF-8
+ * encoding.
+ * @throws UnsupportedEncodingException if an exception is thrown when
+ * creating the InputStreamReader
+ */
+ public TApplication(final InputStream input,
+ final OutputStream output) throws UnsupportedEncodingException {
+
+ backend = new ECMA48Backend(this, input, output);
+ TApplicationImpl();
+ }
+
+ /**
+ * Public constructor. This hook enables use with new non-Jexer
+ * backends.
+ *
+ * @param backend a Backend that is already ready to go.
+ */
+ public TApplication(final Backend backend) {
+ this.backend = backend;
+ TApplicationImpl();
+ }
+
+ /**
+ * Finish construction once the backend is set.
+ */
+ private void TApplicationImpl() {
+ theme = new ColorTheme();
+ desktopBottom = getScreen().getHeight() - 1;
+ fillEventQueue = new ArrayList<TInputEvent>();
+ drainEventQueue = new ArrayList<TInputEvent>();
+ windows = new LinkedList<TWindow>();
+ menus = new LinkedList<TMenu>();
+ subMenus = new LinkedList<TMenu>();
+ timers = new LinkedList<TTimer>();
+ accelerators = new HashMap<TKeypress, TMenuItem>();
+ menuItems = new ArrayList<TMenuItem>();
+
+ // Setup the main consumer thread
+ primaryEventHandler = new WidgetEventHandler(this, true);
+ (new Thread(primaryEventHandler)).start();
+ }
+
+ /**
+ * Invert the cell color at a position. This is used to track the mouse.
+ *
+ * @param x column position
+ * @param y row position
+ */
+ private void invertCell(final int x, final int y) {
+ synchronized (getScreen()) {
+ CellAttributes attr = getScreen().getAttrXY(x, y);
+ attr.setForeColor(attr.getForeColor().invert());
+ attr.setBackColor(attr.getBackColor().invert());
+ getScreen().putAttrXY(x, y, attr, false);
+ }
+ }
+
+ /**
+ * Draw everything.
+ */
+ private void drawAll() {
+ if (debugThreads) {
+ System.err.printf("drawAll() enter\n");
+ }
+
+ if (!repaint) {
+ if ((oldMouseX != mouseX) || (oldMouseY != mouseY)) {
+ // The only thing that has happened is the mouse moved.
+ // Clear the old position and draw the new position.
+ invertCell(oldMouseX, oldMouseY);
+ invertCell(mouseX, mouseY);
+ oldMouseX = mouseX;
+ oldMouseY = mouseY;
+ }
+ if (getScreen().isDirty()) {
+ backend.flushScreen();
+ }
+ return;
+ }
+
+ if (debugThreads) {
+ System.err.printf("drawAll() REDRAW\n");
+ }
+
+ // If true, the cursor is not visible
+ boolean cursor = false;
+
+ // Start with a clean screen
+ getScreen().clear();
+
+ // Draw the background
+ CellAttributes background = theme.getColor("tapplication.background");
+ getScreen().putAll(GraphicsChars.HATCH, background);
+
+ // Draw each window in reverse Z order
+ List<TWindow> sorted = new LinkedList<TWindow>(windows);
+ Collections.sort(sorted);
+ Collections.reverse(sorted);
+ for (TWindow window: sorted) {
+ window.drawChildren();
+ }
+
+ // Draw the blank menubar line - reset the screen clipping first so
+ // it won't trim it out.
+ getScreen().resetClipping();
+ getScreen().hLineXY(0, 0, getScreen().getWidth(), ' ',
+ theme.getColor("tmenu"));
+ // Now draw the menus.
+ int x = 1;
+ for (TMenu menu: menus) {
+ CellAttributes menuColor;
+ CellAttributes menuMnemonicColor;
+ if (menu.isActive()) {
+ menuColor = theme.getColor("tmenu.highlighted");
+ menuMnemonicColor = theme.getColor("tmenu.mnemonic.highlighted");
+ } else {
+ menuColor = theme.getColor("tmenu");
+ menuMnemonicColor = theme.getColor("tmenu.mnemonic");
+ }
+ // Draw the menu title
+ getScreen().hLineXY(x, 0, menu.getTitle().length() + 2, ' ',
+ menuColor);
+ getScreen().putStringXY(x + 1, 0, menu.getTitle(), menuColor);
+ // Draw the highlight character
+ getScreen().putCharXY(x + 1 + menu.getMnemonic().getShortcutIdx(),
+ 0, menu.getMnemonic().getShortcut(), menuMnemonicColor);
+
+ if (menu.isActive()) {
+ menu.drawChildren();
+ // Reset the screen clipping so we can draw the next title.
+ getScreen().resetClipping();
+ }
+ x += menu.getTitle().length() + 2;
+ }
+
+ for (TMenu menu: subMenus) {
+ // Reset the screen clipping so we can draw the next sub-menu.
+ getScreen().resetClipping();
+ menu.drawChildren();
+ }
+
+ // Draw the mouse pointer
+ invertCell(mouseX, mouseY);
+
+ // Place the cursor if it is visible
+ TWidget activeWidget = null;
+ if (sorted.size() > 0) {
+ activeWidget = sorted.get(sorted.size() - 1).getActiveChild();
+ if (activeWidget.isCursorVisible()) {
+ getScreen().putCursor(true, activeWidget.getCursorAbsoluteX(),
+ activeWidget.getCursorAbsoluteY());
+ cursor = true;
+ }
+ }
+
+ // Kill the cursor
+ if (!cursor) {
+ getScreen().hideCursor();
+ }
+
+ // Flush the screen contents
+ backend.flushScreen();
+
+ repaint = false;
+ }
+
+ /**
+ * Run this application until it exits.
+ */
+ public void run() {
+ while (!quit) {
+ // Timeout is in milliseconds, so default timeout after 1 second
+ // of inactivity.
+ long timeout = 0;
+
+ // If I've got no updates to render, wait for something from the
+ // backend or a timer.
+ if (!repaint
+ && ((mouseX == oldMouseX) && (mouseY == oldMouseY))
+ ) {
+ // Never sleep longer than 50 millis. We need time for
+ // windows with background tasks to update the display, and
+ // still flip buffers reasonably quickly in
+ // backend.flushPhysical().
+ timeout = getSleepTime(50);
+ }
+
+ if (timeout > 0) {
+ // As of now, I've got nothing to do: no I/O, nothing from
+ // the consumer threads, no timers that need to run ASAP. So
+ // wait until either the backend or the consumer threads have
+ // something to do.
+ try {
+ synchronized (this) {
+ this.wait(timeout);
+ }
+ } catch (InterruptedException e) {
+ // I'm awake and don't care why, let's see what's going
+ // on out there.
+ }
+ repaint = true;
+ }
+
+ // Prevent stepping on the primary or secondary event handler.
+ stopEventHandlers();
+
+ // Pull any pending I/O events
+ backend.getEvents(fillEventQueue);
+
+ // Dispatch each event to the appropriate handler, one at a time.
+ for (;;) {
+ TInputEvent event = null;
+ if (fillEventQueue.size() == 0) {
+ break;
+ }
+ event = fillEventQueue.remove(0);
+ metaHandleEvent(event);
+ }
+
+ // Wake a consumer thread if we have any pending events.
+ if (drainEventQueue.size() > 0) {
+ wakeEventHandler();
+ }
+
+ // Process timers and call doIdle()'s
+ doIdle();
+
+ // Update the screen
+ synchronized (getScreen()) {
+ drawAll();
+ }
+
+ // Let the event handlers run again.
+ startEventHandlers();
+
+ } // while (!quit)
+
+ // Shutdown the event consumer threads
+ if (secondaryEventHandler != null) {
+ synchronized (secondaryEventHandler) {
+ secondaryEventHandler.notify();
+ }
+ }
+ if (primaryEventHandler != null) {
+ synchronized (primaryEventHandler) {
+ primaryEventHandler.notify();
+ }
+ }
+
+ // Shutdown the user I/O thread(s)
+ backend.shutdown();
+
+ // Close all the windows. This gives them an opportunity to release
+ // resources.
+ closeAllWindows();
+
+ }
+
+ /**
+ * Peek at certain application-level events, add to eventQueue, and wake
+ * up the consuming Thread.
+ *
+ * @param event the input event to consume
+ */
+ private void metaHandleEvent(final TInputEvent event) {
+
+ if (debugEvents) {
+ System.err.printf(String.format("metaHandleEvents event: %s\n",
+ event)); System.err.flush();
+ }
+
+ if (quit) {
+ // Do no more processing if the application is already trying
+ // to exit.
+ return;
+ }
+
+ // Special application-wide events -------------------------------
+
+ // Abort everything
+ if (event instanceof TCommandEvent) {
+ TCommandEvent command = (TCommandEvent) event;
+ if (command.getCmd().equals(cmAbort)) {
+ quit = true;
+ return;
+ }
+ }
+
+ // Screen resize
+ if (event instanceof TResizeEvent) {
+ TResizeEvent resize = (TResizeEvent) event;
+ synchronized (getScreen()) {
+ getScreen().setDimensions(resize.getWidth(),
+ resize.getHeight());
+ desktopBottom = getScreen().getHeight() - 1;
+ mouseX = 0;
+ mouseY = 0;
+ oldMouseX = 0;
+ oldMouseY = 0;
+ }
+ return;
+ }
+
+ // Peek at the mouse position
+ if (event instanceof TMouseEvent) {
+ TMouseEvent mouse = (TMouseEvent) event;
+ synchronized (getScreen()) {
+ if ((mouseX != mouse.getX()) || (mouseY != mouse.getY())) {
+ oldMouseX = mouseX;
+ oldMouseY = mouseY;
+ mouseX = mouse.getX();
+ mouseY = mouse.getY();
+ }
+ }
+ }
+
+ // Put into the main queue
+ drainEventQueue.add(event);
+ }