scroll.c 6.9 KB

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