-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathmod.rs
1214 lines (1072 loc) · 42.3 KB
/
mod.rs
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 std::{
collections::{BTreeMap, HashMap, VecDeque},
fmt,
hash::{Hash, Hasher},
sync::RwLock,
};
use mlua::prelude::*;
use once_cell::sync::Lazy;
use rbx_dom_weak::{
types::{
Attributes as DomAttributes, Ref as DomRef, Variant as DomValue, VariantType as DomType,
},
Instance as DomInstance, InstanceBuilder as DomInstanceBuilder, WeakDom,
};
use crate::{
datatypes::{
attributes::{ensure_valid_attribute_name, ensure_valid_attribute_value},
conversion::{DomValueToLua, LuaToDomValue},
types::EnumItem,
userdata_impl_eq, userdata_impl_to_string,
},
shared::instance::{class_exists, class_is_a, find_property_info},
};
pub(crate) mod data_model;
pub(crate) mod workspace;
const PROPERTY_NAME_ATTRIBUTES: &str = "Attributes";
const PROPERTY_NAME_TAGS: &str = "Tags";
static INTERNAL_DOM: Lazy<RwLock<WeakDom>> =
Lazy::new(|| RwLock::new(WeakDom::new(DomInstanceBuilder::new("ROOT"))));
#[derive(Debug, Clone)]
pub struct Instance {
pub(crate) dom_ref: DomRef,
pub(crate) class_name: String,
}
impl Instance {
/**
Creates a new `Instance` from an existing dom object ref.
Panics if the instance does not exist in the internal dom,
or if the given dom object ref points to the dom root.
*/
pub(crate) fn new(dom_ref: DomRef) -> Self {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let instance = dom
.get_by_ref(dom_ref)
.expect("Failed to find instance in document");
if instance.referent() == dom.root_ref() {
panic!("Instances can not be created from dom roots")
}
Self {
dom_ref,
class_name: instance.class.clone(),
}
}
/**
Creates a new `Instance` from a dom object ref, if the instance exists.
Panics if the given dom object ref points to the dom root.
*/
pub(crate) fn new_opt(dom_ref: DomRef) -> Option<Self> {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
if let Some(instance) = dom.get_by_ref(dom_ref) {
if instance.referent() == dom.root_ref() {
panic!("Instances can not be created from dom roots")
}
Some(Self {
dom_ref,
class_name: instance.class.clone(),
})
} else {
None
}
}
/**
Creates a new orphaned `Instance` with a given class name.
An orphaned instance is an instance at the root of a weak dom.
*/
pub(crate) fn new_orphaned(class_name: impl AsRef<str>) -> Self {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let class_name = class_name.as_ref();
let instance = DomInstanceBuilder::new(class_name.to_string());
let dom_root = dom.root_ref();
let dom_ref = dom.insert(dom_root, instance);
Self {
dom_ref,
class_name: class_name.to_string(),
}
}
/**
Creates a new orphaned `Instance` by transferring
it from an external weak dom to the internal one.
An orphaned instance is an instance at the root of a weak dom.
Panics if the given dom ref is the root dom ref of the external weak dom.
*/
pub fn from_external_dom(external_dom: &mut WeakDom, external_dom_ref: DomRef) -> Self {
{
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let dom_root = dom.root_ref();
external_dom.transfer(external_dom_ref, &mut dom, dom_root);
}
Self::new(external_dom_ref)
}
/**
Clones an instance to an external weak dom.
This will place the instance as a child of the
root of the weak dom, and return its referent.
*/
pub fn clone_into_external_dom(self, external_dom: &mut WeakDom) -> DomRef {
let cloned = self.clone_instance();
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let internal_dom_ref = cloned.dom_ref;
let external_root_ref = external_dom.root_ref();
dom.transfer(internal_dom_ref, external_dom, external_root_ref);
internal_dom_ref
}
/**
Clones the instance and all of its descendants, and orphans it.
To then save the new instance it must be re-parented,
which matches the exact behavior of Roblox's instances.
### See Also
* [`Clone`](https://create.roblox.com/docs/reference/engine/classes/Instance#Clone)
on the Roblox Developer Hub
*/
pub fn clone_instance(&self) -> Instance {
// NOTE: We create a new scope here to avoid deadlocking since
// our clone implementation must have exclusive write access
let parent_ref = {
INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document")
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.parent()
};
// Keep track of a map from old ref -> new ref for each
// instance so that we can then transform properties that
// are instance refs into ones pointing at the new instances
let mut reference_map = HashMap::new();
let new_ref = Self::clone_inner(self.dom_ref, parent_ref, &mut reference_map);
let new_inst = Self::new(new_ref);
{
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let new_refs = reference_map.values().clone().collect::<Vec<_>>();
for new_ref in new_refs {
let new_inst = dom
.get_by_ref_mut(*new_ref)
.expect("Failed to find cloned instance in document");
for prop_value in new_inst.properties.values_mut() {
if let DomValue::Ref(prop_ref) = prop_value {
// NOTE: It is possible to get None here if the ref points to
// something outside of the newly cloned instance hierarchy
if let Some(new) = reference_map.get(prop_ref) {
*prop_value = DomValue::Ref(*new);
}
}
}
}
}
new_inst.set_parent(None);
new_inst
}
pub fn clone_inner(
dom_ref: DomRef,
parent_ref: DomRef,
reference_map: &mut HashMap<DomRef, DomRef>,
) -> DomRef {
// NOTE: We create a new scope here to avoid deadlocking since
// our clone implementation must have exclusive write access
let (new_ref, child_refs) = {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let (new_class, new_name, new_props, child_refs) = {
let instance = dom
.get_by_ref(dom_ref)
.expect("Failed to find instance in document");
(
instance.class.to_string(),
instance.name.to_string(),
instance.properties.clone(),
instance.children().to_vec(),
)
};
let new_ref = dom.insert(
parent_ref,
DomInstanceBuilder::new(new_class)
.with_name(new_name)
.with_properties(new_props),
);
reference_map.insert(dom_ref, new_ref);
(new_ref, child_refs)
};
for child_ref in child_refs {
Self::clone_inner(child_ref, new_ref, reference_map);
}
new_ref
}
/**
Destroys the instance, removing it completely
from the weak dom with no way of recovering it.
All member methods will throw errors when called from lua and panic
when called from rust after the instance has been destroyed.
Returns `true` if destroyed successfully, `false` if already destroyed.
### See Also
* [`Destroy`](https://create.roblox.com/docs/reference/engine/classes/Instance#Destroy)
on the Roblox Developer Hub
*/
pub fn destroy(&mut self) -> bool {
if self.is_destroyed() {
false
} else {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
dom.destroy(self.dom_ref);
true
}
}
fn ensure_not_destroyed(&self) -> LuaResult<()> {
if self.is_destroyed() {
Err(LuaError::RuntimeError(
"Instance has been destroyed".to_string(),
))
} else {
Ok(())
}
}
fn is_destroyed(&self) -> bool {
// NOTE: This property can not be cached since instance references
// other than this one may have destroyed this one, and we don't
// keep track of all current instance reference structs
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
dom.get_by_ref(self.dom_ref).is_none()
}
/**
Destroys all child instances.
### See Also
* [`Instance::Destroy`] for more info about what happens when an instance gets destroyed
* [`ClearAllChildren`](https://create.roblox.com/docs/reference/engine/classes/Instance#ClearAllChildren)
on the Roblox Developer Hub
*/
pub fn clear_all_children(&mut self) {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let instance = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document");
let child_refs = instance.children().to_vec();
for child_ref in child_refs {
dom.destroy(child_ref);
}
}
/**
Checks if the instance matches or inherits a given class name.
### See Also
* [`IsA`](https://create.roblox.com/docs/reference/engine/classes/Instance#IsA)
on the Roblox Developer Hub
*/
pub fn is_a(&self, class_name: impl AsRef<str>) -> bool {
class_is_a(&self.class_name, class_name).unwrap_or(false)
}
/**
Gets the class name of the instance.
This will return the correct class name even if the instance has been destroyed.
### See Also
* [`ClassName`](https://create.roblox.com/docs/reference/engine/classes/Instance#ClassName)
on the Roblox Developer Hub
*/
pub fn get_class_name(&self) -> &str {
self.class_name.as_str()
}
/**
Gets the name of the instance, if it exists.
### See Also
* [`Name`](https://create.roblox.com/docs/reference/engine/classes/Instance#Name)
on the Roblox Developer Hub
*/
pub fn get_name(&self) -> String {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
dom.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.name
.clone()
}
/**
Sets the name of the instance, if it exists.
### See Also
* [`Name`](https://create.roblox.com/docs/reference/engine/classes/Instance#Name)
on the Roblox Developer Hub
*/
pub fn set_name(&self, name: impl Into<String>) {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
dom.get_by_ref_mut(self.dom_ref)
.expect("Failed to find instance in document")
.name = name.into()
}
/**
Gets the parent of the instance, if it exists.
### See Also
* [`Parent`](https://create.roblox.com/docs/reference/engine/classes/Instance#Parent)
on the Roblox Developer Hub
*/
pub fn get_parent(&self) -> Option<Instance> {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let parent_ref = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.parent();
if parent_ref == dom.root_ref() {
None
} else {
Some(Self::new(parent_ref))
}
}
/**
Sets the parent of the instance, if it exists.
If the provided parent is [`None`] the instance will become orphaned.
An orphaned instance is an instance at the root of a weak dom.
### See Also
* [`Parent`](https://create.roblox.com/docs/reference/engine/classes/Instance#Parent)
on the Roblox Developer Hub
*/
pub fn set_parent(&self, parent: Option<Instance>) {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to target document");
let parent_ref = parent
.map(|parent| parent.dom_ref)
.unwrap_or_else(|| dom.root_ref());
dom.transfer_within(self.dom_ref, parent_ref);
}
/**
Gets a property for the instance, if it exists.
*/
pub fn get_property(&self, name: impl AsRef<str>) -> Option<DomValue> {
INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document")
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.properties
.get(name.as_ref())
.cloned()
}
/**
Sets a property for the instance.
Note that setting a property here will not fail even if the
property does not actually exist for the instance class.
*/
pub fn set_property(&self, name: impl AsRef<str>, value: DomValue) {
INTERNAL_DOM
.try_write()
.expect("Failed to get read access to document")
.get_by_ref_mut(self.dom_ref)
.expect("Failed to find instance in document")
.properties
.insert(name.as_ref().to_string(), value);
}
/**
Gets an attribute for the instance, if it exists.
### See Also
* [`GetAttribute`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetAttribute)
on the Roblox Developer Hub
*/
pub fn get_attribute(&self, name: impl AsRef<str>) -> Option<DomValue> {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let inst = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document");
if let Some(DomValue::Attributes(attributes)) =
inst.properties.get(PROPERTY_NAME_ATTRIBUTES)
{
attributes.get(name.as_ref()).cloned()
} else {
None
}
}
/**
Gets all known attributes for the instance.
### See Also
* [`GetAttributes`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetAttributes)
on the Roblox Developer Hub
*/
pub fn get_attributes(&self) -> BTreeMap<String, DomValue> {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let inst = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document");
if let Some(DomValue::Attributes(attributes)) =
inst.properties.get(PROPERTY_NAME_ATTRIBUTES)
{
attributes.clone().into_iter().collect()
} else {
BTreeMap::new()
}
}
/**
Sets an attribute for the instance.
### See Also
* [`SetAttribute`](https://create.roblox.com/docs/reference/engine/classes/Instance#SetAttribute)
on the Roblox Developer Hub
*/
pub fn set_attribute(&self, name: impl AsRef<str>, value: DomValue) {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let inst = dom
.get_by_ref_mut(self.dom_ref)
.expect("Failed to find instance in document");
// NOTE: Attributes do not support integers, only floats
let value = match value {
DomValue::Int32(i) => DomValue::Float32(i as f32),
DomValue::Int64(i) => DomValue::Float64(i as f64),
value => value,
};
if let Some(DomValue::Attributes(attributes)) =
inst.properties.get_mut(PROPERTY_NAME_ATTRIBUTES)
{
attributes.insert(name.as_ref().to_string(), value);
} else {
let mut attributes = DomAttributes::new();
attributes.insert(name.as_ref().to_string(), value);
inst.properties.insert(
PROPERTY_NAME_ATTRIBUTES.to_string(),
DomValue::Attributes(attributes),
);
}
}
/**
Adds a tag to the instance.
### See Also
* [`AddTag`](https://create.roblox.com/docs/reference/engine/classes/CollectionService#AddTag)
on the Roblox Developer Hub
*/
pub fn add_tag(&self, name: impl AsRef<str>) {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let inst = dom
.get_by_ref_mut(self.dom_ref)
.expect("Failed to find instance in document");
if let Some(DomValue::Tags(tags)) = inst.properties.get_mut(PROPERTY_NAME_TAGS) {
tags.push(name.as_ref());
} else {
inst.properties.insert(
PROPERTY_NAME_TAGS.to_string(),
DomValue::Tags(vec![name.as_ref().to_string()].into()),
);
}
}
/**
Gets all current tags for the instance.
### See Also
* [`GetTags`](https://create.roblox.com/docs/reference/engine/classes/CollectionService#GetTags)
on the Roblox Developer Hub
*/
pub fn get_tags(&self) -> Vec<String> {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let inst = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document");
if let Some(DomValue::Tags(tags)) = inst.properties.get(PROPERTY_NAME_TAGS) {
tags.iter().map(ToString::to_string).collect()
} else {
Vec::new()
}
}
/**
Checks if the instance has a specific tag.
### See Also
* [`HasTag`](https://create.roblox.com/docs/reference/engine/classes/CollectionService#HasTag)
on the Roblox Developer Hub
*/
pub fn has_tag(&self, name: impl AsRef<str>) -> bool {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let inst = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document");
if let Some(DomValue::Tags(tags)) = inst.properties.get(PROPERTY_NAME_TAGS) {
let name = name.as_ref();
tags.iter().any(|tag| tag == name)
} else {
false
}
}
/**
Removes a tag from the instance.
### See Also
* [`RemoveTag`](https://create.roblox.com/docs/reference/engine/classes/CollectionService#RemoveTag)
on the Roblox Developer Hub
*/
pub fn remove_tag(&self, name: impl AsRef<str>) {
let mut dom = INTERNAL_DOM
.try_write()
.expect("Failed to get write access to document");
let inst = dom
.get_by_ref_mut(self.dom_ref)
.expect("Failed to find instance in document");
if let Some(DomValue::Tags(tags)) = inst.properties.get_mut(PROPERTY_NAME_TAGS) {
let name = name.as_ref();
let mut new_tags = tags.iter().map(ToString::to_string).collect::<Vec<_>>();
new_tags.retain(|tag| tag != name);
inst.properties.insert(
PROPERTY_NAME_TAGS.to_string(),
DomValue::Tags(new_tags.into()),
);
}
}
/**
Gets all of the current children of this `Instance`.
Note that this is a somewhat expensive operation and that other
operations using weak dom referents should be preferred if possible.
### See Also
* [`GetChildren`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetChildren)
on the Roblox Developer Hub
*/
pub fn get_children(&self) -> Vec<Instance> {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let children = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.children()
.to_vec();
children.into_iter().map(Self::new).collect()
}
/**
Gets all of the current descendants of this `Instance` using a breadth-first search.
Note that this is a somewhat expensive operation and that other
operations using weak dom referents should be preferred if possible.
### See Also
* [`GetDescendants`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetDescendants)
on the Roblox Developer Hub
*/
pub fn get_descendants(&self) -> Vec<Instance> {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let mut descendants = Vec::new();
let mut queue = VecDeque::from_iter(
dom.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.children(),
);
while let Some(queue_ref) = queue.pop_front() {
descendants.push(*queue_ref);
let queue_inst = dom.get_by_ref(*queue_ref).unwrap();
for queue_ref_inner in queue_inst.children().iter().rev() {
queue.push_back(queue_ref_inner);
}
}
descendants.into_iter().map(Self::new).collect()
}
/**
Gets the "full name" of this instance.
This will be a path composed of instance names from the top-level
ancestor of this instance down to itself, in the following format:
`Ancestor.Child.Descendant.Instance`
### See Also
* [`GetFullName`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetFullName)
on the Roblox Developer Hub
*/
pub fn get_full_name(&self) -> String {
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let dom_root = dom.root_ref();
let mut parts = Vec::new();
let mut instance_ref = self.dom_ref;
while let Some(instance) = dom.get_by_ref(instance_ref) {
if instance_ref != dom_root && instance.class != data_model::CLASS_NAME {
instance_ref = instance.parent();
parts.push(instance.name.clone());
} else {
break;
}
}
parts.reverse();
parts.join(".")
}
/**
Finds a child of the instance using the given predicate callback.
### See Also
* [`FindFirstChild`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstChild) on the Roblox Developer Hub
* [`FindFirstChildOfClass`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstChildOfClass) on the Roblox Developer Hub
* [`FindFirstChildWhichIsA`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstChildWhichIsA) on the Roblox Developer Hub
*/
pub fn find_child<F>(&self, predicate: F) -> Option<Instance>
where
F: Fn(&DomInstance) -> bool,
{
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let children = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.children()
.to_vec();
children.into_iter().find_map(|child_ref| {
if let Some(child_inst) = dom.get_by_ref(child_ref) {
if predicate(child_inst) {
Some(Self::new(child_ref))
} else {
None
}
} else {
None
}
})
}
/**
Finds an ancestor of the instance using the given predicate callback.
### See Also
* [`FindFirstAncestor`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstAncestor) on the Roblox Developer Hub
* [`FindFirstAncestorOfClass`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstAncestorOfClass) on the Roblox Developer Hub
* [`FindFirstAncestorWhichIsA`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstAncestorWhichIsA) on the Roblox Developer Hub
*/
pub fn find_ancestor<F>(&self, predicate: F) -> Option<Instance>
where
F: Fn(&DomInstance) -> bool,
{
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let mut ancestor_ref = dom
.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.parent();
while let Some(ancestor) = dom.get_by_ref(ancestor_ref) {
if predicate(ancestor) {
return Some(Self::new(ancestor_ref));
} else {
ancestor_ref = ancestor.parent();
}
}
None
}
/**
Finds a descendant of the instance using the given
predicate callback and a breadth-first search.
### See Also
* [`FindFirstDescendant`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstDescendant)
on the Roblox Developer Hub
*/
pub fn find_descendant<F>(&self, predicate: F) -> Option<Instance>
where
F: Fn(&DomInstance) -> bool,
{
let dom = INTERNAL_DOM
.try_read()
.expect("Failed to get read access to document");
let mut queue = VecDeque::from_iter(
dom.get_by_ref(self.dom_ref)
.expect("Failed to find instance in document")
.children(),
);
while let Some(queue_item) = queue
.pop_front()
.and_then(|queue_ref| dom.get_by_ref(*queue_ref))
{
if predicate(queue_item) {
return Some(Self::new(queue_item.referent()));
} else {
queue.extend(queue_item.children())
}
}
None
}
}
impl Instance {
pub(crate) fn make_table(lua: &Lua, datatype_table: &LuaTable) -> LuaResult<()> {
datatype_table.set(
"new",
lua.create_function(|lua, class_name: String| {
if class_exists(&class_name) {
Instance::new_orphaned(class_name).into_lua(lua)
} else {
Err(LuaError::RuntimeError(format!(
"Failed to create Instance - '{}' is not a valid class name",
class_name
)))
}
})?,
)
}
}
impl LuaUserData for Instance {
fn add_fields<'lua, F: LuaUserDataFields<'lua, Self>>(fields: &mut F) {
// Here we add inheritance-like behavior for instances by creating
// fields that are restricted to specific classnames / base classes
data_model::add_fields(fields);
workspace::add_fields(fields);
}
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_meta_method(LuaMetaMethod::ToString, |lua, this, ()| {
this.ensure_not_destroyed()?;
userdata_impl_to_string(lua, this, ())
});
methods.add_meta_method(LuaMetaMethod::Eq, userdata_impl_eq);
/*
Getting a value does the following:
1. Check if it is a special property like "ClassName", "Name" or "Parent"
2. Check if a property exists for the wanted name
2a. Get an existing instance property OR
2b. Get a property from a known default value
3. Get a current child of the instance
4. No valid property or instance found, throw error
*/
methods.add_meta_method(LuaMetaMethod::Index, |lua, this, prop_name: String| {
this.ensure_not_destroyed()?;
match prop_name.as_str() {
"ClassName" => return this.get_class_name().into_lua(lua),
"Name" => {
return this.get_name().into_lua(lua);
}
"Parent" => {
return this.get_parent().into_lua(lua);
}
_ => {}
}
if let Some(info) = find_property_info(&this.class_name, &prop_name) {
if let Some(prop) = this.get_property(&prop_name) {
if let DomValue::Enum(enum_value) = prop {
let enum_name = info.enum_name.ok_or_else(|| {
LuaError::RuntimeError(format!(
"Failed to get property '{}' - encountered unknown enum",
prop_name
))
})?;
EnumItem::from_enum_name_and_value(&enum_name, enum_value.to_u32())
.ok_or_else(|| {
LuaError::RuntimeError(format!(
"Failed to get property '{}' - Enum.{} does not contain numeric value {}",
prop_name, enum_name, enum_value.to_u32()
))
})?
.into_lua(lua)
} else {
Ok(LuaValue::dom_value_to_lua(lua, &prop)?)
}
} else if let (Some(enum_name), Some(enum_value)) = (info.enum_name, info.enum_default) {
EnumItem::from_enum_name_and_value(&enum_name, enum_value)
.ok_or_else(|| {
LuaError::RuntimeError(format!(
"Failed to get property '{}' - Enum.{} does not contain numeric value {}",
prop_name, enum_name, enum_value
))
})?
.into_lua(lua)
} else if let Some(prop_default) = info.value_default {
Ok(LuaValue::dom_value_to_lua(lua, prop_default)?)
} else if info.value_type.is_some() {
if info.value_type == Some(DomType::Ref) {
Ok(LuaValue::Nil)
} else {
Err(LuaError::RuntimeError(format!(
"Failed to get property '{}' - missing default value",
prop_name
)))
}
} else {
Err(LuaError::RuntimeError(format!(
"Failed to get property '{}' - malformed property info",
prop_name
)))
}
} else if let Some(inst) = this.find_child(|inst| inst.name == prop_name) {
Ok(LuaValue::UserData(lua.create_userdata(inst)?))
} else {
Err(LuaError::RuntimeError(format!(
"{} is not a valid member of {}",
prop_name, this
)))
}
});
/*
Setting a value does the following:
1. Check if it is a special property like "ClassName", "Name" or "Parent"
2. Check if a property exists for the wanted name
2a. Set a strict enum from a given EnumItem OR
2b. Set a normal property from a given value
*/
methods.add_meta_method_mut(
LuaMetaMethod::NewIndex,
|lua, this, (prop_name, prop_value): (String, LuaValue)| {
this.ensure_not_destroyed()?;
match prop_name.as_str() {
"ClassName" => {
return Err(LuaError::RuntimeError(format!(
"Failed to set property '{}' - property is read-only",
prop_name
)));
}
"Name" => {
let name = String::from_lua(prop_value, lua)?;
this.set_name(name);
return Ok(());
}
"Parent" => {
if this.get_class_name() == data_model::CLASS_NAME {
return Err(LuaError::RuntimeError(format!(
"Failed to set property '{}' - DataModel can not be reparented",
prop_name
)));
}
type Parent<'lua> = Option<LuaUserDataRef<'lua, Instance>>;
let parent = Parent::from_lua(prop_value, lua)?;
this.set_parent(parent.map(|p| p.clone()));
return Ok(());
}
_ => {}
}
let info = match find_property_info(&this.class_name, &prop_name) {
Some(b) => b,
None => {
return Err(LuaError::RuntimeError(format!(
"{} is not a valid member of {}",
prop_name, this
)))
}
};
if let Some(enum_name) = info.enum_name {
match LuaUserDataRef::<EnumItem>::from_lua(prop_value, lua) {
Ok(given_enum) if given_enum.parent.desc.name == enum_name => {
this.set_property(
prop_name,
DomValue::Enum((*given_enum).clone().into()),
);
Ok(())
}
Ok(given_enum) => Err(LuaError::RuntimeError(format!(
"Failed to set property '{}' - expected Enum.{}, got Enum.{}",
prop_name, enum_name, given_enum.parent.desc.name
))),