use crate::hit_test::{NodeGeometry, SimpleNodeGeometry};
use crate::state::GeometryCache;
use slint::{Color, Model, VecModel};
use std::fmt;
pub trait LinkModel {
fn id(&self) -> i32;
fn start_pin_id(&self) -> i32;
fn end_pin_id(&self) -> i32;
fn color(&self) -> Color {
Color::from_rgb_u8(255, 255, 255)
}
fn line_width(&self) -> f32 {
2.0
}
fn status(&self) -> i32 {
-1
}
}
impl LinkModel for crate::nodeeditor::LinkData {
fn id(&self) -> i32 {
self.id
}
fn start_pin_id(&self) -> i32 {
self.start_pin_id
}
fn end_pin_id(&self) -> i32 {
self.end_pin_id
}
fn color(&self) -> Color {
self.color
}
fn line_width(&self) -> f32 {
self.line_width
}
fn status(&self) -> i32 {
self.status
}
}
#[derive(Clone, Debug)]
pub struct SimpleLink {
pub id: i32,
pub start_pin_id: i32,
pub end_pin_id: i32,
pub color: Color,
pub line_width: f32,
pub status: i32,
}
impl SimpleLink {
pub fn new(id: i32, start_pin_id: i32, end_pin_id: i32, color: Color) -> Self {
Self {
id,
start_pin_id,
end_pin_id,
color,
line_width: 2.0,
status: -1,
}
}
pub fn with_line_width(
id: i32,
start_pin_id: i32,
end_pin_id: i32,
color: Color,
line_width: f32,
) -> Self {
Self {
id,
start_pin_id,
end_pin_id,
color,
line_width,
status: -1,
}
}
}
impl LinkModel for SimpleLink {
fn id(&self) -> i32 {
self.id
}
fn start_pin_id(&self) -> i32 {
self.start_pin_id
}
fn end_pin_id(&self) -> i32 {
self.end_pin_id
}
fn color(&self) -> Color {
self.color
}
fn line_width(&self) -> f32 {
self.line_width
}
fn status(&self) -> i32 {
self.status
}
}
pub trait MovableNode: Clone + 'static {
fn id(&self) -> i32;
fn x(&self) -> f32;
fn y(&self) -> f32;
fn selected(&self) -> bool;
fn set_x(&mut self, x: f32);
fn set_y(&mut self, y: f32);
fn draggable(&self) -> bool {
true
}
}
pub struct GraphLogic;
impl GraphLogic {
pub fn find_links_connected_to_node<I, L, N>(
node_id: i32,
links: I,
cache: &GeometryCache<N>,
) -> Vec<i32>
where
I: Iterator<Item = L>,
L: LinkModel,
N: NodeGeometry + Copy,
{
links
.filter(|link| {
let start_node = cache
.pin_positions
.get(&link.start_pin_id())
.map(|p| p.node_id);
let end_node = cache
.pin_positions
.get(&link.end_pin_id())
.map(|p| p.node_id);
start_node == Some(node_id) || end_node == Some(node_id)
})
.map(|l| l.id())
.collect()
}
pub fn normalize_link_direction<N>(
pin_a: i32,
pin_b: i32,
cache: &GeometryCache<N>,
output_type: i32,
) -> Option<(i32, i32)>
where
N: NodeGeometry + Copy,
{
let pos_a = cache.pin_positions.get(&pin_a)?;
cache.pin_positions.get(&pin_b)?;
if pos_a.pin_type == output_type {
Some((pin_a, pin_b))
} else {
Some((pin_b, pin_a))
}
}
pub fn commit_drag<T>(model: &VecModel<T>, dragged_id: i32, delta_x: f32, delta_y: f32)
where
T: MovableNode,
{
for i in 0..model.row_count() {
if let Some(mut node) = model.row_data(i) {
if node.id() == dragged_id || Self::carried_by_selection(&node) {
node.set_x(node.x() + delta_x);
node.set_y(node.y() + delta_y);
model.set_row_data(i, node);
}
}
}
}
pub(crate) fn carried_by_selection<T: MovableNode>(node: &T) -> bool {
node.selected() && node.draggable()
}
pub fn duplicate_link_exists<I, L>(start_pin: i32, end_pin: i32, links: I) -> bool
where
I: IntoIterator<Item = L>,
L: LinkModel,
{
links
.into_iter()
.any(|link| link.start_pin_id() == start_pin && link.end_pin_id() == end_pin)
}
pub fn find_node_by_id<T, F>(
model: &impl Model<Data = T>,
id: i32,
predicate: F,
) -> Option<(usize, T)>
where
T: Clone + 'static,
F: Fn(&T) -> i32,
{
for i in 0..model.row_count() {
if let Some(node) = model.row_data(i) {
if predicate(&node) == id {
return Some((i, node));
}
}
}
None
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationResult {
Valid,
Invalid(ValidationError),
}
impl ValidationResult {
pub fn is_valid(&self) -> bool {
matches!(self, ValidationResult::Valid)
}
pub fn and(self, other: ValidationResult) -> ValidationResult {
match self {
ValidationResult::Valid => other,
invalid => invalid,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
PinNotFound(i32),
SamePin,
SameNode,
IncompatibleDirection,
DuplicateLink,
MaxConnectionsReached { pin_id: i32, max: usize },
TypeMismatch { expected: i32, found: i32 },
Custom(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NormalizedLink {
pub output_pin_id: i32,
pub input_pin_id: i32,
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::PinNotFound(id) => write!(f, "Pin {} not found", id),
Self::SamePin => write!(f, "Cannot link pin to itself"),
Self::SameNode => write!(f, "Cannot link pins on same node"),
Self::IncompatibleDirection => write!(f, "Must connect input to output"),
Self::DuplicateLink => write!(f, "Link already exists"),
Self::MaxConnectionsReached { pin_id, max } => {
write!(f, "Pin {} has reached max {} connections", pin_id, max)
}
Self::TypeMismatch { expected, found } => {
write!(f, "Type mismatch: expected {}, found {}", expected, found)
}
Self::Custom(msg) => write!(f, "{}", msg),
}
}
}
impl std::error::Error for ValidationError {}
pub trait LinkValidator<N = SimpleNodeGeometry, L = ()> {
fn validate(
&self,
start_pin: i32,
end_pin: i32,
cache: &GeometryCache<N>,
links: &[L],
) -> ValidationResult;
}
#[derive(Clone, Copy, Debug)]
pub struct BasicLinkValidator {
output_type: i32,
}
impl BasicLinkValidator {
pub fn new(output_type: i32) -> Self {
Self { output_type }
}
}
impl<N, L> LinkValidator<N, L> for BasicLinkValidator
where
N: NodeGeometry + Copy,
{
fn validate(
&self,
start_pin: i32,
end_pin: i32,
cache: &GeometryCache<N>,
_links: &[L],
) -> ValidationResult {
if start_pin == end_pin {
return ValidationResult::Invalid(ValidationError::SamePin);
}
let start_pos = match cache.pin_positions.get(&start_pin) {
Some(p) => p,
None => return ValidationResult::Invalid(ValidationError::PinNotFound(start_pin)),
};
let end_pos = match cache.pin_positions.get(&end_pin) {
Some(p) => p,
None => return ValidationResult::Invalid(ValidationError::PinNotFound(end_pin)),
};
if start_pos.node_id == end_pos.node_id {
return ValidationResult::Invalid(ValidationError::SameNode);
}
let start_is_output = start_pos.pin_type == self.output_type;
let end_is_output = end_pos.pin_type == self.output_type;
if start_is_output == end_is_output {
return ValidationResult::Invalid(ValidationError::IncompatibleDirection);
}
ValidationResult::Valid
}
}
pub fn validate_and_normalize_link<N, L, V>(
pin_a: i32,
pin_b: i32,
cache: &GeometryCache<N>,
links: &[L],
output_type: i32,
topology_validator: &V,
) -> Result<NormalizedLink, ValidationError>
where
N: NodeGeometry + Copy,
V: LinkValidator<N, L>,
{
match BasicLinkValidator::new(output_type).validate(pin_a, pin_b, cache, links) {
ValidationResult::Valid => {}
ValidationResult::Invalid(error) => return Err(error),
}
let Some((output_pin_id, input_pin_id)) =
GraphLogic::normalize_link_direction(pin_a, pin_b, cache, output_type)
else {
return Err(ValidationError::PinNotFound(pin_a));
};
match topology_validator.validate(output_pin_id, input_pin_id, cache, links) {
ValidationResult::Valid => Ok(NormalizedLink {
output_pin_id,
input_pin_id,
}),
ValidationResult::Invalid(error) => Err(error),
}
}
#[derive(Clone, Debug, Default)]
pub struct NoDuplicatesValidator;
impl<N, L> LinkValidator<N, L> for NoDuplicatesValidator
where
L: LinkModel + Clone,
{
fn validate(
&self,
start_pin: i32,
end_pin: i32,
_cache: &GeometryCache<N>,
links: &[L],
) -> ValidationResult {
if GraphLogic::duplicate_link_exists(start_pin, end_pin, links.iter().cloned()) {
ValidationResult::Invalid(ValidationError::DuplicateLink)
} else {
ValidationResult::Valid
}
}
}
pub struct CompositeValidator<N = SimpleNodeGeometry, L = ()> {
validators: Vec<Box<dyn LinkValidator<N, L>>>,
}
impl<N, L> Default for CompositeValidator<N, L> {
fn default() -> Self {
Self::new()
}
}
impl<N, L> CompositeValidator<N, L> {
pub fn new() -> Self {
Self {
validators: Vec::new(),
}
}
pub fn with<V: LinkValidator<N, L> + 'static>(mut self, validator: V) -> Self {
self.validators.push(Box::new(validator));
self
}
}
impl<N, L> LinkValidator<N, L> for CompositeValidator<N, L> {
fn validate(
&self,
start_pin: i32,
end_pin: i32,
cache: &GeometryCache<N>,
links: &[L],
) -> ValidationResult {
for v in &self.validators {
let result = v.validate(start_pin, end_pin, cache, links);
if !result.is_valid() {
return result;
}
}
ValidationResult::Valid
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hit_test::SimpleNodeGeometry;
use crate::state::StoredPin;
fn setup_cache() -> GeometryCache<SimpleNodeGeometry> {
let mut cache = GeometryCache::new();
cache.node_rects.insert(
1,
SimpleNodeGeometry {
id: 1,
x: 0.0,
y: 0.0,
width: 100.0,
height: 50.0,
},
);
cache.node_rects.insert(
2,
SimpleNodeGeometry {
id: 2,
x: 200.0,
y: 0.0,
width: 100.0,
height: 50.0,
},
);
cache.pin_positions.insert(
1001,
StoredPin {
node_id: 1,
pin_type: 2,
rel_x: 100.0,
rel_y: 25.0,
},
);
cache.pin_positions.insert(
2001,
StoredPin {
node_id: 2,
pin_type: 1,
rel_x: 0.0,
rel_y: 25.0,
},
);
cache.pin_positions.insert(
2002,
StoredPin {
node_id: 2,
pin_type: 1,
rel_x: 0.0,
rel_y: 40.0,
},
);
cache
}
#[derive(Clone, Debug)]
struct TestLink {
id: i32,
start: i32,
end: i32,
}
impl LinkModel for TestLink {
fn id(&self) -> i32 {
self.id
}
fn start_pin_id(&self) -> i32 {
self.start
}
fn end_pin_id(&self) -> i32 {
self.end
}
}
#[test]
fn test_basic_validator_accepts_valid_link() {
let cache = setup_cache();
let validator = BasicLinkValidator::new(2); let links: Vec<TestLink> = vec![];
let result = validator.validate(1001, 2001, &cache, &links);
assert!(result.is_valid());
}
#[test]
fn removed_node_pins_are_no_longer_valid_endpoints() {
let mut cache = setup_cache();
let validator = BasicLinkValidator::new(2);
let links: Vec<TestLink> = vec![];
cache.remove_node(1);
assert_eq!(
validator.validate(1001, 2001, &cache, &links),
ValidationResult::Invalid(ValidationError::PinNotFound(1001))
);
}
#[test]
fn test_basic_validator_rejects_same_pin() {
let cache = setup_cache();
let validator = BasicLinkValidator::new(2);
let links: Vec<TestLink> = vec![];
let result = validator.validate(1001, 1001, &cache, &links);
assert_eq!(result, ValidationResult::Invalid(ValidationError::SamePin));
}
#[test]
fn test_basic_validator_rejects_same_node() {
let mut cache = setup_cache();
cache.pin_positions.insert(
1002,
StoredPin {
node_id: 1,
pin_type: 1,
rel_x: 0.0,
rel_y: 25.0,
},
);
let validator = BasicLinkValidator::new(2);
let links: Vec<TestLink> = vec![];
let result = validator.validate(1001, 1002, &cache, &links);
assert_eq!(result, ValidationResult::Invalid(ValidationError::SameNode));
}
#[test]
fn test_basic_validator_rejects_same_direction() {
let mut cache = setup_cache();
cache.pin_positions.insert(
2003,
StoredPin {
node_id: 2,
pin_type: 2,
rel_x: 100.0,
rel_y: 25.0,
},
);
let validator = BasicLinkValidator::new(2);
let links: Vec<TestLink> = vec![];
let result = validator.validate(1001, 2003, &cache, &links);
assert_eq!(
result,
ValidationResult::Invalid(ValidationError::IncompatibleDirection)
);
}
#[test]
fn test_basic_validator_rejects_missing_pin() {
let cache = setup_cache();
let validator = BasicLinkValidator::new(2);
let links: Vec<TestLink> = vec![];
let result = validator.validate(1001, 9999, &cache, &links);
assert_eq!(
result,
ValidationResult::Invalid(ValidationError::PinNotFound(9999))
);
}
#[test]
fn test_no_duplicates_validator_accepts_new_link() {
let cache = setup_cache();
let validator = NoDuplicatesValidator;
let links = vec![TestLink {
id: 1,
start: 1001,
end: 2002,
}];
let result = validator.validate(1001, 2001, &cache, &links);
assert!(result.is_valid());
}
#[test]
fn test_no_duplicates_validator_rejects_duplicate() {
let cache = setup_cache();
let validator = NoDuplicatesValidator;
let links = vec![TestLink {
id: 1,
start: 1001,
end: 2001,
}];
let result = validator.validate(1001, 2001, &cache, &links);
assert_eq!(
result,
ValidationResult::Invalid(ValidationError::DuplicateLink)
);
}
#[test]
fn validation_returns_the_same_normalized_endpoints_for_both_gesture_directions() {
let cache = setup_cache();
let links: Vec<TestLink> = vec![];
let output_first =
validate_and_normalize_link(1001, 2001, &cache, &links, 2, &NoDuplicatesValidator);
let input_first =
validate_and_normalize_link(2001, 1001, &cache, &links, 2, &NoDuplicatesValidator);
let expected = Ok(NormalizedLink {
output_pin_id: 1001,
input_pin_id: 2001,
});
assert_eq!(output_first, expected);
assert_eq!(input_first, expected);
}
#[test]
fn reverse_gesture_is_rejected_after_normalization_when_link_exists() {
let cache = setup_cache();
let links = vec![TestLink {
id: 1,
start: 1001,
end: 2001,
}];
assert_eq!(
validate_and_normalize_link(2001, 1001, &cache, &links, 2, &NoDuplicatesValidator,),
Err(ValidationError::DuplicateLink),
);
}
#[test]
fn topology_rules_receive_normalized_endpoints() {
struct RequireExpectedOrder;
impl<N, L> LinkValidator<N, L> for RequireExpectedOrder {
fn validate(
&self,
start_pin: i32,
end_pin: i32,
_cache: &GeometryCache<N>,
_links: &[L],
) -> ValidationResult {
if (start_pin, end_pin) == (1001, 2001) {
ValidationResult::Valid
} else {
ValidationResult::Invalid(ValidationError::Custom(format!(
"received ({start_pin}, {end_pin})"
)))
}
}
}
let cache = setup_cache();
let links: Vec<TestLink> = vec![];
assert!(
validate_and_normalize_link(2001, 1001, &cache, &links, 2, &RequireExpectedOrder,)
.is_ok()
);
}
#[test]
fn test_composite_validator_passes_all() {
let cache = setup_cache();
let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
.with(BasicLinkValidator::new(2))
.with(NoDuplicatesValidator);
let links = vec![];
let result = validator.validate(1001, 2001, &cache, &links);
assert!(result.is_valid());
}
#[test]
fn test_composite_validator_short_circuits_on_basic() {
let cache = setup_cache();
let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
.with(BasicLinkValidator::new(2))
.with(NoDuplicatesValidator);
let links = vec![];
let result = validator.validate(1001, 1001, &cache, &links);
assert_eq!(result, ValidationResult::Invalid(ValidationError::SamePin));
}
#[test]
fn test_composite_validator_short_circuits_on_duplicates() {
let cache = setup_cache();
let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
.with(BasicLinkValidator::new(2))
.with(NoDuplicatesValidator);
let links = vec![TestLink {
id: 1,
start: 1001,
end: 2001,
}];
let result = validator.validate(1001, 2001, &cache, &links);
assert_eq!(
result,
ValidationResult::Invalid(ValidationError::DuplicateLink)
);
}
#[test]
fn test_validator_validate_directly() {
let cache = setup_cache();
let validator = BasicLinkValidator::new(2);
let links: Vec<TestLink> = vec![];
let result = validator.validate(1001, 2001, &cache, &links);
assert!(result.is_valid());
}
#[test]
fn test_validation_result_and_combinator() {
let result1 = ValidationResult::Valid;
let result2 = ValidationResult::Valid;
assert!(result1.and(result2).is_valid());
let result1 = ValidationResult::Valid;
let result2 = ValidationResult::Invalid(ValidationError::SamePin);
assert_eq!(
result1.and(result2),
ValidationResult::Invalid(ValidationError::SamePin)
);
let result1 = ValidationResult::Invalid(ValidationError::SameNode);
let result2 = ValidationResult::Valid;
assert_eq!(
result1.and(result2),
ValidationResult::Invalid(ValidationError::SameNode)
);
let result1 = ValidationResult::Invalid(ValidationError::SameNode);
let result2 = ValidationResult::Invalid(ValidationError::SamePin);
assert_eq!(
result1.and(result2),
ValidationResult::Invalid(ValidationError::SameNode)
);
}
#[test]
fn test_validation_error_display() {
assert_eq!(
format!("{}", ValidationError::PinNotFound(42)),
"Pin 42 not found"
);
assert_eq!(
format!("{}", ValidationError::SamePin),
"Cannot link pin to itself"
);
assert_eq!(
format!("{}", ValidationError::SameNode),
"Cannot link pins on same node"
);
assert_eq!(
format!("{}", ValidationError::IncompatibleDirection),
"Must connect input to output"
);
assert_eq!(
format!("{}", ValidationError::DuplicateLink),
"Link already exists"
);
assert_eq!(
format!(
"{}",
ValidationError::MaxConnectionsReached {
pin_id: 123,
max: 3
}
),
"Pin 123 has reached max 3 connections"
);
assert_eq!(
format!(
"{}",
ValidationError::TypeMismatch {
expected: 1,
found: 2
}
),
"Type mismatch: expected 1, found 2"
);
assert_eq!(
format!("{}", ValidationError::Custom("Test error".to_string())),
"Test error"
);
}
#[test]
fn test_custom_validator() {
#[derive(Clone, Copy)]
struct FanOutValidator {
max_connections: usize,
}
impl<N, L> LinkValidator<N, L> for FanOutValidator
where
L: LinkModel,
{
fn validate(
&self,
start_pin: i32,
_end_pin: i32,
_cache: &GeometryCache<N>,
links: &[L],
) -> ValidationResult {
let existing_count = links
.iter()
.filter(|link| link.start_pin_id() == start_pin)
.count();
if existing_count >= self.max_connections {
ValidationResult::Invalid(ValidationError::MaxConnectionsReached {
pin_id: start_pin,
max: self.max_connections,
})
} else {
ValidationResult::Valid
}
}
}
let cache = setup_cache();
let validator = FanOutValidator { max_connections: 1 };
let existing_links = vec![TestLink {
id: 1,
start: 1001,
end: 2001,
}];
let result = validator.validate(1001, 2002, &cache, &existing_links);
assert_eq!(
result,
ValidationResult::Invalid(ValidationError::MaxConnectionsReached {
pin_id: 1001,
max: 1,
})
);
let no_links: Vec<TestLink> = vec![];
let result = validator.validate(1001, 2001, &cache, &no_links);
assert!(result.is_valid());
}
#[test]
fn test_find_links_connected_to_node_by_start() {
let cache = setup_cache();
let links = vec![
TestLink {
id: 1,
start: 1001,
end: 2001,
},
TestLink {
id: 2,
start: 2001,
end: 1001,
},
];
let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
assert!(connected.contains(&1));
assert!(connected.contains(&2));
}
#[test]
fn test_find_links_connected_to_node_no_connections() {
let cache = setup_cache();
let links = vec![TestLink {
id: 1,
start: 1001,
end: 2001,
}];
let connected = GraphLogic::find_links_connected_to_node(999, links.into_iter(), &cache);
assert!(connected.is_empty());
}
#[test]
fn test_find_links_connected_to_node_empty_links() {
let cache = setup_cache();
let links: Vec<TestLink> = vec![];
let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
assert!(connected.is_empty());
}
#[test]
fn test_find_links_connected_to_node_multiple_pins() {
let mut cache = setup_cache();
cache.pin_positions.insert(
1002,
StoredPin {
node_id: 1,
pin_type: 1,
rel_x: 0.0,
rel_y: 40.0,
},
);
let links = vec![
TestLink {
id: 1,
start: 1001,
end: 2001,
},
TestLink {
id: 2,
start: 2001,
end: 1002,
},
TestLink {
id: 3,
start: 2001,
end: 2002,
}, ];
let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
assert!(connected.contains(&1));
assert!(connected.contains(&2));
assert!(!connected.contains(&3));
}
#[test]
fn test_normalize_link_direction_output_first() {
let cache = setup_cache();
let result = GraphLogic::normalize_link_direction(1001, 2001, &cache, 2);
assert_eq!(result, Some((1001, 2001)));
}
#[test]
fn test_normalize_link_direction_input_first() {
let cache = setup_cache();
let result = GraphLogic::normalize_link_direction(2001, 1001, &cache, 2);
assert_eq!(result, Some((1001, 2001)));
}
#[test]
fn test_normalize_link_direction_missing_pin() {
let cache = setup_cache();
let result = GraphLogic::normalize_link_direction(9999, 2001, &cache, 2);
assert!(result.is_none());
}
#[test]
fn test_duplicate_link_exists_true() {
let links = vec![TestLink {
id: 1,
start: 1001,
end: 2001,
}];
assert!(GraphLogic::duplicate_link_exists(1001, 2001, links));
}
#[test]
fn test_duplicate_link_exists_false() {
let links = vec![TestLink {
id: 1,
start: 1001,
end: 2001,
}];
assert!(!GraphLogic::duplicate_link_exists(1001, 2002, links));
}
#[test]
fn test_duplicate_link_exists_empty() {
let links: Vec<TestLink> = vec![];
assert!(!GraphLogic::duplicate_link_exists(1001, 2001, links));
}
#[test]
fn test_duplicate_link_exists_direction_matters() {
let links = vec![TestLink {
id: 1,
start: 1001,
end: 2001,
}];
assert!(!GraphLogic::duplicate_link_exists(2001, 1001, links));
}
#[test]
fn test_find_node_by_id_found() {
#[derive(Clone)]
struct TestNode {
id: i32,
name: String,
}
let model = std::rc::Rc::new(VecModel::from(vec![
TestNode {
id: 1,
name: "Node 1".to_string(),
},
TestNode {
id: 2,
name: "Node 2".to_string(),
},
TestNode {
id: 3,
name: "Node 3".to_string(),
},
]));
let result = GraphLogic::find_node_by_id(&model, 2, |n| n.id);
assert!(result.is_some());
let (index, node) = result.unwrap();
assert_eq!(index, 1);
assert_eq!(node.id, 2);
assert_eq!(node.name, "Node 2");
}
#[test]
fn test_find_node_by_id_not_found() {
#[derive(Clone)]
struct TestNode {
id: i32,
}
let model = std::rc::Rc::new(VecModel::from(vec![TestNode { id: 1 }, TestNode { id: 2 }]));
let result = GraphLogic::find_node_by_id(&model, 999, |n| n.id);
assert!(result.is_none());
}
#[test]
fn test_find_node_by_id_empty_model() {
#[derive(Clone)]
struct TestNode {
id: i32,
}
let model = std::rc::Rc::new(VecModel::<TestNode>::default());
let result = GraphLogic::find_node_by_id(&model, 1, |n| n.id);
assert!(result.is_none());
}
#[test]
fn test_find_node_by_id_first_match() {
#[derive(Clone)]
struct TestNode {
id: i32,
value: i32,
}
let model = std::rc::Rc::new(VecModel::from(vec![
TestNode { id: 1, value: 100 },
TestNode { id: 1, value: 200 },
]));
let result = GraphLogic::find_node_by_id(&model, 1, |n| n.id);
assert!(result.is_some());
let (index, node) = result.unwrap();
assert_eq!(index, 0);
assert_eq!(node.value, 100);
}
#[derive(Clone)]
struct TestMovableNode {
id: i32,
x: f32,
y: f32,
selected: bool,
draggable: bool,
}
impl MovableNode for TestMovableNode {
fn id(&self) -> i32 {
self.id
}
fn x(&self) -> f32 {
self.x
}
fn y(&self) -> f32 {
self.y
}
fn selected(&self) -> bool {
self.selected
}
fn set_x(&mut self, x: f32) {
self.x = x;
}
fn set_y(&mut self, y: f32) {
self.y = y;
}
fn draggable(&self) -> bool {
self.draggable
}
}
fn movable_model(rows: &[(i32, f32, f32, bool)]) -> std::rc::Rc<VecModel<TestMovableNode>> {
std::rc::Rc::new(VecModel::from(
rows.iter()
.map(|&(id, x, y, selected)| TestMovableNode {
id,
x,
y,
selected,
draggable: true,
})
.collect::<Vec<_>>(),
))
}
fn positions(model: &VecModel<TestMovableNode>) -> Vec<(f32, f32)> {
(0..model.row_count())
.filter_map(|i| model.row_data(i))
.map(|n| (n.x, n.y))
.collect()
}
#[test]
fn commit_drag_moves_the_whole_selection() {
let model = movable_model(&[
(1, 0.0, 0.0, true),
(2, 100.0, 100.0, false),
(3, 200.0, 200.0, true),
]);
GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
assert_eq!(
positions(&model),
vec![(10.0, 20.0), (100.0, 100.0), (210.0, 220.0)]
);
}
#[test]
fn commit_drag_moves_the_dragged_node_even_when_nothing_is_selected() {
let model = movable_model(&[(1, 50.0, 50.0, false), (2, 0.0, 0.0, false)]);
GraphLogic::commit_drag(&model, 1, 100.0, 100.0);
assert_eq!(positions(&model), vec![(150.0, 150.0), (0.0, 0.0)]);
}
#[test]
fn commit_drag_ignores_a_dragged_id_from_another_model() {
let model = movable_model(&[(1, 0.0, 0.0, true), (2, 100.0, 100.0, false)]);
GraphLogic::commit_drag(&model, 99, 10.0, 10.0);
assert_eq!(positions(&model), vec![(10.0, 10.0), (100.0, 100.0)]);
}
#[test]
fn commit_drag_does_not_move_a_selected_node_twice() {
let model = movable_model(&[(1, 0.0, 0.0, true)]);
GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
assert_eq!(positions(&model), vec![(10.0, 20.0)]);
}
#[test]
fn commit_drag_accepts_a_negative_delta() {
let model = movable_model(&[(1, 100.0, 100.0, true)]);
GraphLogic::commit_drag(&model, 1, -50.0, -30.0);
assert_eq!(positions(&model), vec![(50.0, 70.0)]);
}
#[test]
fn commit_drag_leaves_a_selected_undraggable_node_in_place() {
let model = movable_model(&[(1, 0.0, 0.0, true), (2, 100.0, 100.0, true)]);
let mut undraggable = model.row_data(1).unwrap();
undraggable.draggable = false;
model.set_row_data(1, undraggable);
GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
assert_eq!(positions(&model), vec![(10.0, 20.0), (100.0, 100.0)]);
}
}
impl crate::nodeeditor::LinkData {
pub fn new(id: i32, start_pin_id: i32, end_pin_id: i32, color: Color) -> Self {
Self {
id,
start_pin_id,
end_pin_id,
color,
line_width: 2.0,
status: -1,
selected: false,
..Default::default()
}
}
}
#[cfg(test)]
mod contract_tests {
use super::*;
#[test]
fn normalization_requires_both_endpoints() {
let mut cache = GeometryCache::<SimpleNodeGeometry>::new();
cache.handle_pin_report(1, 1, 2, 0.0, 0.0);
assert_eq!(GraphLogic::normalize_link_direction(1, 2, &cache, 2), None);
assert_eq!(GraphLogic::normalize_link_direction(2, 1, &cache, 2), None);
}
#[test]
fn colored_link_has_no_status_override() {
let color = Color::from_rgb_u8(1, 2, 3);
let link = crate::LinkData::new(0, 1, 2, color);
assert_eq!(link.color, color);
assert_eq!(link.status, -1);
assert_eq!(link.line_width, 2.0);
assert!(!link.selected);
}
}