resize.c 2.1 KB

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