grid.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. use std::io::{Write, Result as IOResult};
  2. use term_grid as grid;
  3. use fs::File;
  4. use output::DisplayWidth;
  5. use output::colours::Colours;
  6. use super::filename;
  7. #[derive(PartialEq, Debug, Copy, Clone)]
  8. pub struct Grid {
  9. pub across: bool,
  10. pub console_width: usize,
  11. pub colours: Colours,
  12. pub classify: bool,
  13. }
  14. impl Grid {
  15. pub fn view<W: Write>(&self, files: &[File], w: &mut W) -> IOResult<()> {
  16. let direction = if self.across { grid::Direction::LeftToRight }
  17. else { grid::Direction::TopToBottom };
  18. let mut grid = grid::Grid::new(grid::GridOptions {
  19. direction: direction,
  20. filling: grid::Filling::Spaces(2),
  21. });
  22. grid.reserve(files.len());
  23. for file in files.iter() {
  24. let mut width = DisplayWidth::from_file(file, self.classify);
  25. if file.dir.is_none() {
  26. if let Some(parent) = file.path.parent() {
  27. width = width + 1 + DisplayWidth::from(parent.to_string_lossy().as_ref());
  28. }
  29. }
  30. grid.add(grid::Cell {
  31. contents: filename(file, &self.colours, false, self.classify).strings().to_string(),
  32. width: *width,
  33. });
  34. }
  35. if let Some(display) = grid.fit_into_width(self.console_width) {
  36. write!(w, "{}", display)
  37. }
  38. else {
  39. // File names too long for a grid - drop down to just listing them!
  40. for file in files.iter() {
  41. writeln!(w, "{}", filename(file, &self.colours, false, self.classify).strings())?;
  42. }
  43. Ok(())
  44. }
  45. }
  46. }