term.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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",
  20. target_os = "ios",
  21. target_os = "bitrig",
  22. target_os = "dragonfly",
  23. target_os = "freebsd",
  24. target_os = "netbsd",
  25. target_os = "openbsd"))]
  26. static TIOCGWINSZ: c_ulong = 0x40087468;
  27. extern {
  28. pub fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
  29. }
  30. /// Runs the ioctl command. Returns (0, 0) if output is not to a terminal, or
  31. /// there is an error. (0, 0) is an invalid size to have anyway, which is why
  32. /// it can be used as a nil value.
  33. unsafe fn get_dimensions() -> Winsize {
  34. let mut window: Winsize = zeroed();
  35. let result = ioctl(STDOUT_FILENO, TIOCGWINSZ, &mut window);
  36. if result == -1 {
  37. zeroed()
  38. }
  39. else {
  40. window
  41. }
  42. }
  43. /// Query the current processes's output, returning its width and height as a
  44. /// number of characters. Returns `None` if the output isn't to a terminal.
  45. pub fn dimensions() -> Option<(usize, usize)> {
  46. let w = unsafe { get_dimensions() };
  47. if w.ws_col == 0 || w.ws_row == 0 {
  48. None
  49. }
  50. else {
  51. Some((w.ws_col as usize, w.ws_row as usize))
  52. }
  53. }