1
0

cell.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. //! The `TextCell` type for the details and lines views.
  2. use std::iter::Sum;
  3. use std::ops::{Add, Deref, DerefMut};
  4. use ansi_term::{Style, ANSIString, ANSIStrings};
  5. use unicode_width::UnicodeWidthStr;
  6. /// An individual cell that holds text in a table, used in the details and
  7. /// lines views to store ANSI-terminal-formatted data before it is printed.
  8. ///
  9. /// A text cell is made up of zero or more strings coupled with the
  10. /// pre-computed length of all the strings combined. When constructing details
  11. /// or grid-details tables, the length will have to be queried multiple times,
  12. /// so it makes sense to cache it.
  13. ///
  14. /// (This used to be called `Cell`, but was renamed because there’s a Rust
  15. /// type by that name too.)
  16. #[derive(PartialEq, Debug, Clone, Default)]
  17. pub struct TextCell {
  18. /// The contents of this cell, as a vector of ANSI-styled strings.
  19. pub contents: TextCellContents,
  20. /// The Unicode “display width” of this cell.
  21. pub width: DisplayWidth,
  22. }
  23. impl Deref for TextCell {
  24. type Target = TextCellContents;
  25. fn deref(&self) -> &Self::Target {
  26. &self.contents
  27. }
  28. }
  29. impl TextCell {
  30. /// Creates a new text cell that holds the given text in the given style,
  31. /// computing the Unicode width of the text.
  32. pub fn paint(style: Style, text: String) -> Self {
  33. let width = DisplayWidth::from(&*text);
  34. Self {
  35. contents: vec![ style.paint(text) ].into(),
  36. width,
  37. }
  38. }
  39. /// Creates a new text cell that holds the given text in the given style,
  40. /// computing the Unicode width of the text. (This could be merged with
  41. /// `paint`, but.)
  42. pub fn paint_str(style: Style, text: &'static str) -> Self {
  43. let width = DisplayWidth::from(text);
  44. Self {
  45. contents: vec![ style.paint(text) ].into(),
  46. width,
  47. }
  48. }
  49. /// Creates a new “blank” text cell that contains a single hyphen in the
  50. /// given style, which should be the “punctuation” style from a `Colours`
  51. /// value.
  52. ///
  53. /// This is used in place of empty table cells, as it is easier to read
  54. /// tabular data when there is *something* in each cell.
  55. pub fn blank(style: Style) -> Self {
  56. Self {
  57. contents: vec![ style.paint("-") ].into(),
  58. width: DisplayWidth::from(1),
  59. }
  60. }
  61. /// Adds the given number of unstyled spaces after this cell.
  62. ///
  63. /// This method allocates a `String` to hold the spaces.
  64. pub fn add_spaces(&mut self, count: usize) {
  65. use std::iter::repeat;
  66. (*self.width) += count;
  67. let spaces: String = repeat(' ').take(count).collect();
  68. self.contents.0.push(Style::default().paint(spaces));
  69. }
  70. /// Adds the contents of another `ANSIString` to the end of this cell.
  71. pub fn push(&mut self, string: ANSIString<'static>, extra_width: usize) {
  72. self.contents.0.push(string);
  73. (*self.width) += extra_width;
  74. }
  75. /// Adds all the contents of another `TextCell` to the end of this cell.
  76. pub fn append(&mut self, other: Self) {
  77. (*self.width) += *other.width;
  78. self.contents.0.extend(other.contents.0);
  79. }
  80. }
  81. // I’d like to eventually abstract cells so that instead of *every* cell
  82. // storing a vector, only variable-length cells would, and individual cells
  83. // would just store an array of a fixed length (which would usually be just 1
  84. // or 2), which wouldn’t require a heap allocation.
  85. //
  86. // For examples, look at the `render_*` methods in the `Table` object in the
  87. // details view:
  88. //
  89. // - `render_blocks`, `inode`, and `links` will always return a
  90. // one-string-long TextCell;
  91. // - `render_size` will return one or two strings in a TextCell, depending on
  92. // the size and whether one is present;
  93. // - `render_permissions` will return ten or eleven strings;
  94. // - `filename` and `symlink_filename` in the output module root return six or
  95. // five strings.
  96. //
  97. // In none of these cases are we dealing with a *truly variable* number of
  98. // strings: it is only when the strings are concatenated together do we need a
  99. // growable, heap-allocated buffer.
  100. //
  101. // So it would be nice to abstract the `TextCell` type so instead of a `Vec`,
  102. // it can use anything of type `T: IntoIterator<Item=ANSIString<’static>>`.
  103. // This would allow us to still hold all the data, but allocate less.
  104. //
  105. // But exa still has bugs and I need to fix those first :(
  106. /// The contents of a text cell, as a vector of ANSI-styled strings.
  107. ///
  108. /// It’s possible to use this type directly in the case where you want a
  109. /// `TextCell` but aren’t concerned with tracking its width, because it occurs
  110. /// in the final cell of a table or grid and there’s no point padding it. This
  111. /// happens when dealing with file names.
  112. #[derive(PartialEq, Debug, Clone, Default)]
  113. pub struct TextCellContents(Vec<ANSIString<'static>>);
  114. impl From<Vec<ANSIString<'static>>> for TextCellContents {
  115. fn from(strings: Vec<ANSIString<'static>>) -> Self {
  116. Self(strings)
  117. }
  118. }
  119. impl Deref for TextCellContents {
  120. type Target = [ANSIString<'static>];
  121. fn deref(&self) -> &Self::Target {
  122. &*self.0
  123. }
  124. }
  125. // No DerefMut implementation here — it would be publicly accessible, and as
  126. // the contents only get changed in this module, the mutators in the struct
  127. // above can just access the value directly.
  128. impl TextCellContents {
  129. /// Produces an `ANSIStrings` value that can be used to print the styled
  130. /// values of this cell as an ANSI-terminal-formatted string.
  131. pub fn strings(&self) -> ANSIStrings {
  132. ANSIStrings(&self.0)
  133. }
  134. /// Calculates the width that a cell with these contents would take up, by
  135. /// counting the number of characters in each unformatted ANSI string.
  136. pub fn width(&self) -> DisplayWidth {
  137. self.0.iter()
  138. .map(|anstr| DisplayWidth::from(&**anstr))
  139. .sum()
  140. }
  141. /// Promotes these contents to a full cell containing them alongside
  142. /// their calculated width.
  143. pub fn promote(self) -> TextCell {
  144. TextCell {
  145. width: self.width(),
  146. contents: self,
  147. }
  148. }
  149. }
  150. /// The Unicode “display width” of a string.
  151. ///
  152. /// This is related to the number of *graphemes* of a string, rather than the
  153. /// number of *characters*, or *bytes*: although most characters are one
  154. /// column wide, a few can be two columns wide, and this is important to note
  155. /// when calculating widths for displaying tables in a terminal.
  156. ///
  157. /// This type is used to ensure that the width, rather than the length, is
  158. /// used when constructing a `TextCell` — it’s too easy to write something
  159. /// like `file_name.len()` and assume it will work!
  160. ///
  161. /// It has `From` impls that convert an input string or fixed with to values
  162. /// of this type, and will `Deref` to the contained `usize` value.
  163. #[derive(PartialEq, Debug, Clone, Copy, Default)]
  164. pub struct DisplayWidth(usize);
  165. impl<'a> From<&'a str> for DisplayWidth {
  166. fn from(input: &'a str) -> Self {
  167. Self(UnicodeWidthStr::width(input))
  168. }
  169. }
  170. impl From<usize> for DisplayWidth {
  171. fn from(width: usize) -> Self {
  172. Self(width)
  173. }
  174. }
  175. impl Deref for DisplayWidth {
  176. type Target = usize;
  177. fn deref(&self) -> &Self::Target {
  178. &self.0
  179. }
  180. }
  181. impl DerefMut for DisplayWidth {
  182. fn deref_mut(&mut self) -> &mut Self::Target {
  183. &mut self.0
  184. }
  185. }
  186. impl Add for DisplayWidth {
  187. type Output = Self;
  188. fn add(self, rhs: Self) -> Self::Output {
  189. Self(self.0 + rhs.0)
  190. }
  191. }
  192. impl Add<usize> for DisplayWidth {
  193. type Output = Self;
  194. fn add(self, rhs: usize) -> Self::Output {
  195. Self(self.0 + rhs)
  196. }
  197. }
  198. impl Sum for DisplayWidth {
  199. fn sum<I>(iter: I) -> Self
  200. where I: Iterator<Item = Self>
  201. {
  202. iter.fold(Self(0), Add::add)
  203. }
  204. }
  205. #[cfg(test)]
  206. mod width_unit_test {
  207. use super::DisplayWidth;
  208. #[test]
  209. fn empty_string() {
  210. let cell = DisplayWidth::from("");
  211. assert_eq!(*cell, 0);
  212. }
  213. #[test]
  214. fn test_string() {
  215. let cell = DisplayWidth::from("Diss Playwidth");
  216. assert_eq!(*cell, 14);
  217. }
  218. #[test]
  219. fn addition() {
  220. let cell_one = DisplayWidth::from("/usr/bin/");
  221. let cell_two = DisplayWidth::from("drinking");
  222. assert_eq!(*(cell_one + cell_two), 17);
  223. }
  224. #[test]
  225. fn addition_usize() {
  226. let cell = DisplayWidth::from("/usr/bin/");
  227. assert_eq!(*(cell + 8), 17);
  228. }
  229. }