grid_details.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. //! The grid-details view lists several details views side-by-side.
  2. use std::io::{Write, Result as IOResult};
  3. use ansi_term::{ANSIGenericString, ANSIStrings};
  4. use term_grid as grid;
  5. use fs::{Dir, File};
  6. use fs::feature::git::GitCache;
  7. use fs::feature::xattr::FileAttributes;
  8. use fs::filter::FileFilter;
  9. use style::Colours;
  10. use output::cell::TextCell;
  11. use output::details::{Options as DetailsOptions, Row as DetailsRow, Render as DetailsRender};
  12. use output::grid::Options as GridOptions;
  13. use output::file_name::FileStyle;
  14. use output::table::{Table, Row as TableRow, Options as TableOptions};
  15. use output::tree::{TreeParams, TreeDepth};
  16. use output::icons::painted_icon;
  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,
  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. // This doesn’t take an IgnoreCache even though the details one does
  93. // because grid-details has no tree view.
  94. pub fn render<W: Write>(self, git: Option<&GitCache>, w: &mut W) -> IOResult<()> {
  95. if let Some((grid, width)) = self.find_fitting_grid(git) {
  96. write!(w, "{}", grid.fit_into_columns(width))
  97. }
  98. else {
  99. self.give_up().render(git, None, w)
  100. }
  101. }
  102. pub fn find_fitting_grid(&self, git: Option<&GitCache>) -> Option<(grid::Grid, grid::Width)> {
  103. let options = self.details.table.as_ref().expect("Details table options not given!");
  104. let drender = self.details();
  105. let (first_table, _) = self.make_table(options, git, &drender);
  106. let rows = self.files.iter()
  107. .map(|file| first_table.row_for_file(file, file_has_xattrs(file)))
  108. .collect::<Vec<TableRow>>();
  109. let file_names = self.files.iter()
  110. .map(|file| {
  111. if self.details.icons {
  112. let mut icon_cell = TextCell::default();
  113. icon_cell.push(ANSIGenericString::from(painted_icon(&file, &self.style)), 2);
  114. let file_cell = self.style.for_file(file, self.colours).paint().promote();
  115. icon_cell.append(file_cell);
  116. icon_cell
  117. } else {
  118. self.style.for_file(file, self.colours).paint().promote()
  119. }
  120. })
  121. .collect::<Vec<TextCell>>();
  122. let mut last_working_table = self.make_grid(1, options, git, &file_names, rows.clone(), &drender);
  123. // If we can’t fit everything in a grid 100 columns wide, then
  124. // something has gone seriously awry
  125. for column_count in 2..100 {
  126. let grid = self.make_grid(column_count, options, git, &file_names, rows.clone(), &drender);
  127. let the_grid_fits = {
  128. let d = grid.fit_into_columns(column_count);
  129. d.is_complete() && d.width() <= self.grid.console_width
  130. };
  131. if the_grid_fits {
  132. last_working_table = grid;
  133. }
  134. else {
  135. // If we’ve figured out how many columns can fit in the user’s
  136. // terminal, and it turns out there aren’t enough rows to
  137. // make it worthwhile, then just resort to the lines view.
  138. if let RowThreshold::MinimumRows(thresh) = self.row_threshold {
  139. if last_working_table.fit_into_columns(column_count - 1).row_count() < thresh {
  140. return None;
  141. }
  142. }
  143. return Some((last_working_table, column_count - 1));
  144. }
  145. }
  146. None
  147. }
  148. fn make_table(&'a self, options: &'a TableOptions, mut git: Option<&'a GitCache>, drender: &DetailsRender) -> (Table<'a>, Vec<DetailsRow>) {
  149. match (git, self.dir) {
  150. (Some(g), Some(d)) => if !g.has_anything_for(&d.path) { git = None },
  151. (Some(g), None) => if !self.files.iter().any(|f| g.has_anything_for(&f.path)) { git = None },
  152. (None, _) => {/* Keep Git how it is */},
  153. }
  154. let mut table = Table::new(options, git, self.colours);
  155. let mut rows = Vec::new();
  156. if self.details.header {
  157. let row = table.header_row();
  158. table.add_widths(&row);
  159. rows.push(drender.render_header(row));
  160. }
  161. (table, rows)
  162. }
  163. fn make_grid(&'a self, column_count: usize, options: &'a TableOptions, git: Option<&GitCache>, file_names: &[TextCell], rows: Vec<TableRow>, drender: &DetailsRender) -> grid::Grid {
  164. let mut tables = Vec::new();
  165. for _ in 0 .. column_count {
  166. tables.push(self.make_table(options, git, drender));
  167. }
  168. let mut num_cells = rows.len();
  169. if self.details.header {
  170. num_cells += column_count;
  171. }
  172. let original_height = divide_rounding_up(rows.len(), column_count);
  173. let height = divide_rounding_up(num_cells, column_count);
  174. for (i, (file_name, row)) in file_names.iter().zip(rows.into_iter()).enumerate() {
  175. let index = if self.grid.across {
  176. i % column_count
  177. }
  178. else {
  179. i / original_height
  180. };
  181. let (ref mut table, ref mut rows) = tables[index];
  182. table.add_widths(&row);
  183. let details_row = drender.render_file(row, file_name.clone(), TreeParams::new(TreeDepth::root(), false));
  184. rows.push(details_row);
  185. }
  186. let columns: Vec<_> = tables.into_iter().map(|(table, details_rows)| {
  187. drender.iterate_with_table(table, details_rows).collect::<Vec<_>>()
  188. }).collect();
  189. let direction = if self.grid.across { grid::Direction::LeftToRight }
  190. else { grid::Direction::TopToBottom };
  191. let mut grid = grid::Grid::new(grid::GridOptions {
  192. direction,
  193. filling: grid::Filling::Spaces(4),
  194. });
  195. if self.grid.across {
  196. for row in 0 .. height {
  197. for column in &columns {
  198. if row < column.len() {
  199. let cell = grid::Cell {
  200. contents: ANSIStrings(&column[row].contents).to_string(),
  201. width: *column[row].width,
  202. };
  203. grid.add(cell);
  204. }
  205. }
  206. }
  207. }
  208. else {
  209. for column in &columns {
  210. for cell in column.iter() {
  211. let cell = grid::Cell {
  212. contents: ANSIStrings(&cell.contents).to_string(),
  213. width: *cell.width,
  214. };
  215. grid.add(cell);
  216. }
  217. }
  218. }
  219. grid
  220. }
  221. }
  222. fn divide_rounding_up(a: usize, b: usize) -> usize {
  223. let mut result = a / b;
  224. if a % b != 0 { result += 1; }
  225. result
  226. }
  227. fn file_has_xattrs(file: &File) -> bool {
  228. match file.path.attributes() {
  229. Ok(attrs) => !attrs.is_empty(),
  230. Err(_) => false,
  231. }
  232. }