vanilladocs
vanillapunch.com
API / ui/autolayout/layoutsolver

ui/autolayout/layoutsolver

제약 솔버. (원본 ui/autolayout/layoutsolver.js 의 LayoutSolver, Kiwi dual simplex 기반)

  • 사용:
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
  • 움직이는 입력(끌기 등):
solver.add_edit_variable(&x, LayoutStrength::STRONG)?;
solver.suggest_value(&x, 50.0)?;
solver.update_variables();
  • 원본과 다른 것:
  • 원본은 객체 하나를 여러 UINode 와 UIScene 이 같이 쥔다. 러스트 판은 Rc<RefCell> 을 품은 값싼 Clone 핸들이고 함수는 모두 &self 다.
  • 원본이 예외를 던지는 곳(겹친 제약, 만족할 수 없는 required 제약, 모르는 제약과 편집 변수, required 편집 강도, 솔버 안의 실패)은 Result<(), LayoutError> 를 돌려준다. 문구는 원본과 같되 긴 줄표는 쌍점으로 바꿨다.
  • 원본의 Map 가운데 차례가 고르는 심볼을 바꾸는 행 맵은 넣은 차례를 지키는 LayoutSymbolMap 이다. 차례를 보지 않는 제약, 변수, 편집 변수 맵은 HashMap 이다.
  • 원본 LayoutTag 의 null 심볼은 무효 심볼(LayoutSymbol::invalid)이다. (Kiwi 와 같다)

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)

LayoutSolverstruct traits Clone, Default

짝Counterpart: vanilla.js LayoutSolver소스source

제약 솔버. (복제해도 같은 솔버를 가리킨다)

Constraint solver. (clones point to the same solver)

예제Examplex == 10, y == x + 20 풀기Solving x == 10, y == x + 20
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
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);
생성자constructorpub fn new() -> LayoutSolver#0.4.0 부터since 0.4.0소스source

생성.

Constructor.

반환ReturnsLayoutSolver 제약이 없는 새 솔버 핸들. (복제하면 같은 솔버를 가리킨다)A new solver handle with no constraints. (clones point to the same solver)

짝Counterpart: vanilla.js LayoutSolver.constructor

메서드methodpub fn add_constraint(&self, constraint: &LayoutConstraint) -> Result<(), LayoutError>#0.4.0 부터since 0.4.0소스source

제약 추가.

Adds a constraint.

constraint&LayoutConstraint
걸 제약. (솔버가 핸들을 복제해 쥔다)Constraint to add. (the solver holds a cloned handle)

반환ReturnsResult<(), LayoutError> 걸었으면 Ok(()). - 같은 제약(같은 핸들이나 그 복제)을 이미 걸었으면 Err(DuplicateConstraint). - required 제약을 만족할 수 없으면 Err(UnsatisfiableConstraint). 부등식이 그렇게 실패하면 솔버 안이 되돌려지지 않는다. (원본, Kiwi 와 같다) - 최적화가 실패하면 Err(UnboundedObjective) 나 Err(OptimizeLimitExceeded).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.

짝Counterpart: vanilla.js LayoutSolver.addConstraint

예제Example겹친 제약과 모순 제약의 오류Errors for duplicate constraints and contradictory constraints
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));
메서드methodpub fn remove_constraint(&self, constraint: &LayoutConstraint) -> Result<(), LayoutError>#0.4.0 부터since 0.4.0소스source

제약 제거.

Removes a constraint.

constraint&LayoutConstraint
뺄 제약. (건 핸들이나 그 복제)Constraint to remove. (the added handle or its clone)

반환ReturnsResult<(), LayoutError> 뺐으면 Ok(()). - 걸지 않은 제약이면 Err(UnknownConstraint). (식이 같아도 따로 만든 제약은 모르는 제약이다) - marker 가 떠날 행을 못 찾으면 Err(RemoveConstraintFailed), 최적화가 실패하면 Err(UnboundedObjective) 나 Err(OptimizeLimitExceeded).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.

짝Counterpart: vanilla.js LayoutSolver.removeConstraint

메서드methodpub fn has_constraint(&self, constraint: &LayoutConstraint) -> bool#0.4.0 부터since 0.4.0소스source

제약이 등록되어 있는지. (핸들이 가리키는 제약으로 가린다)

Whether the constraint is registered. (decided by the constraint the handle points to)

constraint&LayoutConstraint
볼 제약.Constraint to check.

반환Returnsbool 걸려 있으면 true.true if added.

짝Counterpart: vanilla.js LayoutSolver.hasConstraint

메서드methodpub fn add_edit_variable(&self, variable: &LayoutVariable, strength: f64) -> Result<(), LayoutError>#0.4.0 부터since 0.4.0소스source

