提交 c911b5f6 编写于 作者: B Benjamin Sago

Replace Cells with growable TextCells

A recent change to ansi-term [1] means that `ANSIString`s can now hold either
owned *or* borrowed data (Rust calls this the Cow type). This means that we
can delay formatting ANSIStrings into ANSI-control-code-formatted strings
until it's absolutely necessary. The process for doing this was:

1. Replace the `Cell` type with a `TextCell` type that holds a vector of
   `ANSIString` values instead of a formatted string. It still does the
   width tracking.

2. Rework the details module's `render` functions to emit values of this
   type.

3. Similarly, rework the functions that produce cells containing filenames
   to use a `File` value's `name` field, which is an owned `String` that
   can now be re-used.

4. Update the printing, formatting, and width-calculating code in the
   details and grid-details views to produce a table by adding vectors
   together instead of adding strings together, delaying the formatting as
   long as it can.

This results in fewer allocations (as fewer `String` values are produced), and
makes the API tidier (as fewer `String` values are being passed around without
having their contents specified).

This also paves the way to Windows support, or at least support for
non-ANSI terminals: by delaying the time until strings are formatted,
it'll now be easier to change *how* they are formatted.

Casualties include:

- Bump to ansi_term v0.7.1, which impls `PartialEq` and `Debug` on
  `ANSIString`.
- The grid_details and lines views now need to take a vector of files, rather
  than a borrowed slice, so the filename cells produced now own the filename
  strings that get taken from files.
- Fixed the signature of `File#link_target` to specify that the
  file produced refers to the same directory, rather than some phantom
  directory with the same lifetime as the file. (This was wrong from the
  start, but it broke nothing until now)

References:

