about summary refs log tree commit diff stats
path: root/src/display/winattrs.nim
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2023-10-19 20:04:15 +0200
committerbptato <nincsnevem662@gmail.com>2023-10-19 20:05:21 +0200
commit3c3f0f1035d7b71d1993c38ca630095699972f61 (patch)
tree434fde30f4a19a1faaabebf1ba06dda731cde360 /src/display/winattrs.nim
parent46837a6b7186afd9fc2a45b6152672e553ac2c9e (diff)
downloadchawan-3c3f0f1035d7b71d1993c38ca630095699972f61.tar.gz
WindowAttributes: refactor
* rename module (window -> winattrs, to avoid conflict with env/window)
* do not use result
* remove unused cell_ratio
Diffstat (limited to 'src/display/winattrs.nim')
-rw-r--r--src/display/winattrs.nim62
1 files changed, 62 insertions, 0 deletions
diff --git a/src/display/winattrs.nim b/src/display/winattrs.nim
new file mode 100644
index 00000000..74a713bc
--- /dev/null
+++ b/src/display/winattrs.nim
@@ -0,0 +1,62 @@
+import terminal
+
+when defined(posix):
+  import termios
+
+type
+  WindowAttributes* = object
+    width*: int
+    height*: int
+    ppc*: int # cell width
+    ppl*: int # cell height
+    width_px*: int
+    height_px*: int
+
+proc getWindowAttributes*(tty: File): WindowAttributes =
+  when defined(posix):
+    if tty.isatty():
+      var win: IOctl_WinSize
+      if ioctl(cint(getOsFileHandle(tty)), TIOCGWINSZ, addr win) != -1:
+        var cols = int(win.ws_col)
+        var rows = int(win.ws_row)
+        if cols == 0:
+          cols = 80
+        if rows == 0:
+          rows = 24
+        var ppc = int(win.ws_xpixel) div cols
+        var ppl = int(win.ws_ypixel) div rows
+        # some terminal emulators (aka vte) don't set ws_xpixel or ws_ypixel.
+        # solution: use xterm.
+        if ppc == 0:
+          ppc = 9
+        if ppl == 0:
+          ppl = 18
+        # Filling the last row without raw mode breaks things. However,
+        # not supporting Windows means we can always have raw mode, so we can
+        # use all available columns.
+        return WindowAttributes(
+          width: cols,
+          height: rows,
+          ppc: ppc,
+          ppl: ppl,
+          width_px: cols * ppc,
+          height_px: rows * ppl
+        )
+  # For Windows, which is no longer supported. We keep it as a fallback for
+  # when ioctl fails.
+  var height = terminalHeight()
+  if height == 0:
+    height = 24
+  # Windows has no raw mode afaik, so we do not fill the last column to
+  # prevent line wrapping.
+  let width = terminalWidth() - 1
+  let ppc = 9
+  let ppl = 18
+  return WindowAttributes(
+    width: width,
+    height: height,
+    ppc: ppc,
+    ppl: ppl,
+    width_px: ppc * width,
+    height_px: ppl * width
+  )