render_layout_tree.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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
  48. .get(&node.id)
  49. .and_then(|p| x_pos.get(p))
  50. .cloned()
  51. .unwrap_or(0),
  52. Some(_sib) => max_x + 1,
  53. };
  54. let y = parents
  55. .get(&node.id)
  56. .and_then(|p| y_pos.get(p))
  57. .map(|v| v + 1)
  58. .unwrap_or(0);
  59. max_x = max_x.max(x);
  60. x_pos.insert(node.id, x);
  61. y_pos.insert(node.id, y);
  62. let mut sibling: Option<usize> = None;
  63. for ch in node.children.iter() {
  64. parents.insert(ch.id, node.id);
  65. if let Some(sibling) = sibling {
  66. siblings.insert(ch.id, sibling);
  67. }
  68. sibling = Some(ch.id);
  69. dfs.push(ch);
  70. }
  71. }
  72. let mut yvalues = y_pos.values().collect::<Vec<_>>();
  73. yvalues.sort();
  74. yvalues.dedup();
  75. for y in yvalues {
  76. let mut line = y_pos
  77. .iter()
  78. .filter(|(_, v)| *v == y)
  79. .map(|(k, _)| (x_pos.get(k).unwrap(), k))
  80. .collect::<Vec<_>>();
  81. line.sort();
  82. println!("{line:?}");
  83. }
  84. }