scroll.c 8.0 KB

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