├── .gitattributes ├── .github └── FUNDING.yml ├── ThreeFingerDrag ├── small.ico ├── ThreeFingerDrag.rc ├── ThreeFingerDrag.ico ├── targetver.h ├── mouse │ ├── cursor.h │ └── cursor.cpp ├── ThreeFingerDrag.h ├── framework.h ├── data │ ├── touch_data.h │ └── ini.h ├── resource.h ├── notification │ ├── popups.h │ ├── popups.cpp │ └── wintoastlib.h ├── event │ ├── events.h │ └── touch_events.h ├── logging │ ├── logger.h │ └── logger.cpp ├── gesture │ ├── touch_processor.h │ ├── event_listeners.h │ └── touch_processor.cpp ├── config │ ├── globalconfig.h │ └── globalconfig.cpp ├── ThreeFingerDrag.vcxproj.filters ├── task │ └── task_scheduler.h ├── application.h ├── ThreeFingerDrag.vcxproj └── ThreeFingerDrag.cpp ├── ThreeFingerDrag.sln ├── inno_script.iss ├── README.md ├── .gitignore └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: austinnixholm 2 | custom: "https://paypal.me/austinnixholm" 3 | -------------------------------------------------------------------------------- /ThreeFingerDrag/small.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/austinnixholm/ThreeFingerDrag/HEAD/ThreeFingerDrag/small.ico -------------------------------------------------------------------------------- /ThreeFingerDrag/ThreeFingerDrag.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/austinnixholm/ThreeFingerDrag/HEAD/ThreeFingerDrag/ThreeFingerDrag.rc -------------------------------------------------------------------------------- /ThreeFingerDrag/ThreeFingerDrag.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/austinnixholm/ThreeFingerDrag/HEAD/ThreeFingerDrag/ThreeFingerDrag.ico -------------------------------------------------------------------------------- /ThreeFingerDrag/targetver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // // Including SDKDDKVer.h defines the highest available Windows platform. 4 | // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and 5 | // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. 6 | #include 7 | -------------------------------------------------------------------------------- /ThreeFingerDrag/mouse/cursor.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../framework.h" 3 | 4 | class Cursor 5 | { 6 | public: 7 | static void SimulateClick(const DWORD click_flags); 8 | static void MoveCursor(const double delta_x, const double delta_y); 9 | static void LeftMouseDown(); 10 | static void LeftMouseUp(); 11 | static bool IsLeftMouseDown(); 12 | }; 13 | -------------------------------------------------------------------------------- /ThreeFingerDrag/ThreeFingerDrag.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "resource.h" 8 | #include "logging/logger.h" 9 | #include "task/task_scheduler.h" 10 | #include "application.h" 11 | #include "notification/wintoastlib.h" 12 | #include "notification/popups.h" 13 | #include 14 | -------------------------------------------------------------------------------- /ThreeFingerDrag/framework.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "targetver.h" 4 | #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers 5 | // Windows Header Files 6 | #include 7 | #include 8 | // C RunTime Header Files 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | #pragma comment(lib, "hid.lib") 16 | -------------------------------------------------------------------------------- /ThreeFingerDrag/data/touch_data.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | struct TouchContact 5 | { 6 | int contact_id; 7 | int x; 8 | int y; 9 | mutable bool on_surface; 10 | bool has_x_bounds; 11 | bool has_y_bounds; 12 | int minimum_x; 13 | int maximum_x; 14 | int minimum_y; 15 | int maximum_y; 16 | }; 17 | 18 | struct TouchInputData 19 | { 20 | std::vector contacts; 21 | int contact_count = 0; 22 | bool can_perform_gesture = false; 23 | }; 24 | -------------------------------------------------------------------------------- /ThreeFingerDrag/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | 4 | #define IDS_APP_TITLE 103 5 | #define IDS_SETTINGS_TITLE 104 6 | 7 | #define IDI_THREEFINGERDRAG 107 8 | #define IDI_SMALL 108 9 | #define IDC_THREEFINGERDRAG 109 10 | #define IDC_SETTINGS 110 11 | #ifndef IDC_STATIC 12 | #define IDC_STATIC -1 13 | #endif 14 | // Next default values for new objects 15 | // 16 | #ifdef APSTUDIO_INVOKED 17 | #ifndef APSTUDIO_READONLY_SYMBOLS 18 | 19 | #define _APS_NO_MFC 130 20 | #define _APS_NEXT_RESOURCE_VALUE 129 21 | #define _APS_NEXT_COMMAND_VALUE 32771 22 | #define _APS_NEXT_CONTROL_VALUE 1000 23 | #define _APS_NEXT_SYMED_VALUE 110 24 | #endif 25 | #endif 26 | -------------------------------------------------------------------------------- /ThreeFingerDrag/notification/popups.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | /** 5 | * \brief A class for displaying various popups in the application. 6 | */ 7 | class Popups 8 | { 9 | public: 10 | /** 11 | * \brief Displays an error message box with the given message and logs it as an error. 12 | * \param message The message to be displayed. 13 | */ 14 | static void DisplayErrorMessage(const std::string& message); 15 | static void DisplayInfoMessage(const std::string& message); 16 | static bool DisplayPrompt(const std::string& message, const std::string& title); 17 | static bool DisplayWarningPrompt(const std::string& message, const std::string& title); 18 | static void ShowToastNotification(const std::wstring& message, const std::wstring& title); 19 | }; 20 | -------------------------------------------------------------------------------- /ThreeFingerDrag/event/events.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class EventArgs 6 | { 7 | public: 8 | virtual ~EventArgs() 9 | { 10 | } 11 | }; 12 | 13 | template 14 | class Event 15 | { 16 | public: 17 | using EventHandler = std::function; 18 | 19 | void AddListener(EventHandler listener) 20 | { 21 | eventHandlers.push_back(listener); 22 | } 23 | 24 | void RemoveListener(EventHandler listener) 25 | { 26 | eventHandlers.erase(std::remove(eventHandlers.begin(), eventHandlers.end(), listener), eventHandlers.end()); 27 | } 28 | 29 | void RaiseEvent(T args) 30 | { 31 | for (auto& handler : eventHandlers) 32 | handler(args); 33 | } 34 | 35 | private: 36 | std::vector eventHandlers; 37 | }; 38 | -------------------------------------------------------------------------------- /ThreeFingerDrag/event/touch_events.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "events.h" 4 | #include "../data/touch_data.h" 5 | 6 | class TouchActivityEventArgs : public EventArgs 7 | { 8 | public: 9 | TouchInputData* data; 10 | std::vector previous_data; 11 | std::chrono::time_point time; 12 | 13 | TouchActivityEventArgs( 14 | std::chrono::time_point time, 15 | TouchInputData* data, 16 | const std::vector& previous_data) 17 | : data(data), previous_data(previous_data), time(time) 18 | { 19 | } 20 | }; 21 | 22 | class TouchUpEventArgs : public TouchActivityEventArgs 23 | { 24 | public: 25 | TouchUpEventArgs( 26 | std::chrono::time_point time, 27 | TouchInputData* data, 28 | const std::vector& previous_data) 29 | : TouchActivityEventArgs{time, data, previous_data} 30 | { 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /ThreeFingerDrag/mouse/cursor.cpp: -------------------------------------------------------------------------------- 1 | #include "cursor.h" 2 | 3 | void Cursor::SimulateClick(const DWORD click_flags) 4 | { 5 | INPUT input; 6 | input.type = INPUT_MOUSE; 7 | input.mi.dx = 0; 8 | input.mi.dy = 0; 9 | input.mi.mouseData = 0; 10 | input.mi.dwFlags = click_flags; 11 | input.mi.time = 0; 12 | input.mi.dwExtraInfo = 0; 13 | SendInput(1, &input, sizeof(INPUT)); 14 | } 15 | 16 | void Cursor::MoveCursor(const double delta_x, const double delta_y) 17 | { 18 | // Prepare an INPUT structure for the SendInput function to cause a relative mouse move. 19 | INPUT input; 20 | input.type = INPUT_MOUSE; 21 | 22 | input.mi.dx = delta_x; 23 | input.mi.dy = delta_y; 24 | input.mi.mouseData = 0; 25 | input.mi.dwFlags = MOUSEEVENTF_MOVE; 26 | input.mi.time = 0; 27 | input.mi.dwExtraInfo = 0; 28 | 29 | SendInput(1, &input, sizeof(INPUT)); 30 | } 31 | 32 | void Cursor::LeftMouseDown() 33 | { 34 | SimulateClick(MOUSEEVENTF_LEFTDOWN); 35 | } 36 | 37 | void Cursor::LeftMouseUp() 38 | { 39 | if (!IsLeftMouseDown()) 40 | return; 41 | SimulateClick(MOUSEEVENTF_LEFTUP); 42 | } 43 | 44 | bool Cursor::IsLeftMouseDown() 45 | { 46 | return GetAsyncKeyState(VK_LBUTTON) & 0x8000; 47 | } -------------------------------------------------------------------------------- /ThreeFingerDrag.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33414.496 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ThreeFingerDrag", "ThreeFingerDrag\ThreeFingerDrag.vcxproj", "{2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}.Debug|x64.ActiveCfg = Debug|x64 17 | {2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}.Debug|x64.Build.0 = Debug|x64 18 | {2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}.Debug|x86.ActiveCfg = Debug|Win32 19 | {2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}.Debug|x86.Build.0 = Debug|Win32 20 | {2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}.Release|x64.ActiveCfg = Release|x64 21 | {2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}.Release|x64.Build.0 = Release|x64 22 | {2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}.Release|x86.ActiveCfg = Release|Win32 23 | {2F6AB4A4-893D-4FBD-AE32-6EDB569D435A}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {26D44773-7646-453B-B3CD-132DFF5F66A7} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /inno_script.iss: -------------------------------------------------------------------------------- 1 | #define MyAppName "ThreeFingerDrag" 2 | #define MyAppVersion "1.2.7" 3 | #define MyAppPublisher "Austin Nixholm" 4 | #define MyAppURL "https://github.com/austinnixholm/ThreeFingerDrag" 5 | #define MyAppExeName "ThreeFingerDrag.exe" 6 | 7 | [Setup] 8 | AppId={{1D896AD4-D9F6-4A5F-9F96-69B369E0A015}} 9 | AppName={#MyAppName} 10 | AppVersion={#MyAppVersion} 11 | AppVerName="{#MyAppName} {#MyAppVersion}" 12 | AppPublisher={#MyAppPublisher} 13 | AppPublisherURL={#MyAppURL} 14 | AppSupportURL={#MyAppURL} 15 | AppUpdatesURL={#MyAppURL} 16 | DefaultDirName={pf}\{#MyAppName} 17 | DefaultGroupName={#MyAppName} 18 | DisableProgramGroupPage=yes 19 | LicenseFile=LICENSE 20 | OutputDir=installers 21 | OutputBaseFilename="ThreeFingerDrag.Setup.{#MyAppVersion}" 22 | SetupIconFile="{#MyAppName}\{#MyAppName}.ico" 23 | UninstallDisplayIcon="{app}\{#MyAppName}.ico" 24 | Compression=lzma 25 | SolidCompression=yes 26 | WizardStyle=modern 27 | 28 | [Languages] 29 | Name: "english"; MessagesFile: "compiler:Default.isl" 30 | 31 | [Files] 32 | Source: "build\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion; AfterInstall: WriteInstallPathToFile 33 | Source: "{#MyAppName}\{#MyAppName}.ico"; DestDir: "{app}"; Flags: ignoreversion 34 | Source: "{#MyAppName}\small.ico"; DestDir: "{app}"; Flags: ignoreversion 35 | ; NOTE: Don't use "Flags: ignoreversion" on any shared system files 36 | 37 | [Icons] 38 | Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}" 39 | Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon 40 | 41 | [Tasks] 42 | Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked 43 | 44 | [Run] 45 | Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#MyAppName}}"; Flags: nowait postinstall skipifsilent 46 | 47 | [Code] 48 | procedure WriteInstallPathToFile; 49 | var 50 | FilePath: string; 51 | begin 52 | FilePath := ExpandConstant('{localappdata}\tfd_install_location.txt'); 53 | // Write the installation path to the text file, overwriting any existing file 54 | SaveStringToFile(FilePath, ExpandConstant('{app}'), False); 55 | end; 56 | -------------------------------------------------------------------------------- /ThreeFingerDrag/logging/logger.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | /** 9 | * @brief A logger class for writing log messages to a file. 10 | */ 11 | class Logger 12 | { 13 | public: 14 | /** 15 | * @brief Writes an info log message to the file. 16 | * @param message The log message. 17 | */ 18 | void Info(const std::string& message); 19 | 20 | /** 21 | * @brief Writes a debug log message to the file. 22 | * @param message The log message. 23 | */ 24 | void Debug(const std::string& message); 25 | 26 | /** 27 | * @brief Writes a warning log message to the file. 28 | * @param message The log message. 29 | */ 30 | void Warning(const std::string& message); 31 | 32 | /** 33 | * @brief Writes an error log message to the file. 34 | * @param message The log message. 35 | */ 36 | void Error(const std::string& message); 37 | 38 | /** 39 | * @brief Destructor that closes the log file. 40 | */ 41 | ~Logger(); 42 | 43 | Logger(const Logger&) = delete; 44 | Logger& operator=(const Logger&) = delete; 45 | Logger(Logger&&) noexcept = default; 46 | Logger& operator=(Logger&&) noexcept = default; 47 | 48 | /** 49 | * @brief Returns the singleton instance of the logger. 50 | * @return The logger instance. 51 | */ 52 | static Logger& GetInstance(); 53 | 54 | private: 55 | /** 56 | * @brief Constructs the logger and opens the file for writing log lines to. 57 | * 58 | * If the folder or file do not exist, they will be created. 59 | */ 60 | Logger(const std::string& logFileName); 61 | 62 | std::ofstream log_file_; ///< The log file stream. 63 | std::string log_file_path_; ///< The path to the log file. 64 | 65 | /** 66 | * @brief Writes a log message to the file with the specified log type. 67 | * @param type The log type, such as [INFO], [DEBUG], [WARNING], or [ERROR]. 68 | * @param message The log message. 69 | */ 70 | void WriteLog(const std::string& type, const std::string& message); 71 | }; 72 | 73 | #define INFO(msg) Logger::GetInstance().Info(msg) 74 | #define DEBUG(msg) Logger::GetInstance().Debug(msg) 75 | #define WARNING(msg) Logger::GetInstance().Warning(msg) 76 | #define ERROR(msg) Logger::GetInstance().Error(msg) 77 | -------------------------------------------------------------------------------- /ThreeFingerDrag/gesture/touch_processor.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../framework.h" 3 | #include "event_listeners.h" 4 | #include 5 | #include 6 | 7 | namespace Touchpad 8 | { 9 | constexpr auto INIT_VALUE = 65535; 10 | constexpr auto CONTACT_ID_MAXIMUM = 64; 11 | constexpr auto CONTACT_ID_MINIMUM = 0; 12 | constexpr auto USAGE_PAGE_DIGITIZER_VALUES = 0x01; 13 | constexpr auto USAGE_PAGE_DIGITIZER_INFO = 0x0D; 14 | constexpr auto USAGE_DIGITIZER_SCAN_TIME = 0x56; 15 | constexpr auto USAGE_DIGITIZER_CONTACT_COUNT = 0x54; 16 | constexpr auto USAGE_DIGITIZER_CONTACT_ID = 0x51; 17 | constexpr auto USAGE_DIGITIZER_X_COORDINATE = 0x30; 18 | constexpr auto USAGE_DIGITIZER_Y_COORDINATE = 0x31; 19 | 20 | 21 | /** 22 | * \brief Class that processes touch input data to enable three-finger drag functionality. 23 | */ 24 | class TouchProcessor 25 | { 26 | public: 27 | TouchProcessor(); 28 | 29 | /** 30 | * @brief Retrieves touch data from the given raw input handle. 31 | * @param hRawInputHandle Handle to the raw input data. 32 | * @return The retrieved touch data. 33 | */ 34 | void ProcessRawInput(HRAWINPUT hRawInputHandle); 35 | void ClearContacts(); 36 | 37 | TouchProcessor(const TouchProcessor& other) = delete; // Disallow copy constructor 38 | TouchProcessor(TouchProcessor&& other) noexcept = delete; // Disallow move constructor 39 | TouchProcessor& operator=(const TouchProcessor& other) = delete; // Disallow copy assignment 40 | TouchProcessor& operator=(TouchProcessor&& other) noexcept = delete; // Disallow move assignment 41 | ~TouchProcessor() = default; // Default destructor 42 | 43 | private: 44 | void UpdateTouchContactsState(const std::vector& received_contacts); 45 | void RaiseEventsIfNeeded(); 46 | void LogEventDetails(bool touch_up_event, const std::chrono::high_resolution_clock::time_point& time) const; 47 | 48 | static bool ValueWithinRange(int value, int minimum, int maximum); 49 | static std::string DebugPoints(const std::vector& data); 50 | static int CountTouchPointsMakingContact(const std::vector& points); 51 | 52 | EventListeners::TouchActivityListener activity_listener_; 53 | EventListeners::TouchUpListener touch_up_listener_; 54 | 55 | Event touch_activity_event_; 56 | Event touch_up_event_; 57 | std::vector parsed_contacts_; 58 | mutable std::mutex contacts_mutex_; 59 | 60 | GlobalConfig* config; 61 | }; 62 | } 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Release](https://img.shields.io/github/v/release/austinnixholm/ThreeFingerDrag?label=Download%20version)](https://github.com/austinnixholm/ThreeFingerDrag/releases/latest) 2 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 3 | ![GitHub all releases](https://img.shields.io/github/downloads/austinnixholm/threefingerdrag/total) 4 | 5 | [![TFD-GH-DARK-512.png](https://i.postimg.cc/RZXdx8qh/TFD-GH-DARK-512.png)](https://postimg.cc/hXQT92LR#gh-dark-mode-only) 6 | [![TFD-GH-LIGHT-512.png](https://i.postimg.cc/ZYW6WnnT/TFD-GH-LIGHT-512.png)](https://postimg.cc/14RFWmGH#gh-light-mode-only) 7 | 8 | Emulates the macOS three-finger-drag feature on your Windows precision touchpad. Simply download and run, minimal setup required. 9 | 10 | ## Features 11 | 12 | * Easily configurable 13 | * Lightweight and minimalistic design 14 | * Accessible menu through the system tray 15 | 16 | ## Usage 17 | 18 | 1. Download & install the [latest release](https://github.com/austinnixholm/ThreeFingerDrag/releases/latest) from the repository. 19 | 3. Launch the program, and you will be prompted to run ThreeFingerDrag on Windows startup. This is optional, and you can always choose to enable or disable this feature later. 20 | 4. ThreeFingerDrag will now run in the background of the system. You can configure the program through the system tray menu, which is accessible by clicking the ThreeFingerDrag icon in the notification area of the taskbar. 21 | 22 |

