Skip to content

Display and control your Android device

Add util function to get terminal size

Romain Vimont38332f683c67
diff --git a/app/meson.build b/app/meson.build
index 0e33c084..d13e421e 100644
--- a/app/meson.build
+++ b/app/meson.build
@@ -29,6 +29,7 @@ src = [
'src/util/process.c',
'src/util/strbuf.c',
'src/util/str_util.c',
+ 'src/util/term.c',
'src/util/thread.c',
'src/util/tick.c',
]
@@ -189,6 +190,7 @@ if get_option('buildtype') == 'debug'
'src/options.c',
'src/util/strbuf.c',
'src/util/str_util.c',
+ 'src/util/term.c',
]],
['test_clock', [
'tests/test_clock.c',
diff --git a/app/src/util/term.c b/app/src/util/term.c
new file mode 100644
index 00000000..ff6bc4b1
--- /dev/null
+++ b/app/src/util/term.c
@@ -0,0 +1,51 @@
+#include "term.h"
+
+#include <assert.h>
+
+#ifdef _WIN32
+# include <windows.h>
+#else
+# include <unistd.h>
+# include <sys/ioctl.h>
+#endif
+
+bool
+sc_term_get_size(unsigned *rows, unsigned *cols) {
+#ifdef _WIN32
+ CONSOLE_SCREEN_BUFFER_INFO csbi;
+
+ bool ok =
+ GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
+ if (!ok) {
+ return false;
+ }
+
+ if (rows) {
+ assert(csbi.srWindow.Bottom >= csbi.srWindow.Top);
+ *rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
+ }
+
+ if (cols) {
+ assert(csbi.srWindow.Right >= csbi.srWindow.Left);
+ *cols = csbi.srWindow.Right - csbi.srWindow.Left + 1;
+ }
+
+ return true;
+#else
+ struct winsize ws;
+ int r = ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
+ if (r == -1) {
+ return false;
+ }
+
+ if (rows) {
+ *rows = ws.ws_row;
+ }
+
+ if (cols) {
+ *cols = ws.ws_col;
+ }
+
+ return true;
+#endif
+}
diff --git a/app/src/util/term.h b/app/src/util/term.h
new file mode 100644
index 00000000..0211bcb4
--- /dev/null
+++ b/app/src/util/term.h
@@ -0,0 +1,21 @@
+#ifndef SC_TERM_H
+#define SC_TERM_H
+
+#include "common.h"
+
+#include <stdbool.h>
+
+/**
+ * Return the terminal dimensions
+ *
+ * Return false if the dimensions could not be retrieved.
+ *
+ * Otherwise, return true, and:
+ * - if `rows` is not NULL, then the number of rows is written to `*rows`.
+ * - if `columns` is not NULL, then the number of columns is written to
+ * `*columns`.
+ */
+bool
+sc_term_get_size(unsigned *rows, unsigned *cols);
+
+#endif