leafwing_input_manager/user_input/
mouse.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
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
//! Mouse inputs

use bevy::input::mouse::{MouseButtonInput, MouseMotion, MouseWheel};
use bevy::input::{ButtonInput, ButtonState};
use bevy::prelude::{
    Entity, Events, Gamepad, MouseButton, Reflect, Res, ResMut, Resource, Vec2, World,
};
use leafwing_input_manager_macros::serde_typetag;
use serde::{Deserialize, Serialize};

use crate as leafwing_input_manager;
use crate::axislike::{DualAxisDirection, DualAxisType};
use crate::clashing_inputs::BasicInputs;
use crate::input_processing::*;
use crate::user_input::{InputControlKind, UserInput};

use super::updating::{CentralInputStore, UpdatableInput};
use super::{Axislike, Buttonlike, DualAxislike};

// Built-in support for Bevy's MouseButton
impl UserInput for MouseButton {
    /// [`MouseButton`] acts as a button.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::Button
    }

    /// Returns a [`BasicInputs`] that only contains the [`MouseButton`] itself,
    /// as it represents a simple physical button.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Simple(Box::new(*self))
    }
}

impl UpdatableInput for MouseButton {
    type SourceData = ButtonInput<MouseButton>;

    fn compute(
        mut central_input_store: ResMut<CentralInputStore>,
        source_data: Res<Self::SourceData>,
    ) {
        for key in source_data.get_pressed() {
            central_input_store.update_buttonlike(*key, true);
        }

        for key in source_data.get_just_released() {
            central_input_store.update_buttonlike(*key, false);
        }
    }
}

#[serde_typetag]
impl Buttonlike for MouseButton {
    /// Checks if the specified button is currently pressed down.
    #[inline]
    fn pressed(&self, input_store: &CentralInputStore, _gamepad: Gamepad) -> bool {
        input_store.pressed(self)
    }

    /// Sends a fake [`MouseButtonInput`] event to the world with [`ButtonState::Pressed`].
    ///
    /// # Note
    ///
    /// The `window` field will be filled with a placeholder value.
    fn press(&self, world: &mut World) {
        let mut events = world.resource_mut::<Events<MouseButtonInput>>();
        events.send(MouseButtonInput {
            button: *self,
            state: ButtonState::Pressed,
            window: Entity::PLACEHOLDER,
        });
    }

    /// Sends a fake [`MouseButtonInput`] event to the world with [`ButtonState::Released`].
    ///
    /// # Note
    ///
    /// The `window` field will be filled with a placeholder value.
    fn release(&self, world: &mut World) {
        let mut events = world.resource_mut::<Events<MouseButtonInput>>();
        events.send(MouseButtonInput {
            button: *self,
            state: ButtonState::Released,
            window: Entity::PLACEHOLDER,
        });
    }
}

/// Provides button-like behavior for mouse movement in cardinal directions.
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy::input::InputPlugin;
/// use leafwing_input_manager::plugin::{AccumulatorPlugin, CentralInputStorePlugin};
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::user_input::testing_utils::FetchUserInput;
///
/// let mut app = App::new();
/// app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
///
/// // Positive Y-axis movement
/// let input = MouseMoveDirection::UP;
///
/// // Movement in the opposite direction doesn't activate the input
/// MouseMoveAxis::Y.set_value(app.world_mut(), -5.0);
/// app.update();
/// assert!(!app.read_pressed(input));
///
/// // Movement in the chosen direction activates the input
/// MouseMoveAxis::Y.set_value(app.world_mut(), 5.0);
/// app.update();
/// assert!(app.read_pressed(input));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct MouseMoveDirection(pub DualAxisDirection);

impl MouseMoveDirection {
    /// Movement in the upward direction.
    pub const UP: Self = Self(DualAxisDirection::Up);

    /// Movement in the downward direction.
    pub const DOWN: Self = Self(DualAxisDirection::Down);

    /// Movement in the leftward direction.
    pub const LEFT: Self = Self(DualAxisDirection::Left);

    /// Movement in the rightward direction.
    pub const RIGHT: Self = Self(DualAxisDirection::Right);
}

