scroll.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 = 0, start = 0;
  215. struct line *bottom_old = bottom;
  216. /* account for last line */
  217. if(bottom != NULL && TAILQ_PREV(bottom, tailhead, entries) == NULL)
  218. start = 2;
  219. /* wind back bottom pointer by two pages */
  220. for (; bottom != NULL &&
  221. TAILQ_NEXT(bottom, entries) != NULL &&
  222. rows < 2 * ws.ws_row; rows++)
  223. bottom = TAILQ_NEXT(bottom, entries);
  224. if (rows <= ws.ws_row) {
  225. bottom = bottom_old;
  226. return;
  227. }
  228. /* move the text in terminal n lines down */
  229. dprintf(STDOUT_FILENO, "\033[%dT", rows - ws.ws_row);
  230. /* set cursor position */
  231. write(STDOUT_FILENO, "\033[0;0H", 6);
  232. /* hide cursor */
  233. write(STDOUT_FILENO, "\033[?25l", 6);
  234. /* print one page */
  235. for (rows = 0; rows < ws.ws_row + start; rows++) {
  236. write(STDOUT_FILENO, bottom->buf, bottom->size);
  237. bottom = TAILQ_PREV(bottom, tailhead, entries);
  238. }
  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 &&
  246. bottom != NULL &&
  247. TAILQ_PREV(bottom, tailhead, entries) != NULL; rows--) {
  248. bottom = TAILQ_PREV(bottom, tailhead, entries);
  249. write(STDOUT_FILENO, bottom->buf, bottom->size);
  250. }
  251. if (rows < ws.ws_row && bottom == TAILQ_FIRST(&head)) {
  252. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  253. write(STDOUT_FILENO, buf, size);
  254. }
  255. }
  256. void
  257. jumpdown(char *buf, size_t size)
  258. {
  259. int rows = ws.ws_row;
  260. bottom = TAILQ_FIRST(&head);
  261. for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
  262. bottom = TAILQ_NEXT(bottom, entries);
  263. scrolldown(buf, size);
  264. }
  265. int
  266. main(int argc, char *argv[])
  267. {
  268. TAILQ_INIT(&head);
  269. if (isatty(STDIN_FILENO) == 0)
  270. die("stdin it not a tty");
  271. if (isatty(STDOUT_FILENO) == 0)
  272. die("stdout it not a tty");
  273. if (argc <= 1)
  274. die("usage: scroll <program>");
  275. /* save terminal settings for resetting after exit */
  276. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  277. die("tcgetattr:");
  278. if (atexit(reset))
  279. die("atexit:");
  280. /* get window size of the terminal */
  281. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0)
  282. die("ioctl:");
  283. child = forkpty(&mfd, NULL, &dfl, &ws);
  284. if (child == -1)
  285. die("forkpty:");
  286. if (child == 0) { /* child */
  287. execvp(argv[1], argv + 1);
  288. perror("execvp");
  289. _exit(127);
  290. }
  291. #ifdef __OpenBSD__
  292. if (pledge("stdio tty proc", NULL) == -1)
  293. die("pledge:");
  294. #endif
  295. if (signal(SIGCHLD, sigchld) == SIG_ERR)
  296. die("signal:");
  297. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  298. die("signal:");
  299. int f;
  300. if ((f = fcntl(mfd, F_GETFL)) == -1)
  301. die("fcntl:");
  302. if (fcntl(mfd, F_SETFL, f /*| O_NONBLOCK*/) == -1)
  303. die("fcntl:");
  304. struct termios new = dfl;
  305. cfmakeraw(&new);
  306. new.c_cc[VMIN ] = 1;
  307. new.c_cc[VTIME] = 0;
  308. if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
  309. die("tcsetattr:");
  310. size_t size = BUFSIZ, pos = 0;
  311. char *buf = calloc(size, sizeof *buf);
  312. if (buf == NULL)
  313. die("calloc:");
  314. struct pollfd pfd[2] = {
  315. {STDIN_FILENO, POLLIN, 0},
  316. {mfd, POLLIN, 0}
  317. };
  318. for (;;) {
  319. char input[BUFSIZ];
  320. if (poll(pfd, 2, -1) == -1 && errno != EINTR)
  321. die("poll:");
  322. if (pfd[0].revents & POLLIN) {
  323. ssize_t n = read(STDIN_FILENO, input, sizeof input);
  324. if (n <= 0 && errno != EINTR)
  325. die("read:");
  326. if (strncmp(SCROLL_UP, input, n) == 0)
  327. scrollup();
  328. else if (strncmp(SCROLL_DOWN, input, n) == 0)
  329. scrolldown(buf, pos);
  330. else if (write(mfd, input, n) == -1)
  331. die("write:");
  332. else if (bottom != TAILQ_FIRST(&head))
  333. jumpdown(buf, pos);
  334. }
  335. if (pfd[1].revents & POLLIN) {
  336. ssize_t n = read(mfd, input, sizeof input);
  337. if (n == -1 && errno != EINTR)
  338. die("read:");
  339. /* iterate over the input buffer */
  340. for (char *c = input; n-- > 0; c++) {
  341. /* don't save lines from alternative screen */
  342. if (!isaltscreen(*c)) {
  343. if (*c == '\r') {
  344. addline(buf, pos);
  345. memset(buf, 0, size);
  346. pos = 0;
  347. }
  348. buf[pos++] = *c;
  349. if (pos == size) {
  350. size *= 2;
  351. buf = earealloc(buf, size);
  352. }
  353. }
  354. if (write(STDOUT_FILENO, c, 1) == -1)
  355. die("write:");
  356. }
  357. }
  358. }
  359. return EXIT_SUCCESS;
  360. }