CharacterMapFile.cpp 2.5 KB

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