From e44910212ca9dff4de00e485f22c393e9852f1d7 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Tue, 20 Feb 2018 16:47:06 +0530 Subject: [PATCH] Sample code to use TIOCGWINSZ in python --- graphics-protocol.asciidoc | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/graphics-protocol.asciidoc b/graphics-protocol.asciidoc index cc65b1de4..dc44f1122 100644 --- a/graphics-protocol.asciidoc +++ b/graphics-protocol.asciidoc @@ -35,14 +35,23 @@ toc::[] In order to know what size of images to display and how to position them, the client must be able to get the window size in pixels and the number of cells per row and column. This can be done by using the `TIOCGWINSZ` ioctl. -Some C code to demonstrate its use +Some code to demonstrate its use +In C: ```C struct ttysize ts; ioctl(0, TIOCGWINSZ, &ts); printf("number of columns: %i, number of rows: %i, screen width: %i, screen height: %i\n", sz.ws_col, sz.ws_row, sz.ws_xpixel, sz.ws_ypixel); ``` +In Python: +```py +import struct, fcntl, termios +s = struct.pack('HHHH', 0, 0, 0, 0) +x = struct.unpack('HHHH', fcntl.ioctl(1, termios.TIOCGWINSZ, s)) +print(f'number of columns: {x[0]}, number of rows: {x[1]}, screen width: {x[2]}, screen height: {x[3]}') +``` + Note that some terminals return `0` for the width and height values. Such terminals should be modified to return the correct values. Examples of terminals that return correct values: `kitty, xterm`