mabe02 / lanterna

Java library for creating text-based GUIs
GNU Lesser General Public License v3.0
2.23k stars 243 forks source link

GraphicalTerminalImplementation.readInput() should throw InterruptedException #555

Open EnderCrypt opened 2 years ago

EnderCrypt commented 2 years ago

https://github.com/mabe02/lanterna/blob/2fb305ccf3013532166d10003c51bc061889c2ca/src/main/java/com/googlecode/lanterna/terminal/swing/GraphicalTerminalImplementation.java#L651

this code should throw the InterruptedException immidletly rather than catching it it is also a bad practice to throw RuntimeException directly whitout subclassing it as it makes catching that exception significantly harder

the point with an InterruptedException is to cancel the flow of the thread, and essentially return below is an example of what you would be able to do with InterruptedException if it was thrown properly ofcourse in "real" code, its not gonna be as simple as a single try-catch and an inf loop, but keystroke reading may be done several classes away from this runnable class which is why being able to throw and catch this exception is so useful

EXAMPLE CODE:

public abstract class Example implements Runnable
{
    @Override
    public final void run()
    {
        try
        {
            while (true)
            {
                KeyStroke keyStroke = null;
                while ((keyStroke = getTerminalScreen().readInput()) != null)
                {
                    handleKeyInput(keyStroke);
                }
            }
        }
        catch (InterruptedException e)
        {
            return;
        }
    }

    private abstract TerminalScreen getTerminalScreen();

    private abstract void handleKeyInput(KeyStroke keyStroke);
}