resize.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * resize - set terminal width and height.
  4. *
  5. * Copyright 2006 Bernhard Reutner-Fischer
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. /* no options, no getopt */
  10. //usage:#define resize_trivial_usage
  11. //usage: ""
  12. //usage:#define resize_full_usage "\n\n"
  13. //usage: "Resize the screen"
  14. #include "libbb.h"
  15. #define ESC "\033"
  16. #define old_termios_p ((struct termios*)&bb_common_bufsiz1)
  17. static void
  18. onintr(int sig UNUSED_PARAM)
  19. {
  20. tcsetattr(STDERR_FILENO, TCSANOW, old_termios_p);
  21. _exit(EXIT_FAILURE);
  22. }
  23. int resize_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  24. int resize_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  25. {
  26. struct termios new;
  27. struct winsize w = { 0, 0, 0, 0 };
  28. int ret;
  29. /* We use _stderr_ in order to make resize usable
  30. * in shell backticks (those redirect stdout away from tty).
  31. * NB: other versions of resize open "/dev/tty"
  32. * and operate on it - should we do the same?
  33. */
  34. tcgetattr(STDERR_FILENO, old_termios_p); /* fiddle echo */
  35. memcpy(&new, old_termios_p, sizeof(new));
  36. new.c_cflag |= (CLOCAL | CREAD);
  37. new.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
  38. bb_signals(0
  39. + (1 << SIGINT)
  40. + (1 << SIGQUIT)
  41. + (1 << SIGTERM)
  42. + (1 << SIGALRM)
  43. , onintr);
  44. tcsetattr(STDERR_FILENO, TCSANOW, &new);
  45. /* save_cursor_pos 7
  46. * scroll_whole_screen [r
  47. * put_cursor_waaaay_off [$x;$yH
  48. * get_cursor_pos [6n
  49. * restore_cursor_pos 8
  50. */
  51. fprintf(stderr, ESC"7" ESC"[r" ESC"[999;999H" ESC"[6n");
  52. alarm(3); /* Just in case terminal won't answer */
  53. //BUG: death by signal won't restore termios
  54. scanf(ESC"[%hu;%huR", &w.ws_row, &w.ws_col);
  55. fprintf(stderr, ESC"8");
  56. /* BTW, other versions of resize recalculate w.ws_xpixel, ws.ws_ypixel
  57. * by calculating character cell HxW from old values
  58. * (gotten via TIOCGWINSZ) and recomputing *pixel values */
  59. ret = ioctl(STDERR_FILENO, TIOCSWINSZ, &w);
  60. tcsetattr(STDERR_FILENO, TCSANOW, old_termios_p);
  61. if (ENABLE_FEATURE_RESIZE_PRINT)
  62. printf("COLUMNS=%d;LINES=%d;export COLUMNS LINES;\n",
  63. w.ws_col, w.ws_row);
  64. return ret;
  65. }