impl UserInput for MouseMoveDirection {
    /// [`MouseMoveDirection`] acts as a virtual button.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::Button
    }

    /// [`MouseMoveDirection`] represents a simple virtual button.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Simple(Box::new(*self))
    }
}

#[serde_typetag]
impl Buttonlike for MouseMoveDirection {
    /// Checks if there is any recent mouse movement along the specified direction.
    #[must_use]
    #[inline]
    fn pressed(&self, input_store: &CentralInputStore, _gamepad: Gamepad) -> bool {
        let mouse_movement = input_store.pair(&MouseMove::default());
        self.0.is_active(mouse_movement)
    }

    /// Sends a [`MouseMotion`] event with a magnitude of 1.0 in the direction defined by `self`.
    fn press(&self, world: &mut World) {
        world
            .resource_mut::<Events<MouseMotion>>()
            .send(MouseMotion {
                delta: self.0.full_active_value(),
            });
    }

    /// This method has no effect.
    ///
    /// As mouse movement directions are determined based on the recent change in mouse position,
    /// no action other than waiting for the next frame is necessary to release the input.
    fn release(&self, _world: &mut World) {}
}

/// Relative changes in position of mouse movement on a single axis (X or Y).
///
/// # Value Processing
///
/// You can customize how the values are processed using a pipeline of processors.
/// See [`WithAxisProcessingPipelineExt`] for details.
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy::input::InputPlugin;
/// use leafwing_input_manager::plugin::{AccumulatorPlugin, CentralInputStorePlugin};
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::user_input::testing_utils::FetchUserInput;
///
/// let mut app = App::new();
/// app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
///
/// // Y-axis movement
/// let input = MouseMoveAxis::Y;
///
/// // Movement on the chosen axis activates the input
/// MouseMoveAxis::Y.set_value(app.world_mut(), 1.0);
/// app.update();
/// assert_eq!(app.read_axis_value(input), 1.0);
///
/// // You can configure a processing pipeline (e.g., doubling the value)
/// let doubled = MouseMoveAxis::Y.sensitivity(2.0);
/// assert_eq!(app.read_axis_value(doubled), 2.0);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct MouseMoveAxis {
    /// The specified axis that this input tracks.
    pub axis: DualAxisType,

    /// A processing pipeline that handles input values.
    pub(crate) processors: Vec<AxisProcessor>,
}

impl MouseMoveAxis {
    /// Movement on the X-axis. No processing is applied to raw data from the mouse.
    pub const X: Self = Self {
        axis: DualAxisType::X,
        processors: Vec::new(),
    };

    /// Movement on the Y-axis. No processing is applied to raw data from the mouse.
    pub const Y: Self = Self {
        axis: DualAxisType::Y,
        processors: Vec::new(),
    };
}

impl UserInput for MouseMoveAxis {
    /// [`MouseMoveAxis`] acts as an axis input.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::Axis
    }

    /// [`MouseMoveAxis`] represents a composition of two [`MouseMoveDirection`]s.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Composite(vec![
            Box::new(MouseMoveDirection(self.axis.negative())),
            Box::new(MouseMoveDirection(self.axis.positive())),
        ])
    }
}

#[serde_typetag]
impl Axislike for MouseMoveAxis {
    /// Retrieves the amount of the mouse movement along the specified axis
    /// after processing by the associated processors.
    #[must_use]
    #[inline]
    fn value(&self, input_store: &CentralInputStore, _gamepad: Gamepad) -> f32 {
        let movement = input_store.pair(&MouseMove::default());
        let value = self.axis.get_value(movement);
        self.processors
            .iter()
            .fold(value, |value, processor| processor.process(value))
    }

    /// Sends a [`MouseMotion`] event along the appropriate axis with the specified value.
    fn set_value(&self, world: &mut World, value: f32) {
        let event = MouseMotion {
            delta: match self.axis {
                DualAxisType::X => Vec2::new(value, 0.0),
                DualAxisType::Y => Vec2::new(0.0, value),
            },
        };
        world.resource_mut::<Events<MouseMotion>>().send(event);
    }
}

