grid.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. use std::io::{Write, Result as IOResult};
  2. use term_grid as tg;
  3. use fs::File;
  4. use style::Colours;
  5. use output::file_name::FileStyle;
  6. #[derive(PartialEq, Debug, Copy, Clone)]
  7. pub struct Options {
  8. pub across: bool,
  9. pub console_width: usize,
  10. }
  11. impl Options {
  12. pub fn direction(&self) -> tg::Direction {
  13. if self.across { tg::Direction::LeftToRight }
  14. else { tg::Direction::TopToBottom }
  15. }
  16. }
  17. pub struct Render<'a> {
  18. pub files: Vec<File<'a>>,
  19. pub colours: &'a Colours,
  20. pub style: &'a FileStyle,
  21. pub opts: &'a Options,
  22. }
  23. impl<'a> Render<'a> {
  24. pub fn render<W: Write>(&self, w: &mut W) -> IOResult<()> {
  25. let mut grid = tg::Grid::new(tg::GridOptions {
  26. direction: self.opts.direction(),
  27. filling: tg::Filling::Spaces(2),
  28. });
  29. grid.reserve(self.files.len());
  30. for file in self.files.iter() {
  31. let filename = self.style.for_file(file, self.colours).paint();
  32. let width = filename.width();
  33. grid.add(tg::Cell {
  34. contents: filename.strings().to_string(),
  35. width: *width,
  36. });
  37. }
  38. if let Some(display) = grid.fit_into_width(self.opts.console_width) {
  39. write!(w, "{}", display)
  40. }
  41. else {
  42. // File names too long for a grid - drop down to just listing them!
  43. // This isn’t *quite* the same as the lines view, which also
  44. // displays full link paths.
  45. for file in self.files.iter() {
  46. let name_cell = self.style.for_file(file, self.colours).paint();
  47. writeln!(w, "{}", name_cell.strings())?;
  48. }
  49. Ok(())
  50. }
  51. }
  52. }