cell.rs 8.3 KB

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