scroll.c 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. * Based on an example code from Roberto E. Vargas Caballero.
  3. *
  4. * Copyright (c) 2020 Jan Klemkow <j.klemkow@wemelug.de>
  5. * Copyright (c) 2020 Jochen Sprickerhof <git@jochen.sprickerhof.de>
  6. *
  7. * Permission to use, copy, modify, and distribute this software for any
  8. * purpose with or without fee is hereby granted, provided that the above
  9. * copyright notice and this permission notice appear in all copies.
  10. *
  11. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  12. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  13. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  14. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  15. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  16. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  17. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  18. */
  19. #include <sys/types.h>
  20. #include <sys/ioctl.h>
  21. #include <sys/wait.h>
  22. #include <sys/queue.h>
  23. #include <assert.h>
  24. #include <errno.h>
  25. #include <fcntl.h>
  26. #include <poll.h>
  27. #include <signal.h>
  28. #include <stdarg.h>
  29. #include <stdbool.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <termios.h>
  34. #include <unistd.h>
  35. #if defined(__linux)
  36. #include <pty.h>
  37. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  38. #include <util.h>
  39. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  40. #include <libutil.h>
  41. #endif
  42. #include "config.h"
  43. TAILQ_HEAD(tailhead, line) head;
  44. struct line {
  45. TAILQ_ENTRY(line) entries;
  46. size_t size;
  47. size_t len;
  48. char *buf;
  49. } *bottom;
  50. pid_t child;
  51. int mfd;
  52. struct termios dfl;
  53. struct winsize ws;
  54. static bool altscreen = false; /* is alternative screen active */
  55. void
  56. die(const char *fmt, ...)
  57. {
  58. va_list ap;
  59. va_start(ap, fmt);
  60. vfprintf(stderr, fmt, ap);
  61. va_end(ap);
  62. if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
  63. fputc(' ', stderr);
  64. perror(NULL);
  65. } else {
  66. fputc('\n', stderr);
  67. }
  68. exit(EXIT_FAILURE);
  69. }
  70. void
  71. sigchld(int sig)
  72. {
  73. pid_t pid;
  74. int status;
  75. assert(sig == SIGCHLD);
  76. while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
  77. if (pid == child)
  78. exit(WEXITSTATUS(status));
  79. }
  80. void
  81. sigwinch(int sig)
  82. {
  83. assert(sig == SIGWINCH);
  84. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
  85. die("ioctl:");
  86. if (ioctl(mfd, TIOCSWINSZ, &ws) == -1)
  87. die("ioctl:");
  88. kill(-child, SIGWINCH);
  89. }
  90. void
  91. reset(void)
  92. {
  93. if (tcsetattr(STDIN_FILENO, TCSANOW, &dfl) == -1)
  94. die("tcsetattr:");
  95. }
  96. /* error avoiding malloc */
  97. void *
  98. eamalloc(size_t size)
  99. {
  100. void *mem;
  101. while ((mem = malloc(size)) == NULL) {
  102. struct line *line = TAILQ_LAST(&head, tailhead);
  103. if (line == NULL)
  104. die("malloc:");
  105. TAILQ_REMOVE(&head, line, entries);
  106. free(line->buf);
  107. free(line);
  108. }
  109. return mem;
  110. }
  111. /* error avoiding remalloc */
  112. void *
  113. earealloc(void *ptr, size_t size)
  114. {
  115. void *mem;
  116. while ((mem = realloc(ptr, size)) == NULL) {
  117. struct line *line = TAILQ_LAST(&head, tailhead);
  118. if (line == NULL)
  119. die("realloc:");
  120. TAILQ_REMOVE(&head, line, entries);
  121. free(line->buf);
  122. free(line);
  123. }
  124. return mem;
  125. }
  126. /* Count string length w/o ansi esc sequences. */
  127. size_t
  128. strelen(const char *buf, size_t size)
  129. {
  130. enum {CHAR, BREK, ESC} state = CHAR;
  131. size_t len = 0;
  132. for (size_t i = 0; i < size; i++) {
  133. char c = buf[i];
  134. switch (state) {
  135. case CHAR:
  136. if (c == '\033')
  137. state = BREK;
  138. else
  139. len++;
  140. break;
  141. case BREK:
  142. if (c == '[') {
  143. state = ESC;
  144. } else {
  145. state = CHAR;
  146. len++;
  147. }
  148. break;
  149. case ESC:
  150. if (c >= 64 && c <= 126)
  151. state = CHAR;
  152. break;
  153. }
  154. }
  155. return len;
  156. }
  157. /* detect alternative screen switching */
  158. bool
  159. isaltscreen(char c)
  160. {
  161. static enum {CHAR, BREK, ESC} state = CHAR;
  162. static char buf[BUFSIZ];
  163. static size_t i = 0;
  164. switch (state) {
  165. case CHAR:
  166. if (c == '\033')
  167. state = BREK;
  168. break;
  169. case BREK:
  170. if (c == '[')
  171. state = ESC;
  172. else
  173. state = CHAR;
  174. break;
  175. case ESC:
  176. buf[i++] = c;
  177. if (i == sizeof buf) {
  178. /* TODO: find a better way to handle this situation */
  179. state = CHAR;
  180. i = 0;
  181. } else if (c >= 64 && c <= 126) {
  182. state = CHAR;
  183. buf[i] = '\0';
  184. i = 0;
  185. /* esc seq. enable alternative screen */
  186. if (strcmp(buf, "?1049h") == 0 ||
  187. strcmp(buf, "?1047h") == 0 ||
  188. strcmp(buf, "?47h" ) == 0)
  189. altscreen = true;
  190. /* esc seq. disable alternative screen */
  191. if (strcmp(buf, "?1049l") == 0 ||
  192. strcmp(buf, "?1047l") == 0 ||
  193. strcmp(buf, "?47l" ) == 0)
  194. altscreen = false;
  195. }
  196. break;
  197. }
  198. return altscreen;
  199. }
  200. void
  201. addline(char *buf, size_t size)
  202. {
  203. struct line *line = eamalloc(sizeof *line);
  204. line->size = size;
  205. line->len = strelen(buf, size);
  206. line->buf = eamalloc(size);
  207. memcpy(line->buf, buf, size);
  208. bottom = line;
  209. TAILQ_INSERT_HEAD(&head, line, entries);
  210. }
  211. void
  212. scrollup(void)
  213. {
  214. int rows = - ws.ws_row + 1;
  215. struct line *bottom_old = bottom;
  216. /* account for last line */
  217. if (bottom != NULL && TAILQ_PREV(bottom, tailhead, entries) == NULL)
  218. rows++;
  219. /* wind back bottom pointer by two pages */
  220. for (; bottom != NULL && TAILQ_NEXT(bottom, entries) != NULL &&
  221. rows <= ws.ws_row; rows++)
  222. bottom = TAILQ_NEXT(bottom, entries);
  223. if (rows <= 0) {
  224. bottom = bottom_old;
  225. return;
  226. }
  227. /* move the text in terminal n lines down */
  228. dprintf(STDOUT_FILENO, "\033[%dT", rows);
  229. /* set cursor position to upper left corner */
  230. write(STDOUT_FILENO, "\033[0;0H", 6);
  231. /* hide cursor */
  232. write(STDOUT_FILENO, "\033[?25l", 6);
  233. /* print one page */
  234. for (; rows > 0; rows--) {
  235. write(STDOUT_FILENO, bottom->buf, bottom->size);
  236. bottom = TAILQ_PREV(bottom, tailhead, entries);
  237. }
  238. bottom = TAILQ_NEXT(bottom, entries);
  239. }
  240. void
  241. scrolldown(char *buf, size_t size)
  242. {
  243. int rows = ws.ws_row;
  244. /* print one page */
  245. for (; rows > 0 && bottom != NULL &&
  246. TAILQ_PREV(bottom, tailhead, entries) != NULL; rows--) {
  247. bottom = TAILQ_PREV(bottom, tailhead, entries);
  248. write(STDOUT_FILENO, bottom->buf, bottom->size);
  249. }
  250. if (rows < ws.ws_row && bottom == TAILQ_FIRST(&head)) {
  251. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  252. write(STDOUT_FILENO, buf, size);
  253. }
  254. }
  255. void
  256. jumpdown(char *buf, size_t size)
  257. {
  258. int rows = ws.ws_row;
  259. bottom = TAILQ_FIRST(&head);
  260. for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
  261. bottom = TAILQ_NEXT(bottom, entries);
  262. scrolldown(buf, size);
  263. }
  264. int
  265. main(int argc, char *argv[])
  266. {
  267. TAILQ_INIT(&head);
  268. if (isatty(STDIN_FILENO) == 0)
  269. die("stdin it not a tty");
  270. if (isatty(STDOUT_FILENO) == 0)
  271. die("stdout it not a tty");
  272. if (argc <= 1)
  273. die("usage: scroll <program>");
  274. /* save terminal settings for resetting after exit */
  275. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  276. die("tcgetattr:");
  277. if (atexit(reset))
  278. die("atexit:");
  279. /* get window size of the terminal */
  280. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0)
  281. die("ioctl:");
  282. child = forkpty(&mfd, NULL, &dfl, &ws);
  283. if (child == -1)
  284. die("forkpty:");
  285. if (child == 0) { /* child */
  286. execvp(argv[1], argv + 1);
  287. perror("execvp");
  288. _exit(127);
  289. }
  290. #ifdef __OpenBSD__
  291. if (pledge("stdio tty proc", NULL) == -1)
  292. die("pledge:");
  293. #endif
  294. if (signal(SIGCHLD, sigchld) == SIG_ERR)
  295. die("signal:");
  296. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  297. die("signal:");
  298. int f;
  299. if ((f = fcntl(mfd, F_GETFL)) == -1)
  300. die("fcntl:");
  301. if (fcntl(mfd, F_SETFL, f /*| O_NONBLOCK*/) == -1)
  302. die("fcntl:");
  303. struct termios new = dfl;
  304. cfmakeraw(&new);
  305. new.c_cc[VMIN ] = 1;
  306. new.c_cc[VTIME] = 0;
  307. if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
  308. die("tcsetattr:");
  309. size_t size = BUFSIZ, pos = 0;
  310. char *buf = calloc(size, sizeof *buf);
  311. if (buf == NULL)
  312. die("calloc:");
  313. struct pollfd pfd[2] = {
  314. {STDIN_FILENO, POLLIN, 0},
  315. {mfd, POLLIN, 0}
  316. };
  317. for (;;) {
  318. char input[BUFSIZ];
  319. if (poll(pfd, 2, -1) == -1 && errno != EINTR)
  320. die("poll:");
  321. if (pfd[0].revents & POLLIN) {
  322. ssize_t n = read(STDIN_FILENO, input, sizeof input);
  323. if (n <= 0 && errno != EINTR)
  324. die("read:");
  325. if (!altscreen &&
  326. (strncmp(KB_SCROLL_UP, input, n) == 0 ||
  327. strncmp(MS_SCROLL_UP, input, n) == 0))
  328. scrollup();
  329. else if (!altscreen &&
  330. (strncmp(KB_SCROLL_DOWN, input, n) == 0 ||
  331. strncmp(MS_SCROLL_DOWN, input, n) == 0))
  332. scrolldown(buf, pos);
  333. else if (write(mfd, input, n) == -1)
  334. die("write:");
  335. else if (bottom != TAILQ_FIRST(&head))
  336. jumpdown(buf, pos);
  337. }
  338. if (pfd[1].revents & POLLIN) {
  339. ssize_t n = read(mfd, input, sizeof input);
  340. if (n == -1 && errno != EINTR)
  341. die("read:");
  342. /* iterate over the input buffer */
  343. for (char *c = input; n-- > 0; c++) {
  344. /* don't save lines from alternative screen */
  345. if (!isaltscreen(*c)) {
  346. if (*c == '\r') {
  347. addline(buf, pos);
  348. memset(buf, 0, size);
  349. pos = 0;
  350. }
  351. buf[pos++] = *c;
  352. if (pos == size) {
  353. size *= 2;
  354. buf = earealloc(buf, size);
  355. }
  356. }
  357. if (write(STDOUT_FILENO, c, 1) == -1)
  358. die("write:");
  359. }
  360. }
  361. }
  362. return EXIT_SUCCESS;
  363. }