grid_details.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. //! The grid-details view lists several details views side-by-side.
  2. use std::io::{self, Write};
  3. use ansiterm::ANSIStrings;
  4. use term_grid as grid;
  5. use crate::fs::feature::git::GitCache;
  6. use crate::fs::filter::FileFilter;
  7. use crate::fs::{Dir, File};
  8. use crate::output::cell::{DisplayWidth, TextCell};
  9. use crate::output::details::{
  10. Options as DetailsOptions, Render as DetailsRender, Row as DetailsRow,
  11. };
  12. use crate::output::file_name::Options as FileStyle;
  13. use crate::output::file_name::{EmbedHyperlinks, ShowIcons};
  14. use crate::output::grid::Options as GridOptions;
  15. use crate::output::table::{Options as TableOptions, Row as TableRow, Table};
  16. use crate::output::tree::{TreeDepth, TreeParams};
  17. use crate::theme::Theme;
  18. #[derive(PartialEq, Eq, Debug)]
  19. pub struct Options {
  20. pub grid: GridOptions,
  21. pub details: DetailsOptions,
  22. pub row_threshold: RowThreshold,
  23. }
  24. impl Options {
  25. pub fn to_details_options(&self) -> &DetailsOptions {
  26. &self.details
  27. }
  28. }
  29. /// The grid-details view can be configured to revert to just a details view
  30. /// (with one column) if it wouldn’t produce enough rows of output.
  31. ///
  32. /// Doing this makes the resulting output look a bit better: when listing a
  33. /// small directory of four files in four columns, the files just look spaced
  34. /// out and it’s harder to see what’s going on. So it can be enabled just for
  35. /// larger directory listings.
  36. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  37. pub enum RowThreshold {
  38. /// Only use grid-details view if it would result in at least this many
  39. /// rows of output.
  40. MinimumRows(usize),
  41. /// Use the grid-details view no matter what.
  42. AlwaysGrid,
  43. }
  44. pub struct Render<'a> {
  45. /// The directory that’s being rendered here.
  46. /// We need this to know which columns to put in the output.
  47. pub dir: Option<&'a Dir>,
  48. /// The files that have been read from the directory. They should all
  49. /// hold a reference to it.
  50. pub files: Vec<File<'a>>,
  51. /// How to colour various pieces of text.
  52. pub theme: &'a Theme,
  53. /// How to format filenames.
  54. pub file_style: &'a FileStyle,
  55. /// The grid part of the grid-details view.
  56. pub grid: &'a GridOptions,
  57. /// The details part of the grid-details view.
  58. pub details: &'a DetailsOptions,
  59. /// How to filter files after listing a directory. The files in this
  60. /// render will already have been filtered and sorted, but any directories
  61. /// that we recurse into will have to have this applied.
  62. pub filter: &'a FileFilter,
  63. /// The minimum number of rows that there need to be before grid-details
  64. /// mode is activated.
  65. pub row_threshold: RowThreshold,
  66. /// Whether we are skipping Git-ignored files.
  67. pub git_ignoring: bool,
  68. pub git: Option<&'a GitCache>,
  69. pub console_width: usize,
  70. }
  71. impl<'a> Render<'a> {
  72. /// Create a temporary Details render that gets used for the columns of
  73. /// the grid-details render that’s being generated.
  74. ///
  75. /// This includes an empty files vector because the files get added to
  76. /// the table in *this* file, not in details: we only want to insert every
  77. /// *n* files into each column’s table, not all of them.
  78. fn details_for_column(&self) -> DetailsRender<'a> {
  79. #[rustfmt::skip]
  80. return DetailsRender {
  81. dir: self.dir,
  82. files: Vec::new(),
  83. theme: self.theme,
  84. file_style: self.file_style,
  85. opts: self.details,
  86. recurse: None,
  87. filter: self.filter,
  88. git_ignoring: self.git_ignoring,
  89. git: self.git,
  90. };
  91. }
  92. /// Create a Details render for when this grid-details render doesn’t fit
  93. /// in the terminal (or something has gone wrong) and we have given up, or
  94. /// when the user asked for a grid-details view but the terminal width is
  95. /// not available, so we downgrade.
  96. pub fn give_up(self) -> DetailsRender<'a> {
  97. #[rustfmt::skip]
  98. return DetailsRender {
  99. dir: self.dir,
  100. files: self.files,
  101. theme: self.theme,
  102. file_style: self.file_style,
  103. opts: self.details,
  104. recurse: None,
  105. filter: self.filter,
  106. git_ignoring: self.git_ignoring,
  107. git: self.git,
  108. };
  109. }
  110. // This doesn’t take an IgnoreCache even though the details one does
  111. // because grid-details has no tree view.
  112. pub fn render<W: Write>(mut self, w: &mut W) -> io::Result<()> {
  113. if let Some((grid, width)) = self.find_fitting_grid() {
  114. write!(w, "{}", grid.fit_into_columns(width))
  115. } else {
  116. self.give_up().render(w)
  117. }
  118. }
  119. pub fn find_fitting_grid(&mut self) -> Option<(grid::Grid, grid::Width)> {
  120. let options = self
  121. .details
  122. .table
  123. .as_ref()
  124. .expect("Details table options not given!");
  125. let drender = self.details_for_column();
  126. let (first_table, _) = self.make_table(options, &drender);
  127. let rows = self
  128. .files
  129. .iter()
  130. .map(|file| first_table.row_for_file(file, drender.show_xattr_hint(file)))
  131. .collect::<Vec<_>>();
  132. let file_names = self
  133. .files
  134. .iter()
  135. .map(|file| {
  136. let filename = self.file_style.for_file(file, self.theme);
  137. let contents = filename.paint();
  138. #[rustfmt::skip]
  139. let width = match (filename.options.embed_hyperlinks, filename.options.show_icons) {
  140. (EmbedHyperlinks::On, ShowIcons::On(spacing)) => filename.bare_width() + 1 + (spacing as usize),
  141. (EmbedHyperlinks::On, ShowIcons::Off) => filename.bare_width(),
  142. (EmbedHyperlinks::Off, _) => *contents.width(),
  143. };
  144. TextCell {
  145. contents,
  146. // with hyperlink escape sequences,
  147. // the actual *contents.width() is larger than actually needed, so we take only the filename
  148. width: DisplayWidth::from(width),
  149. }
  150. })
  151. .collect::<Vec<_>>();
  152. let mut last_working_grid = self.make_grid(1, options, &file_names, rows.clone(), &drender);
  153. if file_names.len() == 1 {
  154. return Some((last_working_grid, 1));
  155. }
  156. // If we can’t fit everything in a grid 100 columns wide, then
  157. // something has gone seriously awry
  158. for column_count in 2..100 {
  159. let grid = self.make_grid(column_count, options, &file_names, rows.clone(), &drender);
  160. let the_grid_fits = {
  161. let d = grid.fit_into_columns(column_count);
  162. d.width() <= self.console_width
  163. };
  164. if the_grid_fits {
  165. last_working_grid = grid;
  166. }
  167. if !the_grid_fits || column_count == file_names.len() {
  168. let last_column_count = if the_grid_fits {
  169. column_count
  170. } else {
  171. column_count - 1
  172. };
  173. // If we’ve figured out how many columns can fit in the user’s terminal,
  174. // and it turns out there aren’t enough rows to make it worthwhile
  175. // (according to EZA_GRID_ROWS), then just resort to the lines view.
  176. if let RowThreshold::MinimumRows(thresh) = self.row_threshold {
  177. if last_working_grid
  178. .fit_into_columns(last_column_count)
  179. .row_count()
  180. < thresh
  181. {
  182. return None;
  183. }
  184. }
  185. return Some((last_working_grid, last_column_count));
  186. }
  187. }
  188. None
  189. }
  190. fn make_table(
  191. &mut self,
  192. options: &'a TableOptions,
  193. drender: &DetailsRender<'_>,
  194. ) -> (Table<'a>, Vec<DetailsRow>) {
  195. match (self.git, self.dir) {
  196. (Some(g), Some(d)) => {
  197. if !g.has_anything_for(&d.path) {
  198. self.git = None;
  199. }
  200. }
  201. (Some(g), None) => {
  202. if !self.files.iter().any(|f| g.has_anything_for(&f.path)) {
  203. self.git = None;
  204. }
  205. }
  206. (None, _) => { /* Keep Git how it is */ }
  207. }
  208. let mut table = Table::new(options, self.git, self.theme);
  209. let mut rows = Vec::new();
  210. if self.details.header {
  211. let row = table.header_row();
  212. table.add_widths(&row);
  213. rows.push(drender.render_header(row));
  214. }
  215. (table, rows)
  216. }
  217. fn make_grid(
  218. &mut self,
  219. column_count: usize,
  220. options: &'a TableOptions,
  221. file_names: &[TextCell],
  222. rows: Vec<TableRow>,
  223. drender: &DetailsRender<'_>,
  224. ) -> grid::Grid {
  225. let mut tables = Vec::new();
  226. for _ in 0..column_count {
  227. tables.push(self.make_table(options, drender));
  228. }
  229. let mut num_cells = rows.len();
  230. if self.details.header {
  231. num_cells += column_count;
  232. }
  233. let original_height = divide_rounding_up(rows.len(), column_count);
  234. let height = divide_rounding_up(num_cells, column_count);
  235. for (i, (file_name, row)) in file_names.iter().zip(rows).enumerate() {
  236. let index = if self.grid.across {
  237. i % column_count
  238. } else {
  239. i / original_height
  240. };
  241. let (ref mut table, ref mut rows) = tables[index];
  242. table.add_widths(&row);
  243. let details_row = drender.render_file(
  244. row,
  245. file_name.clone(),
  246. TreeParams::new(TreeDepth::root(), false),
  247. );
  248. rows.push(details_row);
  249. }
  250. let columns = tables
  251. .into_iter()
  252. .map(|(table, details_rows)| {
  253. drender
  254. .iterate_with_table(table, details_rows)
  255. .collect::<Vec<_>>()
  256. })
  257. .collect::<Vec<_>>();
  258. let direction = if self.grid.across {
  259. grid::Direction::LeftToRight
  260. } else {
  261. grid::Direction::TopToBottom
  262. };
  263. let filling = grid::Filling::Spaces(4);
  264. let mut grid = grid::Grid::new(grid::GridOptions { direction, filling });
  265. if self.grid.across {
  266. for row in 0..height {
  267. for column in &columns {
  268. if row < column.len() {
  269. let cell = grid::Cell {
  270. contents: ANSIStrings(&column[row].contents).to_string(),
  271. width: *column[row].width,
  272. };
  273. grid.add(cell);
  274. }
  275. }
  276. }
  277. } else {
  278. for column in &columns {
  279. for cell in column {
  280. let cell = grid::Cell {
  281. contents: ANSIStrings(&cell.contents).to_string(),
  282. width: *cell.width,
  283. };
  284. grid.add(cell);
  285. }
  286. }
  287. }
  288. grid
  289. }
  290. }
  291. fn divide_rounding_up(a: usize, b: usize) -> usize {
  292. let mut result = a / b;
  293. if a % b != 0 {
  294. result += 1;
  295. }
  296. result
  297. }