#include "google_drive.h" #include "sync.h" #include "mouse_buttons.h" #include "json.hpp" #include #include #include namespace ks { namespace { using Json = nlohmann::json; constexpr auto NativeFormat = "kswitcher-win32-drive-backup-v1"; constexpr auto PreviewFormat = "kswitcher-drive-backup-v1"; // Select fields explicitly so changes to native serialization cannot expand the backup. constexpr const char *PortableFields[] = { "convertLastWord", "switchSystemLayout", "autoCorrectLayout", "autoCorrectReplace", "autoCorrectTypos", "autoCorrectReplacements", "autoCorrectMaxRank", "autoCorrectMinLength", "autoCorrectPrefixChars", "autoCorrectSuffixChars", "autoCorrectLanguages", "autoCorrectNever", "autoCorrectExcludedApps", "autoCorrectWords", "preventScreenLock", "toggleHotkey", "caseHotkey", "translitHotkey", "undoHotkey", "clipboardHotkey", "screenshotHotkey", "filesHotkey", "screenshotAutoOpenEditor", "historyEnabled", "maxItems", "maxTotalMegabytes", "maxImageMegabytes", "excludedApps", "useTesseract", "tesseractLanguages", "layouts", "layoutHotkeys", "chatCycles", "appLanguageSets", "snippets", "mouseBindings", "mouseProfileApplications", "disabledMouseProfiles", "customMouseEvents" }; Bytes bytes(const Json &object) { const auto text = object.dump(); return {text.begin(), text.end()}; } Json portableFields(const Json &source) { auto result = Json::object(); for (const auto *key : PortableFields) if (source.contains(key)) result[key] = source.at(key); return result; } bool machineLocalMouseAction(const Json &binding) { if (!binding.is_object() || binding.value("action", "") != "Launch application") return false; return binding.at("executable").get().find_first_of("\\/:") != std::string::npos; } void excludeMousePaths(Json &settings) { if (!settings.contains("mouseBindings")) return; auto &profiles = settings.at("mouseBindings"); if (!profiles.is_object()) throw std::runtime_error("Invalid mouse profiles."); for (auto &bindings : profiles) { if (!bindings.is_object()) throw std::runtime_error("Invalid mouse actions."); for (auto action = bindings.begin(); action != bindings.end();) { if (machineLocalMouseAction(*action)) action = bindings.erase(action); else ++action; } } } void preserveMousePaths(Json &settings, const Json &local) { if (!settings.contains("mouseBindings")) return; for (const auto &[profile, bindings] : local.at("mouseBindings").items()) for (const auto &[event, action] : bindings.items()) { if (!machineLocalMouseAction(action)) continue; settings["mouseBindings"][profile][event] = action; if (!settings.contains("mouseProfileApplications") || !settings.at("mouseProfileApplications").is_object()) throw std::runtime_error("Invalid mouse profile applications."); auto &scopes = settings.at("mouseProfileApplications"); if (local.at("mouseProfileApplications").contains(profile)) scopes[profile] = local.at("mouseProfileApplications").at(profile); else scopes.erase(profile); if (local.at("customMouseEvents").contains(event) && !settings.at("customMouseEvents").contains(event)) settings["customMouseEvents"][event] = local.at("customMouseEvents").at(event); auto &disabled = settings.at("disabledMouseProfiles"); if (!disabled.is_array()) throw std::runtime_error("Invalid disabled mouse profiles."); const bool wasDisabled = std::find(local.at("disabledMouseProfiles").begin(), local.at("disabledMouseProfiles").end(), profile) != local.at("disabledMouseProfiles").end(); const auto entry = std::find(disabled.begin(), disabled.end(), profile); if (wasDisabled && entry == disabled.end()) disabled.push_back(profile); if (!wasDisabled && entry != disabled.end()) disabled.erase(entry); } } std::vector list(const Json &value) { if (value.is_array()) return value.get>(); auto input = wide(value.get()); std::replace(input.begin(), input.end(), L',', L' '); std::wistringstream stream(input); std::vector result; for (std::wstring item; stream >> item;) result.push_back(utf8(item)); return result; } std::string layoutId(const Json &value) { auto id = utf8(lower(wide(value.get()))); if (id == "english" || id == "en" || id == "us" || id == "00000409") return "win:04090409"; if (id == "ukrainian" || id == "uk" || id == "ua" || id == "00000422") return "win:04220422"; if (id == "russian" || id == "ru" || id == "00000419") return "win:04190419"; if (id == "00000809") return "win:08090809"; return id; } Json layoutList(const Json &value) { auto result = Json::array(); for (const auto &id : list(value)) result.push_back(layoutId(id)); return result; } std::string appName(const Json &value) { return utf8(snippetAppName(wide(value.get()))); } void previewLayouts(const Json &options, Json &result) { if (options.contains("layouts")) { auto &cycle = result["layouts"] = Json::array(); auto &keys = result["layoutHotkeys"] = Json::array(); for (const auto &row : options.at("layouts").get()) { auto id = layoutId(row.at("layout")); if (row.value("included", true)) cycle.push_back(id); keys.push_back({{"layoutId", id}, {"hotkey", row.value("shortcut", "")}}); } } else if (options.contains("legacySettings")) { const auto &legacy = options.at("legacySettings"); if (legacy.contains("layouts")) result["layouts"] = layoutList(legacy.at("layouts")); if (legacy.contains("layoutHotkeys")) { auto &keys = result["layoutHotkeys"] = Json::array(); for (const auto &row : legacy.at("layoutHotkeys").get()) keys.push_back({{"layoutId", layoutId(row.at("layoutId"))}, {"hotkey", row.at("hotkey").get()}}); } } if (options.contains("appLanguages")) { auto &profiles = result["appLanguageSets"] = Json::object(); for (const auto &row : options.at("appLanguages").get()) { auto app = appName(row.at("app")); auto cycle = layoutList(row.at("languages")); if (!app.empty() && !cycle.empty()) profiles[app] = {{"applications", Json::array({app})}, {"languages", cycle}}; } } if (options.contains("chatLanguages")) { auto &profiles = result["chatCycles"] = Json::object(); for (const auto &row : options.at("chatLanguages").get()) { auto app = appName(row.at("app")); auto contact = row.at("contact").get(); auto cycle = layoutList(row.at("languages")); if ((app == "telegram" || app == "telegram-web" || app == "ms-teams" || app == "viber") && !contact.empty() && !cycle.empty()) profiles[app + "\n" + contact] = cycle; } } } void previewSnippets(const Json &settings, const Json &options, Json &result) { using SnippetKey = std::tuple>; auto keyFor = [](const Json &row) { std::set apps; if (row.contains("apps") && row.value("scoped", true)) for (const auto &app : list(row.at("apps"))) apps.insert(appName(app)); return SnippetKey{row.at("trigger").get(), row.at("replacement").get(), std::move(apps)}; }; const auto optionRows = options.value("snippets", Json::array()).get(); std::map ids; for (const auto &row : optionRows) if (row.value("enabled", false) && row.contains("id")) ids.emplace(keyFor(row), row.at("id").get()); Json::array_t rows; if (settings.contains("snippets") && !settings.at("snippets").is_null()) rows = settings.at("snippets").get(); else if (options.contains("snippets")) rows = optionRows; else if (settings.contains("snippet")) rows.push_back(settings.at("snippet")); else return; auto &snippets = result["snippets"] = Json::array(); for (const auto &row : rows) { if (!row.value("enabled", false)) continue; auto key = keyFor(row); const auto &[trigger, replacement, apps] = key; Json item{{"trigger", trigger}, {"text", replacement}}; if (!apps.empty()) item["apps"] = apps; if (row.value("scoped", false) && (!item.contains("apps") || item.at("apps").empty())) throw std::runtime_error("A scoped snippet needs an application."); if (row.contains("id")) item["id"] = row.at("id").get(); else if (const auto id = ids.find(key); id != ids.end()) item["id"] = id->second; snippets.push_back(std::move(item)); } } void previewMouse(const Json &settings, const Json &options, Json &result) { if (!options.contains("mouseProfiles") && !options.contains("mouseActions") && !options.contains("mouseEvents") && !settings.contains("mouse")) return; auto &bindings = result["mouseBindings"] = Json::object(); auto &scopes = result["mouseProfileApplications"] = Json::object(); auto &disabled = result["disabledMouseProfiles"] = Json::array(); auto &custom = result["customMouseEvents"] = Json::object(); constexpr const char *events[] = {"Left click", "Right click", "Middle click", "First side button", "Second side button", "Left double-click", "Right double-click", "Middle double-click", "Wheel up", "Wheel down", "Wheel left", "Wheel right"}; static_assert(std::size(events) == std::size(MouseEvents)); std::map signals, profiles{{"*", "*"}, {"default", "*"}}; for (size_t i = 0; i < std::size(events); ++i) signals[events[i]] = utf8(MouseEvents[i]); for (const auto &row : options.value("mouseEvents", Json::array()).get()) { auto signal = row.value("signal", ""); if (!signals.contains(signal) || !signal.starts_with("Wheel ")) continue; auto name = row.at("name").get(); custom[signal] = name; signals[name] = signal; } for (const auto &row : options.value("mouseProfiles", Json::array()).get()) { auto id = row.at("id").get(); auto name = row.at("name").get(); auto apps = list(row.value("apps", Json(""))); for (auto &app : apps) app = appName(app); if (id == "*" || (id == "default" && apps.empty())) continue; if (id == name && !id.starts_with("name:") && apps.empty() && row.value("enabled", true) && validMouseApplication(wide(id))) { profiles[id] = id; continue; } auto profile = "name:" + name; profiles[id] = profile; bindings[profile] = Json::object(); scopes[profile] = apps; if (!row.value("enabled", true)) disabled.push_back(profile); } auto add = [&](const std::string &profile, const std::string &event, const Json &row) { constexpr const char *actions[] = {"Unassigned", "Shortcut", "Back", "Forward", "VolumeUp", "VolumeDown", "Mute", "Launch"}; static_assert(std::size(actions) == std::size(MouseActions)); auto name = row.at("action").get(); auto match = std::find(std::begin(actions), std::end(actions), name); if (match == std::end(actions)) throw std::runtime_error("Unknown mouse action."); const auto type = static_cast(match - std::begin(actions)); Json binding{{"action", utf8(MouseActions[static_cast(type)])}}; if (type == MouseActionType::Shortcut) binding["shortcut"] = row.at("shortcut").get(); if (type == MouseActionType::Launch) binding["executable"] = row.at("executable").get(); if (isMouseVolumeStep(type)) binding["volumeStep"] = row.value("step", Json(DefaultMouseVolumeStep)); auto apps = list(row.value("apps", Json(""))); for (auto &app : apps) app = appName(app); if (!apps.empty() && !profile.starts_with("name:")) binding["applications"] = apps; if (event.starts_with("Wheel ") && !custom.contains(event)) custom[event] = event; if (!machineLocalMouseAction(binding)) bindings[profile][event] = std::move(binding); }; const auto rows = options.value("mouseActions", Json::array()).get(); for (const auto &row : rows) { auto event = row.at("event").get(); if (signals.contains(event)) add(profiles.at(row.at("profile").get()), signals.at(event), row); } const auto mouse = settings.value("mouse", Json::object()); if (rows.empty() && mouse.value("enabled", false)) { add("*", "XButton1", {{"action", mouse.value("default_action", "Unassigned")}}); auto app = appName(mouse.value("application", "")); if (!app.empty()) add(app, "XButton1", {{"action", mouse.value("application_action", "Unassigned")}}); } } Json previewFields(const Json &profile, const Json &local) { const auto &options = profile.at("options"); const auto &settings = profile.at("settings"); if (!options.is_object() || !settings.is_object() || (options.empty() && settings.empty())) throw std::runtime_error("Invalid preview profile."); auto result = Json::object(); constexpr std::pair fields[] = { {"general.conversion.recent", "convertLastWord"}, {"general.conversion.switchLayout", "switchSystemLayout"}, {"general.correction.maxRank", "autoCorrectMaxRank"}, {"general.correction.minLength", "autoCorrectMinLength"}, {"general.correction.prefix", "autoCorrectPrefixChars"}, {"general.correction.suffix", "autoCorrectSuffixChars"}, {"general.correction.autoReplace", "autoCorrectReplace"}, {"general.correction.autoTypos", "autoCorrectTypos"}, {"general.integration.awake", "preventScreenLock"}, {"shortcuts.key-bindings.toggle", "toggleHotkey"}, {"shortcuts.key-bindings.case", "caseHotkey"}, {"shortcuts.key-bindings.transliterate", "translitHotkey"}, {"shortcuts.key-bindings.undo", "undoHotkey"}, {"shortcuts.key-bindings.clipboard", "clipboardHotkey"}, {"shortcuts.key-bindings.capture", "screenshotHotkey"}, {"shortcuts.key-bindings.files", "filesHotkey"}, {"shortcuts.capture.openEditor", "screenshotAutoOpenEditor"}, {"clipboard.history.record", "historyEnabled"}, {"clipboard.history.items", "maxItems"}, {"clipboard.history.capacity", "maxTotalMegabytes"}, {"clipboard.history.perItem", "maxImageMegabytes"}, {"clipboard.ocr.useTesseract", "useTesseract"}, {"clipboard.ocr.tesseractLanguages", "tesseractLanguages"} }; for (const auto &[from, to] : fields) if (options.contains(from)) result[to] = options.at(from); for (const auto &[from, to] : {std::pair{"general.correction.dictionaryLanguages", "autoCorrectLanguages"}, {"general.correction.autoExcluded", "autoCorrectExcludedApps"}, {"clipboard.history.excluded", "excludedApps"}}) if (options.contains(from)) result[to] = list(options.at(from)); if (options.contains("general.correction.autoReplacements")) { auto &pairs = result["autoCorrectReplacements"] = Json::object(); std::istringstream lines(options.at("general.correction.autoReplacements").get()); for (std::string line; std::getline(lines, line);) { auto split = line.find('='); if (line.find_first_not_of(" \t\r") == line.npos) continue; if (split == line.npos) throw std::runtime_error("Invalid automatic replacement."); auto trim = [](std::string text) { const auto first = text.find_first_not_of(" \t\r"); return first == text.npos ? std::string{} : text.substr(first, text.find_last_not_of(" \t\r") - first + 1); }; if (!pairs.emplace(trim(line.substr(0, split)), trim(line.substr(split + 1))).second) throw std::runtime_error("Duplicate automatic replacement."); } } if (settings.contains("autocorrect")) result["autoCorrectLayout"] = settings.at("autocorrect"); const auto dictionary = settings.value("personal_dictionary", Json::object()); auto words = local.at("autoCorrectWords"); bool hasWords = false; for (const auto &[key, language] : {std::pair{"en", "english"}, {"uk", "ukrainian"}, {"ru", "russian"}}) { const std::string field = std::string("general.correction.words.") + key; if (options.contains(field)) words[key] = list(options.at(field)); else if (dictionary.contains(language)) words[key] = dictionary.at(language).get>(); else continue; hasWords = true; } if (hasWords) result["autoCorrectWords"] = std::move(words); if (options.contains("general.correction.autoNever")) result["autoCorrectNever"] = list(options.at("general.correction.autoNever")); else if (dictionary.contains("never")) result["autoCorrectNever"] = list(dictionary.at("never")); previewLayouts(options, result); previewSnippets(settings, options, result); previewMouse(settings, options, result); if (result.empty()) throw std::runtime_error("No supported preview settings."); return result; } void checkLayouts(const Json &fields, const std::vector &layouts) { auto check = [&](const std::string &id) { const auto w = wide(id); if (std::none_of(layouts.begin(), layouts.end(), [&](const auto &layout) { return layout.id == w; })) throw std::runtime_error("Install the keyboard layouts used by this backup in Windows, then try restoring again."); }; if (fields.contains("layouts")) for (const auto &id : fields.at("layouts").get>()) check(id); if (fields.contains("layoutHotkeys")) for (const auto &binding : fields.at("layoutHotkeys").get()) if (!binding.at("hotkey").get().empty()) check(binding.at("layoutId").get()); } void allowRestoredSnippets(Json &settings) { std::set ids; for (const auto &item : settings.at("snippets").get()) { auto id = item.value("id", ""); if (id.empty() && (!item.contains("apps") || item.at("apps").empty())) id = utf8(snippetId({wide(item.at("trigger").get()), {}, {}, {}})); if (!id.empty()) ids.insert(std::move(id)); } auto tombstones = settings.at("snippetTombstones").get>(); std::erase_if(tombstones, [&](const auto &id) { return ids.contains(id); }); settings["snippetTombstones"] = std::move(tombstones); } Json mergeDriveFields(Json fields, const Json &original) { excludeMousePaths(fields); auto local = original; local.update(fields); if (local.contains("filesHotkey") && local.at("filesHotkey").is_null()) local.erase("filesHotkey"); if (fields.contains("mouseBindings")) preserveMousePaths(local, original); if (fields.contains("snippets")) allowRestoredSnippets(local); return local; } } Bytes sharedDriveSettings(const Settings &saved) { const auto source = Json::parse(sharedSyncSettings(saved)); auto profile = portableFields(source); excludeMousePaths(profile); auto &bindings = profile.at("mouseBindings"); for (auto it = bindings.begin(); it != bindings.end();) // Named profiles can retain their application scope without actions. if (it->empty() && !isNamedMouseProfile(wide(it.key()))) it = bindings.erase(it); else ++it; if (!profile.contains("filesHotkey")) profile["filesHotkey"] = nullptr; for (const auto *field : {"format", "schemaVersion", "snippetTombstones"}) profile[field] = source.at(field); return bytes(profile); } Settings restoreSharedDriveSettings(const Bytes &shared, const Settings &local, const std::vector &layouts) { const auto source = Json::parse(shared); if (!source.is_object() || source.value("format", "") != "kswitcher-settings" || source.value("schemaVersion", 0) != 1 || source.size() != std::size(PortableFields) + 3 || !source.contains("snippetTombstones")) throw std::runtime_error("Invalid Google Drive synchronization profile."); auto fields = portableFields(source); if (fields.size() != std::size(PortableFields)) throw std::runtime_error("Incomplete Google Drive synchronization profile."); fields["snippetTombstones"] = source.at("snippetTombstones"); checkLayouts(fields, layouts); return decodeSettings(bytes(mergeDriveFields(std::move(fields), Json::parse(encodeSettings(local)))), layouts); } Bytes encodeDriveBackup(const Settings &saved) { auto profile = portableFields(Json::parse(encodeSettings(saved))); if (!profile.contains("filesHotkey")) profile["filesHotkey"] = nullptr; excludeMousePaths(profile); auto result = bytes({{"format", NativeFormat}, {"settings", std::move(profile)}}); if (result.size() > GoogleDriveBackupLimit) throw std::runtime_error("Saved settings exceed the 2 MiB backup limit."); return result; } Settings restoreDriveBackup(const Bytes &backup, const Settings &draft, const std::vector &layouts) { if (backup.size() > GoogleDriveBackupLimit) throw std::runtime_error("This Drive backup exceeds the 2 MiB limit."); // Limit nesting before the parser allocates a tree from downloaded data. const auto document = Json::parse(backup, [](int depth, Json::parse_event_t, Json &) { if (depth > 32) throw std::runtime_error("This Drive backup is corrupt."); return true; }, false); if (!document.is_object() || !document.contains("format") || !document.at("format").is_string()) throw std::runtime_error("This Drive backup is corrupt."); const auto format = document.at("format").get(); if (format != NativeFormat && format != PreviewFormat) throw std::runtime_error("This Drive backup format is unsupported."); const auto original = Json::parse(encodeSettings(draft)); auto local = original; Json fields; try { if (format == NativeFormat) { const auto &source = document.at("settings"); if (!source.is_object()) throw std::runtime_error("Invalid settings."); for (const auto *key : PortableFields) if (!source.contains(key)) throw std::runtime_error("Incomplete settings."); fields = portableFields(source); } else fields = previewFields(document.at("profile"), local); local = mergeDriveFields(fields, original); } catch (const std::exception &) { throw std::runtime_error("This Drive backup contains invalid settings."); } try { checkLayouts(fields, layouts); } catch (const Json::exception &) { throw std::runtime_error("This Drive backup contains invalid layouts or shortcuts."); } try { return decodeSettings(bytes(local), layouts); } catch (const std::exception &) { throw std::runtime_error("This Drive backup contains settings that are invalid or conflict with this PC's settings."); } } }