-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxpath.rs
More file actions
1733 lines (1589 loc) · 61.7 KB
/
Copy pathxpath.rs
File metadata and controls
1733 lines (1589 loc) · 61.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
use platynui_core::ui::PatternName;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use platynui_core::provider::ProviderError;
use platynui_core::ui::attribute_names;
use platynui_core::ui::identifiers::RuntimeId;
use platynui_core::ui::{Namespace as UiNamespace, UiAttribute, UiNode, UiValue};
use platynui_xpath::compiler;
use platynui_xpath::engine::evaluator;
use platynui_xpath::engine::runtime::{DynamicContextBuilder, StaticContextBuilder};
use platynui_xpath::model::{NodeKind, QName};
use platynui_xpath::xdm::XdmAtomicValue;
use platynui_xpath::{self, XdmNode};
use std::sync::LazyLock;
use thiserror::Error;
const CONTROL_NS_URI: &str = "urn:platynui:control";
const ITEM_NS_URI: &str = "urn:platynui:item";
const APP_NS_URI: &str = "urn:platynui:app";
const NATIVE_NS_URI: &str = "urn:platynui:native";
type NodeIterator = Box<dyn Iterator<Item = Arc<dyn UiNode>> + Send>;
type AttributeIterator = Box<dyn Iterator<Item = Arc<dyn UiAttribute>> + Send>;
type NodeIteratorCell = Arc<Mutex<Option<NodeIterator>>>;
type AttributeIteratorCell = Arc<Mutex<Option<AttributeIterator>>>;
type NodeCacheCell = Arc<Mutex<Vec<RuntimeXdmNode>>>;
type ParentCacheCell = Arc<Mutex<Option<Option<RuntimeXdmNode>>>>;
type SharedFlag = Arc<AtomicBool>;
/// Cross-evaluation XDM tree cache.
///
/// `Clone + Send + Sync` so a single runtime-owned cache can be shared across
/// threads while still preserving explicit invalidation semantics.
#[derive(Clone)]
pub struct XdmCache {
inner: Arc<Mutex<Option<(RuntimeId, RuntimeXdmNode)>>>,
}
impl XdmCache {
pub fn new() -> Self {
Self { inner: Arc::new(Mutex::new(None)) }
}
pub fn clear(&self) {
self.inner.lock().expect("xdm cache mutex poisoned").take();
}
}
impl Default for XdmCache {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for XdmCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let has_entry = self.inner.lock().expect("xdm cache mutex poisoned").is_some();
f.debug_struct("XdmCache").field("cached", &has_entry).finish()
}
}
pub trait NodeResolver: Send + Sync {
fn resolve(&self, runtime_id: &RuntimeId) -> Result<Option<Arc<dyn UiNode>>, ProviderError>;
}
#[derive(Clone)]
#[must_use]
pub struct EvaluateOptions {
desktop: Arc<dyn UiNode>,
invalidate_before_eval: bool,
resolver: Option<Arc<dyn NodeResolver>>,
cache: Option<XdmCache>,
cancel_flag: Option<Arc<AtomicBool>>,
}
impl EvaluateOptions {
pub fn new(desktop: Arc<dyn UiNode>) -> Self {
Self { desktop, invalidate_before_eval: false, resolver: None, cache: None, cancel_flag: None }
}
pub fn desktop(&self) -> Arc<dyn UiNode> {
Arc::clone(&self.desktop)
}
pub fn with_invalidation(mut self, invalidate: bool) -> Self {
self.invalidate_before_eval = invalidate;
self
}
pub fn invalidate_before_eval(&self) -> bool {
self.invalidate_before_eval
}
pub fn with_node_resolver(mut self, resolver: Arc<dyn NodeResolver>) -> Self {
self.resolver = Some(resolver);
self
}
pub fn node_resolver(&self) -> Option<Arc<dyn NodeResolver>> {
self.resolver.as_ref().map(Arc::clone)
}
pub fn with_cache(mut self, cache: XdmCache) -> Self {
self.cache = Some(cache);
self
}
pub fn without_cache(mut self) -> Self {
self.cache = None;
self
}
pub fn cache(&self) -> Option<&XdmCache> {
self.cache.as_ref()
}
pub fn with_cancel_flag(mut self, flag: Arc<AtomicBool>) -> Self {
self.cancel_flag = Some(flag);
self
}
pub fn cancel_flag(&self) -> Option<&Arc<AtomicBool>> {
self.cancel_flag.as_ref()
}
}
#[derive(Debug, Error)]
pub enum EvaluateError {
#[error("XPath evaluation failed {0}")]
XPath(#[from] platynui_xpath::engine::runtime::Error),
#[error("context node not part of current evaluation (runtime id: {0})")]
ContextNodeUnknown(String),
#[error("provider error during context resolution: {0}")]
Provider(#[from] ProviderError),
}
#[derive(Clone)]
pub struct EvaluatedAttribute {
pub owner: Arc<dyn UiNode>,
pub namespace: UiNamespace,
pub name: String,
pub value: UiValue,
}
impl std::fmt::Debug for EvaluatedAttribute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EvaluatedAttribute")
.field("namespace", &self.namespace)
.field("name", &self.name)
.field("value", &self.value)
.finish()
}
}
#[derive(Clone)]
pub enum EvaluationItem {
Node(Arc<dyn UiNode>),
Attribute(EvaluatedAttribute),
Value(UiValue),
}
impl std::fmt::Debug for EvaluationItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EvaluationItem::Node(node) => f.debug_tuple("Node").field(&node.runtime_id().as_str()).finish(),
EvaluationItem::Attribute(attr) => f.debug_tuple("Attribute").field(attr).finish(),
EvaluationItem::Value(value) => f.debug_tuple("Value").field(value).finish(),
}
}
}
pub fn evaluate(
node: Option<Arc<dyn UiNode>>,
xpath: &str,
options: EvaluateOptions,
) -> Result<Vec<EvaluationItem>, EvaluateError> {
tracing::debug!(xpath, cached = options.cache().is_some(), "xpath evaluate");
let iter = evaluate_iter(node, xpath, options)?;
iter.collect()
}
/// Returns whether an XPath expression's top-level node selection is relative to the context node —
/// a relative path (`.//x`, `child::x`) or the context item (`.`). Absolute paths (`/x`, `//x`),
/// filtered/parenthesized absolute paths (`(//x)[1]`) and expressions that do not select nodes from
/// the context (`count(...)`, comparisons, ...) are independent; compound forms (if/for/let,
/// sequences) are relative iff a produced branch is. Parses only; no context node or backend is
/// required.
pub fn is_context_dependent(xpath: &str) -> Result<bool, EvaluateError> {
Ok(platynui_xpath::parser::parse(xpath)?.is_context_dependent())
}
pub struct EvaluationStream {
inner: Box<dyn Iterator<Item = Result<EvaluationItem, EvaluateError>>>,
}
impl Iterator for EvaluationStream {
type Item = Result<EvaluationItem, EvaluateError>;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
impl EvaluationStream {
pub fn new(node: Option<Arc<dyn UiNode>>, xpath: String, options: EvaluateOptions) -> Result<Self, EvaluateError> {
let context = resolve_context(node.as_ref(), &options)?;
if options.invalidate_before_eval() {
context.invalidate();
}
let xdm_root = get_or_create_xdm_root(&context, options.invalidate_before_eval(), options.cache());
let static_ctx = build_static_context();
let compiled = compiler::compile_with_context(&xpath, static_ctx)?;
let mut dyn_builder = DynamicContextBuilder::new();
dyn_builder = dyn_builder.with_context_item(xdm_root);
if let Some(flag) = options.cancel_flag() {
dyn_builder = dyn_builder.with_cancel_flag(Arc::clone(flag));
}
let dyn_ctx = dyn_builder.build();
let stream = evaluator::evaluate_stream(&compiled, &dyn_ctx)?;
let it = eval_stream_to_iter(stream);
Ok(Self { inner: Box::new(it) })
}
}
pub fn evaluate_iter(
node: Option<Arc<dyn UiNode>>,
xpath: &str,
options: EvaluateOptions,
) -> Result<impl Iterator<Item = Result<EvaluationItem, EvaluateError>>, EvaluateError> {
tracing::debug!(xpath, cached = options.cache().is_some(), "xpath evaluate_iter");
let context = resolve_context(node.as_ref(), &options)?;
if options.invalidate_before_eval() {
context.invalidate();
}
let xdm_root = get_or_create_xdm_root(&context, options.invalidate_before_eval(), options.cache());
let static_ctx = build_static_context();
let compiled = compiler::compile_with_context(xpath, static_ctx)?;
let mut dyn_builder = DynamicContextBuilder::new();
dyn_builder = dyn_builder.with_context_item(xdm_root);
if let Some(flag) = options.cancel_flag() {
dyn_builder = dyn_builder.with_cancel_flag(Arc::clone(flag));
}
let dyn_ctx = dyn_builder.build();
let stream = evaluator::evaluate_stream(&compiled, &dyn_ctx)?;
Ok(eval_stream_to_iter(stream))
}
/// Resolve the effective context node for evaluation based on input node and options.
fn resolve_context(
node: Option<&Arc<dyn UiNode>>,
options: &EvaluateOptions,
) -> Result<Arc<dyn UiNode>, EvaluateError> {
let root = options.desktop();
let context = if let Some(node_ref) = node {
if let Some(resolver) = options.node_resolver() {
let runtime_id = node_ref.runtime_id().clone();
match resolver.resolve(&runtime_id)? {
Some(resolved) => resolved,
None => return Err(EvaluateError::ContextNodeUnknown(runtime_id.to_string())),
}
} else {
Arc::clone(node_ref)
}
} else {
root.clone()
};
Ok(context)
}
fn get_or_create_xdm_root(context: &Arc<dyn UiNode>, force_rebuild: bool, cache: Option<&XdmCache>) -> RuntimeXdmNode {
let Some(cache) = cache else {
return RuntimeXdmNode::from_node(Arc::clone(context));
};
let mut slot = cache.inner.lock().expect("xdm cache mutex poisoned");
if !force_rebuild {
let context_id = context.runtime_id();
if let Some((cached_id, cached_node)) = slot.as_ref()
&& *cached_id == *context_id
&& cached_node.is_valid()
{
let node = cached_node.clone();
node.prepare_for_evaluation();
return node;
}
}
let context_id = context.runtime_id().clone();
let node = RuntimeXdmNode::from_node(Arc::clone(context));
*slot = Some((context_id, node.clone()));
node
}
/// Build the static context with PlatynUI namespaces configured.
fn build_static_context() -> &'static platynui_xpath::engine::runtime::StaticContext {
static STATIC_CTX: LazyLock<platynui_xpath::engine::runtime::StaticContext> = LazyLock::new(|| {
StaticContextBuilder::new()
.with_default_element_namespace(CONTROL_NS_URI)
.with_namespace("control", CONTROL_NS_URI)
.with_namespace("item", ITEM_NS_URI)
.with_namespace("app", APP_NS_URI)
.with_namespace("native", NATIVE_NS_URI)
.build()
});
&STATIC_CTX
}
/// Map a stream of XDM items to `EvaluationItem`s, propagating evaluation errors.
fn eval_stream_to_iter<I>(iter: I) -> impl Iterator<Item = Result<EvaluationItem, EvaluateError>>
where
I: IntoIterator<
Item = Result<platynui_xpath::xdm::XdmItem<RuntimeXdmNode>, platynui_xpath::engine::runtime::Error>,
>,
{
use platynui_xpath::xdm::XdmItem;
iter.into_iter().map(|res| match res {
Err(e) => Err(EvaluateError::XPath(e)),
Ok(item) => match item {
XdmItem::Node(node) => match node {
RuntimeXdmNode::Document(doc) => Ok(EvaluationItem::Node(doc.root.clone())),
RuntimeXdmNode::Element(elem) => Ok(EvaluationItem::Node(elem.node.clone())),
RuntimeXdmNode::Attribute(attr) => Ok(EvaluationItem::Attribute(attr.to_evaluated())),
},
XdmItem::Atomic(atom) => Ok(EvaluationItem::Value(atomic_to_ui_value(&atom))),
},
})
}
#[derive(Clone)]
enum RuntimeXdmNode {
Document(DocumentData),
Element(ElementData),
Attribute(AttributeData),
}
impl RuntimeXdmNode {
fn document(root: Arc<dyn UiNode>) -> Self {
let runtime_id = root.runtime_id().clone();
RuntimeXdmNode::Document(DocumentData::new(root, runtime_id))
}
fn element(node: Arc<dyn UiNode>) -> Self {
let runtime_id = node.runtime_id().clone();
tracing::trace!(
runtime_id = %runtime_id,
"RuntimeXdmNode::element: resolving namespace/role",
);
let namespace = node.namespace();
let role = node.role().to_string();
let order_key = node.doc_order_key();
tracing::trace!(
runtime_id = %runtime_id,
role = %role,
"RuntimeXdmNode::element: resolved",
);
RuntimeXdmNode::Element(ElementData::new(node, runtime_id, namespace, role, order_key))
}
fn from_node(node: Arc<dyn UiNode>) -> Self {
if node.parent().is_none() { RuntimeXdmNode::document(node) } else { RuntimeXdmNode::element(node) }
}
fn is_valid(&self) -> bool {
match self {
RuntimeXdmNode::Document(doc) => doc.root.is_valid(),
RuntimeXdmNode::Element(elem) => elem.node.is_valid(),
RuntimeXdmNode::Attribute(attr) => attr.owner.is_valid(),
}
}
fn prepare_for_evaluation(&self) {
match self {
RuntimeXdmNode::Document(doc) => {
doc.attrs_cache.lock().expect("document attrs cache mutex poisoned").clear();
doc.attrs_finished.store(false, Ordering::Release);
*doc.attrs_inner.lock().expect("document attrs iterator mutex poisoned") = None;
doc.children_validated.store(false, Ordering::Release);
let children = doc.children_cache.lock().expect("document children cache mutex poisoned").clone();
for child in &children {
child.prepare_for_evaluation();
}
}
RuntimeXdmNode::Element(elem) => {
elem.attrs_cache.lock().expect("element attrs cache mutex poisoned").clear();
elem.attrs_finished.store(false, Ordering::Release);
*elem.attrs_inner.lock().expect("element attrs iterator mutex poisoned") = None;
elem.children_validated.store(false, Ordering::Release);
let children = elem.children_cache.lock().expect("element children cache mutex poisoned").clone();
for child in &children {
child.prepare_for_evaluation();
}
}
RuntimeXdmNode::Attribute(_) => {}
}
}
}
impl PartialEq for RuntimeXdmNode {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(RuntimeXdmNode::Document(a), RuntimeXdmNode::Document(b)) => a.runtime_id == b.runtime_id,
(RuntimeXdmNode::Element(a), RuntimeXdmNode::Element(b)) => {
a.runtime_id == b.runtime_id && a.order_key == b.order_key
}
(RuntimeXdmNode::Attribute(a), RuntimeXdmNode::Attribute(b)) => {
a.owner_runtime_id == b.owner_runtime_id && a.namespace == b.namespace && a.name == b.name
}
_ => false,
}
}
}
impl Eq for RuntimeXdmNode {}
impl std::fmt::Debug for RuntimeXdmNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RuntimeXdmNode::Document(doc) => f.debug_struct("Document").field("runtime_id", &doc.runtime_id).finish(),
RuntimeXdmNode::Element(elem) => f
.debug_struct("Element")
.field("runtime_id", &elem.runtime_id)
.field("order_key", &elem.order_key)
.field("role", &elem.role)
.finish(),
RuntimeXdmNode::Attribute(attr) => {
f.debug_struct("Attribute").field("owner", &attr.owner_runtime_id).field("name", &attr.name).finish()
}
}
}
}
impl XdmNode for RuntimeXdmNode {
type Children<'a>
= NodeChildrenIter<'a>
where
Self: 'a;
type Attributes<'a>
= NodeAttributeIter<'a>
where
Self: 'a;
type Namespaces<'a>
= std::iter::Empty<RuntimeXdmNode>
where
Self: 'a;
fn kind(&self) -> NodeKind {
match self {
RuntimeXdmNode::Document(_) => NodeKind::Document,
RuntimeXdmNode::Element(_) => NodeKind::Element,
RuntimeXdmNode::Attribute(_) => NodeKind::Attribute,
}
}
fn name(&self) -> Option<QName> {
match self {
RuntimeXdmNode::Document(_) => None,
RuntimeXdmNode::Element(elem) => Some(elem.qname.clone()),
RuntimeXdmNode::Attribute(attr) => Some(attr.qname.clone()),
}
}
fn typed_value(&self) -> Vec<XdmAtomicValue> {
match self {
RuntimeXdmNode::Document(_) | RuntimeXdmNode::Element(_) => Vec::new(),
RuntimeXdmNode::Attribute(attr) => attr.typed().clone(),
}
}
fn base_uri(&self) -> Option<String> {
None
}
fn parent(&self) -> Option<Self> {
match self {
RuntimeXdmNode::Document(_) => None,
RuntimeXdmNode::Element(elem) => {
if let Some(cached) = elem.parent_cache.lock().expect("parent cache mutex poisoned").as_ref() {
return cached.clone();
}
let computed: Option<RuntimeXdmNode> = match elem.node.parent() {
Some(parent) => match parent.upgrade() {
Some(p) => Some(RuntimeXdmNode::from_node(p)),
None => Some(RuntimeXdmNode::document(elem.node.clone())),
},
None => Some(RuntimeXdmNode::document(elem.node.clone())),
};
*elem.parent_cache.lock().expect("parent cache mutex poisoned") = Some(computed.clone());
computed
}
RuntimeXdmNode::Attribute(attr) => Some(RuntimeXdmNode::from_node(attr.owner.clone())),
}
}
fn children(&self) -> Self::Children<'_> {
match self {
RuntimeXdmNode::Document(doc) => {
if !doc.children_validated.load(Ordering::Acquire) {
let has_invalid = doc
.children_cache
.lock()
.expect("document children cache mutex poisoned")
.iter()
.any(|c| !c.is_valid());
if has_invalid {
doc.children_cache.lock().expect("document children cache mutex poisoned").clear();
doc.children_finished.store(false, Ordering::Release);
*doc.children_inner.lock().expect("document children iterator mutex poisoned") =
Some(doc.root.children());
}
doc.children_validated.store(true, Ordering::Release);
}
let needs_init = {
doc.children_inner.lock().expect("document children iterator mutex poisoned").is_none()
&& !doc.children_finished.load(Ordering::Acquire)
};
if needs_init {
*doc.children_inner.lock().expect("document children iterator mutex poisoned") =
Some(doc.root.children());
}
NodeChildrenIter::from_shared(
Arc::clone(&doc.children_inner),
Arc::clone(&doc.children_cache),
Arc::clone(&doc.children_finished),
)
.with_parent_node(self.clone())
}
RuntimeXdmNode::Element(elem) => {
if !elem.children_validated.load(Ordering::Acquire) {
let has_invalid = elem
.children_cache
.lock()
.expect("element children cache mutex poisoned")
.iter()
.any(|c| !c.is_valid());
if has_invalid {
elem.children_cache.lock().expect("element children cache mutex poisoned").clear();
elem.children_finished.store(false, Ordering::Release);
*elem.children_inner.lock().expect("element children iterator mutex poisoned") =
Some(elem.node.children());
}
elem.children_validated.store(true, Ordering::Release);
}
let needs_init = {
elem.children_inner.lock().expect("element children iterator mutex poisoned").is_none()
&& !elem.children_finished.load(Ordering::Acquire)
};
if needs_init {
*elem.children_inner.lock().expect("element children iterator mutex poisoned") =
Some(elem.node.children());
}
NodeChildrenIter::from_shared(
Arc::clone(&elem.children_inner),
Arc::clone(&elem.children_cache),
Arc::clone(&elem.children_finished),
)
.with_parent_node(self.clone())
}
RuntimeXdmNode::Attribute(_) => NodeChildrenIter::empty(),
}
}
fn attributes(&self) -> Self::Attributes<'_> {
match self {
RuntimeXdmNode::Document(doc) => {
let needs_init = {
doc.attrs_inner.lock().expect("document attrs iterator mutex poisoned").is_none()
&& !doc.attrs_finished.load(Ordering::Acquire)
};
if needs_init {
*doc.attrs_inner.lock().expect("document attrs iterator mutex poisoned") =
Some(doc.root.attributes());
}
NodeAttributeIter::from_shared(
doc.root.clone(),
Arc::clone(&doc.attrs_inner),
Arc::clone(&doc.attrs_cache),
Arc::clone(&doc.attrs_finished),
)
}
RuntimeXdmNode::Element(elem) => {
let needs_init = {
elem.attrs_inner.lock().expect("element attrs iterator mutex poisoned").is_none()
&& !elem.attrs_finished.load(Ordering::Acquire)
};
if needs_init {
*elem.attrs_inner.lock().expect("element attrs iterator mutex poisoned") =
Some(elem.node.attributes());
}
NodeAttributeIter::from_shared(
elem.node.clone(),
Arc::clone(&elem.attrs_inner),
Arc::clone(&elem.attrs_cache),
Arc::clone(&elem.attrs_finished),
)
}
RuntimeXdmNode::Attribute(_) => NodeAttributeIter::empty(),
}
}
fn namespaces(&self) -> Self::Namespaces<'_> {
std::iter::empty()
}
fn doc_order_key(&self) -> Option<u64> {
match self {
RuntimeXdmNode::Element(elem) => elem.order_key,
RuntimeXdmNode::Document(_) | RuntimeXdmNode::Attribute(_) => None,
}
}
/// O(1) attribute lookup via the provider's `UiNode::attribute()` method,
/// bypassing the full attribute iterator. This avoids materialising
/// expensive native properties (≈1 050 COM calls per element on Windows)
/// when the requested attribute lives in a cheaper namespace.
fn attribute_by_name(&self, name: &QName) -> Option<Self> {
let node: &Arc<dyn UiNode> = match self {
RuntimeXdmNode::Document(doc) => &doc.root,
RuntimeXdmNode::Element(elem) => &elem.node,
RuntimeXdmNode::Attribute(_) => return None,
};
// Map XPath namespace URI to provider UiNamespace.
let ui_ns = match &name.ns_uri {
None => UiNamespace::Control,
Some(uri) => match uri.as_str() {
CONTROL_NS_URI => UiNamespace::Control,
ITEM_NS_URI => UiNamespace::Item,
APP_NS_URI => UiNamespace::App,
NATIVE_NS_URI => UiNamespace::Native,
_ => return None,
},
};
// Fast path: direct provider lookup (handles Role, Name, Id, Bounds, …)
if let Some(attr) = node.attribute(ui_ns, &name.local) {
return Some(RuntimeXdmNode::Attribute(AttributeData::new_from_source(
node.clone(),
attr.namespace(),
attr.name().to_string(),
attr,
)));
}
// Handle virtual component attributes (e.g. Bounds.X, ActivationPoint.Y)
// that only exist inside the `NodeAttributeIter` expansion.
if ui_ns == UiNamespace::Control {
if let Some(suffix) = name.local.strip_prefix("Bounds.") {
let comp = match suffix {
"X" => Some(RectComp::X),
"Y" => Some(RectComp::Y),
"Width" => Some(RectComp::Width),
"Height" => Some(RectComp::Height),
_ => None,
};
if let Some(comp) = comp
&& let Some(base) = node.attribute(ui_ns, attribute_names::element::BOUNDS)
{
return Some(RuntimeXdmNode::Attribute(AttributeData::new_rect_component(
node.clone(),
ui_ns,
base,
attribute_names::element::BOUNDS,
comp,
)));
}
}
if let Some(suffix) = name.local.strip_prefix("ActivationPoint.") {
let comp = match suffix {
"X" => Some(PointComp::X),
"Y" => Some(PointComp::Y),
_ => None,
};
if let Some(comp) = comp
&& let Some(base) = node.attribute(ui_ns, attribute_names::activation_target::ACTIVATION_POINT)
{
return Some(RuntimeXdmNode::Attribute(AttributeData::new_point_component(
node.clone(),
ui_ns,
base,
attribute_names::activation_target::ACTIVATION_POINT,
comp,
)));
}
}
}
None
}
}
#[derive(Clone)]
struct DocumentData {
root: Arc<dyn UiNode>,
runtime_id: RuntimeId,
children_inner: NodeIteratorCell,
children_cache: NodeCacheCell,
children_finished: SharedFlag,
children_validated: SharedFlag,
attrs_inner: AttributeIteratorCell,
attrs_cache: NodeCacheCell,
attrs_finished: SharedFlag,
}
impl DocumentData {
fn new(root: Arc<dyn UiNode>, runtime_id: RuntimeId) -> Self {
Self {
root,
runtime_id,
children_inner: Arc::new(Mutex::new(None)),
children_cache: Arc::new(Mutex::new(Vec::new())),
children_finished: Arc::new(AtomicBool::new(false)),
children_validated: Arc::new(AtomicBool::new(false)),
attrs_inner: Arc::new(Mutex::new(None)),
attrs_cache: Arc::new(Mutex::new(Vec::new())),
attrs_finished: Arc::new(AtomicBool::new(false)),
}
}
}
#[derive(Clone)]
struct ElementData {
node: Arc<dyn UiNode>,
runtime_id: RuntimeId,
role: String,
qname: QName,
order_key: Option<u64>,
children_inner: NodeIteratorCell,
children_cache: NodeCacheCell,
children_finished: SharedFlag,
children_validated: SharedFlag,
attrs_inner: AttributeIteratorCell,
attrs_cache: NodeCacheCell,
attrs_finished: SharedFlag,
parent_cache: ParentCacheCell,
}
impl ElementData {
fn new(
node: Arc<dyn UiNode>,
runtime_id: RuntimeId,
namespace: UiNamespace,
role: String,
order_key: Option<u64>,
) -> Self {
let qname = element_qname(namespace, &role);
Self {
node,
runtime_id,
role,
qname,
order_key,
children_inner: Arc::new(Mutex::new(None)),
children_cache: Arc::new(Mutex::new(Vec::new())),
children_finished: Arc::new(AtomicBool::new(false)),
children_validated: Arc::new(AtomicBool::new(false)),
attrs_inner: Arc::new(Mutex::new(None)),
attrs_cache: Arc::new(Mutex::new(Vec::new())),
attrs_finished: Arc::new(AtomicBool::new(false)),
parent_cache: Arc::new(Mutex::new(None)),
}
}
}
#[derive(Clone)]
struct AttributeData {
owner: Arc<dyn UiNode>,
owner_runtime_id: RuntimeId,
namespace: UiNamespace,
name: String,
qname: QName,
// Lazy value provider (either direct source or derived component)
value_kind: ValueKind,
value_cell: std::sync::OnceLock<UiValue>,
typed_cell: std::sync::OnceLock<Vec<XdmAtomicValue>>,
}
// no StaticUiAttribute needed; attributes are sourced from provider or derived lazily
#[derive(Clone)]
enum ValueKind {
Source(Arc<dyn UiAttribute>),
RectComp { base: Arc<dyn UiAttribute>, comp: RectComp },
PointComp { base: Arc<dyn UiAttribute>, comp: PointComp },
}
#[derive(Clone)]
enum RectComp {
X,
Y,
Width,
Height,
}
#[derive(Clone)]
enum PointComp {
X,
Y,
}
impl AttributeData {
fn new_from_source(
owner: Arc<dyn UiNode>,
namespace: UiNamespace,
name: String,
source: Arc<dyn UiAttribute>,
) -> Self {
let owner_runtime_id = owner.runtime_id().clone();
let qname = attribute_qname(namespace, &name);
Self {
owner,
owner_runtime_id,
namespace,
name,
qname,
value_kind: ValueKind::Source(source),
value_cell: std::sync::OnceLock::new(),
typed_cell: std::sync::OnceLock::new(),
}
}
fn new_rect_component(
owner: Arc<dyn UiNode>,
namespace: UiNamespace,
base: Arc<dyn UiAttribute>,
base_name: &str,
comp: RectComp,
) -> Self {
let name = component_attribute_name(
base_name,
match comp {
RectComp::X => "X",
RectComp::Y => "Y",
RectComp::Width => "Width",
RectComp::Height => "Height",
},
);
let owner_runtime_id = owner.runtime_id().clone();
let qname = attribute_qname(namespace, &name);
Self {
owner,
owner_runtime_id,
namespace,
name,
qname,
value_kind: ValueKind::RectComp { base, comp },
value_cell: std::sync::OnceLock::new(),
typed_cell: std::sync::OnceLock::new(),
}
}
fn new_point_component(
owner: Arc<dyn UiNode>,
namespace: UiNamespace,
base: Arc<dyn UiAttribute>,
base_name: &str,
comp: PointComp,
) -> Self {
let name = component_attribute_name(
base_name,
match comp {
PointComp::X => "X",
PointComp::Y => "Y",
},
);
let owner_runtime_id = owner.runtime_id().clone();
let qname = attribute_qname(namespace, &name);
Self {
owner,
owner_runtime_id,
namespace,
name,
qname,
value_kind: ValueKind::PointComp { base, comp },
value_cell: std::sync::OnceLock::new(),
typed_cell: std::sync::OnceLock::new(),
}
}
fn value(&self) -> UiValue {
self.value_cell
.get_or_init(|| match &self.value_kind {
ValueKind::Source(src) => src.value(),
ValueKind::RectComp { base, comp } => match base.value() {
UiValue::Rect(r) => match comp {
RectComp::X => UiValue::from(r.x()),
RectComp::Y => UiValue::from(r.y()),
RectComp::Width => UiValue::from(r.width()),
RectComp::Height => UiValue::from(r.height()),
},
_ => UiValue::Null,
},
ValueKind::PointComp { base, comp } => match base.value() {
UiValue::Point(p) => match comp {
PointComp::X => UiValue::from(p.x()),
PointComp::Y => UiValue::from(p.y()),
},
_ => UiValue::Null,
},
})
.clone()
}
fn typed(&self) -> &Vec<XdmAtomicValue> {
self.typed_cell.get_or_init(|| ui_value_to_atomic_values(&self.value()))
}
fn to_evaluated(&self) -> EvaluatedAttribute {
EvaluatedAttribute {
owner: self.owner.clone(),
namespace: self.namespace,
name: self.name.clone(),
value: self.value(),
}
}
}
fn ui_value_to_atomic_values(value: &UiValue) -> Vec<XdmAtomicValue> {
match value {
UiValue::Null => Vec::new(),
UiValue::Bool(b) => vec![XdmAtomicValue::Boolean(*b)],
UiValue::Integer(i) => vec![XdmAtomicValue::Integer(*i)],
UiValue::Number(n) => vec![XdmAtomicValue::Double(*n)],
UiValue::String(s) => vec![XdmAtomicValue::String(s.clone())],
UiValue::Array(items) => {
serde_json::to_string(items).ok().map(|json| vec![XdmAtomicValue::String(json)]).unwrap_or_default()
}
UiValue::Object(map) => {
serde_json::to_string(map).ok().map(|json| vec![XdmAtomicValue::String(json)]).unwrap_or_default()
}
UiValue::Point(point) => {
serde_json::to_string(point).ok().map(|json| vec![XdmAtomicValue::String(json)]).unwrap_or_default()
}
UiValue::Size(size) => {
serde_json::to_string(size).ok().map(|json| vec![XdmAtomicValue::String(json)]).unwrap_or_default()
}
UiValue::Rect(rect) => {
serde_json::to_string(rect).ok().map(|json| vec![XdmAtomicValue::String(json)]).unwrap_or_default()
}
}
}
fn component_attribute_name(base: &str, suffix: &str) -> String {
format!("{}.{}", base, suffix)
}
fn element_qname(ns: UiNamespace, role: &str) -> QName {
QName {
prefix: namespace_prefix(ns).map(|p| p.to_string()),
local: role.to_string(),
ns_uri: Some(namespace_uri(ns).to_string()),
}
}
fn attribute_qname(ns: UiNamespace, name: &str) -> QName {
QName {
prefix: attribute_prefix(ns).map(|p| p.to_string()),
local: name.to_string(),
ns_uri: attribute_namespace(ns).map(|uri| uri.to_string()),
}
}
fn namespace_prefix(ns: UiNamespace) -> Option<&'static str> {
match ns {
UiNamespace::Control => None,
UiNamespace::Item => Some("item"),
UiNamespace::App => Some("app"),
UiNamespace::Native => Some("native"),
}
}
fn namespace_uri(ns: UiNamespace) -> &'static str {
match ns {
UiNamespace::Control => CONTROL_NS_URI,
UiNamespace::Item => ITEM_NS_URI,
UiNamespace::App => APP_NS_URI,
UiNamespace::Native => NATIVE_NS_URI,
}
}
fn attribute_prefix(ns: UiNamespace) -> Option<&'static str> {
match ns {
UiNamespace::Control => None,
UiNamespace::Item => Some("item"),
UiNamespace::App => Some("app"),
UiNamespace::Native => Some("native"),
}
}
fn attribute_namespace(ns: UiNamespace) -> Option<&'static str> {
match ns {
UiNamespace::Control => None,
UiNamespace::Item => Some(ITEM_NS_URI),
UiNamespace::App => Some(APP_NS_URI),
UiNamespace::Native => Some(NATIVE_NS_URI),
}