impl WithAxisProcessingPipelineExt for MouseMoveAxis {
    #[inline]
    fn reset_processing_pipeline(mut self) -> Self {
        self.processors.clear();
        self
    }

    #[inline]
    fn replace_processing_pipeline(
        mut self,
        processors: impl IntoIterator<Item = AxisProcessor>,
    ) -> Self {
        self.processors = processors.into_iter().collect();
        self
    }

    #[inline]
    fn with_processor(mut self, processor: impl Into<AxisProcessor>) -> Self {
        self.processors.push(processor.into());
        self
    }
}

/// Relative changes in position of mouse movement on both axes.
///
/// # Value Processing
///
/// You can customize how the values are processed using a pipeline of processors.
/// See [`WithDualAxisProcessingPipelineExt`] for details.
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy::input::InputPlugin;
/// use leafwing_input_manager::plugin::{AccumulatorPlugin, CentralInputStorePlugin};
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::user_input::testing_utils::FetchUserInput;
///
/// let mut app = App::new();
/// app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
///
/// let input = MouseMove::default();
///
/// // Movement on either axis activates the input
/// MouseMoveAxis::Y.set_value(app.world_mut(), 3.0);
/// app.update();
/// assert_eq!(app.read_dual_axis_values(input), Vec2::new(0.0, 3.0));
///
/// // You can configure a processing pipeline (e.g., doubling the Y value)
/// let doubled = MouseMove::default().sensitivity_y(2.0);
/// assert_eq!(app.read_dual_axis_values(doubled), Vec2::new(0.0, 6.0));
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct MouseMove {
    /// A processing pipeline that handles input values.
    pub(crate) processors: Vec<DualAxisProcessor>,
}

impl UpdatableInput for MouseMove {
    type SourceData = AccumulatedMouseMovement;

    fn compute(
        mut central_input_store: ResMut<CentralInputStore>,
        source_data: Res<Self::SourceData>,
    ) {
        central_input_store.update_dualaxislike(Self::default(), source_data.0);
    }
}

impl UserInput for MouseMove {
    /// [`MouseMove`] acts as a dual-axis input.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::DualAxis
    }

    /// [`MouseMove`] represents a composition of four [`MouseMoveDirection`]s.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Composite(vec![
            Box::new(MouseMoveDirection::UP),
            Box::new(MouseMoveDirection::DOWN),
            Box::new(MouseMoveDirection::LEFT),
            Box::new(MouseMoveDirection::RIGHT),
        ])
    }
}

#[serde_typetag]
impl DualAxislike for MouseMove {
    /// Retrieves the mouse displacement after processing by the associated processors.
    #[must_use]
    #[inline]
    fn axis_pair(&self, input_store: &CentralInputStore, _gamepad: Gamepad) -> Vec2 {
        let movement = input_store.pair(&MouseMove::default());
        self.processors
            .iter()
            .fold(movement, |value, processor| processor.process(value))
    }

    /// Sends a [`MouseMotion`] event with the specified displacement.
    fn set_axis_pair(&self, world: &mut World, value: Vec2) {
        world
            .resource_mut::<Events<MouseMotion>>()
            .send(MouseMotion { delta: value });
    }
}

impl WithDualAxisProcessingPipelineExt for MouseMove {
    #[inline]
    fn reset_processing_pipeline(mut self) -> Self {
        self.processors.clear();
        self
    }

    #[inline]
    fn replace_processing_pipeline(
        mut self,
        processor: impl IntoIterator<Item = DualAxisProcessor>,
    ) -> Self {
        self.processors = processor.into_iter().collect();
        self
    }

    #[inline]
    fn with_processor(mut self, processor: impl Into<DualAxisProcessor>) -> Self {
        self.processors.push(processor.into());
        self
    }
}

