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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
//! This module exposes the [`Application`], the core of `tui-realm` and its directly related types.
use std::hash::Hash;
use std::time::{Duration, Instant};
use ratatui::Frame;
use thiserror::Error;
use super::{Subscription, WrappedComponent};
use crate::component::AppComponent;
use crate::event::Event;
use crate::injector::Injector;
use crate::listener::{EventListener, EventListenerCfg, ListenerError, PollError};
use crate::props::{AttrValue, Attribute, QueryResult};
use crate::ratatui::layout::Rect;
use crate::state::State;
use crate::subscription::{EventClause, Sub};
use crate::view::{View, ViewError};
/// Result retuned by [`Application`] functions.
pub type ApplicationResult<T> = Result<T, ApplicationError>;
/// The application defines a tui-realm application.
/// It will handle events, subscriptions and the view too.
/// It provides functions to interact with the view (mount, umount, query, etc), but also
/// the main function: [`Application::tick`].
pub struct Application<ComponentId, Msg, UserEvent>
where
ComponentId: Eq + PartialEq + Clone + Hash,
Msg: PartialEq,
UserEvent: Eq + PartialEq + Clone + Send + 'static,
{
listener: EventListener<UserEvent>,
subs: Vec<Subscription<ComponentId, UserEvent>>,
/// If true, subs won't be processed. (Default: False)
sub_lock: bool,
view: View<ComponentId, Msg, UserEvent>,
}
impl<ComponentId, Msg, UserEvent> Application<ComponentId, Msg, UserEvent>
where
ComponentId: Eq + PartialEq + Clone + Hash,
Msg: PartialEq + 'static,
UserEvent: Eq + PartialEq + Clone + Send + 'static,
{
/// Initialize a new [`Application`].
/// The event listener is immediately created and started.
pub fn init(listener_cfg: EventListenerCfg<UserEvent>) -> Self {
// TODO: maybe consider bubbling this up?
let listener = listener_cfg
.start()
.expect("EventListenerCfg to be configured correctly");
Self {
listener,
subs: Vec::new(),
sub_lock: false,
view: View::default(),
}
}
/// Restart listener in case the previous listener has died or if you want to start a new one with a new configuration.
///
/// > The listener has died if you received a [`ApplicationError::Listener(ListenerError::ListenerDied))`](ApplicationError::Listener).
pub fn restart_listener(
&mut self,
listener_cfg: EventListenerCfg<UserEvent>,
) -> ApplicationResult<()> {
self.listener.stop()?;
self.listener = listener_cfg.start()?;
Ok(())
}
/// Lock ports. As long as Ports are locked, ports won't be polled.
/// Locking ports will also prevent Tick events from being generated.
pub fn lock_ports(&mut self) -> ApplicationResult<()> {
self.listener.pause().map_err(ApplicationError::from)
}
/// Unlock Ports. Once called, the event listener will resume polling Ports.
pub fn unlock_ports(&mut self) -> ApplicationResult<()> {
self.listener.unpause().map_err(ApplicationError::from)
}
/// The tick method makes the application to run once.
/// The workflow of the tick method is the following one:
///
/// 1. The event listener is fetched according to the provided [`PollStrategy`]
/// 2. All the received events are sent to the current active component
/// 3. All the received events are forwarded to the subscribed components which satisfy the received events and conditions.
/// 4. Returns messages to process
///
/// As soon as function returns, you should call the [`Application::view`] method.
///
/// > You can also call [`Application::view`] from your `update` function if you need it
pub fn tick(&mut self, strategy: PollStrategy) -> ApplicationResult<Vec<Msg>> {
// Poll event listener
let events = self.poll(strategy)?;
// Forward to active element
let mut messages: Vec<Msg> = events
.iter()
.filter_map(|x| self.forward_to_active_component(x))
.collect();
// Forward to subscriptions and extend vector
if !self.sub_lock {
self.forward_to_subscriptions(&events, &mut messages);
}
Ok(messages)
}
// -- view bridge
/// Add an injector to the view
pub fn add_injector(&mut self, injector: Box<dyn Injector<ComponentId>>) {
self.view.add_injector(injector);
}
/// Mount component to view and associate subscriptions for it.
/// Returns error if component is already mounted
/// NOTE: if subs vector contains duplicated, these will be discarded
pub fn mount(
&mut self,
id: ComponentId,
component: WrappedComponent<Msg, UserEvent>,
subs: Vec<Sub<ComponentId, UserEvent>>,
) -> ApplicationResult<()> {
// Mount
self.view.mount(&id, component)?;
// Subscribe
self.insert_subscriptions(&id, subs);
Ok(())
}
/// Umount component associated to `id` and remove ALL its SUBSCRIPTIONS.
/// Returns Error if the component doesn't exist
pub fn umount(&mut self, id: &ComponentId) -> ApplicationResult<()> {
self.view.umount(id)?;
self.unsubscribe_component(id);
Ok(())
}
/// Remount provided component.
/// Returns Err if failed to mount. It ignores whether the component already exists or not.
/// If component had focus, focus is preserved
pub fn remount(
&mut self,
id: ComponentId,
component: WrappedComponent<Msg, UserEvent>,
subs: Vec<Sub<ComponentId, UserEvent>>,
) -> ApplicationResult<()> {
// remove subs
self.unsubscribe_component(&id);
// remount into view
self.view.remount(&id, component)?;
// re-add subs
self.insert_subscriptions(&id, subs);
Ok(())
}
/// Umount all components in the view and removed all associated subscriptions
pub fn umount_all(&mut self) {
self.view.umount_all();
self.subs.clear();
}
/// Returns whether component `id` is mounted
pub fn mounted(&self, id: &ComponentId) -> bool {
self.view.mounted(id)
}
/// Render component called `id`
pub fn view(&mut self, id: &ComponentId, f: &mut Frame, area: Rect) {
self.view.view(id, f, area);
}
/// Query view component for a certain `AttrValue`
/// Returns error if the component doesn't exist
/// Returns None if the attribute doesn't exist.
pub fn query<'a>(
&'a self,
id: &ComponentId,
query: Attribute,
) -> ApplicationResult<Option<QueryResult<'a>>> {
self.view.query(id, query).map_err(ApplicationError::from)
}
/// Set attribute for component `id`
/// Returns error if the component doesn't exist
pub fn attr(
&mut self,
id: &ComponentId,
attr: Attribute,
value: AttrValue,
) -> ApplicationResult<()> {
self.view
.attr(id, attr, value)
.map_err(ApplicationError::from)
}
/// Get state for component `id`.
/// Returns `Err` if component doesn't exist
pub fn state(&self, id: &ComponentId) -> ApplicationResult<State> {
self.view.state(id).map_err(ApplicationError::from)
}
/// Shorthand for `attr(id, Attribute::Focus(AttrValue::Flag(true)))`.
/// It also sets the component as the current one having focus.
/// Previous active component, if any, GETS PUSHED to the STACK
/// Returns error: if component doesn't exist. Use `mounted()` to check if component exists
///
/// > NOTE: users should always use this function to give focus to components.
pub fn active(&mut self, id: &ComponentId) -> ApplicationResult<()> {
self.view.active(id).map_err(ApplicationError::from)
}
/// Blur selected element AND DON'T PUSH CURRENT ACTIVE ELEMENT INTO THE STACK
/// Shorthand for `attr(id, Attribute::Focus(AttrValue::Flag(false)))`.
/// It also unset the current focus and give it to the first element in stack.
/// Returns error: if no component has focus
///
/// > NOTE: users should always use this function to remove focus to components.
pub fn blur(&mut self) -> ApplicationResult<()> {
self.view.blur().map_err(ApplicationError::from)
}
/// Get a reference to the id of the current active component in the view
pub fn focus(&self) -> Option<&ComponentId> {
self.view.focus()
}
/// Get a reference to the registered component for the given `id`, if there is one.
pub fn get_component(&self, id: &ComponentId) -> Option<&dyn AppComponent<Msg, UserEvent>> {
self.view.get_component(id)
}
/// Get a mutable reference to the registered component for the given `id`, if there is one.
pub fn get_component_mut(
&mut self,
id: &ComponentId,
) -> Option<&mut dyn AppComponent<Msg, UserEvent>> {
self.view.get_component_mut(id)
}
// -- subs bridge
/// Subscribe component to a certain event.
/// Returns Error if the component doesn't exist or if the component is already subscribed to this event
pub fn subscribe(
&mut self,
id: &ComponentId,
sub: Sub<ComponentId, UserEvent>,
) -> ApplicationResult<()> {
if !self.view.mounted(id) {
return Err(ViewError::ComponentNotFound.into());
}
let subscription = Subscription::new(id.clone(), sub);
if self.subscribed(id, subscription.event()) {
return Err(ApplicationError::AlreadySubscribed);
}
self.subs.push(subscription);
Ok(())
}
/// Unsubscribe a component from a certain event.
/// Returns error if the component doesn't exist or if the component is not subscribed to this event
pub fn unsubscribe(
&mut self,
id: &ComponentId,
ev: EventClause<UserEvent>,
) -> ApplicationResult<()> {
if !self.view.mounted(id) {
return Err(ViewError::ComponentNotFound.into());
}
if !self.subscribed(id, &ev) {
return Err(ApplicationError::NoSuchSubscription);
}
self.subs.retain(|s| s.target() != id && s.event() != &ev);
Ok(())
}
/// Lock subscriptions. As long as the subscriptions are locked, events won't be propagated to
/// subscriptions.
pub fn lock_subs(&mut self) {
self.sub_lock = true;
}
/// Unlock subscriptions. Application will now resume propagating events to subscriptions.
pub fn unlock_subs(&mut self) {
self.sub_lock = false;
}
// -- private
/// remove all subscriptions for component
fn unsubscribe_component(&mut self, id: &ComponentId) {
self.subs.retain(|x| x.target() != id);
}
/// Returns whether component `id` is subscribed to event described by `clause`
fn subscribed(&self, id: &ComponentId, clause: &EventClause<UserEvent>) -> bool {
self.subs
.iter()
.any(|s| s.target() == id && s.event() == clause)
}
/// Insert subscriptions
fn insert_subscriptions(&mut self, id: &ComponentId, subs: Vec<Sub<ComponentId, UserEvent>>) {
for sub in subs {
// Push only if not already subscribed
let subscription = Subscription::new(id.clone(), sub);
if !self.subscribed(id, subscription.event()) {
self.subs.push(subscription);
}
}
}
/// Poll listener according to provided strategy
fn poll(&mut self, strategy: PollStrategy) -> ApplicationResult<Vec<Event<UserEvent>>> {
match strategy {
PollStrategy::Once(timeout) => self
.poll_listener_timeout(timeout)
.map(|x| x.map(|x| vec![x]).unwrap_or_default()),
PollStrategy::TryFor(timeout) => self.poll_try_for(timeout),
PollStrategy::UpTo(times, timeout) => self.poll_upto(times, timeout),
PollStrategy::BlockCollectUpTo(times) => self.poll_blocking_upto(times),
}
}
/// Poll event listener up to `upto` times, without waiting to return if there are events.
fn poll_upto(
&mut self,
upto: usize,
timeout: Duration,
) -> ApplicationResult<Vec<Event<UserEvent>>> {
if upto == 0 {
return Ok(Vec::new());
}
let mut evs: Vec<Event<UserEvent>> = Vec::with_capacity(upto);
match self.poll_listener_timeout(timeout) {
Err(err) => return Err(err),
Ok(None) => (),
Ok(Some(ev)) => evs.push(ev),
}
let t = upto.saturating_sub(1);
for _ in 0..t {
match self.try_poll_listener() {
Err(err) => return Err(err),
Ok(None) => break,
Ok(Some(ev)) => evs.push(ev),
}
}
Ok(evs)
}
/// Poll event listener up to `t` times, without waiting to return if there are events in a blocking fashion.
fn poll_blocking_upto(&mut self, upto: usize) -> ApplicationResult<Vec<Event<UserEvent>>> {
if upto == 0 {
return Ok(Vec::new());
}
let mut evs: Vec<Event<UserEvent>> = Vec::with_capacity(upto);
match self.poll_listener_blocking() {
Err(err) => return Err(err),
Ok(ev) => evs.push(ev),
}
let t = upto.saturating_sub(1);
for _ in 0..t {
match self.try_poll_listener() {
Err(err) => return Err(err),
Ok(None) => break,
Ok(Some(ev)) => evs.push(ev),
}
}
Ok(evs)
}
/// Poll event listener until `timeout` is elapsed
fn poll_try_for(&mut self, timeout: Duration) -> ApplicationResult<Vec<Event<UserEvent>>> {
let started = Instant::now();
let mut evs: Vec<Event<UserEvent>> = Vec::new();
while started.elapsed() < timeout {
// TODO: change to use "deadline" when it becomes stable
match self.poll_listener_timeout(Duration::from_millis(10)) {
Err(err) => return Err(err),
Ok(None) => continue,
Ok(Some(ev)) => evs.push(ev),
}
}
Ok(evs)
}
/// Poll event listener once with timeout.
fn poll_listener_timeout(
&mut self,
timeout: Duration,
) -> ApplicationResult<Option<Event<UserEvent>>> {
self.listener
.poll_timeout(timeout)
.map_err(ApplicationError::from)
}
/// Poll event listener once in a blocking fashion
fn poll_listener_blocking(&mut self) -> ApplicationResult<Event<UserEvent>> {
self.listener
.poll_blocking()
.map_err(ApplicationError::from)
}
/// Try to Poll event listener once, without blocking whatsoever
fn try_poll_listener(&mut self) -> ApplicationResult<Option<Event<UserEvent>>> {
self.listener.try_poll().map_err(ApplicationError::from)
}
/// Forward event to current active component, if any.
fn forward_to_active_component(&mut self, ev: &Event<UserEvent>) -> Option<Msg> {
self.view
.focus()
.cloned()
.and_then(|x| self.view.forward(&x, ev).ok().unwrap())
}
/// Forward events to subscriptions listening to the incoming event.
fn forward_to_subscriptions(&mut self, events: &[Event<UserEvent>], messages: &mut Vec<Msg>) {
// NOTE: don't touch this code again and don't try to use iterators, cause it's not gonna work :)
for ev in events {
for sub in &self.subs {
// ! Active component must be different from sub !
if self.view.has_focus(sub.target()) {
continue;
}
if !sub.forward(
ev,
|id, q| self.view.query(id, q).ok().flatten(),
|id| self.view.state(id).ok(),
|id| self.view.mounted(id),
) {
continue;
}
if let Some(msg) = self.view.forward(sub.target(), ev).ok().unwrap() {
messages.push(msg);
}
}
}
}
}
/// Define how [`Application::tick`] should poll for events from the event listener.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PollStrategy {
/// Poll for one event, waiting for the specified timeout
Once(Duration),
/// Try to poll for `n` duration, regardless if there is a event or not and collect all events that happen in this time.
///
/// This strategy will currently poll with a static timeout of 10ms, so the actual time waited might at worst be `n+10ms`.
/// This *might* be resolved in the future when [`std::sync::mpsc::Receiver::recv_deadline`] becomes stable.
TryFor(Duration),
/// Poll for up to `n` events, waiting the first time for the specified timeout, after that try to collect up to `n-1`
/// events without waiting again.
UpTo(usize, Duration),
/// Block until there is at least one event available, and then collect `n-1` additional events, if available.
BlockCollectUpTo(usize),
}
// -- error
/// Error variants returned by [`Application`] functions.
#[derive(Debug, Error)]
pub enum ApplicationError {
#[error("already subscribed")]
AlreadySubscribed,
#[error("listener error: {0}")]
Listener(#[from] ListenerError),
#[error("poll(): {0}")]
Poll(#[from] PollError),
#[error("no such subscription")]
NoSuchSubscription,
#[error("view error: {0}")]
View(#[from] ViewError),
}
#[cfg(test)]
mod test {
use std::time::Duration;
use pretty_assertions::assert_eq;
use super::*;
use crate::event::{Key, KeyEvent};
use crate::listener::builder::test_utils::BarrierRx;
use crate::mock::{
MockBarInput, MockComponentId, MockEvent, MockFooInput, MockInjector, MockMsg, MockPoll,
};
use crate::state::StateValue;
use crate::subscription::SubClause;
/// Create a common Application with Tick that is configured to only happen once (high interval) and have the lister have a test barrier
fn create_app_tick_once_barrier()
-> (Application<MockComponentId, MockMsg, MockEvent>, BarrierRx) {
let mut listener = listener_config_with_tick(Duration::from_secs(60));
let barrier_rx = listener.with_test_barrier();
let application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener);
(application, barrier_rx)
}
#[test]
fn should_initialize_application() {
let application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener_config());
assert!(application.subs.is_empty());
assert_eq!(application.view.mounted(&MockComponentId::InputFoo), false);
assert_eq!(application.sub_lock, false);
}
#[test]
fn should_restart_listener() {
let mut application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener_config());
assert!(application.restart_listener(listener_config()).is_ok());
}
#[test]
fn should_manipulate_components() {
let mut application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener_config());
// Mount
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
// Remount with mount
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_err()
);
assert!(application.active(&MockComponentId::InputFoo).is_ok());
assert_eq!(application.focus().unwrap(), &MockComponentId::InputFoo);
// Remount
assert!(
application
.remount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(application.view.has_focus(&MockComponentId::InputFoo));
// Mount bar
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![]
)
.is_ok()
);
// Mounted
assert!(application.mounted(&MockComponentId::InputFoo));
assert!(application.mounted(&MockComponentId::InputBar));
assert_eq!(application.mounted(&MockComponentId::InputOmar), false);
// Attribute and Query
assert!(
application
.query(&MockComponentId::InputFoo, Attribute::InputLength)
.ok()
.unwrap()
.is_none()
);
assert!(
application
.attr(
&MockComponentId::InputFoo,
Attribute::InputLength,
AttrValue::Length(8)
)
.is_ok()
);
assert_eq!(
application
.query(&MockComponentId::InputFoo, Attribute::InputLength)
.ok()
.unwrap()
.unwrap(),
AttrValue::Length(8)
);
// State
assert_eq!(
application.state(&MockComponentId::InputFoo).ok().unwrap(),
State::Single(StateValue::String(String::default()))
);
// Active / blur
assert!(application.active(&MockComponentId::InputFoo).is_ok());
assert!(application.active(&MockComponentId::InputBar).is_ok());
assert!(application.active(&MockComponentId::InputOmar).is_err());
assert!(application.blur().is_ok());
assert!(application.blur().is_ok());
// no focus
assert!(application.blur().is_err());
// Umount
assert!(application.umount(&MockComponentId::InputFoo).is_ok());
assert!(application.umount(&MockComponentId::InputFoo).is_err());
assert!(application.umount(&MockComponentId::InputBar).is_ok());
}
#[test]
fn should_subscribe_components() {
let mut application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener_config());
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![
Sub::new(EventClause::Tick, SubClause::Always),
Sub::new(
EventClause::Tick,
SubClause::HasAttrValue(
MockComponentId::InputFoo,
Attribute::InputLength,
AttrValue::Length(8)
)
), // NOTE: This event will be ignored
Sub::new(
EventClause::User(MockEvent::Bar),
SubClause::HasAttrValue(
MockComponentId::InputFoo,
Attribute::Focus,
AttrValue::Flag(true)
)
)
]
)
.is_ok()
);
assert_eq!(application.subs.len(), 2);
// Subscribe for another event
assert!(
application
.subscribe(
&MockComponentId::InputFoo,
Sub::new(
EventClause::User(MockEvent::Foo),
SubClause::HasAttrValue(
MockComponentId::InputFoo,
Attribute::Focus,
AttrValue::Flag(false)
)
)
)
.is_ok()
);
assert_eq!(application.subs.len(), 3);
// Try to re-subscribe
assert!(
application
.subscribe(
&MockComponentId::InputFoo,
Sub::new(
EventClause::User(MockEvent::Foo),
SubClause::HasAttrValue(
MockComponentId::InputFoo,
Attribute::Focus,
AttrValue::Flag(false)
)
)
)
.is_err()
);
// Subscribe for unexisting component
assert!(
application
.subscribe(
&MockComponentId::InputBar,
Sub::new(
EventClause::User(MockEvent::Foo),
SubClause::HasAttrValue(
MockComponentId::InputBar,
Attribute::Focus,
AttrValue::Flag(false)
)
)
)
.is_err()
);
// Unsubscribe element
assert!(
application
.unsubscribe(
&MockComponentId::InputFoo,
EventClause::User(MockEvent::Foo)
)
.is_ok()
);
// Unsubcribe twice
assert!(
application
.unsubscribe(
&MockComponentId::InputFoo,
EventClause::User(MockEvent::Foo)
)
.is_err()
);
}
#[test]
fn should_umount_all() {
let mut application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener_config());
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![
Sub::new(EventClause::Tick, SubClause::Always),
Sub::new(
EventClause::User(MockEvent::Bar),
SubClause::HasAttrValue(
MockComponentId::InputFoo,
Attribute::Focus,
AttrValue::Flag(true)
)
)
]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockFooInput::default()),
vec![Sub::new(EventClause::Any, SubClause::Always)]
)
.is_ok()
);
assert_eq!(application.subs.len(), 3);
// Let's umount all
application.umount_all();
assert_eq!(application.mounted(&MockComponentId::InputFoo), false);
assert_eq!(application.mounted(&MockComponentId::InputBar), false);
assert!(application.subs.is_empty());
}
#[test]
fn should_do_tick() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![
Sub::new(EventClause::Tick, SubClause::Always),
Sub::new(
// NOTE: won't be thrown, since requires focus
EventClause::Keyboard(KeyEvent::from(Key::Enter)),
SubClause::HasAttrValue(
MockComponentId::InputBar,
Attribute::Focus,
AttrValue::Flag(true)
)
)
]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
/*
* Here we should:
*
* - receive an Enter from MockPoll, sent to FOO and will return a `FooSubmit`
* - receive a Tick from MockPoll, sent to FOO, but won't return a msg
* - the Tick will be sent also to BAR since is subscribed and will return a `BarTick`
*/
assert_eq!(
application
.tick(PollStrategy::UpTo(5, Duration::from_millis(10)))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new()), MockMsg::BarTick]
);
// Active BAR
assert!(application.active(&MockComponentId::InputBar).is_ok());
barrier_rx.recieve_cycle();
/*
* Here we should:
*
* - receive an Enter from MockPoll, sent to BAR and will return a `BarSubmit`
*/
assert_eq!(
application
.tick(PollStrategy::Once(Duration::from_millis(10)))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::BarSubmit(String::new())]
);
barrier_rx.recieve_cycle();
barrier_rx.recieve_cycle();
let before = Instant::now();
// Let's try TryFor strategy
let events = application
.tick(PollStrategy::TryFor(Duration::from_millis(400)))
.ok()
.unwrap();
assert!(events.len() >= 2);
assert!(before.elapsed() > Duration::from_millis(400));
assert!(before.elapsed() < Duration::from_millis(500));
}
#[test]
fn strategy_upto_nowait_should_work() {
let mut listener = listener_config_with_tick(Duration::from_secs(60));
let barrier_rx = listener.with_test_barrier();
let mut application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener);
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![
Sub::new(EventClause::Tick, SubClause::Always),
Sub::new(
// NOTE: won't be thrown, since requires focus
EventClause::Keyboard(KeyEvent::from(Key::Enter)),
SubClause::HasAttrValue(
MockComponentId::InputBar,
Attribute::Focus,
AttrValue::Flag(true)
)
)
]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
let before = Instant::now();
assert_eq!(
application
.tick(PollStrategy::UpTo(5, Duration::from_secs(5)))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new()), MockMsg::BarTick]
);
// messages should be available, so "UpToNoWait" should not block again after the first event
assert!(before.elapsed() < Duration::from_millis(100));
}
#[test]
fn strategy_blocking_upto_should_work() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![
Sub::new(EventClause::Tick, SubClause::Always),
Sub::new(
// NOTE: won't be thrown, since requires focus
EventClause::Keyboard(KeyEvent::from(Key::Enter)),
SubClause::HasAttrValue(
MockComponentId::InputBar,
Attribute::Focus,
AttrValue::Flag(true)
)
)
]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
let before = Instant::now();
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new()), MockMsg::BarTick]
);
// messages should be available, so "BlockingCollectUpTo" should not block again after the first event
assert!(before.elapsed() < Duration::from_millis(100));
}
#[test]
fn should_not_propagate_event_when_subs_are_locked() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![
Sub::new(EventClause::Tick, SubClause::Always),
Sub::new(
// NOTE: won't be thrown, since requires focus
EventClause::Keyboard(KeyEvent::from(Key::Enter)),
SubClause::HasAttrValue(
MockComponentId::InputBar,
Attribute::Focus,
AttrValue::Flag(true)
)
)
]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
// lock subs
application.lock_subs();
assert_eq!(application.sub_lock, true);
barrier_rx.recieve_cycle();
assert_eq!(
application
.tick(PollStrategy::UpTo(5, Duration::from_millis(10)))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new())]
);
// unlock subs
application.unlock_subs();
assert_eq!(application.sub_lock, false);
}
#[test]
fn should_not_propagate_events_if_has_attr_cond_is_not_satisfied() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![Sub::new(
// NOTE: won't be thrown, since requires focus
EventClause::Tick,
SubClause::HasAttrValue(
MockComponentId::InputBar,
Attribute::Focus,
AttrValue::Flag(true)
)
)]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new())]
);
}
#[test]
fn should_propagate_events_if_has_attr_cond_is_satisfied() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![Sub::new(
EventClause::Tick,
SubClause::HasAttrValue(
MockComponentId::InputFoo,
Attribute::Focus,
AttrValue::Flag(true)
)
)]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new()), MockMsg::BarTick]
);
}
#[test]
fn should_not_propagate_events_if_has_state_cond_is_not_satisfied() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![Sub::new(
EventClause::Tick,
SubClause::HasState(MockComponentId::InputFoo, State::None)
)]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new())]
);
}
#[test]
fn should_propagate_events_if_has_state_cond_is_satisfied() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![Sub::new(
EventClause::Tick,
SubClause::HasState(
MockComponentId::InputFoo,
State::Single(StateValue::String(String::new()))
)
)]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
// No event should be generated
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new()), MockMsg::BarTick]
);
}
#[test]
fn should_not_propagate_events_if_is_mounted_cond_is_not_satisfied() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![Sub::new(
EventClause::Tick,
SubClause::IsMounted(MockComponentId::InputOmar)
)]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new())]
);
}
#[test]
fn should_propagate_events_if_is_mounted_cond_is_not_satisfied() {
let (mut application, barrier_rx) = create_app_tick_once_barrier();
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![Sub::new(
EventClause::Tick,
SubClause::IsMounted(MockComponentId::InputFoo)
)]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
barrier_rx.recieve_cycle();
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new()), MockMsg::BarTick]
);
}
#[test]
fn should_lock_ports() {
let mut listener = listener_config_with_tick(Duration::from_millis(100));
let barrier_rx = listener.with_test_barrier();
let mut application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener);
// Mount foo and bar
assert!(
application
.mount(
MockComponentId::InputFoo,
Box::new(MockFooInput::default()),
vec![]
)
.is_ok()
);
assert!(
application
.mount(
MockComponentId::InputBar,
Box::new(MockBarInput::default()),
vec![Sub::new(
EventClause::Tick,
SubClause::IsMounted(MockComponentId::InputFoo)
)]
)
.is_ok()
);
// Active FOO
assert!(application.active(&MockComponentId::InputFoo).is_ok());
// verify it start unpaused
barrier_rx.recieve_cycle();
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new()), MockMsg::BarTick]
);
// Lock ports
assert!(application.lock_ports().is_ok());
// wait for multiple cycles to verify that no events are generated
barrier_rx.recieve_start();
barrier_rx.recieve_start();
barrier_rx.recieve_start();
// Tick ( No tick event )
assert_eq!(
application
.tick(PollStrategy::Once(Duration::from_millis(10)))
.ok()
.unwrap()
.as_slice(),
&[]
);
// Unlock ports
assert!(application.unlock_ports().is_ok());
// wait for the tick time to definitely be over
std::thread::sleep(Duration::from_millis(100));
// only then run the loop which will trigger the tick
barrier_rx.recieve_cycle();
// Tick
assert_eq!(
application
.tick(PollStrategy::BlockCollectUpTo(5))
.ok()
.unwrap()
.as_slice(),
&[MockMsg::FooSubmit(String::new()), MockMsg::BarTick]
);
}
#[test]
fn application_should_add_injectors() {
let mut application: Application<MockComponentId, MockMsg, MockEvent> =
Application::init(listener_config_with_tick(Duration::from_millis(500)));
application.add_injector(Box::new(MockInjector));
}
fn listener_config() -> EventListenerCfg<MockEvent> {
EventListenerCfg::default().add_port(
Box::new(MockPoll::<MockEvent>::default()),
Duration::from_millis(100),
1,
)
}
fn listener_config_with_tick(tick: Duration) -> EventListenerCfg<MockEvent> {
listener_config().tick_interval(tick)
}
}