Serenity Operating System
1/*
2 * Copyright (c) 2020, Hüseyin Aslıtürk <asliturk@hotmail.com>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include "CharacterMapFile.h"
8#include <AK/ByteBuffer.h>
9#include <AK/Utf8View.h>
10#include <LibCore/DeprecatedFile.h>
11
12namespace Keyboard {
13
14ErrorOr<CharacterMapData> CharacterMapFile::load_from_file(DeprecatedString const& filename)
15{
16 auto path = filename;
17 if (!path.ends_with(".json"sv)) {
18 StringBuilder full_path;
19 full_path.append("/res/keymaps/"sv);
20 full_path.append(filename);
21 full_path.append(".json"sv);
22 path = full_path.to_deprecated_string();
23 }
24
25 auto file = TRY(Core::DeprecatedFile::open(path, Core::OpenMode::ReadOnly));
26 auto file_contents = file->read_all();
27 auto json_result = TRY(JsonValue::from_string(file_contents));
28 auto const& json = json_result.as_object();
29
30 Vector<u32> map = read_map(json, "map");
31 Vector<u32> shift_map = read_map(json, "shift_map");
32 Vector<u32> alt_map = read_map(json, "alt_map");
33 Vector<u32> altgr_map = read_map(json, "altgr_map");
34 Vector<u32> shift_altgr_map = read_map(json, "shift_altgr_map");
35
36 CharacterMapData character_map;
37 for (int i = 0; i < CHAR_MAP_SIZE; i++) {
38 character_map.map[i] = map.at(i);
39 character_map.shift_map[i] = shift_map.at(i);
40 character_map.alt_map[i] = alt_map.at(i);
41 if (altgr_map.is_empty()) {
42 // AltGr map was not found, using Alt map as fallback.
43 character_map.altgr_map[i] = alt_map.at(i);
44 } else {
45 character_map.altgr_map[i] = altgr_map.at(i);
46 }
47 if (shift_altgr_map.is_empty()) {
48 // Shift+AltGr map was not found, using Alt map as fallback.
49 character_map.shift_altgr_map[i] = alt_map.at(i);
50 } else {
51 character_map.shift_altgr_map[i] = shift_altgr_map.at(i);
52 }
53 }
54
55 return character_map;
56}
57
58Vector<u32> CharacterMapFile::read_map(JsonObject const& json, DeprecatedString const& name)
59{
60 if (!json.has(name))
61 return {};
62
63 Vector<u32> buffer;
64 buffer.resize(CHAR_MAP_SIZE);
65
66 auto map_arr = json.get_array(name).value();
67 for (size_t i = 0; i < map_arr.size(); i++) {
68 auto key_value = map_arr.at(i).as_string();
69 if (key_value.length() == 0) {
70 buffer[i] = 0;
71 } else if (key_value.length() == 1) {
72 buffer[i] = key_value.characters()[0];
73 } else {
74 Utf8View m_utf8_view(key_value);
75 buffer[i] = *m_utf8_view.begin();
76 }
77 }
78
79 return buffer;
80}
81
82}