/// Provides button-like behavior for mouse wheel scrolling in cardinal directions.
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy::input::InputPlugin;
/// use leafwing_input_manager::plugin::{AccumulatorPlugin, CentralInputStorePlugin};
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::user_input::testing_utils::FetchUserInput;
///
/// let mut app = App::new();
/// app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
///
/// // Positive Y-axis scrolling
/// let input = MouseScrollDirection::UP;
///
/// // Scrolling in the opposite direction doesn't activate the input
/// MouseScrollAxis::Y.set_value(app.world_mut(), -5.0);
/// app.update();
/// assert!(!app.read_pressed(input));
///
/// // Scrolling in the chosen direction activates the input
/// MouseScrollAxis::Y.set_value(app.world_mut(), 5.0);
/// app.update();
/// assert!(app.read_pressed(input));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct MouseScrollDirection(pub DualAxisDirection);

impl MouseScrollDirection {
    /// Movement in the upward direction.
    pub const UP: Self = Self(DualAxisDirection::Up);

    /// Movement in the downward direction.
    pub const DOWN: Self = Self(DualAxisDirection::Down);

    /// Movement in the leftward direction.
    pub const LEFT: Self = Self(DualAxisDirection::Left);

    /// Movement in the rightward direction.
    pub const RIGHT: Self = Self(DualAxisDirection::Right);
}

impl UserInput for MouseScrollDirection {
    /// [`MouseScrollDirection`] acts as a virtual button.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::Button
    }

    /// [`MouseScrollDirection`] represents a simple virtual button.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Simple(Box::new(*self))
    }
}

#[serde_typetag]
impl Buttonlike for MouseScrollDirection {
    /// Checks if there is any recent mouse wheel movement along the specified direction.
    #[must_use]
    #[inline]
    fn pressed(&self, input_store: &CentralInputStore, _gamepad: Gamepad) -> bool {
        let movement = input_store.pair(&MouseScroll::default());
        self.0.is_active(movement)
    }

    /// Sends a [`MouseWheel`] event with a magnitude of 1.0 px in the direction defined by `self`.
    ///
    /// # Note
    ///
    /// The `window` field will be filled with a placeholder value.
    fn press(&self, world: &mut World) {
        let vec = self.0.full_active_value();

        world.resource_mut::<Events<MouseWheel>>().send(MouseWheel {
            unit: bevy::input::mouse::MouseScrollUnit::Pixel,
            x: vec.x,
            y: vec.y,
            window: Entity::PLACEHOLDER,
        });
    }

    /// This method has no effect.
    ///
    /// As mouse scroll directions are determined based on the recent change in mouse scrolling,
    /// no action other than waiting for the next frame is necessary to release the input.
    fn release(&self, _world: &mut World) {}
}

/// Amount of mouse wheel scrolling on a single axis (X or Y).
///
/// # Value Processing
///
/// You can customize how the values are processed using a pipeline of processors.
/// See [`WithAxisProcessingPipelineExt`] for details.
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy::input::InputPlugin;
/// use leafwing_input_manager::plugin::{AccumulatorPlugin, CentralInputStorePlugin};
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::user_input::testing_utils::FetchUserInput;
///
/// let mut app = App::new();
/// app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
///
/// // Y-axis movement
/// let input = MouseScrollAxis::Y;
///
/// // Scrolling on the chosen axis activates the input
/// MouseScrollAxis::Y.set_value(app.world_mut(), 1.0);
/// app.update();
/// assert_eq!(app.read_axis_value(input), 1.0);
///
/// // You can configure a processing pipeline (e.g., doubling the value)
/// let doubled = MouseScrollAxis::Y.sensitivity(2.0);
/// assert_eq!(app.read_axis_value(doubled), 2.0);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct MouseScrollAxis {
    /// The axis that this input tracks.
    pub axis: DualAxisType,

    /// A processing pipeline that handles input values.
    pub(crate) processors: Vec<AxisProcessor>,
}

impl MouseScrollAxis {
    /// Horizontal scrolling of the mouse wheel. No processing is applied to raw data from the mouse.
    pub const X: Self = Self {
        axis: DualAxisType::X,
        processors: Vec::new(),
    };

    /// Vertical scrolling of the mouse wheel. No processing is applied to raw data from the mouse.
    pub const Y: Self = Self {
        axis: DualAxisType::Y,
        processors: Vec::new(),
    };
}

