scroll.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. TAILQ_HEAD(tailhead, line) head;
  43. struct line {
  44. TAILQ_ENTRY(line) entries;
  45. size_t size;
  46. size_t len;
  47. char *buf;
  48. } *bottom;
  49. pid_t child;
  50. int mfd;
  51. struct termios dfl;
  52. struct winsize ws;
  53. void
  54. die(const char *fmt, ...)
  55. {
  56. va_list ap;
  57. va_start(ap, fmt);
  58. vfprintf(stderr, fmt, ap);
  59. va_end(ap);
  60. if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
  61. fputc(' ', stderr);
  62. perror(NULL);
  63. } else {
  64. fputc('\n', stderr);
  65. }
  66. exit(EXIT_FAILURE);
  67. }
  68. void
  69. sigchld(int sig)
  70. {
  71. pid_t pid;
  72. int status;
  73. assert(sig == SIGCHLD);
  74. while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
  75. if (pid == child)
  76. exit(WEXITSTATUS(status));
  77. }
  78. void
  79. sigwinch(int sig)
  80. {
  81. assert(sig == SIGWINCH);
  82. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
  83. die("ioctl:");
  84. if (ioctl(mfd, TIOCSWINSZ, &ws) == -1)
  85. die("ioctl:");
  86. kill(-child, SIGWINCH);
  87. }
  88. void
  89. reset(void)
  90. {
  91. if (tcsetattr(STDIN_FILENO, TCSANOW, &dfl) == -1)
  92. die("tcsetattr:");
  93. }
  94. /* error avoiding malloc */
  95. void *
  96. eamalloc(size_t size)
  97. {
  98. void *mem;
  99. while ((mem = malloc(size)) == NULL) {
  100. struct line *line = TAILQ_LAST(&head, tailhead);
  101. if (line == NULL)
  102. die("malloc:");
  103. TAILQ_REMOVE(&head, line, entries);
  104. free(line->buf);
  105. free(line);
  106. }
  107. return mem;
  108. }
  109. /* error avoiding remalloc */
  110. void *
  111. earealloc(void *ptr, size_t size)
  112. {
  113. void *mem;
  114. while ((mem = realloc(ptr, size)) == NULL) {
  115. struct line *line = TAILQ_LAST(&head, tailhead);
  116. if (line == NULL)
  117. die("realloc:");
  118. TAILQ_REMOVE(&head, line, entries);
  119. free(line->buf);
  120. free(line);
  121. }
  122. return mem;
  123. }
  124. /* Count string length w/o ansi esc sequences. */
  125. size_t
  126. strelen(const char *buf, size_t size)
  127. {
  128. enum {CHAR, BREK, ESC} state = CHAR;
  129. size_t len = 0;
  130. for (size_t i = 0; i < size; i++) {
  131. char c = buf[i];
  132. switch (state) {
  133. case CHAR:
  134. if (c == '\033')
  135. state = BREK;
  136. else
  137. len++;
  138. break;
  139. case BREK:
  140. if (c == '[') {
  141. state = ESC;
  142. } else {
  143. state = CHAR;
  144. len++;
  145. }
  146. break;
  147. case ESC:
  148. if (c >= 64 && c <= 126)
  149. state = CHAR;
  150. break;
  151. }
  152. }
  153. return len;
  154. }
  155. /* alternate screen */
  156. bool
  157. isaltscreen(char c)
  158. {
  159. static bool alt = false;
  160. static enum {CHAR, BREK, ESC} state = CHAR;
  161. static char buf[BUFSIZ];
  162. static size_t i = 0;
  163. switch (state) {
  164. case CHAR:
  165. if (c == '\033')
  166. state = BREK;
  167. break;
  168. case BREK:
  169. if (c == '[')
  170. state = ESC;
  171. else
  172. state = CHAR;
  173. break;
  174. case ESC:
  175. buf[i++] = c;
  176. if (i == sizeof buf) {
  177. /* TODO: find a better way to handle this situation */
  178. state = CHAR;
  179. i = 0;
  180. } else if (c >= 64 && c <= 126) {
  181. state = CHAR;
  182. buf[i] = '\0';
  183. i = 0;
  184. if (strcmp(buf, "?1049h") == 0 ||
  185. strcmp(buf, "?1047h") == 0 ||
  186. strcmp(buf, "?47h" ) == 0)
  187. alt = true;
  188. if (strcmp(buf, "?1049l") == 0 ||
  189. strcmp(buf, "?1047l") == 0 ||
  190. strcmp(buf, "?47l" ) == 0)
  191. alt = false;
  192. }
  193. break;
  194. }
  195. return alt;
  196. }
  197. void
  198. addline(char *buf, size_t size)
  199. {
  200. struct line *line = eamalloc(sizeof *line);
  201. line->size = size;
  202. line->len = strelen(buf, size);
  203. line->buf = eamalloc(size);
  204. memcpy(line->buf, buf, size);
  205. bottom = line;
  206. TAILQ_INSERT_HEAD(&head, line, entries);
  207. }
  208. void
  209. scrollup(void)
  210. {
  211. int rows = 0, start = 0;
  212. struct line *bottom_old = bottom;
  213. /* account for last line */
  214. if(bottom != NULL && TAILQ_PREV(bottom, tailhead, entries) == NULL)
  215. start = 2;
  216. /* wind back bottom pointer by two pages */
  217. for (; bottom != NULL &&
  218. TAILQ_NEXT(bottom, entries) != NULL &&
  219. rows < 2 * ws.ws_row; rows++)
  220. bottom = TAILQ_NEXT(bottom, entries);
  221. if (rows <= ws.ws_row) {
  222. bottom = bottom_old;
  223. return;
  224. }
  225. /* move the text in terminal n lines down */
  226. dprintf(STDOUT_FILENO, "\033[%dT", rows - ws.ws_row);
  227. /* set cursor position */
  228. write(STDOUT_FILENO, "\033[0;0H", 6);
  229. /* hide cursor */
  230. write(STDOUT_FILENO, "\033[?25l", 6);
  231. /* print one page */
  232. for (rows = 0; rows < ws.ws_row + start; rows++) {
  233. write(STDOUT_FILENO, bottom->buf, bottom->size);
  234. bottom = TAILQ_PREV(bottom, tailhead, entries);
  235. }
  236. }
  237. void
  238. scrolldown(char *buf, size_t size)
  239. {
  240. int rows = ws.ws_row;
  241. /* print one page */
  242. for (; rows > 0 &&
  243. bottom != NULL &&
  244. TAILQ_PREV(bottom, tailhead, entries) != NULL; rows--) {
  245. bottom = TAILQ_PREV(bottom, tailhead, entries);
  246. write(STDOUT_FILENO, bottom->buf, bottom->size);
  247. }
  248. if (rows < ws.ws_row && bottom == TAILQ_FIRST(&head)) {
  249. write(STDOUT_FILENO, "\033[?25h", 6);
  250. write(STDOUT_FILENO, buf, size);
  251. }
  252. }
  253. void
  254. jumpdown(char *buf, size_t size)
  255. {
  256. int rows = ws.ws_row;
  257. bottom = TAILQ_FIRST(&head);
  258. for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
  259. bottom = TAILQ_NEXT(bottom, entries);
  260. scrolldown(buf, size);
  261. }
  262. int
  263. main(int argc, char *argv[])
  264. {
  265. TAILQ_INIT(&head);
  266. if (isatty(STDIN_FILENO) == 0)
  267. die("stdin it not a tty");
  268. if (isatty(STDOUT_FILENO) == 0)
  269. die("stdout it not a tty");
  270. if (argc <= 1)
  271. die("usage: scroll <program>");
  272. /* save terminal settings for resetting after exit */
  273. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  274. die("tcgetattr:");
  275. if (atexit(reset))
  276. die("atexit:");
  277. /* get window size of the terminal */
  278. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0)
  279. die("ioctl:");
  280. child = forkpty(&mfd, NULL, &dfl, &ws);
  281. if (child == -1)
  282. die("forkpty:");
  283. if (child == 0) { /* child */
  284. execvp(argv[1], argv + 1);
  285. perror("execvp");
  286. _exit(127);
  287. }
  288. #ifdef __OpenBSD__
  289. if (pledge("stdio tty proc", NULL) == -1)
  290. die("pledge:");
  291. #endif
  292. if (signal(SIGCHLD, sigchld) == SIG_ERR)
  293. die("signal:");
  294. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  295. die("signal:");
  296. int f;
  297. if ((f = fcntl(mfd, F_GETFL)) == -1)
  298. die("fcntl:");
  299. if (fcntl(mfd, F_SETFL, f /*| O_NONBLOCK*/) == -1)
  300. die("fcntl:");
  301. struct termios new = dfl;
  302. cfmakeraw(&new);
  303. new.c_cc[VMIN ] = 1;
  304. new.c_cc[VTIME] = 0;
  305. if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
  306. die("tcsetattr:");
  307. size_t size = BUFSIZ, pos = 0;
  308. char *buf = calloc(size, sizeof *buf);
  309. if (buf == NULL)
  310. die("calloc:");
  311. struct pollfd pfd[2] = {
  312. {STDIN_FILENO, POLLIN, 0},
  313. {mfd, POLLIN, 0}
  314. };
  315. for (;;) {
  316. char input[BUFSIZ];
  317. if (poll(pfd, 2, -1) == -1 && errno != EINTR)
  318. die("poll:");
  319. if (pfd[0].revents & POLLIN) {
  320. ssize_t n = read(STDIN_FILENO, input, sizeof input);
  321. if (n <= 0 && errno != EINTR)
  322. die("read:");
  323. /* iterate over the input buffer */
  324. for (char *c = input; n-- > 0; c++) {
  325. if (*c == 17) /* ^Q */
  326. scrollup();
  327. else if (*c == 18) /* ^R */
  328. scrolldown(buf, pos);
  329. else if (write(mfd, c, 1) == -1)
  330. die("write:");
  331. else if (bottom != TAILQ_FIRST(&head))
  332. jumpdown(buf, pos);
  333. }
  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. }