scroll.c 8.6 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. 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 &&
  221. TAILQ_NEXT(bottom, entries) != NULL &&
  222. rows <= ws.ws_row; rows++)
  223. bottom = TAILQ_NEXT(bottom, entries);
  224. if (rows <= 0) {
  225. bottom = bottom_old;
  226. return;
  227. }
  228. /* move the text in terminal n lines down */
  229. dprintf(STDOUT_FILENO, "\033[%dT", rows);
  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--) {
  236. write(STDOUT_FILENO, bottom->buf, bottom->size);
  237. bottom = TAILQ_PREV(bottom, tailhead, entries);
  238. }
  239. bottom = TAILQ_NEXT(bottom, entries);
  240. }
  241. void
  242. scrolldown(char *buf, size_t size)
  243. {
  244. int rows = ws.ws_row;
  245. /* print one page */
  246. for (; rows > 0 &&
  247. bottom != NULL &&
  248. TAILQ_PREV(bottom, tailhead, entries) != NULL; rows--) {
  249. bottom = TAILQ_PREV(bottom, tailhead, entries);
  250. write(STDOUT_FILENO, bottom->buf, bottom->size);
  251. }
  252. if (rows < ws.ws_row && bottom == TAILQ_FIRST(&head)) {
  253. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  254. write(STDOUT_FILENO, buf, size);
  255. }
  256. }
  257. void
  258. jumpdown(char *buf, size_t size)
  259. {
  260. int rows = ws.ws_row;
  261. bottom = TAILQ_FIRST(&head);
  262. for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
  263. bottom = TAILQ_NEXT(bottom, entries);
  264. scrolldown(buf, size);
  265. }
  266. int
  267. main(int argc, char *argv[])
  268. {
  269. TAILQ_INIT(&head);
  270. if (isatty(STDIN_FILENO) == 0)
  271. die("stdin it not a tty");
  272. if (isatty(STDOUT_FILENO) == 0)
  273. die("stdout it not a tty");
  274. if (argc <= 1)
  275. die("usage: scroll <program>");
  276. /* save terminal settings for resetting after exit */
  277. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  278. die("tcgetattr:");
  279. if (atexit(reset))
  280. die("atexit:");
  281. /* get window size of the terminal */
  282. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0)
  283. die("ioctl:");
  284. child = forkpty(&mfd, NULL, &dfl, &ws);
  285. if (child == -1)
  286. die("forkpty:");
  287. if (child == 0) { /* child */
  288. execvp(argv[1], argv + 1);
  289. perror("execvp");
  290. _exit(127);
  291. }
  292. #ifdef __OpenBSD__
  293. if (pledge("stdio tty proc", NULL) == -1)
  294. die("pledge:");
  295. #endif
  296. if (signal(SIGCHLD, sigchld) == SIG_ERR)
  297. die("signal:");
  298. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  299. die("signal:");
  300. int f;
  301. if ((f = fcntl(mfd, F_GETFL)) == -1)
  302. die("fcntl:");
  303. if (fcntl(mfd, F_SETFL, f /*| O_NONBLOCK*/) == -1)
  304. die("fcntl:");
  305. struct termios new = dfl;
  306. cfmakeraw(&new);
  307. new.c_cc[VMIN ] = 1;
  308. new.c_cc[VTIME] = 0;
  309. if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
  310. die("tcsetattr:");
  311. size_t size = BUFSIZ, pos = 0;
  312. char *buf = calloc(size, sizeof *buf);
  313. if (buf == NULL)
  314. die("calloc:");
  315. struct pollfd pfd[2] = {
  316. {STDIN_FILENO, POLLIN, 0},
  317. {mfd, POLLIN, 0}
  318. };
  319. for (;;) {
  320. char input[BUFSIZ];
  321. if (poll(pfd, 2, -1) == -1 && errno != EINTR)
  322. die("poll:");
  323. if (pfd[0].revents & POLLIN) {
  324. ssize_t n = read(STDIN_FILENO, input, sizeof input);
  325. if (n <= 0 && errno != EINTR)
  326. die("read:");
  327. if (strncmp(KB_SCROLL_UP, input, n) == 0 ||
  328. strncmp(MS_SCROLL_UP, input, n) == 0)
  329. scrollup();
  330. else if (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. }