impl UserInput for MouseScrollAxis {
    /// [`MouseScrollAxis`] acts as an axis input.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::Axis
    }

    /// [`MouseScrollAxis`] represents a composition of two [`MouseScrollDirection`]s.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Composite(vec![
            Box::new(MouseScrollDirection(self.axis.negative())),
            Box::new(MouseScrollDirection(self.axis.positive())),
        ])
    }
}

#[serde_typetag]
impl Axislike for MouseScrollAxis {
    /// Retrieves the amount of the mouse wheel movement along the specified axis
    /// after processing by the associated processors.
    #[must_use]
    #[inline]
    fn value(&self, input_store: &CentralInputStore, _gamepad: Gamepad) -> f32 {
        let movement = input_store.pair(&MouseScroll::default());
        let value = self.axis.get_value(movement);
        self.processors
            .iter()
            .fold(value, |value, processor| processor.process(value))
    }

    /// Sends a [`MouseWheel`] event along the appropriate axis with the specified value in pixels.
    ///
    /// # Note
    ///
    /// The `window` field will be filled with a placeholder value.
    fn set_value(&self, world: &mut World, value: f32) {
        let event = MouseWheel {
            unit: bevy::input::mouse::MouseScrollUnit::Pixel,
            x: if self.axis == DualAxisType::X {
                value
            } else {
                0.0
            },
            y: if self.axis == DualAxisType::Y {
                value
            } else {
                0.0
            },
            window: Entity::PLACEHOLDER,
        };
        world.resource_mut::<Events<MouseWheel>>().send(event);
    }
}

impl WithAxisProcessingPipelineExt for MouseScrollAxis {
    #[inline]
    fn reset_processing_pipeline(mut self) -> Self {
        self.processors.clear();
        self
    }

    #[inline]
    fn replace_processing_pipeline(
        mut self,
        processors: impl IntoIterator<Item = AxisProcessor>,
    ) -> Self {
        self.processors = processors.into_iter().collect();
        self
    }

    #[inline]
    fn with_processor(mut self, processor: impl Into<AxisProcessor>) -> Self {
        self.processors.push(processor.into());
        self
    }
}

/// Amount of mouse wheel scrolling on both axes.
///
/// # Value Processing
///
/// You can customize how the values are processed using a pipeline of processors.
/// See [`WithDualAxisProcessingPipelineExt`] for details.
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy::input::InputPlugin;
/// use leafwing_input_manager::plugin::{AccumulatorPlugin, CentralInputStorePlugin};
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::user_input::testing_utils::FetchUserInput;
///
/// let mut app = App::new();
/// app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
///
/// let input = MouseScroll::default();
///
/// // Scrolling on either axis activates the input
/// MouseScrollAxis::Y.set_value(app.world_mut(), 3.0);
/// app.update();
/// assert_eq!(app.read_dual_axis_values(input), Vec2::new(0.0, 3.0));
///
/// // You can configure a processing pipeline (e.g., doubling the Y value)
/// let doubled = MouseScroll::default().sensitivity_y(2.0);
/// assert_eq!(app.read_dual_axis_values(doubled), Vec2::new(0.0, 6.0));
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct MouseScroll {
    /// A processing pipeline that handles input values.
    pub(crate) processors: Vec<DualAxisProcessor>,
}

impl UpdatableInput for MouseScroll {
    type SourceData = AccumulatedMouseScroll;

    fn compute(
        mut central_input_store: ResMut<CentralInputStore>,
        source_data: Res<Self::SourceData>,
    ) {
        central_input_store.update_dualaxislike(Self::default(), source_data.0);
    }
}

impl UserInput for MouseScroll {
    /// [`MouseScroll`] acts as an axis input.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::DualAxis
    }

    /// [`MouseScroll`] represents a composition of four [`MouseScrollDirection`]s.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Composite(vec![
            Box::new(MouseScrollDirection::UP),
            Box::new(MouseScrollDirection::DOWN),
            Box::new(MouseScrollDirection::LEFT),
            Box::new(MouseScrollDirection::RIGHT),
        ])
    }
}

