keyboard: Add new public functions

These will be used by future commits.
This commit is contained in:
Xavier Del Campo Romero 2022-09-20 13:49:32 +02:00
parent 39dc70c385
commit b8d3eff412
2 changed files with 83 additions and 0 deletions

View File

@ -29,6 +29,9 @@ void keyboard_update(struct keyboard *k);
bool keyboard_justpressed(const struct keyboard *k, const struct keyboard_combo *c);
bool keyboard_pressed(const struct keyboard *k, const struct keyboard_combo *c);
bool keyboard_justreleased(const struct keyboard *k, const struct keyboard_combo *c);
bool keyboard_any_justpressed(const struct keyboard *k, struct keyboard_combo *c);
bool keyboard_any_pressed(const struct keyboard *k, struct keyboard_combo *c);
char keyboard_to_char(const struct keyboard *k, enum keyboard_key key);
const char *keyboard_key_str(enum keyboard_key k);
#ifdef __cplusplus

View File

@ -1,8 +1,88 @@
#include <keyboard.h>
#include <keyboard_key.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
bool keyboard_any_justpressed(const struct keyboard *const k,
struct keyboard_combo *const c)
{
bool ret = false;
for (size_t i = 0; i < sizeof c->keys / sizeof c->keys; i++)
c->keys[i] = KEYBOARD_KEY_NONE;
for (size_t i = 0, j = 0;
i < sizeof k->combo.keys / sizeof *k->combo.keys; i++)
{
const enum keyboard_key key = k->combo.keys[i];
if (key != KEYBOARD_KEY_NONE
&& k->oldcombo.keys[i] == KEYBOARD_KEY_NONE)
{
c->keys[j++] = key;
ret = true;
}
}
return ret;
}
bool keyboard_any_pressed(const struct keyboard *const k,
struct keyboard_combo *const c)
{
for (size_t i = 0; i < sizeof k->combo.keys / sizeof *k->combo.keys; i++)
{
const enum keyboard_key key = k->combo.keys[i];
if (key != KEYBOARD_KEY_NONE)
{
*c = k->combo;
return true;
}
}
return false;
}
char keyboard_to_char(const struct keyboard *const k,
const enum keyboard_key key)
{
if (key >= KEYBOARD_KEY_0 && key <= KEYBOARD_KEY_9)
return '0' + key - KEYBOARD_KEY_0;
else if (key >= KEYBOARD_KEY_A && key <= KEYBOARD_KEY_Z)
{
if (keyboard_pressed(k, &KEYBOARD_COMBO(KEYBOARD_KEY_LSHIFT))
|| keyboard_pressed(k, &KEYBOARD_COMBO(KEYBOARD_KEY_RSHIFT)))
return 'A' + key - KEYBOARD_KEY_A;
else
return 'a' + key - KEYBOARD_KEY_A;
}
else
{
static const struct map
{
enum keyboard_key key;
char ch;
} map[] =
{
{.key = KEYBOARD_KEY_DOT, .ch = '.'},
{.key = KEYBOARD_KEY_SPACE, .ch = ' '},
{.key = KEYBOARD_KEY_MINUS, .ch = '-'}
};
for (size_t i = 0; i < sizeof map / sizeof *map; i++)
{
const struct map *const m = &map[i];
if (key == m->key)
return m->ch;
}
}
return -1;
}
static bool combo_pressed(const struct keyboard_combo *const ref,
const struct keyboard_combo *const c)
{