Serenity Operating System
1/*
2 * Copyright (c) 2021-2022, kleines Filmröllchen <filmroellchen@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include "Keyboard.h"
8#include "Music.h"
9#include <AK/Error.h>
10#include <AK/NumericLimits.h>
11
12namespace DSP {
13
14void Keyboard::set_keyboard_note(u8 pitch, Keyboard::Switch note_switch)
15{
16 VERIFY(pitch < note_frequencies.size());
17
18 if (note_switch == Switch::Off) {
19 m_pressed_notes[pitch] = {};
20 return;
21 }
22
23 auto fake_note = RollNote {
24 .on_sample = m_transport->time(),
25 .off_sample = NumericLimits<u32>::max(),
26 .pitch = pitch,
27 .velocity = NumericLimits<i8>::max(),
28 };
29
30 m_pressed_notes[pitch] = fake_note;
31}
32void Keyboard::set_keyboard_note_in_active_octave(i8 octave_offset, Switch note_switch)
33{
34 u8 real_note = octave_offset + (m_virtual_keyboard_octave - 1) * notes_per_octave;
35 set_keyboard_note(real_note, note_switch);
36}
37
38void Keyboard::change_virtual_keyboard_octave(Direction direction)
39{
40 if (direction == Direction::Up) {
41 if (m_virtual_keyboard_octave < octave_max)
42 ++m_virtual_keyboard_octave;
43 } else {
44 if (m_virtual_keyboard_octave > octave_min)
45 --m_virtual_keyboard_octave;
46 }
47}
48
49ErrorOr<void> Keyboard::set_virtual_keyboard_octave(u8 octave)
50{
51 if (octave <= octave_max && octave >= octave_min) {
52 m_virtual_keyboard_octave = octave;
53 return {};
54 }
55 return Error::from_string_literal("Octave out of range");
56}
57
58bool Keyboard::is_pressed(u8 pitch) const
59{
60 return m_pressed_notes[pitch].has_value() && m_pressed_notes[pitch]->is_playing(m_transport->time());
61}
62
63bool Keyboard::is_pressed_in_active_octave(i8 octave_offset) const
64{
65 return is_pressed(octave_offset + virtual_keyboard_octave_base());
66}
67
68}