scroll.c 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. strcmp(buf, "?1049l") == 0 ||
  188. strcmp(buf, "?1047l") == 0 ||
  189. strcmp(buf, "?47l" ) == 0)
  190. alt = !alt;
  191. }
  192. break;
  193. }
  194. return alt;
  195. }
  196. void
  197. addline(char *buf, size_t size)
  198. {
  199. struct line *line = eamalloc(sizeof *line);
  200. line->size = size;
  201. line->len = strelen(buf, size);
  202. line->buf = eamalloc(size);
  203. memcpy(line->buf, buf, size);
  204. bottom = line;
  205. TAILQ_INSERT_HEAD(&head, line, entries);
  206. }
  207. void
  208. scrollup(void)
  209. {
  210. int rows = 0, start = 0;
  211. /* account for last line */
  212. if(TAILQ_PREV(bottom, tailhead, entries) == NULL)
  213. start = 1;
  214. /* wind back bottom pointer by two pages */
  215. for (; bottom != NULL && TAILQ_NEXT(bottom, entries) != NULL && rows < 2 * ws.ws_row; rows++)
  216. bottom = TAILQ_NEXT(bottom, entries);
  217. if (rows <= ws.ws_row) {
  218. bottom = TAILQ_LAST(&head, tailhead);
  219. return;
  220. }
  221. /* move the text in terminal n lines down */
  222. dprintf(STDOUT_FILENO, "\033[%dT", rows - ws.ws_row);
  223. /* set cursor position */
  224. write(STDOUT_FILENO, "\033[0;0H", 6);
  225. /* hide cursor */
  226. write(STDOUT_FILENO, "\033[?25l", 6);
  227. /* print one page */
  228. for (rows = 0; rows < ws.ws_row + start; rows++) {
  229. bottom = TAILQ_PREV(bottom, tailhead, entries);
  230. write(STDOUT_FILENO, bottom->buf, bottom->size);
  231. }
  232. }
  233. void
  234. scrolldown(char *buf, size_t size)
  235. {
  236. int rows = ws.ws_row;
  237. /* print one page */
  238. for (; rows > 0 && bottom != NULL && TAILQ_PREV(bottom, tailhead, entries) != NULL; rows--) {
  239. bottom = TAILQ_PREV(bottom, tailhead, entries);
  240. write(STDOUT_FILENO, bottom->buf, bottom->size);
  241. }
  242. if (rows < ws.ws_row && bottom == TAILQ_FIRST(&head)) {
  243. write(STDOUT_FILENO, "\033[?25h", 6);
  244. write(STDOUT_FILENO, buf, size);
  245. }
  246. }
  247. int
  248. main(int argc, char *argv[])
  249. {
  250. TAILQ_INIT(&head);
  251. if (isatty(STDIN_FILENO) == 0)
  252. die("stdin it not a tty");
  253. if (isatty(STDOUT_FILENO) == 0)
  254. die("stdout it not a tty");
  255. if (argc <= 1)
  256. die("usage: scroll <program>");
  257. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  258. die("tcgetattr:");
  259. if (atexit(reset))
  260. die("atexit:");
  261. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0)
  262. die("ioctl:");
  263. child = forkpty(&mfd, NULL, &dfl, &ws);
  264. if (child == -1)
  265. die("forkpty:");
  266. if (child == 0) { /* child */
  267. execvp(argv[1], argv + 1);
  268. perror("execvp");
  269. _exit(127);
  270. }
  271. #ifdef __OpenBSD__
  272. if (pledge("stdio tty proc", NULL) == -1)
  273. die("pledge:");
  274. #endif
  275. if (signal(SIGCHLD, sigchld) == SIG_ERR)
  276. die("signal:");
  277. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  278. die("signal:");
  279. int f;
  280. if ((f = fcntl(mfd, F_GETFL)) == -1)
  281. die("fcntl:");
  282. if (fcntl(mfd, F_SETFL, f /*| O_NONBLOCK*/) == -1)
  283. die("fcntl:");
  284. struct termios new = dfl;
  285. cfmakeraw(&new);
  286. new.c_cc[VMIN ] = 1;
  287. new.c_cc[VTIME] = 0;
  288. if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
  289. die("tcsetattr:");
  290. size_t size = BUFSIZ, pos = 0;
  291. char *buf = calloc(size, sizeof *buf);
  292. if (buf == NULL)
  293. die("calloc:");
  294. struct pollfd pfd[2] = {
  295. {STDIN_FILENO, POLLIN, 0},
  296. {mfd, POLLIN, 0}
  297. };
  298. for (;;) {
  299. char c;
  300. if (poll(pfd, 2, -1) == -1 && errno != EINTR)
  301. die("poll:");
  302. if (pfd[0].revents & POLLIN) {
  303. if (read(STDIN_FILENO, &c, 1) <= 0 && errno != EINTR)
  304. die("read:");
  305. if (c == 17) /* ^Q */
  306. scrollup();
  307. else if (c == 18) /* ^R */
  308. scrolldown(buf, pos);
  309. else if (write(mfd, &c, 1) == -1)
  310. die("write:");
  311. else if (bottom != TAILQ_FIRST(&head)) {
  312. bottom = TAILQ_FIRST(&head);
  313. scrolldown(buf, pos);
  314. }
  315. }
  316. if (pfd[1].revents & POLLIN) {
  317. ssize_t n = read(mfd, &c, 1);
  318. if (n == -1 && errno != EINTR)
  319. die("read:");
  320. if (!isaltscreen(c)) {
  321. if (c == '\r') {
  322. addline(buf, pos);
  323. memset(buf, 0, size);
  324. pos = 0;
  325. }
  326. buf[pos++] = c;
  327. if (pos == size) {
  328. size *= 2;
  329. buf = earealloc(buf, size);
  330. }
  331. }
  332. if (write(STDOUT_FILENO, &c, 1) == -1)
  333. die("write:");
  334. }
  335. }
  336. return EXIT_SUCCESS;
  337. }