term.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //! System calls for getting the terminal size.
  2. //!
  3. //! Getting the terminal size is performed using an ioctl command that takes
  4. //! the file handle to the terminal -- which in this case, is stdout -- and
  5. //! populates a structure containing the values.
  6. //!
  7. //! The size is needed when the user wants the output formatted into columns:
  8. //! the default grid view, or the hybrid grid-details view.
  9. use std::mem::zeroed;
  10. use libc::{c_int, c_ushort, c_ulong, STDOUT_FILENO};
  11. /// The number of rows and columns of a terminal.
  12. struct Winsize {
  13. ws_row: c_ushort,
  14. ws_col: c_ushort,
  15. }
  16. // Unfortunately the actual command is not standardised...
  17. #[cfg(any(target_os = "linux", target_os = "android"))]
  18. static TIOCGWINSZ: c_ulong = 0x5413;
  19. #[cfg(any(target_os = "macos", target_os = "ios", target_os = "dragonfly"))]
  20. static TIOCGWINSZ: c_ulong = 0x40087468;
  21. extern {
  22. pub fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
  23. }
  24. /// Runs the ioctl command. Returns (0, 0) if output is not to a terminal, or
  25. /// there is an error. (0, 0) is an invalid size to have anyway, which is why
  26. /// it can be used as a nil value.
  27. unsafe fn get_dimensions() -> Winsize {
  28. let mut window: Winsize = zeroed();
  29. let result = ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window);
  30. if result == -1 {
  31. zeroed()
  32. }
  33. else {
  34. window
  35. }
  36. }
  37. /// Query the current processes's output, returning its width and height as a
  38. /// number of characters. Returns `None` if the output isn't to a terminal.
  39. pub fn dimensions() -> Option<(usize, usize)> {
  40. let w = unsafe { get_dimensions() };
  41. if w.ws_col == 0 || w.ws_row == 0 {
  42. None
  43. }
  44. else {
  45. Some((w.ws_col as usize, w.ws_row as usize))
  46. }
  47. }