#[serde_typetag]
impl DualAxislike for MouseScroll {
    /// Retrieves the mouse scroll movement on both axes after processing by the associated processors.
    #[must_use]
    #[inline]
    fn axis_pair(&self, input_store: &CentralInputStore, _gamepad: Gamepad) -> Vec2 {
        let movement = input_store.pair(&MouseScroll::default());
        self.processors
            .iter()
            .fold(movement, |value, processor| processor.process(value))
    }

    /// Sends a [`MouseWheel`] event with the specified displacement in pixels.
    ///
    /// # Note
    /// The `window` field will be filled with a placeholder value.
    fn set_axis_pair(&self, world: &mut World, value: Vec2) {
        world.resource_mut::<Events<MouseWheel>>().send(MouseWheel {
            unit: bevy::input::mouse::MouseScrollUnit::Pixel,
            x: value.x,
            y: value.y,
            window: Entity::PLACEHOLDER,
        });
    }
}

impl WithDualAxisProcessingPipelineExt for MouseScroll {
    #[inline]
    fn reset_processing_pipeline(mut self) -> Self {
        self.processors.clear();
        self
    }

    #[inline]
    fn replace_processing_pipeline(
        mut self,
        processors: impl IntoIterator<Item = DualAxisProcessor>,
    ) -> Self {
        self.processors = processors.into_iter().collect();
        self
    }

    #[inline]
    fn with_processor(mut self, processor: impl Into<DualAxisProcessor>) -> Self {
        self.processors.push(processor.into());
        self
    }
}

/// A resource that records the accumulated mouse movement for the frame.
///
/// These values are computed by summing the [`MouseMotion`] events.
///
/// This resource is automatically added by [`InputManagerPlugin`](crate::plugin::InputManagerPlugin).
/// Its value is updated during [`InputManagerSystem::Update`](crate::plugin::InputManagerSystem::Update).
#[derive(Debug, Default, Resource, Reflect, Serialize, Deserialize, Clone, PartialEq)]
pub struct AccumulatedMouseMovement(pub Vec2);

impl AccumulatedMouseMovement {
    /// Resets the accumulated mouse movement to zero.
    #[inline]
    pub fn reset(&mut self) {
        self.0 = Vec2::ZERO;
    }

    /// Accumulates the specified mouse movement.
    #[inline]
    pub fn accumulate(&mut self, event: &MouseMotion) {
        self.0 += event.delta;
    }
}

/// A resource that records the accumulated mouse wheel (scrolling) movement for the frame.
///
/// These values are computed by summing the [`MouseWheel`] events.
///
/// This resource is automatically added by [`InputManagerPlugin`](crate::plugin::InputManagerPlugin).
/// Its value is updated during [`InputManagerSystem::Update`](crate::plugin::InputManagerSystem::Update).
#[derive(Debug, Default, Resource, Reflect, Serialize, Deserialize, Clone, PartialEq)]
pub struct AccumulatedMouseScroll(pub Vec2);

impl AccumulatedMouseScroll {
    /// Resets the accumulated mouse scroll to zero.
    #[inline]
    pub fn reset(&mut self) {
        self.0 = Vec2::ZERO;
    }

