/
session.rs
1667 lines (1537 loc) · 63.2 KB
/
session.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 crate::application::{
share_group, share_mapping, ControllerPreset, FxId, GroupId, GroupModel, MainPreset,
MainPresetAutoLoadMode, MappingModel, Preset, PresetLinkManager, PresetManager, SharedGroup,
SharedMapping, SourceCategory, TargetCategory, TargetModel, VirtualControlElementType,
};
use crate::core::{prop, when, AsyncNotifier, Global, Prop};
use crate::domain::{
CompoundMappingSource, CompoundMappingSourceValue, DomainEvent, DomainEventHandler,
MainMapping, MappingCompartment, MappingId, MidiControlInput, MidiFeedbackOutput,
NormalMainTask, NormalRealTimeTask, ProcessorContext, ReaperTarget, VirtualSource,
PLUGIN_PARAMETER_COUNT,
};
use enum_iterator::IntoEnumIterator;
use enum_map::EnumMap;
use reaper_high::Reaper;
use rx_util::{BoxedUnitEvent, Event, Notifier, SharedItemEvent, SharedPayload, UnitEvent};
use rxrust::prelude::*;
use slog::debug;
use std::cell::{Ref, RefCell};
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use helgoboss_learn::{MidiSource, MidiSourceValue};
use helgoboss_midi::{Channel, RawShortMessage};
use itertools::Itertools;
use reaper_medium::{MidiInputDeviceId, RecordingInput};
use std::rc::{Rc, Weak};
use wrap_debug::WrapDebug;
pub trait SessionUi {
fn show_mapping(&self, compartment: MappingCompartment, mapping_id: MappingId);
}
/// This represents the user session with one ReaLearn instance.
///
/// It's ReaLearn's main object which keeps everything together.
#[derive(Debug)]
pub struct Session {
instance_id: String,
/// Initially corresponds to instance ID but is persisted and can be user-customized. Should be
/// unique but if not it's not a big deal, then it won't crash but the user can't be sure which
/// session will be picked. Most relevant for HTTP/WS API.
pub id: Prop<String>,
logger: slog::Logger,
pub let_matched_events_through: Prop<bool>,
pub let_unmatched_events_through: Prop<bool>,
pub auto_correct_settings: Prop<bool>,
pub send_feedback_only_if_armed: Prop<bool>,
pub midi_control_input: Prop<MidiControlInput>,
pub midi_feedback_output: Prop<Option<MidiFeedbackOutput>>,
pub main_preset_auto_load_mode: Prop<MainPresetAutoLoadMode>,
// Is set when in the state of learning multiple mappings ("batch learn")
learn_many_state: Prop<Option<LearnManyState>>,
// We want that learn works independently of the UI, so they are session properties.
mapping_which_learns_source: Prop<Option<SharedMapping>>,
mapping_which_learns_target: Prop<Option<SharedMapping>>,
active_controller_preset_id: Option<String>,
active_main_preset_id: Option<String>,
context: ProcessorContext,
mappings: EnumMap<MappingCompartment, Vec<SharedMapping>>,
default_group: SharedGroup,
groups: Vec<SharedGroup>,
everything_changed_subject: LocalSubject<'static, (), ()>,
mapping_list_changed_subject:
LocalSubject<'static, (MappingCompartment, Option<MappingId>), ()>,
group_list_changed_subject: LocalSubject<'static, (), ()>,
mapping_changed_subject: LocalSubject<'static, MappingCompartment, ()>,
group_changed_subject: LocalSubject<'static, (), ()>,
source_touched_subject: LocalSubject<'static, CompoundMappingSource, ()>,
mapping_subscriptions: EnumMap<MappingCompartment, Vec<SubscriptionGuard<LocalSubscription>>>,
group_subscriptions: Vec<SubscriptionGuard<LocalSubscription>>,
normal_main_task_sender: crossbeam_channel::Sender<NormalMainTask>,
normal_real_time_task_sender: crossbeam_channel::Sender<NormalRealTimeTask>,
party_is_over_subject: LocalSubject<'static, (), ()>,
ui: WrapDebug<Box<dyn SessionUi>>,
parameter_settings: Vec<ParameterSetting>,
controller_preset_manager: Box<dyn PresetManager<PresetType = ControllerPreset>>,
main_preset_manager: Box<dyn PresetManager<PresetType = MainPreset>>,
main_preset_link_manager: Box<dyn PresetLinkManager>,
/// The mappings which are on (control or feedback enabled + mapping active + target active)
on_mappings: Prop<HashSet<MappingId>>,
}
#[derive(Clone, PartialEq, Debug)]
pub struct LearnManyState {
pub compartment: MappingCompartment,
pub current_mapping_id: MappingId,
pub sub_state: LearnManySubState,
}
#[derive(Clone, PartialEq, Debug)]
pub enum LearnManySubState {
LearningSource {
// Only relevant in controller compartment
control_element_type: VirtualControlElementType,
},
LearningTarget,
}
impl LearnManyState {
pub fn learning_source(
compartment: MappingCompartment,
current_mapping_id: MappingId,
control_element_type: VirtualControlElementType,
) -> LearnManyState {
LearnManyState {
compartment,
current_mapping_id,
sub_state: LearnManySubState::LearningSource {
control_element_type,
},
}
}
pub fn learning_target(
compartment: MappingCompartment,
current_mapping_id: MappingId,
) -> LearnManyState {
LearnManyState {
compartment,
current_mapping_id,
sub_state: LearnManySubState::LearningTarget,
}
}
}
pub mod session_defaults {
use crate::application::MainPresetAutoLoadMode;
pub const LET_MATCHED_EVENTS_THROUGH: bool = false;
pub const LET_UNMATCHED_EVENTS_THROUGH: bool = true;
pub const AUTO_CORRECT_SETTINGS: bool = true;
pub const SEND_FEEDBACK_ONLY_IF_ARMED: bool = true;
pub const MAIN_PRESET_AUTO_LOAD_MODE: MainPresetAutoLoadMode = MainPresetAutoLoadMode::Off;
}
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
instance_id: String,
parent_logger: &slog::Logger,
context: ProcessorContext,
normal_real_time_task_sender: crossbeam_channel::Sender<NormalRealTimeTask>,
normal_main_task_sender: crossbeam_channel::Sender<NormalMainTask>,
ui: impl SessionUi + 'static,
controller_manager: impl PresetManager<PresetType = ControllerPreset> + 'static,
main_preset_manager: impl PresetManager<PresetType = MainPreset> + 'static,
preset_link_manager: impl PresetLinkManager + 'static,
) -> Session {
Self {
// As long not changed (by loading a preset or manually changing session ID), the
// session ID is equal to the instance ID.
id: prop(instance_id.clone()),
instance_id,
logger: parent_logger.clone(),
let_matched_events_through: prop(session_defaults::LET_MATCHED_EVENTS_THROUGH),
let_unmatched_events_through: prop(session_defaults::LET_UNMATCHED_EVENTS_THROUGH),
auto_correct_settings: prop(session_defaults::AUTO_CORRECT_SETTINGS),
send_feedback_only_if_armed: prop(session_defaults::SEND_FEEDBACK_ONLY_IF_ARMED),
midi_control_input: prop(MidiControlInput::FxInput),
midi_feedback_output: prop(None),
main_preset_auto_load_mode: prop(session_defaults::MAIN_PRESET_AUTO_LOAD_MODE),
learn_many_state: prop(None),
mapping_which_learns_source: prop(None),
mapping_which_learns_target: prop(None),
active_controller_preset_id: None,
active_main_preset_id: None,
context,
mappings: Default::default(),
default_group: Default::default(),
groups: Default::default(),
everything_changed_subject: Default::default(),
mapping_list_changed_subject: Default::default(),
group_list_changed_subject: Default::default(),
mapping_changed_subject: Default::default(),
group_changed_subject: Default::default(),
source_touched_subject: Default::default(),
mapping_subscriptions: Default::default(),
group_subscriptions: Default::default(),
normal_main_task_sender,
normal_real_time_task_sender,
party_is_over_subject: Default::default(),
ui: WrapDebug(Box::new(ui)),
parameter_settings: vec![Default::default(); PLUGIN_PARAMETER_COUNT as usize],
controller_preset_manager: Box::new(controller_manager),
main_preset_manager: Box::new(main_preset_manager),
main_preset_link_manager: Box::new(preset_link_manager),
on_mappings: Default::default(),
}
}
pub fn id(&self) -> &str {
self.id.get_ref()
}
pub fn receives_midi_from(
&self,
device_id: MidiInputDeviceId,
channel: Option<Channel>,
) -> bool {
match self.midi_control_input.get() {
MidiControlInput::FxInput => {
if let Some(track) = self.context().track() {
if !track.is_armed(true) {
return false;
}
if let Some(RecordingInput::Midi {
device_id: dev_id,
channel: ch,
}) = track.recording_input()
{
(dev_id.is_none() || dev_id == Some(device_id))
&& (ch.is_none() || ch == channel)
} else {
false
}
} else {
false
}
}
MidiControlInput::Device(dev) => dev.id() == device_id,
}
}
pub fn find_mapping_with_source(
&self,
compartment: MappingCompartment,
midi_source: &MidiSource,
) -> Option<&SharedMapping> {
let virt_source = self.virtualize_if_possible(midi_source);
self.mappings(compartment)
.find(|m| match m.borrow().source_model.create_source() {
CompoundMappingSource::Midi(s) => s == *midi_source,
CompoundMappingSource::Virtual(s) => Some(s) == virt_source,
})
}
pub fn get_parameter_settings(&self, index: u32) -> &ParameterSetting {
&self.parameter_settings[index as usize]
}
pub fn get_parameter_name(&self, index: u32) -> String {
let setting = &self.parameter_settings[index as usize];
match &setting.custom_name {
None => format!("Parameter {}", index + 1),
Some(n) => n.clone(),
}
}
pub fn set_parameter_settings_without_notification(
&mut self,
parameter_settings: Vec<ParameterSetting>,
) {
self.parameter_settings = parameter_settings;
}
fn initial_sync(&mut self, weak_session: WeakSession) {
self.resubscribe_to_groups(weak_session.clone());
for compartment in MappingCompartment::into_enum_iter() {
self.resubscribe_to_mappings(compartment, weak_session.clone());
self.sync_all_mappings_full(compartment);
}
self.sync_settings_to_real_time_processor();
}
/// Connects the dots.
// TODO-low Too large. Split this into several methods.
pub fn activate(&mut self, weak_session: WeakSession) {
// Initial sync
self.initial_sync(weak_session.clone());
// Whenever auto-correct setting changes, resubscribe to all mappings because
// that saves us some mapping subscriptions.
when(self.auto_correct_settings.changed())
.with(weak_session.clone())
.do_async(|shared_session, _| {
for compartment in MappingCompartment::into_enum_iter() {
shared_session
.borrow_mut()
.resubscribe_to_mappings(compartment, Rc::downgrade(&shared_session));
}
});
// Whenever something in a specific mapping list changes, resubscribe to those mappings.
when(self.mapping_list_changed())
.with(weak_session.clone())
.do_async(|shared_session, (compartment, _)| {
shared_session
.borrow_mut()
.resubscribe_to_mappings(compartment, Rc::downgrade(&shared_session));
});
// Whenever something in the group list changes, resubscribe to those groups and sync
// (because a mapping could have changed its group).
when(self.group_list_changed())
.with(weak_session.clone())
.do_async(|shared_session, _| {
let mut session = shared_session.borrow_mut();
session.resubscribe_to_groups(Rc::downgrade(&shared_session));
session.sync_all_mappings_full(MappingCompartment::MainMappings);
});
// Whenever anything in a mapping list changes and other things which affect all
// processors (including the real-time processor which takes care of sources only), resync
// all mappings to *all* processors.
when(self.mapping_list_changed())
.with(weak_session.clone())
.do_async(move |session, (compartment, _)| {
session.borrow_mut().sync_all_mappings_full(compartment);
});
// Whenever something changes that determines if feedback is enabled in general, let the
// processors know.
when(
// There are several global conditions which affect whether feedback will be enabled in
// general.
self.midi_feedback_output
.changed()
.merge(self.containing_fx_enabled_or_disabled())
.merge(self.containing_track_armed_or_disarmed())
.merge(self.send_feedback_only_if_armed.changed())
// We have this explicit stop criteria because we listen to global REAPER events.
.take_until(self.party_is_over()),
)
.with(weak_session.clone())
.do_async(move |session, _| {
session.borrow_mut().sync_feedback_is_globally_enabled();
});
// Marking project as dirty if certain things are changed. Should only contain events that
// are triggered by the user.
when(
self.settings_changed()
.merge(self.mapping_list_changed().map_to(())),
)
.with(weak_session.clone())
.do_sync(move |s, _| {
s.borrow().mark_project_as_dirty();
});
// Keep syncing some general settings to real-time processor.
when(self.settings_changed())
.with(weak_session.clone())
.do_async(move |s, _| {
s.borrow().sync_settings_to_real_time_processor();
});
// When FX is reordered, invalidate FX indexes. This is primarily for the GUI.
// Existing GUID-tracked `Fx` instances will detect wrong index automatically.
when(
Global::control_surface_rx()
.fx_reordered()
// We have this explicit stop criteria because we listen to global REAPER events.
.take_until(self.party_is_over()),
)
.with(weak_session.clone())
.do_sync(|s, _| {
s.borrow().invalidate_fx_indexes_of_mapping_targets();
});
// When FX focus changes, maybe trigger main preset change
when(
Global::control_surface_rx()
.fx_focused()
.take_until(self.party_is_over()),
)
.with(weak_session)
.do_sync(|s, fx| {
if s.borrow().main_preset_auto_load_mode.get() == MainPresetAutoLoadMode::FocusedFx {
let fx_id = fx.as_ref().map(FxId::from_fx);
s.borrow_mut()
.auto_load_preset_linked_to_fx(fx_id, Rc::downgrade(&s));
}
});
}
pub fn activate_main_preset_auto_load_mode(
&mut self,
mode: MainPresetAutoLoadMode,
session: WeakSession,
) {
if mode != MainPresetAutoLoadMode::Off {
self.activate_main_preset(None, session).unwrap();
}
self.main_preset_auto_load_mode.set(mode);
}
pub fn main_preset_auto_load_is_active(&self) -> bool {
self.main_preset_auto_load_mode.get() != MainPresetAutoLoadMode::Off
}
fn auto_load_preset_linked_to_fx(&mut self, fx_id: Option<FxId>, weak_session: WeakSession) {
if let Some(fx_id) = fx_id {
let preset_id = self
.main_preset_link_manager
.find_preset_linked_to_fx(&fx_id);
let _ = self.activate_main_preset(preset_id, weak_session);
} else {
self.activate_main_preset(None, weak_session).unwrap();
}
}
fn invalidate_fx_indexes_of_mapping_targets(&self) {
for m in self.all_mappings() {
m.borrow_mut()
.target_model
.invalidate_fx_index(&self.context);
}
}
/// Settings are all the things displayed in the ReaLearn header panel.
fn settings_changed(&self) -> impl UnitEvent {
self.let_matched_events_through
.changed()
.merge(self.let_unmatched_events_through.changed())
.merge(self.midi_control_input.changed())
.merge(self.midi_feedback_output.changed())
.merge(self.auto_correct_settings.changed())
.merge(self.send_feedback_only_if_armed.changed())
.merge(self.main_preset_auto_load_mode.changed())
}
pub fn learn_source(&mut self, source: MidiSource) {
self.source_touched_subject
.next(self.create_compound_source(source));
}
pub fn create_compound_source(&self, source: MidiSource) -> CompoundMappingSource {
if let Some(virt_source) = self.virtualize_if_possible(&source) {
CompoundMappingSource::Virtual(virt_source)
} else {
CompoundMappingSource::Midi(source)
}
}
fn virtualize_if_possible(&self, source: &MidiSource) -> Option<VirtualSource> {
for m in self.mappings(MappingCompartment::ControllerMappings) {
let m = m.borrow();
if !m.control_is_enabled.get() {
continue;
}
if m.target_model.category.get() != TargetCategory::Virtual {
continue;
}
if let CompoundMappingSource::Midi(s) = m.source_model.create_source() {
if s == *source {
let virtual_source =
VirtualSource::new(m.target_model.create_control_element());
return Some(virtual_source);
}
}
}
None
}
pub fn source_touched(
&self,
reenable_control_after_touched: bool,
) -> impl Event<CompoundMappingSource> {
// TODO-low Would be nicer to do this on subscription instead of immediately. from_fn()?
self.normal_real_time_task_sender
.send(NormalRealTimeTask::StartLearnSource)
.unwrap();
let rt_sender = self.normal_real_time_task_sender.clone();
self.source_touched_subject.clone().finalize(move || {
if reenable_control_after_touched {
rt_sender
.send(NormalRealTimeTask::ReturnToControlMode)
.unwrap();
}
})
}
fn resubscribe_to_mappings(
&mut self,
compartment: MappingCompartment,
weak_session: WeakSession,
) {
self.mapping_subscriptions[compartment] = self.mappings[compartment]
.iter()
.map(|shared_mapping| {
// We don't need to take until "party is over" because if the session disappears,
// we know the mappings disappear as well.
let mapping = shared_mapping.borrow();
let shared_mapping_clone = shared_mapping.clone();
let mut all_subscriptions = LocalSubscription::default();
// Keep syncing to processors
{
let subscription = when(mapping.changed_processing_relevant())
.with(weak_session.clone())
.do_sync(move |session, _| {
let mut session = session.borrow_mut();
session.sync_single_mapping_to_processors(
compartment,
&shared_mapping_clone.borrow(),
);
session.mark_project_as_dirty();
session.notify_mapping_changed(compartment);
});
all_subscriptions.add(subscription);
}
// Keep marking project as dirty
{
let subscription = when(mapping.changed_non_processing_relevant())
.with(weak_session.clone())
.do_sync(move |session, _| {
let mut session = session.borrow_mut();
session.mark_project_as_dirty();
session.notify_mapping_changed(compartment);
});
all_subscriptions.add(subscription);
}
// Keep auto-detecting mode settings
if self.auto_correct_settings.get() {
let processor_context = self.context().clone();
let subscription = when(
mapping
.source_model
.changed()
.merge(mapping.target_model.changed()),
)
.with(Rc::downgrade(&shared_mapping))
.do_sync(move |mapping, _| {
mapping
.borrow_mut()
.adjust_mode_if_necessary(&processor_context);
});
all_subscriptions.add(subscription);
}
SubscriptionGuard::new(all_subscriptions)
})
.collect();
}
fn resubscribe_to_groups(&mut self, weak_session: WeakSession) {
self.group_subscriptions = self
.groups_including_default_group()
.map(|shared_group| {
// We don't need to take until "party is over" because if the session disappears,
// we know the groups disappear as well.
let group = shared_group.borrow();
let mut all_subscriptions = LocalSubscription::default();
// Keep syncing to processors
{
let subscription = when(group.changed_processing_relevant())
.with(weak_session.clone())
.do_sync(move |session, _| {
let mut session = session.borrow_mut();
// Change of a single group can affect many mappings
session.sync_all_mappings_full(MappingCompartment::MainMappings);
session.mark_project_as_dirty();
session.notify_group_changed();
});
all_subscriptions.add(subscription);
}
// Keep marking project as dirty
{
let subscription = when(group.changed_non_processing_relevant())
.with(weak_session.clone())
.do_sync(move |session, _| {
let mut session = session.borrow_mut();
session.mark_project_as_dirty();
session.notify_group_changed();
});
all_subscriptions.add(subscription);
}
SubscriptionGuard::new(all_subscriptions)
})
.collect();
}
fn learn_target(&mut self, target: &ReaperTarget) {
// Prevent learning targets from in other project tabs (leads to weird effects, just think
// about it)
if let Some(p) = target.project() {
if p != self.context.project_or_current_project() {
return;
}
}
if let Some(mapping) = self.mapping_which_learns_target.replace(None) {
mapping
.borrow_mut()
.target_model
.apply_from_target(target, &self.context);
}
}
pub fn context(&self) -> &ProcessorContext {
&self.context
}
pub fn add_default_group(&mut self, name: String) -> GroupId {
let group = GroupModel::new_from_ui(name);
self.add_group(group)
}
fn add_group(&mut self, group: GroupModel) -> GroupId {
let id = group.id();
let shared_group = Rc::new(RefCell::new(group));
self.groups.push(shared_group);
self.notify_group_list_changed();
id
}
pub fn find_group_index_by_id_sorted(&self, id: GroupId) -> Option<usize> {
self.groups_sorted().position(|g| g.borrow().id() == id)
}
pub fn group_contains_mappings(&self, id: GroupId) -> bool {
self.mappings(MappingCompartment::MainMappings)
.filter(|m| m.borrow().group_id.get() == id)
.count()
> 0
}
pub fn find_group_by_id(&self, id: GroupId) -> Option<&SharedGroup> {
self.groups.iter().find(|g| g.borrow().id() == id)
}
pub fn find_group_by_index_sorted(&self, index: usize) -> Option<&SharedGroup> {
self.groups_sorted().nth(index)
}
pub fn groups_sorted(&self) -> impl Iterator<Item = &SharedGroup> {
self.groups
.iter()
.sorted_by_key(|g| g.borrow().name.get_ref().clone())
}
pub fn find_group_id_by_index_sorted(&self, index: usize) -> Option<GroupId> {
let group = self.find_group_by_index_sorted(index)?;
Some(group.borrow().id())
}
pub fn move_mapping_to_group(
&mut self,
mapping_id: MappingId,
group_id: GroupId,
) -> Result<(), &'static str> {
let (_, mapping) = self
.find_mapping_and_index_by_id(MappingCompartment::MainMappings, mapping_id)
.ok_or("no such mapping")?;
mapping.borrow_mut().group_id.set(group_id);
self.notify_group_list_changed();
Ok(())
}
pub fn remove_group(&mut self, id: GroupId, delete_mappings: bool) {
self.groups.retain(|g| g.borrow().id() != id);
if delete_mappings {
self.mappings[MappingCompartment::MainMappings]
.retain(|m| m.borrow().group_id.get() != id);
} else {
for m in self.mappings(MappingCompartment::MainMappings) {
let mut m = m.borrow_mut();
if m.group_id.get() == id {
m.group_id.set_without_notification(GroupId::default());
}
}
}
self.notify_group_list_changed();
}
pub fn add_default_mapping(
&mut self,
compartment: MappingCompartment,
// Only relevant for main mapping compartment
initial_group_id: GroupId,
// Only relevant for controller mapping compartment
control_element_type: VirtualControlElementType,
) -> SharedMapping {
let mut mapping = MappingModel::new(compartment, initial_group_id);
mapping
.name
.set_without_notification(self.generate_name_for_new_mapping(compartment));
if compartment == MappingCompartment::ControllerMappings {
let next_control_element_index =
self.get_next_control_element_index(control_element_type);
let target_model = TargetModel {
category: prop(TargetCategory::Virtual),
control_element_type: prop(control_element_type),
control_element_index: prop(next_control_element_index),
..Default::default()
};
mapping.target_model = target_model;
}
self.add_mapping(compartment, mapping)
}
fn get_next_control_element_index(&self, element_type: VirtualControlElementType) -> u32 {
let max_index_so_far = self
.mappings(MappingCompartment::ControllerMappings)
.filter_map(|m| {
let m = m.borrow();
let target = &m.target_model;
if target.category.get() != TargetCategory::Virtual
|| target.control_element_type.get() != element_type
{
return None;
}
Some(target.control_element_index.get())
})
.max();
if let Some(i) = max_index_so_far {
i + 1
} else {
0
}
}
pub fn start_learning_many_mappings(
&mut self,
session: &SharedSession,
compartment: MappingCompartment,
// Only relevant for main mapping compartment
initial_group_id: GroupId,
// Only relevant for controller mapping compartment
control_element_type: VirtualControlElementType,
) {
// Prepare
self.disable_control();
self.stop_learning_source();
self.stop_learning_target();
// Add initial mapping and start learning its source
self.add_and_learn_one_of_many_mappings(
session,
compartment,
initial_group_id,
control_element_type,
);
// After target learned, add new mapping and start learning its source
let prop_to_observe = match compartment {
// For controller mappings we don't need to learn a target so we move on to the next
// mapping as soon as the source has been learned.
MappingCompartment::ControllerMappings => &self.mapping_which_learns_source,
// For main mappings we want to learn a target before moving on to the next mapping.
MappingCompartment::MainMappings => &self.mapping_which_learns_target,
};
when(
prop_to_observe
.changed_to(None)
.take_until(self.learn_many_state.changed_to(None)),
)
.with(Rc::downgrade(session))
.do_async(move |session, _| {
session.borrow_mut().add_and_learn_one_of_many_mappings(
&session,
compartment,
initial_group_id,
control_element_type,
);
});
}
fn add_and_learn_one_of_many_mappings(
&mut self,
session: &SharedSession,
compartment: MappingCompartment,
// Only relevant for main mapping compartment
initial_group_id: GroupId,
// Only relevant for controller mapping compartment
control_element_type: VirtualControlElementType,
) {
let ignore_sources = match compartment {
MappingCompartment::ControllerMappings => {
// When batch-learning controller mappings, we just want to learn sources that have
// not yet been learned. Otherwise when we move a fader, we create many mappings in
// one go.
self.mappings(compartment)
.map(|m| m.borrow().source_model.create_source())
.collect()
}
MappingCompartment::MainMappings => HashSet::new(),
};
let mapping = self.add_default_mapping(compartment, initial_group_id, control_element_type);
let mapping_id = mapping.borrow().id();
self.learn_many_state
.set(Some(LearnManyState::learning_source(
compartment,
mapping_id,
control_element_type,
)));
self.start_learning_source(
Rc::downgrade(session),
mapping.clone(),
false,
ignore_sources,
);
// If this is a main mapping, start learning target as soon as source learned. For
// controller mappings we don't need to do this because adding the default mapping will
// automatically increase the virtual target control element index (which is usually what
// one wants when creating a controller mapping).
if compartment == MappingCompartment::MainMappings {
when(
self.mapping_which_learns_source
.changed_to(None)
.take_until(self.learn_many_state.changed_to(None))
.take(1),
)
.with(Rc::downgrade(session))
.do_async(move |shared_session, _| {
let mut session = shared_session.borrow_mut();
session
.learn_many_state
.set(Some(LearnManyState::learning_target(
compartment,
mapping_id,
)));
session.start_learning_target(
Rc::downgrade(&shared_session),
mapping.clone(),
false,
);
});
}
}
pub fn stop_learning_many_mappings(&mut self) {
self.learn_many_state.set(None);
let source_learning_mapping = self.mapping_which_learns_source.get_ref().clone();
self.stop_learning_source();
self.stop_learning_target();
self.enable_control();
// Remove last added mapping if source not learned already
if let Some(mapping) = source_learning_mapping {
self.remove_mapping(mapping.borrow().compartment(), mapping.as_ptr());
}
}
pub fn learn_many_state_changed(&self) -> impl UnitEvent {
self.learn_many_state.changed()
}
pub fn is_learning_many_mappings(&self) -> bool {
self.learn_many_state.get_ref().is_some()
}
pub fn learn_many_state(&self) -> Option<&LearnManyState> {
self.learn_many_state.get_ref().as_ref()
}
pub fn mapping_count(&self, compartment: MappingCompartment) -> usize {
self.mappings[compartment].len()
}
pub fn find_mapping_by_address(
&self,
compartment: MappingCompartment,
mapping: *const MappingModel,
) -> Option<&SharedMapping> {
self.mappings(compartment)
.find(|m| m.as_ptr() == mapping as _)
}
pub fn find_mapping_and_index_by_id(
&self,
compartment: MappingCompartment,
mapping_id: MappingId,
) -> Option<(usize, &SharedMapping)> {
self.mappings(compartment)
.enumerate()
.find(|(_, m)| m.borrow().id() == mapping_id)
}
pub fn mappings(
&self,
compartment: MappingCompartment,
) -> impl Iterator<Item = &SharedMapping> {
self.mappings[compartment].iter()
}
pub fn default_group(&self) -> &SharedGroup {
&self.default_group
}
pub fn groups(&self) -> impl Iterator<Item = &SharedGroup> {
self.groups.iter()
}
fn groups_including_default_group(&self) -> impl Iterator<Item = &SharedGroup> {
std::iter::once(&self.default_group).chain(self.groups.iter())
}
fn all_mappings(&self) -> impl Iterator<Item = &SharedMapping> {
MappingCompartment::into_enum_iter()
.map(move |compartment| self.mappings(compartment))
.flatten()
}
pub fn mapping_is_learning_source(&self, mapping: *const MappingModel) -> bool {
match self.mapping_which_learns_source.get_ref() {
None => false,
Some(m) => m.as_ptr() == mapping as _,
}
}
pub fn mapping_is_learning_target(&self, mapping: *const MappingModel) -> bool {
match self.mapping_which_learns_target.get_ref() {
None => false,
Some(m) => m.as_ptr() == mapping as _,
}
}
/// Resets the session ID to the (hopefully) always unique instance ID.
pub fn reset_id(&mut self) {
self.id.set(self.instance_id.clone());
}
pub fn mapping_which_learns_source_changed(&self) -> impl UnitEvent {
self.mapping_which_learns_source.changed()
}
pub fn mapping_which_learns_target_changed(&self) -> impl UnitEvent {
self.mapping_which_learns_target.changed()
}
pub fn toggle_learning_source(&mut self, session: &SharedSession, mapping: &SharedMapping) {
if self.mapping_which_learns_source.get_ref().is_none() {
self.start_learning_source(
Rc::downgrade(session),
mapping.clone(),
true,
HashSet::new(),
);
} else {
self.stop_learning_source();
}
}
fn start_learning_source(
&mut self,
session: WeakSession,
mapping: SharedMapping,
reenable_control_after_touched: bool,
ignore_sources: HashSet<CompoundMappingSource>,
) {
self.mapping_which_learns_source.set(Some(mapping.clone()));
when(
self.source_touched(reenable_control_after_touched)
.filter(move |s| !ignore_sources.contains(s))
// We have this explicit stop criteria because we listen to global REAPER
// events.
.take_until(self.party_is_over())
.take_until(self.mapping_which_learns_source.changed_to(None))
.take(1),
)
.with(session)
.finally(|session| session.borrow_mut().mapping_which_learns_source.set(None))
.do_async(|session, source| {
if let Some(m) = session.borrow().mapping_which_learns_source.get_ref() {
m.borrow_mut().source_model.apply_from_source(&source);
}
});
}
fn stop_learning_source(&mut self) {
self.mapping_which_learns_source.set(None);
}
pub fn toggle_learning_target(&mut self, session: &SharedSession, mapping: &SharedMapping) {
if self.mapping_which_learns_target.get_ref().is_none() {
self.start_learning_target(Rc::downgrade(session), mapping.clone(), true);
} else {
self.stop_learning_target();
}
}
fn start_learning_target(
&mut self,
session: WeakSession,
mapping: SharedMapping,
handle_control_disabling: bool,
) {
self.mapping_which_learns_target.set(Some(mapping));
if handle_control_disabling {
self.disable_control();
}
when(
ReaperTarget::touched()
// We have this explicit stop criteria because we listen to global REAPER
// events.
.take_until(self.party_is_over())
.take_until(self.mapping_which_learns_target.changed_to(None))
.take(1),
)
.with(session)
.finally(move |session| {
let mut session = session.borrow_mut();
if handle_control_disabling {
session.enable_control();
}
session.mapping_which_learns_target.set(None);
})
.do_async(|session, target| {
session.borrow_mut().learn_target(target.as_ref());
});
}
fn disable_control(&self) {
self.normal_real_time_task_sender
.send(NormalRealTimeTask::DisableControl)
.unwrap();
}
fn enable_control(&self) {
self.normal_real_time_task_sender
.send(NormalRealTimeTask::ReturnToControlMode)
.unwrap();