scroll.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. static bool altscreen = false; /* is alternative screen active */
  55. void
  56. die(const char *fmt, ...)
  57. {
  58. va_list ap;
  59. va_start(ap, fmt);
  60. vfprintf(stderr, fmt, ap);
  61. va_end(ap);
  62. if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
  63. fputc(' ', stderr);
  64. perror(NULL);
  65. } else {
  66. fputc('\n', stderr);
  67. }
  68. exit(EXIT_FAILURE);
  69. }
  70. void
  71. sigchld(int sig)
  72. {
  73. pid_t pid;
  74. int status;
  75. assert(sig == SIGCHLD);
  76. while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
  77. if (pid == child)
  78. exit(WEXITSTATUS(status));
  79. }
  80. void
  81. sigwinch(int sig)
  82. {
  83. assert(sig == SIGWINCH);
  84. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
  85. die("ioctl:");
  86. if (ioctl(mfd, TIOCSWINSZ, &ws) == -1)
  87. die("ioctl:");
  88. kill(-child, SIGWINCH);
  89. }
  90. void
  91. reset(void)
  92. {
  93. if (tcsetattr(STDIN_FILENO, TCSANOW, &dfl) == -1)
  94. die("tcsetattr:");
  95. }
  96. /* error avoiding malloc */
  97. void *
  98. eamalloc(size_t size)
  99. {
  100. void *mem;
  101. while ((mem = malloc(size)) == NULL) {
  102. struct line *line = TAILQ_LAST(&head, tailhead);
  103. if (line == NULL)
  104. die("malloc:");
  105. TAILQ_REMOVE(&head, line, entries);
  106. free(line->buf);
  107. free(line);
  108. }
  109. return mem;
  110. }
  111. /* error avoiding remalloc */
  112. void *
  113. earealloc(void *ptr, size_t size)
  114. {
  115. void *mem;
  116. while ((mem = realloc(ptr, size)) == NULL) {
  117. struct line *line = TAILQ_LAST(&head, tailhead);
  118. if (line == NULL)
  119. die("realloc:");
  120. TAILQ_REMOVE(&head, line, entries);
  121. free(line->buf);
  122. free(line);
  123. }
  124. return mem;
  125. }
  126. /* Count string length w/o ansi esc sequences. */
  127. size_t
  128. strelen(const char *buf, size_t size)
  129. {
  130. enum {CHAR, BREK, ESC} state = CHAR;
  131. size_t len = 0;
  132. for (size_t i = 0; i < size; i++) {
  133. char c = buf[i];
  134. switch (state) {
  135. case CHAR:
  136. if (c == '\033')
  137. state = BREK;
  138. else
  139. len++;
  140. break;
  141. case BREK:
  142. if (c == '[') {
  143. state = ESC;
  144. } else {
  145. state = CHAR;
  146. len++;
  147. }
  148. break;
  149. case ESC:
  150. if (c >= 64 && c <= 126)
  151. state = CHAR;
  152. break;
  153. }
  154. }
  155. return len;
  156. }
  157. /* detect alternative screen switching */
  158. bool
  159. isaltscreen(char c)
  160. {
  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. altscreen = true;
  190. /* esc seq. disable alternative screen */
  191. if (strcmp(buf, "?1049l") == 0 ||
  192. strcmp(buf, "?1047l") == 0 ||
  193. strcmp(buf, "?47l" ) == 0)
  194. altscreen = false;
  195. }
  196. break;
  197. }
  198. return altscreen;
  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(int n)
  213. {
  214. int rows = 2;
  215. struct line *scrollend = bottom;
  216. /* wind back scrollend pointer by one page plus n */
  217. for (; scrollend != NULL && TAILQ_NEXT(scrollend, entries) != NULL &&
  218. rows < ws.ws_row + n; rows++)
  219. scrollend = TAILQ_NEXT(scrollend, entries);
  220. rows -= ws.ws_row;
  221. if (rows <= 0) {
  222. return;
  223. }
  224. /* move the text in terminal rows lines down */
  225. dprintf(STDOUT_FILENO, "\033[%dT", rows);
  226. /* set cursor position to upper left corner */
  227. write(STDOUT_FILENO, "\033[0;0H", 6);
  228. /* hide cursor */
  229. write(STDOUT_FILENO, "\033[?25l", 6);
  230. /* remove newline of first line as we are at 0,0 already */
  231. if (scrollend->size > 2)
  232. write(STDOUT_FILENO, scrollend->buf + 2, scrollend->size - 2);
  233. bottom = TAILQ_NEXT(bottom, entries);
  234. /* print rows lines and move bottom forward to the new screen bottom */
  235. for (; rows > 1; rows--) {
  236. scrollend = TAILQ_PREV(scrollend, tailhead, entries);
  237. bottom = TAILQ_NEXT(bottom, entries);
  238. write(STDOUT_FILENO, scrollend->buf, scrollend->size);
  239. }
  240. dprintf(STDOUT_FILENO, "\033[%d;%dH", ws.ws_row, ws.ws_col);
  241. }
  242. void
  243. scrolldown(char *buf, size_t size, int n)
  244. {
  245. if (bottom == NULL || bottom == TAILQ_FIRST(&head))
  246. return;
  247. bottom = TAILQ_PREV(bottom, tailhead, entries);
  248. /* print n lines */
  249. for (; n > 0 && bottom != NULL && bottom != TAILQ_FIRST(&head); n--) {
  250. bottom = TAILQ_PREV(bottom, tailhead, entries);
  251. write(STDOUT_FILENO, bottom->buf, bottom->size);
  252. }
  253. if (n > 0 && bottom == TAILQ_FIRST(&head)) {
  254. write(STDOUT_FILENO, "\033[?25h", 6); /* show cursor */
  255. write(STDOUT_FILENO, buf, size);
  256. } else if (bottom != NULL)
  257. bottom = TAILQ_NEXT(bottom, entries);
  258. }
  259. void
  260. jumpdown(char *buf, size_t size)
  261. {
  262. int rows = ws.ws_row;
  263. bottom = TAILQ_FIRST(&head);
  264. for (; TAILQ_NEXT(bottom, entries) != NULL && rows > 0; rows--)
  265. bottom = TAILQ_NEXT(bottom, entries);
  266. scrolldown(buf, size, ws.ws_row);
  267. }
  268. int
  269. main(int argc, char *argv[])
  270. {
  271. TAILQ_INIT(&head);
  272. if (isatty(STDIN_FILENO) == 0)
  273. die("stdin it not a tty");
  274. if (isatty(STDOUT_FILENO) == 0)
  275. die("stdout it not a tty");
  276. if (argc <= 1)
  277. die("usage: scroll <program>");
  278. /* save terminal settings for resetting after exit */
  279. if (tcgetattr(STDIN_FILENO, &dfl) == -1)
  280. die("tcgetattr:");
  281. if (atexit(reset))
  282. die("atexit:");
  283. /* get window size of the terminal */
  284. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0)
  285. die("ioctl:");
  286. child = forkpty(&mfd, NULL, &dfl, &ws);
  287. if (child == -1)
  288. die("forkpty:");
  289. if (child == 0) { /* child */
  290. execvp(argv[1], argv + 1);
  291. perror("execvp");
  292. _exit(127);
  293. }
  294. #ifdef __OpenBSD__
  295. if (pledge("stdio tty proc", NULL) == -1)
  296. die("pledge:");
  297. #endif
  298. if (signal(SIGCHLD, sigchld) == SIG_ERR)
  299. die("signal:");
  300. if (signal(SIGWINCH, sigwinch) == SIG_ERR)
  301. die("signal:");
  302. int f;
  303. if ((f = fcntl(mfd, F_GETFL)) == -1)
  304. die("fcntl:");
  305. if (fcntl(mfd, F_SETFL, f /*| O_NONBLOCK*/) == -1)
  306. die("fcntl:");
  307. struct termios new = dfl;
  308. cfmakeraw(&new);
  309. new.c_cc[VMIN ] = 1;
  310. new.c_cc[VTIME] = 0;
  311. if (tcsetattr(STDIN_FILENO, TCSANOW, &new) == -1)
  312. die("tcsetattr:");
  313. size_t size = BUFSIZ, pos = 0;
  314. char *buf = calloc(size, sizeof *buf);
  315. if (buf == NULL)
  316. die("calloc:");
  317. struct pollfd pfd[2] = {
  318. {STDIN_FILENO, POLLIN, 0},
  319. {mfd, POLLIN, 0}
  320. };
  321. for (;;) {
  322. char input[BUFSIZ];
  323. if (poll(pfd, 2, -1) == -1 && errno != EINTR)
  324. die("poll:");
  325. if (pfd[0].revents & POLLIN) {
  326. ssize_t n = read(STDIN_FILENO, input, sizeof(input)-1);
  327. if (n <= 0 && errno != EINTR)
  328. die("read:");
  329. input[n] = '\0';
  330. if (!altscreen && strcmp(KB_SCROLL_UP, input) == 0)
  331. scrollup(ws.ws_row);
  332. else if (!altscreen && strcmp(MS_SCROLL_UP, input) == 0)
  333. scrollup(1);
  334. else if (!altscreen && strcmp(KB_SCROLL_DOWN, input) == 0)
  335. scrolldown(buf, pos, ws.ws_row);
  336. else if (!altscreen && strcmp(MS_SCROLL_DOWN, input) == 0)
  337. scrolldown(buf, pos, 1);
  338. else if (write(mfd, input, n) == -1)
  339. die("write:");
  340. else if (bottom != TAILQ_FIRST(&head))
  341. jumpdown(buf, pos);
  342. }
  343. if (pfd[1].revents & POLLIN) {
  344. ssize_t n = read(mfd, input, sizeof input);
  345. if (n == -1 && errno != EINTR)
  346. die("read:");
  347. if (write(STDOUT_FILENO, input, n) == -1)
  348. die("write:");
  349. /* don't save clear screen esc sequences in log */
  350. if (strncmp("\033[H\033[2J", input, n) == 0)
  351. continue;
  352. /* iterate over the input buffer */
  353. for (char *c = input; n-- > 0; c++) {
  354. /* don't save lines from alternative screen */
  355. if (isaltscreen(*c))
  356. continue;
  357. if (*c == '\r') {
  358. addline(buf, pos);
  359. memset(buf, 0, size);
  360. pos = 0;
  361. }
  362. buf[pos++] = *c;
  363. if (pos == size) {
  364. size *= 2;
  365. buf = earealloc(buf, size);
  366. }
  367. }
  368. }
  369. }
  370. return EXIT_SUCCESS;
  371. }