@@ -3,7 +3,10 @@ use caw_computer_keyboard::Key;
33use caw_keyboard:: Note ;
44use midly:: { MidiMessage , num:: u7} ;
55use sdl2:: { keyboard:: Scancode , pixels:: Color } ;
6- use std:: { collections:: HashMap , time:: Instant } ;
6+ use std:: {
7+ collections:: { HashMap , HashSet } ,
8+ time:: Instant ,
9+ } ;
710
811const WIDTH_PX : u32 = 128 ;
912const HEIGHT_PX : u32 = 128 ;
@@ -20,6 +23,7 @@ impl KeyMappings {
2023pub struct ComputerKeyboard {
2124 window : Window ,
2225 key_mappings : KeyMappings ,
26+ pressed_keys : HashSet < Note > ,
2327}
2428
2529const SPACEBAR_CONTROLLER : u7 = u7:: from_int_lossy ( 0 ) ;
@@ -35,6 +39,7 @@ impl ComputerKeyboard {
3539 Ok ( Self {
3640 window,
3741 key_mappings,
42+ pressed_keys : HashSet :: new ( ) ,
3843 } )
3944 }
4045
@@ -57,18 +62,19 @@ impl ComputerKeyboard {
5762 controller : SPACEBAR_CONTROLLER ,
5863 value : 0 . into ( ) ,
5964 } ) ,
60-
6165 Event :: KeyDown {
6266 scancode : Some ( scancode) ,
6367 ..
6468 } => {
6569 if let Some ( note) =
6670 self . key_mappings . note_from_scancode ( scancode)
6771 {
68- buf. push ( MidiMessage :: NoteOn {
69- key : note. to_midi_index ( ) . into ( ) ,
70- vel : u7:: max_value ( ) ,
71- } ) ;
72+ if self . pressed_keys . insert ( note) {
73+ buf. push ( MidiMessage :: NoteOn {
74+ key : note. to_midi_index ( ) . into ( ) ,
75+ vel : u7:: max_value ( ) ,
76+ } ) ;
77+ }
7278 }
7379 }
7480 Event :: KeyUp {
@@ -78,9 +84,10 @@ impl ComputerKeyboard {
7884 if let Some ( note) =
7985 self . key_mappings . note_from_scancode ( scancode)
8086 {
87+ self . pressed_keys . remove ( & note) ;
8188 buf. push ( MidiMessage :: NoteOff {
8289 key : note. to_midi_index ( ) . into ( ) ,
83- vel : u7 :: max_value ( ) ,
90+ vel : 0 . into ( ) ,
8491 } ) ;
8592 }
8693 }
0 commit comments