# ui/autolayout/layoutsolver (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/ui/autolayout/layoutsolver/

Constraint solver. (LayoutSolver of the original ui/autolayout/layoutsolver.js, based on Kiwi dual simplex)
- Usage:
  let solver = LayoutSolver::new();
  let x = LayoutVariable::new("x");
  let y = LayoutVariable::new("y");
  solver.add_constraint(&LayoutExpression::from_variable(&x).equal_to(10))?;
  solver.add_constraint(&LayoutExpression::from_variable(&y).equal_to(LayoutExpression::from_variable(&x).add(20)))?;
  solver.update_variables();
  x.get_value(); // 10
  y.get_value(); // 30
- Dynamic input (drag, etc):
  solver.add_edit_variable(&x, LayoutStrength::STRONG)?;
  solver.suggest_value(&x, 50.0)?;
  solver.update_variables();
- Differences from the original:
  - In the original, several UINodes and UIScenes share one object. The Rust version is a cheap Clone handle holding an `Rc<RefCell>`, and all functions take &self.
  - Where the original throws exceptions (duplicate constraints, unsatisfiable required constraints, unknown constraints and edit variables, required edit strength,
    internal solver failures), it returns `Result<(), LayoutError>`. The messages are the same as the original, except the long dashes were changed to colons.
  - Among the original's Maps, the row map, whose order changes which symbol is chosen, is a LayoutSymbolMap that keeps insertion order.
    The constraint, variable and edit variable maps, which do not depend on order, are HashMaps.
  - The null symbol of the original LayoutTag is the invalid symbol (LayoutSymbol::invalid). (same as Kiwi)

## LayoutSolver (struct) (Clone, Default)

Constraint solver. (clones point to the same solver)

Example: Solving x == 10, y == x + 20

```rust
use vanilla::{LayoutExpression, LayoutSolver, LayoutVariable};

let solver = LayoutSolver::new();
let x = LayoutVariable::new("x");
let y = LayoutVariable::new("y");
solver.add_constraint(&LayoutExpression::from_variable(&x).equal_to(10))?;
solver.add_constraint(&LayoutExpression::from_variable(&y).equal_to(LayoutExpression::from_variable(&x).add(20)))?;
solver.update_variables();
assert!((x.get_value() - 10.0).abs() < 1e-9);
assert!((y.get_value() - 30.0).abs() < 1e-9);
```

Example: Dynamic input (drag, etc) through edit variables

```rust
use vanilla::{LayoutExpression, LayoutSolver, LayoutStrength, LayoutVariable};

let solver = LayoutSolver::new();
let x = LayoutVariable::new("x");
solver.add_constraint(&LayoutExpression::from_variable(&x).less_than_or_equal_to(100))?;
solver.add_edit_variable(&x, LayoutStrength::STRONG)?;
solver.suggest_value(&x, 50.0)?;
solver.update_variables();
assert!((x.get_value() - 50.0).abs() < 1e-9);
```

- `pub fn new() -> LayoutSolver` (constructor, since 0.4.0): Constructor.
  - returns LayoutSolver: A new solver handle with no constraints. (clones point to the same solver)
- `pub fn add_constraint(&self, constraint: &LayoutConstraint) -> Result<(), LayoutError>` (method, since 0.4.0): Adds a constraint.
  - `constraint` &LayoutConstraint: Constraint to add. (the solver holds a cloned handle)
  - returns Result<(), LayoutError>: Ok(()) if added.
- Err(DuplicateConstraint) if the same constraint (the same handle or its clone) was already added.
- Err(UnsatisfiableConstraint) if a required constraint cannot be satisfied. When an inequality fails this way, the solver's internals are not rolled back. (same as the original, Kiwi)
- Err(UnboundedObjective) or Err(OptimizeLimitExceeded) if optimization fails.

  Example: Errors for duplicate constraints and contradictory constraints

  ```rust
  use vanilla::{LayoutError, LayoutExpression, LayoutSolver, LayoutVariable};
  
  let solver = LayoutSolver::new();
  let x = LayoutVariable::new("x");
  let constraint = LayoutExpression::from_variable(&x).equal_to(10);
  assert_eq!(solver.add_constraint(&constraint), Ok(()));
  assert_eq!(solver.add_constraint(&constraint.clone()), Err(LayoutError::DuplicateConstraint));
  let conflict = LayoutExpression::from_variable(&x).equal_to(20);
  assert_eq!(solver.add_constraint(&conflict), Err(LayoutError::UnsatisfiableConstraint));
  assert!(!solver.has_constraint(&conflict));
  ```

- `pub fn remove_constraint(&self, constraint: &LayoutConstraint) -> Result<(), LayoutError>` (method, since 0.4.0): Removes a constraint.
  - `constraint` &LayoutConstraint: Constraint to remove. (the added handle or its clone)
  - returns Result<(), LayoutError>: Ok(()) if removed.
