grid_details.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //! The grid-details view lists several details views side-by-side.
  2. use std::io::{Write, Result as IOResult};
  3. use ansi_term::ANSIStrings;
  4. use term_grid as grid;
  5. use fs::{Dir, File};
  6. use fs::feature::ignore::IgnoreCache;
  7. use fs::feature::git::GitCache;
  8. use fs::feature::xattr::FileAttributes;
  9. use fs::filter::FileFilter;
  10. use style::Colours;
  11. use output::cell::TextCell;
  12. use output::details::{Options as DetailsOptions, Row as DetailsRow, Render as DetailsRender};
  13. use output::grid::Options as GridOptions;
  14. use output::file_name::FileStyle;
  15. use output::table::{Table, Row as TableRow, Options as TableOptions};
  16. use output::tree::{TreeParams, TreeDepth};
  17. #[derive(Debug)]
  18. pub struct Options {
  19. pub grid: GridOptions,
  20. pub details: DetailsOptions,
  21. pub row_threshold: RowThreshold,
  22. }
  23. /// The grid-details view can be configured to revert to just a details view
  24. /// (with one column) if it wouldn’t produce enough rows of output.
  25. ///
  26. /// Doing this makes the resulting output look a bit better: when listing a
  27. /// small directory of four files in four columns, the files just look spaced
  28. /// out and it’s harder to see what’s going on. So it can be enabled just for
  29. /// larger directory listings.
  30. #[derive(Copy, Clone, Debug, PartialEq)]
  31. pub enum RowThreshold {
  32. /// Only use grid-details view if it would result in at least this many
  33. /// rows of output.
  34. MinimumRows(usize),
  35. /// Use the grid-details view no matter what.
  36. AlwaysGrid,
  37. }
  38. pub struct Render<'a> {
  39. /// The directory that’s being rendered here.
  40. /// We need this to know which columns to put in the output.
  41. pub dir: Option<&'a Dir>,
  42. /// The files that have been read from the directory. They should all
  43. /// hold a reference to it.
  44. pub files: Vec<File<'a>>,
  45. /// How to colour various pieces of text.
  46. pub colours: &'a Colours,
  47. /// How to format filenames.
  48. pub style: &'a FileStyle,
  49. /// The grid part of the grid-details view.
  50. pub grid: &'a GridOptions,
  51. /// The details part of the grid-details view.
  52. pub details: &'a DetailsOptions,
  53. /// How to filter files after listing a directory. The files in this
  54. /// render will already have been filtered and sorted, but any directories
  55. /// that we recurse into will have to have this applied.
  56. pub filter: &'a FileFilter,
  57. /// The minimum number of rows that there need to be before grid-details
  58. /// mode is activated.
  59. pub row_threshold: RowThreshold,
  60. }
  61. impl<'a> Render<'a> {
  62. /// Create a temporary Details render that gets used for the columns of
  63. /// the grid-details render that's being generated.
  64. ///
  65. /// This includes an empty files vector because the files get added to
  66. /// the table in *this* file, not in details: we only want to insert every
  67. /// *n* files into each column’s table, not all of them.
  68. pub fn details(&self) -> DetailsRender<'a> {
  69. DetailsRender {
  70. dir: self.dir.clone(),
  71. files: Vec::new(),
  72. colours: self.colours,
  73. style: self.style,
  74. opts: self.details,
  75. recurse: None,
  76. filter: self.filter,
  77. }
  78. }
  79. /// Create a Details render for when this grid-details render doesn’t fit
  80. /// in the terminal (or something has gone wrong) and we have given up.
  81. pub fn give_up(self) -> DetailsRender<'a> {
  82. DetailsRender {
  83. dir: self.dir,
  84. files: self.files,
  85. colours: self.colours,
  86. style: self.style,
  87. opts: self.details,
  88. recurse: None,
  89. filter: &self.filter,
  90. }
  91. }
  92. pub fn render<W: Write>(self, git: Option<&GitCache>, ignore: Option<&'a IgnoreCache>, w: &mut W) -> IOResult<()> {
  93. if let Some((grid, width)) = self.find_fitting_grid(git, ignore) {
  94. write!(w, "{}", grid.fit_into_columns(width))
  95. }
  96. else {
  97. self.give_up().render(git, ignore, w)
  98. }
  99. }
  100. pub fn find_fitting_grid(&self, git: Option<&GitCache>, ignore: Option<&'a IgnoreCache>) -> Option<(grid::Grid, grid::Width)> {
  101. let options = self.details.table.as_ref().expect("Details table options not given!");
  102. let drender = self.details();
  103. let (first_table, _) = self.make_table(options, git, &drender);
  104. let rows = self.files.iter()
  105. .map(|file| first_table.row_for_file(file, file_has_xattrs(file)))
  106. .collect::<Vec<TableRow>>();
  107. let file_names = self.files.iter()
  108. .map(|file| self.style.for_file(file, self.colours).paint().promote())
  109. .collect::<Vec<TextCell>>();
  110. let mut last_working_table = self.make_grid(1, options, git, &file_names, rows.clone(), &drender);
  111. // If we can’t fit everything in a grid 100 columns wide, then
  112. // something has gone seriously awry
  113. for column_count in 2..100 {
  114. let grid = self.make_grid(column_count, options, git, &file_names, rows.clone(), &drender);
  115. let the_grid_fits = {
  116. let d = grid.fit_into_columns(column_count);
  117. d.is_complete() && d.width() <= self.grid.console_width
  118. };
  119. if the_grid_fits {
  120. last_working_table = grid;
  121. }
  122. else {
  123. // If we’ve figured out how many columns can fit in the user’s
  124. // terminal, and it turns out there aren’t enough rows to
  125. // make it worthwhile, then just resort to the lines view.
  126. if let RowThreshold::MinimumRows(thresh) = self.row_threshold {
  127. if last_working_table.fit_into_columns(column_count - 1).row_count() < thresh {
  128. return None;
  129. }
  130. }
  131. return Some((last_working_table, column_count - 1));
  132. }
  133. }
  134. None
  135. }
  136. fn make_table<'t>(&'a self, options: &'a TableOptions, mut git: Option<&'a GitCache>, drender: &DetailsRender) -> (Table<'a>, Vec<DetailsRow>) {
  137. match (git, self.dir) {
  138. (Some(g), Some(d)) => if !g.has_anything_for(&d.path) { git = None },
  139. (Some(g), None) => if !self.files.iter().any(|f| g.has_anything_for(&f.path)) { git = None },
  140. (None, _) => {/* Keep Git how it is */},
  141. }
  142. let mut table = Table::new(options, git, self.colours);
  143. let mut rows = Vec::new();
  144. if self.details.header {
  145. let row = table.header_row();
  146. table.add_widths(&row);
  147. rows.push(drender.render_header(row));
  148. }
  149. (table, rows)
  150. }
  151. fn make_grid(&'a self, column_count: usize, options: &'a TableOptions, git: Option<&GitCache>, file_names: &[TextCell], rows: Vec<TableRow>, drender: &DetailsRender) -> grid::Grid {
  152. let mut tables = Vec::new();
  153. for _ in 0 .. column_count {
  154. tables.push(self.make_table(options, git, drender));
  155. }
  156. let mut num_cells = rows.len();
  157. if self.details.header {
  158. num_cells += column_count;
  159. }
  160. let original_height = divide_rounding_up(rows.len(), column_count);
  161. let height = divide_rounding_up(num_cells, column_count);
  162. for (i, (file_name, row)) in file_names.iter().zip(rows.into_iter()).enumerate() {
  163. let index = if self.grid.across {
  164. i % column_count
  165. }
  166. else {
  167. i / original_height
  168. };
  169. let (ref mut table, ref mut rows) = tables[index];
  170. table.add_widths(&row);
  171. let details_row = drender.render_file(row, file_name.clone(), TreeParams::new(TreeDepth::root(), false));
  172. rows.push(details_row);
  173. }
  174. let columns: Vec<_> = tables.into_iter().map(|(table, details_rows)| {
  175. drender.iterate_with_table(table, details_rows).collect::<Vec<_>>()
  176. }).collect();
  177. let direction = if self.grid.across { grid::Direction::LeftToRight }
  178. else { grid::Direction::TopToBottom };
  179. let mut grid = grid::Grid::new(grid::GridOptions {
  180. direction: direction,
  181. filling: grid::Filling::Spaces(4),
  182. });
  183. if self.grid.across {
  184. for row in 0 .. height {
  185. for column in &columns {
  186. if row < column.len() {
  187. let cell = grid::Cell {
  188. contents: ANSIStrings(&column[row].contents).to_string(),
  189. width: *column[row].width,
  190. };
  191. grid.add(cell);
  192. }
  193. }
  194. }
  195. }
  196. else {
  197. for column in &columns {
  198. for cell in column.iter() {
  199. let cell = grid::Cell {
  200. contents: ANSIStrings(&cell.contents).to_string(),
  201. width: *cell.width,
  202. };
  203. grid.add(cell);
  204. }
  205. }
  206. }
  207. grid
  208. }
  209. }
  210. fn divide_rounding_up(a: usize, b: usize) -> usize {
  211. let mut result = a / b;
  212. if a % b != 0 { result += 1; }
  213. result
  214. }
  215. fn file_has_xattrs(file: &File) -> bool {
  216. match file.path.attributes() {
  217. Ok(attrs) => !attrs.is_empty(),
  218. Err(_) => false,
  219. }
  220. }