render_layout_tree.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. use std::collections::HashMap;
  2. #[derive(serde::Deserialize)]
  3. struct Margin {
  4. top: isize,
  5. bottom: isize,
  6. left: isize,
  7. right: isize,
  8. }
  9. #[derive(serde::Deserialize)]
  10. struct Node {
  11. id: usize,
  12. behaviour: String,
  13. child_arrangement: String,
  14. width_policy: [usize; 3],
  15. height_policy: [usize; 3],
  16. halign: String,
  17. valign: String,
  18. margin: Margin,
  19. table_cell: Option<[usize; 2]>,
  20. render_area: Option<[[usize; 2]; 2]>,
  21. children: Vec<Node>,
  22. }
  23. fn main() {
  24. let mut args = std::env::args();
  25. let execname = args.next().unwrap();
  26. if args.len() != 1 {
  27. println!("usage: {} path-to-json", execname);
  28. return
  29. }
  30. let fname = args.next().unwrap();
  31. let indata = std::fs::read(fname).expect("couldn't open file");
  32. let nodetree : Node = serde_json::from_slice(&indata).expect("couldn't parse file");
  33. let mut x_pos : HashMap<usize, usize> = HashMap::new();
  34. let mut y_pos : HashMap<usize, usize> = HashMap::new();
  35. let mut parents : HashMap<usize, usize> = HashMap::new();
  36. let mut siblings : HashMap<usize, usize> = HashMap::new();
  37. let mut dfs = vec![&nodetree];
  38. let mut max_x = 0;
  39. while let Some(node) = dfs.pop() {
  40. println!("visiting node {}", node.id);
  41. // X coordinate:
  42. // case 1: no sibling, so same x as parent
  43. // case 2: sibling, so use max_x + 1
  44. // Y coordinate:
  45. // always use parent's y pos + 1
  46. let x = match siblings.get(&node.id) {
  47. None => parents.get(&node.id).and_then(|p| x_pos.get(p)).cloned().unwrap_or(0),
  48. Some(_sib) => max_x + 1,
  49. };
  50. let y = parents.get(&node.id).and_then(|p| y_pos.get(p)).map(|v| v + 1).unwrap_or(0);
  51. max_x = max_x.max(x);
  52. x_pos.insert(node.id, x);
  53. y_pos.insert(node.id, y);
  54. let mut sibling : Option<usize> = None;
  55. for ch in node.children.iter() {
  56. parents.insert(ch.id, node.id);
  57. if let Some(sibling) = sibling {
  58. siblings.insert(ch.id, sibling);
  59. }
  60. sibling = Some(ch.id);
  61. dfs.push(ch);
  62. }
  63. }
  64. let mut yvalues = y_pos.values().collect::<Vec<_>>();
  65. yvalues.sort();
  66. yvalues.dedup();
  67. for y in yvalues {
  68. let mut line = y_pos.iter().filter(|(_,v)| *v == y).map(|(k,_)| (x_pos.get(k).unwrap(), k)).collect::<Vec<_>>();
  69. line.sort();
  70. println!("{line:?}");
  71. }
  72. }