grid_details.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // SPDX-FileCopyrightText: 2024 Christina Sørensen
  2. // SPDX-License-Identifier: EUPL-1.2
  3. //
  4. // SPDX-FileCopyrightText: 2023-2024 Christina Sørensen, eza contributors
  5. // SPDX-FileCopyrightText: 2014 Benjamin Sago
  6. // SPDX-License-Identifier: MIT
  7. //! The grid-details view lists several details views side-by-side.
  8. use std::io::{self, Write};
  9. use ansi_width;
  10. use grid::{Direction, Filling, Grid, GridOptions};
  11. use term_grid as grid;
  12. use crate::fs::feature::git::GitCache;
  13. use crate::fs::filter::FileFilter;
  14. use crate::fs::{Dir, File};
  15. use crate::output::cell::TextCell;
  16. use crate::output::color_scale::ColorScaleInformation;
  17. use crate::output::details::{Options as DetailsOptions, Render as DetailsRender};
  18. use crate::output::file_name::Options as FileStyle;
  19. use crate::output::table::{Options as TableOptions, Table};
  20. use crate::theme::Theme;
  21. #[derive(PartialEq, Eq, Debug)]
  22. pub struct Options {
  23. pub details: DetailsOptions,
  24. pub row_threshold: RowThreshold,
  25. }
  26. impl Options {
  27. #[must_use] pub fn to_details_options(&self) -> &DetailsOptions {
  28. &self.details
  29. }
  30. }
  31. /// The grid-details view can be configured to revert to just a details view
  32. /// (with one column) if it wouldn’t produce enough rows of output.
  33. ///
  34. /// Doing this makes the resulting output look a bit better: when listing a
  35. /// small directory of four files in four columns, the files just look spaced
  36. /// out and it’s harder to see what’s going on. So it can be enabled just for
  37. /// larger directory listings.
  38. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  39. pub enum RowThreshold {
  40. /// Only use grid-details view if it would result in at least this many
  41. /// rows of output.
  42. MinimumRows(usize),
  43. /// Use the grid-details view no matter what.
  44. AlwaysGrid,
  45. }
  46. pub struct Render<'a> {
  47. /// The directory that’s being rendered here.
  48. /// We need this to know which columns to put in the output.
  49. pub dir: Option<&'a Dir>,
  50. /// The files that have been read from the directory. They should all
  51. /// hold a reference to it.
  52. pub files: Vec<File<'a>>,
  53. /// How to colour various pieces of text.
  54. pub theme: &'a Theme,
  55. /// How to format filenames.
  56. pub file_style: &'a FileStyle,
  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. #[allow(dead_code)]
  66. pub row_threshold: RowThreshold,
  67. /// Whether we are skipping Git-ignored files.
  68. pub git_ignoring: bool,
  69. pub git: Option<&'a GitCache>,
  70. pub console_width: usize,
  71. pub git_repos: bool,
  72. }
  73. impl<'a> Render<'a> {
  74. /// Create a temporary Details render that gets used for the columns of
  75. /// the grid-details render that’s being generated.
  76. ///
  77. /// This includes an empty files vector because the files get added to
  78. /// the table in *this* file, not in details: we only want to insert every
  79. /// *n* files into each column’s table, not all of them.
  80. fn details_for_column(&self) -> DetailsRender<'a> {
  81. #[rustfmt::skip]
  82. return DetailsRender {
  83. dir: self.dir,
  84. files: Vec::new(),
  85. theme: self.theme,
  86. file_style: self.file_style,
  87. opts: self.details,
  88. recurse: None,
  89. filter: self.filter,
  90. git_ignoring: self.git_ignoring,
  91. git: self.git,
  92. git_repos: self.git_repos,
  93. };
  94. }
  95. // This doesn’t take an IgnoreCache even though the details one does
  96. // because grid-details has no tree view.
  97. pub fn render<W: Write>(mut self, w: &mut W) -> io::Result<()> {
  98. let options = self
  99. .details
  100. .table
  101. .as_ref()
  102. .expect("Details table options not given!");
  103. let drender = self.details_for_column();
  104. let color_scale_info = ColorScaleInformation::from_color_scale(
  105. self.details.color_scale,
  106. &self.files,
  107. self.filter.dot_filter,
  108. self.git,
  109. self.git_ignoring,
  110. None,
  111. );
  112. let mut table = self.make_table(options);
  113. // It is important to collect all these rows _before_ turning them into
  114. // cells, because the width calculations need to consider all rows
  115. // before each row is turned into a string.
  116. let rows: Vec<_> = self
  117. .files
  118. .iter()
  119. .map(|file| {
  120. let row = table.row_for_file(file, drender.show_xattr_hint(file), color_scale_info);
  121. table.add_widths(&row);
  122. row
  123. })
  124. .collect();
  125. let cells = rows
  126. .into_iter()
  127. .zip(&self.files)
  128. .map(|(row, file)| {
  129. let filename = self
  130. .file_style
  131. .for_file(file, self.theme)
  132. .paint()
  133. .strings()
  134. .to_string();
  135. let details = table.render(row).strings().to_string();
  136. // This bit fixes a strange corner case. If there is a header,
  137. // then "Name" will be added to the header row. That means that
  138. // the filename column, should be at least 4 characters wide.
  139. // Therefore we pad the filenames with some spaces. We have to
  140. // use ansi_width here, because the filename might contain some
  141. // styling.
  142. let padding = " ".repeat(if self.details.header {
  143. 4usize.saturating_sub(ansi_width::ansi_width(&filename))
  144. } else {
  145. 0
  146. });
  147. format!("{details} {filename}{padding}")
  148. })
  149. .collect();
  150. let grid = Grid::new(
  151. cells,
  152. GridOptions {
  153. filling: Filling::Spaces(4),
  154. direction: Direction::TopToBottom,
  155. width: self.console_width,
  156. },
  157. );
  158. // If a minimum grid rows threshold has been set
  159. // via the `EZA_GRID_ROWS` environment variable
  160. // and the grid is going to get rendered with fewer rows,
  161. // then render a details list view instead.
  162. if let RowThreshold::MinimumRows(minimum_rows) = self.row_threshold {
  163. if grid.row_count() < minimum_rows {
  164. let Self {
  165. dir,
  166. files,
  167. theme,
  168. file_style,
  169. details: opts,
  170. filter,
  171. git_ignoring,
  172. git,
  173. git_repos,
  174. ..
  175. } = self;
  176. let r = DetailsRender {
  177. dir,
  178. files,
  179. theme,
  180. file_style,
  181. opts,
  182. recurse: None,
  183. filter,
  184. git_ignoring,
  185. git,
  186. git_repos,
  187. };
  188. return r.render(w);
  189. }
  190. }
  191. if self.details.header {
  192. let row = table.header_row();
  193. let name = TextCell::paint_str(self.theme.ui.header.unwrap_or_default(), "Name")
  194. .strings()
  195. .to_string();
  196. let s = table.render(row).strings().to_string();
  197. let combined_header = format!("{s} {name}");
  198. let header_width = ansi_width::ansi_width(&combined_header);
  199. for column_width in grid.column_widths() {
  200. let padding = " ".repeat((column_width + 4).saturating_sub(header_width));
  201. write!(w, "{combined_header}{padding}")?;
  202. }
  203. writeln!(w)?;
  204. }
  205. write!(w, "{grid}")?;
  206. Ok(())
  207. }
  208. fn make_table(&mut self, options: &'a TableOptions) -> Table<'a> {
  209. match (self.git, self.dir) {
  210. (Some(g), Some(d)) => {
  211. if !g.has_anything_for(&d.path) {
  212. self.git = None;
  213. }
  214. }
  215. (Some(g), None) => {
  216. if !self.files.iter().any(|f| g.has_anything_for(&f.path)) {
  217. self.git = None;
  218. }
  219. }
  220. (None, _) => { /* Keep Git how it is */ }
  221. }
  222. let mut table = Table::new(options, self.git, self.theme, self.git_repos);
  223. // The header row will be printed separately, but it should be
  224. // considered for the width calculations.
  225. if self.details.header {
  226. let row = table.header_row();
  227. table.add_widths(&row);
  228. }
  229. table
  230. }
  231. }