TTYModeSwitcher.java

/*
 * Copyright (c) 2016, Stein Eldar Johnsen
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.io.tty;

import java.io.Closeable;
import java.io.IOException;

import static java.util.Objects.requireNonNull;

/**
 * Switches the terminal to a given {@link TTYMode} and restores the previous
 * mode on close. Designed for use in try-with-resources blocks:
 *
 * <pre>{@code
 * try (TTYModeSwitcher ignored = new TTYModeSwitcher(tty, TTYMode.RAW)) {
 *     // do stuff in raw mode.
 * }
 * // previous mode is restored.
 * }</pre>
 */
public class TTYModeSwitcher implements Closeable {
    /**
     * Switch to the requested mode until closed.
     *
     * @param terminal Terminal to use to set mode.
     * @param mode The mode to switch to.
     * @throws IOException If unable to switch.

     */
    public TTYModeSwitcher(TTY terminal, TTYMode mode) throws IOException {
        this.terminal = requireNonNull(terminal, "terminal == null");
        this.mode = requireNonNull(mode, "mode == null");
        this.before = terminal.getAndUpdateMode(mode);
    }

    /**
     * Close the terminal mode switcher and restore the mode that was active
     * before it was opened.
     *
     * @throws IOException If unable to switch back.
     */
    @Override
    public void close() throws IOException {
        if (before != null) {
            terminal.getAndUpdateMode(before);
        }
    }

    /**
     * Get the mode set by the switcher.
     *
     * @return The TTY mode.
     */
    public TTYMode getMode() {
        return mode;
    }

    /**
     * Get the mode that was active before the switcher changed it.
     *
     * @return The previous TTY mode.
     */
    public TTYMode getBefore() {
        return before;
    }

    /**
     * @return True if the mode switcher changed the TTY mode.
     */
    public boolean didChangeMode() {
        return mode != before;
    }

    @Override
    public String toString() {
        return "TTYModeSwitcher{before=" + before + ", mode=" + mode + '}';
    }

    private final TTY     terminal;
    private final TTYMode before;
    private final TTYMode mode;
}