diff --git a/CMakeLists.txt b/CMakeLists.txt index df067ad..79c3fe3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,8 +48,16 @@ foreach(utilityTarget StayHere StayHereTest) endif() endforeach() add_library(kscore src/lan_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp) +target_sources(kscore PRIVATE src/drive_snapshot.cpp src/google_drive.cpp) +foreach(field IN ITEMS ID SECRET) + set(KS_GOOGLE_CLIENT_${field} "$ENV{KSWITCHER_GOOGLE_CLIENT_${field}}") + if(NOT KS_GOOGLE_CLIENT_${field} MATCHES "^[A-Za-z0-9_.-]*$") + message(FATAL_ERROR "Invalid Google OAuth client configuration.") + endif() +endforeach() +configure_file(cmake/google_drive_oauth_config.h.in generated/google_drive_oauth_config.h @ONLY) target_link_libraries(KSwitcherFiles PRIVATE kscore) -target_include_directories(kscore PUBLIC src PRIVATE vendor) +target_include_directories(kscore PUBLIC src PRIVATE vendor "${CMAKE_CURRENT_BINARY_DIR}/generated") target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00) target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore dwmapi) set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS @@ -221,6 +229,7 @@ else() endif() add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests) add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout) +add_test(NAME google-drive-settings-page COMMAND KSwitcherChatProfileTests --google-drive-layout) set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30) add_executable(KSwitcherHistoryHostTests tests/history_host.cpp) target_include_directories(KSwitcherHistoryHostTests PRIVATE vendor) @@ -306,3 +315,14 @@ else() target_link_options(KSwitcherSettingsMergeTests PRIVATE -static -static-libgcc -static-libstdc++) endif() add_test(NAME settings-save-merge COMMAND KSwitcherSettingsMergeTests) + +add_executable(KSwitcherDriveTests tests/drive_snapshot.cpp) +target_include_directories(KSwitcherDriveTests PRIVATE vendor) +target_link_libraries(KSwitcherDriveTests PRIVATE kscore) +if(MSVC) + target_compile_options(KSwitcherDriveTests PRIVATE /utf-8) + set_property(TARGET KSwitcherDriveTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +else() + target_link_options(KSwitcherDriveTests PRIVATE -static -static-libgcc -static-libstdc++) +endif() +add_test(NAME google-drive-backup COMMAND KSwitcherDriveTests) diff --git a/README.md b/README.md index e2800a0..093013e 100644 --- a/README.md +++ b/README.md @@ -710,6 +710,37 @@ This is a working native implementation, not a claim of complete UI/release pari The Windows focus/injection rules still apply: an unelevated process cannot edit an elevated app. Conversion is cancelled rather than pasting into a different window or replacing unverified recent text. +## Google Drive settings backup + +Open **Settings → Sync → Google Drive** and choose **Connect** to authorize +KSwitcher in your browser. **Back up saved settings** uploads your last applied +settings and displays the backup time. **Restore latest backup** asks for +confirmation and loads the settings into the current draft. Review the result +and choose **Apply** or **Save**. **Disconnect** removes the refresh token from +Windows Credential Manager and leaves existing backups in Google Drive. + +Backups include layouts, shortcuts, snippets, compatible language and mouse +profiles, personal dictionaries and clipboard history preferences. Windows +autostart, diagnostic logging, credentials, paired computer state, clipboard +contents, screenshots and local executable paths stay on the computer. +Install any Windows layouts used by the backup before restoring. Each backup +is limited to 2 MiB. + +The Win32 app can read KSwitcher-New's `kswitcher-drive-backup-v1` snapshots +when both builds have access to the same Google application's private Drive +folder. Win32 imports supported settings and keeps destination values for +fields absent from the backup. Preview-only settings such as the theme and +disabled snippets have no Win32 equivalent. Win32 writes its own versioned +snapshot, which KSwitcher-New does not import. + +To enable the page in a build, supply `KSWITCHER_GOOGLE_CLIENT_ID` and +`KSWITCHER_GOOGLE_CLIENT_SECRET` in the build environment before running +`build.ps1` or configuring CMake. Use a Google OAuth **Desktop app** client +with the Drive API enabled. Use the same authorized Google application as +KSwitcher-New for access to its existing backups. The browser flow uses +PKCE and requests the `drive.appdata` scope. Builds without both values +show the page with its actions disabled. + ## OpenBao synchronization (experimental, opt-in) Open **Settings → Sync → OpenBao**. Synchronization remains disabled diff --git a/build.ps1 b/build.ps1 index 409d687..20793e2 100644 --- a/build.ps1 +++ b/build.ps1 @@ -22,7 +22,12 @@ try { & $compiler @common -Werror -mwindows -municode -static -s utilities/StayHere/main.cpp -luser32 -lshell32 -lgdi32 -lwtsapi32 -o $stayHere if ($LASTEXITCODE) { throw 'StayHere build failed' } Copy-Item -LiteralPath $stayHere -Destination build/release/tools/StayHere.exe -Force - foreach ($name in @('lan_files','lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) { + $filesBuild = Join-Path $outDir 'files-cmake' + & cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel + if ($LASTEXITCODE) { throw 'CMake configuration failed' } + $common += "-I$(Join-Path $filesBuild 'generated')" + $driveObjects = @('build/drive_snapshot.o','build/google_drive.o') + foreach ($name in @('lan_files','lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','drive_snapshot','google_drive','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) { & $compiler @common -c "src/$name.cpp" -o "build/$name.o" if ($LASTEXITCODE) { throw "Compilation failed: $name" } } @@ -35,11 +40,11 @@ try { & windres --codepage=65001 -DKS_SCREENSHOT_RESOURCES resources/app.rc -O coff -o build/screenshot-res.o if ($LASTEXITCODE) { throw 'Screenshot resource compilation failed' } New-Item -ItemType Directory -Force build/release | Out-Null - & $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o @libs -o $executablePath + & $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o @driveObjects build/main.o build/app-res.o @libs -o $executablePath if ($LASTEXITCODE) { throw 'Link failed' } Copy-Item -LiteralPath $executablePath -Destination build/release/KSwitcher.exe -Force $configPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Config.exe' - & $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath + & $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o build/configuration.o build/config_main.o build/ui-config.o @driveObjects build/app-res.o @libs -o $configPath if ($LASTEXITCODE) { throw 'Configurator link failed' } Copy-Item -LiteralPath $configPath -Destination build/release/KSwitcher.Config.exe -Force $screenshotPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Screenshot.exe' @@ -47,9 +52,6 @@ try { if ($LASTEXITCODE) { throw 'Screenshot link failed' } Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force $filesPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Files.exe' - $filesBuild = Join-Path $outDir 'files-cmake' - & cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel - if ($LASTEXITCODE) { throw 'File manager configuration failed' } & cmake --build $filesBuild --target KSwitcherFiles --parallel 8 if ($LASTEXITCODE) { throw 'File manager build failed' } Copy-Item -LiteralPath (Join-Path $filesBuild 'KSwitcher.Files.exe') -Destination $filesPath -Force @@ -67,6 +69,10 @@ try { if ($LASTEXITCODE) { throw 'Settings merge test build failed' } & .\build\KSwitcherSettingsMergeTests.exe if ($LASTEXITCODE) { throw 'Settings merge tests failed' } + & $compiler @common -Werror tests/drive_snapshot.cpp @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherDriveTests.exe + if ($LASTEXITCODE) { throw 'Google Drive snapshot test build failed' } + & .\build\KSwitcherDriveTests.exe + if ($LASTEXITCODE) { throw 'Google Drive snapshot tests failed' } & $compiler @common -Werror tests/lan_clipboard.cpp build/lan_channel.o build/lan_pairing.o build/core.o build/platform.o @libs -static -s -o build/KSwitcherLanClipboardTests.exe if ($LASTEXITCODE) { throw 'LAN clipboard test build failed' } & .\build\KSwitcherLanClipboardTests.exe @@ -107,16 +113,18 @@ try { if ($LASTEXITCODE) { throw 'Test build failed' } & .\build\KSwitcherTests.exe if ($LASTEXITCODE) { throw 'Tests failed' } - & $compiler @common tests/input.cpp tests/input_pause.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe + & $compiler @common tests/input.cpp tests/input_pause.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o @driveObjects build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe if ($LASTEXITCODE) { throw 'Input test build failed' } & .\build\KSwitcherInputTests.exe if ($LASTEXITCODE) { throw 'Input tests failed' } & .\build\KSwitcherInputTests.exe --input-pause if ($LASTEXITCODE) { throw 'Tray pause/resume test failed' } - & $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe + & $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o @driveObjects build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe if ($LASTEXITCODE) { throw 'Chat profile test build failed' } & .\build\KSwitcherChatProfileTests.exe if ($LASTEXITCODE) { throw 'Chat profile tests failed' } + & .\build\KSwitcherChatProfileTests.exe --google-drive-layout + if ($LASTEXITCODE) { throw 'Google Drive Settings test failed' } & $compiler @common tests/screenshot_ui.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/ocr.o build/screenshot-res.o @libs -static -s -o build/KSwitcherScreenshotUITests.exe if ($LASTEXITCODE) { throw 'Screenshot UI test build failed' } & .\build\KSwitcherScreenshotUITests.exe @@ -137,7 +145,7 @@ try { if ($LASTEXITCODE) { throw 'Updater progress UI tests failed' } } if ($Far) { - & $compiler @common tests/far_snippets.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe + & $compiler @common tests/far_snippets.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o @driveObjects build/screenshot-res.o @libs -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe if ($LASTEXITCODE) { throw 'Far snippet test build failed' } $fixture = Start-Process -FilePath (Join-Path $outDir 'KSwitcherFarSnippetTests.exe') -WindowStyle Hidden -Wait -PassThru Get-Content -LiteralPath (Join-Path $outDir 'far-snippets.log') @@ -163,14 +171,14 @@ try { if ($LASTEXITCODE) { throw 'Image capture test build failed' } & $captureTest if ($LASTEXITCODE) { throw 'Image capture tests failed' } - & $compiler @common tests/integration.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherIntegration.exe + & $compiler @common tests/integration.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o @driveObjects build/screenshot-res.o @libs -static -s -o build/KSwitcherIntegration.exe if ($LASTEXITCODE) { throw 'Integration test build failed' } & .\build\KSwitcherIntegration.exe if ($LASTEXITCODE) { throw 'Integration tests failed' } } if ($Ocr) { $ocrTest = Join-Path (Split-Path $executablePath) 'KSwitcherOcrTests.exe' - & $compiler @common tests/ocr.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o $ocrTest + & $compiler @common tests/ocr.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o @driveObjects build/screenshot-res.o @libs -static -s -o $ocrTest if ($LASTEXITCODE) { throw 'OCR test build failed' } & $ocrTest if ($LASTEXITCODE) { throw 'OCR tests failed' } diff --git a/cmake/google_drive_oauth_config.h.in b/cmake/google_drive_oauth_config.h.in new file mode 100644 index 0000000..954669b --- /dev/null +++ b/cmake/google_drive_oauth_config.h.in @@ -0,0 +1,3 @@ +#pragma once +#define KS_GOOGLE_CLIENT_ID "@KS_GOOGLE_CLIENT_ID@" +#define KS_GOOGLE_CLIENT_SECRET "@KS_GOOGLE_CLIENT_SECRET@" diff --git a/src/drive_snapshot.cpp b/src/drive_snapshot.cpp new file mode 100644 index 0000000..26447be --- /dev/null +++ b/src/drive_snapshot.cpp @@ -0,0 +1,457 @@ +#include "google_drive.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); +} +} + +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); + excludeMousePaths(fields); + 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); + } + 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."); + } +} +} diff --git a/src/google_drive.cpp b/src/google_drive.cpp new file mode 100644 index 0000000..cdd15cc --- /dev/null +++ b/src/google_drive.cpp @@ -0,0 +1,534 @@ +#include +#include +#include +#include +#include +#include +#include +#include "google_drive.h" +#include "google_drive_oauth.h" +#include "http_handle.h" +#include "json.hpp" +#if __has_include("google_drive_oauth_config.h") +#include "google_drive_oauth_config.h" +#endif +#include +#include +#include + +namespace ks +{ +namespace +{ +using Json = nlohmann::json; +constexpr std::string_view Scope = "https://www.googleapis.com/auth/drive.appdata"; +constexpr auto TokenHost = L"oauth2.googleapis.com"; +constexpr auto DriveHost = L"www.googleapis.com"; +constexpr auto NativeName = "kswitcher-win32-settings.json"; +constexpr auto Reconnect = "Google Drive needs authorization again. Reconnect your Google account."; +constexpr auto Network = "Could not reach Google Drive. Check your connection and try again."; + +#ifdef KS_GOOGLE_CLIENT_ID +constexpr std::string_view ClientId = KS_GOOGLE_CLIENT_ID, ClientSecret = KS_GOOGLE_CLIENT_SECRET; +#else +constexpr std::string_view ClientId, ClientSecret; +#endif + +void requireConfiguration() +{ + if (!googleDriveConfigured()) throw std::runtime_error("Google Drive is unavailable in this build."); +} + +std::wstring credentialName() +{ + return L"KSwitcher.GoogleDrive/" + wide(std::string(ClientId)); +} + +std::string refreshToken() +{ + PCREDENTIALW raw{}; + if (!CredReadW(credentialName().c_str(), CRED_TYPE_GENERIC, 0, &raw)) + { + if (GetLastError() == ERROR_NOT_FOUND) return {}; + throw std::runtime_error("Could not read the Google Drive connection from Windows Credential Manager."); + } + struct Credential + { + PCREDENTIALW value; + ~Credential() + { + if (value->CredentialBlobSize) SecureZeroMemory(value->CredentialBlob, value->CredentialBlobSize); + CredFree(value); + } + } credential{raw}; + if (!raw->CredentialBlobSize) return {}; + return {reinterpret_cast(raw->CredentialBlob), raw->CredentialBlobSize}; +} + +void saveRefreshToken(std::string &token) +{ + if (token.empty() || token.size() > CRED_MAX_CREDENTIAL_BLOB_SIZE) + throw std::runtime_error("Google did not return a usable offline connection. Reconnect and allow access."); + auto target = credentialName(); + CREDENTIALW credential{}; + credential.Type = CRED_TYPE_GENERIC; + credential.TargetName = target.data(); + credential.CredentialBlobSize = static_cast(token.size()); + credential.CredentialBlob = reinterpret_cast(token.data()); + credential.Persist = CRED_PERSIST_LOCAL_MACHINE; + if (!CredWriteW(&credential, 0)) + throw std::runtime_error("Could not save the Google Drive connection in Windows Credential Manager."); +} + +std::string urlEncode(std::string_view value) +{ + constexpr char hex[] = "0123456789ABCDEF"; + std::string result; + for (unsigned char c : value) + { + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '-' || c == '_' || c == '.' || c == '~') result += static_cast(c); + else + { + result += '%'; + result += hex[c >> 4]; + result += hex[c & 15]; + } + } + return result; +} + +std::string form(std::initializer_list> fields) +{ + std::string result; + for (const auto &[key, value] : fields) + { + if (!result.empty()) result += '&'; + result += key; + result += '='; + result += urlEncode(value); + } + return result; +} + +std::optional urlDecode(std::string_view value) +{ + auto digit = [](char c) + { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + }; + std::string result; + while (!value.empty()) + { + const char c = value.front(); + value.remove_prefix(1); + if (c != '%') result += (c == '+' ? ' ' : c); + else + { + if (value.size() < 2 || digit(value[0]) < 0 || digit(value[1]) < 0) return {}; + result += static_cast(digit(value[0]) * 16 + digit(value[1])); + value.remove_prefix(2); + } + } + return result; +} + +std::string base64Url(const std::array &data) +{ + std::array encoded{}; + DWORD length = static_cast(encoded.size()); + if (!CryptBinaryToStringA(data.data(), static_cast(data.size()), + CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, encoded.data(), &length)) + throw std::runtime_error("Could not start a secure Google connection."); + std::string result(encoded.data(), length); + for (char &c : result) + { + if (c == '/') c = '_'; + if (c == '+') c = '-'; + } + result.resize(result.find('=')); + return result; +} + +std::string randomParameter() +{ + std::array data{}; + if (BCryptGenRandom(nullptr, data.data(), static_cast(data.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0) + throw std::runtime_error("Could not start a secure Google connection."); + return base64Url(data); +} + +} + +std::string google_drive_oauth::challengeFor(const std::string &verifier) +{ + BCRYPT_ALG_HANDLE algorithm{}; + if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0) + throw std::runtime_error("Could not start a secure Google connection."); + std::array hash{}; + const auto status = BCryptHash(algorithm, nullptr, 0, + reinterpret_cast(const_cast(verifier.data())), static_cast(verifier.size()), + hash.data(), static_cast(hash.size())); + BCryptCloseAlgorithmProvider(algorithm, 0); + if (status < 0) throw std::runtime_error("Could not start a secure Google connection."); + return base64Url(hash); +} + +namespace +{ +struct HttpResponse { DWORD status{}; Bytes body; }; + +HttpResponse https(const wchar_t *host, const wchar_t *method, const std::wstring &path, + const std::wstring &headers, std::string &payload, size_t limit) +{ + HttpHandle session{WinHttpOpen(L"KSwitcher Google Drive/1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)}; + if (!session.h || !WinHttpSetTimeouts(session.h, 5000, 5000, 10000, 10000)) + throw std::runtime_error(Network); + HttpHandle connection{WinHttpConnect(session.h, host, INTERNET_DEFAULT_HTTPS_PORT, 0)}; + HttpHandle request{connection.h ? WinHttpOpenRequest(connection.h, method, path.c_str(), nullptr, + WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr}; + DWORD redirects = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; + DWORD disable = WINHTTP_DISABLE_COOKIES | WINHTTP_DISABLE_AUTHENTICATION; + if (!request.h || + !WinHttpSetOption(request.h, WINHTTP_OPTION_REDIRECT_POLICY, &redirects, sizeof(redirects)) || + !WinHttpSetOption(request.h, WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable)) || + !WinHttpSendRequest(request.h, headers.c_str(), static_cast(headers.size()), + payload.empty() ? WINHTTP_NO_REQUEST_DATA : payload.data(), static_cast(payload.size()), + static_cast(payload.size()), 0) || + !WinHttpReceiveResponse(request.h, nullptr)) + throw std::runtime_error(Network); + HttpResponse response; + DWORD length = sizeof(response.status); + if (!WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, + WINHTTP_HEADER_NAME_BY_INDEX, &response.status, &length, WINHTTP_NO_HEADER_INDEX)) + throw std::runtime_error(Network); + if (response.status < 200 || response.status >= 300) return response; + const auto deadline = GetTickCount64() + 30000; + for (;;) + { + unsigned char buffer[8192]; + DWORD count{}; + if (GetTickCount64() >= deadline || !WinHttpReadData(request.h, buffer, sizeof(buffer), &count)) + throw std::runtime_error(Network); + if (!count) return response; + if (count > limit - response.body.size()) + throw std::runtime_error(limit == GoogleDriveBackupLimit ? "This Drive backup exceeds the 2 MiB limit." : + "Google returned an oversized response."); + response.body.insert(response.body.end(), buffer, buffer + count); + } +} + +struct ClearString +{ + std::string &value; + ~ClearString() { if (!value.empty()) SecureZeroMemory(value.data(), value.size()); } +}; + +struct Tokens { std::string access, refresh; }; + +Tokens requestTokens(std::string payload) +{ + ClearString clear{payload}; + payload += "&" + form({{"client_id", ClientId}, {"client_secret", ClientSecret}}); + auto response = https(TokenHost, L"POST", L"/token", L"Content-Type: application/x-www-form-urlencoded\r\n", + payload, 64 * 1024); + if (response.status == 400 || response.status == 401 || response.status == 403) + throw std::runtime_error(Reconnect); + if (response.status < 200 || response.status >= 300) + throw std::runtime_error("Google could not authorize the connection. Try again."); + const auto data = Json::parse(response.body, nullptr, false); + if (!response.body.empty()) SecureZeroMemory(response.body.data(), response.body.size()); + try + { + Tokens tokens{data.at("access_token").get(), data.value("refresh_token", "")}; + if (tokens.access.empty() || tokens.access.find_first_not_of( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~+/=") != std::string::npos) + throw std::runtime_error("Invalid Google access token."); + return tokens; + } + catch (const std::exception &) + { + throw std::runtime_error("Google returned an invalid authorization response."); + } +} + +struct Winsock +{ + Winsock() + { + WSADATA data{}; + if (WSAStartup(MAKEWORD(2, 2), &data)) throw std::runtime_error("Could not open a local sign-in callback."); + } + ~Winsock() { WSACleanup(); } +}; + +struct Socket +{ + SOCKET handle; + ~Socket() { if (handle != INVALID_SOCKET) closesocket(handle); } +}; + +} + +std::optional google_drive_oauth::callbackCode(std::string_view request, std::string_view state) +{ + constexpr std::string_view prefix = "GET /oauth/callback?"; + const auto end = request.find(' ', prefix.size()); + if (!request.starts_with(prefix) || end == std::string_view::npos) return {}; + auto query = request.substr(prefix.size(), end - prefix.size()); + std::optional returnedState, code; + bool denied = false; + while (!query.empty()) + { + const auto next = query.find('&'); + const auto entry = query.substr(0, next); + const auto equals = entry.find('='); + if (equals != std::string_view::npos) + { + const auto key = entry.substr(0, equals); + const auto value = entry.substr(equals + 1); + if (key == "state") + { + if (returnedState) return {}; + returnedState = urlDecode(value); + if (!returnedState) return {}; + } + if (key == "code") + { + if (code) return {}; + code = urlDecode(value); + if (!code) return {}; + } + if (key == "error") denied = true; + } + if (next == std::string_view::npos) break; + query.remove_prefix(next + 1); + } + if (!returnedState || *returnedState != state) return {}; + return denied ? std::string{} : code.value_or(""); +} + +namespace +{ +void checkCanceled(std::stop_token stop) +{ + if (stop.stop_requested()) throw std::runtime_error("Google sign-in was canceled."); +} + +std::optional readCallback(SOCKET socket, std::string_view state, std::stop_token stop) +{ + const DWORD timeout = 200; + const auto timeoutValue = reinterpret_cast(&timeout); + if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, timeoutValue, sizeof(timeout)) || + setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, timeoutValue, sizeof(timeout))) return {}; + const auto deadline = GetTickCount64() + 2000; + std::string request; + for (;;) + { + checkCanceled(stop); + if (GetTickCount64() >= deadline || request.size() >= 8192) return {}; + char buffer[1024]; + const auto count = recv(socket, buffer, static_cast(sizeof(buffer)), 0); + if (count <= 0) return {}; + request.append(buffer, count); + if (request.find("\r\n") != request.npos) break; + } + auto code = google_drive_oauth::callbackCode(request.substr(0, request.find("\r\n")), state); + const std::string message = !code ? "This sign-in response did not match KSwitcher." : + code->empty() ? "Google sign-in was canceled. Return to KSwitcher." : "Return to KSwitcher to finish signing in."; + const std::string reply = std::string(code ? "HTTP/1.1 200 OK" : "HTTP/1.1 400 Bad Request") + + "\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer" + "\r\nConnection: close\r\nContent-Length: " + std::to_string(message.size()) + "\r\n\r\n" + message; + send(socket, reply.data(), static_cast(reply.size()), 0); + return code; +} + +std::string waitForCode(SOCKET listener, const std::string &state, std::stop_token stop) +{ + const auto deadline = GetTickCount64() + 120000; + while (GetTickCount64() < deadline) + { + checkCanceled(stop); + fd_set readable; + FD_ZERO(&readable); + FD_SET(listener, &readable); + timeval interval{0, 200000}; + const int ready = select(0, &readable, nullptr, nullptr, &interval); + if (!ready) continue; + Socket peer{ready == SOCKET_ERROR ? INVALID_SOCKET : accept(listener, nullptr, nullptr)}; + if (peer.handle == INVALID_SOCKET) throw std::runtime_error("Could not receive the Google sign-in response."); + const auto code = readCallback(peer.handle, state, stop); + if (!code) continue; + if (code->empty()) throw std::runtime_error("Google sign-in was declined or canceled."); + return *code; + } + throw std::runtime_error("Google sign-in timed out. Connect again to retry."); +} + +void checkDrive(DWORD status) +{ + if (status == 401) throw std::runtime_error(Reconnect); + if (status == 403) throw std::runtime_error("Google Drive denied access. Reconnect or check your account's access."); + if (status < 200 || status >= 300) throw std::runtime_error("Google Drive could not complete the request. Try again."); +} + +HttpResponse driveRequest(const wchar_t *method, const std::string &path, const std::string &access, + const std::wstring &contentType = {}, std::string payload = {}, size_t limit = 64 * 1024) +{ + auto response = https(DriveHost, method, wide(path), L"Authorization: Bearer " + wide(access) + L"\r\n" + + (contentType.empty() ? L"" : L"Content-Type: " + contentType + L"\r\n"), payload, limit); + checkDrive(response.status); + return response; +} + +std::string accessToken() +{ + requireConfiguration(); + auto refresh = refreshToken(); + ClearString clear{refresh}; + if (refresh.empty()) throw std::runtime_error(Reconnect); + return requestTokens(form({{"grant_type", "refresh_token"}, {"refresh_token", refresh}})).access; +} + +struct DriveFile { std::string id; std::wstring created; }; + +DriveFile driveFile(const Json &file) +{ + DriveFile result{file.at("id").get(), wide(file.at("createdTime").get())}; + if (result.id.empty() || result.created.empty()) throw std::runtime_error("Incomplete backup metadata."); + return result; +} + +std::optional latestFile(const std::string &access) +{ + std::string page; + // Drive can return an empty page with a continuation token. + for (int i = 0; i < 20; ++i) + { + const auto query = form({{"spaces", "appDataFolder"}, {"pageSize", "1"}, {"orderBy", "createdTime desc"}, + {"q", "name = 'kswitcher-settings.json' or name = 'kswitcher-win32-settings.json'"}, + {"fields", "nextPageToken,files(id,createdTime)"}}); + const auto response = driveRequest(L"GET", "/drive/v3/files?" + query + + (page.empty() ? "" : "&pageToken=" + urlEncode(page)), access); + try + { + const auto data = Json::parse(response.body, nullptr, false); + const auto &files = data.at("files").get_ref(); + if (!files.empty()) return driveFile(files.front()); + page = data.value("nextPageToken", ""); + if (page.empty()) return {}; + } + catch (const std::exception &) + { + throw std::runtime_error("Google Drive returned an unreadable backup list."); + } + } + throw std::runtime_error("Google Drive did not finish listing backups. Try again."); +} +} + +bool googleDriveConfigured() +{ + return !ClientId.empty() && !ClientSecret.empty(); +} + +bool googleDriveConnected() +{ + if (!googleDriveConfigured()) return false; + auto token = refreshToken(); + ClearString clear{token}; + return !token.empty(); +} + +void connectGoogleDrive(std::stop_token stop) +{ + requireConfiguration(); + checkCanceled(stop); + Winsock winsock; + Socket listener{socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)}; + sockaddr_in address{}; + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + int length = sizeof(address); + const BOOL exclusive = TRUE; + if (listener.handle == INVALID_SOCKET || + setsockopt(listener.handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast(&exclusive), sizeof(exclusive)) || + bind(listener.handle, reinterpret_cast(&address), length) || + listen(listener.handle, SOMAXCONN) || + getsockname(listener.handle, reinterpret_cast(&address), &length)) + throw std::runtime_error("Could not open a local sign-in callback."); + const auto redirect = "http://127.0.0.1:" + std::to_string(ntohs(address.sin_port)) + "/oauth/callback"; + const auto state = randomParameter(); + const auto verifier = randomParameter(); + const auto url = wide("https://accounts.google.com/o/oauth2/v2/auth?" + form({ + {"client_id", ClientId}, {"redirect_uri", redirect}, {"response_type", "code"}, {"scope", Scope}, + {"access_type", "offline"}, {"prompt", "consent select_account"}, {"state", state}, + {"code_challenge", google_drive_oauth::challengeFor(verifier)}, {"code_challenge_method", "S256"}})); + const auto initialized = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); + const auto opened = ShellExecuteW(nullptr, L"open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL); + if (SUCCEEDED(initialized)) CoUninitialize(); + if (reinterpret_cast(opened) <= 32) + throw std::runtime_error("Could not open the system browser."); + auto code = waitForCode(listener.handle, state, stop); + ClearString clearCode{code}; + checkCanceled(stop); + auto tokens = requestTokens(form({{"grant_type", "authorization_code"}, {"code", code}, + {"redirect_uri", redirect}, {"code_verifier", verifier}})); + ClearString clearAccess{tokens.access}, clearRefresh{tokens.refresh}; + checkCanceled(stop); + saveRefreshToken(tokens.refresh); +} + +void disconnectGoogleDrive() +{ + requireConfiguration(); + if (!CredDeleteW(credentialName().c_str(), CRED_TYPE_GENERIC, 0) && GetLastError() != ERROR_NOT_FOUND) + throw std::runtime_error("Could not remove the Google Drive connection from Windows Credential Manager."); +} + +std::wstring latestGoogleDriveBackup() +{ + auto access = accessToken(); + ClearString clear{access}; + auto file = latestFile(access); + return file ? file->created : std::wstring{}; +} + +std::wstring uploadGoogleDriveBackup(const Bytes &settings) +{ + if (settings.size() > GoogleDriveBackupLimit) throw std::runtime_error("Saved settings exceed the 2 MiB backup limit."); + auto access = accessToken(); + ClearString clear{access}; + const auto boundary = randomParameter(); + const auto metadata = Json{{"name", NativeName}, {"parents", Json::array({"appDataFolder"})}}.dump(); + std::string payload = "--" + boundary + "\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n" + + metadata + "\r\n--" + boundary + "\r\nContent-Type: application/json\r\n\r\n"; + payload.append(settings.begin(), settings.end()); + payload += "\r\n--" + boundary + "--\r\n"; + const auto response = driveRequest(L"POST", "/upload/drive/v3/files?uploadType=multipart&fields=id%2CcreatedTime", + access, L"multipart/related; boundary=" + wide(boundary), std::move(payload)); + try + { + return driveFile(Json::parse(response.body, nullptr, false)).created; + } + catch (const std::exception &) + { + throw std::runtime_error("Google Drive did not confirm the saved backup."); + } +} + +GoogleDriveBackup fetchGoogleDriveBackup() +{ + auto access = accessToken(); + ClearString clear{access}; + const auto file = latestFile(access); + if (!file) return {}; + auto response = driveRequest(L"GET", "/drive/v3/files/" + urlEncode(file->id) + "?alt=media", access, + {}, {}, GoogleDriveBackupLimit); + return {file->created, std::move(response.body)}; +} +} diff --git a/src/google_drive.h b/src/google_drive.h new file mode 100644 index 0000000..fba3c35 --- /dev/null +++ b/src/google_drive.h @@ -0,0 +1,24 @@ +#pragma once +#include "storage.h" +#include + +namespace ks +{ +inline constexpr size_t GoogleDriveBackupLimit = 2 * 1024 * 1024; + +Bytes encodeDriveBackup(const Settings &saved); +Settings restoreDriveBackup(const Bytes &, const Settings &draft, const std::vector &); + +bool googleDriveConfigured(); +bool googleDriveConnected(); +void connectGoogleDrive(std::stop_token); +void disconnectGoogleDrive(); +std::wstring latestGoogleDriveBackup(); +std::wstring uploadGoogleDriveBackup(const Bytes &); +struct GoogleDriveBackup +{ + std::wstring created; + Bytes settings; +}; +GoogleDriveBackup fetchGoogleDriveBackup(); +} diff --git a/src/google_drive_oauth.h b/src/google_drive_oauth.h new file mode 100644 index 0000000..2bbb0fb --- /dev/null +++ b/src/google_drive_oauth.h @@ -0,0 +1,11 @@ +#pragma once +#include +#include +#include + +namespace ks::google_drive_oauth +{ +std::string challengeFor(const std::string &verifier); +// nullopt ignores unrelated requests. An empty code is a rejected authorization. +std::optional callbackCode(std::string_view request, std::string_view state); +} diff --git a/src/http_handle.h b/src/http_handle.h new file mode 100644 index 0000000..e20e622 --- /dev/null +++ b/src/http_handle.h @@ -0,0 +1,15 @@ +#pragma once +#include +#include + +namespace ks +{ +struct HttpHandle +{ + explicit HttpHandle(HINTERNET handle) : h(handle) {} + HttpHandle(const HttpHandle &) = delete; + HttpHandle &operator=(const HttpHandle &) = delete; + ~HttpHandle() { if (h) WinHttpCloseHandle(h); } + HINTERNET h; +}; +} diff --git a/src/sync.cpp b/src/sync.cpp index c7cf204..0c88c44 100644 --- a/src/sync.cpp +++ b/src/sync.cpp @@ -1,7 +1,7 @@ #include "sync.h" +#include "http_handle.h" #include "mouse_buttons.h" #include "json.hpp" -#include #include #include #include @@ -30,11 +30,6 @@ bool safePath(const std::wstring &s) s.find(L"//") != s.npos) return false; return s.find_first_not_of(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-/") == s.npos; } -struct HttpHandle -{ - HINTERNET h{}; - ~HttpHandle() { if (h) WinHttpCloseHandle(h); } -}; class OpenBao final : public SyncProvider { SyncConfig config; diff --git a/src/ui.cpp b/src/ui.cpp index f5675cb..f30ce99 100644 --- a/src/ui.cpp +++ b/src/ui.cpp @@ -9,10 +9,13 @@ #include "richtext.h" #include "ui_geometry.h" #include "diagnostics.h" +#include "google_drive.h" #include #include +#include #include #include +#include #include #include #include @@ -20,6 +23,7 @@ #include #include #include +#include #include namespace ks @@ -1131,7 +1135,7 @@ constexpr UINT AppWindowPicked = WM_APP + 78; constexpr int SettingsNavigation = 260, SettingsStatus = 261, SettingsViewport = 264, SettingsApply = 272; constexpr int SettingsBrand = 265, SettingsHeading = 266, SettingsDescription = 267, SettingsGroup = 268; constexpr int SettingsSearch = 269, GeneralPage = 0, ComputersPage = 7, ManageComputersPage = 10, CorrectionPage = 11; -constexpr int SyncPage = 6, OpenBaoPage = 17, SettingsSyncPanel = 271; +constexpr int SyncPage = 6, OpenBaoPage = 17, GoogleDrivePage = 18, SettingsSyncPanel = 271; constexpr UINT CollapseSettingsGroupMessage = WM_APP + 188; constexpr int SettingsSidebarWidth = 214, SettingsHeaderHeight = 82, SettingsFooterHeight = 76; constexpr int SettingsNavigationIndent = 16; @@ -1151,7 +1155,7 @@ constexpr struct SettingsSection {"clipboard", L"Clipboard", L"Configure clipboard history, storage limits and text recognition."}, {"snippets", L"Snippets", L"Create text expansions and choose which applications can use them."}, {"mouse", L"Mouse", L"Manage profiles, assign actions and test your mouse buttons."}, - {"sync", L"Sync", L"Back up and synchronize settings through OpenBao."}, + {"sync", L"Sync", L"Choose a provider to back up or synchronize your settings."}, {"computers", L"Computers", L"Share mouse and keyboard with paired computers."}, {"diagnostics", L"Diagnostics", L"Manage diagnostic logging and view recent operations."}, {"mcp", L"MCP", L"Connect Codex to KSwitcher to read diagnostic logs."}, @@ -1163,6 +1167,7 @@ constexpr struct SettingsSection {"word-boundaries", L"Word boundaries", L"Choose which punctuation KSwitcher keeps before and after a corrected word.", CorrectionPage}, {"custom-replacements", L"Custom replacements", L"Define your own corrections, which take priority over dictionary suggestions.", CorrectionPage}, {"openbao", L"OpenBao", L"Connect to OpenBao and synchronize your saved settings.", SyncPage}, + {"google-drive", L"Google Drive", L"Manually back up saved settings or restore a backup into the Settings draft.", SyncPage}, }; constexpr wchar_t SettingsWindowFile[] = L"configurator-window.json"; struct SettingsWindowState @@ -1284,7 +1289,7 @@ struct SettingsView }; std::array pages; int selectedPage = -1; - HWND viewport{}, navigation{}, search{}, heading{}, description{}, brand{}, lan{}, sync{}, splitter{}; + HWND viewport{}, navigation{}, search{}, heading{}, description{}, brand{}, lan{}, sync{}, drive{}, splitter{}; int sidebarWidth = SettingsSidebarWidth; std::optional splitterDragOffset; bool splitterHovered{}; @@ -1340,6 +1345,7 @@ void snippetWindowPicked(HWND w, WPARAM target, LPARAM phase); bool snippetDraftChanged(HWND, SnippetView *); bool mergeSnippetDraft(HWND, SnippetView *, Settings &); void refreshSnippetDraft(HWND, SnippetView *); +void fillSnippets(HWND, SnippetView *); void updateSettingsState(HWND w, SettingsView *v); bool matchesSettingsSearch(const SettingsView &v, const std::wstring &text) { @@ -1391,6 +1397,7 @@ void repaintSettingsMatches(const SettingsView &v) InvalidateRect(v.viewport, nullptr, TRUE); if (v.lan) InvalidateRect(v.lan, nullptr, TRUE); if (v.sync) InvalidateRect(v.sync, nullptr, TRUE); + if (v.drive) InvalidateRect(v.drive, nullptr, TRUE); } LRESULT CALLBACK settingsViewportProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) { @@ -1566,7 +1573,7 @@ void setSettingsFonts(HWND w, SettingsView &v, UINT dpi) assign(v.brand, font(w, 18, FW_SEMIBOLD), v.brandFont); HFONT group = font(w, 15, FW_SEMIBOLD); HFONT field = font(w, 14, FW_SEMIBOLD); - for (HWND pane : {v.viewport, v.lan, v.sync}) + for (HWND pane : {v.viewport, v.lan, v.sync, v.drive}) if (pane) { SetPropW(pane, L"Font", GetPropW(w, L"Font")); @@ -1751,6 +1758,7 @@ int fitSettingsColumns(WindowLayout &layout, size_t first, size_t end, int width } int fitLanSettings(HWND panel, int width); int fitSyncSettings(HWND panel, int width); +int fitDriveSettings(HWND panel, int width); void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height) { const auto &v = *reinterpret_cast(GetWindowLongPtrW(GetParent(pane), GWLP_USERDATA)); @@ -1759,11 +1767,11 @@ void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height) auto fit = [&](int pixels) { const int available = std::max(1, pixels * 96 / static_cast(dpi)); - if (v.selectedPage == ManageComputersPage || v.selectedPage == OpenBaoPage) + if (v.selectedPage == ManageComputersPage || v.selectedPage == OpenBaoPage || v.selectedPage == GoogleDrivePage) { const int panelWidth = std::max(1, available - 16); const int panelHeight = v.selectedPage == ManageComputersPage ? fitLanSettings(v.lan, panelWidth) : - fitSyncSettings(v.sync, panelWidth); + v.selectedPage == OpenBaoPage ? fitSyncSettings(v.sync, panelWidth) : fitDriveSettings(v.drive, panelWidth); layout.controls[page.first].second = {8, 7, 8 + panelWidth, 7 + panelHeight}; layout.height = panelHeight + 15; return; @@ -2432,6 +2440,7 @@ void resizeSettingsForDpi(HWND w, int previousDpi, int nextDpi) arrangeWindow(v.viewport); if (v.lan) arrangeWindow(v.lan); if (v.sync) arrangeWindow(v.sync); + if (v.drive) arrangeWindow(v.drive); if (previousDpi != nextDpi) scaleMouseTableColumns(w, previousDpi, nextDpi); } void collectLayout(SettingsView *v) @@ -2796,6 +2805,7 @@ void showOcrOptions(HWND parent, SettingsView *v) } #include "ui_sync.inl" #include "ui_lan.inl" +#include "ui_google_drive.inl" bool settingsChanged(SettingsView *v) { try @@ -2868,7 +2878,10 @@ void applySettingsDraft(HWND w, SettingsView *v, bool keepOpen) if (lanEdited) lan->draft.clear(); v->draft = v->app->settings; fillSettings(w, v); - refreshSnippetDraft(v->viewport, &v->snippets); + v->snippets.snippets = v->snippets.saved = v->draft.snippets; + if (v->snippets.selection >= static_cast(v->snippets.snippets.size())) v->snippets.selection = -1; + fillSnippets(v->viewport, &v->snippets); + updateSettingsState(w, v); if (syncEdited) reloadSyncEditor(v->sync); if (lanEdited) refreshLan(v->lan, *lan); } @@ -3971,6 +3984,12 @@ void showSettings(App &app, bool visible) indexSettingsControl(*v, OpenBaoPage, child); page(); + v->drive = createDriveSettings(pane, *v); + layout->controls.push_back({v->drive, {8, 55, 8 + DriveSettingsWidth, 55 + DriveSettingsHeight}}); + for (HWND child = GetWindow(v->drive, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT)) + indexSettingsControl(*v, GoogleDrivePage, child); + page(); + v->splitter = control(w, L"STATIC", L"Resize navigation pane", SS_NOTIFY | WS_TABSTOP, SettingsSplitter, 0, 0, 0, 0); SetWindowSubclass(v->splitter, settingsSplitterProc, 1, reinterpret_cast(v)); diff --git a/src/ui_google_drive.inl b/src/ui_google_drive.inl new file mode 100644 index 0000000..df81e1b --- /dev/null +++ b/src/ui_google_drive.inl @@ -0,0 +1,295 @@ +constexpr int DriveConnect = 620, DriveBackup = 621, DriveRestore = 622, DriveDisconnect = 623, DriveStatus = 624; +constexpr int DriveSettingsWidth = 660, DriveSettingsHeight = 270; +enum class DriveAction { Status, Connect, Backup, Restore, Disconnect }; +struct DriveResult +{ + std::optional connected; + std::optional latest; + std::wstring notice; + std::optional backup; +}; +struct DriveTask +{ + std::stop_source stop; + std::atomic_bool signingIn{}; + std::mutex mutex; + std::optional result; +}; +struct DriveView +{ + SettingsView *settings; + bool configured = googleDriveConfigured(), connected{}; + DriveAction action = DriveAction::Status; + std::shared_ptr task; + std::wstring latest, notice; +}; + +std::wstring driveBackupTime(const std::wstring &value) +{ + SYSTEMTIME utc{}, local{}; + const int fields = std::swscanf(value.c_str(), L"%hu-%hu-%huT%hu:%hu:%hu", + &utc.wYear, &utc.wMonth, &utc.wDay, &utc.wHour, &utc.wMinute, &utc.wSecond); + if (fields != 6 || !SystemTimeToTzSpecificLocalTimeEx(nullptr, &utc, &local)) return value; + wchar_t date[128]{}, time[128]{}; + if (!GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, DATE_SHORTDATE, &local, nullptr, date, std::size(date), nullptr) || + !GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, 0, &local, nullptr, time, std::size(time))) return value; + return std::wstring(date) + L" " + time; +} + +void updateDriveControls(HWND w, const DriveView &view) +{ + const bool signingIn = view.task && view.task->signingIn; + const bool busy = view.task != nullptr; + const bool available = view.configured && !busy; + EnableWindow(GetDlgItem(w, DriveConnect), available || (signingIn && !view.task->stop.stop_requested())); + EnableWindow(GetDlgItem(w, DriveBackup), available && view.connected); + EnableWindow(GetDlgItem(w, DriveRestore), available && view.connected); + EnableWindow(GetDlgItem(w, DriveDisconnect), available && view.connected); + value(w, DriveConnect, signingIn ? L"Cancel &sign-in" : view.connected ? L"&Reconnect" : L"&Connect"); + std::wstring status = !view.configured ? L"Google Drive is unavailable in this build." : + view.connected ? L"Google Drive is connected." : L"Google Drive is disconnected."; + if (view.connected && !view.latest.empty()) status += L"\r\nLatest backup: " + driveBackupTime(view.latest); + if (!view.notice.empty()) status += L"\r\n" + view.notice; + if (value(w, DriveStatus) != status) value(w, DriveStatus, status); +} + +void startDriveTask(HWND w, DriveView &view, DriveAction action) +{ + auto task = std::make_shared(); + task->signingIn = action == DriveAction::Connect; + const auto path = view.settings->app->data / L"settings.json"; + const auto layouts = view.settings->app->layouts; + if (!SetTimer(w, 1, 100, nullptr)) throw std::runtime_error("Could not start the Google Drive action."); + try + { + std::thread([task, action, path, layouts] + { + DriveResult result; + try + { + switch (action) + { + case DriveAction::Status: + case DriveAction::Connect: + if (action == DriveAction::Connect) + { + connectGoogleDrive(task->stop.get_token()); + task->signingIn = false; + } + result.connected = googleDriveConnected(); + if (*result.connected) + { + result.latest = latestGoogleDriveBackup(); + if (result.latest->empty()) result.notice = L"No Google Drive backup yet."; + } + break; + case DriveAction::Backup: + { + Settings saved; + try { saved = loadSettings(path, layouts); } + catch (const std::exception &) { throw std::runtime_error("Could not read the saved KSwitcher settings."); } + result.latest = uploadGoogleDriveBackup(encodeDriveBackup(saved)); + result.notice = L"Saved settings backed up to Google Drive."; + break; + } + case DriveAction::Restore: + { + auto backup = fetchGoogleDriveBackup(); + result.latest = std::move(backup.created); + if (result.latest->empty()) result.notice = L"No backup is available for this Google account."; + else result.backup = std::move(backup.settings); + break; + } + case DriveAction::Disconnect: + disconnectGoogleDrive(); + result.connected = false; + result.notice = L"Disconnected. Backups are still in Google Drive."; + break; + } + } + catch (const std::runtime_error &error) { result.notice = wide(error.what()); } + catch (const std::exception &) { result.notice = L"The Google Drive operation could not finish."; } + std::lock_guard lock(task->mutex); + task->result.emplace(std::move(result)); + }).detach(); + } + catch (...) + { + KillTimer(w, 1); + throw; + } + view.task = std::move(task); + view.action = action; + switch (action) + { + case DriveAction::Status: view.notice = L"Checking the Google Drive connection…"; break; + case DriveAction::Connect: view.notice = L"Complete Google sign-in in your browser."; break; + case DriveAction::Backup: view.notice = L"Backing up saved settings…"; break; + case DriveAction::Restore: view.notice = L"Downloading the latest backup…"; break; + case DriveAction::Disconnect: view.notice = L"Disconnecting from Google Drive…"; break; + } + updateDriveControls(w, view); +} + +void restoreDriveDraft(HWND root, SettingsView &settings, const Bytes &backup) +{ + Settings draft; + try + { + draft = collectSettings(&settings); + mergeSnippetDraft(settings.viewport, &settings.snippets, draft); + } + catch (const std::exception &) + { + throw std::runtime_error("Correct invalid edits in Settings before restoring the backup."); + } + auto restored = restoreDriveBackup(backup, draft, settings.app->layouts); + settings.draft = std::move(restored); + settings.snippets.snippets = settings.draft.snippets; + settings.snippets.selection = -1; + fillSnippets(settings.viewport, &settings.snippets); + fillSettings(root, &settings); +} + +void finishDriveTask(HWND w, DriveView &view) +{ + const auto root = GetAncestor(w, GA_ROOT); + auto task = view.task; + if (!task) return; + DriveResult result; + { + std::lock_guard lock(task->mutex); + if (!task->result) + { + if (view.action == DriveAction::Connect && !task->signingIn) + { + view.connected = true; + view.latest.clear(); + view.notice = L"Checking for the latest backup…"; + updateDriveControls(w, view); + } + return; + } + if (task->result->backup && (!IsWindowEnabled(root) || !IsWindowVisible(w))) return; + result = std::move(*task->result); + } + KillTimer(w, 1); + view.task.reset(); + if (result.connected) + { + view.connected = *result.connected; + view.latest.clear(); + } + if (result.latest) view.latest = std::move(*result.latest); + view.notice = std::move(result.notice); + if (result.backup) + { + const auto accepted = MessageBoxW(root, + L"Load the latest backup into Settings? It will replace unapplied edits to the settings included in the backup. Use Apply or Save to make the restored settings active.", + L"Restore settings from Google Drive", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) == IDYES; + if (!IsWindow(w)) return; + if (accepted) + { + restoreDriveDraft(root, *view.settings, *result.backup); + view.notice = L"Backup loaded into Settings. Click Apply or Save to use it."; + } + else view.notice = L"Restore canceled."; + } + updateDriveControls(w, view); +} + +LRESULT CALLBACK driveSettingsProc(HWND w, UINT message, WPARAM wp, LPARAM lp) +{ + if (message == WM_SIZE) arrangeWindow(w); + auto *view = reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)); + if (!view) return DefWindowProcW(w, message, wp, lp); + try + { + switch (message) + { + case WM_PAINT: paintSettingsMatches(w); return 0; + case WM_CTLCOLORSTATIC: return SendMessageW(GetParent(w), message, wp, lp); + case WM_SHOWWINDOW: + if (wp && !view->task && view->configured) startDriveTask(w, *view, DriveAction::Status); + break; + case WM_TIMER: + if (wp == 1) finishDriveTask(w, *view); + return 0; + case WM_COMMAND: + { + const auto id = LOWORD(wp); + if (id < DriveConnect || id > DriveDisconnect || HIWORD(wp) != BN_CLICKED || + !IsWindowEnabled(GetDlgItem(w, id))) break; + if (view->task) + { + if (!view->task->signingIn) return 0; + view->task->stop.request_stop(); + view->notice = L"Canceling Google sign-in…"; + updateDriveControls(w, *view); + return 0; + } + const auto action = id == DriveConnect ? DriveAction::Connect : id == DriveBackup ? DriveAction::Backup : + id == DriveRestore ? DriveAction::Restore : DriveAction::Disconnect; + startDriveTask(w, *view, action); + return 0; + } + case WM_NCDESTROY: + KillTimer(w, 1); + if (view->task) view->task->stop.request_stop(); + delete windowLayoutState(w); + RemovePropW(w, L"WindowLayout"); + RemovePropW(w, L"Font"); + delete view; + SetWindowLongPtrW(w, GWLP_USERDATA, 0); + break; + } + } + catch (const std::exception &error) + { + view->notice = dynamic_cast(&error) ? wide(error.what()) : + L"The Google Drive operation could not finish."; + updateDriveControls(w, *view); + return 0; + } + return DefWindowProcW(w, message, wp, lp); +} + +HWND createDriveSettings(HWND pane, SettingsView &settings) +{ + WNDCLASSW panel{}; + panel.hInstance = settings.app->instance; + panel.lpfnWndProc = driveSettingsProc; + panel.lpszClassName = L"KSwitcher.GoogleDrive"; + panel.hCursor = LoadCursorW(nullptr, IDC_ARROW); + panel.hbrBackground = GetSysColorBrush(COLOR_WINDOW); + RegisterClassW(&panel); + const HWND w = CreateWindowExW(WS_EX_CONTROLPARENT, panel.lpszClassName, L"", WS_CHILD | WS_CLIPCHILDREN, + 0, 0, scale(pane, DriveSettingsWidth), scale(pane, DriveSettingsHeight), pane, nullptr, panel.hInstance, nullptr); + if (!w) throw std::runtime_error("Cannot create Google Drive settings."); + auto *view = new DriveView{&settings}; + SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast(view)); + SetPropW(w, L"Font", GetPropW(pane, L"Font")); + auto *layout = new WindowLayout{DriveSettingsWidth, DriveSettingsHeight, 0, 0, true, true}; + SetPropW(w, L"WindowLayout", layout); + constexpr int left = 16, width = DriveSettingsWidth - 2 * left; + settingsGroupLabel(w, L"Backup and restore", left, 14, width); + label(w, L"Apply or Save your edits before backing them up.", left, 44, width); + edit(w, DriveStatus, left, 72, width, 76, ES_MULTILINE | ES_READONLY | WS_VSCROLL); + button(w, L"&Connect", DriveConnect, left, 160, 210); + button(w, L"Back &up saved settings", DriveBackup, left, 198, 210); + button(w, L"&Restore latest backup", DriveRestore, 338, 160, 210); + button(w, L"&Disconnect", DriveDisconnect, 338, 198, 210); + captureSettingsGeometry(*layout, 0, w); + layout->arranging = false; + updateDriveControls(w, *view); + return w; +} + +int fitDriveSettings(HWND panel, int width) +{ + auto &layout = *windowLayoutState(panel); + layout.width = 1; + layout.height = fitSettingsColumns(layout, 0, layout.controls.size(), width, + {16, DriveSettingsWidth - 16, 338, 322, 0, 535, 0, 150}); + return layout.height; +} diff --git a/tests/chat_profiles.cpp b/tests/chat_profiles.cpp index f564161..47ce118 100644 --- a/tests/chat_profiles.cpp +++ b/tests/chat_profiles.cpp @@ -3,6 +3,7 @@ #include "ocr.h" #include "screenshot.h" #include "lan_pairing.h" +#include "google_drive.h" #include "settings_ui.h" #include #include @@ -25,6 +26,55 @@ void require(bool ok, const char *message) if (!ok) throw std::runtime_error(message); ++passed; } +void googleDriveWindowChecks(const std::filesystem::path &root) +{ + ks::App app(GetModuleHandleW(nullptr), true, root); + ks::showSettings(app); + const auto settings = app.settingsWindow; + const auto pane = settingsViewport(settings); + const auto navigation = settingsNavigation(settings); + const auto driveItem = settingsSection(navigation, 18); + const auto baoItem = settingsSection(navigation, 17); + require(driveItem && baoItem && TreeView_GetParent(navigation, driveItem) == settingsSection(navigation, 6) && + TreeView_GetParent(navigation, baoItem) == settingsSection(navigation, 6), + "Google Drive and OpenBao are siblings under Sync"); + selectSettingsPage(settings, 18); + const auto drive = FindWindowExW(pane, nullptr, L"KSwitcher.GoogleDrive", nullptr); + require(drive && IsWindowVisible(drive) && !IsWindowVisible(GetDlgItem(pane, 271)), + "Google Drive opens inside Settings and hides OpenBao"); + RECT panelBounds{}; + GetWindowRect(drive, &panelBounds); + for (int id : {620, 621, 622, 623, 624}) + { + const auto control = GetDlgItem(drive, id); + RECT bounds{}; + require(IsWindowVisible(control) && GetWindowRect(control, &bounds) && + bounds.left >= panelBounds.left && bounds.top >= panelBounds.top && + bounds.right <= panelBounds.right && bounds.bottom <= panelBounds.bottom, + "Google Drive controls fit inside the rendered panel"); + } + if (!ks::googleDriveConfigured()) + { + wchar_t status[160]{}; + GetDlgItemTextW(drive, 624, status, std::size(status)); + require(std::wstring_view(status).find(L"unavailable in this build") != std::wstring_view::npos, + "unconfigured OAuth build shows its status"); + for (int id : {620, 621, 622, 623}) + require(!IsWindowEnabled(GetDlgItem(drive, id)), "unconfigured OAuth actions are disabled"); + } + RedrawWindow(settings, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); + RECT area{}; + GetClientRect(settings, &area); + const auto dc = GetDC(settings); + const auto capture = ks::screenshotClip(dc, area.right, area.bottom, {}); + ReleaseDC(settings, dc); + ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-google-drive.png", + ks::encodePng(ks::decodeImage(capture))); + selectSettingsPage(settings, 17); + require(!IsWindowVisible(drive) && IsWindowVisible(GetDlgItem(pane, 271)), "OpenBao is still accessible"); + require(!IsWindowEnabled(GetDlgItem(settings, SettingsApply)) && + !std::filesystem::exists(root / L"settings.json"), "navigation leaves the settings draft and disk clean"); +} void settingsWindowStateChecks(const std::filesystem::path &root) { ks::App app(GetModuleHandleW(nullptr), true, root); @@ -470,6 +520,14 @@ int main(int argc,char **argv) auto root = std::filesystem::temp_directory_path() / (L"KSwitcher-chat-tests-" + std::to_wstring(GetCurrentProcessId())); try { + if (argc == 2 && std::string_view(argv[1]) == "--google-drive-layout") + { + googleDriveWindowChecks(root); + std::filesystem::remove_all(root); + CoUninitialize(); + std::cout << "PASS Google Drive Settings (" << passed << " checks)\n"; + return 0; + } if(argc==2 && std::string_view(argv[1])=="--lan-layout") { lanWindowLayoutChecks(root); @@ -565,7 +623,7 @@ int main(int argc,char **argv) SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0); require(!saveEnabled(), "reverting an inline correction edit disables Save"); HWND navigation = settingsNavigation(parent); - constexpr int sections = 18; + constexpr int sections = 19; require(navigation && TreeView_GetCount(navigation) == sections && TreeView_GetParent(navigation, settingsSection(navigation, 10)) == settingsSection(navigation, 7) && TreeView_GetParent(navigation, settingsSection(navigation, 11)) == settingsSection(navigation, 0), diff --git a/tests/drive_snapshot.cpp b/tests/drive_snapshot.cpp new file mode 100644 index 0000000..b8727c2 --- /dev/null +++ b/tests/drive_snapshot.cpp @@ -0,0 +1,178 @@ +#include "google_drive.h" +#include "google_drive_oauth.h" +#include "mouse_buttons.h" +#include "json.hpp" +#include +#include + +namespace +{ +using namespace ks; +using Json = nlohmann::json; + +void check(bool condition, const char *message) +{ + if (!condition) throw std::runtime_error(message); +} + +Bytes bytes(std::string_view text) { return {text.begin(), text.end()}; } + +const std::vector Layouts{{{}, L"win:04090409"}, {{}, L"win:04220422"}}; + +void oauthProtocol() +{ + using namespace google_drive_oauth; + check(challengeFor("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") == + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "PKCE challenge differs from the RFC 7636 vector"); + check(callbackCode("GET /oauth/callback?state=right&code=a%2Bb HTTP/1.1", "right") == "a+b", + "loopback rejected a correctly encoded authorization code"); + check(callbackCode("GET /oauth/callback?state=right&error=access_denied HTTP/1.1", "right") == "", + "loopback did not report denied consent"); + for (const auto *request : {"GET /oauth/callback?state=other&code=x HTTP/1.1", + "GET /oauth/callback?state=right&state=right&code=x HTTP/1.1", + "GET /oauth/callback?state=right&code=%X1 HTTP/1.1", + "GET /favicon.ico?state=right&code=x HTTP/1.1"}) + check(!callbackCode(request, "right"), "loopback accepted an unrelated or malformed request"); +} + +void nativeBackup() +{ + auto saved = decodeSettings({}, Layouts); + saved.toggle = L"Ctrl+Alt+F10"; + saved.filesHotkey = L""; + saved.direct[0] = L"Ctrl+F9"; + saved.snippets = {{L";hi", L"Hello", L"restored-snippet", {L"notepad"}}}; + saved.autoWords[L"en"] = {L"foobar"}; + saved.appLanguageSets[L"Editor"] = {{L"win:04220422"}, {L"notepad"}}; + saved.mouseBindings[GlobalMouseProfile][L"XButton1"] = {MouseActionType::Back}; + saved.mouseBindings[L"edge"][L"XButton1"] = {MouseActionType::Launch, {}, L"C:\\source-private\\secret.exe"}; + saved.mouseBindings[L"edge"][L"XButton2"] = {MouseActionType::Launch, {}, L"calc.exe"}; + saved.tesseractPath = L"C:\\private\\ocr.exe"; + saved.snippetTombstones = {L"source-tombstone"}; + saved.autostart = saved.elevatedAutostart = saved.writeLog = true; + + auto destination = decodeSettings({}, Layouts); + destination.toggle = L"Ctrl+Alt+F11"; + destination.tesseractPath = L"D:\\local\\ocr.exe"; + destination.writeLog = true; + destination.snippetTombstones = {L"restored-snippet", L"destination-tombstone"}; + destination.mouseBindings[L"edge"][L"XButton1"] = {MouseActionType::Launch, {}, L"D:\\local\\tool.exe"}; + + const auto backup = encodeDriveBackup(saved); + auto envelope = Json::parse(backup); + const auto &stored = envelope.at("settings"); + for (auto key : {"writeLog", "startWithSystem", "autostartAsAdministrator", "tesseractPath", "snippetTombstones"}) + check(!stored.contains(key), "machine-specific field in native backup"); + check(!stored.at("mouseBindings").at("edge").contains("XButton1"), "local executable path in native backup"); + envelope["settings"]["openBaoPassword"] = "fake-provider-password"; + envelope["settings"]["tesseractPath"] = "C:\\injected\\ocr.exe"; + envelope["settings"]["mouseBindings"]["edge"]["XButton1"] = {{"action", "Launch application"}, + {"executable", "C:\\injected\\other.exe"}}; + const auto restored = restoreDriveBackup(bytes(envelope.dump()), destination, Layouts); + check(restored.toggle == saved.toggle && restored.filesHotkey == L"" && restored.direct == saved.direct, + "saved shortcuts failed to restore"); + check(restored.snippets.size() == 1 && restored.snippets[0].id == L"restored-snippet" && + restored.snippets[0].apps == std::vector{L"notepad"}, "saved snippet failed to restore"); + check(restored.snippetTombstones == std::vector{L"destination-tombstone"}, + "restore did not resurrect the snippet while preserving unrelated tombstones"); + check(restored.autoWords == saved.autoWords && restored.appLanguageSets == saved.appLanguageSets, + "saved dictionary or language profile failed to restore"); + const auto &mouse = restored.mouseBindings.at(L"edge"); + check(mouse.at(L"XButton1").executable == L"D:\\local\\tool.exe" && mouse.at(L"XButton2").executable == L"calc.exe", + "local mouse action or portable executable name failed to survive restore"); + check(restored.tesseractPath == destination.tesseractPath && restored.writeLog && + !restored.autostart && !restored.elevatedAutostart, "restore overwrote local preferences"); + check(destination.toggle == L"Ctrl+Alt+F11" && destination.snippets.empty(), "restore mutated its input draft"); +} + +// Envelope and profile fields emitted by KSwitcher-New at 6a8d71d. +constexpr auto PreviewSample = R"json({ + "format": "kswitcher-drive-backup-v1", + "profile": { + "settings": { + "autocorrect": true, + "mouse": {"enabled": false, "default_action": "Unassigned", "application": "", "application_action": "Unassigned"}, + "snippet": {"enabled": false, "trigger": "", "replacement": ""}, + "snippets": [{"enabled": true, "trigger": ";mail", "replacement": "Hello {cursor}", "apps": ["notepad"], "template": true}], + "personal_dictionary": {"english": ["foobar"], "ukrainian": [], "never": ["skip"]} + }, + "options": { + "layouts": [{"id": "us", "layout": "English", "included": true, "shortcut": "Ctrl+F9"}, + {"id": "ua", "layout": "win:04220422", "included": true, "shortcut": ""}], + "appLanguages": [{"id": "editor", "app": "notepad.exe", "languages": "win:04220422\nEnglish"}], + "chatLanguages": [{"id": "chat", "app": "telegram.exe", "contact": "Example", "languages": "English"}], + "snippets": [{"id": "preview-uuid", "enabled": true, "trigger": ";mail", "replacement": "Hello {cursor}", "scoped": true, "apps": "notePAD.exe"}], + "mouseProfiles": [{"id": "*", "name": "Global", "enabled": true, "apps": ""}, + {"id": "editor", "name": "Editor mouse", "enabled": true, "apps": "notepad.exe"}, + {"id": "chrome", "name": "chrome", "enabled": true, "apps": ""}], + "mouseActions": [{"id": "wheel", "profile": "editor", "event": "Wheel up", "action": "VolumeUp", "step": 7}, + {"id": "back", "profile": "chrome", "event": "First side button", "action": "Back"}], + "mouseEvents": [{"id": "wheel-up", "name": "Scroll up", "signal": "Wheel up"}], + "shortcuts.key-bindings.toggle": "Ctrl+Alt+F10", + "general.correction.autoReplacements": "teh=the", + "appearance.color-scheme.scheme": "dark" + } + } +})json"; + +void previewBackup() +{ + auto destination = decodeSettings({}, Layouts); + destination.clipboard = L"Ctrl+F8"; + destination.tesseractPath = L"D:\\local\\ocr.exe"; + destination.autoWords[L"ru"] = {L"слово"}; + auto restored = restoreDriveBackup(bytes(PreviewSample), destination, Layouts); + check(restored.autoCorrect && restored.toggle == L"Ctrl+Alt+F10" && restored.direct[0] == L"Ctrl+F9", + "preview layout or shortcut mapping failed"); + check(restored.snippets.size() == 1 && restored.snippets[0].id == L"preview-uuid" && + restored.snippets[0].apps == std::vector{L"notepad"} && + restored.snippets[0].text == L"Hello {cursor}", "preview snippet mapping failed"); + check(restored.autoWords.at(L"en").front() == L"foobar" && restored.autoNever.front() == L"skip" && + restored.autoReplacements.at(L"teh") == L"the" && restored.autoWords.at(L"ru") == destination.autoWords.at(L"ru"), + "preview personal dictionary mapping or retention failed"); + check(restored.appLanguageSets.at(L"notepad").languages.size() == 2 && + restored.chatCycles.at(L"telegram\nExample").front() == L"win:04090409", "preview language profiles failed"); + check(restored.mouseProfileApplications.at(L"name:Editor mouse").contains(L"notepad") && + restored.mouseBindings.at(L"name:Editor mouse").at(L"Wheel up").volumeStep == 7 && + restored.customMouseEvents.at(L"Wheel up") == L"Scroll up" && + restored.mouseBindings.at(L"chrome").at(L"XButton1").type == MouseActionType::Back, "preview mouse mapping failed"); + check(restored.clipboard == destination.clipboard && restored.tesseractPath == destination.tesseractPath, + "preview settings overwritten despite being absent from backup"); +} + +void rejects(const Bytes &backup, std::string_view expected, const std::vector &layouts = Layouts) +{ + try { restoreDriveBackup(backup, decodeSettings({}, layouts), layouts); } + catch (const std::runtime_error &error) + { + check(std::string_view(error.what()).find(expected) != std::string_view::npos, "unexpected restore error"); + return; + } + throw std::runtime_error("invalid backup was accepted"); +} +} + +int main() +{ + try + { + oauthProtocol(); + nativeBackup(); + previewBackup(); + rejects(bytes("not json"), "corrupt"); + rejects(bytes(R"({"format":"other"})"), "unsupported"); + rejects(bytes(R"({"format":"kswitcher-win32-drive-backup-v1","settings":{}})"), "invalid"); + rejects(Bytes(GoogleDriveBackupLimit + 1, 'a'), "2 MiB"); + rejects(bytes(PreviewSample), "Install the keyboard layouts", {}); + auto malformed = Json::parse(PreviewSample); + malformed["profile"]["options"]["shortcuts.key-bindings.toggle"] = "not a shortcut"; + rejects(bytes(malformed.dump()), "invalid or conflict"); + std::cout << "Google Drive backup tests passed\n"; + return 0; + } + catch (const std::exception &error) + { + std::cerr << error.what() << '\n'; + return 1; + } +}