scroll.c 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. void
  55. die(const char *fmt, ...)
  56. {
  57. va_list ap;
  58. va_start(ap, fmt);
  59. vfprintf(stderr, fmt, ap);
  60. va_end(ap);
  61. if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
  62. fputc(' ', stderr);
  63. perror(NULL);
  64. } else {
  65. fputc('\n', stderr);
  66. }
  67. exit(EXIT_FAILURE);
  68. }
  69. void
  70. sigchld(int sig)
  71. {
  72. pid_t pid;
  73. int status;
  74. assert(sig == SIGCHLD);
  75. while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
  76. if (pid == child)
  77. exit(WEXITSTATUS(status));
  78. }
  79. void
  80. sigwinch(int sig)
  81. {
  82. assert(sig == SIGWINCH);
  83. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
  84. die("ioctl:");
  85. if (ioctl(mfd, TIOCSWINSZ, &ws) == -1)
  86. die("ioctl:");
  87. kill(-child, SIGWINCH);
  88. }
  89. void
  90. reset(void)
  91. {
  92. if (tcsetattr(STDIN_FILENO, TCSANOW, &dfl) == -1)
  93. die("tcsetattr:");
  94. }
  95. /* error avoiding malloc */
  96. void *
  97. eamalloc(size_t size)
  98. {
  99. void *mem;
  100. while ((mem = malloc(size)) == NULL) {
  101. struct line *line = TAILQ_LAST(&head, tailhead);
  102. if (line == NULL)
  103. die("malloc:");
  104. TAILQ_REMOVE(&head, line, entries);
  105. free(line->buf);
  106. free(line);
  107. }
  108. return mem;
  109. }
  110. /* error avoiding remalloc */
  111. void *
  112. earealloc(void *ptr, size_t size)
  113. {
  114. void *mem;
  115. while ((mem = realloc(ptr, size)) == NULL) {
  116. struct line *line = TAILQ_LAST(&head, tailhead);
  117. if (line == NULL)
  118. die("realloc:");
  119. TAILQ_REMOVE(&head, line, entries);
  120. free(line->buf);
  121. free(line);
  122. }
  123. return mem;
  124. }
  125. /* Count string length w/o ansi esc sequences. */
  126. size_t
  127. strelen(const char *buf, size_t size)
  128. {
  129. enum {CHAR, BREK, ESC} state = CHAR;
  130. size_t len = 0;
  131. for (size_t i = 0; i < size; i++) {
  132. char c = buf[i];
  133. switch (state) {
  134. case CHAR:
  135. if (c == '\033')
  136. state = BREK;
  137. else
  138. len++;
  139. break;
  140. case BREK:
  141. if (c == '[') {
  142. state = ESC;
  143. } else {
  144. state = CHAR;
  145. len++;
  146. }
  147. break;
  148. case ESC:
  149. if (c >= 64 && c <= 126)
  150. state = CHAR;
  151. break;
  152. }
  153. }
  154. return len;
  155. }
  156. /* detect alternative screen switching */
  157. bool
  158. isaltscreen(char c)
  159. {
  160. static bool alt = false;
  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. alt = true;
  190. /* esc seq. disable alternative screen */
  191. if (strcmp(buf, "?1049l") == 0 ||
  192. strcmp(buf, "?1047l") == 0 ||
  193. strcmp(buf, "?47l" ) == 0)
  194. alt = false;
  195. }
  196. break;
  197. }
  198. return alt;
  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 (strncmp(KB_SCROLL_UP, input, n) == 0 ||
  326. strncmp(MS_SCROLL_UP, input, n) == 0)
  327. scrollup();
  328. else if (strncmp(KB_SCROLL_DOWN, input, n) == 0 ||
  329. strncmp(MS_SCROLL_DOWN, input, n) == 0)
  330. scrolldown(buf, pos);
  331. else if (write(mfd, input, n) == -1)
  332. die("write:");
  333. else if (bottom != TAILQ_FIRST(&head))
  334. jumpdown(buf, pos);
  335. }
  336. if (pfd[1].revents & POLLIN) {
  337. ssize_t n = read(mfd, input, sizeof input);
  338. if (n == -1 && errno != EINTR)
  339. die("read:");
  340. /* iterate over the input buffer */
  341. for (char *c = input; n-- > 0; c++) {
  342. /* don't save lines from alternative screen */
  343. if (!isaltscreen(*c)) {
  344. if (*c == '\r') {
  345. addline(buf, pos);
  346. memset(buf, 0, size);
  347. pos = 0;
  348. }
  349. buf[pos++] = *c;
  350. if (pos == size) {
  351. size *= 2;
  352. buf = earealloc(buf, size);
  353. }
  354. }
  355. if (write(STDOUT_FILENO, c, 1) == -1)
  356. die("write:");
  357. }
  358. }
  359. }
  360. return EXIT_SUCCESS;
  361. }