- Err(UnknownConstraint) if the constraint was not added. (a separately created constraint is unknown even with the same expression)
- Err(RemoveConstraintFailed) if no row for the marker to leave is found, Err(UnboundedObjective) or Err(OptimizeLimitExceeded) if optimization fails.
- `pub fn has_constraint(&self, constraint: &LayoutConstraint) -> bool` (method, since 0.4.0): Whether the constraint is registered. (decided by the constraint the handle points to)
  - `constraint` &LayoutConstraint: Constraint to check.
  - returns bool: true if added.
- `pub fn add_edit_variable(&self, variable: &LayoutVariable, strength: f64) -> Result<(), LayoutError>` (method, since 0.4.0): Adds an edit variable. (must be registered before using suggest_value. strength must be less than REQUIRED)
  - `variable` &LayoutVariable: Variable to use as an edit variable.
  - `strength` f64: Strength for keeping the desired value. (the value clamped to 0 ~ REQUIRED must be less than REQUIRED)
  - returns Result<(), LayoutError>: Ok(()) if registered.
- Err(DuplicateEditVariable) if already an edit variable.
- Err(BadRequiredStrength) if the clamped strength is REQUIRED.
- The add_constraint error if the internally added edit constraint (variable == desired value, initial desired value 0) fails.
- `pub fn remove_edit_variable(&self, variable: &LayoutVariable) -> Result<(), LayoutError>` (method, since 0.4.0): Removes an edit variable.
  - `variable` &LayoutVariable: Edit variable to remove.
  - returns Result<(), LayoutError>: Ok(()) if removed. Err(UnknownEditVariable) if not an edit variable. The remove_constraint error if removing the edit constraint fails.
- `pub fn has_edit_variable(&self, variable: &LayoutVariable) -> bool` (method, since 0.4.0): Whether it is registered as an edit variable.
  - `variable` &LayoutVariable: Variable to check.
  - returns bool: true if registered as an edit variable.
- `pub fn suggest_value(&self, variable: &LayoutVariable, value: f64) -> Result<(), LayoutError>` (method, since 0.4.0): Gives an edit variable a desired value. (drag updates, etc)
  - The solver keeps that value as much as possible, but yields according to strength when it conflicts with other constraints.
  - `variable` &LayoutVariable: Edit variable. (registered with add_edit_variable)
  - `value` f64: Desired value.
  - returns Result<(), LayoutError>: Ok(()) if applied. (variable values change after update_variables)
- Err(UnknownEditVariable) if not an edit variable.
- Err(DualOptimizeFailed) or Err(DualOptimizeLimitExceeded) if dual optimize fails.

  Example: Moving a value by drag but stopping at a required constraint

  ```rust
  use vanilla::{LayoutExpression, LayoutSolver, LayoutStrength, LayoutVariable};
  
  let solver = LayoutSolver::new();
  let x = LayoutVariable::new("x");
  solver.add_constraint(&LayoutExpression::from_variable(&x).less_than_or_equal_to(100))?;
  solver.add_edit_variable(&x, LayoutStrength::STRONG)?;
  for drag_value in [30.0, 60.0, 150.0] {
  	solver.suggest_value(&x, drag_value)?;
  	solver.update_variables();
  }
  assert!((x.get_value() - 100.0).abs() < 1e-9);
  solver.remove_edit_variable(&x)?;
  assert!(!solver.has_edit_variable(&x));
  ```

- `pub fn update_variables(&self)` (method, since 0.4.0): Updates variable values. (puts the constants of the tableau's external rows into each LayoutVariable)

## LayoutError (enum) (Clone, Copy, Debug, PartialEq, Eq, fmt::Display, std::error::Error)

Solver error. (where the original throws exceptions)

- `DuplicateConstraint`: A constraint already added was added again.
- `UnsatisfiableConstraint`: A required constraint cannot be satisfied.
- `UnknownConstraint`: Tried to remove an unregistered constraint.
- `DuplicateEditVariable`: A variable already registered as an edit variable was registered again.
- `BadRequiredStrength`: Gave an edit variable required strength.
- `UnknownEditVariable`: Tried to use or remove an unregistered edit variable.
- `RemoveConstraintFailed`: When removing a constraint, no row for the marker to leave was found. (internal solver failure)
- `UnboundedObjective`: The objective function decreases without bound. (internal solver failure)
- `OptimizeLimitExceeded`: Exceeded the optimize iteration limit. (internal solver failure)
- `DualOptimizeFailed`: No entering symbol found in dual_optimize. (internal solver failure)
- `DualOptimizeLimitExceeded`: Exceeded the dual_optimize iteration limit. (internal solver failure)
