CharacterMapFile.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. Optional<CharacterMapData> CharacterMapFile::load_from_file(const String& filename)
  12. {
  13. auto path = filename;
  14. if (!path.ends_with(".json")) {
  15. StringBuilder full_path;
  16. full_path.append("/res/keymaps/");
  17. full_path.append(filename);
  18. full_path.append(".json");
  19. path = full_path.to_string();
  20. }
  21. auto file = Core::File::construct(path);
  22. file->open(Core::OpenMode::ReadOnly);
  23. if (!file->is_open()) {
  24. dbgln("Failed to open {}: {}", filename, file->error_string());
  25. return {};
  26. }
  27. auto file_contents = file->read_all();
  28. auto json_result = JsonValue::from_string(file_contents);
  29. if (!json_result.has_value())
  30. return {};
  31. auto json = json_result.value().as_object();
  32. Vector<u32> map = read_map(json, "map");
  33. Vector<u32> shift_map = read_map(json, "shift_map");
  34. Vector<u32> alt_map = read_map(json, "alt_map");
  35. Vector<u32> altgr_map = read_map(json, "altgr_map");
  36. Vector<u32> shift_altgr_map = read_map(json, "shift_altgr_map");
  37. CharacterMapData character_map;
  38. for (int i = 0; i < CHAR_MAP_SIZE; i++) {
  39. character_map.map[i] = map.at(i);
  40. character_map.shift_map[i] = shift_map.at(i);
  41. character_map.alt_map[i] = alt_map.at(i);
  42. if (altgr_map.is_empty()) {
  43. // AltGr map was not found, using Alt map as fallback.
  44. character_map.altgr_map[i] = alt_map.at(i);
  45. } else {
  46. character_map.altgr_map[i] = altgr_map.at(i);
  47. }
  48. if (shift_altgr_map.is_empty()) {
  49. // Shift+AltGr map was not found, using Alt map as fallback.
  50. character_map.shift_altgr_map[i] = alt_map.at(i);
  51. } else {
  52. character_map.shift_altgr_map[i] = shift_altgr_map.at(i);
  53. }
  54. }
  55. return character_map;
  56. }
  57. Vector<u32> CharacterMapFile::read_map(const JsonObject& json, const String& name)
  58. {
  59. if (!json.has(name))
  60. return {};
  61. Vector<u32> buffer;
  62. buffer.resize(CHAR_MAP_SIZE);
  63. auto map_arr = json.get(name).as_array();
  64. for (int i = 0; i < map_arr.size(); i++) {
  65. auto key_value = map_arr.at(i).as_string();
  66. if (key_value.length() == 0) {
  67. buffer[i] = 0;
  68. } else if (key_value.length() == 1) {
  69. buffer[i] = key_value.characters()[0];
  70. } else {
  71. Utf8View m_utf8_view(key_value.characters());
  72. buffer[i] = *m_utf8_view.begin();
  73. }
  74. }
  75. return buffer;
  76. }
  77. }