[1]: ansi-term@f6a6579ba8174de1cae64d181ec04af32ba2a4f0
上级 95c0d630
......@@ -2,13 +2,13 @@
name = "exa"
version = "0.4.0"
dependencies = [
"ansi_term 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"ansi_term 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"datetime 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
"getopts 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)",
"git2 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"lazy_static 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"locale 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
"natord 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
"num_cpus 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)",
......@@ -38,7 +38,7 @@ dependencies = [
[[package]]
name = "ansi_term"
version = "0.7.0"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
......@@ -92,7 +92,7 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"bitflags 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libgit2-sys 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
"url 0.2.38 (registry+https://github.com/rust-lang/crates.io-index)",
]
......@@ -118,7 +118,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "libc"
version = "0.2.2"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
......@@ -127,10 +127,10 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cmake 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libssh2-sys 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)",
"libz-sys 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"openssl-sys 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"openssl-sys 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)",
"pkg-config 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
......@@ -148,9 +148,9 @@ version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cmake 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libz-sys 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"openssl-sys 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"openssl-sys 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)",
"pkg-config 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
......@@ -162,7 +162,7 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"gcc 0.3.20 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"pkg-config 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
......@@ -185,7 +185,7 @@ name = "memchr"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
......@@ -208,7 +208,7 @@ version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
......@@ -222,10 +222,10 @@ dependencies = [
[[package]]
name = "openssl-sys"
version = "0.7.1"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libressl-pnacl-sys 2.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"pkg-config 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
......@@ -257,7 +257,7 @@ version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"advapi32-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
......@@ -346,7 +346,7 @@ name = "users"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
......
......@@ -7,7 +7,7 @@ authors = [ "ogham@bsago.me" ]
name = "exa"
[dependencies]
ansi_term = "0.7.0"
ansi_term = "0.7.1"
bitflags = "0.1"
datetime = "0.4.1"
getopts = "0.2.14"
......
......@@ -195,7 +195,7 @@ impl<'dir> File<'dir> {
/// If statting the file fails (usually because the file on the
/// other end doesn't exist), returns the *filename* of the file
/// that should be there.
pub fn link_target(&self) -> Result<File, String> {
pub fn link_target(&self) -> Result<File<'dir>, String> {
let path = match fs::read_link(&self.path) {
Ok(path) => path,
Err(_) => return Err(self.name.clone()),
......
......@@ -135,8 +135,8 @@ impl Exa {
match self.options.view {
View::Grid(g) => g.view(&files),
View::Details(d) => d.view(dir, files),
View::GridDetails(gd) => gd.view(dir, &files),
View::Lines(l) => l.view(&files),
View::GridDetails(gd) => gd.view(dir, files),
View::Lines(l) => l.view(files),
}
}
}
......
//! The `TextCell` type for the details and lines views.
use ansi_term::{Style, ANSIString, ANSIStrings};
use unicode_width::UnicodeWidthStr;
/// An individual cell that holds text in a table, used in the details and
/// lines views to store ANSI-terminal-formatted data before it is printed.
///
/// A text cell is made up of zero or more strings coupled with the
/// pre-computed length of all the strings combined. When constructing details
/// or grid-details tables, the length will have to be queried multiple times,
/// so it makes sense to cache it.
///
/// (This used to be called `Cell`, but was renamed because there’s a Rust
/// type by that name too.)
#[derive(PartialEq, Debug, Clone, Default)]
pub struct TextCell {
/// The contents of this cell, as a vector of ANSI-styled strings.
pub contents: TextCellContents,
/// The Unicode “display width” of this cell, in characters.
///
/// As with the `File` type’s width, this is related to the number of
/// *graphemes*, rather than *characters*, in the cell: most are 1 column
/// wide, but in some contexts, certain characters are two columns wide.
pub length: usize,
}
impl TextCell {
/// Creates a new text cell that holds the given text in the given style,
/// computing the Unicode width of the text.
pub fn paint(style: Style, text: String) -> Self {
TextCell {
length: text.width(),
contents: vec![ style.paint(text) ],
}
}
/// Creates a new text cell that holds the given text in the given style,
/// computing the Unicode width of the text. (This could be merged with
/// `paint`, but.)
pub fn paint_str(style: Style, text: &'static str) -> Self {
TextCell {
length: text.len(),
contents: vec![ style.paint(text) ],
}
}
/// Creates a new “blank” text cell that contains a single hyphen in the
/// given style, which should be the “punctuation” style from a `Colours`
/// value.
///
/// This is used in place of empty table cells, as it is easier to read
/// tabular data when there is *something* in each cell.
pub fn blank(style: Style) -> Self {
TextCell {
length: 1,
contents: vec![ style.paint("-") ],
}
}
/// Adds the given number of unstyled spaces after this cell.
///
/// This method allocates a `String` to hold the spaces.
pub fn add_spaces(&mut self, count: usize) {
use std::iter::repeat;
self.length += count;
let spaces: String = repeat(' ').take(count).collect();
self.contents.push(Style::default().paint(spaces));
}
/// Adds the contents of another `ANSIString` to the end of this cell.
pub fn push(&mut self, string: ANSIString<'static>, length: usize) {
self.contents.push(string);
self.length += length;
}
/// Adds all the contents of another `TextCell` to the end of this cell.
pub fn append(&mut self, other: TextCell) {
self.length += other.length;
self.contents.extend(other.contents);
}
/// Produces an `ANSIStrings` value that can be used to print the styled
/// values of this cell as an ANSI-terminal-formatted string.
pub fn strings(&self) -> ANSIStrings {
ANSIStrings(&self.contents)
}
}
// I’d like to eventually abstract cells so that instead of *every* cell
// storing a vector, only variable-length cells would, and individual cells
// would just store an array of a fixed length (which would usually be just 1
// or 2), which wouldn’t require a heap allocation.
//
// For examples, look at the `render_*` methods in the `Table` object in the
// details view:
//
// - `render_blocks`, `inode`, and `links` will always return a
// one-string-long TextCell;
// - `render_size` will return one or two strings in a TextCell, depending on
// the size and whether one is present;
// - `render_permissions` will return ten or eleven strings;
// - `filename` and `symlink_filename` in the output module root return six or
// five strings.
//
// In none of these cases are we dealing with a *truly variable* number of
// strings: it is only when the strings are concatenated together do we need a
// growable, heap-allocated buffer.
//
// So it would be nice to abstract the `TextCell` type so instead of a `Vec`,
// it can use anything of type `T: IntoIterator<Item=ANSIString<’static>>`.
// This would allow us to still hold all the data, but allocate less.
//
// But exa still has bugs and I need to fix those first :(
/// The contents of a text cell, as a vector of ANSI-styled strings.
///
/// It’s possible to use this type directly in the case where you want a
/// `TextCell` but aren’t concerned with tracking its width, because it occurs
/// in the final cell of a table or grid and there’s no point padding it. This
/// happens when dealing with file names.
pub type TextCellContents = Vec<ANSIString<'static>>;
\ No newline at end of file
use ansi_term::Style;
use unicode_width::UnicodeWidthStr;
use dir::Dir;
......@@ -194,38 +191,3 @@ impl Default for TimeTypes {
TimeTypes { accessed: false, modified: true, created: false }
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct Cell {
pub length: usize,
pub text: String,
}
impl Cell {
pub fn empty() -> Cell {
Cell {
text: String::new(),
length: 0,
}
}
pub fn paint(style: Style, string: &str) -> Cell {
Cell {
text: style.paint(string).to_string(),
length: UnicodeWidthStr::width(string),
}
}
pub fn add_spaces(&mut self, count: usize) {
self.length += count;
for _ in 0 .. count {
self.text.push(' ');
}
}
pub fn append(&mut self, other: &Cell) {
self.length += other.length;
self.text.push_str(&*other.text);
}
}
此差异已折叠。
use std::iter::repeat;
use ansi_term::ANSIStrings;
use users::OSUsers;
use term_grid as grid;
......@@ -7,7 +8,8 @@ use dir::Dir;
use feature::xattr::FileAttributes;
use file::File;
use output::column::{Column, Cell};
use output::cell::TextCell;
use output::column::Column;
use output::details::{Details, Table};
use output::grid::Grid;
......@@ -25,19 +27,25 @@ fn file_has_xattrs(file: &File) -> bool {
}
impl GridDetails {
pub fn view(&self, dir: Option<&Dir>, files: &[File]) {
pub fn view(&self, dir: Option<&Dir>, files: Vec<File>) {
let columns_for_dir = match self.details.columns {
Some(cols) => cols.for_dir(dir),
None => Vec::new(),
};
let mut first_table = Table::with_options(self.details.colours, columns_for_dir.clone());
let cells: Vec<_> = files.iter().map(|file| first_table.cells_for_file(file, file_has_xattrs(file))).collect();
let cells = files.iter()
.map(|file| first_table.cells_for_file(file, file_has_xattrs(file)))
.collect::<Vec<_>>();
let mut last_working_table = self.make_grid(1, &*columns_for_dir, files, cells.clone());
let file_names = files.into_iter()
.map(|file| first_table.filename_cell(file, false))
.collect::<Vec<_>>();
let mut last_working_table = self.make_grid(1, &columns_for_dir, &file_names, cells.clone());
for column_count in 2.. {
let grid = self.make_grid(column_count, &*columns_for_dir, files, cells.clone());
let grid = self.make_grid(column_count, &columns_for_dir, &file_names, cells.clone());
let the_grid_fits = {
let d = grid.fit_into_columns(column_count);
......@@ -60,7 +68,7 @@ impl GridDetails {
table
}
fn make_grid(&self, column_count: usize, columns_for_dir: &[Column], files: &[File], cells: Vec<Vec<Cell>>) -> grid::Grid {
fn make_grid(&self, column_count: usize, columns_for_dir: &[Column], file_names: &[TextCell], cells: Vec<Vec<TextCell>>) -> grid::Grid {
let mut tables: Vec<_> = repeat(()).map(|_| self.make_table(columns_for_dir)).take(column_count).collect();
let mut num_cells = cells.len();
......@@ -71,7 +79,7 @@ impl GridDetails {
let original_height = divide_rounding_up(cells.len(), column_count);
let height = divide_rounding_up(num_cells, column_count);
for (i, (file, row)) in files.iter().zip(cells.into_iter()).enumerate() {
for (i, (file_name, row)) in file_names.iter().zip(cells.into_iter()).enumerate() {
let index = if self.grid.across {
i % column_count
}
......@@ -79,10 +87,10 @@ impl GridDetails {
i / original_height
};
tables[index].add_file_with_cells(row, file, 0, false, false);
tables[index].add_file_with_cells(row, file_name.clone(), 0, false);
}
let columns: Vec<_> = tables.iter().map(|t| t.print_table()).collect();
let columns: Vec<_> = tables.into_iter().map(|t| t.print_table()).collect();
let direction = if self.grid.across { grid::Direction::LeftToRight }
else { grid::Direction::TopToBottom };
......@@ -97,7 +105,7 @@ impl GridDetails {
for column in columns.iter() {
if row < column.len() {
let cell = grid::Cell {
contents: column[row].text.clone(),
contents: ANSIStrings(&column[row].contents).to_string(),
width: column[row].length,
};
......@@ -110,7 +118,7 @@ impl GridDetails {
for column in columns.iter() {
for cell in column.iter() {
let cell = grid::Cell {
contents: cell.text.clone(),
contents: ANSIStrings(&cell.contents).to_string(),
width: cell.length,
};
......
use colours::Colours;
use file::File;
use ansi_term::ANSIStrings;
use super::filename;
......@@ -11,9 +13,9 @@ pub struct Lines {
/// The lines view literally just displays each file, line-by-line.
impl Lines {
pub fn view(&self, files: &[File]) {
pub fn view(&self, files: Vec<File>) {
for file in files {
println!("{}", filename(file, &self.colours, true));
println!("{}", ANSIStrings(&filename(file, &self.colours, true)));
}
}
}
use ansi_term::ANSIStrings;
use ansi_term::Style;
use colours::Colours;
use file::File;
use filetype::file_colour;
pub use self::cell::{TextCell, TextCellContents};
pub use self::details::Details;
pub use self::grid::Grid;
pub use self::lines::Lines;
......@@ -14,29 +15,37 @@ pub mod details;
mod lines;
mod grid_details;
pub mod column;
mod cell;
pub fn filename(file: &File, colours: &Colours, links: bool) -> String {
pub fn filename(file: File, colours: &Colours, links: bool) -> TextCellContents {
if links && file.is_link() {
symlink_filename(file, colours)
}
else {
let style = file_colour(colours, file);
style.paint(&*file.name).to_string()
vec![
file_colour(colours, &file).paint(file.name)
]
}
}
fn symlink_filename(file: &File, colours: &Colours) -> String {
fn symlink_filename(file: File, colours: &Colours) -> TextCellContents {
match file.link_target() {
Ok(target) => format!("{} {} {}",
file_colour(colours, file).paint(&*file.name),
colours.punctuation.paint("->"),
ANSIStrings(&[ colours.symlink_path.paint(target.path_prefix()),
file_colour(colours, &target).paint(target.name) ])),
Ok(target) => vec![
file_colour(colours, &file).paint(file.name),
Style::default().paint(" "),
colours.punctuation.paint("->"),
Style::default().paint(" "),
colours.symlink_path.paint(target.path_prefix()),
file_colour(colours, &target).paint(target.name)
],
Err(filename) => format!("{} {} {}",
file_colour(colours, file).paint(&*file.name),
colours.broken_arrow.paint("->"),
colours.broken_filename.paint(filename)),
Err(filename) => vec![
file_colour(colours, &file).paint(file.name),
Style::default().paint(" "),
colours.broken_arrow.paint("->"),
Style::default().paint(" "),
colours.broken_filename.paint(filename),
],
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册