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;

/**
 * Switch terminal mode and make it return on close. Basic usage is:
 *
 * <code>
 * try (TerminalModeSwitcher ignore = new TerminalModeSwitcher(TerminalMode.RAW)) {
 *     // do stuff in raw mode.
 * }
 * </code>
 */
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, "model == null");
        this.before = terminal.getAndUpdateMode(mode);
    }

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

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

    /**
     * Get the mode that was replaced by the switcher.
     *
     * @return the 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 "TerminalModeSwitcher{before=" + before + ", mode=" + mode + '}';
    }

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