diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5bf1328..2d4d5f2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,65 +1,88 @@ -name: Release Build +name: CI on: push: - tags: - - 'v*' + branches: [main] + tags: ['v*'] + pull_request: + branches: [main] permissions: contents: write jobs: - build: + # The detection algorithm has no Windows dependency, so its regression suite + # runs on Linux in a couple of seconds. + detector-tests: + name: Shake detector tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Configure + run: cmake -S . -B build -DSTFC_BUILD_TESTS=ON + - name: Build tests + run: cmake --build build --target shake_detector_tests + - name: Run tests + run: ctest --test-dir build --output-on-failure + + windows: + name: Windows (${{ matrix.arch }}) runs-on: windows-latest strategy: matrix: - arch: [x64, x86] - + arch: [x64, Win32] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4 - - name: Set up Visual Studio shell - uses: egor-tensin/vs-shell@v2 - with: - arch: ${{ matrix.arch }} + - name: Configure + run: cmake -S . -B build -A ${{ matrix.arch }} - - name: Create Build Directory - run: cmake -E make_directory ${{github.workspace}}/build + - name: Build + run: cmake --build build --config Release - - name: Configure CMake - working-directory: ${{github.workspace}}/build - run: cmake .. -A ${{ matrix.arch=='x64' && 'x64' || 'Win32' }} + - name: Run tests (MSVC) + run: ctest --test-dir build -C Release --output-on-failure - - name: Build - working-directory: ${{github.workspace}}/build - run: cmake --build . --config Release + - name: Check the manifest really is embedded + shell: pwsh + run: | + $exe = "build/Release/ShakeToFindCursor.exe" + Get-Item $exe | Select-Object Name, Length + $bytes = [System.IO.File]::ReadAllBytes((Resolve-Path $exe)) + $text = [System.Text.Encoding]::ASCII.GetString($bytes) + if (-not $text.Contains('PerMonitorV2')) { + throw "the embedded manifest does not declare PerMonitorV2" + } - - name: Package - run: | - mkdir publish - cp build/Release/ShakeToFindCursor.exe "publish/ShakeToFindCursor-${{ matrix.arch }}.exe" || true + - name: Package + shell: pwsh + run: | + New-Item -ItemType Directory -Force -Path publish | Out-Null + $arch = "${{ matrix.arch }}".ToLower() + Copy-Item build/Release/ShakeToFindCursor.exe "publish/ShakeToFindCursor-$arch.exe" + Get-ChildItem publish - - name: Upload Artifacts - uses: actions/upload-artifact@v4 - with: - name: ShakeToFindCursor-${{ matrix.arch }} - path: publish/* + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: ShakeToFindCursor-${{ matrix.arch }} + path: publish/* release: - needs: build + name: GitHub release + needs: [windows, detector-tests] + if: startsWith(github.ref, 'refs/tags/v') runs-on: windows-latest steps: - - name: Download Artifacts - uses: actions/download-artifact@v4 - with: - path: artifacts - merge-multiple: true - - - name: Create Release - uses: softprops/action-gh-release@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - files: artifacts/*.exe - draft: false - prerelease: false \ No newline at end of file + - name: Download artifacts + uses: actions/download-artifact@v4 + with: + path: artifacts + merge-multiple: true + - name: Create release + uses: softprops/action-gh-release@v2 + with: + files: artifacts/*.exe + draft: false + prerelease: false + generate_release_notes: true diff --git a/.gitignore b/.gitignore index e6fe1cb..7130336 100644 --- a/.gitignore +++ b/.gitignore @@ -35,4 +35,6 @@ .vscode/* # Build files -build/* \ No newline at end of file +build/* +# Generated resources +*.res diff --git a/CMakeLists.txt b/CMakeLists.txt index 234f25b..6ed6187 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,40 +1,126 @@ -cmake_minimum_required(VERSION 3.15) - -project(ShakeToFindCursor - VERSION 1.3.0 - LANGUAGES CXX) - -set(CMAKE_CXX_STANDARD 17) - -if(NOT WIN32) - message(FATAL_ERROR "This project only supports Windows platform") -endif() - -add_definitions(-DUNICODE -D_UNICODE) - -add_executable(${PROJECT_NAME} - WIN32 - main.cpp - res.rc -) - -if(MSVC) - target_compile_options(${PROJECT_NAME} - PRIVATE - /W4 - /WX - /MP - /EHsc - /utf-8 - ) - set_target_properties(${PROJECT_NAME} PROPERTIES - LINK_FLAGS "/MANIFEST /MANIFESTUAC:\"level='requireAdministrator' uiAccess='false'\" " - ) -else() - target_compile_options(${PROJECT_NAME} - PRIVATE - -Wall - -Wextra - -Wpedantic - ) -endif() +cmake_minimum_required(VERSION 3.15) + +project(ShakeToFindCursor + VERSION 1.4.0 + LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# The app ships as one bare .exe, so the CRT is linked in rather than referenced +# (otherwise a fresh Windows box without the Visual C++ redistributable gets +# "VCRUNTIME140.dll was not found" on first double-click). +if(MSVC) + set(CMAKE_MSVC_RUNTIME_LIBRARY + "MultiThreaded$<$:Debug>") +endif() + +option(STFC_BUILD_TESTS "Build the detector unit tests (run with ctest)" ON) +option(STFC_STRICT_WARNINGS "Treat warnings as errors when building" ON) +option(STFC_REQUIRE_ADMIN + "Embed a requireAdministrator manifest instead of asInvoker") + +enable_testing() + +# --------------------------------------------------------------------------- +# Shake detector tests. Header-only, no Windows dependency, so they build and +# run on any platform - which is how the detection algorithm gets regression +# coverage without a Windows machine. +# --------------------------------------------------------------------------- +if(STFC_BUILD_TESTS) + add_executable(shake_detector_tests tests/shake_detector_test.cpp) + target_include_directories(shake_detector_tests PRIVATE src) + if(MSVC) + target_compile_options(shake_detector_tests PRIVATE /W3 /EHsc /utf-8) + else() + target_compile_options(shake_detector_tests PRIVATE -Wall -Wextra) + endif() + add_test(NAME shake_detector_tests COMMAND shake_detector_tests) +endif() + +if(NOT WIN32) + message(STATUS "ShakeToFindCursor: not on Windows - only the detector " + "tests were configured.") + return() +endif() + +add_definitions(-DUNICODE -D_UNICODE) + +set(STFC_SOURCES + main.cpp + src/app_settings.cpp + src/auto_start.cpp + src/find_overlay.cpp + src/pointer_zoomer.cpp + src/win_util.cpp) + +# --------------------------------------------------------------------------- +# Resources. res.rc is generated with absolute paths for the icon and the +# manifest: rc.exe and windres disagree about how a relative resource file name +# is resolved, and the manifest is what carries the DPI awareness plus the +# asInvoker / requireAdministrator choice, so it must be embedded exactly once. +# --------------------------------------------------------------------------- +if(STFC_REQUIRE_ADMIN) + set(STFC_MANIFEST_FILE + "${CMAKE_CURRENT_SOURCE_DIR}/app.requireAdministrator.manifest") +else() + set(STFC_MANIFEST_FILE "${CMAKE_CURRENT_SOURCE_DIR}/app.manifest") +endif() +# rc.exe runs quoted resource strings through its own escape processing, so a +# backslash path such as D:\a\ShakeToFindCursor\app_icon.ico can come out +# mangled (\a) or rejected outright. Forward slashes are accepted by both +# rc.exe and windres, which is also what CMake itself writes into the .rc files +# it generates for the Visual Studio generators. +string(REPLACE "\\" "/" STFC_MANIFEST_FILE "${STFC_MANIFEST_FILE}") +string(REPLACE "\\" "/" STFC_ICON_FILE + "${CMAKE_CURRENT_SOURCE_DIR}/app_icon.ico") +set(STFC_MANIFEST_LINE + "1 24 \"${STFC_MANIFEST_FILE}\"") +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/res.rc.in" + "${CMAKE_CURRENT_BINARY_DIR}/res.rc" @ONLY) + +add_executable(${PROJECT_NAME} + WIN32 + ${STFC_SOURCES} + "${CMAKE_CURRENT_BINARY_DIR}/res.rc") + +target_include_directories(${PROJECT_NAME} PRIVATE src) + +# The five DLLs the app really imports. MSVC additionally picks ole32 up from +# the #pragma comment in src/auto_start.cpp, which is harmless. Notably absent +# is taskschd: the Task Scheduler API is used through COM interfaces obtained +# from CoCreateInstance, so no import library is required (and a toolchain +# without one, like the many MinGW builds, still links). +target_link_libraries(${PROJECT_NAME} PRIVATE + user32 gdi32 shell32 ole32 oleaut32 advapi32) + +if(MSVC) + target_compile_options(${PROJECT_NAME} PRIVATE + /W4 + /MP + /EHsc + /utf-8) + if(STFC_STRICT_WARNINGS) + target_compile_options(${PROJECT_NAME} PRIVATE /WX) + endif() + # The manifest is embedded by the resource compiler; keep the linker from + # generating (and then merging) a second one. + target_link_options(${PROJECT_NAME} PRIVATE "/MANIFEST:NO") +else() + target_compile_options(${PROJECT_NAME} PRIVATE + -Wall + -Wextra + -municode) + if(STFC_STRICT_WARNINGS) + target_compile_options(${PROJECT_NAME} PRIVATE -Werror) + endif() + # -municode picks the startup object that calls wWinMain instead of + # WinMain; the -static flags keep libgcc/libstdc++/libwinpthread out of the + # result so the MinGW build is a single file as well. + target_link_options(${PROJECT_NAME} PRIVATE + -municode -static -static-libgcc -static-libstdc++) +endif() + +message(STATUS "ShakeToFindCursor ${PROJECT_VERSION}: manifest " + "${STFC_MANIFEST_FILE}") diff --git a/app.manifest b/app.manifest new file mode 100644 index 0000000..002f459 --- /dev/null +++ b/app.manifest @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, system + true + + + diff --git a/app.requireAdministrator.manifest b/app.requireAdministrator.manifest new file mode 100644 index 0000000..b17405b --- /dev/null +++ b/app.requireAdministrator.manifest @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2, system + true + + + diff --git a/binaries/ShakeToFindCursor-amd64.exe b/binaries/ShakeToFindCursor-amd64.exe new file mode 100755 index 0000000..0d82e85 Binary files /dev/null and b/binaries/ShakeToFindCursor-amd64.exe differ diff --git a/binaries/ShakeToFindCursor-x86.exe b/binaries/ShakeToFindCursor-x86.exe new file mode 100755 index 0000000..73aaaea Binary files /dev/null and b/binaries/ShakeToFindCursor-x86.exe differ diff --git a/main.cpp b/main.cpp index 9f81c09..69eae2c 100644 --- a/main.cpp +++ b/main.cpp @@ -1,968 +1,839 @@ -#define _WIN32_WINNT 0x0601 -#define WIN32_LEAN_AND_MEAN -#define OEMRESOURCE - -// clang-format off -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "resource.h" -#include -#include -#pragma comment(lib, "taskschd.lib") -#pragma comment(lib, "comsupp.lib") - - - -// Configuration class to manage all configurable parameters -class CursorConfig { - public: - static constexpr double kScaleFactor = 3.0; // Cursor enlargement factor - static constexpr size_t kHistorySize = 10; // Keep last 10 movements - static constexpr int kMinDirectionChanges = 5; // Minimum direction changes required - static constexpr double kMinMovementSpeed = 800.0; // Minimum speed in pixels/second - static constexpr int kMaxTimeWindow = 500; // Time window in milliseconds - static constexpr int kEnlargeDurationMs = 800; // Cursor enlargement duration (milliseconds) - static constexpr int kGrowAnimationMs = 150; // Grow animation duration - static constexpr int kShrinkAnimationMs = 200; // Shrink animation duration - static constexpr UINT_PTR kTimerId = 1; // Timer ID - static constexpr UINT kTimerInterval = 16; // Timer interval for smooth animation (~60 FPS) - static constexpr UINT kTrayIconId = 1; // Tray icon ID - static constexpr UINT kTrayIconMessage = WM_APP + 1; // Tray message ID - static constexpr UINT kMenuExitId = 2000; // Exit menu item ID - static constexpr UINT kMenuAutoStartId = 2001; // Enable auto-start menu item ID - static constexpr UINT kMenuDisableAutoStartId = 2002; // Disable auto-start menu item ID - - enum class MouseTrackingMode { - kHook, // Use SetWindowsHookEx - kPolling // Use GetCursorPos in WM_TIMER - }; -}; - -// clang-format on - -class Logger { - public: - static Logger& GetInstance() { - static Logger instance; - return instance; - } - - void Log(const std::string& message) { - std::ofstream log_file("ShakeToFindCursor.log", std::ios_base::app); - if (log_file.is_open()) { - log_file << GetTimestamp() << " - " << message << std::endl; - } - } - - private: - Logger() = default; - Logger(const Logger&) = delete; - Logger& operator=(const Logger&) = delete; - - std::string GetTimestamp() { - auto now = std::chrono::system_clock::now(); - auto now_time_t = std::chrono::system_clock::to_time_t(now); - std::tm now_tm; - localtime_s(&now_tm, &now_time_t); - std::stringstream ss; - ss << std::put_time(&now_tm, "%Y-%m-%d %H:%M:%S"); - return ss.str(); - } -}; - -#ifdef _DEBUG -#define DEBUG_LOG(msg) Logger::GetInstance().Log(msg) -#else -#define DEBUG_LOG(msg) -#endif - -// COM initialization class -class ComInitializer { - public: - ComInitializer() { - if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) { - throw std::runtime_error("Failed to initialize COM"); - } - } - - ~ComInitializer() { CoUninitialize(); } -}; - -// Auto-start manager class to enable/disable auto-start -class AutoStartManager { - public: - static bool IsAutoStartEnabled() { - CComPtr task_service; - HRESULT hr = task_service.CoCreateInstance(CLSID_TaskScheduler, nullptr, - CLSCTX_INPROC_SERVER); - if (FAILED(hr)) return false; - - hr = task_service->Connect(_variant_t(), _variant_t(), _variant_t(), - _variant_t()); - if (FAILED(hr)) return false; - - CComPtr root_folder; - hr = task_service->GetFolder(_bstr_t(L"\\"), &root_folder); - if (FAILED(hr)) return false; - - CComPtr task; - hr = root_folder->GetTask(_bstr_t(L"ShakeToFindCursor"), &task); - - return SUCCEEDED(hr) && task != nullptr; - } - - static bool EnableAutoStart() { - WCHAR exe_path[MAX_PATH]; - if (!GetModuleFileNameW(nullptr, exe_path, MAX_PATH)) return false; - - CComPtr task_service; - HRESULT hr = task_service.CoCreateInstance(CLSID_TaskScheduler, nullptr, - CLSCTX_INPROC_SERVER); - if (FAILED(hr)) return false; - - hr = task_service->Connect(_variant_t(), _variant_t(), _variant_t(), - _variant_t()); - if (FAILED(hr)) return false; - - CComPtr root_folder; - hr = task_service->GetFolder(_bstr_t(L"\\"), &root_folder); - if (FAILED(hr)) return false; - - // Delete existing task if present - root_folder->DeleteTask(_bstr_t(L"ShakeToFindCursor"), 0); - - CComPtr task; - hr = task_service->NewTask(0, &task); - if (FAILED(hr)) return false; - - // Set general info - CComPtr reg_info; - hr = task->get_RegistrationInfo(®_info); - if (SUCCEEDED(hr)) { - reg_info->put_Author(_bstr_t(L"ShakeToFindCursor")); - reg_info->put_Description( - _bstr_t(L"Auto-start ShakeToFindCursor with elevated privileges")); - } - - // Set principal (run with highest privileges) - CComPtr principal; - hr = task->get_Principal(&principal); - if (SUCCEEDED(hr)) { - principal->put_RunLevel(TASK_RUNLEVEL_HIGHEST); - principal->put_LogonType(TASK_LOGON_INTERACTIVE_TOKEN); - } - - // Configure settings - CComPtr settings; - hr = task->get_Settings(&settings); - if (SUCCEEDED(hr)) { - settings->put_StartWhenAvailable(VARIANT_TRUE); - settings->put_DisallowStartIfOnBatteries(VARIANT_FALSE); - settings->put_StopIfGoingOnBatteries(VARIANT_FALSE); - settings->put_ExecutionTimeLimit(_bstr_t(L"PT0S")); // No time limit - settings->put_Hidden(VARIANT_FALSE); - settings->put_Priority(5); // Above normal priority - settings->put_RunOnlyIfNetworkAvailable(VARIANT_FALSE); - settings->put_WakeToRun(VARIANT_TRUE); - settings->put_AllowHardTerminate(VARIANT_TRUE); - settings->put_Enabled(VARIANT_TRUE); - } - - // Create triggers - CComPtr trigger_collection; - hr = task->get_Triggers(&trigger_collection); - if (SUCCEEDED(hr)) { - // Add logon trigger - CComPtr logon_trigger; - if (SUCCEEDED( - trigger_collection->Create(TASK_TRIGGER_LOGON, &logon_trigger))) { - CComQIPtr logon(logon_trigger); - if (logon) { - logon->put_Id(_bstr_t(L"LogonTriggerId")); - logon->put_Enabled(VARIANT_TRUE); - // Add a small delay to ensure shell is ready - logon->put_Delay(_bstr_t(L"PT10S")); - } - } - - // Add boot trigger - CComPtr boot_trigger; - if (SUCCEEDED( - trigger_collection->Create(TASK_TRIGGER_BOOT, &boot_trigger))) { - CComQIPtr boot(boot_trigger); - if (boot) { - boot->put_Id(_bstr_t(L"BootTriggerId")); - boot->put_Enabled(VARIANT_TRUE); - // Add a delay after boot - boot->put_Delay(_bstr_t(L"PT60S")); - } - } - } - - // Create action - CComPtr action_collection; - hr = task->get_Actions(&action_collection); - if (SUCCEEDED(hr)) { - CComPtr action; - hr = action_collection->Create(TASK_ACTION_EXEC, &action); - if (SUCCEEDED(hr)) { - CComQIPtr exec_action(action); - if (exec_action) { - exec_action->put_Path(_bstr_t(exe_path)); - // Set working directory - WCHAR work_dir[MAX_PATH]; - wcscpy_s(work_dir, exe_path); - PathRemoveFileSpecW(work_dir); - exec_action->put_WorkingDirectory(_bstr_t(work_dir)); - } - } - } - - // Register the task - use current user's credentials - CComPtr registered_task; - hr = root_folder->RegisterTaskDefinition( - _bstr_t(L"ShakeToFindCursor"), task, TASK_CREATE_OR_UPDATE, - _variant_t(), // Default credentials (current user) - _variant_t(), // Default password - TASK_LOGON_INTERACTIVE_TOKEN, // Run only when user is logged on - _variant_t(L""), // No sddl - ®istered_task); - - return SUCCEEDED(hr); - } - - static bool DisableAutoStart() { - CComPtr task_service; - HRESULT hr = task_service.CoCreateInstance(CLSID_TaskScheduler, nullptr, - CLSCTX_INPROC_SERVER); - if (FAILED(hr)) return false; - - hr = task_service->Connect(_variant_t(), _variant_t(), _variant_t(), - _variant_t()); - if (FAILED(hr)) return false; - - CComPtr root_folder; - hr = task_service->GetFolder(_bstr_t(L"\\"), &root_folder); - if (FAILED(hr)) return false; - - hr = root_folder->DeleteTask(_bstr_t(L"ShakeToFindCursor"), 0); - return SUCCEEDED(hr); - } -}; - -// Cursor utilities class -class CursorUtils { - public: - static HCURSOR ScaleCursor(HCURSOR src_cursor, double scale_factor) { - if (!src_cursor || scale_factor <= 0) { - return nullptr; - } - - ICONINFO icon_info; - if (!GetIconInfo(src_cursor, &icon_info)) { - return nullptr; - } - - // RAII cleanup for bitmap resources returned by GetIconInfo - std::unique_ptr::type, decltype(&DeleteObject)> - color_bitmap(icon_info.hbmColor, DeleteObject); - std::unique_ptr::type, decltype(&DeleteObject)> - mask_bitmap(icon_info.hbmMask, DeleteObject); - - // Get bitmap dimensions (use color bitmap if available, otherwise mask) - BITMAP bm; - if (!GetObject(icon_info.hbmColor ? icon_info.hbmColor : icon_info.hbmMask, - sizeof(BITMAP), &bm)) { - return nullptr; - } - - // For monochrome cursors (hbmColor == NULL), hbmMask height is 2x the - // actual cursor height (AND mask + XOR mask stacked vertically). - int cursor_height = icon_info.hbmColor ? bm.bmHeight : bm.bmHeight / 2; - - int new_width = static_cast(bm.bmWidth * scale_factor); - int new_height = static_cast(cursor_height * scale_factor); - if (new_width <= 0 || new_height <= 0) return nullptr; - - // Use CopyImage for scaling. Windows handles the alpha channel and mask - // bitmap correctly, producing smooth anti-aliased edges when scaling. - // CopyImage with IMAGE_CURSOR creates a new cursor scaled to the requested size. - HCURSOR scaled = (HCURSOR)CopyImage(src_cursor, IMAGE_CURSOR, new_width, - new_height, 0); - - return scaled; - } -}; - -HCURSOR GetSystemArrowCursor() { - CURSORINFO ci = {sizeof(CURSORINFO)}; - if (GetCursorInfo(&ci)) { - return CopyCursor(ci.hCursor); - } - return nullptr; -} - -// Large cursor class -class LargeCursor { - public: - LargeCursor(LPCWSTR cursor_name, DWORD system_cursor_id) - : system_cursor_id_(system_cursor_id) { - original_cursor_ = CopyCursor(LoadCursorW(nullptr, cursor_name)); - if (!original_cursor_) { - throw std::runtime_error("Failed to load system cursor"); - } - } - - void ApplyScale(double scale_factor) { - if (scale_factor <= 1.0001) { - Restore(); - return; - } - - HCURSOR scaled = CursorUtils::ScaleCursor(original_cursor_, scale_factor); - if (scaled && scaled != original_cursor_) { - // CopyCursor creates an independent copy that SetSystemCursor can own. - HCURSOR cursor_copy = CopyCursor(scaled); - DestroyCursor(scaled); - if (cursor_copy) { - SetSystemCursor(cursor_copy, system_cursor_id_); - current_scale_ = scale_factor; - } - } - } - - void Restore() { - if (original_cursor_) { - HCURSOR cursor_copy = CopyCursor(original_cursor_); - if (cursor_copy) { - SetSystemCursor(cursor_copy, system_cursor_id_); - current_scale_ = 1.0; - } else { - DestroyCursor(cursor_copy); - } - } - } - - ~LargeCursor() { - if (original_cursor_) { - DestroyCursor(original_cursor_); - } - } - - private: - DWORD system_cursor_id_; - HCURSOR original_cursor_ = nullptr; - double current_scale_ = 1.0; -}; - -// Large cursor manager class -class LargeCursorManager { - public: - LargeCursorManager() { - large_cursors_.push_back( - std::make_unique(IDC_ARROW, OCR_NORMAL)); - large_cursors_.push_back( - std::make_unique(IDC_IBEAM, OCR_IBEAM)); - large_cursors_.push_back(std::make_unique(IDC_WAIT, OCR_WAIT)); - large_cursors_.push_back( - std::make_unique(IDC_CROSS, OCR_CROSS)); - large_cursors_.push_back( - std::make_unique(IDC_UPARROW, OCR_UP)); - large_cursors_.push_back( - std::make_unique(IDC_SIZENWSE, OCR_SIZENWSE)); - large_cursors_.push_back( - std::make_unique(IDC_SIZENESW, OCR_SIZENESW)); - large_cursors_.push_back( - std::make_unique(IDC_SIZEWE, OCR_SIZEWE)); - large_cursors_.push_back( - std::make_unique(IDC_SIZENS, OCR_SIZENS)); - large_cursors_.push_back( - std::make_unique(IDC_SIZEALL, OCR_SIZEALL)); - large_cursors_.push_back(std::make_unique(IDC_NO, OCR_NO)); - large_cursors_.push_back(std::make_unique(IDC_HAND, OCR_HAND)); - large_cursors_.push_back( - std::make_unique(IDC_APPSTARTING, OCR_APPSTARTING)); - } - - void ApplyScale(double scale_factor) { - for (const auto& cursor : large_cursors_) { - cursor->ApplyScale(scale_factor); - } - } - - void RestoreAll() { - for (const auto& cursor : large_cursors_) { - cursor->Restore(); - } - } - - private: - std::vector> large_cursors_; -}; -class CursorState { - public: - CursorState() {} - - ~CursorState() { - DEBUG_LOG("CursorState destroyed"); - if (SystemParametersInfo(SPI_SETCURSORS, 0, nullptr, SPIF_SENDCHANGE)) { - state_ = kIdle; - } - } - - void Enlarge() { - if (state_ == kIdle) { - state_ = kGrowing; - enlarge_start_time_ = std::chrono::high_resolution_clock::now(); - } else if (state_ == kShrinking) { - // Re-trigger from shrink: jump back to full size and hold - ApplyScale(CursorConfig::kScaleFactor); - state_ = kHolding; - enlarge_start_time_ = std::chrono::high_resolution_clock::now(); - last_apply_time_ = std::chrono::high_resolution_clock::now(); - } else if (state_ == kHolding) { - // Re-trigger during hold: extend the hold duration - enlarge_start_time_ = std::chrono::high_resolution_clock::now(); - } - } - - void RestoreIfNeeded() { - if (state_ == kIdle) return; - - auto now = std::chrono::high_resolution_clock::now(); - auto elapsed = std::chrono::duration_cast( - now - enlarge_start_time_) - .count(); - - // Frame throttle: limit cursor updates to ~30 FPS to reduce flicker - auto since_last_apply = - std::chrono::duration_cast( - now - last_apply_time_) - .count(); - bool should_apply = (since_last_apply >= 33); - - double current_scale = 1.0; - - switch (state_) { - case kGrowing: { - if (elapsed >= CursorConfig::kGrowAnimationMs) { - current_scale = CursorConfig::kScaleFactor; - state_ = kHolding; - hold_start_time_ = now; - ApplyScale(current_scale); - last_apply_time_ = now; - } else if (should_apply) { - double t = static_cast(elapsed) / - CursorConfig::kGrowAnimationMs; - // Ease-out cubic for smooth deceleration - double eased = 1.0 - std::pow(1.0 - t, 3.0); - current_scale = 1.0 + (CursorConfig::kScaleFactor - 1.0) * eased; - ApplyScale(current_scale); - last_apply_time_ = now; - } - break; - } - case kHolding: { - if (elapsed >= CursorConfig::kEnlargeDurationMs) { - state_ = kShrinking; - shrink_start_time_ = now; - } - break; - } - case kShrinking: { - auto shrink_elapsed = - std::chrono::duration_cast( - now - shrink_start_time_) - .count(); - if (shrink_elapsed >= CursorConfig::kShrinkAnimationMs) { - RestoreOriginalCursor(); - state_ = kIdle; - } else if (should_apply) { - double t = static_cast(shrink_elapsed) / - CursorConfig::kShrinkAnimationMs; - // Ease-in cubic for smooth acceleration - double eased = t * t * t; - current_scale = - CursorConfig::kScaleFactor - - (CursorConfig::kScaleFactor - 1.0) * eased; - ApplyScale(current_scale); - last_apply_time_ = now; - } - break; - } - default: - break; - } - } - private: - void ApplyScale(double scale) { - large_cursor_manager_.ApplyScale(scale); - } - - void RestoreOriginalCursor() { - large_cursor_manager_.RestoreAll(); - } - - enum AnimationState { - kIdle, - kGrowing, - kHolding, - kShrinking - }; - - AnimationState state_ = kIdle; - LargeCursorManager large_cursor_manager_; - std::chrono::high_resolution_clock::time_point enlarge_start_time_; - std::chrono::high_resolution_clock::time_point hold_start_time_; - std::chrono::high_resolution_clock::time_point shrink_start_time_; - std::chrono::high_resolution_clock::time_point last_apply_time_; -}; - -// Mouse movement detector class with shake pattern recognition -class MouseMoveDetector { - public: - MouseMoveDetector() { - GetCursorPos(&last_pos_); - last_time_ = std::chrono::high_resolution_clock::now(); - } - - bool ShouldEnlargeCursor(const POINT& current_pos) { - auto now = std::chrono::high_resolution_clock::now(); - auto delta_time = - std::chrono::duration_cast(now - last_time_) - .count(); - - if (delta_time <= 0) return false; - - // Calculate movement vector - int dx = current_pos.x - last_pos_.x; - int dy = current_pos.y - last_pos_.y; - - // Update position history - movement_history_.push_back({dx, dy, delta_time}); - if (movement_history_.size() > CursorConfig::kHistorySize) { - movement_history_.pop_front(); - } - - last_pos_ = current_pos; - last_time_ = now; - - return DetectShakePattern(); - } - - private: - struct Movement { - int dx; - int dy; - long long dt; - }; - - bool DetectShakePattern() { - if (movement_history_.size() < CursorConfig::kHistorySize) return false; - - int direction_changes = 0; - double total_speed = 0.0; - long long total_time = 0; - - // Previous movement direction (-1: negative, 1: positive, 0: neutral) - int last_x_dir = 0; - int last_y_dir = 0; - - for (const auto& mov : movement_history_) { - // Calculate current direction - int curr_x_dir = (mov.dx > 0) ? 1 : (mov.dx < 0) ? -1 : 0; - int curr_y_dir = (mov.dy > 0) ? 1 : (mov.dy < 0) ? -1 : 0; - - // Count direction changes - if (last_x_dir != 0 && curr_x_dir != 0 && last_x_dir != curr_x_dir) { - direction_changes++; - } - if (last_y_dir != 0 && curr_y_dir != 0 && last_y_dir != curr_y_dir) { - direction_changes++; - } - - // Update last direction - last_x_dir = curr_x_dir; - last_y_dir = curr_y_dir; - - // Calculate speed - double distance = std::sqrt(mov.dx * mov.dx + mov.dy * mov.dy); - double speed = (mov.dt > 0) ? (distance / mov.dt) * 1000.0 : 0; - total_speed += speed; - total_time += mov.dt; - } - - // Check if we're within the time window - if (total_time > CursorConfig::kMaxTimeWindow) return false; - - // Calculate average speed - double avg_speed = total_speed / movement_history_.size(); - - // Return true if we have enough direction changes and sufficient speed - return direction_changes >= CursorConfig::kMinDirectionChanges && - avg_speed >= CursorConfig::kMinMovementSpeed; - } - - POINT last_pos_; - std::chrono::high_resolution_clock::time_point last_time_; - std::deque movement_history_; -}; - -class ShakeToFindCursor { - public: - static ShakeToFindCursor& GetInstance() { - static ShakeToFindCursor instance; - return instance; - } - - bool Initialize(CursorConfig::MouseTrackingMode mode) { - if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) { - throw std::runtime_error("Failed to initialize COM"); - } - tracking_mode_ = mode; - - // Register window class - WNDCLASSEXW wc = {0}; - wc.cbSize = sizeof(WNDCLASSEX); - wc.lpfnWndProc = WindowProc; - wc.hInstance = GetModuleHandle(nullptr); - wc.hIcon = LoadIcon(wc.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); - wc.lpszClassName = L"ShakeToFindCursorClass"; - - if (!RegisterClassExW(&wc)) { - throw std::runtime_error("Failed to register window class"); - } - - // Create hidden window - hwnd_ = CreateWindowW(L"ShakeToFindCursorClass", L"ShakeToFindCursor", - WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, - nullptr, nullptr, GetModuleHandle(nullptr), nullptr); - - if (!hwnd_) { - throw std::runtime_error("Failed to create window"); - } - - // Set window instance pointer - SetWindowLongPtr(hwnd_, GWLP_USERDATA, reinterpret_cast(this)); - - // Create timer with different interval based on mode - UINT timer_interval = - (tracking_mode_ == CursorConfig::MouseTrackingMode::kPolling) - ? 10 // Poll more frequently when using timer - : CursorConfig::kTimerInterval; - - if (!SetTimer(hwnd_, CursorConfig::kTimerId, timer_interval, nullptr)) { - DestroyWindow(hwnd_); - throw std::runtime_error("Failed to create timer"); - } - - // Only install hook if using hook mode - if (tracking_mode_ == CursorConfig::MouseTrackingMode::kHook) { - mouse_hook_ = - SetWindowsHookEx(WH_MOUSE_LL, MouseProc, GetModuleHandle(nullptr), 0); - - if (!mouse_hook_) { - KillTimer(hwnd_, CursorConfig::kTimerId); - DestroyWindow(hwnd_); - throw std::runtime_error("Failed to install mouse hook"); - } - } - - // Set Ctrl+C handler - SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); - - // Create tray icon - NOTIFYICONDATAW nid = {sizeof(NOTIFYICONDATAW)}; - nid.hWnd = hwnd_; - nid.uID = CursorConfig::kTrayIconId; - nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; - nid.uCallbackMessage = CursorConfig::kTrayIconMessage; - nid.hIcon = - LoadIcon(GetModuleHandle(nullptr), MAKEINTRESOURCE(IDI_APP_ICON)); - wcscpy_s(nid.szTip, L"Shake to Find Cursor"); - - if (!Shell_NotifyIconW(NIM_ADD, &nid)) { - KillTimer(hwnd_, CursorConfig::kTimerId); - DestroyWindow(hwnd_); - throw std::runtime_error("Failed to create tray icon"); - } - - tray_icon_added_ = true; - - return true; - } - - void Run() { - MSG msg; - running_ = true; - - while (running_) { - // Use PeekMessage instead of GetMessage to handle timers even when there - // are no messages - while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { - if (msg.message == WM_QUIT) { - running_ = false; - break; - } - TranslateMessage(&msg); - DispatchMessage(&msg); - } - - // Yield CPU time slice - Sleep(1); - } - } - - void Stop() { - running_ = false; - if (hwnd_) { - PostMessage(hwnd_, WM_QUIT, 0, 0); - } - } - - ~ShakeToFindCursor() { - RemoveTrayIcon(); - if (mouse_hook_) { - UnhookWindowsHookEx(mouse_hook_); - } - if (hwnd_) { - KillTimer(hwnd_, CursorConfig::kTimerId); - DestroyWindow(hwnd_); - } - SetConsoleCtrlHandler(ConsoleCtrlHandler, FALSE); - CoUninitialize(); - } - - void ProcessMouseMove(const MSLLHOOKSTRUCT* mouse_info) { - if (move_detector_.ShouldEnlargeCursor(mouse_info->pt)) { - cursor_state_.Enlarge(); - } - } - - private: - ShakeToFindCursor() = default; - ShakeToFindCursor(const ShakeToFindCursor&) = delete; - ShakeToFindCursor& operator=(const ShakeToFindCursor&) = delete; - - static LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) { - if (nCode == HC_ACTION && wParam == WM_MOUSEMOVE) { - auto& instance = GetInstance(); - instance.ProcessMouseMove(reinterpret_cast(lParam)); - } - return CallNextHookEx(nullptr, nCode, wParam, lParam); - } - - static LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, - LPARAM lParam) { - auto* instance = reinterpret_cast( - GetWindowLongPtr(hwnd, GWLP_USERDATA)); - - switch (msg) { - case WM_TIMER: - if (wParam == CursorConfig::kTimerId && instance) { - if (instance->tracking_mode_ == - CursorConfig::MouseTrackingMode::kPolling) { - POINT pt; - GetCursorPos(&pt); - instance->ProcessMouseMove(reinterpret_cast(&pt)); - } - instance->cursor_state_.RestoreIfNeeded(); - } - return 0; - - case WM_DESTROY: - PostQuitMessage(0); - return 0; - - case CursorConfig::kTrayIconMessage: - if (LOWORD(lParam) == WM_RBUTTONUP) { - instance->ShowContextMenu(hwnd); - } - return 0; - - case WM_COMMAND: - if (LOWORD(wParam) == CursorConfig::kMenuExitId) { - instance->Stop(); - } else if (LOWORD(wParam) == CursorConfig::kMenuAutoStartId) { - if (AutoStartManager::EnableAutoStart()) { - MessageBoxW(hwnd, L"Auto-start enabled successfully.", L"Success", - MB_OK | MB_ICONINFORMATION); - } else { - MessageBoxW(hwnd, L"Failed to enable auto-start.", L"Error", - MB_OK | MB_ICONERROR); - } - } else if (LOWORD(wParam) == CursorConfig::kMenuDisableAutoStartId) { - if (AutoStartManager::DisableAutoStart()) { - MessageBoxW(hwnd, L"Auto-start disabled successfully.", L"Success", - MB_OK | MB_ICONINFORMATION); - } else { - MessageBoxW(hwnd, L"Failed to disable auto-start.", L"Error", - MB_OK | MB_ICONERROR); - } - } - return 0; - } - - return DefWindowProc(hwnd, msg, wParam, lParam); - } - - static BOOL WINAPI ConsoleCtrlHandler(DWORD ctrlType) { - if (ctrlType == CTRL_C_EVENT || ctrlType == CTRL_BREAK_EVENT) { - GetInstance().Stop(); - return TRUE; - } - return FALSE; - } - - void RemoveTrayIcon() { - if (tray_icon_added_ && hwnd_) { - NOTIFYICONDATA nid = {sizeof(NOTIFYICONDATA)}; - nid.hWnd = hwnd_; - nid.uID = CursorConfig::kTrayIconId; - Shell_NotifyIcon(NIM_DELETE, &nid); - tray_icon_added_ = false; - } - } - - void ShowContextMenu(HWND hwnd) { - POINT pt; - GetCursorPos(&pt); - - HMENU menu = CreatePopupMenu(); - if (!menu) return; - - bool is_auto_start = AutoStartManager::IsAutoStartEnabled(); - if (is_auto_start) { - AppendMenuW(menu, MF_STRING, CursorConfig::kMenuDisableAutoStartId, - L"Disable Auto-start"); - } else { - AppendMenuW(menu, MF_STRING, CursorConfig::kMenuAutoStartId, - L"Enable Auto-start"); - } - AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); - AppendMenuW(menu, MF_STRING, CursorConfig::kMenuExitId, L"Exit"); - - SetForegroundWindow(hwnd); - TrackPopupMenu(menu, TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, nullptr); - DestroyMenu(menu); - } - - HHOOK mouse_hook_ = nullptr; - HWND hwnd_ = nullptr; - CursorState cursor_state_; - MouseMoveDetector move_detector_; - std::atomic running_{false}; - bool tray_icon_added_ = false; - CursorConfig::MouseTrackingMode tracking_mode_; -}; - -bool IsRunAsAdmin() { - BOOL is_admin = FALSE; - PSID admin_group = nullptr; - SID_IDENTIFIER_AUTHORITY nt_authority = SECURITY_NT_AUTHORITY; - - if (AllocateAndInitializeSid(&nt_authority, 2, SECURITY_BUILTIN_DOMAIN_RID, - DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, - &admin_group)) { - if (!CheckTokenMembership(nullptr, admin_group, &is_admin)) { - is_admin = FALSE; - } - FreeSid(admin_group); - } - return is_admin != FALSE; -} - -#ifdef CONSOLE_MODE -int main(int argc, char* argv[]) { - if (!IsRunAsAdmin()) { - std::cerr << "This program requires administrator privileges to run." - << std::endl; - return 1; - } - - ComInitializer com_initializer; - - SetProcessDPIAware(); - - CursorConfig::MouseTrackingMode mode = - CursorConfig::MouseTrackingMode::kPolling; - if (argc > 1 && std::string(argv[1]) == "--hook") { - mode = CursorConfig::MouseTrackingMode::kHook; - } - - try { - auto& cursor_finder = ShakeToFindCursor::GetInstance(); - if (!cursor_finder.Initialize(mode)) { - return 1; - } - - std::cout << "Shake to Find Cursor demo started. Move the mouse quickly to " - "trigger zoom." - << std::endl; - std::cout << "Press Ctrl + C to exit." << std::endl; - - cursor_finder.Run(); - } catch (const std::exception& e) { - std::cerr << "Error: " << e.what() << std::endl; - SystemParametersInfo(SPI_SETCURSORS, 0, nullptr, SPIF_SENDCHANGE); - return 1; - } - return 0; -} -#else -int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, - LPWSTR lpCmdLine, int nCmdShow) { - UNREFERENCED_PARAMETER(hInstance); - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - UNREFERENCED_PARAMETER(nCmdShow); - - if (!IsRunAsAdmin()) { - MessageBoxW(nullptr, - L"This program requires administrator privileges to run.", - L"Error", MB_OK | MB_ICONERROR); - return 1; - } - - ComInitializer com_initializer; - - SetProcessDPIAware(); - - CursorConfig::MouseTrackingMode mode = - CursorConfig::MouseTrackingMode::kPolling; - if (wcsstr(lpCmdLine, L"--hook")) { - mode = CursorConfig::MouseTrackingMode::kHook; - } - - try { - auto& cursor_finder = ShakeToFindCursor::GetInstance(); - if (!cursor_finder.Initialize(mode)) { - return 1; - } - - DEBUG_LOG( - "Shake to Find Cursor started. Move the mouse quickly to trigger " - "zoom."); - - cursor_finder.Run(); - } catch (const std::exception& e) { - std::wstringstream ws; - ws << L"Error: " << e.what(); - MessageBoxW(nullptr, ws.str().c_str(), L"Error", MB_OK | MB_ICONERROR); - DEBUG_LOG("Error: " + std::string(e.what())); - SystemParametersInfo(SPI_SETCURSORS, 0, nullptr, SPIF_SENDCHANGE); - return 1; - } - return 0; -} -#endif +// Shake to Find Cursor - a Windows utility that makes the pointer easy to +// locate. Shake the mouse and the pointer grows (needs admin) and a +// click-through highlight is drawn around it (always, no privileges needed). +// +// Layout: +// src/shake_detector.h input-rate independent shake recognition (unit tested) +// src/pointer_zoomer.* SetSystemCursor based pointer enlargement +// src/find_overlay.* ripple / spotlight highlight on its own thread +// src/auto_start.* scheduled task when elevated, HKCU Run key otherwise +// src/app_settings.* registry backed settings plus the optional debug log +// +// One threading rule drives most of this file: the low-level mouse hook runs on +// this thread, and every microsecond spent inside it is latency for mouse input +// in *every other application on the desktop*. So the hook only feeds numbers +// to the detector. When a shake is recognised it posts a message, and the +// expensive part (rewriting the whole cursor scheme, painting the overlay) +// happens in the window procedure below. + +#include "targetver.h" + +#include + +#include + +#include "app_settings.h" +#include "auto_start.h" +#include "find_overlay.h" +#include "pointer_zoomer.h" +#include "resource.h" +#include "shake_detector.h" +#include "win_util.h" + +namespace stfc { +namespace { + +enum class StartupMode { kUseSettings, kForceHook, kForcePolling }; + +constexpr UINT kMsgTray = WM_APP + 1; +constexpr UINT kMsgTrigger = WM_APP + 2; + +constexpr UINT_PTR kAnimTimerId = 1; +constexpr UINT_PTR kTrayRetryTimerId = 2; +constexpr UINT kFastTickMs = 8; // animation frames +constexpr UINT kHoldTickMs = 100; // only waiting the hold out +constexpr UINT kPollTickMs = 8; // polling mode also drives detection + +constexpr UINT kTrayIconId = 1; +constexpr UINT kHotkeyId = 0x5CF1; +constexpr UINT kHotkeyModifiers = MOD_CONTROL | MOD_ALT; +constexpr UINT kHotkeyVirtualKey = 'F'; + +constexpr wchar_t kWindowClass[] = L"ShakeToFindCursor.Window"; +constexpr wchar_t kWindowTitle[] = L"Shake to Find Cursor"; +constexpr wchar_t kSingleInstanceMutex[] = + L"Local\\ShakeToFindCursor.SingleInstance"; + +enum MenuCommand : WORD { + kCmdFind = 1, + kCmdPaused = 2, + kCmdSensGentle = 10, + kCmdSensStandard = 11, + kCmdSensSharp = 12, + kCmdScale2 = 20, + kCmdScale3 = 21, + kCmdScale4 = 22, + kCmdScale5 = 23, + kCmdHoldShort = 30, + kCmdHoldNormal = 31, + kCmdHoldLong = 32, + kCmdOverlayNone = 40, + kCmdOverlayRipple = 41, + kCmdOverlaySpotlight = 42, + kCmdEnlarge = 50, + kCmdAutostart = 51, + kCmdUseHook = 52, + kCmdIgnoreFullscreen = 53, + kCmdHotkey = 54, + kCmdLogging = 55, + kCmdElevate = 60, + kCmdExit = 99, +}; + +int SensitivityForCommand(MenuCommand command) { + switch (command) { + case kCmdSensGentle: + return 20; + case kCmdSensSharp: + return 85; + default: + return ShakeTuning::kDefaultSensitivity; + } +} + +int ScaleForCommand(MenuCommand command) { + switch (command) { + case kCmdScale2: + return 200; + case kCmdScale4: + return 400; + case kCmdScale5: + return 500; + default: + return 300; + } +} + +int HoldForCommand(MenuCommand command) { + switch (command) { + case kCmdHoldShort: + return 400; + case kCmdHoldLong: + return 1800; + default: + return 900; + } +} + +OverlayStyle OverlayForCommand(MenuCommand command) { + switch (command) { + case kCmdOverlayNone: + return OverlayStyle::kNone; + case kCmdOverlaySpotlight: + return OverlayStyle::kSpotlight; + default: + return OverlayStyle::kRipple; + } +} + +LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM w_param, + LPARAM l_param); +LRESULT CALLBACK MouseHookProc(int code, WPARAM w_param, LPARAM l_param); + +// Held for the lifetime of the process: closing it would let a second copy in. +HANDLE g_singleton = nullptr; + +// Explorer broadcasts this when (re)creating the taskbar toolbar; the id is +// assigned by the system, so it has to be registered rather than defined. +UINT TaskbarCreatedMessage() { + static const UINT message = RegisterWindowMessageW(L"TaskbarCreated"); + return message; +} + +// --------------------------------------------------------------------------- +// App +// --------------------------------------------------------------------------- +// All members are public on purpose: the window procedure and the mouse hook +// are plain callbacks in this file and both drive the object directly. +class App { + public: + static App& Get() { + static App instance; + return instance; + } + + bool Initialize(StartupMode mode) { + AppSettings& settings = AppSettings::Get(); + // A previous instance may have died while the pointers were enlarged. + PointerZoomer::HealIfNeeded(); + detector_.SetTuning(settings.DetectorTuning()); + + WNDCLASSEXW wc = {}; + wc.cbSize = sizeof(wc); + wc.lpfnWndProc = &WindowProc; + wc.hInstance = GetModuleHandleW(nullptr); + wc.hIcon = LoadIconW(wc.hInstance, MAKEINTRESOURCEW(IDI_APP_ICON)); + wc.lpszClassName = kWindowClass; + if (!RegisterClassExW(&wc)) { + LogCritical("RegisterClassExW failed (%lu)", GetLastError()); + return false; + } + + // A 0x0 unshown top-level window rather than a message-only one: the tray + // menu needs a window it can hand activation semantics to, and only + // top-level windows are told about logoff and shutdown (which is how the + // pointer scheme gets restored before the session goes away). + hwnd_ = CreateWindowExW(WS_EX_TOOLWINDOW, kWindowClass, kWindowTitle, + WS_POPUP, -32000, -32000, 0, 0, nullptr, nullptr, + wc.hInstance, nullptr); + if (!hwnd_) { + LogCritical("CreateWindowExW failed (%lu)", GetLastError()); + return false; + } + + // A command line switch only overrides this session; it must not overwrite + // what the user chose in the tray menu. + use_hook_ = mode == StartupMode::kUseSettings + ? settings.tracking == TrackingMode::kHook + : mode == StartupMode::kForceHook; + + const bool zoomer_ready = zoomer_.Initialize(); + if (!use_hook_ || !InstallHook()) use_hook_ = false; + RescheduleTimer(); + + if (settings.hotkey && !RegisterHotKey(hwnd_, kHotkeyId, kHotkeyModifiers, + kHotkeyVirtualKey)) { + Logf("hotkey Ctrl+Alt+F is taken by another app (%lu)", GetLastError()); + } + + if (!AddTrayIcon()) { + // At logon the tray can still be starting up; retry until it appears. + SetTimer(hwnd_, kTrayRetryTimerId, 2000, nullptr); + } else { + AnnounceOnce(); + } + Logf("started: hook=%d zoomer=%d overlay=%d sensitivity=%d", + use_hook_ ? 1 : 0, zoomer_ready ? 1 : 0, + static_cast(settings.overlay), settings.sensitivity); + return true; + } + + int Run() { + MSG msg = {}; + while (GetMessageW(&msg, nullptr, 0, 0) > 0) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + return static_cast(msg.wParam); + } + + void Shutdown() { + if (shut_down_) return; + shut_down_ = true; + UninstallHook(); + overlay_.Hide(); + zoomer_.RestoreNow(); + overlay_.Shutdown(); + RemoveTrayIcon(); + if (hwnd_) { + const AppSettings& settings = AppSettings::Get(); + if (settings.hotkey) UnregisterHotKey(hwnd_, kHotkeyId); + KillTimer(hwnd_, kAnimTimerId); + KillTimer(hwnd_, kTrayRetryTimerId); + DestroyWindow(hwnd_); + hwnd_ = nullptr; + } + } + + // --- message handling --------------------------------------------------- + + void OnTimer(UINT_PTR id) { + if (id == kTrayRetryTimerId) { + if (AddTrayIcon()) { + KillTimer(hwnd_, kTrayRetryTimerId); + AnnounceOnce(); + } + return; + } + if (id != kAnimTimerId) return; + + const AppSettings& settings = AppSettings::Get(); + if (!use_hook_ && !paused_) { + POINT point = {}; + if (GetCursorPos(&point)) FeedSample(point, settings); + } + if (zoomer_.Active()) { + zoomer_.Tick(NowUs()); + RescheduleTimer(); + } + // If a message could not be queued (a saturated queue) the trigger is + // still honoured on the next tick. + if (pending_trigger_) OnTrigger(); + } + + void OnTrayNotification(LPARAM l_param) { + switch (LOWORD(l_param)) { + case WM_RBUTTONUP: + case WM_LBUTTONUP: + ShowMenu(); + break; + case WM_LBUTTONDBLCLK: + TriggerNow(); + break; + default: + break; + } + } + + void OnSettingChange() { + // The user picked a new pointer scheme, theme or DPI while we were running. + zoomer_.RefreshScheme(); + } + + // Explorer owns the notification area, so restarting it takes the icon away. + // Without this the settings menu becomes unreachable until the app restarts. + void OnTaskbarCreated() { + tray_icon_added_ = false; + if (AddTrayIcon()) Logf("tray icon re-added after an explorer restart"); + } + + void FeedSample(POINT point, const AppSettings& settings) { + if (paused_) return; + if (!EffectsEnabled(settings)) return; + PointerSample sample; + sample.time_us = NowUs(); + sample.x = point.x; + sample.y = point.y; + if (!detector_.AddSample(sample)) return; + QueueTrigger(); + } + + // The trigger is queued so the work happens on the message-loop side. If the + // queue is saturated (it takes ~10k pending messages) the flag is still set, + // so arm a tick to make sure it is picked up. + void QueueTrigger() { + pending_trigger_ = true; + if (hwnd_ && !PostMessageW(hwnd_, kMsgTrigger, 0, 0)) { + SetTimer(hwnd_, kAnimTimerId, kFastTickMs, nullptr); + timer_active_ = true; + timer_interval_ = kFastTickMs; + } + } + + // Nothing to detect if every effect is switched off, so do not sample at all. + static bool EffectsEnabled(const AppSettings& settings) { + return settings.overlay != OverlayStyle::kNone || settings.enlarge_pointer; + } + + void OnTrigger() { + pending_trigger_ = false; + if (hwnd_) { + // Any tick armed by QueueTrigger is not needed once we are here; the + // real reschedule below sets the interval the animation actually wants. + KillTimer(hwnd_, kAnimTimerId); + timer_active_ = false; + } + if (paused_) return; + AppSettings& settings = AppSettings::Get(); + if (settings.ignore_fullscreen && IsForegroundFullscreen()) { + Logf("shake ignored: full screen window in front"); + return; + } + POINT point = {}; + if (!GetCursorPos(&point)) return; + if (settings.enlarge_pointer && zoomer_.available()) zoomer_.Trigger(); + if (settings.overlay != OverlayStyle::kNone) { + overlay_.Show(point, settings.overlay, settings.OverlayDurationMs()); + } + const ShakeStats& stats = detector_.stats(); + Logf("shake %d/%d reversals, %lld px, %.0f px/s, axis %.0f deg", + stats.good_reversals, stats.reversals, + static_cast(stats.travel_px), stats.speed, stats.axis_deg); + RescheduleTimer(); + } + + void TriggerNow() { QueueTrigger(); } + + void RescheduleTimer() { + if (!hwnd_) return; + const bool polling = !use_hook_; + const bool fast = zoomer_.Active() && zoomer_.NeedsFastTick(); + const bool needs_ticks = polling || zoomer_.Active(); + if (!needs_ticks) { + if (timer_active_) { + KillTimer(hwnd_, kAnimTimerId); + timer_active_ = false; + timer_interval_ = 0; + } + return; + } + const UINT interval = + polling ? kPollTickMs : (fast ? kFastTickMs : kHoldTickMs); + if (timer_active_ && interval == timer_interval_) return; + SetTimer(hwnd_, kAnimTimerId, interval, nullptr); + timer_active_ = true; + timer_interval_ = interval; + } + + bool InstallHook() { + mouse_hook_ = SetWindowsHookExW(WH_MOUSE_LL, &MouseHookProc, + GetModuleHandleW(nullptr), 0); + if (!mouse_hook_) { + LogCritical("low-level mouse hook refused (%lu); using polling instead", + GetLastError()); + return false; + } + return true; + } + + void UninstallHook() { + if (!mouse_hook_) return; + UnhookWindowsHookEx(mouse_hook_); + mouse_hook_ = nullptr; + } + + bool AddTrayIcon() { + tray_ = {}; + tray_.cbSize = sizeof(tray_); + tray_.hWnd = hwnd_; + tray_.uID = kTrayIconId; + tray_.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; + tray_.uCallbackMessage = kMsgTray; + tray_.hIcon = + LoadIconW(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(IDI_APP_ICON)); + if (!tray_.hIcon) return false; + UpdateTip(tray_); + if (!Shell_NotifyIconW(NIM_ADD, &tray_)) return false; + tray_icon_added_ = true; + return true; + } + + void RemoveTrayIcon() { + if (!tray_icon_added_) return; + NOTIFYICONDATAW nid = {}; + nid.cbSize = sizeof(nid); + nid.hWnd = hwnd_; + nid.uID = kTrayIconId; + Shell_NotifyIconW(NIM_DELETE, &nid); + tray_icon_added_ = false; + } + + void UpdateTip(NOTIFYICONDATAW& nid) { + StringCchCopyW(nid.szTip, ARRAYSIZE(nid.szTip), + paused_ ? L"Shake to Find Cursor - paused" + : L"Shake to Find Cursor - shake to find it"); + } + + void AnnounceOnce() { + AppSettings& settings = AppSettings::Get(); + if (settings.seen_intro) return; + settings.seen_intro = true; + settings.Save(); + if (zoomer_.available()) { + ShowBalloon(L"Shake the mouse and the pointer grows. Right-click the tray " + L"icon for size, sensitivity and highlight options.", + L"Shake to Find Cursor"); + } else { + ShowBalloon( + L"The highlight is on. Enlarging the pointer itself needs " + L"administrator rights: right-click the tray icon and choose " + L"'Restart as administrator' to enable it.", + L"Shake to Find Cursor"); + } + } + + void ShowBalloon(const wchar_t* text, const wchar_t* title) { + if (!tray_icon_added_) return; + NOTIFYICONDATAW nid = {}; + nid.cbSize = sizeof(nid); + nid.hWnd = hwnd_; + nid.uID = kTrayIconId; + nid.uFlags = NIF_INFO; + StringCchCopyW(nid.szInfo, ARRAYSIZE(nid.szInfo), text); + StringCchCopyW(nid.szInfoTitle, ARRAYSIZE(nid.szInfoTitle), title); + nid.dwInfoFlags = NIIF_INFO; + Shell_NotifyIconW(NIM_MODIFY, &nid); + } + + // --- tray menu ---------------------------------------------------------- + + void BuildMenu(HMENU menu) { + const AppSettings& settings = AppSettings::Get(); + AppendMenuW(menu, MF_STRING, kCmdFind, L"Find cursor now\t\tCtrl+Alt+F"); + AppendMenuW(menu, paused_ ? MF_CHECKED : MF_STRING, kCmdPaused, L"Paused"); + AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); + + HMENU sub = CreatePopupMenu(); + if (sub) { + const int level = settings.sensitivity; + AppendMenuW(sub, level < 40 ? MF_CHECKED : MF_STRING, kCmdSensGentle, + L"Gentle - big, deliberate shakes"); + AppendMenuW(sub, (level >= 40 && level < 70) ? MF_CHECKED : MF_STRING, + kCmdSensStandard, L"Standard"); + AppendMenuW(sub, level >= 70 ? MF_CHECKED : MF_STRING, kCmdSensSharp, + L"Sharp - short flicks too"); + AppendMenuW(menu, MF_POPUP, reinterpret_cast(sub), + L"Shake sensitivity"); + } + + sub = CreatePopupMenu(); + if (sub) { + const int scale = settings.scale_percent; + AppendMenuW(sub, scale <= 200 ? MF_CHECKED : MF_STRING, kCmdScale2, + L"2x"); + AppendMenuW(sub, (scale > 200 && scale <= 300) ? MF_CHECKED : MF_STRING, + kCmdScale3, L"3x"); + AppendMenuW(sub, (scale > 300 && scale <= 400) ? MF_CHECKED : MF_STRING, + kCmdScale4, L"4x"); + AppendMenuW(sub, scale > 400 ? MF_CHECKED : MF_STRING, kCmdScale5, L"5x"); + AppendMenuW(menu, MF_POPUP, reinterpret_cast(sub), + L"Pointer size"); + } + + sub = CreatePopupMenu(); + if (sub) { + const int hold = settings.hold_ms; + AppendMenuW(sub, hold <= 600 ? MF_CHECKED : MF_STRING, kCmdHoldShort, + L"Briefly (0.4 s)"); + AppendMenuW(sub, (hold > 600 && hold <= 1200) ? MF_CHECKED : MF_STRING, + kCmdHoldNormal, L"A moment (0.9 s)"); + AppendMenuW(sub, hold > 1200 ? MF_CHECKED : MF_STRING, kCmdHoldLong, + L"A while (1.8 s)"); + AppendMenuW(menu, MF_POPUP, reinterpret_cast(sub), + L"Keep it visible"); + } + + sub = CreatePopupMenu(); + if (sub) { + const OverlayStyle overlay = settings.overlay; + AppendMenuW(sub, overlay == OverlayStyle::kNone ? MF_CHECKED : MF_STRING, + kCmdOverlayNone, L"None (pointer size only)"); + AppendMenuW(sub, overlay == OverlayStyle::kRipple ? MF_CHECKED : MF_STRING, + kCmdOverlayRipple, L"Ripple rings"); + AppendMenuW(sub, + overlay == OverlayStyle::kSpotlight ? MF_CHECKED : MF_STRING, + kCmdOverlaySpotlight, L"Spotlight - dim the screen"); + AppendMenuW(menu, MF_POPUP, reinterpret_cast(sub), L"Highlight"); + } + + AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); + UINT enlarge_flags = + MF_STRING | (settings.enlarge_pointer ? MF_CHECKED : 0); + if (!zoomer_.available()) enlarge_flags |= MF_GRAYED; + AppendMenuW(menu, enlarge_flags, kCmdEnlarge, + zoomer_.available() + ? L"Enlarge the pointer" + : L"Enlarge the pointer (needs administrator)"); + if (!zoomer_.available()) { + AppendMenuW(menu, MF_STRING, kCmdElevate, L"Restart as administrator..."); + } + AppendMenuW(menu, AutoStart::IsEnabled() ? MF_CHECKED : MF_STRING, + kCmdAutostart, L"Start when I sign in"); + AppendMenuW(menu, use_hook_ ? MF_CHECKED : MF_STRING, kCmdUseHook, + L"Track with a mouse hook (recommended)"); + AppendMenuW(menu, settings.ignore_fullscreen ? MF_CHECKED : MF_STRING, + kCmdIgnoreFullscreen, L"Skip while a full screen app is in front"); + AppendMenuW(menu, settings.hotkey ? MF_CHECKED : MF_STRING, kCmdHotkey, + L"Ctrl+Alt+F finds the pointer"); + AppendMenuW(menu, settings.logging ? MF_CHECKED : MF_STRING, kCmdLogging, + L"Write a debug log (shake.log)"); + AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); + AppendMenuW(menu, MF_STRING, kCmdExit, L"Exit"); + } + + void ShowMenu() { + HMENU menu = CreatePopupMenu(); + if (!menu) return; + BuildMenu(menu); + + POINT point = {}; + GetCursorPos(&point); + // Without the foreground dance the menu keeps capture and only closes when + // clicked, instead of dismissing when the user clicks elsewhere. + SetForegroundWindow(hwnd_); + const int command = TrackPopupMenuEx( + menu, TPM_RIGHTBUTTON | TPM_NONOTIFY | TPM_RETURNCMD, point.x, point.y, + hwnd_, nullptr); + DestroyMenu(menu); + PostMessageW(hwnd_, WM_NULL, 0, 0); + if (command != 0) HandleCommand(command); + } + + void HandleCommand(int command_id) { + AppSettings& settings = AppSettings::Get(); + const MenuCommand command = static_cast(command_id); + bool save = true; + + switch (command) { + case kCmdFind: + TriggerNow(); + return; + case kCmdPaused: + paused_ = !paused_; + if (tray_icon_added_) { + NOTIFYICONDATAW nid = tray_; + nid.uFlags = NIF_TIP; + UpdateTip(nid); + Shell_NotifyIconW(NIM_MODIFY, &nid); + } + if (paused_) { + overlay_.Hide(); + } else { + detector_.Reset(); + } + RescheduleTimer(); + return; + case kCmdSensGentle: + case kCmdSensStandard: + case kCmdSensSharp: + settings.sensitivity = SensitivityForCommand(command); + detector_.SetTuning(settings.DetectorTuning()); + break; + case kCmdScale2: + case kCmdScale3: + case kCmdScale4: + case kCmdScale5: + settings.scale_percent = ScaleForCommand(command); + zoomer_.Configure(); + break; + case kCmdHoldShort: + case kCmdHoldNormal: + case kCmdHoldLong: + settings.hold_ms = HoldForCommand(command); + break; + case kCmdOverlayNone: + case kCmdOverlayRipple: + case kCmdOverlaySpotlight: + settings.overlay = OverlayForCommand(command); + if (settings.overlay == OverlayStyle::kNone) overlay_.Hide(); + break; + case kCmdEnlarge: + settings.enlarge_pointer = !settings.enlarge_pointer; + break; + case kCmdAutostart: { + if (AutoStart::IsEnabled()) { + AutoStart::Disable(); + } else if (!AutoStart::Enable()) { + MessageBoxW(hwnd_, + L"Windows would not let this app be added to start-up.", + L"Shake to Find Cursor", MB_OK | MB_ICONWARNING); + } else { + ShowBalloon(zoomer_.available() + ? L"A scheduled task will start this app with " + L"administrator rights at sign-in." + : L"This app will start automatically at sign-in.", + L"Start-up"); + } + save = false; + break; + } + case kCmdUseHook: + use_hook_ = !use_hook_; + settings.tracking = + use_hook_ ? TrackingMode::kHook : TrackingMode::kPolling; + if (use_hook_) { + if (!InstallHook()) { + use_hook_ = false; + settings.tracking = TrackingMode::kPolling; + } + } else { + UninstallHook(); + } + break; + case kCmdIgnoreFullscreen: + settings.ignore_fullscreen = !settings.ignore_fullscreen; + break; + case kCmdHotkey: + settings.hotkey = !settings.hotkey; + if (settings.hotkey) { + RegisterHotKey(hwnd_, kHotkeyId, kHotkeyModifiers, kHotkeyVirtualKey); + } else { + UnregisterHotKey(hwnd_, kHotkeyId); + } + break; + case kCmdLogging: + settings.logging = !settings.logging; + break; + case kCmdElevate: + // The elevated copy is started before this process exits, so it is + // told to skip the single-instance check rather than finding our mutex + // still held and giving up with an "already running" box. + if (RelaunchElevated(L"--elevated")) { + PostMessageW(hwnd_, WM_CLOSE, 0, 0); + } else { + MessageBoxW(hwnd_, + L"The elevation request was declined, so only the " + L"highlight overlay is available.", + L"Shake to Find Cursor", MB_OK | MB_ICONINFORMATION); + } + save = false; + break; + case kCmdExit: + PostMessageW(hwnd_, WM_CLOSE, 0, 0); + return; + default: + save = false; + break; + } + + if (save) { + settings.Save(); + Logf("settings: sensitivity=%d scale=%d%% hold=%dms overlay=%d " + "enlarge=%d hook=%d", + settings.sensitivity, settings.scale_percent, settings.hold_ms, + static_cast(settings.overlay), + settings.enlarge_pointer ? 1 : 0, use_hook_ ? 1 : 0); + } + RescheduleTimer(); + } + + ~App() { Shutdown(); } + + HWND hwnd_ = nullptr; + HHOOK mouse_hook_ = nullptr; + NOTIFYICONDATAW tray_ = {}; + bool use_hook_ = true; + bool timer_active_ = false; + bool tray_icon_added_ = false; + bool shut_down_ = false; + bool paused_ = false; + UINT timer_interval_ = 0; + volatile bool pending_trigger_ = false; + ShakeDetector detector_; + PointerZoomer zoomer_; + FindOverlay overlay_; +}; + +LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM w_param, + LPARAM l_param) { + App& app = App::Get(); + if (message == TaskbarCreatedMessage() && TaskbarCreatedMessage() != 0) { + app.OnTaskbarCreated(); + return 0; + } + switch (message) { + case WM_TIMER: + app.OnTimer(static_cast(w_param)); + return 0; + case kMsgTrigger: + app.OnTrigger(); + return 0; + case kMsgTray: + app.OnTrayNotification(l_param); + return 0; + case WM_HOTKEY: + if (w_param == kHotkeyId) { + app.paused_ = false; + app.TriggerNow(); + } + return 0; + case WM_SETTINGCHANGE: + app.OnSettingChange(); + return 0; + case WM_DISPLAYCHANGE: + // Monitors moved or changed mode: the overlay geometry is stale. + app.overlay_.Hide(); + return 0; + case WM_ENDSESSION: + // Logoff or shutdown: never leave the session with an enlarged cursor. + if (w_param != 0) app.Shutdown(); + return 0; + case WM_CLOSE: + // Shutdown() tears the hooks, the overlay and the cursor scheme down, + // and destroys this window on the way out; the quit message is posted + // here as well so the loop ends even when the window is already gone. + app.Shutdown(); + PostQuitMessage(0); + return 0; + case WM_DESTROY: + PostQuitMessage(0); + return 0; + default: + break; + } + return DefWindowProcW(hwnd, message, w_param, l_param); +} + +LRESULT CALLBACK MouseHookProc(int code, WPARAM w_param, LPARAM l_param) { + if (code == HC_ACTION && w_param == WM_MOUSEMOVE) { + App& app = App::Get(); + if (!app.paused_) { + const auto* event = reinterpret_cast(l_param); + // Injected events come from remote tools and macros: they should not + // trigger a highlight the user never asked for. + if ((event->flags & LLMHF_INJECTED) == 0) { + app.FeedSample(event->pt, AppSettings::Get()); + } + } + } + // hHook may be NULL from Vista on: the system fills in the next one. + return CallNextHookEx(nullptr, code, w_param, l_param); +} + +} // namespace +} // namespace stfc + +namespace { + +bool CommandLineHas(const wchar_t* line, const wchar_t* flag) { + return line && wcsstr(line, flag) != nullptr; +} + +} // namespace + +int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE previous, + LPWSTR command_line, + int show) { + UNREFERENCED_PARAMETER(instance); + UNREFERENCED_PARAMETER(previous); + UNREFERENCED_PARAMETER(show); + + stfc::AdoptDpiAwareness(); + + stfc::StartupMode mode = stfc::StartupMode::kUseSettings; + const wchar_t* line = command_line; + const bool relaunch_handoff = CommandLineHas(line, L"--elevated"); + + if (!relaunch_handoff) { + // Two instances would fight over the cursor scheme: the second one would + // snapshot the first one's enlarged cursor as the "original". + HANDLE singleton = + CreateMutexW(nullptr, TRUE, stfc::kSingleInstanceMutex); + if (GetLastError() == ERROR_ALREADY_EXISTS) { + MessageBoxW(nullptr, + L"Shake to Find Cursor is already running - look for its icon " + L"in the notification area.", + L"Shake to Find Cursor", MB_OK | MB_ICONINFORMATION); + if (singleton) CloseHandle(singleton); + return 0; + } + // The handle is intentionally leaked for the lifetime of the process; it is + // the mutex's reference. + stfc::g_singleton = singleton; + } + + if (CommandLineHas(line, L"--poll")) { + mode = stfc::StartupMode::kForcePolling; + } else if (CommandLineHas(line, L"--hook")) { + mode = stfc::StartupMode::kForceHook; + } else if (CommandLineHas(line, L"--help") || + CommandLineHas(line, L"/?")) { + MessageBoxW(nullptr, + L"Shake to Find Cursor\n\n" + L" --hook track the pointer with a low-level mouse hook " + L"(default, zero idle cost)\n" + L" --poll track the pointer by sampling it on a timer " + L"(fallback when hooks are blocked)\n\n" + L"Shake the mouse to find the pointer. Right-click the tray " + L"icon for settings; Ctrl+Alt+F finds the pointer on demand.", + L"Shake to Find Cursor", MB_OK | MB_ICONINFORMATION); + return 0; + } + + stfc::Logf("=== start (elevated=%d, relaunch=%d) ===", + stfc::IsElevated() ? 1 : 0, relaunch_handoff ? 1 : 0); + + if (!stfc::App::Get().Initialize(mode)) { + MessageBoxW(nullptr, + L"Shake to Find Cursor could not start: it could not create " + L"its hidden window or tray icon.", + L"Shake to Find Cursor", MB_OK | MB_ICONERROR); + stfc::App::Get().Shutdown(); + return 1; + } + + const int result = stfc::App::Get().Run(); + stfc::App::Get().Shutdown(); + stfc::Logf("=== exit ==="); + return result; +} diff --git a/readme.md b/readme.md index 22d4e29..707d9b6 100644 --- a/readme.md +++ b/readme.md @@ -1,78 +1,175 @@ # Shake to Find Cursor -A Windows utility that helps you locate your cursor by enlarging it when you shake your mouse. When you can't find your cursor on screen, just shake your mouse and the cursor will temporarily become larger. +Lose the pointer on a big or busy screen? Shake the mouse and the pointer grows +and a click-through highlight is drawn around it for a moment, then everything +fades back to normal. Inspired by the macOS "shake to find cursor" behaviour. -## Features - -- Two tracking modes: - - Hook mode: Uses Windows hook to track mouse movement - - Polling mode: Uses timer to track mouse movement -- System tray integration -- Temporary cursor enlargement -- Shake pattern recognition -- Administrator privileges required (for system cursor modification) - -## Usage - -### Command Line Arguments - -- `--hook`: Use hook mode for mouse tracking (default is polling mode) - -Example: ``` -ShakeToFindCursor.exe --hook + shake the mouse -> pointer enlarges + ripple rings / spotlight around it + -> fades back after ~1 s, no clicks stolen, no focus moved ``` -### Finding Your Cursor +## What changed in 1.4 + +The detection and the animation were rebuilt around one constraint: a low-level +mouse hook runs on your thread and blocks *everyone's* input while it is inside +the callback. + +* **Shake detection actually detects shakes.** The old build judged a fixed + 10-sample history, which at 500-8000 Hz mouse report rates is 1-20 ms of + movement - far too short to hold the five direction changes it demanded, so + shaking did nothing. It also counted X and Y sign flips separately, which both + missed diagonal shakes and mistook high-rate sensor jitter for a shake. The + new algorithm projects the recent motion onto its principal axis, counts + hysteresis reversals there with a per-stroke amplitude and speed requirement, + and ignores pauses and pointer warps. `tests/shake_detector_test.cpp` replays + recorded synthetic traces through the old and the new algorithm side by side: + + | trace | v1.3 | v1.4 | + | ---------------------- | ---- | ---- | + | deliberate shake | 0 | 2 | + | same, sampled at 1 kHz | 0 | 2 | + | same, sampled at 8 kHz | 0 | 2 | + | diagonal shake | 0 | 2 | + | fast curved sweep | 0 | 0 | + | optical sensor jitter | 999 | 0 | + +* **No input lag, no flicker.** The hook only feeds numbers to the detector and + posts one message. The pointer enlargement is applied from a pre-built ladder + of scaled cursors, so a frame is one `SetSystemCursor` per cursor instead of + thirteen `CopyImage` calls at 60 FPS; growing a cursor that used to be scaled + on demand is now free while you shake. The overlay renders on its own thread. +* **The highlight overlay** (new): *ripple* rings plus a marker dot, or + *spotlight* which dims the monitor around the pointer. It is layered, + topmost and click-through, so it never takes focus or a click - and it works + without administrator rights, which is what makes the app usable for people + who will not elevate it. +* **Your pointer scheme is respected.** The cursors that get enlarged are the + ones the system is using right now, and they are put back afterwards; a custom + scheme, a theme or DPI change while running is picked up again on the next + `WM_SETTINGCHANGE`. +* **No more hard requirement for admin.** The manifest is `asInvoker`. Losing + the dialog at start-up means the pointer enlargement is simply unavailable, + and the tray menu offers *Restart as administrator* (one click) plus a + scheduled task for it at sign-in. +* **It cleans up after itself.** A registry marker is written while the pointer + is enlarged, so an instance that was killed mid-animation heals the session on + the next start instead of leaving a 5x pointer until you sign out. Logoff and + shutdown restore the cursors too, and a second copy refuses to start rather + than fighting over the cursor scheme. +* **Settings, not source edits.** Sensitivity, size, duration, highlight, + tracking mode, hotkey and logging live in `HKCU\Software\ShakeToFindCursor` + and are settable from the tray menu. They used to be `constexpr` fields you + had to recompile to change (and the documented values had drifted from the + code). +* **Idle cost.** In hook mode there is no periodic timer at all while nothing is + happening: the old loop woke every 10-16 ms forever (`PeekMessage` + + `Sleep(1)`). Polling mode still samples at 125 Hz. +* **Small things:** the tray icon is re-added when Explorer restarts + (`TaskbarCreated`), auto-start works when not elevated (HKCU Run key), the + debug log goes to `%LOCALAPPDATA%\ShakeToFindCursor\shake.log` instead of a + file next to the exe, injected mouse events from automation no longer trigger + the effect, and `--help` works. + +## Using it + +1. Run `ShakeToFindCursor.exe`. A tray icon appears; the first start shows a + balloon pointing at the menu. +2. Shake the mouse when you lose the pointer. Clicking the tray icon (either + button) opens the menu; double-clicking it finds the pointer once. +3. `Ctrl+Alt+F` also finds the pointer - useful in a window where you cannot see + it but do not want to move the mouse. + +### Tray menu + +| Item | Effect | +| ---- | ------ | +| Find cursor now | trigger once | +| Paused | stop reacting, keep the tray icon | +| Shake sensitivity | Gentle / Standard / Sharp | +| Pointer size | 2x / 3x / 4x / 5x | +| Keep it visible | 0.4 s / 0.9 s / 1.8 s | +| Highlight | None / Ripple rings / Spotlight | +| Enlarge the pointer | needs administrator; greyed out when not elevated | +| Restart as administrator... | re-launches this exe through UAC | +| Start when I sign in | scheduled task when elevated, Run key otherwise | +| Track with a mouse hook | turn off to fall back to timer polling | +| Skip while a full screen app is in front | avoids interrupting games and video | +| Write a debug log | `%LOCALAPPDATA%\ShakeToFindCursor\shake.log` | + +### Command line -1. When you lose track of your cursor, shake your mouse rapidly -2. The cursor will temporarily enlarge for better visibility -3. After 0.5 seconds, the cursor will return to its normal size - -### System Tray - -- Right-click the tray icon to access the menu -- Select "Exit" to close the application -- Or enable/disable auto-start from the menu +``` +ShakeToFindCursor.exe use the saved tracking mode +ShakeToFindCursor.exe --hook low-level mouse hook (default, zero idle cost) +ShakeToFindCursor.exe --poll sample the pointer on a timer (if hooks are blocked) +ShakeToFindCursor.exe --help usage +``` -#### Auto-start Setup +`--hook` and `--poll` apply to that run only; the tray menu choice is what gets +remembered. -To have the application launch at Windows startup: -1. Right-click the tray icon and click "Enable Auto-start." -2. A scheduled task will be created to start the application automatically. +## Building -To remove auto-start: -1. Right-click the tray icon again. -2. Click "Disable Auto-start" to remove the scheduled task. +Requires only the Windows SDK - no third-party dependencies, no ATL, and no +Visual C++ redistributable (the CRT is linked statically by both toolchains). -## System Requirements +``` +cmake -S . -B build +cmake --build build --config Release +``` -- Windows 7 or later -- Administrator privileges -- No additional dependencies required +* Visual Studio: open a *Developer Command Prompt*, run the two lines above, and + use `build\Release\ShakeToFindCursor.exe`. +* MinGW-w64: `cmake -S . -B build -G "MinGW Makefiles" && cmake --build build`. +* Always-on-administrator build (the pre-1.4 behaviour): + `cmake -S . -B build -DSTFC_REQUIRE_ADMIN=ON`. -## Building +Options: `STFC_BUILD_TESTS` (on), `STFC_STRICT_WARNINGS` (on, adds `/WX`), +`STFC_REQUIRE_ADMIN` (off). -1. Clone the repository -2. Create a "build" folder -3. Run "cmake .." inside that folder -4. Build the project using your chosen compiler +### Tests -## Configuration +The shake detector has no Windows dependency, so it is unit tested on any +platform. CI runs this on Linux and on Windows: -The following parameters can be adjusted in `CursorConfig` class: +``` +cmake -S . -B build -DSTFC_BUILD_TESTS=ON +cmake --build build --target shake_detector_tests +ctest --test-dir build --output-on-failure +``` -- `kScaleFactor`: Cursor enlargement factor (default: 3.0) -- `kEnlargeDurationMs`: Duration of cursor enlargement (default: 500ms) -- `kHistorySize`: Number of movements to track for shake detection (default: 10) -- `kMinDirectionChanges`: Minimum direction changes to trigger enlargement (default: 5) -- `kMinMovementSpeed`: Minimum speed to consider as shaking (default: 800 pixels/second) -- `kMaxTimeWindow`: Time window for shake detection (default: 500ms) +It covers report-rate independence (25 Hz to 8 kHz), diagonal and vertical +shakes, the false-positive cases (sweeps, wobbles, jitter, warps), the +sensitivity slider, re-arming after a pause, and the cost per sample. To tune +how a shake feels, change `ShakeTuning::ForSensitivity()` in +`src/shake_detector.h` and re-run the tests: the false-positive cases are the +ones to watch. + +## How it decides + +`src/shake_detector.h` keeps the last `window_us` of pointer samples (decimated +so a 8 kHz mouse costs the same as a 125 Hz one), finds the dominant direction +of that motion from the covariance of its steps, projects the positions onto it, +and counts reversals on that scalar signal with a hysteresis band. A reversal +only counts when the stroke it completed was long enough, fast enough, and short +in duration; the shake must still be underway; and one detection starts a +cooldown so a long shake extends the highlight instead of re-firing sixty times +a second. + +## Requirements and limitations + +* Windows 7 or later, x86 or x64. Multi-monitor and per-monitor DPI aware. +* Enlarging the *pointer* goes through `SetSystemCursor`, which needs + administrator rights. Without them the overlay still works, and the effect is + the part most people actually see. +* Applications that install their own cursor (a game's custom crosshair) are not + ours to enlarge; the overlay is what will find them. +* A game in exclusive full screen composites its own surface, so no overlay can + be drawn over it - which is also why the pointer is usually irrelevant there. +* `SetSystemCursor` is session global, so a crash between enlarging and restoring + would outlive the process; the start-up marker above is what repairs that. ## License -This project is licensed under the MIT License - see the LICENSE file for details. - -## Acknowledgments - -- Inspired by macOS's shake-to-find-cursor feature \ No newline at end of file +MIT - see [LICENSE](LICENSE). diff --git a/res.rc b/res.rc deleted file mode 100644 index f1b2ab5..0000000 --- a/res.rc +++ /dev/null @@ -1,37 +0,0 @@ -#include "winres.h" - -#include "resource.h" - -IDI_APP_ICON ICON "app_icon.ico" - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,3,0,0 - PRODUCTVERSION 1,3,0,0 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "CompanyName", "0CCh\0" - VALUE "FileDescription", "Shake to Find Cursor\0" - VALUE "FileVersion", "1.3.0.0\0" - VALUE "InternalName", "ShakeToFindCursor\0" - VALUE "OriginalFilename", "ShakeToFindCursor.exe\0" - VALUE "ProductName", "Shake to Find Cursor\0" - VALUE "ProductVersion", "1.3.0.0\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END diff --git a/res.rc.in b/res.rc.in new file mode 100644 index 0000000..6c765a6 --- /dev/null +++ b/res.rc.in @@ -0,0 +1,50 @@ +// Generated into the build directory by CMake (see CMakeLists.txt), which +// substitutes absolute paths for the icon and the manifest and picks the +// manifest that matches STFC_REQUIRE_ADMIN. Doing it this way means one source of +// truth for the resources and no reliance on how a particular RC compiler +// resolves relative file names (rc.exe and windres disagree about that). +#include "winres.h" + +// IDI_APP_ICON from resource.h, spelled numerically so this file needs no +// include path of its own. +101 ICON "@STFC_ICON_FILE@" + +// An embedded manifest is the only reliable place for the DPI awareness and +// OS-support declarations (and it keeps rc.exe and windres in agreement, unlike +// a linker flag). The numeric ids are CREATEPROCESS_MANIFEST_RESOURCE_ID (1) +// and RT_MANIFEST (24); spelled numerically because winres.h pulls those names +// in through winuser.rh, whose contents differ between SDKs. +@STFC_MANIFEST_LINE@ + +VS_VERSION_INFO VERSIONINFO + FILEVERSION @PROJECT_VERSION_MAJOR@,@PROJECT_VERSION_MINOR@,@PROJECT_VERSION_PATCH@,0 + PRODUCTVERSION @PROJECT_VERSION_MAJOR@,@PROJECT_VERSION_MINOR@,@PROJECT_VERSION_PATCH@,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "0CCh\0" + VALUE "FileDescription", "Shake to Find Cursor\0" + VALUE "FileVersion", "@PROJECT_VERSION@\0" + VALUE "InternalName", "ShakeToFindCursor\0" + VALUE "LegalCopyright", "MIT License\0" + VALUE "OriginalFilename", "ShakeToFindCursor.exe\0" + VALUE "ProductName", "Shake to Find Cursor\0" + VALUE "ProductVersion", "@PROJECT_VERSION@\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END diff --git a/src/app_settings.cpp b/src/app_settings.cpp new file mode 100644 index 0000000..1842e18 --- /dev/null +++ b/src/app_settings.cpp @@ -0,0 +1,213 @@ +#include "app_settings.h" + +#include +#include + +#include +#include + +namespace stfc { +namespace { + +constexpr const wchar_t* kValueSensitivity = L"Sensitivity"; +constexpr const wchar_t* kValueEnlarge = L"EnlargePointer"; +constexpr const wchar_t* kValueScale = L"ScalePercent"; +constexpr const wchar_t* kValueGrow = L"GrowMs"; +constexpr const wchar_t* kValueHold = L"HoldMs"; +constexpr const wchar_t* kValueShrink = L"ShrinkMs"; +constexpr const wchar_t* kValueOverlay = L"Overlay"; +constexpr const wchar_t* kValueTracking = L"Tracking"; +constexpr const wchar_t* kValueHotkey = L"Hotkey"; +constexpr const wchar_t* kValueIgnoreFullscreen = L"IgnoreFullscreen"; +constexpr const wchar_t* kValueLogging = L"Logging"; +constexpr const wchar_t* kValueSeenIntro = L"SeenIntro"; + +constexpr size_t kLogRotateBytes = 256 * 1024; + +bool ReadDword(HKEY key, const wchar_t* name, DWORD* out) { + DWORD type = 0; + DWORD size = sizeof(DWORD); + if (RegQueryValueExW(key, name, nullptr, &type, reinterpret_cast(out), + &size) != ERROR_SUCCESS) { + return false; + } + return type == REG_DWORD && size == sizeof(DWORD); +} + +void ClampSetting(int& value, int lo, int hi) { + if (value < lo) value = lo; + if (value > hi) value = hi; +} + +// %LOCALAPPDATA%\ShakeToFindCursor, created if missing. Returns false when no +// writable location could be found, in which case logging is simply off. +bool LogDirectory(wchar_t* out, size_t cch) { + wchar_t base[MAX_PATH] = L""; + if (FAILED(SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, base))) { + if (GetEnvironmentVariableW(L"TEMP", base, MAX_PATH) == 0) return false; + } + if (FAILED(StringCchCatW(base, MAX_PATH, L"\\ShakeToFindCursor"))) return false; + CreateDirectoryW(base, nullptr); + return SUCCEEDED(StringCchCopyW(out, cch, base)); +} + +void LogV(const char* fmt, va_list args, bool always) { + if (!always && !AppSettings::Get().logging) return; + + wchar_t dir[MAX_PATH]; + if (!LogDirectory(dir, MAX_PATH)) return; + wchar_t path[MAX_PATH]; + if (FAILED(StringCchCopyW(path, MAX_PATH, dir)) || + FAILED(StringCchCatW(path, MAX_PATH, L"\\shake.log"))) { + return; + } + + // Share read *and* write so the log can be open in an editor while we append, + // and so a second instance (e.g. the elevated one during a relaunch) does not + // lock us out of logging entirely. + const DWORD sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; + HANDLE file = CreateFileW(path, FILE_WRITE_DATA | FILE_APPEND_DATA, sharing, + nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, + nullptr); + if (file == INVALID_HANDLE_VALUE) return; + + // Rotate: move the previous copy aside, then start a fresh file. Bounded, + // readable in Notepad, and no dependency on a logging framework. + LARGE_INTEGER size = {}; + if (GetFileSizeEx(file, &size) && + size.QuadPart > static_cast(kLogRotateBytes)) { + CloseHandle(file); + wchar_t backup[MAX_PATH]; + StringCchCopyW(backup, MAX_PATH, dir); + StringCchCatW(backup, MAX_PATH, L"\\shake.old.log"); + MoveFileExW(path, backup, MOVEFILE_REPLACE_EXISTING); + file = CreateFileW(path, FILE_WRITE_DATA | FILE_APPEND_DATA, sharing, + nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, + nullptr); + if (file == INVALID_HANDLE_VALUE) return; + } + + char body[768]; + vsnprintf(body, sizeof(body), fmt, args); + + SYSTEMTIME st = {}; + GetLocalTime(&st); + char line[900]; + const int n = snprintf(line, sizeof(line), + "%04d-%02d-%02d %02d:%02d:%02d.%03d %s", st.wYear, + st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, + st.wMilliseconds, body); + if (n <= 0) { + CloseHandle(file); + return; + } + size_t len = static_cast(n); + if (len > sizeof(line) - 3) len = sizeof(line) - 3; + line[len++] = '\r'; + line[len++] = '\n'; + + SetFilePointer(file, 0, nullptr, FILE_END); + DWORD written = 0; + WriteFile(file, line, static_cast(len), &written, nullptr); + CloseHandle(file); +} + +} // namespace + +AppSettings& AppSettings::Get() { + static AppSettings instance; + static bool loaded = false; + if (!loaded) { + loaded = true; + instance.Load(); + } + return instance; +} + +int AppSettings::OverlayDurationMs() const { + const int total = grow_ms + hold_ms + shrink_ms; + return total < 600 ? 600 : total; +} + +void AppSettings::Load() { + HKEY key = nullptr; + if (RegOpenKeyExW(HKEY_CURRENT_USER, AppSettings::KeyPath(), 0, KEY_READ, + &key) != ERROR_SUCCESS) { + return; // first run: the defaults above stand + } + DWORD value = 0; + if (ReadDword(key, kValueSensitivity, &value)) + sensitivity = static_cast(value); + if (ReadDword(key, kValueEnlarge, &value)) enlarge_pointer = value != 0; + if (ReadDword(key, kValueScale, &value)) scale_percent = static_cast(value); + if (ReadDword(key, kValueGrow, &value)) grow_ms = static_cast(value); + if (ReadDword(key, kValueHold, &value)) hold_ms = static_cast(value); + if (ReadDword(key, kValueShrink, &value)) shrink_ms = static_cast(value); + if (ReadDword(key, kValueOverlay, &value)) + overlay = static_cast(value); + if (ReadDword(key, kValueTracking, &value)) + tracking = static_cast(value); + if (ReadDword(key, kValueHotkey, &value)) hotkey = value != 0; + if (ReadDword(key, kValueIgnoreFullscreen, &value)) + ignore_fullscreen = value != 0; + if (ReadDword(key, kValueLogging, &value)) logging = value != 0; + if (ReadDword(key, kValueSeenIntro, &value)) seen_intro = value != 0; + RegCloseKey(key); + + ClampSetting(sensitivity, 1, 100); + ClampSetting(scale_percent, 150, 600); + ClampSetting(grow_ms, 0, 1000); + ClampSetting(hold_ms, 150, 8000); + ClampSetting(shrink_ms, 0, 1500); + const int overlay_value = static_cast(overlay); + if (overlay_value < 0 || overlay_value > 2) overlay = OverlayStyle::kRipple; + const int tracking_value = static_cast(tracking); + if (tracking_value < 0 || tracking_value > 1) tracking = TrackingMode::kHook; +} + +void AppSettings::Save() const { + HKEY key = nullptr; + if (RegCreateKeyExW(HKEY_CURRENT_USER, AppSettings::KeyPath(), 0, nullptr, 0, + KEY_WRITE, nullptr, &key, nullptr) != ERROR_SUCCESS) { + return; + } + struct Item { + const wchar_t* name; + DWORD value; + }; + const Item items[] = { + {kValueSensitivity, static_cast(sensitivity)}, + {kValueEnlarge, enlarge_pointer ? 1u : 0u}, + {kValueScale, static_cast(scale_percent)}, + {kValueGrow, static_cast(grow_ms)}, + {kValueHold, static_cast(hold_ms)}, + {kValueShrink, static_cast(shrink_ms)}, + {kValueOverlay, static_cast(static_cast(overlay))}, + {kValueTracking, static_cast(static_cast(tracking))}, + {kValueHotkey, hotkey ? 1u : 0u}, + {kValueIgnoreFullscreen, ignore_fullscreen ? 1u : 0u}, + {kValueLogging, logging ? 1u : 0u}, + {kValueSeenIntro, seen_intro ? 1u : 0u}, + }; + for (const auto& item : items) { + RegSetValueExW(key, item.name, 0, REG_DWORD, + reinterpret_cast(&item.value), sizeof(DWORD)); + } + RegCloseKey(key); +} + +void Logf(const char* fmt, ...) { + va_list args; + va_start(args, fmt); + LogV(fmt, args, false); + va_end(args); +} + +void LogCritical(const char* fmt, ...) { + va_list args; + va_start(args, fmt); + LogV(fmt, args, true); + va_end(args); +} + +} // namespace stfc diff --git a/src/app_settings.h b/src/app_settings.h new file mode 100644 index 0000000..283372a --- /dev/null +++ b/src/app_settings.h @@ -0,0 +1,83 @@ +// Persisted user settings and the (optional) debug log. +// +// Settings live in HKCU\Software\ShakeToFindCursor so that nothing needs to be +// written next to the executable (Program Files is not writable, and the old +// build logged into its working directory, which silently failed there). +#pragma once + +#include + +#include +#include + +#include "shake_detector.h" + +namespace stfc { + +enum class OverlayStyle : int { + kNone = 0, + kRipple = 1, // expanding rings + marker dot at the pointer + kSpotlight = 2 // dim the monitor, punch a soft hole around the pointer +}; + +enum class TrackingMode : int { + kHook = 0, // WH_MOUSE_LL: per-event samples, zero idle cost + kPolling = 1 // GetCursorPos on a timer: fallback when hooks are blocked +}; + +struct AppSettings { + // Shake detection. + int sensitivity = ShakeTuning::kDefaultSensitivity; // 1..100 + // Pointer enlargement. + bool enlarge_pointer = true; + int scale_percent = 300; // 150..600 + int grow_ms = 140; + int hold_ms = 900; + int shrink_ms = 240; + // Highlight overlay. + OverlayStyle overlay = OverlayStyle::kRipple; + // Behaviour. + TrackingMode tracking = TrackingMode::kHook; + bool hotkey = true; // Ctrl+Alt+F finds the pointer on demand + bool ignore_fullscreen = false; // do not trigger while a fullscreen app is up + bool logging = false; + bool seen_intro = false; // the introductory balloon has been shown + + static AppSettings& Get(); + void Load(); + void Save() const; + + ShakeTuning DetectorTuning() const { + return ShakeTuning::ForSensitivity(sensitivity); + } + // The overlay should stay up at least as long as the pointer is enlarged, + // otherwise the highlight disappears before the user has looked at it. + int OverlayDurationMs() const; + + static const wchar_t* KeyPath() { return L"Software\\ShakeToFindCursor"; } +}; + +// Debug logging. Logf() is a no-op unless the user turned logging on; +// LogCritical() always writes, so a start-up failure is diagnosable without +// asking the user to reproduce it with a debugger. +void Logf(const char* fmt, ...); +void LogCritical(const char* fmt, ...); + +// Monotonic clock in microseconds, used for all animation and detection math. +// Split into whole seconds plus remainder so the multiply cannot overflow +// 64-bit math on a machine with a 10 MHz counter that has been up for a week. +inline int64_t NowUs() { + static const LARGE_INTEGER kFrequency = [] { + LARGE_INTEGER f = {}; + QueryPerformanceFrequency(&f); + return f; + }(); + LARGE_INTEGER now = {}; + QueryPerformanceCounter(&now); + const long long freq = kFrequency.QuadPart > 0 ? kFrequency.QuadPart : 1; + const long long seconds = now.QuadPart / freq; + const long long remainder = now.QuadPart % freq; + return static_cast(seconds * 1000000 + remainder * 1000000 / freq); +} + +} // namespace stfc diff --git a/src/auto_start.cpp b/src/auto_start.cpp new file mode 100644 index 0000000..1eb55dc --- /dev/null +++ b/src/auto_start.cpp @@ -0,0 +1,286 @@ +#include "targetver.h" + +#include "auto_start.h" + +#include + +#include "app_settings.h" +#include "com_ptr.h" +#include "win_util.h" + +// Only the interfaces' vtables are used, and the CLSID/IID values below are +// spelled by hand, so nothing has to be imported from taskschd.dll: this file +// needs no taskschd.lib / uuid.lib, which also keeps it linkable with a +// toolchain that has no import library for that DLL. CoCreateInstance and the +// BSTR helpers do come from ole32. +#if defined(_MSC_VER) +#pragma comment(lib, "ole32.lib") +#endif + +namespace stfc { +namespace { + +// Hard-coded so the build needs neither uuid.lib nor initguid.h. +const GUID kCLSIDTaskScheduler = { + 0x0f87369f, 0xa4e5, 0x4cfc, + {0xbd, 0x3e, 0x73, 0xe6, 0x15, 0x45, 0x72, 0xdd}}; +const GUID kIIDTaskService = { + 0x2faba4c7, 0x4da9, 0x4013, + {0x96, 0x97, 0x20, 0xcc, 0x3f, 0xd4, 0x0f, 0x85}}; +const GUID kIIDLogonTrigger = { + 0x72dade38, 0xfae4, 0x4b3e, + {0xba, 0xf4, 0x5d, 0x00, 0x9a, 0xf0, 0x2b, 0x1c}}; +const GUID kIIDExecAction = { + 0x4c3d624d, 0xfd6b, 0x49a3, + {0xb9, 0xb7, 0x09, 0xcb, 0x3c, 0xd3, 0xf0, 0x47}}; + +// COM is only needed for this file, and only for as long as a call lasts, so +// the message-loop thread never has to commit to an apartment model. +class ComScope { + public: + ComScope() : hr_(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED)) { + owns_ = SUCCEEDED(hr_); + } + ~ComScope() { + if (owns_) CoUninitialize(); + } + bool ok() const { return owns_ || hr_ == RPC_E_CHANGED_MODE; } + + private: + HRESULT hr_; + bool owns_ = false; +}; + +class BStr { + public: + explicit BStr(const wchar_t* text) : value_(SysAllocString(text)) {} + ~BStr() { + if (value_) SysFreeString(value_); + } + BSTR get() const { return value_; } + explicit operator bool() const { return value_ != nullptr; } + + private: + BStr(const BStr&) = delete; + BStr& operator=(const BStr&) = delete; + BSTR value_; +}; + +VARIANT EmptyVariant() { + VARIANT value; + VariantInit(&value); + return value; +} + +bool ConnectTaskService(ComPtr* service, + ComPtr* root_folder) { + IUnknown* unknown = nullptr; + const HRESULT hr = CoCreateInstance(kCLSIDTaskScheduler, nullptr, + CLSCTX_INPROC_SERVER, kIIDTaskService, + reinterpret_cast(&unknown)); + if (FAILED(hr)) { + return false; + } + ComPtr connected; + connected.Attach(static_cast(unknown)); + if (FAILED(connected->Connect(EmptyVariant(), EmptyVariant(), EmptyVariant(), + EmptyVariant()))) { + return false; + } + ComPtr root; + if (FAILED(connected->GetFolder(BStr(L"\\").get(), root.Receive()))) { + return false; + } + service->Attach(connected.Get()); + connected.Reset(); // service now owned by the caller + root_folder->Attach(root.Get()); + root.Reset(); + return true; +} + +} // namespace + +bool AutoStart::IsTaskRegistered() { + ComScope com; + if (!com.ok()) return false; + ComPtr service; + ComPtr root; + if (!ConnectTaskService(&service, &root)) return false; + ComPtr task; + const HRESULT hr = root->GetTask(BStr(kTaskName).get(), task.Receive()); + return SUCCEEDED(hr) && task; +} + +bool AutoStart::IsRunKeySet() { + HKEY key = nullptr; + if (RegOpenKeyExW(HKEY_CURRENT_USER, + L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, + KEY_READ, &key) != ERROR_SUCCESS) { + return false; + } + const bool set = + RegQueryValueExW(key, kRunValueName, nullptr, nullptr, nullptr, nullptr) == + ERROR_SUCCESS; + RegCloseKey(key); + return set; +} + +bool AutoStart::IsEnabled() { return IsTaskRegistered() || IsRunKeySet(); } + +bool AutoStart::Enable() { + if (IsElevated()) { + if (EnableTask()) return true; + LogCritical( + "scheduled task could not be registered; falling back to the Run key"); + } + return EnableRunKey(); +} + +bool AutoStart::Disable() { + const bool task = DisableTask(); + const bool run = DisableRunKey(); + // Disabling a mechanism that was never enabled is not a failure; the user + // just wants the app out of their start-up. + return task || run || (!IsTaskRegistered() && !IsRunKeySet()); +} + +bool AutoStart::EnableTask() { + wchar_t exe[MAX_PATH]; + GetExePath(exe, MAX_PATH); + if (exe[0] == L'\0') return false; + wchar_t working[MAX_PATH]; + StringCchCopyW(working, MAX_PATH, exe); + RemoveFileName(working); + + ComScope com; + if (!com.ok()) { + LogCritical("COM unavailable, cannot register the start-up task"); + return false; + } + ComPtr service; + ComPtr root; + if (!ConnectTaskService(&service, &root)) { + LogCritical("Task Scheduler unavailable"); + return false; + } + + // A stale task (for example one pointing at a deleted exe) is replaced. + root->DeleteTask(BStr(kTaskName).get(), 0); + + ComPtr definition; + if (FAILED(service->NewTask(0, definition.Receive()))) return false; + + ComPtr info; + if (SUCCEEDED(definition->get_RegistrationInfo(info.Receive())) && info) { + info->put_Description(BStr(L"Shake to Find Cursor: enlarge the pointer when " + L"the mouse is shaken.") + .get()); + info->put_Author(BStr(L"ShakeToFindCursor").get()); + } + + ComPtr principal; + if (SUCCEEDED(definition->get_Principal(principal.Receive())) && principal) { + principal->put_RunLevel(TASK_RUNLEVEL_HIGHEST); + principal->put_LogonType(TASK_LOGON_INTERACTIVE_TOKEN); + } + + ComPtr settings; + if (SUCCEEDED(definition->get_Settings(settings.Receive())) && settings) { + settings->put_StartWhenAvailable(VARIANT_TRUE); + settings->put_DisallowStartIfOnBatteries(VARIANT_FALSE); + settings->put_StopIfGoingOnBatteries(VARIANT_FALSE); + settings->put_Hidden(VARIANT_FALSE); + BStr no_limit(L"PT0S"); + settings->put_ExecutionTimeLimit(no_limit.get()); + } + + ComPtr triggers; + if (SUCCEEDED(definition->get_Triggers(triggers.Receive())) && triggers) { + ComPtr trigger; + if (SUCCEEDED(triggers->Create(TASK_TRIGGER_LOGON, trigger.Receive())) && + trigger) { + BStr id(L"ShakeToFindCursorLogon"); + trigger->put_Id(id.get()); + trigger->put_Enabled(VARIANT_TRUE); + // Give Explorer a moment, so the very first tray icon add succeeds. + ComPtr logon; + if (logon.From(trigger.Get(), kIIDLogonTrigger)) { + BStr delay(L"PT5S"); + logon->put_Delay(delay.get()); + } + } + } + + ComPtr actions; + if (SUCCEEDED(definition->get_Actions(actions.Receive())) && actions) { + ComPtr action; + const HRESULT create_hr = actions->Create(TASK_ACTION_EXEC, action.Receive()); + if (SUCCEEDED(create_hr) && action) { + ComPtr exec; + if (exec.From(action.Get(), kIIDExecAction)) { + BStr path(exe); + BStr directory(working); + exec->put_Path(path.get()); + exec->put_WorkingDirectory(directory.get()); + } + } + } + + ComPtr registered; + const HRESULT hr = root->RegisterTaskDefinition( + BStr(kTaskName).get(), definition.Get(), TASK_CREATE_OR_UPDATE, + EmptyVariant(), EmptyVariant(), TASK_LOGON_INTERACTIVE_TOKEN, + EmptyVariant(), registered.Receive()); + if (FAILED(hr)) { + LogCritical("RegisterTaskDefinition failed (0x%08lX)", + static_cast(hr)); + return false; + } + Logf("start-up task registered"); + return true; +} + +bool AutoStart::EnableRunKey() { + wchar_t exe[MAX_PATH]; + GetExePath(exe, MAX_PATH); + if (exe[0] == L'\0') return false; + wchar_t command[MAX_PATH + 8]; + StringCchCopyW(command, MAX_PATH + 8, L"\""); + StringCchCatW(command, MAX_PATH + 8, exe); + StringCchCatW(command, MAX_PATH + 8, L"\""); + + HKEY key = nullptr; + if (RegOpenKeyExW(HKEY_CURRENT_USER, + L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, + KEY_SET_VALUE, &key) != ERROR_SUCCESS) { + return false; + } + const LONG result = RegSetValueExW( + key, kRunValueName, 0, REG_SZ, reinterpret_cast(command), + static_cast((wcslen(command) + 1) * sizeof(wchar_t))); + RegCloseKey(key); + return result == ERROR_SUCCESS; +} + +bool AutoStart::DisableTask() { + ComScope com; + if (!com.ok()) return false; + ComPtr service; + ComPtr root; + if (!ConnectTaskService(&service, &root)) return false; + return SUCCEEDED(root->DeleteTask(BStr(kTaskName).get(), 0)); +} + +bool AutoStart::DisableRunKey() { + HKEY key = nullptr; + if (RegOpenKeyExW(HKEY_CURRENT_USER, + L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, + KEY_SET_VALUE, &key) != ERROR_SUCCESS) { + return false; + } + const LONG result = RegDeleteValueW(key, kRunValueName); + RegCloseKey(key); + return result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND; +} + +} // namespace stfc diff --git a/src/auto_start.h b/src/auto_start.h new file mode 100644 index 0000000..1972214 --- /dev/null +++ b/src/auto_start.h @@ -0,0 +1,33 @@ +// "Start with Windows". +// +// Two mechanisms, because the app runs fine un-elevated but SetSystemCursor +// does not: +// * elevated -> a Task Scheduler task with highest privileges, so no UAC +// prompt per logon (what v1.3 attempted, minus the ATL dependency); +// * not elevated -> the HKCU Run key, which needs no elevation at all. +#pragma once + +#include "targetver.h" + +namespace stfc { + +class AutoStart { + public: + static constexpr const wchar_t* kTaskName = L"ShakeToFindCursor"; + static constexpr const wchar_t* kRunValueName = L"ShakeToFindCursor"; + + static bool IsTaskRegistered(); + static bool IsRunKeySet(); + static bool IsEnabled(); + // Chooses the mechanism based on the current token. + static bool Enable(); + static bool Disable(); + + private: + static bool EnableTask(); + static bool EnableRunKey(); + static bool DisableTask(); + static bool DisableRunKey(); +}; + +} // namespace stfc diff --git a/src/com_ptr.h b/src/com_ptr.h new file mode 100644 index 0000000..3dd7f33 --- /dev/null +++ b/src/com_ptr.h @@ -0,0 +1,56 @@ +#pragma once +// A 30-line smart pointer, so the Task Scheduler plumbing does not drag in ATL +// (atlbase.h) or comsupp.lib. Owning semantics only: attach on creation, +// Release on destruction, and no AddRef games beyond the copy paths we use. +#include + +namespace stfc { + +template +class ComPtr { + public: + ComPtr() = default; + ComPtr(std::nullptr_t) {} + ~ComPtr() { Reset(); } + + ComPtr(const ComPtr&) = delete; + ComPtr& operator=(const ComPtr&) = delete; + + // Takes ownership of an already add-ref'd pointer. + void Attach(T* pointer) { + Reset(); + pointer_ = pointer; + } + + T** Receive() { + Reset(); + return &pointer_; + } + + // QIs `other` into this pointer; returns false when the interface is absent. + template + bool From(Other* other, const IID& iid) { + Reset(); + if (!other) return false; + void* got = nullptr; + if (FAILED(other->QueryInterface(iid, &got))) return false; + pointer_ = static_cast(got); + return pointer_ != nullptr; + } + + T* Get() const { return pointer_; } + T* operator->() const { return pointer_; } + explicit operator bool() const { return pointer_ != nullptr; } + + void Reset() { + if (pointer_) { + pointer_->Release(); + pointer_ = nullptr; + } + } + + private: + T* pointer_ = nullptr; +}; + +} // namespace stfc diff --git a/src/find_overlay.cpp b/src/find_overlay.cpp new file mode 100644 index 0000000..796df27 --- /dev/null +++ b/src/find_overlay.cpp @@ -0,0 +1,555 @@ +#include "targetver.h" + +#include "find_overlay.h" + +#include +#include +#include +#include +#include + +#include "app_settings.h" + +namespace stfc { +namespace { + +constexpr wchar_t kClassName[] = L"ShakeToFindCursorOverlay"; +constexpr UINT kMsgRequest = WM_APP + 0x40; // a request is queued in the owner +constexpr UINT_PTR kAnimTimer = 0xEE1; +constexpr UINT kRippleFrameMs = 15; +constexpr UINT kSpotlightFrameMs = 33; +constexpr int kRingCount = 3; + +// White with a faint cool tint: reads as "highlight" on both dark and light +// content, and with a flat colour the premultiplied form is trivial. +constexpr uint8_t kTintR = 235, kTintG = 245, kTintB = 255; + +inline uint32_t Premultiplied(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + const uint32_t alpha = a; + return (alpha << 24) | ((static_cast(r) * alpha / 255u) << 16) | + ((static_cast(g) * alpha / 255u) << 8) | + (static_cast(b) * alpha / 255u); +} + +inline double Clamp01(double v) { return v < 0.0 ? 0.0 : (v > 1.0 ? 1.0 : v); } + +inline double EaseOutCubic(double t) { + const double u = 1.0 - t; + return 1.0 - u * u * u; +} + +int ScaleForDpi(int px, int dpi) { return MulDiv(px, dpi, 96); } + +// Everything one paint needs. +struct Frame { + uint32_t* bits = nullptr; + int width = 0; + int height = 0; + POINT center = {}; // client coordinates + int dpi = 96; + double progress = 0.0; // 0..1 through the whole effect +}; + +// Soft-edged ring. Only the annulus is visited, so a 600 px ripple touches a +// few tens of thousands of pixels per frame instead of the whole surface. +void DrawRing(const Frame& f, double radius, double thickness, uint8_t alpha) { + if (alpha == 0 || radius <= 0.0 || thickness <= 0.0) return; + const int cx = static_cast(f.center.x); + const int cy = static_cast(f.center.y); + const int reach = static_cast(radius + thickness * 0.5 + 1.0); + const int y_begin = std::max(0, cy - reach); + const int y_end = std::min(f.height - 1, cy + reach); + const int x_begin = std::max(0, cx - reach); + const int x_end = std::min(f.width - 1, cx + reach); + const double inv_thickness = 1.0 / thickness; + + for (int y = y_begin; y <= y_end; ++y) { + const double dy = y - cy; + uint32_t* row = f.bits + static_cast(y) * f.width; + for (int x = x_begin; x <= x_end; ++x) { + const double dx = x - cx; + const double distance = std::sqrt(dx * dx + dy * dy); + const double off = std::fabs(distance - radius) * inv_thickness; + if (off >= 0.5) continue; + const double edge = Clamp01((0.5 - off) * 2.0); + const uint8_t a = static_cast(alpha * edge + 0.5); + if (a == 0) continue; + uint32_t& pixel = row[x]; + // Overlapping rings take the brighter alpha rather than summing, which + // keeps crossings from blowing out to opaque. + if (a <= static_cast(pixel >> 24)) continue; + pixel = Premultiplied(kTintR, kTintG, kTintB, a); + } + } +} + +void DrawDisc(const Frame& f, double radius, uint8_t alpha) { + if (alpha == 0 || radius <= 0.0) return; + const int cx = static_cast(f.center.x); + const int cy = static_cast(f.center.y); + const int reach = static_cast(radius) + 1; + for (int y = std::max(0, cy - reach); + y <= std::min(f.height - 1, cy + reach); ++y) { + const double dy = y - cy; + uint32_t* row = f.bits + static_cast(y) * f.width; + for (int x = std::max(0, cx - reach); + x <= std::min(f.width - 1, cx + reach); ++x) { + const double dx = x - cx; + if (dx * dx + dy * dy > radius * radius) continue; + row[x] = Premultiplied(kTintR, kTintG, kTintB, alpha); + } + } +} + +void RenderRipple(const Frame& f, int max_radius) { + for (int k = 0; k < kRingCount; ++k) { + const double local = f.progress * 1.35 - k * 0.16; + if (local <= 0.0 || local >= 1.0) continue; + const double first = 0.18 * max_radius; + const double radius = first + (max_radius - first) * EaseOutCubic(local); + const double fade = 1.0 - local; + const uint8_t alpha = static_cast(215.0 * fade * fade + 0.5); + const double thickness = + static_cast(ScaleForDpi(7, f.dpi)) * (1.0 - 0.4 * local); + DrawRing(f, radius, thickness, alpha); + } + // The exact position stays marked while the rings fade, so the eye can lock + // onto the pointer instead of onto the halo. + const uint8_t marker = + static_cast(230.0 * (1.0 - f.progress) + 0.5); + DrawDisc(f, ScaleForDpi(3, f.dpi), marker); + DrawRing(f, ScaleForDpi(11, f.dpi) * (1.0 - 0.35 * f.progress), + static_cast(ScaleForDpi(2, f.dpi)), marker); +} + +void RenderSpotlight(const Frame& f, int hole_radius, uint8_t veil_alpha) { + const size_t pixels = static_cast(f.width) * f.height; + const uint32_t veil = static_cast(veil_alpha) << 24; + for (size_t i = 0; i < pixels; ++i) f.bits[i] = veil; + if (veil_alpha == 0) return; + + // A feathered edge is what makes it read as a spotlight instead of a punched + // rectangle. Smoothstep keeps the ramp cheap and free of seams. + const int edge = ScaleForDpi(34, f.dpi); + const int reach = hole_radius + edge + 1; + const double inner = static_cast(hole_radius); + const double span = static_cast(edge > 1 ? edge : 1); + const int cx = static_cast(f.center.x); + const int cy = static_cast(f.center.y); + for (int y = std::max(0, cy - reach); + y <= std::min(f.height - 1, cy + reach); ++y) { + const double dy = y - cy; + uint32_t* row = f.bits + static_cast(y) * f.width; + for (int x = std::max(0, cx - reach); + x <= std::min(f.width - 1, cx + reach); ++x) { + const double dx = x - cx; + const double distance = std::sqrt(dx * dx + dy * dy); + uint32_t& pixel = row[x]; + if (distance < inner) { + pixel = 0u; // fully clear: the pointer is plainly visible here + continue; + } + if (distance > inner + span) continue; // untouched veil + const double t = Clamp01((distance - inner) / span); + const double smooth = t * t * (3.0 - 2.0 * t); + const uint32_t a = + static_cast(static_cast(veil_alpha * smooth + 0.5)); + pixel = a << 24; + } + } + // A thin bright rim keeps the hole readable on dark content. + DrawRing(f, inner, static_cast(ScaleForDpi(2, f.dpi)), 90); +} + +// --------------------------------------------------------------------------- +// Per-window state. Owned by the overlay thread only. +// --------------------------------------------------------------------------- +struct Context { + FindOverlay* owner = nullptr; + HDC screen_dc = nullptr; + HDC mem_dc = nullptr; + HBITMAP dib = nullptr; + HBITMAP stock_bitmap = nullptr; // what the DC held before our DIB + void* bits = nullptr; + SIZE bitmap_size = {0, 0}; + RECT window_rect = {0, 0, 0, 0}; + POINT center_screen = {0, 0}; + POINT center_local = {0, 0}; + OverlayStyle style = OverlayStyle::kNone; + int duration_us = 900000; + int64_t start_us = 0; + int dpi = 96; + int max_radius = 300; + int last_spot_radius = -1; + uint8_t last_veil_alpha = 0; + bool frame_ready = false; +}; + +Context* FromHwnd(HWND hwnd) { + return reinterpret_cast(GetWindowLongPtrW(hwnd, GWLP_USERDATA)); +} + +void ReleaseBitmap(Context* ctx) { + if (!ctx->dib) return; + if (ctx->mem_dc && ctx->stock_bitmap) { + SelectObject(ctx->mem_dc, ctx->stock_bitmap); + } + DeleteObject(ctx->dib); + ctx->dib = nullptr; + ctx->bits = nullptr; + ctx->bitmap_size.cx = 0; + ctx->bitmap_size.cy = 0; +} + +bool EnsureBitmap(Context* ctx, int width, int height) { + if (ctx->dib && ctx->bitmap_size.cx == width && + ctx->bitmap_size.cy == height) { + return true; + } + ReleaseBitmap(ctx); + BITMAPINFO info = {}; + info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + info.bmiHeader.biWidth = width; + info.bmiHeader.biHeight = -height; // negative = top-down rows + info.bmiHeader.biPlanes = 1; + info.bmiHeader.biBitCount = 32; + info.bmiHeader.biCompression = BI_RGB; + ctx->dib = CreateDIBSection(ctx->screen_dc, &info, DIB_RGB_COLORS, &ctx->bits, + nullptr, 0); + if (!ctx->dib) { + LogCritical("overlay: CreateDIBSection(%d x %d) failed", width, height); + return false; + } + const HBITMAP previous = + static_cast(SelectObject(ctx->mem_dc, ctx->dib)); + if (!ctx->stock_bitmap) ctx->stock_bitmap = previous; + ctx->bitmap_size.cx = width; + ctx->bitmap_size.cy = height; + return true; +} + +// Ring and hole sizes follow the system DPI. Per-monitor DPI would be nicer on +// a mixed-DPI desktop (GetDpiForWindow exists from Windows 10 1607), but reaching +// it means casting a FARPROC to a typed function pointer, which is a /W4 +// warning in a project built with /WX; the effect is only cosmetic here, so the +// universally available system value is used. +int QueryDpi(HDC dc) { + const int dpi = GetDeviceCaps(dc, LOGPIXELSX); + return dpi > 0 ? dpi : 96; +} + +void Present(Context* ctx, HWND hwnd) { + BLENDFUNCTION blend = {}; + blend.BlendOp = AC_SRC_OVER; + blend.BlendFlags = 0; + blend.SourceConstantAlpha = 255; // per-pixel alpha carries everything + blend.AlphaFormat = AC_SRC_ALPHA; + POINT source = {0, 0}; + SIZE size = ctx->bitmap_size; + POINT target = {ctx->window_rect.left, ctx->window_rect.top}; + if (!UpdateLayeredWindow(hwnd, ctx->screen_dc, &target, &size, ctx->mem_dc, + &source, 0, &blend, ULW_ALPHA)) { + Logf("overlay: UpdateLayeredWindow failed (%lu)", GetLastError()); + } +} + +void ComputeGeometry(Context* ctx) { + RECT area = {0, 0, 1280, 720}; + MONITORINFO info = {}; + info.cbSize = sizeof(info); + const HMONITOR monitor = + MonitorFromPoint(ctx->center_screen, MONITOR_DEFAULTTONEAREST); + if (GetMonitorInfo(monitor, &info)) area = info.rcMonitor; + + ctx->max_radius = ScaleForDpi(300, ctx->dpi); + + if (ctx->style == OverlayStyle::kSpotlight) { + ctx->window_rect = area; + } else { + const int reach = ctx->max_radius + ScaleForDpi(40, ctx->dpi); + RECT rect = {ctx->center_screen.x - reach, ctx->center_screen.y - reach, + ctx->center_screen.x + reach, ctx->center_screen.y + reach}; + // Slide the surface back inside the monitor near screen edges so the rings + // are not chopped off; the centre is recomputed from the final rect. + if (rect.left < area.left) { + rect.right += area.left - rect.left; + rect.left = area.left; + } + if (rect.top < area.top) { + rect.bottom += area.top - rect.top; + rect.top = area.top; + } + if (rect.right > area.right) { + rect.left -= rect.right - area.right; + rect.right = area.right; + } + if (rect.bottom > area.bottom) { + rect.top -= rect.bottom - area.bottom; + rect.bottom = area.bottom; + } + // A surface bigger than the monitor (very high zoom) clamps from the left. + if (rect.left < area.left) rect.left = area.left; + if (rect.top < area.top) rect.top = area.top; + ctx->window_rect = rect; + } + ctx->center_local.x = ctx->center_screen.x - ctx->window_rect.left; + ctx->center_local.y = ctx->center_screen.y - ctx->window_rect.top; +} + +void StopAnimation(HWND hwnd, Context* ctx) { + KillTimer(hwnd, kAnimTimer); + ShowWindow(hwnd, SW_HIDE); + ctx->frame_ready = false; + ctx->last_spot_radius = -1; + ctx->last_veil_alpha = 0; +} + +void RenderOnce(HWND hwnd, Context* ctx) { + const int width = ctx->window_rect.right - ctx->window_rect.left; + const int height = ctx->window_rect.bottom - ctx->window_rect.top; + if (width <= 0 || height <= 0) return; + if (!EnsureBitmap(ctx, width, height)) return; + + const int64_t elapsed = NowUs() - ctx->start_us; + const double progress = Clamp01(static_cast(elapsed) / + static_cast(ctx->duration_us)); + + if (ctx->style == OverlayStyle::kSpotlight) { + const double full_hole = static_cast(ScaleForDpi(120, ctx->dpi)); + const int hole = static_cast( + std::max(8.0, full_hole * EaseOutCubic(Clamp01(progress / 0.30)))); + const double fade = progress < 0.75 ? 1.0 : 1.0 - (progress - 0.75) / 0.25; + const uint8_t veil = static_cast(165.0 * fade + 0.5); + if (hole == ctx->last_spot_radius && veil == ctx->last_veil_alpha && + ctx->frame_ready) { + return; // hold phase: nothing moved, skip the upload entirely + } + ctx->last_spot_radius = hole; + ctx->last_veil_alpha = veil; + + Frame frame; + frame.bits = static_cast(ctx->bits); + frame.width = width; + frame.height = height; + frame.center = ctx->center_local; + frame.dpi = ctx->dpi; + frame.progress = progress; + RenderSpotlight(frame, hole, veil); + } else { + // Clear to fully transparent, then draw. A 640x640 surface is ~0.2 ms. + std::memset(ctx->bits, 0, + static_cast(width) * height * sizeof(uint32_t)); + Frame frame; + frame.bits = static_cast(ctx->bits); + frame.width = width; + frame.height = height; + frame.center = ctx->center_local; + frame.dpi = ctx->dpi; + frame.progress = progress; + RenderRipple(frame, ctx->max_radius); + } + ctx->frame_ready = true; + Present(ctx, hwnd); +} + +void HandleRequest(HWND hwnd) { + Context* ctx = FromHwnd(hwnd); + if (!ctx || !ctx->owner) return; + + const FindOverlay::Request request = ctx->owner->TakePending(); + if (request.hide) { + StopAnimation(hwnd, ctx); + return; + } + if (!request.valid) return; + + ctx->center_screen = request.center; + ctx->style = request.style; + ctx->duration_us = std::max(150000, request.duration_ms * 1000); + ctx->start_us = NowUs(); + ctx->frame_ready = false; + ctx->last_spot_radius = -1; + ctx->last_veil_alpha = 0; + + if (!ctx->screen_dc) ctx->screen_dc = GetDC(nullptr); + ctx->dpi = QueryDpi(ctx->screen_dc); + + ComputeGeometry(ctx); + SetWindowPos(hwnd, HWND_TOPMOST, ctx->window_rect.left, ctx->window_rect.top, + ctx->window_rect.right - ctx->window_rect.left, + ctx->window_rect.bottom - ctx->window_rect.top, + SWP_NOACTIVATE | SWP_SHOWWINDOW); + RenderOnce(hwnd, ctx); + SetTimer(hwnd, kAnimTimer, + ctx->style == OverlayStyle::kSpotlight ? kSpotlightFrameMs + : kRippleFrameMs, + nullptr); +} + +} // namespace + +// --- FindOverlay ------------------------------------------------------------ + +FindOverlay::~FindOverlay() { + Shutdown(); + DeleteCriticalSection(&lock_); +} + +void FindOverlay::SetPending(const Request& request) { + EnterCriticalSection(&lock_); + pending_ = request; + LeaveCriticalSection(&lock_); +} + +FindOverlay::Request FindOverlay::TakePending() { + Request copy; + EnterCriticalSection(&lock_); + copy = pending_; + pending_ = Request(); + LeaveCriticalSection(&lock_); + return copy; +} + +void FindOverlay::StartThreadIfNeeded() { + if (thread_) return; + thread_ = CreateThread(nullptr, 0, &FindOverlay::ThreadEntry, this, 0, nullptr); + if (!thread_) LogCritical("overlay: could not start the render thread"); +} + +LRESULT CALLBACK FindOverlay::WndProc(HWND hwnd, UINT message, WPARAM w_param, + LPARAM l_param) { + if (message == WM_NCCREATE) { + auto* create = reinterpret_cast(l_param); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, + reinterpret_cast(create->lpCreateParams)); + return DefWindowProcW(hwnd, message, w_param, l_param); + } + + Context* ctx = FromHwnd(hwnd); + switch (message) { + case kMsgRequest: + HandleRequest(hwnd); + return 0; + case WM_TIMER: + if (w_param == kAnimTimer && ctx) { + RenderOnce(hwnd, ctx); + if (NowUs() - ctx->start_us >= ctx->duration_us) { + StopAnimation(hwnd, ctx); + if (ctx->owner) ctx->owner->MarkInactive(); + } + } + return 0; + case WM_ERASEBKGND: + return 1; // the layered surface is the only thing that shows + case WM_DESTROY: + if (ctx) { + StopAnimation(hwnd, ctx); + ReleaseBitmap(ctx); + if (ctx->mem_dc) DeleteDC(ctx->mem_dc); + if (ctx->screen_dc) ReleaseDC(nullptr, ctx->screen_dc); + EnterCriticalSection(ctx->owner->lock()); + ctx->owner->ClearHwndLocked(); + LeaveCriticalSection(ctx->owner->lock()); + delete ctx; + SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0); + } + PostQuitMessage(0); + return 0; + default: + break; + } + return DefWindowProcW(hwnd, message, w_param, l_param); +} + +DWORD WINAPI FindOverlay::ThreadEntry(LPVOID param) { + auto* self = static_cast(param); + + WNDCLASSEXW wc = {}; + wc.cbSize = sizeof(wc); + wc.lpfnWndProc = &FindOverlay::WndProc; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = kClassName; + if (!RegisterClassExW(&wc) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { + LogCritical("overlay: RegisterClassExW failed (%lu)", GetLastError()); + return 1; + } + + Context* ctx = new (std::nothrow) Context(); + if (!ctx) return 1; + ctx->owner = self; + ctx->mem_dc = CreateCompatibleDC(nullptr); + + // A 1x1 surface parked off screen: the real geometry is set per show, so no + // full-screen layered window exists while nothing is happening. + HWND hwnd = CreateWindowExW( + WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW | WS_EX_TOPMOST | + WS_EX_NOACTIVATE, + kClassName, L"", WS_POPUP, -32000, -32000, 1, 1, nullptr, nullptr, + wc.hInstance, ctx); + if (!hwnd) { + LogCritical("overlay: CreateWindowExW failed (%lu)", GetLastError()); + if (ctx->mem_dc) DeleteDC(ctx->mem_dc); + delete ctx; + return 1; + } + + bool has_pending = false; + EnterCriticalSection(&self->lock_); + self->hwnd_ = hwnd; + has_pending = self->pending_.valid || self->pending_.hide; + LeaveCriticalSection(&self->lock_); + if (has_pending) PostMessageW(hwnd, kMsgRequest, 0, 0); + + MSG msg = {}; + while (GetMessageW(&msg, nullptr, 0, 0) > 0) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + return 0; +} + +void FindOverlay::Show(POINT center, OverlayStyle style, int duration_ms) { + if (style == OverlayStyle::kNone) return; + Request request; + request.center = center; + request.style = style; + request.duration_ms = duration_ms; + request.valid = true; + SetPending(request); + active_ = true; + StartThreadIfNeeded(); + EnterCriticalSection(&lock_); + HWND target = hwnd_; + LeaveCriticalSection(&lock_); + if (target) PostMessageW(target, kMsgRequest, 0, 0); +} + +void FindOverlay::Hide() { + Request request; + request.hide = true; + SetPending(request); + active_ = false; + EnterCriticalSection(&lock_); + HWND target = hwnd_; + LeaveCriticalSection(&lock_); + if (target) PostMessageW(target, kMsgRequest, 0, 0); +} + +void FindOverlay::Shutdown() { + if (!thread_) return; + HWND target = nullptr; + EnterCriticalSection(&lock_); + target = hwnd_; + LeaveCriticalSection(&lock_); + if (target) { + PostMessageW(target, WM_CLOSE, 0, 0); + } else { + PostThreadMessageW(GetThreadId(thread_), WM_QUIT, 0, 0); + } + WaitForSingleObject(thread_, 2000); + CloseHandle(thread_); + thread_ = nullptr; + active_ = false; +} + +} // namespace stfc diff --git a/src/find_overlay.h b/src/find_overlay.h new file mode 100644 index 0000000..b0c76fb --- /dev/null +++ b/src/find_overlay.h @@ -0,0 +1,75 @@ +// Click-through highlight drawn around the pointer. +// +// Two effects share one window: "ripple" (expanding rings plus a marker dot) +// and "spotlight" (the monitor dims, a soft hole stays around the pointer). +// The window is layered, topmost and transparent to hit-testing, so it cannot +// steal focus or clicks. +// +// It lives on its own thread with its own message loop. That is the point: a +// full-screen UpdateLayeredWindow costs a few milliseconds, and doing that work +// on the thread that answers the low-level mouse hook would add visible input +// lag for every application on the desktop. +// +// Needs no elevation, which is why the effect survives even when pointer +// enlargement is unavailable. +#pragma once + +#include + +#include "app_settings.h" // OverlayStyle +#include "targetver.h" + +namespace stfc { + +class FindOverlay { + public: + FindOverlay() { InitializeCriticalSection(&lock_); } + ~FindOverlay(); + FindOverlay(const FindOverlay&) = delete; + FindOverlay& operator=(const FindOverlay&) = delete; + + struct Request { + POINT center = {0, 0}; + OverlayStyle style = OverlayStyle::kNone; + int duration_ms = 900; + bool valid = false; + bool hide = false; + }; + + // Draw the effect centred on `center` (physical screen pixels) for + // `duration_ms`. Cheap to call from any thread: it queues a request and + // posts one message. + void Show(POINT center, OverlayStyle style, int duration_ms); + + // Stop the effect now (used on exit and when the session locks). + void Hide(); + + bool Active() const { return active_.load(); } + + // Stops the worker thread. Safe to call more than once. + void Shutdown(); + + // Internal plumbing, public only so the window procedure and the thread + // entry point can reach them. + Request TakePending(); + void MarkInactive() { active_ = false; } + void ClearHwndLocked() { hwnd_ = nullptr; } + CRITICAL_SECTION* lock() { return &lock_; } + + private: + static DWORD WINAPI ThreadEntry(LPVOID param); + static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM w, LPARAM l); + + void StartThreadIfNeeded(); + void SetPending(const Request& request); + + // Guards the hand-off queue between the caller thread and the render + // thread; it exists for the whole lifetime of the object. + CRITICAL_SECTION lock_; + HWND hwnd_ = nullptr; // guarded by lock_; null until the thread is ready + Request pending_; + HANDLE thread_ = nullptr; + std::atomic active_{false}; +}; + +} // namespace stfc diff --git a/src/pointer_zoomer.cpp b/src/pointer_zoomer.cpp new file mode 100644 index 0000000..6e37288 --- /dev/null +++ b/src/pointer_zoomer.cpp @@ -0,0 +1,338 @@ +#include "targetver.h" + +#include "pointer_zoomer.h" + +#include + +#include "app_settings.h" +#include "win_util.h" + +// Some SDK versions omit the help/size cursors. +#ifndef OCR_HELP +#define OCR_HELP 32651 +#endif +#ifndef OCR_SIZE +#define OCR_SIZE 32640 +#endif + +namespace stfc { +namespace { + +// The system cursor ids an application can ask for. The stock names +// (IDC_ARROW & friends) are exactly MAKEINTRESOURCE of these ids, so listing +// the ids is enough. Everything an ordinary desktop shows is covered here; an +// application that installs its own cursor (a game, a CAD tool) is unaffected +// by us either way. +constexpr DWORD kSystemCursors[] = { + OCR_NORMAL, OCR_IBEAM, OCR_WAIT, OCR_CROSS, + OCR_UP, OCR_SIZE, OCR_SIZENWSE, OCR_SIZENESW, + OCR_SIZEWE, OCR_SIZENS, OCR_SIZEALL, OCR_NO, + OCR_HAND, OCR_APPSTARTING, OCR_HELP, +}; + +double EaseOutCubic(double t) { + const double u = 1.0 - t; + return 1.0 - u * u * u; +} + +double EaseInCubic(double t) { + return t * t * t; +} + +void WriteDirtyFlag(DWORD value) { + HKEY key = nullptr; + if (RegCreateKeyExW(HKEY_CURRENT_USER, AppSettings::KeyPath(), 0, nullptr, 0, + KEY_WRITE, nullptr, &key, nullptr) != ERROR_SUCCESS) { + return; + } + RegSetValueExW(key, L"CursorsDirty", 0, REG_DWORD, + reinterpret_cast(&value), sizeof(value)); + RegCloseKey(key); +} + +} // namespace + +PointerZoomer::~PointerZoomer() { + RestoreNow(); + FreeScaled(); + for (auto& slot : slots_) { + if (slot.original) DestroyCursor(slot.original); + } + slots_.clear(); +} + +bool PointerZoomer::Initialize() { + if (!IsElevated()) { + available_ = false; + LogCritical( + "pointer enlargement disabled: process is not elevated " + "(SetSystemCursor requires admin); the highlight overlay still works"); + return false; + } + SnapshotScheme(); + if (slots_.empty()) { + available_ = false; + Logf("no system cursors could be snapshotted"); + return false; + } + BuildLadder(); + available_ = true; + Logf("pointer zoomer ready: %d cursors x %d ladder steps", + static_cast(slots_.size()), kLadderSteps); + return true; +} + +void PointerZoomer::Configure() { + if (!available_) return; + FreeScaled(); + if (!modified_) SnapshotScheme(); + BuildLadder(); + if (modified_) { + current_step_ = -1; // re-apply: the ladder it was drawn from is gone + ApplyStep(kLadderSteps - 1); + } +} + +void PointerZoomer::RefreshScheme() { + if (modified_) return; // never snapshot a cursor we replaced ourselves + FreeScaled(); + SnapshotScheme(); + BuildLadder(); +} + +void PointerZoomer::SnapshotScheme() { + for (auto& slot : slots_) { + if (slot.original) DestroyCursor(slot.original); + } + slots_.clear(); + slots_.reserve(sizeof(kSystemCursors) / sizeof(kSystemCursors[0])); + for (const DWORD ocr_id : kSystemCursors) { + HCURSOR shared = LoadCursorW(nullptr, MAKEINTRESOURCEW(ocr_id)); + if (!shared) continue; + // The shared system cursor object belongs to user32; our own copy is what + // we later hand back to SetSystemCursor. + HCURSOR copy = CopyCursor(shared); + if (!copy) continue; + Slot slot; + slot.ocr_id = ocr_id; + slot.original = copy; + slots_.push_back(slot); + } +} + +SIZE PointerZoomer::OriginalSize(HCURSOR cursor) { + SIZE size = {32, 32}; + ICONINFO icon_info = {}; + if (!GetIconInfo(cursor, &icon_info)) return size; + + HBITMAP query = icon_info.hbmColor ? icon_info.hbmColor : icon_info.hbmMask; + BITMAP bm = {}; + if (query && GetObject(query, sizeof(BITMAP), &bm)) { + size.cx = bm.bmWidth; + // A monochrome cursor stores the AND and XOR planes stacked in one bitmap. + size.cy = icon_info.hbmColor ? bm.bmHeight : bm.bmHeight / 2; + } + if (icon_info.hbmColor) DeleteObject(icon_info.hbmColor); + if (icon_info.hbmMask) DeleteObject(icon_info.hbmMask); + if (size.cx <= 0 || size.cy <= 0) { + size.cx = 32; + size.cy = 32; + } + return size; +} + +void PointerZoomer::BuildLadder() { + const AppSettings& settings = AppSettings::Get(); + const double max_scale = settings.scale_percent / 100.0; + for (auto& slot : slots_) { + for (HCURSOR& handle : slot.scaled) { + if (handle) DestroyCursor(handle); + } + slot.scaled.assign(static_cast(kLadderSteps), nullptr); + + const SIZE native = OriginalSize(slot.original); + for (int step = 1; step < kLadderSteps; ++step) { + const double t = static_cast(step) / (kLadderSteps - 1); + const double scale = 1.0 + (max_scale - 1.0) * t; + const int w = static_cast(native.cx * scale + 0.5); + const int h = static_cast(native.cy * scale + 0.5); + if (w < 1 || h < 1) continue; + if (w == native.cx && h == native.cy) continue; // step 0 already covers it + HCURSOR scaled = static_cast( + CopyImage(slot.original, IMAGE_CURSOR, w, h, 0)); + // A null or the source itself means "nothing to gain here": fall back to + // the native cursor for that step instead of risking a double destroy. + slot.scaled[static_cast(step)] = + (scaled && scaled != slot.original) ? scaled : nullptr; + } + } +} + +void PointerZoomer::FreeScaled() { + for (auto& slot : slots_) { + for (HCURSOR& handle : slot.scaled) { + if (handle) DestroyCursor(handle); + handle = nullptr; + } + slot.scaled.clear(); + } +} + +void PointerZoomer::ApplyStep(int step) { + if (slots_.empty()) return; + // Restoring is allowed even once enlargement has been switched off, so a + // session that lost its privilege halfway cannot strand an enlarged cursor. + if (!available_ && step != 0) return; + if (step < 0) step = 0; + if (step >= kLadderSteps) step = kLadderSteps - 1; + if (step == current_step_) return; // nothing visible to change + + int applied = 0; + for (auto& slot : slots_) { + HCURSOR source = slot.original; + if (step > 0 && static_cast(step) < slot.scaled.size() && + slot.scaled[static_cast(step)]) { + source = slot.scaled[static_cast(step)]; + } + // SetSystemCursor takes ownership of the handle and destroys it, so it + // always gets a throwaway copy of our cached cursor. + HCURSOR copy = CopyCursor(source); + if (!copy) continue; + if (SetSystemCursor(copy, slot.ocr_id)) ++applied; + } + + current_step_ = step; + modified_ = step > 0; + + if (applied == 0) { + // Two empty passes in a row means the session refuses cursor changes + // (locked-down policy, another app owns the cursors). Stop trying and let + // the overlay carry the effect instead of spinning. + if (++failed_applies_ >= 2) { + LogCritical("SetSystemCursor failed; pointer enlargement turned off for " + "this session"); + available_ = false; + phase_ = Phase::kIdle; + modified_ = false; + current_step_ = 0; + MarkDirty(false); + } + } else { + failed_applies_ = 0; + } +} + +void PointerZoomer::Trigger() { + if (!available_) return; + const int64_t now = NowUs(); + switch (phase_) { + case Phase::kIdle: + MarkDirty(true); + phase_ = Phase::kGrow; + phase_start_us_ = now; + if (AppSettings::Get().grow_ms <= 0) { + ApplyStep(kLadderSteps - 1); + phase_ = Phase::kHold; + phase_start_us_ = now; + } + break; + case Phase::kGrow: + case Phase::kHold: + phase_start_us_ = now; // extend the highlight, do not restart it + break; + case Phase::kShrink: + // The user is still shaking mid-shrink: jump back to full size and hold. + ApplyStep(kLadderSteps - 1); + phase_ = Phase::kHold; + phase_start_us_ = now; + break; + } +} + +void PointerZoomer::Tick(int64_t now_us) { + if (phase_ == Phase::kIdle) return; + const AppSettings& settings = AppSettings::Get(); + const int64_t elapsed_us = now_us - phase_start_us_; + + switch (phase_) { + case Phase::kGrow: { + if (settings.grow_ms <= 0 || elapsed_us >= settings.grow_ms * 1000LL) { + phase_ = Phase::kHold; + phase_start_us_ = now_us; + ApplyStep(kLadderSteps - 1); + break; + } + const double t = + static_cast(elapsed_us) / (settings.grow_ms * 1000.0); + const int step = static_cast( + EaseOutCubic(t) * (kLadderSteps - 1) + 0.5); + if (step != current_step_) ApplyStep(step); + break; + } + case Phase::kHold: + if (elapsed_us >= settings.hold_ms * 1000LL) { + phase_ = Phase::kShrink; + phase_start_us_ = now_us; + } + break; + case Phase::kShrink: { + if (settings.shrink_ms <= 0 || + elapsed_us >= settings.shrink_ms * 1000LL) { + ApplyStep(0); + phase_ = Phase::kIdle; + current_step_ = 0; + MarkDirty(false); + break; + } + const double t = + static_cast(elapsed_us) / (settings.shrink_ms * 1000.0); + const double span = kLadderSteps - 1; + int step = static_cast(span - EaseInCubic(t) * span + 0.5); + if (step < 0) step = 0; + if (step != current_step_) ApplyStep(step); + break; + } + default: + break; + } +} + +void PointerZoomer::RestoreNow() { + if (modified_) ApplyStep(0); + phase_ = Phase::kIdle; + current_step_ = 0; + MarkDirty(false); +} + +void PointerZoomer::MarkDirty(bool dirty) { + WriteDirtyFlag(dirty ? 1u : 0u); +} + +bool PointerZoomer::NeedsHealing() { + HKEY key = nullptr; + if (RegOpenKeyExW(HKEY_CURRENT_USER, AppSettings::KeyPath(), 0, KEY_READ, + &key) != ERROR_SUCCESS) { + return false; + } + DWORD value = 0; + DWORD type = 0; + DWORD size = sizeof(value); + const BOOL dirty = RegQueryValueExW(key, L"CursorsDirty", nullptr, &type, + reinterpret_cast(&value), &size) == + ERROR_SUCCESS && + type == REG_DWORD && + size == sizeof(value) && value != 0; + RegCloseKey(key); + return dirty != FALSE; +} + +void PointerZoomer::HealIfNeeded() { + if (!NeedsHealing()) return; + // The previous instance died mid-animation; tell the system to reload the + // user's pointer scheme from its registry settings. + SystemParametersInfoW(SPI_SETCURSORS, 0, nullptr, SPIF_SENDCHANGE); + WriteDirtyFlag(0); + LogCritical("restored the pointer scheme left enlarged by a previous run"); +} + +} // namespace stfc diff --git a/src/pointer_zoomer.h b/src/pointer_zoomer.h new file mode 100644 index 0000000..7684af7 --- /dev/null +++ b/src/pointer_zoomer.h @@ -0,0 +1,97 @@ +// Pointer enlargement: snapshots the user's own pointer scheme, pre-scales it +// once, and animates between the cached sizes. +// +// Two deliberate design choices: +// * The scaled cursors are built *before* the shake happens. Growing a cursor +// then costs nothing but a SetSystemCursor call per cursor, instead of 13 +// CopyImage() calls per animation frame (what v1.3 did at 30 FPS, on the +// thread that also serves the low-level mouse hook). +// * The originals are the system cursors as they are right now, so a user +// with a custom pointer scheme gets their own scheme enlarged and restored +// rather than the stock Windows arrow. +#pragma once + +#include + +#include "targetver.h" + +namespace stfc { + +class PointerZoomer { + public: + PointerZoomer() = default; + ~PointerZoomer(); + PointerZoomer(const PointerZoomer&) = delete; + PointerZoomer& operator=(const PointerZoomer&) = delete; + + // Snapshot the current pointer scheme and pre-build the scaled ladder. + // Returns false when enlargement is not possible (not elevated), in which + // case every other method is a cheap no-op and the overlay takes over. + bool Initialize(); + + // A setting changed: re-snapshot and rebuild. + void Configure(); + + // The pointer scheme, theme or DPI changed while we were running. Only + // re-snapshots while idle, so we can never capture an already enlarged + // cursor and mistake it for the original. + void RefreshScheme(); + + // Start a highlight, or extend the running one. + void Trigger(); + + // Advance the animation; call at ~8 ms intervals while Active() is true. + void Tick(int64_t now_us); + + bool Active() const { return phase_ != Phase::kIdle; } + // Growing and shrinking need ~120 Hz attention; holding only needs to notice + // a timeout, so the caller can drop to a slow timer in that phase. + bool NeedsFastTick() const { + return phase_ == Phase::kGrow || phase_ == Phase::kShrink; + } + void RestoreNow(); + + bool available() const { return available_; } + + // SetSystemCursor survives our death, so a killed process could leave the + // whole session with giant pointers. Mark the session while enlarged and + // heal on the next start-up. + static bool NeedsHealing(); + static void HealIfNeeded(); + + // Number of cursors in the scheme (for logging/tests). + size_t slot_count() const { return slots_.size(); } + + private: + enum class Phase { kIdle, kGrow, kHold, kShrink }; + + // Animation resolution: step 0 is the native size, step kLadderSteps-1 the + // configured maximum. 13 steps over ~140 ms reads as a smooth zoom while + // keeping the pre-built set small. + static constexpr int kLadderSteps = 13; + + // `scaled` holds kLadderSteps handles; entry 0 stays null because step 0 + // means "the original cursor", which is what `original` already is. + struct Slot { + DWORD ocr_id = 0; + HCURSOR original = nullptr; // owned by us + std::vector scaled; + }; + + void SnapshotScheme(); + void BuildLadder(); + void FreeScaled(); + void ApplyStep(int step); + static SIZE OriginalSize(HCURSOR cursor); + static void MarkDirty(bool dirty); + + std::vector slots_; + Phase phase_ = Phase::kIdle; + int64_t phase_start_us_ = 0; + int current_step_ = 0; + bool available_ = false; + bool modified_ = false; + int failed_applies_ = 0; +}; + +} // namespace stfc diff --git a/src/shake_detector.h b/src/shake_detector.h new file mode 100644 index 0000000..447d8a9 --- /dev/null +++ b/src/shake_detector.h @@ -0,0 +1,422 @@ +// Shake detection for a stream of pointer positions. +// +// This header is deliberately free of Windows headers so the algorithm can be +// compiled and unit tested on any platform (see tests/shake_detector_test.cpp) +// and so the hot path stays allocation-free and branch-predictable: it is +// called from inside a WH_MOUSE_LL hook, where every microsecond spent here is +// input latency for the whole desktop. +#pragma once + +#include +#include +#include +#include + +namespace stfc { + +// One observation of the pointer position. Timestamps are supplied by the +// caller (monotonic microseconds) which keeps the detector deterministic and +// therefore testable. +struct PointerSample { + int64_t time_us = 0; + int x = 0; + int y = 0; +}; + +// All thresholds that decide what counts as a shake. +struct ShakeTuning { + // Upper bound on the history retained for one analysis pass. Work per + // sample is O(kSampleCap), never O(events_per_second), so a 8 kHz gaming + // mouse costs no more than a 125 Hz one. + static constexpr int kSampleCap = 128; + + // Sensitivity the tray menu labels "Standard". The field defaults below are + // exactly ForSensitivity(kDefaultSensitivity); a unit test enforces it. + static constexpr int kDefaultSensitivity = 55; + + // Everything is judged inside this sliding window. + int64_t window_us = 345000; + // A pause longer than this ends the streak (the user stopped moving). + int64_t stall_us = 76000; + // A single jump larger than this is treated as a pointer teleport (remote + // desktop, monitor switch, window snap tools) and resets the streak instead + // of counting as violent movement. + int max_step_px = 420; + // How many direction reversals are required inside the window. + int min_reversals = 3; + // One half-stroke must cover at least this much travel along the shake + // axis. This is what rejects sensor jitter and hand tremor. + int min_stroke_px = 48; + // A half-stroke must be completed within this time (rejects slow wobble). + int64_t max_stroke_us = 198000; + // Average speed of the counted strokes, in pixels/second. + double min_speed = 700.0; + // The shake still has to be *underway*: the newest reversal must be no + // older than this. Without it, a shake from half a second ago could fire + // while the pointer is already parked. + int64_t max_last_reversal_age_us = 202500; + // After a successful detection, ignore results for this long so one long + // shake cannot restart the animation dozens of times per second. + int64_t cooldown_us = 700000; + // Ignore windows with fewer samples than this (also avoids triggering on the + // first twitch after logon or after a resume). + int min_samples = 6; + // Input decimation: samples arriving faster than this are merged into the + // pending one. The effective interval is additionally stretched so the + // window never holds more than kSampleCap samples. + int64_t min_sample_interval_us = 2000; + // Retention cap, clamped to kSampleCap by the detector. + int max_samples = kSampleCap; + + int sample_cap() const { + return max_samples < kSampleCap ? max_samples : kSampleCap; + } + + // The window is sampled at most sample_cap() times. + int64_t effective_sample_interval_us() const { + const int cap = sample_cap(); + const int64_t spread = + cap > 1 ? window_us / static_cast(cap - 1) : window_us; + return std::max(min_sample_interval_us, spread); + } + + static int64_t RoundUs(double value, int64_t step) { + return static_cast(value / static_cast(step) + 0.5) * step; + } + + // Map a user-facing 1..100 sensitivity slider onto the thresholds. Low + // values demand big, deliberate shakes; high values answer to short + // flicks. Amplitude and speed carry the discrimination and the reversal + // count only has to reject one-off sweeps, so the window *grows* at the low + // end (a slow, wide shake is still a shake) instead of demanding a faster + // shake rate, which is what made the old build ignore big gentle shakes. + static ShakeTuning ForSensitivity(int sensitivity) { + const double t = static_cast(std::clamp(sensitivity, 1, 100) - 1) / + 99.0; + ShakeTuning s; + s.min_stroke_px = + static_cast(80.0 + (22.0 - 80.0) * t + 0.5); // px, rounded + s.min_reversals = t < 0.72 ? 3 : 2; + const double speed = 1000.0 + (450.0 - 1000.0) * t; + s.min_speed = static_cast(RoundUs(speed, 10)); + s.window_us = RoundUs(400000.0 + (300000.0 - 400000.0) * t, 5000); + s.max_stroke_us = RoundUs(220000.0 + (180000.0 - 220000.0) * t, 1000); + s.stall_us = RoundUs(60000.0 + (90000.0 - 60000.0) * t, 1000); + s.max_last_reversal_age_us = s.window_us / 2 + 30000; + return s; + } +}; + +// Diagnostics of the last evaluated window; handy for logging and tests. +struct ShakeStats { + int samples = 0; + int reversals = 0; + int good_reversals = 0; + int64_t travel_px = 0; + int64_t window_us = 0; + double speed = 0.0; + double axis_deg = 0.0; + int64_t us_since_trigger = -1; +}; + +// Counts fast, large direction reversals along the *principal axis* of the +// recent movement. +// +// Why not "count X flips plus Y flips" (what v1.3 did): a diagonal shake then +// needs both axes to flip, so real shakes are under-counted, while one smooth +// arc scores several free flips, so ordinary sweeps are over-counted. Worse, +// v1.3 judged a fixed 10-sample history, which at 500-8000 Hz report rates is +// 1-20 ms of motion - far too short to contain five reversals - so shaking +// simply did nothing unless the polling fallback was in use. +// +// Projecting onto the dominant direction of travel and running a hysteresis +// reversal counter on that scalar signal fixes all three problems and is +// cheaper than the per-axis version. +class ShakeDetector { + public: + explicit ShakeDetector(ShakeTuning tuning = ShakeTuning{}) + : tuning_(tuning) {} + + void SetTuning(const ShakeTuning& tuning) { + tuning_ = tuning; + Reset(); + } + const ShakeTuning& tuning() const { return tuning_; } + const ShakeStats& stats() const { return stats_; } + + // Forget the history. The cooldown survives on purpose: changing a setting + // must not let a shake in progress re-trigger instantly. + void Reset() { + head_ = 0; + count_ = 0; + have_pending_ = false; + stats_ = ShakeStats{}; + } + + // Feed one pointer observation. Returns true exactly once per detected + // shake, at the moment the final reversal is registered. + bool AddSample(const PointerSample& incoming) { + if (!have_pending_) { + have_pending_ = true; + pending_ = incoming; + Push(incoming); + return false; + } + + const int64_t dt = incoming.time_us - pending_.time_us; + if (dt <= 0) return false; // duplicated or non-monotonic stamp + + const int64_t dx = static_cast(incoming.x) - pending_.x; + const int64_t dy = static_cast(incoming.y) - pending_.y; + + // Stopped moving, or the pointer was warped: start over. + if (dt > tuning_.stall_us || + (tuning_.max_step_px > 0 && + ApproxHypot(dx, dy) > tuning_.max_step_px)) { + StartOver(incoming); + return false; + } + + pending_ = incoming; + // Decimate, but keep the newest position so the next accepted sample + // carries the full travel in between. + if (incoming.time_us - Last().time_us < + tuning_.effective_sample_interval_us()) { + return false; + } + + Push(incoming); + Prune(incoming.time_us); + return Evaluate(incoming.time_us); + } + + private: + static constexpr int kBuf = ShakeTuning::kSampleCap; + + // Integer octagon approximation of the Euclidean length: exact enough for a + // threshold test and free of sqrt() in the hook path. + static int64_t ApproxHypot(int64_t dx, int64_t dy) { + const int64_t ax = dx < 0 ? -dx : dx; + const int64_t ay = dy < 0 ? -dy : dy; + const int64_t hi = ax > ay ? ax : ay; + const int64_t lo = ax > ay ? ay : ax; + return hi + lo / 2; + } + + int cap() const { return tuning_.sample_cap(); } + + const PointerSample& At(int i) const { + return buf_[static_cast((head_ + i) % kBuf)]; + } + const PointerSample& Last() const { return At(count_ - 1); } + + void Push(const PointerSample& s) { + const int c = cap(); + if (count_ < c) { + buf_[static_cast((head_ + count_) % kBuf)] = s; + ++count_; + } else { + buf_[static_cast(head_)] = s; // overwrite oldest + head_ = (head_ + 1) % kBuf; + } + } + + void StartOver(const PointerSample& s) { + head_ = 0; + count_ = 0; + have_pending_ = true; + pending_ = s; + Push(s); + } + + void Prune(int64_t now_us) { + const int64_t oldest = now_us - tuning_.window_us; + while (count_ > 2 && At(0).time_us < oldest) { + head_ = (head_ + 1) % kBuf; + --count_; + } + } + + bool Evaluate(int64_t now_us) { + ShakeStats stats; + stats.samples = count_; + const int n = count_; + if (n < 2 || n < tuning_.min_samples) { + stats_ = stats; + return false; + } + + // ---- Pass 1: principal axis + total travel ------------------------- + // Dominant eigenvector of the 2x2 covariance of consecutive deltas is at + // angle 0.5 * atan2(2*Sxy, Sxx - Syy). + double sxx = 0.0, syy = 0.0, sxy = 0.0; + int64_t travel = 0; + for (int i = 1; i < n; ++i) { + const PointerSample& a = At(i - 1); + const PointerSample& b = At(i); + const double dx = static_cast(b.x - a.x); + const double dy = static_cast(b.y - a.y); + sxx += dx * dx; + syy += dy * dy; + sxy += dx * dy; + travel += ApproxHypot(b.x - a.x, b.y - a.y); + } + stats.travel_px = travel; + stats.window_us = Last().time_us - At(0).time_us; + + const double angle = + (sxx + syy > 0.0) ? 0.5 * std::atan2(2.0 * sxy, sxx - syy) : 0.0; + const double ux = std::cos(angle); + const double uy = std::sin(angle); + stats.axis_deg = angle * 57.29577951308232; // 180/pi + + // ---- Pass 2: hysteresis reversal counter on the projected signal ---- + double proj[kBuf]; + int64_t stamp[kBuf]; + proj[0] = static_cast(At(0).x) * ux + + static_cast(At(0).y) * uy; + stamp[0] = At(0).time_us; + for (int i = 1; i < n; ++i) { + const PointerSample& s = At(i); + proj[i] = static_cast(s.x) * ux + static_cast(s.y) * uy; + stamp[i] = s.time_us; + } + + const double amp = static_cast(tuning_.min_stroke_px); + double anchor = proj[0]; + int64_t anchor_t = stamp[0]; + double high = proj[0], low = proj[0]; + int64_t high_t = stamp[0], low_t = stamp[0]; + int dir = 0; // +1 along +axis, -1 against it, 0 undecided + int reversals = 0, good = 0; + double counted_len = 0.0; + int64_t counted_us = 0; + int64_t first_good_t = now_us; + int64_t last_reversal_t = stamp[0]; + + for (int i = 1; i < n; ++i) { + const double v = proj[i]; + if (dir == 0) { + if (v - low >= amp) { // first clear move was positive + dir = 1; + anchor = low; + anchor_t = low_t; + high = v; + high_t = stamp[i]; + } else if (high - v >= amp) { // first clear move was negative + dir = -1; + anchor = high; + anchor_t = high_t; + low = v; + low_t = stamp[i]; + } else { // still inside the hysteresis band + if (v > high) { + high = v; + high_t = stamp[i]; + } + if (v < low) { + low = v; + low_t = stamp[i]; + } + } + continue; + } + + double stroke_len = 0.0; + int64_t stroke_us = 0; + int64_t stroke_start_t = stamp[i]; + if (dir > 0) { + if (v > high) { // still extending the stroke + high = v; + high_t = stamp[i]; + continue; + } + if (high - v < amp) continue; // not a reversal yet + stroke_len = high - anchor; + stroke_us = high_t - anchor_t; + stroke_start_t = anchor_t; + last_reversal_t = high_t; + anchor = high; + anchor_t = high_t; + low = v; + low_t = stamp[i]; + dir = -1; + } else { + if (v < low) { + low = v; + low_t = stamp[i]; + continue; + } + if (v - low < amp) continue; + stroke_len = anchor - low; + stroke_us = low_t - anchor_t; + stroke_start_t = anchor_t; + last_reversal_t = low_t; + anchor = low; + anchor_t = low_t; + high = v; + high_t = stamp[i]; + dir = 1; + } + + ++reversals; + // A stroke only counts if it was long, fast and decisive. + const double speed_px_s = + stroke_us > 0 + ? stroke_len * 1000000.0 / static_cast(stroke_us) + : 0.0; + if (stroke_us > 0 && stroke_len >= amp && + stroke_us <= tuning_.max_stroke_us && speed_px_s >= tuning_.min_speed) { + if (good == 0) first_good_t = stroke_start_t; + ++good; + counted_len += stroke_len; + counted_us += stroke_us; + } + } + + stats.reversals = reversals; + stats.good_reversals = good; + const double speed = + counted_us > 0 + ? counted_len * 1000000.0 / static_cast(counted_us) + : 0.0; + stats.speed = speed; + + const bool underway = + now_us - last_reversal_t <= tuning_.max_last_reversal_age_us; + bool shake = good >= tuning_.min_reversals && underway && + speed >= tuning_.min_speed && + travel >= std::max(2 * tuning_.min_stroke_px, 120) && + (last_reversal_t - first_good_t) <= tuning_.window_us + + tuning_.max_stroke_us; + if (have_trigger_time_) { + stats.us_since_trigger = now_us - last_trigger_us_; + if (shake && now_us - last_trigger_us_ < tuning_.cooldown_us) { + shake = false; // still the same shake; stay quiet + } + } + + stats_ = stats; + if (!shake) return false; + + have_trigger_time_ = true; + last_trigger_us_ = now_us; + // Consume the streak: a *continued* shake has to build a fresh set of + // reversals, which is what makes the cooldown above extend the highlight + // instead of re-firing every frame. + StartOver(pending_); + return true; + } + + ShakeTuning tuning_; + PointerSample buf_[kBuf]; + int head_ = 0; + int count_ = 0; + PointerSample pending_; + bool have_pending_ = false; + int64_t last_trigger_us_ = 0; + bool have_trigger_time_ = false; + ShakeStats stats_; +}; + +} // namespace stfc diff --git a/src/targetver.h b/src/targetver.h new file mode 100644 index 0000000..86269f5 --- /dev/null +++ b/src/targetver.h @@ -0,0 +1,29 @@ +#pragma once + +// Pin the APIs we use to Windows 7 so nothing silently requires a newer SDK +// (the project advertises "Windows 7 or later"). Include this header before +// in every translation unit. + +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0601 +#endif +#ifndef WINVER +#define WINVER 0x0601 +#endif +#ifndef NTDDI_VERSION +#define NTDDI_VERSION 0x06010000 +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +// OCR_NORMAL & friends (the system cursor ids) are only declared with +// OEMRESOURCE in effect. +#ifndef OEMRESOURCE +#define OEMRESOURCE +#endif + +#include +#include diff --git a/src/win_util.cpp b/src/win_util.cpp new file mode 100644 index 0000000..a4eb395 --- /dev/null +++ b/src/win_util.cpp @@ -0,0 +1,88 @@ +#include "targetver.h" + +#include "win_util.h" + +#include + +namespace stfc { + +void AdoptDpiAwareness() { SetProcessDPIAware(); } + +bool IsElevated() { + BOOL elevated = FALSE; + HANDLE token = nullptr; + if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) { + TOKEN_ELEVATION info = {}; + DWORD size = sizeof(info); + if (GetTokenInformation(token, TokenElevation, &info, sizeof(info), &size)) { + elevated = info.TokenIsElevated; + } + CloseHandle(token); + } + return elevated != FALSE; +} + +void GetExePath(wchar_t* out, size_t cch) { + out[0] = L'\0'; + if (GetModuleFileNameW(nullptr, out, static_cast(cch)) == 0) { + out[0] = L'\0'; + } +} + +void RemoveFileName(wchar_t* path) { + wchar_t* slash = wcsrchr(path, L'\\'); + if (slash) *slash = L'\0'; +} + +bool RelaunchElevated(const wchar_t* arguments) { + wchar_t exe[MAX_PATH]; + GetExePath(exe, MAX_PATH); + if (exe[0] == L'\0') return false; + + SHELLEXECUTEINFOW info = {}; + info.cbSize = sizeof(info); + info.fMask = SEE_MASK_FLAG_DDEWAIT; + info.hwnd = nullptr; + info.lpVerb = L"runas"; + info.lpFile = exe; + info.lpParameters = (arguments && arguments[0]) ? arguments : nullptr; + info.lpDirectory = nullptr; + info.nShow = SW_HIDE; + if (!ShellExecuteExW(&info)) return false; + return info.hProcess != nullptr; +} + +bool IsForegroundFullscreen() { + HWND foreground = GetForegroundWindow(); + if (!foreground) return false; + + WINDOWPLACEMENT placement = {}; + placement.length = sizeof(placement); + if (GetWindowPlacement(foreground, &placement) && + placement.showCmd == SW_SHOWMINIMIZED) { + return false; + } + + // A layered or tool window covering the screen is an overlay, not a game. + const LONG_PTR style = GetWindowLongPtrW(foreground, GWL_STYLE); + const LONG_PTR ex_style = GetWindowLongPtrW(foreground, GWL_EXSTYLE); + if (ex_style & (WS_EX_LAYERED | WS_EX_TOOLWINDOW)) return false; + if ((style & (WS_CAPTION | WS_THICKFRAME)) == 0 && + (style & WS_POPUP) == 0) { + return false; + } + + RECT window = {}; + if (!GetWindowRect(foreground, &window)) return false; + HMONITOR monitor = MonitorFromWindow(foreground, MONITOR_DEFAULTTONEAREST); + MONITORINFO info = {}; + info.cbSize = sizeof(info); + if (!GetMonitorInfo(monitor, &info)) return false; + + return window.left <= info.rcMonitor.left && + window.top <= info.rcMonitor.top && + window.right >= info.rcMonitor.right && + window.bottom >= info.rcMonitor.bottom; +} + +} // namespace stfc diff --git a/src/win_util.h b/src/win_util.h new file mode 100644 index 0000000..05a65e9 --- /dev/null +++ b/src/win_util.h @@ -0,0 +1,32 @@ +// Windows helpers shared by the app modules. +#pragma once + +#include + +namespace stfc { + +// Called before the first window exists. The manifest is what actually requests +// PerMonitorV2 (with a system-DPI fallback); this is the Win7-era call that +// covers a build whose manifest was stripped. It is spelled without a +// GetProcAddress dance on purpose: casting a FARPROC to a typed function +// pointer is C4191, a /W4 warning, and this project builds with /WX. +void AdoptDpiAwareness(); + +// True when the process has an elevated token (SetSystemCursor needs it). +bool IsElevated(); + +// Full path of this executable. +void GetExePath(wchar_t* out, size_t cch); + +// Strips the file name in place, i.e. C:\Dir\App.exe -> C:\Dir +void RemoveFileName(wchar_t* path); + +// Re-launch this executable with "runas" (one UAC prompt). Returns true when a +// new process was started. +bool RelaunchElevated(const wchar_t* arguments); + +// True when the foreground window covers a whole monitor without a title bar +// (a game or a video). Used to avoid interrupting full screen content. +bool IsForegroundFullscreen(); + +} // namespace stfc diff --git a/tests/shake_detector_test.cpp b/tests/shake_detector_test.cpp new file mode 100644 index 0000000..5970b39 --- /dev/null +++ b/tests/shake_detector_test.cpp @@ -0,0 +1,474 @@ +// Host-side unit tests for the shake detector. +// +// Build and run: +// g++ -std=c++17 -O2 -Wall -Wextra tests/shake_detector_test.cpp -o tests +// ./tests +// or through CMake: cmake -S . -B build && cmake --build build && ctest +// +// Everything is deterministic: synthetic pointer traces with explicit +// timestamps, so a failure here is a real algorithmic regression and not a +// timing fluke. The last section replays the same traces through the v1.3 +// algorithm (copied below) to show what changed. +#include "../src/shake_detector.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using stfc::PointerSample; +using stfc::ShakeDetector; +using stfc::ShakeTuning; + +int g_checks = 0; +int g_failures = 0; + +void Check(bool ok, const std::string& what) { + ++g_checks; + if (!ok) { + ++g_failures; + std::printf(" FAIL %s\n", what.c_str()); + } +} + +// --------------------------------------------------------------------------- +// Synthetic pointer traces +// --------------------------------------------------------------------------- + +struct TraceOptions { + int64_t duration_us = 1200000; + int64_t interval_us = 8000; // ~125 Hz mouse + double freq_hz = 6.0; // shake rate + double amplitude_px = 90.0; // half peak-to-peak along the shake axis + double angle_deg = 0.0; // shake axis + double drift_px = 0.0; // slow drift along the axis + int center_x = 800; + int center_y = 500; + int noise_px = 0; // deterministic sensor noise + int64_t start_us = 1000000; +}; + +constexpr double kPi = 3.14159265358979323846; +constexpr double kUsPerSecond = 1e6; + +// Deterministic little PRNG, so the noise in a trace is the same everywhere. +int Jitter(uint32_t* state, int amplitude_px) { + *state = *state * 1103515245u + 12345u; + if (amplitude_px <= 0) return 0; + return static_cast(*state % (2 * static_cast(amplitude_px) + 1)) - + amplitude_px; +} + +// A back-and-forth trace along a line through (center_x, center_y). +// Shorthand for "the default shake, but sampled at this rate / along this +// angle", which keeps the case tables below readable. +TraceOptions WithInterval(int64_t interval_us) { + TraceOptions o; + o.interval_us = interval_us; + return o; +} + +TraceOptions WithAngle(double angle_deg) { + TraceOptions o; + o.angle_deg = angle_deg; + return o; +} + +std::vector MakeShake(const TraceOptions& o) { + std::vector out; + const double ca = std::cos(o.angle_deg * kPi / 180.0); + const double sa = std::sin(o.angle_deg * kPi / 180.0); + uint32_t rng = 12345u; + for (int64_t t = 0; t <= o.duration_us; t += o.interval_us) { + const double seconds = static_cast(t) / kUsPerSecond; + const double wave = std::sin(2.0 * kPi * o.freq_hz * seconds); + const double drift = o.drift_px * seconds / + (static_cast(o.duration_us) / kUsPerSecond); + const double along = o.amplitude_px * wave + drift; + const int dx = static_cast(along * ca) + Jitter(&rng, o.noise_px); + const int dy = static_cast(along * sa) + Jitter(&rng, o.noise_px); + out.push_back({o.start_us + t, o.center_x + dx, o.center_y + dy}); + } + return out; +} + +// One long, straight, very fast flick - the classic "reach across the screen". +std::vector MakeDash(int64_t interval_us, double px_per_s) { + std::vector out; + const int64_t start = 1000000; + for (int i = 0; i < 60; ++i) { + const double seconds = static_cast(i * interval_us) / kUsPerSecond; + out.push_back({start + i * interval_us, + 100 + static_cast(px_per_s * seconds), 400}); + } + return out; +} + +// A fast curved sweep: high speed, several sign changes per axis, no shake. +std::vector MakeArc(int64_t interval_us) { + std::vector out; + const int64_t start = 1000000; + for (int64_t t = 0; t <= 400000; t += interval_us) { + const double p = static_cast(t) / 400000.0; + const int x = 200 + static_cast(1400.0 * p); + const int y = 300 + static_cast(500.0 * std::sin(kPi * p)); + out.push_back({start + t, x, y}); + } + return out; +} + +// Pointer resting on a desk with an optical sensor ticking: sub-pixel jitter, +// enormous sample rate. +std::vector MakeJitter(int64_t interval_us) { + std::vector out; + uint32_t rng = 7u; + for (int64_t t = 0; t <= 1200000; t += interval_us) { + rng = rng * 1103515245u + 12345u; + const int dx = static_cast(rng % 5u) - 2; + rng = rng * 1103515245u + 12345u; + const int dy = static_cast(rng % 5u) - 2; + out.push_back({1000000 + t, 640 + dx, 360 + dy}); + } + return out; +} + +// Slow, wide wobble while dragging something: big amplitude, low speed. +std::vector MakeWobble() { + TraceOptions o; + o.freq_hz = 1.6; + o.amplitude_px = 110.0; + o.duration_us = 2000000; + return MakeShake(o); +} + +struct FeedResult { + int triggers = 0; + int64_t first_trigger_us = -1; + int64_t last_sample_us = 0; +}; + +FeedResult Feed(ShakeDetector& d, const std::vector& trace) { + FeedResult r; + for (const auto& s : trace) { + if (d.AddSample(s)) ++r.triggers; + r.last_sample_us = s.time_us; + } + if (r.triggers > 0) { + // Re-derive the first trigger time by replaying into a fresh detector. + ShakeDetector fresh(d.tuning()); + for (const auto& s : trace) { + if (fresh.AddSample(s)) { + r.first_trigger_us = s.time_us; + break; + } + } + } + return r; +} + +ShakeDetector DetectorForSensitivity(int sensitivity) { + return ShakeDetector(ShakeTuning::ForSensitivity(sensitivity)); +} + +// --------------------------------------------------------------------------- +// The v1.3 algorithm, reproduced so the improvement can be measured instead of +// asserted. Fixed 10-sample history, X/Y sign flips counted independently, +// average speed over the history, 500 ms window. +// --------------------------------------------------------------------------- +class LegacyDetector { + public: + bool AddSample(const PointerSample& s) { + const int64_t now_ms = s.time_us / 1000; + if (have_last_) { + const int64_t dt = now_ms - last_ms_; + if (dt > 0) { + hist_.push_back({s.x - last_x_, s.y - last_y_, static_cast(dt)}); + if (hist_.size() > kHistorySize) hist_.pop_front(); + } + } + last_x_ = s.x; + last_y_ = s.y; + last_ms_ = now_ms; + have_last_ = true; + return Detect(); + } + + private: + struct Movement { + int dx, dy, dt; + }; + static constexpr size_t kHistorySize = 10; + static constexpr int kMinDirectionChanges = 5; + static constexpr double kMinMovementSpeed = 800.0; + static constexpr int64_t kMaxTimeWindow = 500; + + bool Detect() const { + if (hist_.size() < kHistorySize) return false; + int changes = 0; + double total_speed = 0.0; + int64_t total_time = 0; + int last_x_dir = 0, last_y_dir = 0; + for (const auto& m : hist_) { + const int cx = m.dx > 0 ? 1 : (m.dx < 0 ? -1 : 0); + const int cy = m.dy > 0 ? 1 : (m.dy < 0 ? -1 : 0); + if (last_x_dir != 0 && cx != 0 && last_x_dir != cx) ++changes; + if (last_y_dir != 0 && cy != 0 && last_y_dir != cy) ++changes; + last_x_dir = cx; + last_y_dir = cy; + const double dd = static_cast(m.dx * m.dx + m.dy * m.dy); + const double dist = std::sqrt(dd); + total_speed += m.dt > 0 ? dist / m.dt * 1000.0 : 0.0; + total_time += m.dt; + } + if (total_time > kMaxTimeWindow) return false; + const double avg = total_speed / static_cast(hist_.size()); + return changes >= kMinDirectionChanges && avg >= kMinMovementSpeed; + } + + std::deque hist_; + int last_x_ = 0, last_y_ = 0; + int64_t last_ms_ = 0; + bool have_last_ = false; +}; + +int CountTriggers(const std::vector& trace, int max = 999) { + LegacyDetector d; + int n = 0; + for (const auto& s : trace) { + if (d.AddSample(s)) ++n; + if (n >= max) break; + } + return n; +} + +} // namespace + +int main() { + std::printf("ShakeToFindCursor detector tests\n"); + std::printf("================================\n"); + + // 1. A deliberate shake must trigger, at every mouse report rate. + { + std::printf("\n[1] shake -> trigger (report-rate independence)\n"); + const int64_t rates[] = {40000, 16000, 8000, 4000, 1000, 125}; // 25..8000 Hz + for (int64_t interval : rates) { + TraceOptions o; + o.interval_us = interval; + auto trace = MakeShake(o); + ShakeDetector d; + FeedResult r = Feed(d, trace); + char msg[160]; + std::snprintf(msg, sizeof(msg), + "triggers at %lld Hz sampling", + static_cast(1000000 / interval)); + Check(r.triggers >= 1, msg); + if (r.first_trigger_us >= 0) { + const int64_t latency_us = + r.first_trigger_us - trace.front().time_us; + std::snprintf(msg, sizeof(msg), + "latency %.0f ms at %lld Hz stays under 300 ms", + static_cast(latency_us) / 1000.0, + static_cast(1000000 / interval)); + Check(latency_us < 300000, msg); + } + } + } + + // 2. Cooldown: a 1.2 s shake must not re-arm more than a couple of times. + { + std::printf("\n[2] one long shake does not spam triggers\n"); + TraceOptions o; + o.duration_us = 1200000; + ShakeDetector d; + FeedResult r = Feed(d, MakeShake(o)); + std::printf(" info: %d triggers in 1.2 s of shaking\n", r.triggers); + Check(r.triggers >= 1 && r.triggers <= 3, "trigger count stays in 1..3"); + } + + // 3. Everyday pointer motion must stay silent. + { + std::printf("\n[3] false positives\n"); + struct Case { + const char* name; + std::vector trace; + }; + std::vector cases; + cases.push_back({"fast straight dash", MakeDash(8000, 4000.0)}); + cases.push_back({"fast curved sweep", MakeArc(8000)}); + cases.push_back({"sensor jitter at 1 kHz", MakeJitter(1000)}); + cases.push_back({"sensor jitter at 250 Hz", MakeJitter(4000)}); + cases.push_back({"slow wide wobble", MakeWobble()}); + for (const auto& c : cases) { + ShakeDetector d; + FeedResult r = Feed(d, c.trace); + Check(r.triggers == 0, c.name); + } + } + + // 4. A shake along any axis is still a shake (the projection property). + { + std::printf("\n[4] diagonal and vertical shakes\n"); + for (double angle : {0.0, 22.0, 35.0, 45.0, 71.0, 90.0, 150.0, -60.0}) { + TraceOptions o; + o.angle_deg = angle; + ShakeDetector d; + FeedResult r = Feed(d, MakeShake(o)); + char msg[96]; + std::snprintf(msg, sizeof(msg), "triggers at %.0f deg axis", angle); + Check(r.triggers >= 1, msg); + } + } + + // 5. Low amplitude / low speed shakes are rejected unless the user asks for + // high sensitivity. + { + std::printf("\n[5] sensitivity slider changes behaviour\n"); + TraceOptions small; + small.amplitude_px = 18.0; + small.freq_hz = 9.0; // a short, snappy flick + { + ShakeDetector d = DetectorForSensitivity(10); + Check(Feed(d, MakeShake(small)).triggers == 0, + "18 px flick ignored at sensitivity 10"); + } + { + ShakeDetector d = DetectorForSensitivity(100); + Check(Feed(d, MakeShake(small)).triggers >= 1, + "18 px flick honoured at sensitivity 100"); + } + TraceOptions big; + big.amplitude_px = 120.0; + { + ShakeDetector d = DetectorForSensitivity(1); + Check(Feed(d, MakeShake(big)).triggers >= 1, + "big shake honoured even at sensitivity 1"); + } + } + + // 6. Shake, stop, shake again -> the second shake is still honoured. + { + std::printf("\n[6] re-arm after the pointer rests\n"); + auto first = MakeShake(TraceOptions{}); + TraceOptions o; + o.start_us = first.back().time_us + 700000; // 700 ms of nothing + auto second = MakeShake(o); + ShakeDetector d; + int triggers = 0; + for (const auto& s : first) triggers += d.AddSample(s) ? 1 : 0; + for (const auto& s : second) triggers += d.AddSample(s) ? 1 : 0; + std::printf(" info: %d triggers for two separated shakes\n", triggers); + Check(triggers >= 2, "both shakes detected"); + } + + // 7. Pointer teleports (RDP, monitor switch, window snap) are not shakes. + { + std::printf("\n[7] warping and session oddities\n"); + { + std::vector trace; + int x = 100; + for (int i = 0; i < 40; ++i) { + trace.push_back({1000000 + i * 8000, x, 200}); + x += (i % 2 == 0) ? 3000 : -3000; // huge alternating jumps + } + ShakeDetector d; + Check(Feed(d, trace).triggers == 0, "alternating 3000 px warps ignored"); + } + { + // Non-monotonic / duplicated timestamps must not divide by zero. + std::vector trace = { + {1000000, 0, 0}, {1000000, 90, 0}, {999000, 0, 0}, + {1000000, 90, 0}, {1000000, 0, 0}, {1001000, 90, 0}}; + ShakeDetector d; + Feed(d, trace); + Check(true, "duplicate and backwards timestamps do not crash"); + } + } + + // 7b. The struct defaults must equal the shipped "Standard" preset, so the + // defaults the app uses and the preset the user can pick cannot drift. + { + std::printf("\n[7b] defaults track the Standard preset\n"); + const auto d = ShakeTuning{}; + const auto p = ShakeTuning::ForSensitivity(ShakeTuning::kDefaultSensitivity); + Check(d.window_us == p.window_us, "window_us"); + Check(d.min_stroke_px == p.min_stroke_px, "min_stroke_px"); + Check(d.min_reversals == p.min_reversals, "min_reversals"); + Check(d.min_speed == p.min_speed, "min_speed"); + Check(d.max_stroke_us == p.max_stroke_us, "max_stroke_us"); + Check(d.stall_us == p.stall_us, "stall_us"); + Check(d.max_last_reversal_age_us == p.max_last_reversal_age_us, + "max_last_reversal_age_us"); + } + + // 8. Stats sanity. + { + std::printf("\n[8] diagnostics\n"); + ShakeDetector d; + Feed(d, MakeShake(TraceOptions{})); + const auto& s = d.stats(); + std::printf( + " info: samples=%d reversals=%d good=%d travel=%lld px speed=%.0f px/s " + "axis=%.1f deg\n", + s.samples, s.reversals, s.good_reversals, + static_cast(s.travel_px), s.speed, s.axis_deg); + Check(s.samples > 0 && s.samples <= static_cast(ShakeTuning::kSampleCap), + "sample count stays inside the cap"); + Check(std::fabs(s.axis_deg) < 5.0, "axis of a horizontal shake is ~0 deg"); + } + + // 9. Cost, because this runs inside a WH_MOUSE_LL hook. + { + std::printf("\n[9] per-sample cost\n"); + auto trace = MakeShake(TraceOptions{}); + ShakeDetector d; + const auto t0 = std::chrono::steady_clock::now(); + constexpr int kLoops = 4000; + for (int i = 0; i < kLoops; ++i) { + d.Reset(); + for (const auto& s : trace) d.AddSample(s); + } + const auto us = std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0) + .count(); + const double per_sample = static_cast(us) / + static_cast(kLoops * trace.size()); + std::printf(" info: %.2f us per sample over %zu samples\n", per_sample, + trace.size()); + Check(per_sample < 5.0, "detector stays far below a mouse report period"); + } + + // 10. What the old algorithm did with the exact same traces. + { + std::printf("\n[10] v1.3 algorithm on the same traces (reference only)\n"); + struct Row { + const char* name; + std::vector trace; + }; + const std::vector rows = { + Row{"shake @125Hz", MakeShake(TraceOptions{})}, + Row{"shake @250Hz", MakeShake(WithInterval(4000))}, + Row{"shake @1kHz", MakeShake(WithInterval(1000))}, + Row{"shake @8kHz", MakeShake(WithInterval(125))}, + Row{"diagonal shake @8ms", MakeShake(WithAngle(45.0))}, + Row{"curved sweep", MakeArc(8000)}, + Row{"jitter @1kHz", MakeJitter(1000)}, + }; + std::printf(" %-22s %-16s %-16s\n", "trace", "v1.3 triggers", "new triggers"); + for (const auto& r : rows) { + ShakeDetector d; + const int new_n = Feed(d, r.trace).triggers; + const int old_n = CountTriggers(r.trace); + std::printf(" %-22s %-16s %-16s\n", r.name, + std::to_string(old_n).c_str(), std::to_string(new_n).c_str()); + } + } + + std::printf("\n================================\n%d checks, %d failures\n", + g_checks, g_failures); + return g_failures == 0 ? 0 : 1; +}