편집 변수 추가. (suggest_value 를 쓰기 전에 꼭 등록한다. strength 는 REQUIRED 보다 작아야 한다)

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.
strengthf64
바라는 값을 지킬 강도. (0 ~ REQUIRED 로 자른 값이 REQUIRED 보다 작아야 한다)Strength for keeping the desired value. (the value clamped to 0 ~ REQUIRED must be less than REQUIRED)

반환ReturnsResult<(), LayoutError> 등록했으면 Ok(()). - 이미 편집 변수면 Err(DuplicateEditVariable). - 자른 강도가 REQUIRED 면 Err(BadRequiredStrength). - 안에서 거는 편집 제약(variable == 바라는 값, 처음 바라는 값은 0)이 실패하면 add_constraint 의 오류.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.

짝Counterpart: vanilla.js LayoutSolver.addEditVariable

메서드methodpub fn remove_edit_variable(&self, variable: &LayoutVariable) -> Result<(), LayoutError>#0.4.0 부터since 0.4.0소스source

편집 변수 제거.

Removes an edit variable.

variable&LayoutVariable
뺄 편집 변수.Edit variable to remove.

반환ReturnsResult<(), LayoutError> 뺐으면 Ok(()). 편집 변수가 아니면 Err(UnknownEditVariable). 편집 제약을 빼다 실패하면 remove_constraint 의 오류.Ok(()) if removed. Err(UnknownEditVariable) if not an edit variable. The remove_constraint error if removing the edit constraint fails.

짝Counterpart: vanilla.js LayoutSolver.removeEditVariable

메서드methodpub fn has_edit_variable(&self, variable: &LayoutVariable) -> bool#0.4.0 부터since 0.4.0소스source

편집 변수로 등록되어 있는지.

Whether it is registered as an edit variable.

variable&LayoutVariable
볼 변수.Variable to check.

반환Returnsbool 편집 변수로 등록되어 있으면 true.true if registered as an edit variable.

짝Counterpart: vanilla.js LayoutSolver.hasEditVariable

메서드methodpub fn suggest_value(&self, variable: &LayoutVariable, value: f64) -> Result<(), LayoutError>#0.4.0 부터since 0.4.0소스source

편집 변수에 바라는 값을 준다. (끌기 갱신 등)

  • 솔버는 되도록 그 값을 지키되 다른 제약과 부딪히면 강도에 따라 양보한다.

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
편집 변수. (add_edit_variable 로 등록한 것)Edit variable. (registered with add_edit_variable)
valuef64
바라는 값.Desired value.

반환ReturnsResult<(), LayoutError> 반영했으면 Ok(()). (변수 값은 update_variables 뒤에 바뀐다) - 편집 변수가 아니면 Err(UnknownEditVariable). - dual optimize 가 실패하면 Err(DualOptimizeFailed) 나 Err(DualOptimizeLimitExceeded).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.

짝Counterpart: vanilla.js LayoutSolver.suggestValue

예제Example끌기로 값을 옮기되 required 제약에서 멈춘다Moving a value by drag but stopping at a required constraint
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));
메서드methodpub fn update_variables(&self)#0.4.0 부터since 0.4.0소스source

변수 값 갱신. (tableau 의 external 행 상수항을 각 LayoutVariable 에 넣는다)

Updates variable values. (puts the constants of the tableau's external rows into each LayoutVariable)

짝Counterpart: vanilla.js LayoutSolver.updateVariables

LayoutErrorenum traits Clone, Copy, Debug, PartialEq, Eq, fmt::Display, std::error::Error

소스source

솔버 오류. (원본이 던지는 예외 자리)

Solver error. (where the original throws exceptions)

이름Name설명Description
DuplicateConstraint이미 추가한 제약을 또 추가했다.A constraint already added was added again.
UnsatisfiableConstraintrequired 제약을 만족할 수 없다.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편집 변수에 required 강도를 주었다.Gave an edit variable required strength.
UnknownEditVariable등록하지 않은 편집 변수를 쓰거나 지우려 했다.Tried to use or remove an unregistered edit variable.
RemoveConstraintFailed제약을 지울 때 marker 가 떠날 행을 못 찾았다. (솔버 안의 실패)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)
OptimizeLimitExceededoptimize 반복 상한을 넘었다. (솔버 안의 실패)Exceeded the optimize iteration limit. (internal solver failure)
DualOptimizeFaileddual_optimize 에서 들어올 심볼을 못 찾았다. (솔버 안의 실패)No entering symbol found in dual_optimize. (internal solver failure)
DualOptimizeLimitExceededdual_optimize 반복 상한을 넘었다. (솔버 안의 실패)Exceeded the dual_optimize iteration limit. (internal solver failure)