Lines
91.56 %
Functions
50 %
Branches
100 %
//! The report filter builder: the rows of the filter grammar, edited one
//! group at a time. Enter on a group or an `in` row steps into it, `back`
//! steps out; the whole tree is written back only by [`FilterBuilder::apply`].
use forms::FormValues;
use forms::filter::{Fault, Item, Logic, Restored, group_sexpr, restore};
use crate::form::RowShape;
use crate::widgets::SelectOption;
use describe::{describe, label, logic as logic_label};
use rows::{blank, id_of, item_of, picks_commodities, shape_of, values_of};
mod describe;
mod rows;
#[cfg(test)]
mod tests;
/// The rows or the ids of the group or `in` row being edited.
enum Level<'a> {
Items(&'a [Item]),
Ids(&'a [String]),
}
enum LevelMut<'a> {
Items(&'a mut Vec<Item>),
Ids(&'a mut Vec<String>),
fn level<'a>(items: &'a [Item], path: &[usize]) -> Option<Level<'a>> {
let Some((&first, rest)) = path.split_first() else {
return Some(Level::Items(items));
};
match items.get(first)? {
Item::Group { items, .. } => level(items, rest),
Item::AccountIn { ids } | Item::CounterpartyIn { ids } | Item::CommodityIn { ids } => {
rest.is_empty().then_some(Level::Ids(ids))
_ => None,
fn level_mut<'a>(items: &'a mut Vec<Item>, path: &[usize]) -> Option<LevelMut<'a>> {
return Some(LevelMut::Items(items));
match items.get_mut(first)? {
Item::Group { items, .. } => level_mut(items, rest),
rest.is_empty().then_some(LevelMut::Ids(ids))
/// What the builder shows: the heading, one line per row and the cursor.
#[derive(Debug, PartialEq, Eq)]
pub struct View {
pub heading: String,
pub rows: Vec<String>,
pub selected: usize,
pub notice: Option<String>,
/// A row form is open: where its values go.
#[derive(Debug, Clone)]
enum Pending {
/// An id for the `in` row being edited.
Id,
/// A row of the kind of `template`, replacing the row `at` or appended.
Row { at: Option<usize>, template: Item },
/// A row form to open: its shape and the values it starts with.
#[derive(Debug)]
pub struct Opened {
pub shape: RowShape,
pub values: FormValues,
pub struct FilterBuilder {
logic: Logic,
items: Vec<Item>,
original: (Logic, Vec<Item>),
/// The filter text rows cannot show; the builder then edits nothing.
opaque: Option<String>,
path: Vec<usize>,
selected: usize,
pending: Option<Pending>,
/// Why the last apply or edit was refused.
pub error: Option<String>,
pub accounts: Vec<SelectOption>,
pub commodities: Vec<SelectOption>,
impl FilterBuilder {
/// A builder holding the rows of the filter `text`.
#[must_use]
pub fn new(text: &str) -> Self {
let (logic, items, opaque) = match restore(text) {
Restored::Rows { logic, items } => (logic, items, None),
Restored::Opaque => (Logic::And, Vec::new(), Some(text.to_string())),
Self {
original: (logic, items.clone()),
logic,
items,
opaque,
path: Vec::new(),
selected: 0,
pending: None,
error: None,
accounts: Vec::new(),
commodities: Vec::new(),
pub fn is_dirty(&self) -> bool {
self.original != (self.logic, self.items.clone())
pub fn is_opaque(&self) -> bool {
self.opaque.is_some()
fn len(&self) -> usize {
match level(&self.items, &self.path) {
Some(Level::Items(items)) => items.len(),
Some(Level::Ids(ids)) => ids.len(),
None => 0,
pub fn select_next(&mut self) {
self.selected = (self.selected + 1).min(self.len().saturating_sub(1));
pub fn select_prev(&mut self) {
self.selected = self.selected.saturating_sub(1);
/// The row under the cursor when this level holds rows.
pub fn selected_item(&self) -> Option<&Item> {
match level(&self.items, &self.path)? {
Level::Items(items) => items.get(self.selected),
Level::Ids(_) => None,
/// Whether the level holds ids of an `in` row.
pub fn in_ids(&self) -> bool {
matches!(level(&self.items, &self.path), Some(Level::Ids(_)))
/// Steps into the group or `in` row under the cursor; `false` for any other row.
pub fn enter(&mut self) -> bool {
let steps = matches!(
self.selected_item(),
Some(
Item::Group { .. }
| Item::AccountIn { .. }
| Item::CounterpartyIn { .. }
| Item::CommodityIn { .. }
)
);
if steps {
self.path.push(self.selected);
self.selected = 0;
self.error = None;
steps
/// Steps out to the enclosing level, the cursor on the row left.
pub fn back(&mut self) -> bool {
let Some(index) = self.path.pop() else {
return false;
self.selected = index;
true
pub fn delete(&mut self) {
match level_mut(&mut self.items, &self.path) {
Some(LevelMut::Items(items)) if self.selected < items.len() => {
items.remove(self.selected);
Some(LevelMut::Ids(ids)) if self.selected < ids.len() => {
ids.remove(self.selected);
_ => return,
self.selected = self.selected.min(self.len().saturating_sub(1));
/// And, or, not in turn for the group being edited.
pub fn cycle_logic(&mut self) {
let Some(logic) = self.logic_mut() else {
return;
*logic = match *logic {
Logic::And => Logic::Or,
Logic::Or => Logic::Not,
Logic::Not => Logic::And,
fn logic_mut(&mut self) -> Option<&mut Logic> {
let Some((&last, parent)) = self.path.split_last() else {
return Some(&mut self.logic);
let Some(LevelMut::Items(items)) = level_mut(&mut self.items, parent) else {
return None;
match items.get_mut(last)? {
Item::Group { logic, .. } => Some(logic),
/// The form for adding an id to the `in` row being edited; `None` off an `in` row.
pub fn begin_id(&mut self) -> Option<Opened> {
let shape = match self.in_row()? {
Item::AccountIn { .. } => RowShape::AccountId,
Item::CounterpartyIn { .. } => RowShape::Counterparty,
Item::CommodityIn { .. } => RowShape::Commodity,
_ => return None,
self.pending = Some(Pending::Id);
Some(Opened {
shape,
values: FormValues::default(),
})
/// The form for the row under the cursor; `None` for a group or an `in` row.
pub fn begin_edit(&mut self) -> Option<Opened> {
let template = self.selected_item()?.clone();
let shape = shape_of(&template)?;
let values = values_of(&template);
self.pending = Some(Pending::Row {
at: Some(self.selected),
template,
});
Some(Opened { shape, values })
/// Starts a new row of the named kind. Groups and `in` rows are added at
/// once and stepped into; the others come back as a form to fill.
pub fn begin_add(&mut self, kind: &str) -> Option<Opened> {
let template = blank(kind)?;
let Some(shape) = shape_of(&template) else {
self.push(template);
self.enter();
self.pending = Some(Pending::Row { at: None, template });
/// Takes the values of the open row form.
///
/// # Errors
/// Why they are not a row; the form stays open and the same values may be retried.
pub fn accept(&mut self, values: &FormValues) -> Result<(), String> {
match self.pending.clone() {
Some(Pending::Id) => {
let id = id_of(values)?;
if !self.has_id(&id) {
self.push_id(id);
Some(Pending::Row { at, template }) => {
let item = item_of(&template, values)?;
match at {
Some(index) => self.replace(index, item),
None => self.push(item),
None => return Err("no row is being edited".to_string()),
self.pending = None;
Ok(())
fn has_id(&self, id: &str) -> bool {
matches!(level(&self.items, &self.path), Some(Level::Ids(ids)) if ids.iter().any(|have| have == id))
/// The names a row form of this shape picks among.
pub fn options_for(&self, shape: RowShape) -> &[SelectOption] {
match picks_commodities(shape) {
true => &self.commodities,
false => &self.accounts,
/// Adds `item` to the rows being edited and puts the cursor on it.
fn push(&mut self, item: Item) {
if let Some(LevelMut::Items(items)) = level_mut(&mut self.items, &self.path) {
items.push(item);
self.selected = items.len() - 1;
/// Adds `id` to the `in` row being edited.
fn push_id(&mut self, id: String) {
if let Some(LevelMut::Ids(ids)) = level_mut(&mut self.items, &self.path) {
ids.push(id);
self.selected = ids.len() - 1;
/// Replaces the row at `index` of the rows being edited.
fn replace(&mut self, index: usize, item: Item) {
if let Some(LevelMut::Items(items)) = level_mut(&mut self.items, &self.path)
&& let Some(row) = items.get_mut(index)
{
*row = item;
/// The filter text of all rows. A row the writer would drop or widen is
/// refused: the cursor goes to it and `error` says why.
pub fn apply(&mut self) -> Option<String> {
if self.is_opaque() {
self.error = Some("the filter text is not shown as rows; nothing applied".into());
match group_sexpr(self.logic, &self.items) {
Ok(text) => Some(text.unwrap_or_default()),
Err(fault) => {
self.refuse(fault);
None
fn refuse(&mut self, fault: Fault) {
let (selected, parent) = match fault.path.split_last() {
Some((&index, parent)) => (index, parent.to_vec()),
None => (0, Vec::new()),
self.path = parent;
self.selected = selected;
self.error = Some(fault.reason.describe());
fn heading(&self) -> String {
let mut crumbs = vec![logic_label(self.logic).to_string()];
let mut items = self.items.as_slice();
for &index in &self.path {
match items.get(index) {
Some(Item::Group {
items: inner,
}) => {
crumbs.push(logic_label(*logic).to_string());
items = inner;
Some(row) => crumbs.push(describe(row, &self.accounts, &self.commodities)),
None => break,
crumbs.join(" > ")
fn rows(&self) -> Vec<String> {
Some(Level::Items(items)) => items
.iter()
.map(|item| describe(item, &self.accounts, &self.commodities))
.collect(),
Some(Level::Ids(ids)) => ids.iter().map(|id| self.id_label(id)).collect(),
None => Vec::new(),
/// The name of an id of the `in` row being edited.
fn id_label(&self, id: &str) -> String {
let options = match self.in_row() {
Some(Item::CommodityIn { .. }) => &self.commodities,
_ => &self.accounts,
label(options, id)
fn in_row(&self) -> Option<&Item> {
let (&last, parent) = self.path.split_last()?;
match level(&self.items, parent)? {
Level::Items(items) => items.get(last),
pub fn view(&self) -> View {
View {
heading: self.heading(),
rows: self.rows(),
selected: self.selected,
notice: self
.opaque
.as_ref()
.map(|text| format!("cannot be shown as rows; the filter is left as is:\n{text}")),