    /// Accumulates the specified mouse wheel movement.
    ///
    /// # Warning
    ///
    /// This ignores the mouse scroll unit: all values are treated as equal.
    /// All scrolling, no matter what window it is on, is added to the same total.
    #[inline]
    pub fn accumulate(&mut self, event: &MouseWheel) {
        self.0.x += event.x;
        self.0.y += event.y;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugin::{AccumulatorPlugin, CentralInputStorePlugin};
    use bevy::input::InputPlugin;
    use bevy::prelude::*;

    fn test_app() -> App {
        let mut app = App::new();
        app.add_plugins(InputPlugin)
            .add_plugins((AccumulatorPlugin, CentralInputStorePlugin));
        app
    }

    #[test]
    fn test_mouse_button() {
        let left = MouseButton::Left;
        assert_eq!(left.kind(), InputControlKind::Button);

        let middle = MouseButton::Middle;
        assert_eq!(middle.kind(), InputControlKind::Button);

        let right = MouseButton::Right;
        assert_eq!(right.kind(), InputControlKind::Button);

        // No inputs
        let mut app = test_app();
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        let gamepad = Gamepad::new(0);

        assert!(!left.pressed(inputs, gamepad));
        assert!(!middle.pressed(inputs, gamepad));
        assert!(!right.pressed(inputs, gamepad));

        // Press left
        let mut app = test_app();
        MouseButton::Left.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(left.pressed(inputs, gamepad));
        assert!(!middle.pressed(inputs, gamepad));
        assert!(!right.pressed(inputs, gamepad));

        // Press middle
        let mut app = test_app();
        MouseButton::Middle.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(!left.pressed(inputs, gamepad));
        assert!(middle.pressed(inputs, gamepad));
        assert!(!right.pressed(inputs, gamepad));

        // Press right
        let mut app = test_app();
        MouseButton::Right.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(!left.pressed(inputs, gamepad));
        assert!(!middle.pressed(inputs, gamepad));
        assert!(right.pressed(inputs, gamepad));
    }

    #[test]
    fn test_mouse_move() {
        let mouse_move_up = MouseMoveDirection::UP;
        assert_eq!(mouse_move_up.kind(), InputControlKind::Button);

        let mouse_move_y = MouseMoveAxis::Y;
        assert_eq!(mouse_move_y.kind(), InputControlKind::Axis);

        let mouse_move = MouseMove::default();
        assert_eq!(mouse_move.kind(), InputControlKind::DualAxis);

        // No inputs
        let mut app = test_app();
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        let gamepad = Gamepad::new(0);

        assert!(!mouse_move_up.pressed(inputs, gamepad));
        assert_eq!(mouse_move_y.value(inputs, gamepad), 0.0);
        assert_eq!(mouse_move.axis_pair(inputs, gamepad), Vec2::new(0.0, 0.0));

        // Move left
        let data = Vec2::new(-1.0, 0.0);
        let mut app = test_app();
        MouseMoveDirection::LEFT.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(!mouse_move_up.pressed(inputs, gamepad));
        assert_eq!(mouse_move_y.value(inputs, gamepad), 0.0);
        assert_eq!(mouse_move.axis_pair(inputs, gamepad), data);

        // Move up
        let data = Vec2::new(0.0, 1.0);
        let mut app = test_app();
        MouseMoveDirection::UP.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(mouse_move_up.pressed(inputs, gamepad));
        assert_eq!(mouse_move_y.value(inputs, gamepad), data.y);
        assert_eq!(mouse_move.axis_pair(inputs, gamepad), data);

        // Move down
        let data = Vec2::new(0.0, -1.0);
        let mut app = test_app();
        MouseMoveDirection::DOWN.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(!mouse_move_up.pressed(inputs, gamepad));
        assert_eq!(mouse_move_y.value(inputs, gamepad), data.y);
        assert_eq!(mouse_move.axis_pair(inputs, gamepad), data);

        // Set changes in movement on the Y-axis to 3.0
        let data = Vec2::new(0.0, 3.0);
        let mut app = test_app();
        MouseMoveAxis::Y.set_value(app.world_mut(), data.y);
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(mouse_move_up.pressed(inputs, gamepad));
        assert_eq!(mouse_move_y.value(inputs, gamepad), data.y);
        assert_eq!(mouse_move.axis_pair(inputs, gamepad), data);

        // Set changes in movement to (2.0, 3.0)
        let data = Vec2::new(2.0, 3.0);
        let mut app = test_app();
        MouseMove::default().set_axis_pair(app.world_mut(), data);
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(mouse_move_up.pressed(inputs, gamepad));
        assert_eq!(mouse_move_y.value(inputs, gamepad), data.y);
        assert_eq!(mouse_move.axis_pair(inputs, gamepad), data);
    }

    #[test]
    fn test_mouse_scroll() {
        let mouse_scroll_up = MouseScrollDirection::UP;
        assert_eq!(mouse_scroll_up.kind(), InputControlKind::Button);

        let mouse_scroll_y = MouseScrollAxis::Y;
        assert_eq!(mouse_scroll_y.kind(), InputControlKind::Axis);
        let mouse_scroll = MouseScroll::default();
        assert_eq!(mouse_scroll.kind(), InputControlKind::DualAxis);

        // No inputs
        let mut app = test_app();
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        let gamepad = Gamepad::new(0);

        assert!(!mouse_scroll_up.pressed(inputs, gamepad));
        assert_eq!(mouse_scroll_y.value(inputs, gamepad), 0.0);
        assert_eq!(mouse_scroll.axis_pair(inputs, gamepad), Vec2::new(0.0, 0.0));

        // Move up
        let data = Vec2::new(0.0, 1.0);
        let mut app = test_app();
        MouseScrollDirection::UP.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(mouse_scroll_up.pressed(inputs, gamepad));
        assert_eq!(mouse_scroll_y.value(inputs, gamepad), data.y);
        assert_eq!(mouse_scroll.axis_pair(inputs, gamepad), data);

        // Scroll down
        let data = Vec2::new(0.0, -1.0);
        let mut app = test_app();
        MouseScrollDirection::DOWN.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(!mouse_scroll_up.pressed(inputs, gamepad));
        assert_eq!(mouse_scroll_y.value(inputs, gamepad), data.y);
        assert_eq!(mouse_scroll.axis_pair(inputs, gamepad), data);

        // Set changes in scrolling on the Y-axis to 3.0
        let data = Vec2::new(0.0, 3.0);
        let mut app = test_app();
        MouseScrollAxis::Y.set_value(app.world_mut(), data.y);
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(mouse_scroll_up.pressed(inputs, gamepad));
        assert_eq!(mouse_scroll_y.value(inputs, gamepad), data.y);
        assert_eq!(mouse_scroll.axis_pair(inputs, gamepad), data);

        // Set changes in scrolling to (2.0, 3.0)
        let data = Vec2::new(2.0, 3.0);
        let mut app = test_app();
        MouseScroll::default().set_axis_pair(app.world_mut(), data);
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert!(mouse_scroll_up.pressed(inputs, gamepad));
        assert_eq!(mouse_scroll_y.value(inputs, gamepad), data.y);
        assert_eq!(mouse_scroll.axis_pair(inputs, gamepad), data);
    }

    #[test]
    fn one_frame_accumulate_mouse_movement() {
        let mut app = test_app();
        MouseMoveAxis::Y.set_value(app.world_mut(), 3.0);
        MouseMoveAxis::Y.set_value(app.world_mut(), 2.0);

        let mouse_motion_events = app.world().get_resource::<Events<MouseMotion>>().unwrap();
        for event in mouse_motion_events.iter_current_update_events() {
            dbg!("Event sent: {:?}", event);
        }

        // The haven't been processed yet
        let accumulated_mouse_movement = app.world().resource::<AccumulatedMouseMovement>();
        assert_eq!(accumulated_mouse_movement.0, Vec2::new(0.0, 0.0));

        app.update();

        // Now the events should be processed
        let accumulated_mouse_movement = app.world().resource::<AccumulatedMouseMovement>();
        assert_eq!(accumulated_mouse_movement.0, Vec2::new(0.0, 5.0));

        let inputs = app.world().resource::<CentralInputStore>();
        assert_eq!(inputs.pair(&MouseMove::default()), Vec2::new(0.0, 5.0));
    }

    #[test]
    fn multiple_frames_accumulate_mouse_movement() {
        let mut app = test_app();
        let inputs = app.world().resource::<CentralInputStore>();
        // Starts at 0
        assert_eq!(
            inputs.pair(&MouseMove::default()),
            Vec2::ZERO,
            "Initial movement is not zero."
        );

        // Send some data
        MouseMoveAxis::Y.set_value(app.world_mut(), 3.0);
        // Wait for the events to be processed
        app.update();

        let inputs = app.world().resource::<CentralInputStore>();
        // Data is read
        assert_eq!(
            inputs.pair(&MouseMove::default()),
            Vec2::new(0.0, 3.0),
            "Movement sent was not read correctly."
        );

        // Do nothing
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();
        // Back to 0 for this frame
        assert_eq!(
            inputs.pair(&MouseMove::default()),
            Vec2::ZERO,
            "No movement was expected. Is the position in the event stream being cleared properly?"
        );
    }
}