23 | 24 |

25 | 26 | **NOTE:** It's recommended to remove any existing three-finger swipe gestures within `Touchpad Settings` in order to prevent possible interference. 27 | 28 | #### Upcoming Enhancements (v1.3.0) 29 | 30 | - Elevated mode to start the program with admin privileges (manual process is required for now). 31 | - Optional customization of activation & deactivation conditions. 32 | 33 | ## Build with Visual Studio 34 | 35 | You can build the project using Visual Studio 2017 or newer. 36 | 37 | 1. Open the ThreeFingerDrag.sln file in Visual Studio. 38 | 2. Select the "Release" configuration and click "Build Solution". 39 | 3. The built executable will be located in the `/build/` directory in the base project folder. 40 | 41 | ## Create Installer via [Inno Setup](https://jrsoftware.org/isinfo.php) 42 | 43 | 1. After building the executable, locate the `inno_script.iss` file in the base project folder. 44 | 2. Right click on the inno_script.iss file and select "Compile" or open the file in the InnoSetup editor and compile it from there. 45 | 3. The created installer executable will be located in the `/installers/` directory in the base project folder. 46 | 47 | ## Credits 48 | 49 | * [mohabouje/WinToast][1] - A library for displaying toast notifications on Windows 8 and later. 50 | * [pulzed/mINI][2] - A library for manipulating INI files. 51 | 52 | [1]: https://github.com/mohabouje/WinToast 53 | [2]: https://github.com/pulzed/mINI/ 54 | -------------------------------------------------------------------------------- /ThreeFingerDrag/logging/logger.cpp: -------------------------------------------------------------------------------- 1 | #include "logger.h" 2 | #include 3 | #include 4 | #include 5 | 6 | #include "../application.h" 7 | 8 | Logger& Logger::GetInstance() 9 | { 10 | static Logger instance("log.txt"); 11 | return instance; 12 | } 13 | 14 | Logger::Logger(const std::string& logFileName) 15 | { 16 | log_file_path_ = Application::GetConfigurationFolderPath(); 17 | 18 | // Check if the folder exists, and create it if necessary 19 | if (!std::filesystem::exists(log_file_path_)) 20 | std::filesystem::create_directory(log_file_path_); 21 | 22 | log_file_path_ += "\\" + logFileName; 23 | 24 | // Check if the log file exists, and create it if necessary 25 | if (!std::filesystem::exists(log_file_path_)) 26 | { 27 | std::ofstream file(log_file_path_, std::ios::out); 28 | file.close(); 29 | } 30 | 31 | log_file_.open(log_file_path_, std::ios::out | std::ios::app); 32 | } 33 | 34 | void Logger::WriteLog(const std::string& type, const std::string& message) 35 | { 36 | // Check if the log file has exceeded the threshold size of 5 MB 37 | const std::streampos current_pos = log_file_.tellp(); 38 | const std::streampos max_size = 5 * 1024 * 1024; // 5MB 39 | if (current_pos >= max_size) 40 | { 41 | // Truncate the log file to zero size 42 | log_file_.close(); 43 | std::ofstream file(log_file_path_, std::ios::out | std::ios::trunc); 44 | file.close(); 45 | } 46 | 47 | // Get the current system time 48 | const auto now = std::chrono::system_clock::now(); 49 | const std::time_t now_time = std::chrono::system_clock::to_time_t(now); 50 | 51 | // Convert the time to a string 52 | std::tm time_info; 53 | if (localtime_s(&time_info, &now_time) == 0) 54 | { 55 | std::stringstream ss; 56 | ss << std::put_time(&time_info, "%y-%m-%d %H:%M:%S"); 57 | const std::string timestamp_str = ss.str(); 58 | 59 | // Write the log message to the file with the timestamp 60 | if (!type.empty()) 61 | log_file_ << timestamp_str << " " << type << " " << message << '\n'; 62 | else 63 | log_file_ << timestamp_str << ": " << message << '\n'; 64 | 65 | } 66 | else 67 | { 68 | // Write the log message to the file without the timestamp 69 | if (!type.empty()) 70 | log_file_ << type << " - " << message << '\n'; 71 | else 72 | log_file_ << ": " << message << '\n'; 73 | } 74 | } 75 | 76 | void Logger::Info(const std::string& message) 77 | { 78 | WriteLog("[INFO]", message); 79 | } 80 | 81 | void Logger::Debug(const std::string& message) 82 | { 83 | WriteLog("[DEBUG]", message); 84 | } 85 | 86 | void Logger::Warning(const std::string& message) 87 | { 88 | WriteLog("[WARNING]", message); 89 | } 90 | 91 | void Logger::Error(const std::string& message) 92 | { 93 | WriteLog("[ERROR]", message); 94 | } 95 | 96 | Logger::~Logger() 97 | { 98 | log_file_.close(); 99 | } 100 | -------------------------------------------------------------------------------- /ThreeFingerDrag/config/globalconfig.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #ifndef GLOBALCONFIG_H 3 | #define GLOBALCONFIG_H 4 | #include 5 | #include "../data/touch_data.h" 6 | #include "../event/touch_events.h" 7 | 8 | constexpr auto DEFAULT_ACCELERATION_FACTOR = 15.0; 9 | constexpr auto DEFAULT_PRECISION_CURSOR_SPEED = 0.5; 10 | constexpr auto DEFAULT_MOUSE_CURSOR_SPEED = 0.5; 11 | constexpr auto DEFAULT_CANCELLATION_DELAY_MS = 500; 12 | constexpr auto DEFAULT_ONE_FINGER_TRANSITION_DELAY_MS = 100; 13 | constexpr auto DEFAULT_AUTOMATIC_TIMEOUT_DELAY_MS = 33; 14 | 15 | class GlobalConfig 16 | { 17 | private: 18 | double gesture_speed_; 19 | double precision_touch_cursor_speed_; 20 | double mouse_cursor_speed_; 21 | int cancellation_delay_ms_; 22 | int automatic_timeout_delay_ms; 23 | int one_finger_transition_delay_ms_; 24 | int last_contact_count_; 25 | bool gesture_started_; 26 | bool cancellation_started_; 27 | bool log_debug_; 28 | bool portable_mode_; 29 | std::chrono::time_point cancellation_time_; 30 | std::chrono::time_point last_valid_movement_; 31 | std::chrono::time_point last_event_; 32 | std::chrono::time_point last_one_finger_switch_time_; 33 | std::vector previous_touch_contacts_; 34 | static GlobalConfig* instance_; 35 | 36 | // Private constructor 37 | GlobalConfig(); 38 | 39 | public: 40 | // Singleton instance 41 | static GlobalConfig* GetInstance(); 42 | 43 | int GetCancellationDelayMs() const; 44 | int GetAutomaticTimeoutDelayMs() const; 45 | int GetOneFingerTransitionDelayMs() const; 46 | int GetLastContactCount() const; 47 | double GetGestureSpeed() const; 48 | bool IsGestureStarted() const; 49 | bool IsCancellationStarted() const; 50 | bool LogDebug() const; 51 | bool IsPortableMode() const; 52 | std::chrono::time_point GetCancellationTime() const; 53 | std::chrono::time_point GetLastValidMovement() const; 54 | std::chrono::time_point GetLastEvent() const; 55 | std::chrono::time_point GetLastOneFingerSwitchTime() const; 56 | std::vector GetPreviousTouchContacts() const; 57 | 58 | void SetCancellationDelayMs(int delay); 59 | void SetAutomaticTimeoutDelayMs(int delay); 60 | void SetOneFingerTransitionDelayMs(int delay); 61 | void SetLastContactCount(int count); 62 | void SetGestureSpeed(double speed); 63 | void SetGestureStarted(bool started); 64 | void SetCancellationStarted(bool started); 65 | void SetLogDebug(bool log); 66 | void SetPortableMode(bool portable); 67 | void SetCancellationTime(std::chrono::time_point time); 68 | void SetLastValidMovement(std::chrono::time_point time); 69 | void SetLastEvent(std::chrono::time_point time); 70 | void SetLastOneFingerSwitchTime(std::chrono::time_point time); 71 | void SetPreviousTouchContacts(const std::vector& data); 72 | }; 73 | 74 | #endif // GLOBALCONFIG_H 75 | -------------------------------------------------------------------------------- /ThreeFingerDrag/notification/popups.cpp: -------------------------------------------------------------------------------- 1 | #include "popups.h" 2 | #include "../logging/logger.h" 3 | #include "wintoastlib.h" 4 | 5 | using namespace WinToastLib; 6 | 7 | class WinToastHandler : public WinToastLib::IWinToastHandler 8 | { 9 | public: 10 | WinToastHandler() 11 | { 12 | } 13 | 14 | // Public interfaces 15 | void toastActivated() const override 16 | { 17 | } 18 | 19 | void toastActivated(int actionIndex) const override 20 | { 21 | } 22 | 23 | void toastDismissed(WinToastDismissalReason state) const override 24 | { 25 | } 26 | 27 | void toastFailed() const override 28 | { 29 | } 30 | }; 31 | 32 | /** 33 | * \brief Displays a message box popup with an error icon and message. 34 | * \param message The message to display. 35 | * \param logger A pointer to the logger object. 36 | * \remarks The sent message will be logged as an error. 37 | */ 38 | void Popups::DisplayErrorMessage(const std::string& message) 39 | { 40 | const auto temp = std::wstring(message.begin(), message.end()); 41 | const LPCWSTR wstr_message = temp.c_str(); 42 | 43 | MessageBox(nullptr, wstr_message, TEXT("Three Finger Drag"), MB_OK | MB_ICONERROR | MB_TOPMOST); 44 | ERROR(message); 45 | } 46 | 47 | /** 48 | * \brief Displays a message box popup with an info icon and message. 49 | * \param message The message to display. 50 | * \param logger A pointer to the logger object. 51 | * \remarks The sent message will be logged as an error. 52 | */ 53 | void Popups::DisplayInfoMessage(const std::string& message) 54 | { 55 | const auto temp = std::wstring(message.begin(), message.end()); 56 | const LPCWSTR wstr_message = temp.c_str(); 57 | 58 | MessageBox(nullptr, wstr_message, TEXT("Three Finger Drag"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); 59 | INFO(message); 60 | } 61 | 62 | /** 63 | * \brief Displays a message box popup with yes and no buttons and returns true if "yes" is clicked. 64 | * \param message The message to display. 65 | * \param title The title of the message box. 66 | * \return true if "yes" is clicked, false otherwise. 67 | */ 68 | bool Popups::DisplayPrompt(const std::string& message, const std::string& title) 69 | { 70 | const auto temp_message = std::wstring(message.begin(), message.end()); 71 | const auto temp_title = std::wstring(title.begin(), title.end()); 72 | 73 | const int response = MessageBox(nullptr, temp_message.c_str(), temp_title.c_str(), 74 | MB_YESNO | MB_ICONQUESTION | MB_TOPMOST); 75 | return response == IDYES; 76 | } 77 | 78 | /** 79 | * \brief Displays a message box popup with yes and no buttons and returns true if "yes" is clicked. 80 | * \param message The message to display. 81 | * \param title The title of the message box. 82 | * \return true if "yes" is clicked, false otherwise. 83 | */ 84 | bool Popups::DisplayWarningPrompt(const std::string& message, const std::string& title) 85 | { 86 | const auto temp_message = std::wstring(message.begin(), message.end()); 87 | const auto temp_title = std::wstring(title.begin(), title.end()); 88 | 89 | const int response = MessageBox(nullptr, temp_message.c_str(), temp_title.c_str(), 90 | MB_YESNO | MB_ICONWARNING | MB_TOPMOST); 91 | return response == IDYES; 92 | } 93 | 94 | void Popups::ShowToastNotification(const std::wstring& message, const std::wstring& title) 95 | { 96 | auto templ = WinToastTemplate(WinToastTemplate::Text02); 97 | templ.setTextField(title, WinToastTemplate::FirstLine); 98 | templ.setTextField(message, WinToastTemplate::SecondLine); 99 | WinToast::instance()->showToast(templ, new WinToastHandler()); 100 | } 101 | -------------------------------------------------------------------------------- /ThreeFingerDrag/ThreeFingerDrag.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | Header Files 26 | 27 | 28 | Header Files 29 | 30 | 31 | Header Files 32 | 33 | 34 | Header Files 35 | 36 | 37 | Header Files 38 | 39 | 40 | Header Files 41 | 42 | 43 | Header Files 44 | 45 | 46 | Header Files 47 | 48 | 49 | Header Files 50 | 51 | 52 | Header Files 53 | 54 | 55 | Header Files 56 | 57 | 58 | Header Files 59 | 60 | 61 | Header Files 62 | 63 | 64 | Header Files 65 | 66 | 67 | Header Files 68 | 69 | 70 | 71 | 72 | Source Files 73 | 74 | 75 | Source Files 76 | 77 | 78 | Source Files 79 | 80 | 81 | Source Files 82 | 83 | 84 | Source Files 85 | 86 | 87 | Source Files 88 | 89 | 90 | Source Files 91 | 92 | 93 | 94 | 95 | Resource Files 96 | 97 | 98 | 99 | 100 | Resource Files 101 | 102 | 103 | Resource Files 104 | 105 | 106 | -------------------------------------------------------------------------------- /ThreeFingerDrag/config/globalconfig.cpp: -------------------------------------------------------------------------------- 1 | #include "globalconfig.h" 2 | 3 | GlobalConfig* GlobalConfig::instance_ = nullptr; 4 | 5 | GlobalConfig::GlobalConfig() 6 | { 7 | // Set default values 8 | gesture_speed_ = DEFAULT_ACCELERATION_FACTOR; 9 | cancellation_delay_ms_ = DEFAULT_CANCELLATION_DELAY_MS; 10 | automatic_timeout_delay_ms = DEFAULT_AUTOMATIC_TIMEOUT_DELAY_MS; 11 | one_finger_transition_delay_ms_ = DEFAULT_ONE_FINGER_TRANSITION_DELAY_MS; 12 | precision_touch_cursor_speed_ = DEFAULT_PRECISION_CURSOR_SPEED; 13 | mouse_cursor_speed_ = DEFAULT_MOUSE_CURSOR_SPEED; 14 | gesture_started_ = false; 15 | cancellation_started_ = false; 16 | log_debug_ = false; 17 | } 18 | 19 | GlobalConfig* GlobalConfig::GetInstance() 20 | { 21 | if (instance_ == nullptr) 22 | instance_ = new GlobalConfig(); 23 | return instance_; 24 | } 25 | 26 | int GlobalConfig::GetCancellationDelayMs() const 27 | { 28 | return cancellation_delay_ms_; 29 | } 30 | 31 | void GlobalConfig::SetCancellationDelayMs(int delay) 32 | { 33 | cancellation_delay_ms_ = delay; 34 | } 35 | 36 | double GlobalConfig::GetGestureSpeed() const 37 | { 38 | return gesture_speed_; 39 | } 40 | 41 | void GlobalConfig::SetGestureSpeed(double speed) 42 | { 43 | gesture_speed_ = speed; 44 | } 45 | 46 | bool GlobalConfig::IsGestureStarted() const 47 | { 48 | return gesture_started_; 49 | } 50 | 51 | void GlobalConfig::SetGestureStarted(bool started) 52 | { 53 | gesture_started_ = started; 54 | } 55 | 56 | bool GlobalConfig::IsCancellationStarted() const 57 | { 58 | return cancellation_started_; 59 | } 60 | 61 | void GlobalConfig::SetCancellationStarted(bool started) 62 | { 63 | cancellation_started_ = started; 64 | } 65 | 66 | std::chrono::time_point GlobalConfig::GetCancellationTime() const 67 | { 68 | return cancellation_time_; 69 | } 70 | 71 | void GlobalConfig::SetCancellationTime(const std::chrono::time_point time) 72 | { 73 | cancellation_time_ = time; 74 | } 75 | 76 | std::chrono::time_point GlobalConfig::GetLastValidMovement() const 77 | { 78 | return last_valid_movement_; 79 | } 80 | 81 | void GlobalConfig::SetLastValidMovement(const std::chrono::time_point time) 82 | { 83 | last_valid_movement_ = time; 84 | } 85 | 86 | std::chrono::time_point GlobalConfig::GetLastEvent() const 87 | { 88 | return last_event_; 89 | } 90 | 91 | void GlobalConfig::SetLastEvent(const std::chrono::time_point time) 92 | { 93 | last_event_ = time; 94 | } 95 | 96 | std::vector GlobalConfig::GetPreviousTouchContacts() const 97 | { 98 | return previous_touch_contacts_; 99 | } 100 | 101 | void GlobalConfig::SetPreviousTouchContacts(const std::vector& data) 102 | { 103 | previous_touch_contacts_ = data; 104 | } 105 | 106 | bool GlobalConfig::LogDebug() const 107 | { 108 | return log_debug_; 109 | } 110 | 111 | void GlobalConfig::SetLogDebug(bool log) 112 | { 113 | log_debug_ = log; 114 | } 115 | 116 | int GlobalConfig::GetLastContactCount() const 117 | { 118 | return last_contact_count_; 119 | } 120 | 121 | void GlobalConfig::SetLastContactCount(int count) 122 | { 123 | last_contact_count_ = count; 124 | } 125 | 126 | std::chrono::time_point GlobalConfig::GetLastOneFingerSwitchTime() const 127 | { 128 | return last_one_finger_switch_time_; 129 | } 130 | 131 | void GlobalConfig::SetLastOneFingerSwitchTime(std::chrono::time_point time) 132 | { 133 | last_one_finger_switch_time_ = time; 134 | } 135 | 136 | int GlobalConfig::GetOneFingerTransitionDelayMs() const 137 | { 138 | return one_finger_transition_delay_ms_; 139 | } 140 | 141 | void GlobalConfig::SetOneFingerTransitionDelayMs(int delay) 142 | { 143 | one_finger_transition_delay_ms_ = delay; 144 | } 145 | 146 | bool GlobalConfig::IsPortableMode() const 147 | { 148 | return portable_mode_; 149 | } 150 | 151 | void GlobalConfig::SetPortableMode(bool portable) 152 | { 153 | portable_mode_ = portable; 154 | } 155 | 156 | int GlobalConfig::GetAutomaticTimeoutDelayMs() const 157 | { 158 | return automatic_timeout_delay_ms; 159 | } 160 | 161 | void GlobalConfig::SetAutomaticTimeoutDelayMs(int delay) 162 | { 163 | automatic_timeout_delay_ms = delay; 164 | } 165 | -------------------------------------------------------------------------------- /ThreeFingerDrag/task/task_scheduler.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #pragma comment(lib, "taskschd.lib") 7 | #include 8 | #include 9 | 10 | class TaskScheduler 11 | { 12 | public: 13 | static bool TaskExists(const std::string& taskName); 14 | static bool CreateLoginTask(const std::string& taskName, const std::string& exePath); 15 | static void DeleteTask(const std::string& taskName); 16 | }; 17 | 18 | inline bool TaskScheduler::CreateLoginTask(const std::string& taskName, const std::string& exePath) 19 | { 20 | // Get current user name 21 | wchar_t username[UNLEN + 1]; 22 | DWORD username_len = UNLEN + 1; 23 | GetUserName(username, &username_len); 24 | 25 | // Initialize COM 26 | CoInitializeEx(NULL, COINIT_MULTITHREADED); 27 | 28 | // Create Task Service 29 | ITaskService* pService = NULL; 30 | CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void**)&pService); 31 | 32 | // Connect to Task Service 33 | pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t()); 34 | 35 | // Get Task Folder 36 | ITaskFolder* pRootFolder = NULL; 37 | pService->GetFolder(_bstr_t(L"\\"), &pRootFolder); 38 | 39 | // Create Task Definition 40 | ITaskDefinition* pTask = NULL; 41 | pService->NewTask(0, &pTask); 42 | 43 | // Set Task Registration Information 44 | IRegistrationInfo* pRegInfo = NULL; 45 | pTask->get_RegistrationInfo(&pRegInfo); 46 | pRegInfo->put_Author(SysAllocString(username)); 47 | 48 | // Create Task Trigger 49 | ITriggerCollection* pTriggerCollection = NULL; 50 | pTask->get_Triggers(&pTriggerCollection); 51 | ITrigger* pTrigger = NULL; 52 | pTriggerCollection->Create(TASK_TRIGGER_LOGON, &pTrigger); 53 | ILogonTrigger* pLogonTrigger = NULL; 54 | pTrigger->QueryInterface(IID_ILogonTrigger, (void**)&pLogonTrigger); 55 | pLogonTrigger->put_UserId(_bstr_t(username)); 56 | 57 | // Create Task Action 58 | IActionCollection* pActionCollection = NULL; 59 | pTask->get_Actions(&pActionCollection); 60 | IAction* pAction = NULL; 61 | pActionCollection->Create(TASK_ACTION_EXEC, &pAction); 62 | IExecAction* pExecAction = NULL; 63 | pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction); 64 | pExecAction->put_Path(_bstr_t(exePath.c_str())); 65 | 66 | // Register Task 67 | IRegisteredTask* pRegisteredTask = NULL; 68 | HRESULT hr = pRootFolder->RegisterTaskDefinition(_bstr_t(taskName.c_str()), pTask, TASK_CREATE_OR_UPDATE, 69 | _variant_t(), _variant_t(), TASK_LOGON_INTERACTIVE_TOKEN, 70 | _variant_t(), &pRegisteredTask); 71 | 72 | if (FAILED(hr)) 73 | { 74 | _com_error err(hr); 75 | LPCTSTR errMsg = err.ErrorMessage(); 76 | std::wcout << L"Failed to create task. Error: " << errMsg << '\n'; 77 | return false; 78 | } 79 | pRegisteredTask->Release(); 80 | pExecAction->Release(); 81 | pAction->Release(); 82 | pActionCollection->Release(); 83 | pLogonTrigger->Release(); 84 | pTrigger->Release(); 85 | pTriggerCollection->Release(); 86 | pRegInfo->Release(); 87 | pTask->Release(); 88 | pRootFolder->Release(); 89 | pService->Release(); 90 | CoUninitialize(); 91 | return true; 92 | } 93 | 94 | inline void TaskScheduler::DeleteTask(const std::string& taskName) 95 | { 96 | // Initialize COM 97 | CoInitializeEx(NULL, COINIT_MULTITHREADED); 98 | 99 | // Create Task Service 100 | ITaskService* pService = NULL; 101 | CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void**)&pService); 102 | 103 | // Connect to Task Service 104 | pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t()); 105 | 106 | // Get Task Folder 107 | ITaskFolder* pRootFolder = NULL; 108 | pService->GetFolder(_bstr_t(L"\\"), &pRootFolder); 109 | 110 | // Delete the task 111 | pRootFolder->DeleteTask(_bstr_t(taskName.c_str()), 0); 112 | 113 | // Release COM objects 114 | pRootFolder->Release(); 115 | pService->Release(); 116 | CoUninitialize(); 117 | } 118 | 119 | inline bool TaskScheduler::TaskExists(const std::string& taskName) 120 | { 121 | // Initialize COM 122 | CoInitializeEx(NULL, COINIT_MULTITHREADED); 123 | 124 | // Create Task Service 125 | ITaskService* pService = NULL; 126 | CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void**)&pService); 127 | 128 | // Connect to Task Service 129 | pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t()); 130 | 131 | // Get Task Folder 132 | ITaskFolder* pRootFolder = NULL; 133 | pService->GetFolder(_bstr_t(L"\\"), &pRootFolder); 134 | 135 | // Check if the task exists 136 | IRegisteredTask* pRegisteredTask = NULL; 137 | HRESULT hr = pRootFolder->GetTask(_bstr_t(taskName.c_str()), &pRegisteredTask); 138 | 139 | if (!SUCCEEDED(hr)) 140 | { 141 | pRootFolder->Release(); 142 | pService->Release(); 143 | CoUninitialize(); 144 | return false; 145 | } 146 | 147 | // Release COM objects 148 | pRegisteredTask->Release(); 149 | pRootFolder->Release(); 150 | pService->Release(); 151 | CoUninitialize(); 152 | return SUCCEEDED(hr); 153 | } 154 | -------------------------------------------------------------------------------- /ThreeFingerDrag/application.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "gesture/touch_processor.h" 8 | #include "data/ini.h" 9 | #include "config/globalconfig.h" 10 | 11 | namespace Application 12 | { 13 | constexpr bool RELEASE_BUILD = true; 14 | 15 | constexpr int VERSION_MAJOR = 1; 16 | constexpr int VERSION_MINOR = 2; 17 | constexpr int VERSION_PATCH = 7; 18 | 19 | constexpr int VERSION_REVISION = 0; 20 | 21 | constexpr char VERSION_FILE_NAME[] = "version.txt"; 22 | 23 | inline std::string GetVersionString() 24 | { 25 | std::string version = std::to_string(VERSION_MAJOR) + "." + 26 | std::to_string(VERSION_MINOR) + "." + 27 | std::to_string(VERSION_PATCH); 28 | 29 | // If it's not a release build, then it's a snapshot 30 | if (!RELEASE_BUILD) 31 | version += "." + std::to_string(VERSION_REVISION) + "-SNAPSHOT"; 32 | 33 | return version; 34 | } 35 | 36 | inline GlobalConfig* config = GlobalConfig::GetInstance(); 37 | 38 | inline std::string config_folder_path; 39 | 40 | /** 41 | * @brief Constructs and returns the path to application configuration files. If required, the directory will be created. 42 | * @return The local app data folder path 43 | */ 44 | inline std::string GetConfigurationFolderPath() 45 | { 46 | if (!config_folder_path.empty()) 47 | { 48 | return config_folder_path; 49 | } 50 | 51 | if (config->IsPortableMode()) 52 | { 53 | config_folder_path = std::filesystem::current_path().u8string(); 54 | return config_folder_path; 55 | } 56 | 57 | size_t len; 58 | char* env_path; 59 | const errno_t err = _dupenv_s(&env_path, &len, "LOCALAPPDATA"); 60 | 61 | auto directory_path = std::string(env_path); 62 | directory_path += "\\"; 63 | directory_path += "ThreeFingerDrag"; 64 | 65 | config_folder_path = directory_path; 66 | 67 | // Create the application data directory if necessary 68 | if (!std::filesystem::exists(directory_path)) 69 | std::filesystem::create_directory(directory_path); 70 | return directory_path; 71 | } 72 | 73 | /** 74 | * @brief Checks if a version.txt file exists in application data and updates it. 75 | * @return True if no version file was found 76 | */ 77 | inline bool IsInitialStartup() 78 | { 79 | std::string version_file_path_ = GetConfigurationFolderPath(); 80 | 81 | version_file_path_ += "\\"; 82 | version_file_path_ += VERSION_FILE_NAME; 83 | 84 | // File contents do not need to update after initial creation 85 | if (std::filesystem::exists(version_file_path_)) 86 | return false; 87 | 88 | // Create the file if it has not been created yet, and write the current version to it 89 | std::ofstream versionFile(version_file_path_); 90 | if (!versionFile) 91 | return false; 92 | 93 | versionFile << GetVersionString(); 94 | versionFile.close(); 95 | 96 | return true; 97 | } 98 | 99 | inline void WriteConfiguration() 100 | { 101 | std::stringstream ss; 102 | std::string file_path = GetConfigurationFolderPath(); 103 | 104 | file_path += "\\"; 105 | file_path += "\\config.ini"; 106 | 107 | mINI::INIFile file(file_path); 108 | mINI::INIStructure ini; 109 | 110 | ss << std::fixed << std::setprecision(2) << config->GetGestureSpeed(); 111 | 112 | ini["Configuration"]["gesture_speed"] = ss.str(); 113 | ini["Configuration"]["cancellation_delay_ms"] = std::to_string(config->GetCancellationDelayMs()); 114 | ini["Configuration"]["automatic_timeout_delay_ms"] = std::to_string(config->GetAutomaticTimeoutDelayMs()); 115 | ini["Configuration"]["one_finger_transition_delay_ms"] = std::to_string(config->GetOneFingerTransitionDelayMs()); 116 | ini["Configuration"]["debug"] = config->LogDebug() ? "true" : "false"; 117 | 118 | if (!file.generate(ini)) 119 | ERROR("Error writing to config file."); 120 | } 121 | 122 | inline void ReadConfiguration() 123 | { 124 | std::string file_path = GetConfigurationFolderPath(); 125 | 126 | file_path += "\\"; 127 | file_path += "\\config.ini"; 128 | 129 | if (!std::filesystem::exists(file_path)) 130 | { 131 | WriteConfiguration(); 132 | return; 133 | } 134 | 135 | 136 | mINI::INIFile file(file_path); 137 | mINI::INIStructure ini; 138 | 139 | if (!file.read(ini)) 140 | { 141 | std::stringstream ss; 142 | ss << "Couldn't read '" << file_path << "'"; 143 | ERROR(ss.str()); 144 | return; 145 | } 146 | 147 | const auto config_section = ini["Configuration"]; 148 | 149 | if (config_section.has("gesture_speed")) 150 | config->SetGestureSpeed(std::stof(config_section.get("gesture_speed"))); 151 | 152 | if (config_section.has("cancellation_delay_ms")) 153 | config->SetCancellationDelayMs(std::stof(config_section.get("cancellation_delay_ms"))); 154 | 155 | if (config_section.has("automatic_timeout_delay_ms")) 156 | config->SetAutomaticTimeoutDelayMs(std::stof(config_section.get("automatic_timeout_delay_ms"))); 157 | 158 | if (config_section.has("one_finger_transition_delay_ms")) 159 | config->SetOneFingerTransitionDelayMs(std::stof(config_section.get("one_finger_transition_delay_ms"))); 160 | 161 | if (config_section.has("debug")) 162 | config->SetLogDebug(config_section.get("debug") == "true"); 163 | } 164 | 165 | inline std::filesystem::path ExePath() 166 | { 167 | wchar_t path[FILENAME_MAX] = {0}; 168 | GetModuleFileNameW(nullptr, path, FILENAME_MAX); 169 | return std::filesystem::path(path); 170 | } 171 | 172 | inline void CheckPortableMode() 173 | { 174 | size_t len; 175 | char* env_path; 176 | const errno_t err = _dupenv_s(&env_path, &len, "LOCALAPPDATA"); 177 | 178 | auto file_path = std::string(env_path); 179 | file_path += "\\"; 180 | file_path += "tfd_install_location.txt"; 181 | 182 | std::ifstream file; 183 | file.open(file_path); 184 | 185 | // No file was found, so the program probably wasn't installed 186 | if (!file.good()) 187 | { 188 | config->SetPortableMode(true); 189 | return; 190 | } 191 | 192 | std::string firstLine; 193 | std::getline(file, firstLine); 194 | 195 | if (firstLine.empty()) 196 | { 197 | return; 198 | } 199 | // Determine if the program is not running from its installed location 200 | config->SetPortableMode(ExePath().u8string().find(firstLine) == std::string::npos); 201 | } 202 | 203 | } 204 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | # Notepad++ auto-generated backup files 400 | *.bak 401 | 402 | # Project Outputs 403 | installers/ 404 | build/ 405 | 406 | # Extra 407 | enc_temp_folder/ 408 | 409 | -------------------------------------------------------------------------------- /ThreeFingerDrag/ThreeFingerDrag.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {2f6ab4a4-893d-4fbd-ae32-6edb569d435a} 25 | ThreeFingerDrag 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | $(SolutionDir)\build\ 75 | false 76 | 77 | 78 | false 79 | 80 | 81 | 82 | Level3 83 | true 84 | WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) 85 | true 86 | 87 | 88 | Windows 89 | true 90 | 91 | 92 | 93 | 94 | Level3 95 | true 96 | true 97 | true 98 | WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) 99 | true 100 | 101 | 102 | Windows 103 | true 104 | true 105 | true 106 | 107 | 108 | 109 | 110 | Level3 111 | true 112 | _DEBUG;_WINDOWS;%(PreprocessorDefinitions) 113 | true 114 | stdcpp17 115 | 116 | 117 | Windows 118 | true 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | Level3 128 | true 129 | true 130 | true 131 | NDEBUG;_WINDOWS;%(PreprocessorDefinitions) 132 | true 133 | stdcpp17 134 | 135 | 136 | Windows 137 | true 138 | true 139 | true 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | -------------------------------------------------------------------------------- /ThreeFingerDrag/gesture/event_listeners.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../config/globalconfig.h" 3 | #include "../event/touch_events.h" 4 | #include "../mouse/cursor.h" 5 | #include "../logging/logger.h" 6 | #include 7 | #include 8 | 9 | namespace EventListeners 10 | { 11 | constexpr auto NUM_TOUCH_CONTACTS_REQUIRED = 3; 12 | constexpr auto MAX_CONTACT_SIZE = 10; 13 | constexpr auto MIN_VALID_TOUCH_CONTACTS = 1; 14 | constexpr auto INACTIVITY_THRESHOLD_MS = 100; 15 | constexpr auto GESTURE_START_THRESHOLD_MS = 50; 16 | 17 | inline GlobalConfig* config = GlobalConfig::GetInstance(); 18 | 19 | static void CancelGesture() 20 | { 21 | Cursor::LeftMouseUp(); 22 | config->SetCancellationStarted(false); 23 | config->SetGestureStarted(false); 24 | if (config->LogDebug()) 25 | DEBUG("Cancelled gesture."); 26 | } 27 | 28 | static float CalculateElapsedTimeMs(const std::chrono::time_point& start_time, 29 | const std::chrono::time_point& end_time) 30 | { 31 | const std::chrono::duration elapsed = end_time - start_time; 32 | return elapsed.count() * 1000.0f; 33 | } 34 | 35 | class TouchActivityListener 36 | { 37 | public: 38 | void OnTouchActivity(const TouchActivityEventArgs& args) 39 | { 40 | config->SetPreviousTouchContacts(args.data->contacts); 41 | 42 | // Check if it's the initial gesture 43 | const bool is_dragging = Cursor::IsLeftMouseDown(); 44 | const bool is_initial_gesture = !is_dragging && args.data->can_perform_gesture; 45 | const auto current_time = args.time; 46 | 47 | // If it's the initial gesture, set the gesture start time 48 | if (is_initial_gesture && !config->IsGestureStarted()) 49 | { 50 | config->SetGestureStarted(true); 51 | gesture_start_ = current_time; 52 | if (config->LogDebug()) 53 | DEBUG("Started gesture."); 54 | } 55 | 56 | // If there's no previous data, return 57 | if (args.previous_data.empty()) 58 | return; 59 | 60 | // Calculate the time elapsed 61 | const float ms_since_gesture_start = CalculateElapsedTimeMs(gesture_start_, current_time); 62 | const float ms_since_last_event = CalculateElapsedTimeMs(config->GetLastEvent(), current_time); 63 | 64 | // Prevent initial movement jitter 65 | if (ms_since_last_event > GESTURE_START_THRESHOLD_MS) 66 | return; 67 | 68 | // Ignore initial movement 69 | if (ms_since_gesture_start <= GESTURE_START_THRESHOLD_MS) 70 | return; 71 | 72 | // If invalid amount of fingers, and gesture is not currently performing 73 | if (!args.data->can_perform_gesture && !is_dragging) 74 | return; 75 | 76 | // Loop through each touch contact 77 | int valid_touches = 0; 78 | for (int i = 0; i < args.data->contacts.size(); i++) 79 | { 80 | if (i > args.previous_data.size() - 1 || i > args.data->contacts.size() - 1 || i > MAX_CONTACT_SIZE) 81 | continue; 82 | 83 | const auto& contact = args.data->contacts[i]; 84 | const auto& previous_contact = args.previous_data[i]; 85 | 86 | if (!contact.on_surface || !previous_contact.on_surface) 87 | { 88 | // Reset the accumulated movement for this finger 89 | accumulated_delta_x_[i] = 0; 90 | accumulated_delta_y_[i] = 0; 91 | continue; 92 | } 93 | 94 | // Only compare identical touch contact points 95 | if (contact.contact_id != previous_contact.contact_id) 96 | continue; 97 | 98 | // Ignore initial movement of contact point if inactivity, to prevent jitter 99 | const float ms_since_movement = CalculateElapsedTimeMs(movement_times_[i], current_time); 100 | movement_times_[i] = current_time; 101 | 102 | if (ms_since_movement > INACTIVITY_THRESHOLD_MS) 103 | continue; 104 | 105 | // Cancel immediately if a previous cancellation has begun, and this is a non-gesture movement 106 | if (config->IsCancellationStarted() && !args.data->can_perform_gesture && config->IsGestureStarted()) 107 | { 108 | CancelGesture(); 109 | return; 110 | } 111 | 112 | // Calculate the movement delta for the current finger 113 | const double x_diff = contact.x - previous_contact.x; 114 | const double y_diff = contact.y - previous_contact.y; 115 | const double movement_delta = std::abs(x_diff) + std::abs(y_diff); 116 | const double accumulated_movement = 117 | std::abs(accumulated_delta_x_[i]) + std::abs(accumulated_delta_y_[i]); 118 | 119 | const bool include_fine_movement = accumulated_movement >= 1.0 && movement_delta > 0; 120 | 121 | // Check if any valid movement was present 122 | if (!include_fine_movement && movement_delta < 1.0) 123 | continue; 124 | 125 | // Accumulate the movement delta for the current finger 126 | accumulated_delta_x_[i] += x_diff; 127 | accumulated_delta_y_[i] += y_diff; 128 | valid_touches++; 129 | } 130 | 131 | const auto contact_count = args.data->contact_count; 132 | 133 | // Switched to one finger during gesture 134 | if (contact_count == 1 && config->GetLastContactCount() == 1) 135 | { 136 | const float ms_since_last_switch = CalculateElapsedTimeMs(config->GetLastOneFingerSwitchTime(), current_time); 137 | 138 | // After a short delay, stop continuing the gesture movement from this event in favor of 139 | // default touchpad cursor movement to prevent input flooding. 140 | if (ms_since_last_switch > config->GetOneFingerTransitionDelayMs()) 141 | { 142 | accumulated_delta_x_ = {0.0}; 143 | accumulated_delta_y_ = {0.0}; 144 | return; 145 | } 146 | } 147 | 148 | if (config->IsGestureStarted() && config->GetLastContactCount() > 1 && contact_count == 1) 149 | config->SetLastOneFingerSwitchTime(current_time); 150 | 151 | config->SetLastContactCount(contact_count); 152 | 153 | // If there are not enough valid touches, return 154 | if (valid_touches < MIN_VALID_TOUCH_CONTACTS) 155 | return; 156 | 157 | // Apply movement acceleration 158 | const double gesture_speed = config->GetGestureSpeed() / 100.0; 159 | 160 | const double delta_x = 161 | std::accumulate(accumulated_delta_x_.begin(), accumulated_delta_x_.end(), 0.0) * gesture_speed; 162 | const double delta_y = 163 | std::accumulate(accumulated_delta_y_.begin(), accumulated_delta_y_.end(), 0.0) * gesture_speed; 164 | 165 | config->SetCancellationStarted(false); 166 | 167 | // Move the mouse pointer based on the calculated vector 168 | Cursor::MoveCursor(delta_x, delta_y); 169 | 170 | // Start dragging if left mouse is not already down 171 | if (!is_dragging) 172 | Cursor::LeftMouseDown(); 173 | 174 | const auto change_x = std::abs(delta_x); 175 | const auto change_y = std::abs(delta_y); 176 | const auto total_change = change_x + change_y; 177 | 178 | // Check if any movement occurred 179 | if (total_change < 1.0) 180 | return; 181 | 182 | // Set timestamp for last valid movement 183 | config->SetLastValidMovement(current_time); 184 | 185 | // Reset accumulated x/y data if necessary 186 | if (change_x >= 1.0) 187 | accumulated_delta_x_.fill(0); 188 | if (change_y >= 1.0) 189 | accumulated_delta_y_.fill(0); 190 | } 191 | 192 | private: 193 | std::array accumulated_delta_x_ = {0.0}; 194 | std::array accumulated_delta_y_ = {0.0}; 195 | std::array, MAX_CONTACT_SIZE> movement_times_; 196 | std::chrono::time_point gesture_start_; 197 | }; 198 | 199 | class TouchUpListener 200 | { 201 | public: 202 | void OnTouchUp(const TouchUpEventArgs& args) 203 | { 204 | config->SetPreviousTouchContacts(args.data->contacts); 205 | 206 | if (config->IsCancellationStarted() || !config->IsGestureStarted()) 207 | return; 208 | 209 | // Calculate the time elapsed since the last valid gesture movement 210 | const auto current_time = std::chrono::high_resolution_clock::now(); 211 | const float ms_since_last_movement = CalculateElapsedTimeMs(config->GetLastValidMovement(), current_time); 212 | 213 | // If there hasn't been any movement for same amount of time we will delay, then cancel immediately 214 | if (ms_since_last_movement >= static_cast(config->GetCancellationDelayMs())) 215 | { 216 | CancelGesture(); 217 | return; 218 | } 219 | 220 | config->SetCancellationStarted(true); 221 | config->SetCancellationTime(current_time); 222 | config->SetLastValidMovement(current_time); 223 | 224 | if (config->LogDebug()) 225 | DEBUG("Started gesture cancellation."); 226 | } 227 | }; 228 | } 229 | -------------------------------------------------------------------------------- /ThreeFingerDrag/notification/wintoastlib.h: -------------------------------------------------------------------------------- 1 | /* * Copyright (C) 2016-2023 Mohammed Boujemaoui 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | * this software and associated documentation files (the "Software"), to deal in 5 | * the Software without restriction, including without limitation the rights to 6 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | * the Software, and to permit persons to whom the Software is furnished to do so, 8 | * subject to the following conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in all 11 | * copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 15 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 16 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 17 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 18 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | */ 20 | 21 | #ifndef WINTOASTLIB_H 22 | #define WINTOASTLIB_H 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | 44 | using namespace Microsoft::WRL; 45 | using namespace ABI::Windows::Data::Xml::Dom; 46 | using namespace ABI::Windows::Foundation; 47 | using namespace ABI::Windows::UI::Notifications; 48 | using namespace Windows::Foundation; 49 | 50 | namespace WinToastLib 51 | { 52 | class IWinToastHandler 53 | { 54 | public: 55 | enum WinToastDismissalReason 56 | { 57 | UserCanceled = ToastDismissalReason::ToastDismissalReason_UserCanceled, 58 | ApplicationHidden = ToastDismissalReason::ToastDismissalReason_ApplicationHidden, 59 | TimedOut = ToastDismissalReason::ToastDismissalReason_TimedOut 60 | }; 61 | 62 | virtual ~IWinToastHandler() = default; 63 | virtual void toastActivated() const = 0; 64 | virtual void toastActivated(int actionIndex) const = 0; 65 | virtual void toastDismissed(WinToastDismissalReason state) const = 0; 66 | virtual void toastFailed() const = 0; 67 | }; 68 | 69 | class WinToastTemplate 70 | { 71 | public: 72 | enum class Scenario { Default, Alarm, IncomingCall, Reminder }; 73 | 74 | enum Duration { System, Short, Long }; 75 | 76 | enum AudioOption { Default = 0, Silent, Loop }; 77 | 78 | enum TextField { FirstLine = 0, SecondLine, ThirdLine }; 79 | 80 | enum WinToastTemplateType 81 | { 82 | ImageAndText01 = ToastTemplateType::ToastTemplateType_ToastImageAndText01, 83 | ImageAndText02 = ToastTemplateType::ToastTemplateType_ToastImageAndText02, 84 | ImageAndText03 = ToastTemplateType::ToastTemplateType_ToastImageAndText03, 85 | ImageAndText04 = ToastTemplateType::ToastTemplateType_ToastImageAndText04, 86 | Text01 = ToastTemplateType::ToastTemplateType_ToastText01, 87 | Text02 = ToastTemplateType::ToastTemplateType_ToastText02, 88 | Text03 = ToastTemplateType::ToastTemplateType_ToastText03, 89 | Text04 = ToastTemplateType::ToastTemplateType_ToastText04 90 | }; 91 | 92 | enum AudioSystemFile 93 | { 94 | DefaultSound, 95 | IM, 96 | Mail, 97 | Reminder, 98 | SMS, 99 | Alarm, 100 | Alarm2, 101 | Alarm3, 102 | Alarm4, 103 | Alarm5, 104 | Alarm6, 105 | Alarm7, 106 | Alarm8, 107 | Alarm9, 108 | Alarm10, 109 | Call, 110 | Call1, 111 | Call2, 112 | Call3, 113 | Call4, 114 | Call5, 115 | Call6, 116 | Call7, 117 | Call8, 118 | Call9, 119 | Call10, 120 | }; 121 | 122 | enum CropHint 123 | { 124 | Square, 125 | Circle, 126 | }; 127 | 128 | WinToastTemplate(_In_ WinToastTemplateType type = WinToastTemplateType::ImageAndText02); 129 | ~WinToastTemplate(); 130 | 131 | void setFirstLine(_In_ std::wstring const& text); 132 | void setSecondLine(_In_ std::wstring const& text); 133 | void setThirdLine(_In_ std::wstring const& text); 134 | void setTextField(_In_ std::wstring const& txt, _In_ TextField pos); 135 | void setAttributionText(_In_ std::wstring const& attributionText); 136 | void setImagePath(_In_ std::wstring const& imgPath, _In_ CropHint cropHint = CropHint::Square); 137 | void setHeroImagePath(_In_ std::wstring const& imgPath, _In_ bool inlineImage = false); 138 | void setAudioPath(_In_ WinToastTemplate::AudioSystemFile audio); 139 | void setAudioPath(_In_ std::wstring const& audioPath); 140 | void setAudioOption(_In_ WinToastTemplate::AudioOption audioOption); 141 | void setDuration(_In_ Duration duration); 142 | void setExpiration(_In_ INT64 millisecondsFromNow); 143 | void setScenario(_In_ Scenario scenario); 144 | void addAction(_In_ std::wstring const& label); 145 | 146 | std::size_t textFieldsCount() const; 147 | std::size_t actionsCount() const; 148 | bool hasImage() const; 149 | bool hasHeroImage() const; 150 | std::vector const& textFields() const; 151 | std::wstring const& textField(_In_ TextField pos) const; 152 | std::wstring const& actionLabel(_In_ std::size_t pos) const; 153 | std::wstring const& imagePath() const; 154 | std::wstring const& heroImagePath() const; 155 | std::wstring const& audioPath() const; 156 | std::wstring const& attributionText() const; 157 | std::wstring const& scenario() const; 158 | INT64 expiration() const; 159 | WinToastTemplateType type() const; 160 | WinToastTemplate::AudioOption audioOption() const; 161 | Duration duration() const; 162 | bool isToastGeneric() const; 163 | bool isInlineHeroImage() const; 164 | bool isCropHintCircle() const; 165 | 166 | private: 167 | std::vector _textFields{}; 168 | std::vector _actions{}; 169 | std::wstring _imagePath{}; 170 | std::wstring _heroImagePath{}; 171 | bool _inlineHeroImage{false}; 172 | std::wstring _audioPath{}; 173 | std::wstring _attributionText{}; 174 | std::wstring _scenario{L"Default"}; 175 | INT64 _expiration{0}; 176 | AudioOption _audioOption{WinToastTemplate::AudioOption::Default}; 177 | WinToastTemplateType _type{WinToastTemplateType::Text01}; 178 | Duration _duration{Duration::System}; 179 | CropHint _cropHint{CropHint::Square}; 180 | }; 181 | 182 | class WinToast 183 | { 184 | public: 185 | enum WinToastError 186 | { 187 | NoError = 0, 188 | NotInitialized, 189 | SystemNotSupported, 190 | ShellLinkNotCreated, 191 | InvalidAppUserModelID, 192 | InvalidParameters, 193 | InvalidHandler, 194 | NotDisplayed, 195 | UnknownError 196 | }; 197 | 198 | enum ShortcutResult 199 | { 200 | SHORTCUT_UNCHANGED = 0, 201 | SHORTCUT_WAS_CHANGED = 1, 202 | SHORTCUT_WAS_CREATED = 2, 203 | 204 | SHORTCUT_MISSING_PARAMETERS = -1, 205 | SHORTCUT_INCOMPATIBLE_OS = -2, 206 | SHORTCUT_COM_INIT_FAILURE = -3, 207 | SHORTCUT_CREATE_FAILED = -4 208 | }; 209 | 210 | enum ShortcutPolicy 211 | { 212 | /* Don't check, create, or modify a shortcut. */ 213 | SHORTCUT_POLICY_IGNORE = 0, 214 | /* Require a shortcut with matching AUMI, don't create or modify an existing one. */ 215 | SHORTCUT_POLICY_REQUIRE_NO_CREATE = 1, 216 | /* Require a shortcut with matching AUMI, create if missing, modify if not matching. This is the default. */ 217 | SHORTCUT_POLICY_REQUIRE_CREATE = 2, 218 | }; 219 | 220 | WinToast(void); 221 | virtual ~WinToast(); 222 | static WinToast* instance(); 223 | static bool isCompatible(); 224 | static bool isSupportingModernFeatures(); 225 | static bool isWin10AnniversaryOrHigher(); 226 | static std::wstring configureAUMI(_In_ std::wstring const& companyName, _In_ std::wstring const& productName, 227 | _In_ std::wstring const& subProduct = std::wstring(), 228 | _In_ std::wstring const& versionInformation = std::wstring()); 229 | static std::wstring const& strerror(_In_ WinToastError error); 230 | virtual bool initialize(_Out_opt_ WinToastError* error = nullptr); 231 | virtual bool isInitialized() const; 232 | virtual bool hideToast(_In_ INT64 id); 233 | virtual INT64 showToast(_In_ WinToastTemplate const& toast, _In_ IWinToastHandler* eventHandler, 234 | _Out_opt_ WinToastError* error = nullptr); 235 | virtual void clear(); 236 | virtual enum ShortcutResult createShortcut(); 237 | 238 | std::wstring const& appName() const; 239 | std::wstring const& appUserModelId() const; 240 | void setAppUserModelId(_In_ std::wstring const& aumi); 241 | void setAppName(_In_ std::wstring const& appName); 242 | void setShortcutPolicy(_In_ ShortcutPolicy policy); 243 | 244 | protected: 245 | struct NotifyData 246 | { 247 | NotifyData() 248 | { 249 | }; 250 | 251 | NotifyData(_In_ ComPtr notify, _In_ EventRegistrationToken activatedToken, 252 | _In_ EventRegistrationToken dismissedToken, _In_ EventRegistrationToken failedToken) : 253 | _notify(notify), _activatedToken(activatedToken), _dismissedToken(dismissedToken), 254 | _failedToken(failedToken) 255 | { 256 | } 257 | 258 | ~NotifyData() 259 | { 260 | RemoveTokens(); 261 | } 262 | 263 | void RemoveTokens() 264 | { 265 | if (!_readyForDeletion) 266 | { 267 | return; 268 | } 269 | 270 | if (_previouslyTokenRemoved) 271 | { 272 | return; 273 | } 274 | 275 | if (!_notify.Get()) 276 | { 277 | return; 278 | } 279 | 280 | _notify->remove_Activated(_activatedToken); 281 | _notify->remove_Dismissed(_dismissedToken); 282 | _notify->remove_Failed(_failedToken); 283 | _previouslyTokenRemoved = true; 284 | } 285 | 286 | void markAsReadyForDeletion() 287 | { 288 | _readyForDeletion = true; 289 | } 290 | 291 | bool isReadyForDeletion() const 292 | { 293 | return _readyForDeletion; 294 | } 295 | 296 | IToastNotification* notification() 297 | { 298 | return _notify.Get(); 299 | } 300 | 301 | private: 302 | ComPtr _notify{nullptr}; 303 | EventRegistrationToken _activatedToken{}; 304 | EventRegistrationToken _dismissedToken{}; 305 | EventRegistrationToken _failedToken{}; 306 | bool _readyForDeletion{false}; 307 | bool _previouslyTokenRemoved{false}; 308 | }; 309 | 310 | bool _isInitialized{false}; 311 | bool _hasCoInitialized{false}; 312 | ShortcutPolicy _shortcutPolicy{SHORTCUT_POLICY_REQUIRE_CREATE}; 313 | std::wstring _appName{}; 314 | std::wstring _aumi{}; 315 | std::map _buffer{}; 316 | 317 | void markAsReadyForDeletion(_In_ INT64 id); 318 | HRESULT validateShellLinkHelper(_Out_ bool& wasChanged); 319 | HRESULT createShellLinkHelper(); 320 | HRESULT setImageFieldHelper(_In_ IXmlDocument* xml, _In_ std::wstring const& path, _In_ bool isToastGeneric, 321 | bool isCropHintCircle); 322 | HRESULT setHeroImageHelper(_In_ IXmlDocument* xml, _In_ std::wstring const& path, _In_ bool isInlineImage); 323 | HRESULT setBindToastGenericHelper(_In_ IXmlDocument* xml); 324 | HRESULT 325 | setAudioFieldHelper(_In_ IXmlDocument* xml, _In_ std::wstring const& path, 326 | _In_opt_ WinToastTemplate::AudioOption option = WinToastTemplate::AudioOption::Default); 327 | HRESULT setTextFieldHelper(_In_ IXmlDocument* xml, _In_ std::wstring const& text, _In_ UINT32 pos); 328 | HRESULT setAttributionTextFieldHelper(_In_ IXmlDocument* xml, _In_ std::wstring const& text); 329 | HRESULT addActionHelper(_In_ IXmlDocument* xml, _In_ std::wstring const& action, 330 | _In_ std::wstring const& arguments); 331 | HRESULT addDurationHelper(_In_ IXmlDocument* xml, _In_ std::wstring const& duration); 332 | HRESULT addScenarioHelper(_In_ IXmlDocument* xml, _In_ std::wstring const& scenario); 333 | ComPtr notifier(_In_ bool* succeded) const; 334 | void setError(_Out_opt_ WinToastError* error, _In_ WinToastError value); 335 | }; 336 | } // namespace WinToastLib 337 | #endif // WINTOASTLIB_H 338 | -------------------------------------------------------------------------------- /ThreeFingerDrag/gesture/touch_processor.cpp: -------------------------------------------------------------------------------- 1 | #include "touch_processor.h" 2 | #include 3 | #include 4 | 5 | namespace Touchpad 6 | { 7 | TouchProcessor::TouchProcessor() 8 | { 9 | config = GlobalConfig::GetInstance(); 10 | 11 | touch_activity_event_.AddListener(std::bind( 12 | &EventListeners::TouchActivityListener::OnTouchActivity, 13 | &activity_listener_, 14 | std::placeholders::_1)); 15 | 16 | touch_up_event_.AddListener(std::bind( 17 | &EventListeners::TouchUpListener::OnTouchUp, 18 | &touch_up_listener_, 19 | std::placeholders::_1)); 20 | } 21 | 22 | void TouchProcessor::ClearContacts() 23 | { 24 | parsed_contacts_.clear(); 25 | } 26 | 27 | /** 28 | * \brief Retrieves touchpad input data from a raw input handle. 29 | * \param hRawInputHandle Handle to the raw input. 30 | * \return A struct containing the touchpad input data. 31 | */ 32 | void TouchProcessor::ProcessRawInput(const HRAWINPUT hRawInputHandle) 33 | { 34 | const bool log_debug = config->LogDebug(); 35 | 36 | // Initialize touchpad input data struct with default values. 37 | TouchInputData data{}; 38 | 39 | // Initialize variable to hold size of raw input. 40 | UINT size = sizeof(RAWINPUT); 41 | 42 | // Get process heap handle. 43 | const HANDLE hHeap = GetProcessHeap(); 44 | 45 | // Get size of raw input data. 46 | GetRawInputData(hRawInputHandle, RID_INPUT, nullptr, &size, sizeof(RAWINPUTHEADER)); 47 | 48 | if (size == 0) 49 | { 50 | if (log_debug) 51 | DEBUG("No data present."); 52 | return; 53 | } 54 | 55 | // Allocate memory for raw input data. 56 | auto* raw_input = static_cast(HeapAlloc(hHeap, 0, size)); 57 | 58 | if (raw_input == nullptr) 59 | return; 60 | 61 | // Get raw input data. 62 | if (GetRawInputData(hRawInputHandle, RID_INPUT, raw_input, &size, sizeof(RAWINPUTHEADER)) == static_cast(- 63 | 1)) 64 | { 65 | HeapFree(hHeap, 0, raw_input); 66 | ERROR("Could not retrieve raw input data from the HID device."); 67 | return; 68 | } 69 | 70 | // Get size of pre-parsed data buffer. 71 | UINT buffer_size; 72 | GetRawInputDeviceInfo(raw_input->header.hDevice, RIDI_PREPARSEDDATA, nullptr, &buffer_size); 73 | 74 | if (buffer_size == 0) 75 | { 76 | HeapFree(hHeap, 0, raw_input); 77 | ERROR("Could not retrieve pre-parsed data buffer from the HID device."); 78 | return; 79 | } 80 | 81 | // Allocate memory for pre-parsed data buffer. 82 | const auto pre_parsed_data = static_cast(HeapAlloc(hHeap, 0, buffer_size)); 83 | 84 | // Get pre-parsed data buffer. 85 | GetRawInputDeviceInfo(raw_input->header.hDevice, RIDI_PREPARSEDDATA, pre_parsed_data, &buffer_size); 86 | 87 | // Get capabilities of HID device. 88 | HIDP_CAPS caps; 89 | if (HidP_GetCaps(pre_parsed_data, &caps) != HIDP_STATUS_SUCCESS) 90 | { 91 | HeapFree(hHeap, 0, raw_input); 92 | HeapFree(hHeap, 0, pre_parsed_data); 93 | ERROR("Could not retrieve capabilities from the HID device."); 94 | return; 95 | } 96 | 97 | // Get number of input value caps. 98 | USHORT length = caps.NumberInputValueCaps; 99 | 100 | // Allocate memory for input value caps. 101 | const auto value_caps = static_cast(HeapAlloc(hHeap, 0, sizeof(HIDP_VALUE_CAPS) * length)); 102 | 103 | // Get input value caps. 104 | if (HidP_GetValueCaps(HidP_Input, value_caps, &length, pre_parsed_data) != HIDP_STATUS_SUCCESS) 105 | { 106 | HeapFree(hHeap, 0, raw_input); 107 | HeapFree(hHeap, 0, pre_parsed_data); 108 | HeapFree(hHeap, 0, value_caps); 109 | ERROR("Could not retrieve input value caps from the HID device."); 110 | return; 111 | } 112 | 113 | if (log_debug) 114 | DEBUG("Data Length = " + std::to_string(length)); 115 | 116 | // Initialize vector to hold touchpad contact data. 117 | std::vector received_contacts; 118 | 119 | // Loop through input value caps and retrieve touchpad data. 120 | ULONG value; 121 | TouchContact parsed_contact{INIT_VALUE, INIT_VALUE, INIT_VALUE, false}; 122 | for (USHORT i = 0; i < length; i++) 123 | { 124 | auto current_cap = value_caps[i]; 125 | if (HidP_GetUsageValue( 126 | HidP_Input, 127 | current_cap.UsagePage, 128 | current_cap.LinkCollection, 129 | current_cap.NotRange.Usage, 130 | &value, 131 | pre_parsed_data, 132 | (PCHAR)raw_input->data.hid.bRawData, 133 | raw_input->data.hid.dwSizeHid 134 | ) != HIDP_STATUS_SUCCESS) 135 | { 136 | continue; 137 | } 138 | 139 | const USAGE usage_page = current_cap.UsagePage; 140 | const USAGE usage = current_cap.Range.UsageMin; 141 | switch (current_cap.LinkCollection) 142 | { 143 | default: 144 | switch (usage_page) 145 | { 146 | case HID_USAGE_PAGE_GENERIC: 147 | if (current_cap.NotRange.Usage == HID_USAGE_GENERIC_X) 148 | { 149 | parsed_contact.minimum_x = current_cap.LogicalMin; 150 | parsed_contact.maximum_x = current_cap.LogicalMax; 151 | parsed_contact.has_x_bounds = true; 152 | } 153 | else if (current_cap.NotRange.Usage == HID_USAGE_GENERIC_Y) 154 | { 155 | parsed_contact.minimum_y = current_cap.LogicalMin; 156 | parsed_contact.maximum_y = current_cap.LogicalMax; 157 | parsed_contact.has_y_bounds = true; 158 | } 159 | switch (usage) 160 | { 161 | case USAGE_DIGITIZER_X_COORDINATE: 162 | parsed_contact.x = static_cast(value); 163 | break; 164 | case USAGE_DIGITIZER_Y_COORDINATE: 165 | parsed_contact.y = static_cast(value); 166 | break; 167 | default: break; 168 | } 169 | break; 170 | case HID_USAGE_PAGE_DIGITIZER: 171 | if (usage == USAGE_DIGITIZER_CONTACT_ID) 172 | parsed_contact.contact_id = static_cast(value); 173 | break; 174 | default: break; 175 | } 176 | break; 177 | } 178 | 179 | // If all contact fields are populated, add contact to list and reset fields. 180 | if (parsed_contact.contact_id != INIT_VALUE && parsed_contact.x != INIT_VALUE && parsed_contact.y != 181 | INIT_VALUE) 182 | { 183 | const ULONG maxNumButtons = 184 | HidP_MaxUsageListLength(HidP_Input, HID_USAGE_PAGE_DIGITIZER, pre_parsed_data); 185 | USAGE* buttonUsageArray = (USAGE*)malloc(sizeof(USAGE) * maxNumButtons); 186 | ULONG _maxNumButtons = maxNumButtons; 187 | 188 | if (HidP_GetUsages( 189 | HidP_Input, 190 | HID_USAGE_PAGE_DIGITIZER, 191 | current_cap.LinkCollection, 192 | buttonUsageArray, 193 | &_maxNumButtons, 194 | pre_parsed_data, 195 | (PCHAR)raw_input->data.hid.bRawData, 196 | raw_input->data.hid.dwSizeHid) == HIDP_STATUS_SUCCESS) 197 | { 198 | for (ULONG usageIdx = 0; usageIdx < maxNumButtons; usageIdx++) 199 | { 200 | // Determine if this contact point is on the touchpad surface 201 | if (buttonUsageArray[usageIdx] == HID_USAGE_DIGITIZER_TIP_SWITCH) 202 | { 203 | parsed_contact.on_surface = true; 204 | break; 205 | } 206 | } 207 | 208 | free(buttonUsageArray); 209 | } 210 | 211 | received_contacts.emplace_back(parsed_contact); 212 | 213 | parsed_contact = {INIT_VALUE, INIT_VALUE, INIT_VALUE, false}; 214 | } 215 | } 216 | // Free allocated memory. 217 | HeapFree(hHeap, 0, raw_input); 218 | HeapFree(hHeap, 0, pre_parsed_data); 219 | HeapFree(hHeap, 0, value_caps); 220 | 221 | const auto interval = EventListeners::CalculateElapsedTimeMs( 222 | config->GetLastEvent(), std::chrono::high_resolution_clock::now()); 223 | 224 | // Clear any old contact data if enough time has passed 225 | if (interval > config->GetCancellationDelayMs()) 226 | ClearContacts(); 227 | 228 | if (log_debug) 229 | { 230 | std::ostringstream debug; 231 | debug << "[RAW REPORTED DATA]\n\n"; 232 | debug << "Interval: " << std::to_string(interval) << "ms\n"; 233 | debug << DebugPoints(received_contacts); 234 | DEBUG(debug.str()); 235 | } 236 | 237 | UpdateTouchContactsState(received_contacts); 238 | RaiseEventsIfNeeded(); 239 | } 240 | 241 | void TouchProcessor::UpdateTouchContactsState(const std::vector& received_contacts) 242 | { 243 | std::lock_guard lock(contacts_mutex_); 244 | std::unordered_map id_to_contact_map; 245 | 246 | for (const auto& contact : parsed_contacts_) 247 | { 248 | id_to_contact_map[contact.contact_id] = contact; 249 | } 250 | 251 | // Validate each received contact and filter out unwanted data 252 | for (const auto& received_contact : received_contacts) 253 | { 254 | if (received_contact.contact_id > CONTACT_ID_MAXIMUM || received_contact.contact_id < 0) 255 | continue; 256 | 257 | if (received_contact.x == 0 || received_contact.y == 0) 258 | continue; 259 | 260 | if (received_contact.has_x_bounds) 261 | { 262 | const auto min_x = received_contact.minimum_x; 263 | const auto max_x = received_contact.maximum_x; 264 | if (!ValueWithinRange(received_contact.x, min_x, max_x)) 265 | continue; 266 | } 267 | if (received_contact.has_y_bounds) 268 | { 269 | const auto min_y = received_contact.minimum_y; 270 | const auto max_y = received_contact.maximum_y; 271 | if (!ValueWithinRange(received_contact.y, min_y, max_y)) 272 | continue; 273 | } 274 | id_to_contact_map[received_contact.contact_id] = received_contact; 275 | } 276 | 277 | parsed_contacts_.clear(); 278 | for (const auto& pair : id_to_contact_map) 279 | { 280 | parsed_contacts_.push_back(pair.second); 281 | } 282 | 283 | std::sort(parsed_contacts_.begin(), parsed_contacts_.end(), [](const TouchContact& a, const TouchContact& b) 284 | { 285 | return a.contact_id < b.contact_id; 286 | }); 287 | } 288 | 289 | void TouchProcessor::RaiseEventsIfNeeded() 290 | { 291 | std::lock_guard lock(contacts_mutex_); 292 | const int current_contact_count = CountTouchPointsMakingContact(parsed_contacts_); 293 | const bool has_contact = current_contact_count > 0; 294 | const auto time = std::chrono::high_resolution_clock::now(); 295 | 296 | // Construct the TouchInputData object 297 | TouchInputData touchInputData; 298 | touchInputData.contacts = parsed_contacts_; 299 | touchInputData.contact_count = parsed_contacts_.size(); 300 | touchInputData.can_perform_gesture = current_contact_count == 301 | EventListeners::NUM_TOUCH_CONTACTS_REQUIRED; 302 | 303 | // Determine if a touch up event should be raised 304 | const int previous_contact_count = CountTouchPointsMakingContact(config->GetPreviousTouchContacts()); 305 | const bool previous_has_contact = previous_contact_count > 0; 306 | const bool touch_up_event = !has_contact && previous_has_contact || !has_contact && !previous_has_contact; 307 | 308 | if (touch_up_event) 309 | { 310 | touch_up_event_.RaiseEvent(TouchUpEventArgs(time, &touchInputData, config->GetPreviousTouchContacts())); 311 | } 312 | else if (has_contact) 313 | { 314 | touch_activity_event_.RaiseEvent( 315 | TouchActivityEventArgs(time, &touchInputData, config->GetPreviousTouchContacts())); 316 | } 317 | 318 | // Optionally, log the event details for debugging 319 | if (config->LogDebug()) 320 | { 321 | LogEventDetails(touch_up_event, time); 322 | } 323 | 324 | config->SetPreviousTouchContacts(parsed_contacts_); 325 | config->SetLastEvent(time); 326 | 327 | const auto it = std::remove_if(parsed_contacts_.begin(), parsed_contacts_.end(), 328 | [](const TouchContact& tc) { return !tc.on_surface; }); 329 | parsed_contacts_.erase(it, parsed_contacts_.end()); 330 | } 331 | 332 | void TouchProcessor::LogEventDetails(bool touch_up_event, 333 | const std::chrono::high_resolution_clock::time_point& time) const 334 | { 335 | std::stringstream debug; 336 | debug << "[RAISED EVENT]\n\n"; 337 | debug << "TYPE: "; 338 | if (touch_up_event) 339 | debug << "TouchUpEvent"; 340 | else 341 | debug << "TouchActivityEvent"; 342 | debug << "\n"; 343 | debug << "Interval: " << std::to_string(EventListeners::CalculateElapsedTimeMs(config->GetLastEvent(), time)) << 344 | "ms\n"; 345 | debug << DebugPoints(parsed_contacts_); 346 | DEBUG(debug.str()); 347 | } 348 | 349 | std::string TouchProcessor::DebugPoints(const std::vector& data) 350 | { 351 | std::ostringstream oss; 352 | oss << "Contacts: (size = " << data.size() << ")\n"; 353 | for (const auto& contact : data) 354 | { 355 | oss << "[ID: " << contact.contact_id 356 | << ", X: " << contact.x 357 | << ", Y: " << contact.y 358 | << ", On Surface: " << (contact.on_surface ? "Yes" : "No") << "]"; 359 | if (contact.has_x_bounds) 360 | oss << ", X Boundary: (min=" << contact.minimum_x << ", max=" << contact.maximum_x << ")"; 361 | if (contact.has_y_bounds) 362 | oss << ", Y Boundary: (min=" << contact.minimum_y << ", max=" << contact.maximum_y << ")"; 363 | oss << "\n"; 364 | } 365 | return oss.str(); 366 | } 367 | 368 | int TouchProcessor::CountTouchPointsMakingContact(const std::vector& points) 369 | { 370 | return std::count_if(points.begin(), points.end(), [](const TouchContact& p) 371 | { 372 | return p.on_surface; 373 | }); 374 | } 375 | 376 | bool TouchProcessor::ValueWithinRange(const int value, const int minimum, const int maximum) 377 | { 378 | return value < maximum && value > minimum; 379 | } 380 | } 381 | -------------------------------------------------------------------------------- /ThreeFingerDrag/ThreeFingerDrag.cpp: -------------------------------------------------------------------------------- 1 | #include "ThreeFingerDrag.h" 2 | 3 | using namespace Touchpad; 4 | using namespace WinToastLib; 5 | 6 | // Constants 7 | namespace 8 | { 9 | constexpr auto STARTUP_REGISTRY_KEY = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"; 10 | constexpr auto PROGRAM_NAME = L"ThreeFingerDrag"; 11 | constexpr auto TOUCH_ACTIVITY_PERIOD_MS = std::chrono::milliseconds(1); 12 | constexpr auto MAX_LOAD_STRING_LENGTH = 100; 13 | 14 | constexpr auto SETTINGS_WINDOW_WIDTH = 456; 15 | constexpr auto SETTINGS_WINDOW_HEIGHT = 170; 16 | constexpr auto MIN_CANCELLATION_DELAY_MS = 100; 17 | constexpr auto MAX_CANCELLATION_DELAY_MS = 2000; 18 | constexpr auto MIN_GESTURE_SPEED = 1; 19 | constexpr auto MAX_GESTURE_SPEED = 100; 20 | constexpr auto ID_SETTINGS_MENUITEM = 10000; 21 | constexpr auto ID_QUIT_MENUITEM = 10001; 22 | constexpr auto ID_RUN_ON_STARTUP_CHECKBOX = 10002; 23 | constexpr auto ID_GESTURE_SPEED_TRACKBAR = 10003; 24 | constexpr auto ID_TEXT_BOX = 10004; 25 | constexpr auto ID_CANCELLATION_DELAY_SPINNER = 10005; 26 | constexpr auto ID_OPEN_CONFIG_FOLDER = 10005; 27 | } 28 | 29 | // Global Variables 30 | 31 | HINSTANCE current_instance; 32 | HWND tray_icon_hwnd; 33 | HWND settings_hwnd; 34 | HWND settings_trackbar_hwnd; 35 | HWND settings_checkbox_hwnd; 36 | WCHAR title_bar_text[MAX_LOAD_STRING_LENGTH]; 37 | WCHAR settings_title_text[MAX_LOAD_STRING_LENGTH]; 38 | WCHAR main_window_class_name[MAX_LOAD_STRING_LENGTH]; 39 | WCHAR settings_window_class_name[MAX_LOAD_STRING_LENGTH]; 40 | NOTIFYICONDATA tray_icon_data; 41 | TouchProcessor touch_processor; 42 | std::thread touch_activity_thread; 43 | BOOL application_running = TRUE; 44 | BOOL gui_initialized = FALSE; 45 | HBRUSH white_brush = CreateSolidBrush(RGB(255, 255, 255)); 46 | HFONT normal_font = CreateFont(17, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_TT_PRECIS, 47 | CLIP_DEFAULT_PRECIS, PROOF_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Segoe UI")); 48 | GlobalConfig* config = GlobalConfig::GetInstance(); 49 | 50 | // Forward declarations 51 | 52 | ATOM RegisterWindowClass(HINSTANCE, WCHAR*, WNDPROC); 53 | BOOL InitInstance(); 54 | LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); 55 | LRESULT CALLBACK SettingsWndProc(HWND, UINT, WPARAM, LPARAM); 56 | 57 | void CreateTrayMenu(HWND hWnd); 58 | void ShowSettingsWindow(); 59 | void AddStartupTask(); 60 | void RemoveStartupTask(); 61 | void RemoveStartupRegistryKey(); 62 | void StartPeriodicUpdateThreads(); 63 | void HandleUncaughtExceptions(); 64 | void PerformAdditionalSteps(); 65 | void PromptUserForStartupPreference(); 66 | void InitializeConfiguration(); 67 | bool InitializeWindowsNotifications(); 68 | bool StartupRegistryKeyExists(); 69 | bool RegisterRawInputDevices(); 70 | bool CheckSingleInstance(); 71 | bool InitializeGUI(); 72 | 73 | int APIENTRY wWinMain(_In_ HINSTANCE hInstance, 74 | _In_opt_ HINSTANCE hPrevInstance, 75 | _In_ LPWSTR lpCmdLine, 76 | _In_ int nCmdShow) 77 | { 78 | Application::CheckPortableMode(); 79 | 80 | current_instance = hInstance; 81 | UNREFERENCED_PARAMETER(hPrevInstance); 82 | UNREFERENCED_PARAMETER(lpCmdLine); 83 | 84 | std::set_terminate(HandleUncaughtExceptions); 85 | 86 | if (!CheckSingleInstance()) 87 | { 88 | return FALSE; 89 | } 90 | 91 | InitializeConfiguration(); 92 | 93 | if (!InitInstance()) 94 | { 95 | ERROR("Application initialization failed."); 96 | return FALSE; 97 | } 98 | 99 | StartPeriodicUpdateThreads(); 100 | PerformAdditionalSteps(); 101 | 102 | MSG msg; 103 | while (GetMessage(&msg, nullptr, 0, 0)) 104 | { 105 | TranslateMessage(&msg); 106 | DispatchMessage(&msg); 107 | } 108 | 109 | // Delete tray icon 110 | Shell_NotifyIcon(NIM_DELETE, &tray_icon_data); 111 | 112 | // Join threads 113 | application_running = false; 114 | if (touch_activity_thread.joinable()) 115 | touch_activity_thread.join(); 116 | return static_cast(msg.wParam); 117 | } 118 | 119 | BOOL InitInstance() 120 | { 121 | const bool log = config->LogDebug(); 122 | // Initialize WinToast notifications 123 | if (!InitializeWindowsNotifications()) 124 | { 125 | ERROR("Failed to initialize WinToast."); 126 | return FALSE; 127 | } 128 | if (log) 129 | DEBUG("Initialized notifications."); 130 | // Initialize tray icon, settings window 131 | if (!InitializeGUI()) 132 | { 133 | Popups::DisplayErrorMessage("GUI initialization failed!"); 134 | return FALSE; 135 | } 136 | if (log) 137 | DEBUG("Initialized GUI."); 138 | // Start listening to raw touchpad input. 139 | if (!RegisterRawInputDevices()) 140 | { 141 | Popups::DisplayErrorMessage( 142 | "ThreeFingerDrag couldn't find a precision touchpad device on your system. The program will now exit."); 143 | return FALSE; 144 | } 145 | if (log) 146 | DEBUG("Registered raw input device."); 147 | 148 | // Show the settings icon 149 | Shell_NotifyIcon(NIM_ADD, &tray_icon_data); 150 | 151 | if (config->LogDebug()) 152 | DEBUG("Application initialized successfully!"); 153 | return TRUE; 154 | } 155 | 156 | LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) 157 | { 158 | static UINT taskbar_restarted; 159 | switch (message) 160 | { 161 | case WM_CREATE: 162 | taskbar_restarted = RegisterWindowMessage(TEXT("TaskbarCreated")); 163 | break; 164 | 165 | // Raw touch device input 166 | case WM_INPUT: 167 | touch_processor.ProcessRawInput((HRAWINPUT)lParam); 168 | break; 169 | 170 | // Notify Icon 171 | case WM_APP: 172 | switch (lParam) 173 | { 174 | case WM_LBUTTONDOWN: 175 | case WM_RBUTTONDOWN: 176 | CreateTrayMenu(hWnd); 177 | break; 178 | default: 179 | return DefWindowProc(hWnd, message, wParam, lParam); 180 | } 181 | break; 182 | case WM_COMMAND: 183 | { 184 | // Parse menu selections 185 | switch (LOWORD(wParam)) 186 | { 187 | case ID_QUIT_MENUITEM: 188 | DestroyWindow(hWnd); 189 | break; 190 | case ID_SETTINGS_MENUITEM: 191 | ShowSettingsWindow(); 192 | break; 193 | case ID_OPEN_CONFIG_FOLDER: 194 | ShellExecuteA(NULL, "open", Application::config_folder_path.c_str(), NULL, NULL, SW_SHOWNORMAL); 195 | break; 196 | default: 197 | return DefWindowProc(hWnd, message, wParam, lParam); 198 | } 199 | } 200 | break; 201 | case WM_DESTROY: 202 | DeleteObject(white_brush); 203 | DeleteObject(normal_font); 204 | PostQuitMessage(0); 205 | break; 206 | default: 207 | if (message == taskbar_restarted) 208 | { 209 | Shell_NotifyIcon(NIM_DELETE, &tray_icon_data); 210 | InitializeGUI(); 211 | Shell_NotifyIcon(NIM_ADD, &tray_icon_data); 212 | if (config->LogDebug()) 213 | DEBUG("Refreshing tray icon"); 214 | break; 215 | } 216 | return DefWindowProc(hWnd, message, wParam, lParam); 217 | } 218 | return 0; 219 | } 220 | 221 | LRESULT CALLBACK SettingsWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) 222 | { 223 | const auto loword_param = LOWORD(wParam); 224 | const auto hiword_param = HIWORD(wParam); 225 | switch (msg) 226 | { 227 | case WM_COMMAND: 228 | 229 | if (hiword_param == EN_CHANGE) 230 | { 231 | // Ignore change events until GUI has been initialized 232 | if (!gui_initialized) 233 | return TRUE; 234 | 235 | switch (loword_param) 236 | { 237 | // The text in the textbox has changed. Update the config value 238 | case ID_TEXT_BOX: 239 | wchar_t buffer[64]; 240 | GetWindowText((HWND)lParam, buffer, 64); // get textbox text 241 | config->SetCancellationDelayMs(_wtoi(buffer)); // convert to integer (only numerical values are entered) 242 | Application::WriteConfiguration(); 243 | break; 244 | } 245 | } 246 | 247 | switch (loword_param) 248 | { 249 | case ID_RUN_ON_STARTUP_CHECKBOX: 250 | // Run on startup checkbox clicked 251 | if (SendMessage(GetDlgItem(hWnd, ID_RUN_ON_STARTUP_CHECKBOX), BM_GETCHECK, 0, 0) == BST_CHECKED) 252 | AddStartupTask(); 253 | else 254 | RemoveStartupTask(); 255 | break; 256 | } 257 | break; 258 | 259 | case WM_HSCROLL: 260 | if (GetDlgCtrlID((HWND)lParam) == ID_GESTURE_SPEED_TRACKBAR) 261 | { 262 | if (loword_param < TB_THUMBTRACK) 263 | { 264 | // Trackbar value changed 265 | config->SetGestureSpeed(SendMessage((HWND)lParam, TBM_GETPOS, 0, 0)); 266 | Application::WriteConfiguration(); 267 | } 268 | } 269 | break; 270 | 271 | case WM_CTLCOLORSTATIC: 272 | { 273 | const auto hdcStatic = (HDC)wParam; 274 | SetBkColor(hdcStatic, RGB(255, 255, 255)); 275 | return (INT_PTR)white_brush; 276 | } 277 | 278 | case WM_ERASEBKGND: 279 | { 280 | const auto hdc = (HDC)wParam; 281 | RECT rect; 282 | GetClientRect(hWnd, &rect); 283 | FillRect(hdc, &rect, white_brush); 284 | return TRUE; 285 | } 286 | 287 | case WM_CLOSE: 288 | ShowWindow(hWnd, SW_HIDE); 289 | return TRUE; 290 | } 291 | 292 | return DefWindowProc(hWnd, msg, wParam, lParam); 293 | } 294 | 295 | /** 296 | * \brief Create the main application window and the settings window. 297 | */ 298 | bool InitializeGUI() 299 | { 300 | tray_icon_hwnd = CreateWindowEx( 301 | WS_EX_TOOLWINDOW, 302 | main_window_class_name, 303 | title_bar_text, 304 | 0, 305 | 0, 0, 306 | 0, 0, 307 | NULL, 308 | NULL, 309 | current_instance, 310 | NULL); 311 | 312 | if (!tray_icon_hwnd) 313 | { 314 | ERROR("Tray icon window handle could not be created!"); 315 | return FALSE; 316 | } 317 | 318 | // Initialize tray icon data 319 | tray_icon_data.cbSize = sizeof(NOTIFYICONDATA); 320 | tray_icon_data.hWnd = tray_icon_hwnd; 321 | tray_icon_data.uID = 1; 322 | tray_icon_data.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; 323 | tray_icon_data.uCallbackMessage = WM_APP; 324 | tray_icon_data.hIcon = LoadIcon(current_instance, MAKEINTRESOURCE(IDI_THREEFINGERDRAG)); 325 | 326 | // Set tooltip to versioned title 327 | std::string title = "Three Finger Drag "; 328 | title.append(Application::GetVersionString()); 329 | const std::wstring w_title(title.begin(), title.end()); 330 | lstrcpy(tray_icon_data.szTip, w_title.c_str()); 331 | 332 | // Create the settings window 333 | 334 | settings_hwnd = CreateWindowEx( 335 | WS_EX_TOPMOST | WS_EX_COMPOSITED, // Always on top and enable double-buffering 336 | settings_window_class_name, 337 | settings_title_text, 338 | WS_SYSMENU, 339 | CW_USEDEFAULT, CW_USEDEFAULT, 340 | SETTINGS_WINDOW_WIDTH, SETTINGS_WINDOW_HEIGHT, 341 | tray_icon_hwnd, 342 | NULL, 343 | current_instance, 344 | NULL 345 | ); 346 | 347 | constexpr int textbox_width = 56, textbox_height = 24; 348 | constexpr int label_height = 20, trackbar_height = 46; 349 | constexpr int margin = 32; 350 | int pos_x = 8, pos_y = 8; 351 | 352 | // Run on startup checkbox 353 | settings_checkbox_hwnd = CreateWindowW(L"button", L"Run ThreeFingerDrag on startup of Windows", 354 | WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX, 355 | pos_x, pos_y, SETTINGS_WINDOW_WIDTH - 32, 20, settings_hwnd, 356 | (HMENU)ID_RUN_ON_STARTUP_CHECKBOX, NULL, NULL); 357 | 358 | SendMessage(settings_checkbox_hwnd, WM_SETFONT, reinterpret_cast(normal_font), TRUE); 359 | 360 | pos_y += 24; 361 | 362 | // Numeric textbox 363 | HWND hwndTextBox = CreateWindowEx(WS_EX_CLIENTEDGE, L"EDIT", NULL, 364 | WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_NUMBER, 365 | pos_x, pos_y, textbox_width, textbox_height, 366 | settings_hwnd, (HMENU)ID_TEXT_BOX, current_instance, NULL); 367 | 368 | SendMessage(hwndTextBox, WM_SETFONT, reinterpret_cast(normal_font), TRUE); 369 | 370 | // Spinner for numeric textbox 371 | HWND settings_spinner_hwnd = CreateWindowW(L"msctls_updown32", NULL, 372 | WS_CHILD | WS_VISIBLE | UDS_ALIGNRIGHT | UDS_ARROWKEYS | UDS_SETBUDDYINT 373 | | UDS_NOTHOUSANDS, 374 | pos_x, pos_y, 0, label_height, 375 | settings_hwnd, (HMENU)ID_CANCELLATION_DELAY_SPINNER, current_instance, 376 | NULL); 377 | 378 | SendMessage(settings_spinner_hwnd, UDM_SETBUDDY, (WPARAM)hwndTextBox, 0); 379 | SendMessage(settings_spinner_hwnd, UDM_SETRANGE, 0, MAKELONG(MAX_CANCELLATION_DELAY_MS, MIN_CANCELLATION_DELAY_MS)); 380 | SendMessage(settings_spinner_hwnd, UDM_SETPOS, 0, MAKELONG(config->GetCancellationDelayMs(), 0)); 381 | 382 | pos_x += 60; 383 | 384 | // Label for numeric textbox 385 | HWND hwnd_spinner_label = CreateWindowW(L"STATIC", L"Cancellation Delay (milliseconds)", 386 | WS_CHILD | WS_VISIBLE | SS_LEFT, 387 | pos_x, pos_y, SETTINGS_WINDOW_WIDTH - margin, label_height, 388 | settings_hwnd, NULL, NULL, NULL); 389 | 390 | SendMessage(hwnd_spinner_label, WM_SETFONT, reinterpret_cast(normal_font), TRUE); 391 | 392 | pos_x = 8; // Resetting the X position for the new line 393 | pos_y += 26; 394 | 395 | // Label for trackbar 396 | HWND hwnd_trackbar_label = CreateWindowW(WC_STATIC, L"Gesture speed (slower -> faster)", 397 | WS_CHILD | WS_VISIBLE | SS_LEFT, 398 | pos_x, pos_y, SETTINGS_WINDOW_WIDTH - margin, label_height, settings_hwnd, 399 | NULL, NULL, NULL); 400 | 401 | SendMessage(hwnd_trackbar_label, WM_SETFONT, reinterpret_cast(normal_font), TRUE); 402 | 403 | pos_y += 20; 404 | 405 | // Gesture speed trackbar 406 | settings_trackbar_hwnd = CreateWindowW(TRACKBAR_CLASS, NULL, 407 | WS_CHILD | WS_VISIBLE | TBS_AUTOTICKS | TBS_TOOLTIPS, 408 | pos_x, pos_y, SETTINGS_WINDOW_WIDTH - margin, trackbar_height, settings_hwnd, 409 | (HMENU)ID_GESTURE_SPEED_TRACKBAR, current_instance, NULL); 410 | SendMessage(settings_trackbar_hwnd, TBM_SETRANGE, TRUE, MAKELONG(MIN_GESTURE_SPEED, MAX_GESTURE_SPEED)); 411 | SendMessage(settings_trackbar_hwnd, TBM_SETPOS, TRUE, static_cast(config->GetGestureSpeed())); 412 | 413 | // Remove its resizable border 414 | LONG_PTR style = GetWindowLongPtr(settings_hwnd, GWL_STYLE); 415 | style &= ~(WS_SIZEBOX | WS_MAXIMIZEBOX); 416 | SetWindowLongPtr(settings_hwnd, GWL_STYLE, style); 417 | 418 | if (settings_hwnd == NULL) 419 | { 420 | ERROR("Settings window handle could not be created!"); 421 | return FALSE; 422 | } 423 | gui_initialized = TRUE; 424 | return TRUE; 425 | } 426 | 427 | 428 | /** 429 | * \brief Creates a menu and displays it at the cursor position. The menu contains options 430 | * to run the application on startup or remove the startup task, and to quit the application. 431 | * 432 | * \loword_param hWnd Handle to the window that will own the menu. 433 | */ 434 | void CreateTrayMenu(const HWND hWnd) 435 | { 436 | // Get the cursor position to determine where to display the menu. 437 | POINT pt; 438 | GetCursorPos(&pt); 439 | 440 | // Create the popup menu. 441 | const HMENU hMenu = CreatePopupMenu(); 442 | 443 | // Add the menu items 444 | AppendMenu(hMenu, MF_STRING, ID_SETTINGS_MENUITEM, TEXT("Settings")); 445 | AppendMenu(hMenu, MF_STRING, ID_OPEN_CONFIG_FOLDER, TEXT("Open Config")); 446 | 447 | // Add a separator and the "Exit" menu item. 448 | AppendMenu(hMenu, MF_SEPARATOR, 0, nullptr); 449 | AppendMenu(hMenu, MF_STRING, ID_QUIT_MENUITEM, TEXT("Exit")); 450 | 451 | // Set the window specified by tray_icon_hwnd to the foreground, so that the menu will be displayed above it. 452 | SetForegroundWindow(hWnd); 453 | 454 | // Display the popup menu. 455 | TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN, pt.x, pt.y, 0, hWnd, nullptr); 456 | 457 | PostMessage(hWnd, WM_NULL, 0, 0); 458 | DestroyMenu(hMenu); 459 | } 460 | 461 | /** 462 | * \brief Makes the settings window visible and positions it in the center of the screen. 463 | */ 464 | void ShowSettingsWindow() 465 | { 466 | // Update run on startup checkbox 467 | if (TaskScheduler::TaskExists("ThreeFingerDrag")) 468 | SendMessage(settings_checkbox_hwnd, BM_SETCHECK, BST_CHECKED, 0); 469 | else 470 | SendMessage(settings_checkbox_hwnd, BM_SETCHECK, BST_UNCHECKED, 0); 471 | 472 | // Update trackbar position 473 | SendMessage(settings_trackbar_hwnd, TBM_SETPOS, TRUE, static_cast(config->GetGestureSpeed())); 474 | 475 | RECT rect_client, rect_window; 476 | GetClientRect(settings_hwnd, &rect_client); 477 | GetWindowRect(settings_hwnd, &rect_window); 478 | const int x = GetSystemMetrics(SM_CXSCREEN) / 2 - (rect_window.right - rect_window.left) / 2; 479 | const int y = GetSystemMetrics(SM_CYSCREEN) / 2 - (rect_window.bottom - rect_window.top) / 2; 480 | MoveWindow(settings_hwnd, x, y, SETTINGS_WINDOW_WIDTH, SETTINGS_WINDOW_HEIGHT, TRUE); 481 | 482 | // Show and update the window 483 | ShowWindow(settings_hwnd, SW_SHOW); 484 | UpdateWindow(settings_hwnd); 485 | } 486 | 487 | /** 488 | * \brief Starts any threads required for periodic updates throughout the application. 489 | */ 490 | void StartPeriodicUpdateThreads() 491 | { 492 | // Check if the dragging action needs to be completed 493 | touch_activity_thread = std::thread([&] 494 | { 495 | while (application_running) 496 | { 497 | std::this_thread::sleep_for(TOUCH_ACTIVITY_PERIOD_MS); 498 | 499 | if (Cursor::IsLeftMouseDown() && config->IsGestureStarted()) 500 | { 501 | const auto interval = EventListeners::CalculateElapsedTimeMs( 502 | config->GetLastEvent(), std::chrono::high_resolution_clock::now()); 503 | if (interval > config->GetCancellationDelayMs()) 504 | { 505 | EventListeners::CancelGesture(); 506 | touch_processor.ClearContacts(); 507 | if (config->LogDebug()) 508 | DEBUG("Cancelled gesture (automatic timeout)."); 509 | } 510 | } 511 | 512 | // Only continue if a cancellation was initiated, or if the gesture is ongoing 513 | if (!config->IsCancellationStarted() && !config->IsGestureStarted()) 514 | continue; 515 | 516 | if (config->IsCancellationStarted()) // Check for cancellation timeout started by user 517 | { 518 | const auto now = std::chrono::high_resolution_clock::now(); 519 | const std::chrono::duration duration = now - config->GetCancellationTime(); 520 | const float ms_since_cancellation = duration.count() * 1000.0f; 521 | if (ms_since_cancellation < config->GetCancellationDelayMs()) 522 | { 523 | continue; 524 | } 525 | 526 | EventListeners::CancelGesture(); 527 | touch_processor.ClearContacts(); 528 | if (config->LogDebug()) 529 | DEBUG("Cancelled gesture (cancellation timeout)."); 530 | } 531 | else if (Cursor::IsLeftMouseDown()) // Check for automatic gesture timeout (failsafe) 532 | { 533 | const auto now = std::chrono::high_resolution_clock::now(); 534 | const auto ms_since_last_touch_event = EventListeners::CalculateElapsedTimeMs(config->GetLastEvent(), now); 535 | if (ms_since_last_touch_event > config->GetAutomaticTimeoutDelayMs()) 536 | { 537 | EventListeners::CancelGesture(); 538 | touch_processor.ClearContacts(); 539 | if (config->LogDebug()) 540 | DEBUG("Cancelled gesture (automatic timeout)."); 541 | } 542 | } 543 | } 544 | }); 545 | } 546 | 547 | /** 548 | * \brief Registers the first available precision touchpad as a raw input device, to listen for WM_INPUT events. 549 | * \return True if the raw input device was successfully registered. 550 | */ 551 | bool RegisterRawInputDevices() 552 | { 553 | // Register precision touchpad device 554 | 555 | RAWINPUTDEVICE rid; 556 | 557 | rid.usUsagePage = HID_USAGE_PAGE_DIGITIZER; 558 | rid.usUsage = HID_USAGE_DIGITIZER_TOUCH_PAD; 559 | rid.dwFlags = RIDEV_INPUTSINK; // Receive input even when the application is in the background 560 | rid.hwndTarget = tray_icon_hwnd; // Handle to the application window 561 | 562 | return RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE)); 563 | } 564 | 565 | /** 566 | * \brief Initializes WinToast to allow sending windows desktop notifications 567 | * \return True if the registry key exists, false otherwise. 568 | */ 569 | bool InitializeWindowsNotifications() 570 | { 571 | const auto app_name = L"ThreeFingerDrag"; 572 | 573 | WinToast::WinToastError error; 574 | WinToast::instance()->setAppName(app_name); 575 | 576 | auto str = Application::GetVersionString(); 577 | const std::wstring w_version(str.begin(), str.end()); 578 | const auto aumi = WinToast::configureAUMI(L"Austin Nixholm", app_name, L"Tool", L"Current"); 579 | 580 | WinToast::instance()->setAppUserModelId(aumi); 581 | 582 | if (!WinToast::instance()->initialize(&error)) 583 | { 584 | ERROR("WinToast could not be initialized."); 585 | return FALSE; 586 | } 587 | return true; 588 | } 589 | 590 | /** 591 | * \brief Adds the registry key for starting the program at system startup. 592 | */ 593 | void AddStartupTask() 594 | { 595 | // Remove possible existing registry key from previous version of application 596 | if (StartupRegistryKeyExists()) 597 | RemoveStartupRegistryKey(); 598 | 599 | if (TaskScheduler::TaskExists("ThreeFingerDrag")) 600 | { 601 | Popups::DisplayInfoMessage("Startup task already exists!"); 602 | return; 603 | } 604 | 605 | if (TaskScheduler::CreateLoginTask("ThreeFingerDrag", Application::ExePath().u8string())) 606 | Popups::DisplayInfoMessage("Startup task has been created successfully."); 607 | else 608 | Popups::DisplayErrorMessage("An error occurred while trying to create the login task."); 609 | } 610 | 611 | /** 612 | * \brief Removes the registry key for starting the program at system startup. Displays a message box on success. 613 | */ 614 | void RemoveStartupTask() 615 | { 616 | // Remove possible existing registry key from previous version of application 617 | if (StartupRegistryKeyExists()) 618 | RemoveStartupRegistryKey(); 619 | 620 | TaskScheduler::DeleteTask("ThreeFingerDrag"); 621 | if (!TaskScheduler::TaskExists("ThreeFingerDrag")) 622 | Popups::DisplayInfoMessage("Startup task has been removed successfully."); 623 | } 624 | 625 | 626 | /** 627 | * \return True if the registry key for the startup program name exists. 628 | */ 629 | bool StartupRegistryKeyExists() 630 | { 631 | HKEY hKey; 632 | LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, STARTUP_REGISTRY_KEY, 0, KEY_READ, &hKey); 633 | if (result != ERROR_SUCCESS) 634 | return false; 635 | DWORD valueSize = 0; 636 | result = RegQueryValueEx(hKey, PROGRAM_NAME, 0, nullptr, nullptr, &valueSize); 637 | RegCloseKey(hKey); 638 | return result == ERROR_SUCCESS; 639 | } 640 | 641 | /** 642 | * \brief Removes the registry key for starting the program at system startup. Displays a message box on success. 643 | */ 644 | void RemoveStartupRegistryKey() 645 | { 646 | HKEY h_key; 647 | const LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, STARTUP_REGISTRY_KEY, 0, KEY_WRITE, &h_key); 648 | if (result != ERROR_SUCCESS) 649 | return; 650 | RegDeleteValue(h_key, PROGRAM_NAME); 651 | RegCloseKey(h_key); 652 | } 653 | 654 | bool CheckSingleInstance() 655 | { 656 | const HANDLE h_mutex = CreateMutex(nullptr, TRUE, PROGRAM_NAME); 657 | if (GetLastError() == ERROR_ALREADY_EXISTS) 658 | { 659 | Popups::DisplayErrorMessage("Another instance of Three Finger Drag is already running."); 660 | CloseHandle(h_mutex); 661 | return false; 662 | } 663 | return true; 664 | } 665 | 666 | void InitializeConfiguration() 667 | { 668 | // Read user configuration values 669 | Application::ReadConfiguration(); 670 | 671 | // Initialize global strings 672 | LoadStringW(current_instance, IDS_APP_TITLE, title_bar_text, MAX_LOAD_STRING_LENGTH); 673 | LoadStringW(current_instance, IDS_SETTINGS_TITLE, settings_title_text, MAX_LOAD_STRING_LENGTH); 674 | LoadStringW(current_instance, IDC_THREEFINGERDRAG, main_window_class_name, MAX_LOAD_STRING_LENGTH); 675 | LoadStringW(current_instance, IDC_SETTINGS, settings_window_class_name, MAX_LOAD_STRING_LENGTH); 676 | 677 | // Register window classes 678 | RegisterWindowClass(current_instance, main_window_class_name, WndProc); 679 | RegisterWindowClass(current_instance, settings_window_class_name, SettingsWndProc); 680 | } 681 | 682 | void PromptUserForStartupPreference() 683 | { 684 | if (!TaskScheduler::TaskExists("ThreeFingerDrag")) 685 | { 686 | if (Popups::DisplayPrompt("Would you like run ThreeFingerDrag on startup of Windows?", "ThreeFingerDrag")) 687 | AddStartupTask(); 688 | } 689 | Popups::ShowToastNotification(L"To change your sensitivity, access your settings via the tray icon.", 690 | L"Welcome to ThreeFingerDrag!"); 691 | } 692 | 693 | void PerformAdditionalSteps() 694 | { 695 | // First time running application 696 | if (Application::IsInitialStartup()) 697 | PromptUserForStartupPreference(); 698 | 699 | // Replace legacy startup registry key with login task automatically for previous users 700 | if (StartupRegistryKeyExists()) 701 | { 702 | RemoveStartupRegistryKey(); 703 | TaskScheduler::CreateLoginTask("ThreeFingerDrag", Application::ExePath().u8string()); 704 | } 705 | 706 | if (config->IsPortableMode()) 707 | { 708 | INFO("Running in portable mode."); 709 | INFO(Application::config_folder_path); 710 | } else 711 | INFO("Running from installed path."); 712 | 713 | // Notify the user if debug mode is enabled 714 | if (config->LogDebug()) 715 | Popups::ShowToastNotification(L"To find logs & configuration, click 'Open Config' in the tray menu.", 716 | L"(ThreeFingerDrag) Debug mode enabled!"); 717 | } 718 | 719 | ATOM RegisterWindowClass(HINSTANCE hInstance, WCHAR* className, WNDPROC wndProc) 720 | { 721 | WNDCLASSEXW wcex; 722 | 723 | wcex.cbSize = sizeof(WNDCLASSEX); 724 | 725 | wcex.style = 0; 726 | wcex.lpfnWndProc = wndProc; 727 | wcex.cbClsExtra = 0; 728 | wcex.cbWndExtra = 0; 729 | wcex.hInstance = hInstance; 730 | wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_THREEFINGERDRAG)); 731 | wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); 732 | wcex.hbrBackground = nullptr; 733 | wcex.lpszMenuName = nullptr; 734 | wcex.lpszClassName = className; 735 | wcex.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_THREEFINGERDRAG)); 736 | 737 | return RegisterClassExW(&wcex); 738 | } 739 | 740 | void HandleUncaughtExceptions() 741 | { 742 | std::stringstream ss; 743 | try 744 | { 745 | throw; // Rethrow the exception to get the exception type and message 746 | } 747 | catch (const std::exception& e) 748 | { 749 | ss << "Unhandled exception: " << typeid(e).name() << ": " << e.what() << "\n"; 750 | } 751 | catch (...) 752 | { 753 | ss << "Unhandled exception: Unknown exception type\n"; 754 | } 755 | ERROR(ss.str()); 756 | std::terminate(); 757 | } 758 | -------------------------------------------------------------------------------- /ThreeFingerDrag/data/ini.h: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * Copyright (c) 2018 Danijel Durakovic 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 9 | * of the Software, and to permit persons to whom the Software is furnished to do 10 | * so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | */ 23 | 24 | /////////////////////////////////////////////////////////////////////////////// 25 | // 26 | // /mINI/ v0.9.14 27 | // An INI file reader and writer for the modern age. 28 | // 29 | /////////////////////////////////////////////////////////////////////////////// 30 | // 31 | // A tiny utility library for manipulating INI files with a straightforward 32 | // API and a minimal footprint. It conforms to the (somewhat) standard INI 33 | // format - sections and keys are case insensitive and all leading and 34 | // trailing whitespace is ignored. Comments are lines that begin with a 35 | // semicolon. Trailing comments are allowed on section lines. 36 | // 37 | // Files are read on demand, upon which data is kept in memory and the file 38 | // is closed. This utility supports lazy writing, which only writes changes 39 | // and updates to a file and preserves custom formatting and comments. A lazy 40 | // write invoked by a write() call will read the output file, find what 41 | // changes have been made and update the file accordingly. If you only need to 42 | // generate files, use generate() instead. Section and key order is preserved 43 | // on read, write and insert. 44 | // 45 | /////////////////////////////////////////////////////////////////////////////// 46 | // 47 | // /* BASIC USAGE EXAMPLE: */ 48 | // 49 | // /* read from file */ 50 | // mINI::INIFile file("myfile.ini"); 51 | // mINI::INIStructure ini; 52 | // file.read(ini); 53 | // 54 | // /* read value; gets a reference to actual value in the structure. 55 | // if key or section don't exist, a new empty value will be created */ 56 | // std::string& value = ini["section"]["key"]; 57 | // 58 | // /* read value safely; gets a copy of value in the structure. 59 | // does not alter the structure */ 60 | // std::string value = ini.get("section").get("key"); 61 | // 62 | // /* set or update values */ 63 | // ini["section"]["key"] = "value"; 64 | // 65 | // /* set multiple values */ 66 | // ini["section2"].set({ 67 | // {"key1", "value1"}, 68 | // {"key2", "value2"} 69 | // }); 70 | // 71 | // /* write updates back to file, preserving comments and formatting */ 72 | // file.write(ini); 73 | // 74 | // /* or generate a file (overwrites the original) */ 75 | // file.generate(ini); 76 | // 77 | /////////////////////////////////////////////////////////////////////////////// 78 | // 79 | // Long live the INI file!!! 80 | // 81 | /////////////////////////////////////////////////////////////////////////////// 82 | 83 | #ifndef MINI_INI_H_ 84 | #define MINI_INI_H_ 85 | 86 | #include 87 | #include 88 | #include 89 | #include 90 | #include 91 | #include 92 | #include 93 | #include 94 | #include 95 | #include 96 | 97 | namespace mINI 98 | { 99 | namespace INIStringUtil 100 | { 101 | const char* const whitespaceDelimiters = " \t\n\r\f\v"; 102 | 103 | inline void trim(std::string& str) 104 | { 105 | str.erase(str.find_last_not_of(whitespaceDelimiters) + 1); 106 | str.erase(0, str.find_first_not_of(whitespaceDelimiters)); 107 | } 108 | #ifndef MINI_CASE_SENSITIVE 109 | inline void toLower(std::string& str) 110 | { 111 | std::transform(str.begin(), str.end(), str.begin(), [](const char c) 112 | { 113 | return static_cast(std::tolower(c)); 114 | }); 115 | } 116 | #endif 117 | inline void replace(std::string& str, std::string const& a, std::string const& b) 118 | { 119 | if (!a.empty()) 120 | { 121 | std::size_t pos = 0; 122 | while ((pos = str.find(a, pos)) != std::string::npos) 123 | { 124 | str.replace(pos, a.size(), b); 125 | pos += b.size(); 126 | } 127 | } 128 | } 129 | #ifdef _WIN32 130 | const char* const endl = "\r\n"; 131 | #else 132 | const char* const endl = "\n"; 133 | #endif 134 | } 135 | 136 | template 137 | class INIMap 138 | { 139 | private: 140 | using T_DataIndexMap = std::unordered_map; 141 | using T_DataItem = std::pair; 142 | using T_DataContainer = std::vector; 143 | using T_MultiArgs = typename std::vector>; 144 | 145 | T_DataIndexMap dataIndexMap; 146 | T_DataContainer data; 147 | 148 | inline std::size_t setEmpty(std::string& key) 149 | { 150 | std::size_t index = data.size(); 151 | dataIndexMap[key] = index; 152 | data.emplace_back(key, T()); 153 | return index; 154 | } 155 | 156 | public: 157 | using const_iterator = typename T_DataContainer::const_iterator; 158 | 159 | INIMap() 160 | { 161 | } 162 | 163 | INIMap(INIMap const& other) 164 | { 165 | std::size_t data_size = other.data.size(); 166 | for (std::size_t i = 0; i < data_size; ++i) 167 | { 168 | auto const& key = other.data[i].first; 169 | auto const& obj = other.data[i].second; 170 | data.emplace_back(key, obj); 171 | } 172 | dataIndexMap = T_DataIndexMap(other.dataIndexMap); 173 | } 174 | 175 | T& operator[](std::string key) 176 | { 177 | INIStringUtil::trim(key); 178 | #ifndef MINI_CASE_SENSITIVE 179 | INIStringUtil::toLower(key); 180 | #endif 181 | auto it = dataIndexMap.find(key); 182 | bool hasIt = (it != dataIndexMap.end()); 183 | std::size_t index = (hasIt) ? it->second : setEmpty(key); 184 | return data[index].second; 185 | } 186 | 187 | T get(std::string key) const 188 | { 189 | INIStringUtil::trim(key); 190 | #ifndef MINI_CASE_SENSITIVE 191 | INIStringUtil::toLower(key); 192 | #endif 193 | auto it = dataIndexMap.find(key); 194 | if (it == dataIndexMap.end()) 195 | { 196 | return T(); 197 | } 198 | return T(data[it->second].second); 199 | } 200 | 201 | bool has(std::string key) const 202 | { 203 | INIStringUtil::trim(key); 204 | #ifndef MINI_CASE_SENSITIVE 205 | INIStringUtil::toLower(key); 206 | #endif 207 | return (dataIndexMap.count(key) == 1); 208 | } 209 | 210 | void set(std::string key, T obj) 211 | { 212 | INIStringUtil::trim(key); 213 | #ifndef MINI_CASE_SENSITIVE 214 | INIStringUtil::toLower(key); 215 | #endif 216 | auto it = dataIndexMap.find(key); 217 | if (it != dataIndexMap.end()) 218 | { 219 | data[it->second].second = obj; 220 | } 221 | else 222 | { 223 | dataIndexMap[key] = data.size(); 224 | data.emplace_back(key, obj); 225 | } 226 | } 227 | 228 | void set(T_MultiArgs const& multiArgs) 229 | { 230 | for (auto const& it : multiArgs) 231 | { 232 | auto const& key = it.first; 233 | auto const& obj = it.second; 234 | set(key, obj); 235 | } 236 | } 237 | 238 | bool remove(std::string key) 239 | { 240 | INIStringUtil::trim(key); 241 | #ifndef MINI_CASE_SENSITIVE 242 | INIStringUtil::toLower(key); 243 | #endif 244 | auto it = dataIndexMap.find(key); 245 | if (it != dataIndexMap.end()) 246 | { 247 | std::size_t index = it->second; 248 | data.erase(data.begin() + index); 249 | dataIndexMap.erase(it); 250 | for (auto& it2 : dataIndexMap) 251 | { 252 | auto& vi = it2.second; 253 | if (vi > index) 254 | { 255 | vi--; 256 | } 257 | } 258 | return true; 259 | } 260 | return false; 261 | } 262 | 263 | void clear() 264 | { 265 | data.clear(); 266 | dataIndexMap.clear(); 267 | } 268 | 269 | std::size_t size() const 270 | { 271 | return data.size(); 272 | } 273 | 274 | const_iterator begin() const { return data.begin(); } 275 | const_iterator end() const { return data.end(); } 276 | }; 277 | 278 | using INIStructure = INIMap>; 279 | 280 | namespace INIParser 281 | { 282 | using T_ParseValues = std::pair; 283 | 284 | enum class PDataType : char 285 | { 286 | PDATA_NONE, 287 | PDATA_COMMENT, 288 | PDATA_SECTION, 289 | PDATA_KEYVALUE, 290 | PDATA_UNKNOWN 291 | }; 292 | 293 | inline PDataType parseLine(std::string line, T_ParseValues& parseData) 294 | { 295 | parseData.first.clear(); 296 | parseData.second.clear(); 297 | INIStringUtil::trim(line); 298 | if (line.empty()) 299 | { 300 | return PDataType::PDATA_NONE; 301 | } 302 | char firstCharacter = line[0]; 303 | if (firstCharacter == ';') 304 | { 305 | return PDataType::PDATA_COMMENT; 306 | } 307 | if (firstCharacter == '[') 308 | { 309 | auto commentAt = line.find_first_of(';'); 310 | if (commentAt != std::string::npos) 311 | { 312 | line = line.substr(0, commentAt); 313 | } 314 | auto closingBracketAt = line.find_last_of(']'); 315 | if (closingBracketAt != std::string::npos) 316 | { 317 | auto section = line.substr(1, closingBracketAt - 1); 318 | INIStringUtil::trim(section); 319 | parseData.first = section; 320 | return PDataType::PDATA_SECTION; 321 | } 322 | } 323 | auto lineNorm = line; 324 | INIStringUtil::replace(lineNorm, "\\=", " "); 325 | auto equalsAt = lineNorm.find_first_of('='); 326 | if (equalsAt != std::string::npos) 327 | { 328 | auto key = line.substr(0, equalsAt); 329 | INIStringUtil::trim(key); 330 | INIStringUtil::replace(key, "\\=", "="); 331 | auto value = line.substr(equalsAt + 1); 332 | INIStringUtil::trim(value); 333 | parseData.first = key; 334 | parseData.second = value; 335 | return PDataType::PDATA_KEYVALUE; 336 | } 337 | return PDataType::PDATA_UNKNOWN; 338 | } 339 | } 340 | 341 | class INIReader 342 | { 343 | public: 344 | using T_LineData = std::vector; 345 | using T_LineDataPtr = std::shared_ptr; 346 | 347 | bool isBOM = false; 348 | 349 | private: 350 | std::ifstream fileReadStream; 351 | T_LineDataPtr lineData; 352 | 353 | T_LineData readFile() 354 | { 355 | fileReadStream.seekg(0, std::ios::end); 356 | const std::size_t fileSize = static_cast(fileReadStream.tellg()); 357 | fileReadStream.seekg(0, std::ios::beg); 358 | if (fileSize >= 3) 359 | { 360 | const char header[3] = { 361 | static_cast(fileReadStream.get()), 362 | static_cast(fileReadStream.get()), 363 | static_cast(fileReadStream.get()) 364 | }; 365 | isBOM = ( 366 | header[0] == static_cast(0xEF) && 367 | header[1] == static_cast(0xBB) && 368 | header[2] == static_cast(0xBF) 369 | ); 370 | } 371 | else 372 | { 373 | isBOM = false; 374 | } 375 | std::string fileContents; 376 | fileContents.resize(fileSize); 377 | fileReadStream.seekg(isBOM ? 3 : 0, std::ios::beg); 378 | fileReadStream.read(&fileContents[0], fileSize); 379 | fileReadStream.close(); 380 | T_LineData output; 381 | if (fileSize == 0) 382 | { 383 | return output; 384 | } 385 | std::string buffer; 386 | buffer.reserve(50); 387 | for (std::size_t i = 0; i < fileSize; ++i) 388 | { 389 | char& c = fileContents[i]; 390 | if (c == '\n') 391 | { 392 | output.emplace_back(buffer); 393 | buffer.clear(); 394 | continue; 395 | } 396 | if (c != '\0' && c != '\r') 397 | { 398 | buffer += c; 399 | } 400 | } 401 | output.emplace_back(buffer); 402 | return output; 403 | } 404 | 405 | public: 406 | INIReader(std::string const& filename, bool keepLineData = false) 407 | { 408 | fileReadStream.open(filename, std::ios::in | std::ios::binary); 409 | if (keepLineData) 410 | { 411 | lineData = std::make_shared(); 412 | } 413 | } 414 | 415 | ~INIReader() 416 | { 417 | } 418 | 419 | bool operator>>(INIStructure& data) 420 | { 421 | if (!fileReadStream.is_open()) 422 | { 423 | return false; 424 | } 425 | T_LineData fileLines = readFile(); 426 | std::string section; 427 | bool inSection = false; 428 | INIParser::T_ParseValues parseData; 429 | for (auto const& line : fileLines) 430 | { 431 | auto parseResult = INIParser::parseLine(line, parseData); 432 | if (parseResult == INIParser::PDataType::PDATA_SECTION) 433 | { 434 | inSection = true; 435 | data[section = parseData.first]; 436 | } 437 | else if (inSection && parseResult == INIParser::PDataType::PDATA_KEYVALUE) 438 | { 439 | auto const& key = parseData.first; 440 | auto const& value = parseData.second; 441 | data[section][key] = value; 442 | } 443 | if (lineData && parseResult != INIParser::PDataType::PDATA_UNKNOWN) 444 | { 445 | if (parseResult == INIParser::PDataType::PDATA_KEYVALUE && !inSection) 446 | { 447 | continue; 448 | } 449 | lineData->emplace_back(line); 450 | } 451 | } 452 | return true; 453 | } 454 | 455 | T_LineDataPtr getLines() 456 | { 457 | return lineData; 458 | } 459 | }; 460 | 461 | class INIGenerator 462 | { 463 | private: 464 | std::ofstream fileWriteStream; 465 | 466 | public: 467 | bool prettyPrint = false; 468 | 469 | INIGenerator(std::string const& filename) 470 | { 471 | fileWriteStream.open(filename, std::ios::out | std::ios::binary); 472 | } 473 | 474 | ~INIGenerator() 475 | { 476 | } 477 | 478 | bool operator<<(INIStructure const& data) 479 | { 480 | if (!fileWriteStream.is_open()) 481 | { 482 | return false; 483 | } 484 | if (!data.size()) 485 | { 486 | return true; 487 | } 488 | auto it = data.begin(); 489 | for (;;) 490 | { 491 | auto const& section = it->first; 492 | auto const& collection = it->second; 493 | fileWriteStream 494 | << "[" 495 | << section 496 | << "]"; 497 | if (collection.size()) 498 | { 499 | fileWriteStream << INIStringUtil::endl; 500 | auto it2 = collection.begin(); 501 | for (;;) 502 | { 503 | auto key = it2->first; 504 | INIStringUtil::replace(key, "=", "\\="); 505 | auto value = it2->second; 506 | INIStringUtil::trim(value); 507 | fileWriteStream 508 | << key 509 | << ((prettyPrint) ? " = " : "=") 510 | << value; 511 | if (++it2 == collection.end()) 512 | { 513 | break; 514 | } 515 | fileWriteStream << INIStringUtil::endl; 516 | } 517 | } 518 | if (++it == data.end()) 519 | { 520 | break; 521 | } 522 | fileWriteStream << INIStringUtil::endl; 523 | if (prettyPrint) 524 | { 525 | fileWriteStream << INIStringUtil::endl; 526 | } 527 | } 528 | return true; 529 | } 530 | }; 531 | 532 | class INIWriter 533 | { 534 | private: 535 | using T_LineData = std::vector; 536 | using T_LineDataPtr = std::shared_ptr; 537 | 538 | std::string filename; 539 | 540 | T_LineData getLazyOutput(T_LineDataPtr const& lineData, INIStructure& data, INIStructure& original) 541 | { 542 | T_LineData output; 543 | INIParser::T_ParseValues parseData; 544 | std::string sectionCurrent; 545 | bool parsingSection = false; 546 | bool continueToNextSection = false; 547 | bool discardNextEmpty = false; 548 | bool writeNewKeys = false; 549 | std::size_t lastKeyLine = 0; 550 | for (auto line = lineData->begin(); line != lineData->end(); ++line) 551 | { 552 | if (!writeNewKeys) 553 | { 554 | auto parseResult = INIParser::parseLine(*line, parseData); 555 | if (parseResult == INIParser::PDataType::PDATA_SECTION) 556 | { 557 | if (parsingSection) 558 | { 559 | writeNewKeys = true; 560 | parsingSection = false; 561 | --line; 562 | continue; 563 | } 564 | sectionCurrent = parseData.first; 565 | if (data.has(sectionCurrent)) 566 | { 567 | parsingSection = true; 568 | continueToNextSection = false; 569 | discardNextEmpty = false; 570 | output.emplace_back(*line); 571 | lastKeyLine = output.size(); 572 | } 573 | else 574 | { 575 | continueToNextSection = true; 576 | discardNextEmpty = true; 577 | continue; 578 | } 579 | } 580 | else if (parseResult == INIParser::PDataType::PDATA_KEYVALUE) 581 | { 582 | if (continueToNextSection) 583 | { 584 | continue; 585 | } 586 | if (data.has(sectionCurrent)) 587 | { 588 | auto& collection = data[sectionCurrent]; 589 | auto const& key = parseData.first; 590 | auto const& value = parseData.second; 591 | if (collection.has(key)) 592 | { 593 | auto outputValue = collection[key]; 594 | if (value == outputValue) 595 | { 596 | output.emplace_back(*line); 597 | } 598 | else 599 | { 600 | INIStringUtil::trim(outputValue); 601 | auto lineNorm = *line; 602 | INIStringUtil::replace(lineNorm, "\\=", " "); 603 | auto equalsAt = lineNorm.find_first_of('='); 604 | auto valueAt = lineNorm.find_first_not_of( 605 | INIStringUtil::whitespaceDelimiters, 606 | equalsAt + 1 607 | ); 608 | std::string outputLine = line->substr(0, valueAt); 609 | if (prettyPrint && equalsAt + 1 == valueAt) 610 | { 611 | outputLine += " "; 612 | } 613 | outputLine += outputValue; 614 | output.emplace_back(outputLine); 615 | } 616 | lastKeyLine = output.size(); 617 | } 618 | } 619 | } 620 | else 621 | { 622 | if (discardNextEmpty && line->empty()) 623 | { 624 | discardNextEmpty = false; 625 | } 626 | else if (parseResult != INIParser::PDataType::PDATA_UNKNOWN) 627 | { 628 | output.emplace_back(*line); 629 | } 630 | } 631 | } 632 | if (writeNewKeys || std::next(line) == lineData->end()) 633 | { 634 | T_LineData linesToAdd; 635 | if (data.has(sectionCurrent) && original.has(sectionCurrent)) 636 | { 637 | auto const& collection = data[sectionCurrent]; 638 | auto const& collectionOriginal = original[sectionCurrent]; 639 | for (auto const& it : collection) 640 | { 641 | auto key = it.first; 642 | if (collectionOriginal.has(key)) 643 | { 644 | continue; 645 | } 646 | auto value = it.second; 647 | INIStringUtil::replace(key, "=", "\\="); 648 | INIStringUtil::trim(value); 649 | linesToAdd.emplace_back( 650 | key + ((prettyPrint) ? " = " : "=") + value 651 | ); 652 | } 653 | } 654 | if (!linesToAdd.empty()) 655 | { 656 | output.insert( 657 | output.begin() + lastKeyLine, 658 | linesToAdd.begin(), 659 | linesToAdd.end() 660 | ); 661 | } 662 | if (writeNewKeys) 663 | { 664 | writeNewKeys = false; 665 | --line; 666 | } 667 | } 668 | } 669 | for (auto const& it : data) 670 | { 671 | auto const& section = it.first; 672 | if (original.has(section)) 673 | { 674 | continue; 675 | } 676 | if (prettyPrint && output.size() > 0 && !output.back().empty()) 677 | { 678 | output.emplace_back(); 679 | } 680 | output.emplace_back("[" + section + "]"); 681 | auto const& collection = it.second; 682 | for (auto const& it2 : collection) 683 | { 684 | auto key = it2.first; 685 | auto value = it2.second; 686 | INIStringUtil::replace(key, "=", "\\="); 687 | INIStringUtil::trim(value); 688 | output.emplace_back( 689 | key + ((prettyPrint) ? " = " : "=") + value 690 | ); 691 | } 692 | } 693 | return output; 694 | } 695 | 696 | public: 697 | bool prettyPrint = false; 698 | 699 | INIWriter(std::string const& filename) 700 | : filename(filename) 701 | { 702 | } 703 | 704 | ~INIWriter() 705 | { 706 | } 707 | 708 | bool operator<<(INIStructure& data) 709 | { 710 | struct stat buf; 711 | bool fileExists = (stat(filename.c_str(), &buf) == 0); 712 | if (!fileExists) 713 | { 714 | INIGenerator generator(filename); 715 | generator.prettyPrint = prettyPrint; 716 | return generator << data; 717 | } 718 | INIStructure originalData; 719 | T_LineDataPtr lineData; 720 | bool readSuccess = false; 721 | bool fileIsBOM = false; 722 | { 723 | INIReader reader(filename, true); 724 | if ((readSuccess = reader >> originalData)) 725 | { 726 | lineData = reader.getLines(); 727 | fileIsBOM = reader.isBOM; 728 | } 729 | } 730 | if (!readSuccess) 731 | { 732 | return false; 733 | } 734 | T_LineData output = getLazyOutput(lineData, data, originalData); 735 | std::ofstream fileWriteStream(filename, std::ios::out | std::ios::binary); 736 | if (fileWriteStream.is_open()) 737 | { 738 | if (fileIsBOM) 739 | { 740 | const char utf8_BOM[3] = { 741 | static_cast(0xEF), 742 | static_cast(0xBB), 743 | static_cast(0xBF) 744 | }; 745 | fileWriteStream.write(utf8_BOM, 3); 746 | } 747 | if (output.size()) 748 | { 749 | auto line = output.begin(); 750 | for (;;) 751 | { 752 | fileWriteStream << *line; 753 | if (++line == output.end()) 754 | { 755 | break; 756 | } 757 | fileWriteStream << INIStringUtil::endl; 758 | } 759 | } 760 | return true; 761 | } 762 | return false; 763 | } 764 | }; 765 | 766 | class INIFile 767 | { 768 | private: 769 | std::string filename; 770 | 771 | public: 772 | INIFile(std::string const& filename) 773 | : filename(filename) 774 | { 775 | } 776 | 777 | ~INIFile() 778 | { 779 | } 780 | 781 | bool read(INIStructure& data) const 782 | { 783 | if (data.size()) 784 | { 785 | data.clear(); 786 | } 787 | if (filename.empty()) 788 | { 789 | return false; 790 | } 791 | INIReader reader(filename); 792 | return reader >> data; 793 | } 794 | 795 | bool generate(INIStructure const& data, bool pretty = false) const 796 | { 797 | if (filename.empty()) 798 | { 799 | return false; 800 | } 801 | INIGenerator generator(filename); 802 | generator.prettyPrint = pretty; 803 | return generator << data; 804 | } 805 | 806 | bool write(INIStructure& data, bool pretty = false) const 807 | { 808 | if (filename.empty()) 809 | { 810 | return false; 811 | } 812 | INIWriter writer(filename); 813 | writer.prettyPrint = pretty; 814 | return writer << data; 815 | } 816 | }; 817 | } 818 | 819 | #endif // MINI_INI_H_ 820 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------