3

I am developing a Scala script which runs in a Bash script (on a Linux machine). In order to have a sophisticated user interface, I need to always now the exact terminal size.

So how can I get terminal window size (rows, columns) change events? Programs like mc (Midnight Commander) seem to react immediately on window size changes. I want this too :)

Update: With the help of larsks and Thomas Dickey I was able to find a solution, which looks like this:

import sun.misc.{Signal, SignalHandler}

Signal.handle(new Signal("WINCH"), TerminalSizeChangedHandler)

object TerminalSizeChangedHandler extends SignalHandler
{
   override def handle(sig: Signal)
   {
      println("terminal size changed");     
   }    
}

The dowside is, that it's relying on sun.misc classes. If someone shows me an equally simple solution without sun.misc, it would make be even more happy :)

Marcus
  • 1,857
  • 4
  • 22
  • 44
  • 1
    As scala is java, I'd point you towards http://stackoverflow.com/questions/1286461/can-i-find-the-console-width-with-java – childofsoong Jul 23 '15 at 17:38
  • After **export COLUMNS** in Bash I can do **sys.env("COLUMNS")** in Scala. But that value reflects only the situation when the VM was started. That does not help. So how do programs like mc (Midnight Commander) do it? – Marcus Jul 23 '15 at 17:55
  • Well, as I know absolutely nothing about 'Midnight Commander', do you happen to know if that program runs on Java? If so, see how they do it (if you can find their code). If it's in C/C++, you could perhaps use their technique with the JNI to use their own method. – childofsoong Jul 23 '15 at 17:57

2 Answers2

3

When running under X11, window size changes should result in a SIGWINCH signal being sent to your program. You would need to arrange to respond to this signal using whatever mechanism Scala provides for signal handling (possibly something like this, but I don't know any Scala).

larsks
  • 277,717
  • 41
  • 399
  • 399
2

SIGWINCH originated independently of X11:

  • SIGWINCH likely was first used in NeWS, a PostScript rendering system), and
  • NAWS (Telnet Window Size Option) is another place to start.

Still, X10R4 (December 1986) used SIGWINCH in xterm. Whatever its history, it is not solely an X11 feature.

In Java you could use POSIXSignalHandler to catch SIGWINCH. Scala is not identical to Java, but that provides a starting point. For instance, there are a few Github projects which may be useful reading:

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • Thank you! That was helpful. However, POSIXSignalHandler is not an option for me, as it's not part of standard JVM. The Interpol "signals.scala" looked promising, but for some unknown reason did not work out of the box for me. Rapture could be useful; however I would need to look into, as it would not work without its library ... – Marcus Jul 27 '15 at 09:21