├── .gitignore ├── gui ├── gui.rc ├── build.rs ├── gui.exe.manifest ├── Cargo.toml └── src │ ├── color_chooser.rs │ └── gui.rs ├── screenshot.png ├── cli ├── Cargo.toml └── src │ └── cli.rs ├── lib ├── Cargo.toml └── src │ ├── cfg.rs │ ├── error.rs │ ├── device.rs │ └── lib.rs ├── Cargo.toml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /Cargo.lock 2 | /target 3 | -------------------------------------------------------------------------------- /gui/gui.rc: -------------------------------------------------------------------------------- 1 | #define RT_MANIFEST 24 2 | 1 RT_MANIFEST "gui.exe.manifest" -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gpoulios/deathadderv2/HEAD/screenshot.png -------------------------------------------------------------------------------- /gui/build.rs: -------------------------------------------------------------------------------- 1 | use embed_resource; 2 | fn main() { 3 | embed_resource::compile("gui.rc", embed_resource::NONE); 4 | } -------------------------------------------------------------------------------- /cli/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "deathadder-rgb-cli" 3 | edition = { workspace = true } 4 | version = { workspace = true } 5 | authors = { workspace = true } 6 | description = { workspace = true } 7 | repository = { workspace = true } 8 | license = { workspace = true } 9 | 10 | [[bin]] 11 | name = "deathadder-rgb-cli" 12 | path = "src/cli.rs" 13 | 14 | [dependencies] 15 | librazer = { path = "../lib" } 16 | rgb = { workspace = true } -------------------------------------------------------------------------------- /lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "librazer" 3 | description = "A partial port of openrazer's driver for DeathAdder v2" 4 | edition = { workspace = true } 5 | version = { workspace = true } 6 | authors = { workspace = true } 7 | repository = { workspace = true } 8 | 9 | [dependencies] 10 | rusb = { workspace = true } 11 | serde = { version = "1.0.152", features = ["derive"] } 12 | rgb = { workspace = true, features = ["serde"] } 13 | confy = "0.5.1" -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["lib", "cli", "gui"] 3 | default-members = ["gui"] 4 | 5 | [workspace.package] 6 | edition = "2021" 7 | version = "0.3.2" 8 | authors = ["George Poulios"] 9 | description = "A utility to control Razer DeathAdder v2 on Windows" 10 | readme = "./README.md" 11 | repository = "https://github.com/gpoulios/deathadderv2" 12 | license = "GPLv3" 13 | 14 | [workspace.dependencies] 15 | rgb = { version = "0.8.36" } 16 | rusb = { version = "0.9" } 17 | -------------------------------------------------------------------------------- /gui/gui.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /gui/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "deathadder-rgb-gui" 3 | edition = { workspace = true } 4 | version = { workspace = true } 5 | authors = { workspace = true } 6 | description = { workspace = true } 7 | repository = { workspace = true } 8 | license = { workspace = true } 9 | 10 | [[bin]] 11 | name = "deathadder-rgb-gui" 12 | path = "src/gui.rs" 13 | 14 | [dependencies] 15 | librazer = { path = "../lib" } 16 | rgb = { workspace = true } 17 | native-windows-gui = "1.0.13" 18 | native-windows-derive = "1.0.5" 19 | rusb = { workspace = true } 20 | hidapi-rusb = "1.3.2" 21 | 22 | [dependencies.windows] 23 | version = "0.46.0" 24 | features = [ 25 | "Win32_Foundation", 26 | "Win32_UI_Controls_Dialogs", 27 | "Win32_UI_WindowsAndMessaging", 28 | "Win32_System_Diagnostics_Debug" 29 | ] 30 | 31 | [build-dependencies] 32 | embed-resource = "2.0.0" -------------------------------------------------------------------------------- /lib/src/cfg.rs: -------------------------------------------------------------------------------- 1 | use std::default::Default; 2 | use serde::{Serialize, Deserialize}; 3 | use confy::ConfyError; 4 | use rgb::RGB8; 5 | 6 | #[derive(Debug, Clone, Copy, Serialize, Deserialize)] 7 | pub struct Config { 8 | pub same_color: bool, 9 | pub same_brightness: bool, 10 | pub logo_color: RGB8, 11 | pub scroll_color: RGB8, 12 | } 13 | 14 | impl Config { 15 | pub fn save(&self) -> Result<(), ConfyError> { 16 | confy::store("deathadder_v2", None, self) 17 | } 18 | 19 | pub fn load() -> Option { 20 | match confy::load("deathadder_v2", None) { 21 | Ok(cfg) => Some(cfg), 22 | Err(_) => None 23 | } 24 | } 25 | } 26 | 27 | impl Default for Config { 28 | fn default() -> Self { 29 | Self { 30 | same_color: true, 31 | same_brightness: true, 32 | logo_color: RGB8::new(0xAA, 0xAA, 0xAA), 33 | scroll_color: RGB8::new(0xAA, 0xAA, 0xAA), 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /cli/src/cli.rs: -------------------------------------------------------------------------------- 1 | use rgb::RGB8; 2 | use librazer::cfg::Config; 3 | use librazer::common::rgb_from_hex; 4 | use librazer::device::{DeathAdderV2, RazerMouse}; 5 | 6 | fn main() { 7 | let args: Vec = std::env::args().collect(); 8 | 9 | let parse_arg = |input: &str| -> RGB8 { 10 | match rgb_from_hex(input) { 11 | Ok(rgb) => rgb, 12 | Err(e) => panic!("argument '{}' should be in the \ 13 | form [0x/#]RGB[h] or [0x/#]RRGGBB[h] where R, G, and B are hex \ 14 | digits: {}", input, e) 15 | } 16 | }; 17 | 18 | let cfgopt = Config::load(); 19 | 20 | let (logo_color, scroll_color) = match args.len() { 21 | ..=1 => { 22 | match cfgopt { 23 | Some(cfg) => (cfg.logo_color, cfg.scroll_color), 24 | None => panic!("failed to load configuration; please specify \ 25 | arguments manually") 26 | } 27 | }, 28 | 2..=3 => { 29 | let color = parse_arg(args[1].as_ref()); 30 | (color, if args.len() == 3 { 31 | parse_arg(args[2].as_ref()) 32 | } else { 33 | color 34 | }) 35 | }, 36 | _ => panic!("usage: {} [(body) color] [wheel color]", args[0]) 37 | }; 38 | 39 | let dav2 = DeathAdderV2::new().expect("failed to open device"); 40 | 41 | _= dav2.set_logo_color(logo_color) 42 | .map_err(|e| panic!("failed to set logo color: {}", e)) 43 | .and_then(|_| dav2.set_scroll_color(scroll_color)) 44 | .map_err(|e| panic!("failed to set scroll color: {}", e)); 45 | 46 | _ = Config { 47 | logo_color: logo_color, 48 | scroll_color: scroll_color, 49 | ..cfgopt.unwrap_or(Default::default()) 50 | }.save().map_err(|e| panic!("failed to save config: {}", e)); 51 | } 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # deathadderv2 2 | 3 | A tool to configure the Razer DeathAdder v2 and save the settings in the on-board memory. 4 | 5 | I just wanted static color without having to run in the background 2-3 apps and 6 services that come with Synapse. Although the device supports it, for some reason Razer's driver does not save the color in the on-board memory. As a result, you need to keep running Synapse and co. or the mouse goes back to those wave effects that I don't like as they keep catching my eye when typing or reading. 6 | 7 | Device protocol has been largely ported from [openrazer](https://github.com/openrazer/openrazer) (except for DPI stages which I didn't find in openrazer). GUI mostly built using [native-windows-gui](https://github.com/gabdube/native-windows-gui). 8 | 9 | So far, it supports the following (all saved on the device, including the color): 10 | 11 | - DPI and DPI stages 12 | - Polling rate 13 | - Static logo and scroll wheel color 14 | - Logo and scroll wheel brightness 15 | 16 | It doesn't support: 17 | 18 | - Wave/breath/spectrum effects 19 | - Profiles 20 | - I believe they're emulated by Synapse and not really supported by the hardware, otherwise I'd be glad to implement them 21 | 22 | - Other devices 23 | 24 | ## Requirements 25 | 26 | This is not supposed to be for Linux hosts. If you are on Linux, see [openrazer](https://github.com/openrazer/openrazer), it's a great project, and supports many more features, as well as almost all devices. 27 | 28 | For Windows users, the only requirement is to be using the [libusb driver](https://github.com/libusb/libusb/wiki/Windows) (either WinUSB or libusb-win32). One way to install it is using [Zadig](https://zadig.akeo.ie/). You only need to do this once. Change the entry "Razer DeathAdder V2 (Interface 3)" by using the spinner to select either "WinUSB (vXXX)" (recommended) or "libusb-win32 (vX.Y.Z)" and hit "Replace driver". In my case (Win11) it seemed to time out while creating a restore point but it actually installed it. 29 | 30 | ## Usage 31 | 32 | The UI should be self-explanatory. No need to keep it running in the background. 33 | 34 | ![UI screenshot](screenshot.png?raw=true "UI screenshot") 35 | 36 | Contrary to all other settings, I have not found a way to retrieve the current color from the device so the app will save the last applied color to a file under %APPDATA%/deathadder/config/default-config.toml, just so it doesn't reset every time it opens. 37 | 38 | --- 39 | This project is licensed under the GPL. -------------------------------------------------------------------------------- /lib/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::{num::ParseIntError, fmt, result, error}; 2 | 3 | #[derive(Debug)] 4 | pub enum ParseRGBError { 5 | WrongLength(usize), 6 | ParseHex(ParseIntError), 7 | } 8 | 9 | impl fmt::Display for ParseRGBError { 10 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 11 | match *self { 12 | ParseRGBError::WrongLength(len) => 13 | write!(f, "excluding pre/suffixes, \ 14 | string can only be of length 3 or 6 ({} given)", len), 15 | ParseRGBError::ParseHex(ref pie) => 16 | write!(f, "{}", pie), 17 | } 18 | } 19 | } 20 | 21 | impl error::Error for ParseRGBError { 22 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { 23 | match *self { 24 | ParseRGBError::WrongLength(_) => None, 25 | ParseRGBError::ParseHex(ref pie) => Some(pie), 26 | } 27 | } 28 | } 29 | 30 | impl From for ParseRGBError { 31 | fn from(err: ParseIntError) -> ParseRGBError { 32 | ParseRGBError::ParseHex(err) 33 | } 34 | } 35 | 36 | /// A result of a function that may return a `Error`. 37 | pub type USBResult = result::Result; 38 | 39 | #[derive(Debug)] 40 | pub enum USBError { 41 | NonCompatibleDevice, 42 | DeviceNotFound, 43 | /// (total, written) An incomplete write 44 | IncompleteWrite(usize, usize), 45 | /// (total, read) An incomplete read 46 | IncompleteRead(usize, usize), 47 | ResponseMismatch, 48 | DeviceBusy, 49 | CommandFailed, 50 | CommandNotSupported, 51 | CommandTimeout, 52 | ResponseUnknownStatus(u8), 53 | ResponseUnknownValue(u8), 54 | /// Wrapper for rusb::Error 55 | RUSBError(rusb::Error), 56 | } 57 | 58 | impl fmt::Display for USBError { 59 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 60 | match *self { 61 | USBError::NonCompatibleDevice => write!(f, "device is incompatible"), 62 | USBError::DeviceNotFound => write!(f, "device not found"), 63 | USBError::IncompleteWrite(total, written) => 64 | write!(f, "failed to write full control message \ 65 | (written {} out of {} bytes)", written, total), 66 | USBError::IncompleteRead(total, read) => 67 | write!(f, "failed to read full control message \ 68 | (read {} out of {} bytes)", read, total), 69 | USBError::ResponseMismatch => write!(f, "wrong response type"), 70 | USBError::DeviceBusy => write!(f, "device is busy"), 71 | USBError::CommandFailed => write!(f, "command failed"), 72 | USBError::CommandNotSupported => write!(f, "command not supported"), 73 | USBError::CommandTimeout => write!(f, "command timed out"), 74 | USBError::ResponseUnknownStatus(status) => 75 | write!(f, "unrecognized status in response: {:#02X}", status), 76 | USBError::ResponseUnknownValue(value) => 77 | write!(f, "unrecognized value in response: {:#02X}", value), 78 | USBError::RUSBError(ref e) => write!(f, "{}", e), 79 | } 80 | } 81 | } 82 | 83 | impl error::Error for USBError { 84 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { 85 | match *self { 86 | USBError::RUSBError(ref e) => Some(e), 87 | _ => None 88 | } 89 | } 90 | } 91 | 92 | impl From for USBError { 93 | fn from(err: rusb::Error) -> USBError { 94 | USBError::RUSBError(err) 95 | } 96 | } -------------------------------------------------------------------------------- /gui/src/color_chooser.rs: -------------------------------------------------------------------------------- 1 | use std::{mem::{size_of, MaybeUninit}, thread::{self, JoinHandle}, ffi::CStr}; 2 | use windows::{ 3 | core::{PCSTR}, 4 | Win32::{ 5 | Foundation::{HWND, WPARAM, LRESULT, LPARAM, RECT, COLORREF}, 6 | UI::{ 7 | WindowsAndMessaging::{ 8 | WM_INITDIALOG, WM_COMMAND, WM_PAINT, EN_UPDATE, GetWindowTextA, 9 | SWP_NOSIZE, SWP_NOZORDER, GetWindowRect, GetDesktopWindow, 10 | GetClientRect, SetWindowPos, 11 | SetWindowLongPtrA, GetWindowLongPtrA, DWLP_MSGRESULT, WINDOW_LONG_PTR_INDEX, 12 | }, 13 | Controls::Dialogs::* 14 | }, 15 | }, 16 | }; 17 | use rgb::RGB8; 18 | 19 | /* 20 | * trying hard to follow: 21 | * https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlongptra 22 | * We're gonna need DWLP_USER to set a pointer to our Color Dialog struct 23 | * on the winapi Dialog window (GWLP_USERDATA only works for window class) 24 | */ 25 | const DWLP_DLGPROC: u32 = DWLP_MSGRESULT + size_of::() as u32; 26 | const DWLP_USER: WINDOW_LONG_PTR_INDEX = WINDOW_LONG_PTR_INDEX( 27 | (DWLP_DLGPROC + size_of::() as u32) as i32); 28 | 29 | /* 30 | * std::ffi::CStr::from_bytes_until_nul() is atm nightly experimental API so 31 | * we need this to convert a byte array with one or more null terminators in it 32 | */ 33 | unsafe fn u8sz_to_u8(s: &[u8]) -> u8 { 34 | let str = CStr::from_ptr(s.as_ptr() as *const _).to_str().unwrap(); 35 | str.parse::().unwrap() 36 | } 37 | 38 | pub type ColorChangeCallback<'a> = dyn Fn(&ColorDialog, &RGB8) + Send + Sync + 'a; 39 | 40 | pub struct ColorDialog<'a> { 41 | current: [u8; 3], 42 | last_notified: RGB8, 43 | change_cb: Option>>, 44 | } 45 | 46 | impl Default for ColorDialog<'_> { 47 | fn default() -> Self { 48 | unsafe { 49 | // safe as 0 a valid bit-pattern for all fields 50 | MaybeUninit::::zeroed().assume_init() 51 | } 52 | } 53 | } 54 | 55 | impl<'a> ColorDialog<'a> { 56 | pub fn new() -> Self { 57 | Self { ..Default::default() } 58 | } 59 | 60 | pub fn show_async( 61 | &'static mut self, 62 | parent: HWND, 63 | initial: Option, 64 | change_cb: Option 65 | ) -> JoinHandle> 66 | where F: Fn(&ColorDialog, &RGB8) + Send + Sync + 'a { 67 | thread::spawn(move || { 68 | self.show(parent, initial, change_cb) 69 | }) 70 | } 71 | 72 | pub fn show( 73 | &mut self, 74 | parent: HWND, 75 | initial: Option, 76 | change_cb: Option, 77 | ) -> Option 78 | where F: Fn(&ColorDialog, &RGB8) + Send + Sync + 'a { 79 | unsafe { 80 | let initial = initial.unwrap_or(RGB8::new(0xaa, 0xaa, 0xaa)); 81 | 82 | // init these so we don't trigger an unnecessary 'change' event on bootstrap 83 | self.current = [initial.r, initial.g, initial.b]; 84 | self.last_notified = initial; 85 | 86 | self.change_cb = match change_cb { 87 | Some(cb) => Some(Box::new(cb)), 88 | None => None 89 | }; 90 | 91 | // will set lCustData to self so we can access it in the hook proc 92 | let this_lp = LPARAM((self as *mut Self) as isize); 93 | 94 | // this will be both the initial and custom colors for now 95 | let mut initial_cr = COLORREF( 96 | initial.r as u32 | 97 | (initial.g as u32) << 8 | 98 | (initial.b as u32) << 16); 99 | 100 | let mut cc = CHOOSECOLORA { 101 | lStructSize: size_of::() as u32, 102 | hwndOwner: parent, 103 | rgbResult: initial_cr, 104 | lpCustColors: &mut initial_cr, 105 | Flags: CC_FULLOPEN | CC_ANYCOLOR | CC_RGBINIT | CC_ENABLEHOOK | CC_PREVENTFULLOPEN, 106 | lpfnHook: Some(cc_hook_proc), 107 | lpTemplateName: PCSTR::null(), 108 | lCustData: this_lp, 109 | ..Default::default() 110 | }; 111 | 112 | let ok = ChooseColorA(&mut cc).into(); 113 | if ok { 114 | Some(RGB8{ 115 | r: (cc.rgbResult.0 & 0xff) as u8, 116 | g: ((cc.rgbResult.0 >> 8) & 0xff) as u8, 117 | b: ((cc.rgbResult.0 >> 16) & 0xff) as u8, 118 | }) 119 | } else { 120 | None 121 | } 122 | } 123 | } 124 | } 125 | 126 | /* 127 | * The CCHOOKPROC used for 2 things: 128 | * 1) to center our orphan dialog if it has no parent and 129 | * 2) to generate color change events 130 | * 131 | * We get RGB channel updates one-by-one in 3 consecutive WM_COMMAND(EN_UPDATE) 132 | * messages in CCHOOKPROC, therefore it should be more perfomant not to trigger 133 | * any listener callbacks (in this case our preview thread which would send a 134 | * USB command to the mouse) on each of those (partial) updates. We store those 135 | * updates in `ColorDialog.current`. 136 | * 137 | * A full update is assumed to be when the WM_PAINT message is sent, at which 138 | * point we invoke the `change_cb`. 139 | */ 140 | unsafe extern "system" fn cc_hook_proc( 141 | hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM 142 | ) -> usize { 143 | match msg { 144 | 145 | WM_INITDIALOG => { 146 | // save our pointer to this instance of the ColorDialog struct 147 | let cc_ptr = lparam.0 as *const CHOOSECOLORA; 148 | let cc = &cc_ptr.read(); 149 | SetWindowLongPtrA(hwnd, DWLP_USER, cc.lCustData.0); 150 | 151 | if cc.hwndOwner.0 == 0 { 152 | // center our dialog window on the desktop 153 | let mut rc = RECT::default(); 154 | let mut desktop_rc = RECT::default(); 155 | 156 | if GetWindowRect(hwnd, &mut rc).into() && 157 | GetClientRect(GetDesktopWindow(), &mut desktop_rc).into() { 158 | 159 | rc.left = (desktop_rc.right/2) - ((rc.right - rc.left)/2); 160 | rc.top = (desktop_rc.bottom/2) - ((rc.bottom - rc.top)/2); 161 | 162 | SetWindowPos(hwnd, HWND(0), rc.left, rc.top, 0, 0, 163 | SWP_NOZORDER | SWP_NOSIZE); 164 | } 165 | } 166 | }, 167 | 168 | WM_COMMAND => { 169 | // update one RGB channel 170 | let cmd = (wparam.0 >> 16) as u32; 171 | let ctrl_id = wparam.0 & 0xffff; 172 | let ctrl_handle = HWND(lparam.0); 173 | 174 | // used WinId to get the textboxes' ids (0x2c2,3,4) 175 | if cmd == EN_UPDATE && 0x2c2 <= ctrl_id && ctrl_id <= 0x2c4 { 176 | let mut text = [0u8; 10]; 177 | let len = GetWindowTextA(ctrl_handle, &mut text); 178 | if 0 < len && len <= 3 { 179 | 180 | // update this.current 181 | let this_lp = GetWindowLongPtrA(hwnd, DWLP_USER); 182 | if this_lp != 0 { 183 | let this_ptr = this_lp as *mut ColorDialog; 184 | let this = this_ptr.as_mut().unwrap(); 185 | 186 | this.current[ctrl_id - 0x2c2] = u8sz_to_u8(&text); 187 | } 188 | } 189 | } 190 | }, 191 | 192 | WM_PAINT => { 193 | // trigger the change event 194 | let this_lp = GetWindowLongPtrA(hwnd, DWLP_USER); 195 | if this_lp != 0 { 196 | let this_ptr = this_lp as *mut ColorDialog; 197 | let this = this_ptr.as_mut().unwrap(); 198 | 199 | let rgb = RGB8::from(this.current); 200 | if rgb != this.last_notified { 201 | this.last_notified = rgb; 202 | 203 | if this.change_cb.is_some() { 204 | let cb = this.change_cb.as_ref().unwrap().as_ref(); 205 | cb(this_ptr.as_ref().unwrap(), &rgb); 206 | } 207 | } 208 | } 209 | }, 210 | 211 | _ => () 212 | } 213 | 0 214 | } -------------------------------------------------------------------------------- /lib/src/device.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Deref; 2 | use std::fmt; 3 | use rusb::{Context, UsbContext, DeviceHandle, Device, DeviceList}; 4 | use rgb::RGB8; 5 | 6 | use crate::error::{USBResult, USBError}; 7 | use crate::common::*; 8 | 9 | pub(crate) const USB_VENDOR_ID_RAZER: u16 = 0x1532; 10 | pub(crate) const USB_DEVICE_ID_RAZER_DEATHADDER_V2: u16 = 0x0084; 11 | 12 | /// A wrapper for rusb:Device with Display, and Default 13 | pub struct UsbDevice(Option>); 14 | 15 | impl Deref for UsbDevice { 16 | type Target = Option>; 17 | 18 | fn deref(&self) -> &Self::Target { 19 | &self.0 20 | } 21 | } 22 | 23 | fn get_device_name(handle: &DeviceHandle) -> String { 24 | let dev = handle.device(); 25 | match dev.device_descriptor() { 26 | Ok(dd) => { 27 | let serial = handle.read_serial_number_string_ascii(&dd) 28 | .unwrap_or_default(); 29 | let product = handle.read_product_string_ascii(&dd) 30 | .unwrap_or_default(); 31 | format!("{}{}{}", product, if serial.len() > 0 {" "} else {""}, serial) 32 | }, 33 | Err(_) => String::new(), 34 | } 35 | } 36 | 37 | impl fmt::Display for UsbDevice { 38 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 39 | match self { 40 | UsbDevice(Some(dev)) => { 41 | let devname = match dev.open() { 42 | Ok(h) => { 43 | get_device_name(&h) 44 | }, 45 | Err(_) => String::new(), 46 | }; 47 | write!(f, "{} ({}-{})", devname, dev.bus_number(), dev.address()) 48 | }, 49 | UsbDevice(None) => write!(f, "None") 50 | } 51 | } 52 | } 53 | 54 | impl Default for UsbDevice { 55 | fn default() -> Self { 56 | UsbDevice(None) 57 | } 58 | } 59 | 60 | impl UsbDevice { 61 | /// List all usb devices 62 | pub fn list() -> USBResult> { 63 | let ctx = Context::new()?; 64 | let device_list = DeviceList::new_with_context(ctx)?; 65 | let res = device_list.iter() 66 | .map(|d| UsbDevice(Some(d))) 67 | .collect::>(); 68 | Ok(res) 69 | } 70 | 71 | /// List all usb devices of the specified vendor 72 | pub fn by_vendor(vid: u16) -> USBResult> { 73 | let ctx = Context::new()?; 74 | let device_list = DeviceList::new_with_context(ctx)?; 75 | let res = device_list.iter() 76 | .filter_map(|device| { 77 | match device.device_descriptor() { 78 | Ok(descr) => if descr.vendor_id() == vid { 79 | Some(UsbDevice(Some(device))) 80 | } else { 81 | None 82 | }, 83 | Err(_) => None 84 | } 85 | }) 86 | .collect::>(); 87 | Ok(res) 88 | } 89 | 90 | /// List all usb devices of the specified vendor and with the specified product ID 91 | pub fn by_product(vid: u16, pid: u16) -> USBResult> { 92 | let ctx = Context::new()?; 93 | let device_list = DeviceList::new_with_context(ctx)?; 94 | let res = device_list.iter() 95 | .filter_map(|device| { 96 | match device.device_descriptor() { 97 | Ok(descr) => 98 | if descr.vendor_id() == vid && descr.product_id() == pid { 99 | Some(UsbDevice(Some(device))) 100 | } else { 101 | None 102 | }, 103 | Err(_) => None 104 | } 105 | }) 106 | .collect::>(); 107 | Ok(res) 108 | } 109 | } 110 | 111 | pub trait RazerDevice: fmt::Display { 112 | fn list() -> USBResult> { 113 | UsbDevice::by_vendor(USB_VENDOR_ID_RAZER) 114 | } 115 | 116 | fn vid(&self) -> u16 { USB_VENDOR_ID_RAZER } 117 | 118 | fn pid(&self) -> u16; 119 | 120 | fn name(&self) -> String { 121 | get_device_name(self.handle()) 122 | } 123 | 124 | fn handle(&self) -> &DeviceHandle; 125 | 126 | fn default_tx_id(&self) -> u8; 127 | 128 | fn send_payload(&self, request: &mut RazerReport) -> USBResult { 129 | request.transaction_id = self.default_tx_id(); 130 | razer_send_payload(self.handle(), request) 131 | } 132 | 133 | fn get_serial(&self) -> USBResult { 134 | let mut request = razer_chroma_standard_get_serial(); 135 | let response = self.send_payload(&mut request)?; 136 | 137 | let bytes = response.arguments[..22].iter() 138 | .take_while(|&&c| c != 0) 139 | .cloned() 140 | .collect::>(); 141 | 142 | Ok(String::from_utf8(bytes).unwrap_or(String::from(""))) 143 | } 144 | } 145 | 146 | /// A default implementation; Most mice would need some specialization 147 | pub trait RazerMouse: RazerDevice { 148 | fn min_dpi(&self) -> u16 { 149 | 100 150 | } 151 | 152 | fn max_dpi(&self) -> u16 { 153 | 30000 154 | } 155 | 156 | fn get_dpi(&self) -> USBResult<(u16, u16)> { 157 | let mut request = razer_chroma_misc_get_dpi_xy(LedStorage::NoStore); 158 | let response = self.send_payload(&mut request)?; 159 | 160 | let dpi_x = ((response.arguments[1] as u16) << 8) | (response.arguments[2] as u16) & 0xff; 161 | let dpi_y = ((response.arguments[3] as u16) << 8) | (response.arguments[4] as u16) & 0xff; 162 | 163 | Ok((dpi_x, dpi_y)) 164 | } 165 | 166 | fn set_dpi(&self, dpi_x: u16, dpi_y: u16) -> USBResult<()> { 167 | let dpi_x = dpi_x.clamp(self.min_dpi(), self.max_dpi()); 168 | let dpi_y = dpi_y.clamp(self.min_dpi(), self.max_dpi()); 169 | 170 | let mut request = razer_chroma_misc_set_dpi_xy( 171 | LedStorage::NoStore, dpi_x, dpi_y); 172 | self.send_payload(&mut request)?; 173 | Ok(()) 174 | } 175 | 176 | /// Return a vector of the DPI stages in (dpiX, dpiY) tuples, and an 177 | /// index of the currently selected stage 178 | fn get_dpi_stages(&self) -> USBResult<(Vec<(u16, u16)>, u8)> { 179 | let mut request = razer_chroma_misc_get_dpi_xy_stages(LedStorage::NoStore); 180 | let response = self.send_payload(&mut request)?; 181 | 182 | // index reported by the device (at least DeathAdderV2) is 1-based 183 | let current = response.arguments[1] - 1; 184 | let num_stages = response.arguments[2]; 185 | let mut dpi_stages: Vec<(u16, u16)> = Vec::with_capacity(num_stages as usize); 186 | let mut arg_idx = 3; 187 | for _i in 1..=num_stages { 188 | let dpi_x = ((response.arguments[arg_idx+1] as u16) << 8) | 189 | (response.arguments[arg_idx+2] as u16) & 0xff; 190 | let dpi_y = ((response.arguments[arg_idx+3] as u16) << 8) | 191 | (response.arguments[arg_idx+4] as u16) & 0xff; 192 | dpi_stages.push((dpi_x, dpi_y)); 193 | arg_idx += 7; 194 | } 195 | 196 | Ok((dpi_stages, current)) 197 | } 198 | 199 | fn set_dpi_stages( 200 | &self, 201 | dpi_stages: &[(u16, u16)], 202 | current: u8 203 | ) -> USBResult<()> { 204 | let mut dpi_stages: Vec<(u16, u16)> = dpi_stages.to_vec(); 205 | for (dpi_x, dpi_y) in &mut dpi_stages { 206 | *dpi_x = (*dpi_x).clamp(self.min_dpi(), self.max_dpi()); 207 | *dpi_y = (*dpi_y).clamp(self.min_dpi(), self.max_dpi()); 208 | } 209 | 210 | // device expects current index to be 1-based 211 | let mut request = razer_chroma_misc_set_dpi_xy_stages( 212 | LedStorage::NoStore, &dpi_stages, current + 1); 213 | self.send_payload(&mut request)?; 214 | Ok(()) 215 | } 216 | 217 | fn get_poll_rate(&self) -> USBResult { 218 | let mut request = razer_chroma_misc_get_polling_rate(); 219 | let response = self.send_payload(&mut request)?; 220 | PollingRate::try_from(response.arguments[0]) 221 | .or(Err(USBError::ResponseUnknownValue(response.arguments[0]))) 222 | } 223 | 224 | fn set_poll_rate(&self, poll_rate: PollingRate) -> USBResult<()> { 225 | let mut request = razer_chroma_misc_set_polling_rate(poll_rate); 226 | self.send_payload(&mut request)?; 227 | Ok(()) 228 | } 229 | 230 | fn preview_static(&self, logo_color: RGB8, scroll_color: RGB8) -> USBResult<()>; 231 | 232 | fn set_logo_color(&self, color: RGB8) -> USBResult<()> { 233 | let mut request = razer_chroma_extended_matrix_effect_static( 234 | LedStorage::VarStore, Led::Logo, color); 235 | self.send_payload(&mut request)?; 236 | Ok(()) 237 | } 238 | 239 | fn set_scroll_color(&self, color: RGB8) -> USBResult<()> { 240 | let mut request = razer_chroma_extended_matrix_effect_static( 241 | LedStorage::VarStore, Led::ScrollWheel, color); 242 | self.send_payload(&mut request)?; 243 | Ok(()) 244 | } 245 | 246 | fn get_logo_brightness(&self) -> USBResult { 247 | let mut request = razer_chroma_extended_matrix_get_brightness( 248 | LedStorage::VarStore, Led::Logo); 249 | 250 | let response = self.send_payload(&mut request)?; 251 | Ok((100.0 * response.arguments[2] as f32 / 255.0).round() as u8) 252 | } 253 | 254 | fn set_logo_brightness(&self, brightness: u8) -> USBResult<()> { 255 | let b = (255.0 * brightness.clamp(0, 100) as f32 / 100.0).round() as u8; 256 | let mut request = razer_chroma_extended_matrix_brightness( 257 | LedStorage::VarStore, Led::Logo, b); 258 | self.send_payload(&mut request)?; 259 | Ok(()) 260 | } 261 | 262 | fn get_scroll_brightness(&self) -> USBResult { 263 | let mut request = razer_chroma_extended_matrix_get_brightness( 264 | LedStorage::VarStore, Led::ScrollWheel); 265 | 266 | let response = self.send_payload(&mut request)?; 267 | Ok((100.0 * response.arguments[2] as f32 / 255.0).round() as u8) 268 | } 269 | 270 | fn set_scroll_brightness(&self, brightness: u8) -> USBResult<()> { 271 | let b = (255.0 * brightness.clamp(0, 100) as f32 / 100.0).round() as u8; 272 | let mut request = razer_chroma_extended_matrix_brightness( 273 | LedStorage::VarStore, Led::ScrollWheel, b); 274 | self.send_payload(&mut request)?; 275 | Ok(()) 276 | } 277 | 278 | } 279 | 280 | /// A default "to_string()" implementation for all RazerDevices 281 | fn razer_dev_default_fmt(dev: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { 282 | let serial = dev.get_serial().unwrap_or(String::from("")); 283 | write!(f, "{} ({})", dev.name(), serial) 284 | } 285 | 286 | pub struct DeathAdderV2 { 287 | handle: DeviceHandle, 288 | } 289 | 290 | impl RazerDevice for DeathAdderV2 { 291 | fn pid(&self) -> u16 { USB_DEVICE_ID_RAZER_DEATHADDER_V2 } 292 | 293 | fn handle(&self) -> &DeviceHandle { 294 | &self.handle 295 | } 296 | 297 | fn default_tx_id(&self) -> u8 { 298 | 0x3f // except for razer_naga_trinity_effect_static which is 0x1f 299 | } 300 | } 301 | 302 | impl RazerMouse for DeathAdderV2 { 303 | fn max_dpi(&self) -> u16 { 304 | 20000 305 | } 306 | 307 | fn preview_static(&self, logo_color: RGB8, scroll_color: RGB8) -> USBResult<()> { 308 | let mut request = razer_naga_trinity_effect_static( 309 | LedStorage::NoStore, LedEffect::Static, logo_color, scroll_color); 310 | self.send_payload(&mut request)?; 311 | Ok(()) 312 | } 313 | } 314 | 315 | impl fmt::Display for DeathAdderV2 { 316 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 317 | razer_dev_default_fmt(self, f) 318 | } 319 | } 320 | 321 | impl DeathAdderV2 { 322 | pub fn new() -> USBResult { 323 | let ctx = Context::new()?; 324 | let handle = match ctx.open_device_with_vid_pid( 325 | USB_VENDOR_ID_RAZER, USB_DEVICE_ID_RAZER_DEATHADDER_V2) { 326 | Some(handle) => Ok(handle), 327 | None => Err(USBError::DeviceNotFound), 328 | }?; 329 | Ok(Self { handle: handle }) 330 | } 331 | 332 | pub fn list() -> USBResult> { 333 | UsbDevice::by_product( 334 | USB_VENDOR_ID_RAZER, USB_DEVICE_ID_RAZER_DEATHADDER_V2) 335 | } 336 | 337 | pub fn from(device: &UsbDevice) -> USBResult { 338 | let device = match device.as_ref() { 339 | Some(device) => Ok(device), 340 | None => Err(USBError::DeviceNotFound), 341 | }?; 342 | 343 | let desc = device.device_descriptor()?; 344 | if desc.vendor_id() != USB_VENDOR_ID_RAZER || 345 | desc.product_id() != USB_DEVICE_ID_RAZER_DEATHADDER_V2 { 346 | return Err(USBError::NonCompatibleDevice); 347 | } 348 | 349 | let handle = device.open()?; 350 | Ok(Self { handle: handle }) 351 | } 352 | } 353 | -------------------------------------------------------------------------------- /lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod cfg; 2 | pub mod error; 3 | pub mod device; 4 | 5 | pub mod common { 6 | use std::{num::ParseIntError, thread, time::Duration, fmt::Display}; 7 | use rusb::{DeviceHandle, UsbContext}; 8 | use core::mem::{size_of, size_of_val, MaybeUninit}; 9 | use rgb::{RGB8, FromSlice}; 10 | use crate::error::{ParseRGBError, USBResult, USBError}; 11 | 12 | pub fn rgb_from_hex(input: &str) -> Result { 13 | let s = input 14 | .trim_start_matches("0x") 15 | .trim_start_matches("#") 16 | .trim_end_matches("h"); 17 | 18 | match s.len() { 19 | 3 => { 20 | match s.chars() 21 | .map(|c| u8::from_str_radix(format!("{}{}", c, c).as_str(), 16)) 22 | .collect::, ParseIntError>>() { 23 | Ok(res) => Ok(res.as_rgb()[0]), 24 | Err(pie) => Err(ParseRGBError::from(pie)) 25 | } 26 | }, 27 | 6 => { 28 | match (0..s.len()) 29 | .step_by(2) 30 | .map(|i| u8::from_str_radix(&s[i..i + 2], 16)) 31 | .collect::, ParseIntError>>() { 32 | Ok(res) => Ok(res.as_rgb()[0]), 33 | Err(pie) => Err(ParseRGBError::from(pie)) 34 | } 35 | }, 36 | _ => { 37 | Err(ParseRGBError::WrongLength(s.len())) 38 | } 39 | } 40 | } 41 | 42 | // tried also 1ms with varying results 43 | static USB_RECEIVER_WAIT: Duration = Duration::from_millis(10); 44 | static USB_TXFER_TIMEOUT: Duration = Duration::from_secs(1); 45 | 46 | // const RAZER_USB_REPORT_LEN: usize = 0x5A; 47 | 48 | #[repr(u8)] 49 | #[derive(Debug, Copy, Clone)] 50 | pub enum LedState { 51 | Off = 0x00, 52 | On = 0x01, 53 | } 54 | 55 | #[repr(u8)] 56 | #[derive(Debug, Copy, Clone)] 57 | pub enum LedStorage { 58 | NoStore = 0x00, 59 | VarStore = 0x01, 60 | } 61 | 62 | #[repr(u8)] 63 | #[derive(Debug, Copy, Clone)] 64 | pub enum Led { 65 | Zero = 0x00, 66 | ScrollWheel = 0x01, 67 | Battery = 0x03, 68 | Logo = 0x04, 69 | Backlight = 0x05, 70 | Macro = 0x07, 71 | Game = 0x08, 72 | RedProfile = 0x0C, 73 | GreenProfile = 0x0D, 74 | BlueProfile = 0x0E, 75 | RightSide = 0x10, 76 | LeftSide = 0x11, 77 | ArgbCh1 = 0x1A, 78 | ArgbCh2 = 0x1B, 79 | ArgbCh3 = 0x1C, 80 | ArgbCh4 = 0x1D, 81 | ArgbCh5 = 0x1E, 82 | ArgbCh6 = 0x1F, 83 | Charging = 0x20, 84 | FastCharging = 0x21, 85 | FullyCharged = 0x22 86 | } 87 | 88 | #[repr(u8)] 89 | #[derive(Debug, Copy, Clone)] 90 | pub enum LedEffect { 91 | None = 0x00, 92 | Static = 0x01, 93 | Breathing = 0x02, 94 | Spectrum = 0x03, 95 | Wave = 0x04, 96 | Reactive = 0x05, 97 | Starlight = 0x07, 98 | CustomFrame = 0x08, 99 | } 100 | 101 | #[repr(u8)] 102 | #[derive(Debug, Copy, Clone)] 103 | enum CmdStatus { 104 | Busy = 0x01, 105 | Successful = 0x02, 106 | Failure = 0x03, 107 | Timeout = 0x04, 108 | NotSupported = 0x05, 109 | } 110 | 111 | impl TryFrom for CmdStatus { 112 | type Error = u8; 113 | 114 | fn try_from(byte: u8) -> Result { 115 | match byte { 116 | x if x == CmdStatus::Busy as u8 => Ok(CmdStatus::Busy), 117 | x if x == CmdStatus::Successful as u8 => Ok(CmdStatus::Successful), 118 | x if x == CmdStatus::Failure as u8 => Ok(CmdStatus::Failure), 119 | x if x == CmdStatus::Timeout as u8 => Ok(CmdStatus::Timeout), 120 | x if x == CmdStatus::NotSupported as u8 => Ok(CmdStatus::NotSupported), 121 | _ => Err(byte), 122 | } 123 | } 124 | } 125 | 126 | #[repr(u8)] 127 | #[derive(Debug, Copy, Clone, PartialEq)] 128 | pub enum PollingRate { 129 | Hz1000 = 0x01, 130 | Hz500 = 0x02, 131 | Hz250 = 0x04, 132 | Hz125 = 0x08, 133 | } 134 | 135 | impl Default for PollingRate { 136 | fn default() -> Self { 137 | PollingRate::Hz500 138 | } 139 | } 140 | 141 | impl TryFrom for PollingRate { 142 | type Error = u8; 143 | 144 | fn try_from(flag: u8) -> Result { 145 | match flag { 146 | x if x == PollingRate::Hz1000 as u8 => Ok(PollingRate::Hz1000), 147 | x if x == PollingRate::Hz500 as u8 => Ok(PollingRate::Hz500), 148 | x if x == PollingRate::Hz250 as u8 => Ok(PollingRate::Hz250), 149 | x if x == PollingRate::Hz125 as u8 => Ok(PollingRate::Hz125), 150 | _ => Err(flag), 151 | } 152 | } 153 | } 154 | 155 | impl Display for PollingRate { 156 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 157 | match self { 158 | PollingRate::Hz1000 => write!(f, "1000 Hz"), 159 | PollingRate::Hz500 => write!(f, "500 Hz"), 160 | PollingRate::Hz250 => write!(f, "250 Hz"), 161 | PollingRate::Hz125 => write!(f, "125 Hz"), 162 | } 163 | } 164 | } 165 | 166 | impl PollingRate { 167 | pub fn all() -> Vec { 168 | vec![PollingRate::Hz125, PollingRate::Hz250, PollingRate::Hz500, PollingRate::Hz1000] 169 | } 170 | } 171 | 172 | #[repr(C, packed)] 173 | #[derive(Debug, Copy, Clone)] 174 | pub struct RazerReport { 175 | status: u8, 176 | pub(crate) transaction_id: u8, 177 | remaining_packets: u16, // big endian 178 | protocol_type: u8, // 0x0 179 | data_size: u8, 180 | command_class: u8, 181 | command_id: u8, 182 | pub(crate) arguments: [u8; 80], 183 | crc: u8, // xor'ed bytes of report 184 | reserved: u8, // 0x0 185 | } 186 | 187 | impl Default for RazerReport { 188 | fn default() -> Self { 189 | unsafe { 190 | // safe as 0 a valid bit-pattern for all fields 191 | MaybeUninit::::zeroed().assume_init() 192 | } 193 | } 194 | } 195 | 196 | impl RazerReport { 197 | fn init(cmd_cls: u8, cmd_id: u8, data_size: u8) -> Self { 198 | Self { 199 | command_class: cmd_cls, 200 | command_id: cmd_id, 201 | data_size: data_size, 202 | ..Default::default() 203 | } 204 | } 205 | 206 | fn new(cmd_cls: u8, cmd_id: u8, args: &[u8]) -> Self { 207 | let mut r = Self { 208 | command_class: cmd_cls, 209 | command_id: cmd_id, 210 | data_size: args.len() as u8, 211 | ..Default::default() 212 | }; 213 | r.arguments[..args.len()].copy_from_slice(args); 214 | r 215 | } 216 | 217 | fn update_crc(&mut self) -> &mut Self { 218 | let s = self.bytes(); 219 | 220 | self.crc = s[2..88].iter().fold(0, |crc, x| crc ^ x); 221 | self 222 | } 223 | 224 | /// Converts this struct to network byte order in-place 225 | fn to_network_byte_order_mut(&mut self) -> &mut Self { 226 | self.remaining_packets = 227 | (self.remaining_packets & 0xff) << 8 | 228 | (self.remaining_packets >> 8); 229 | self 230 | } 231 | 232 | /// Returns a copy of this struct in network byte order 233 | fn to_network_byte_order(mut self) -> Self { 234 | self.to_network_byte_order_mut(); 235 | self 236 | } 237 | 238 | /// Converts this struct to host byte order in-place 239 | fn to_host_byte_order_mut(&mut self) -> &mut Self { 240 | self.to_network_byte_order_mut() 241 | } 242 | 243 | /// Returns a copy of this struct in host byte order 244 | fn to_host_byte_order(mut self) -> Self { 245 | self.to_host_byte_order_mut(); 246 | self 247 | } 248 | 249 | /// Struct as a slice; fast, zero-copy; host byte order 250 | fn bytes(&self) -> &[u8] { 251 | unsafe { 252 | core::slice::from_raw_parts( 253 | (self as *const Self) as *const u8, 254 | size_of::(), 255 | ) 256 | } 257 | } 258 | 259 | /// Initializes this struct from the given slice. No conversion to byte order. 260 | fn from(buffer: &[u8]) -> Option { 261 | let c_buf = buffer.as_ptr(); 262 | let s = c_buf as *mut Self; 263 | 264 | if size_of::() == size_of_val(buffer) { 265 | unsafe { 266 | let ref s2 = *s; 267 | Some(*s2) 268 | } 269 | } else { 270 | None 271 | } 272 | } 273 | 274 | /// Converts to network byte order and returns a copy as_slice 275 | fn pack(self) -> Vec { 276 | self.to_network_byte_order().bytes().into() 277 | } 278 | 279 | /// Converts to network byte order in-place(!) and returns as_slice. 280 | /// Equivalent to self.to_network_byte_order_mut().bytes() 281 | #[allow(dead_code)] 282 | fn pack_mut(&mut self) -> &[u8] { 283 | self.to_network_byte_order_mut().bytes() 284 | } 285 | 286 | /// Construct from slice and return a copy in host byte order 287 | fn unpack(buffer: &[u8]) -> Option { 288 | match Self::from(buffer) { 289 | Some(rep) => Some(rep.to_host_byte_order()), 290 | None => None 291 | } 292 | } 293 | 294 | } 295 | 296 | fn razer_send_control_msg( 297 | usb_dev: &DeviceHandle, 298 | data: &RazerReport, 299 | report_index: u16 300 | ) -> USBResult { 301 | let request = 0x09u8; // HID_REQ_SET_REPORT 302 | let request_type = 0x21u8; // USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT 303 | let value = 0x300u16; 304 | 305 | let written = usb_dev.write_control( 306 | request_type, request, value, report_index, 307 | &data.pack(), USB_TXFER_TIMEOUT)?; 308 | 309 | // wait here otherwise we fail on any subsequent HID_REQ_GET_REPORTs 310 | thread::sleep(USB_RECEIVER_WAIT); 311 | 312 | Ok(written) 313 | } 314 | 315 | fn razer_get_usb_response( 316 | usb_dev: &DeviceHandle, 317 | report_index: u16, 318 | request_report: &RazerReport, 319 | response_index: u16 320 | ) -> USBResult { 321 | let written = razer_send_control_msg( 322 | usb_dev, request_report, report_index)?; 323 | if written != size_of_val(request_report) { 324 | return Err(USBError::IncompleteWrite( 325 | size_of_val(request_report), written)); 326 | } 327 | 328 | let request = 0x01u8; // HID_REQ_GET_REPORT 329 | let request_type = 0xA1u8; // USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN 330 | let value = 0x300u16; 331 | let mut buffer = [0u8; size_of::()]; 332 | let read = usb_dev.read_control( 333 | request_type, request, value, response_index, 334 | &mut buffer, USB_TXFER_TIMEOUT)?; 335 | if read != size_of::() { 336 | return Err(USBError::IncompleteRead( 337 | size_of::(), read)); 338 | } 339 | 340 | // RazerReport::from() won't fail with this buf 341 | Ok(RazerReport::unpack(&buffer).unwrap()) 342 | } 343 | 344 | fn razer_get_report( 345 | usb_dev: &DeviceHandle, 346 | request: &RazerReport 347 | ) -> USBResult { 348 | let index = 0u16; 349 | razer_get_usb_response(usb_dev, index, request, index) 350 | } 351 | 352 | pub(crate) fn razer_send_payload( 353 | usb_dev: &DeviceHandle, 354 | request: &mut RazerReport 355 | ) -> USBResult { 356 | request.update_crc(); 357 | let response = razer_get_report(usb_dev, request)?; 358 | 359 | if response.remaining_packets != request.remaining_packets || 360 | response.command_class != request.command_class || 361 | response.command_id != request.command_id { 362 | return Err(USBError::ResponseMismatch); 363 | } 364 | 365 | match CmdStatus::try_from(response.status) { 366 | Ok(CmdStatus::Busy) => Err(USBError::DeviceBusy), 367 | Ok(CmdStatus::Failure) => Err(USBError::CommandFailed), 368 | Ok(CmdStatus::NotSupported) => Err(USBError::CommandNotSupported), 369 | Ok(CmdStatus::Timeout) => Err(USBError::CommandTimeout), 370 | Ok(CmdStatus::Successful) => Ok(response), 371 | Err(status) => Err(USBError::ResponseUnknownStatus(status)), 372 | } 373 | } 374 | 375 | pub(crate) fn razer_chroma_standard_get_serial() -> RazerReport { 376 | RazerReport::init(0x00, 0x82, 0x16) 377 | } 378 | 379 | pub(crate) fn razer_chroma_misc_get_dpi_xy(variable_storage: LedStorage) -> RazerReport { 380 | let mut report = RazerReport::init(0x04, 0x85, 0x07); 381 | report.arguments[0] = variable_storage as u8; 382 | report 383 | } 384 | 385 | pub(crate) fn razer_chroma_misc_set_dpi_xy( 386 | variable_storage: LedStorage, 387 | dpi_x: u16, 388 | dpi_y: u16 389 | ) -> RazerReport { 390 | // Keep the DPI within bounds 391 | let dpi_x = dpi_x.clamp(100, 30000); 392 | let dpi_y = dpi_y.clamp(100, 30000); 393 | RazerReport::new(0x04, 0x05, &[ 394 | variable_storage as u8, 395 | ((dpi_x >> 8) & 0xFF) as u8, 396 | (dpi_x & 0xFF) as u8, 397 | ((dpi_y >> 8) & 0xFF) as u8, 398 | (dpi_y & 0xFF) as u8, 399 | 0x00u8, 400 | 0x00u8, 401 | ]) 402 | } 403 | 404 | pub(crate) fn razer_chroma_misc_get_dpi_xy_stages(variable_storage: LedStorage) -> RazerReport { 405 | RazerReport::new(0x04, 0x86, &[variable_storage as u8]) 406 | } 407 | 408 | pub(crate) fn razer_chroma_misc_set_dpi_xy_stages( 409 | variable_storage: LedStorage, 410 | dpi_stages: &[(u16, u16)], 411 | current: u8 412 | ) -> RazerReport { 413 | let num_stages = dpi_stages.len(); 414 | assert!(num_stages > 0, "num stages must be greater than 0"); 415 | assert!(num_stages < 6, "num stages cannot be more than 5"); 416 | let num_stages = num_stages as u8; 417 | 418 | let current = current.clamp(1, num_stages); 419 | let mut report = RazerReport::init(0x04, 0x06, 3 + num_stages * 7); 420 | report.arguments[0] = variable_storage as u8; 421 | report.arguments[1] = current; 422 | report.arguments[2] = num_stages; 423 | 424 | let mut report_idx = 3; 425 | let mut stage_idx = 1; 426 | 427 | for &(dpi_x, dpi_y) in dpi_stages { 428 | // Keep the DPI within bounds 429 | let dpi_x = dpi_x.clamp(100, 30000); 430 | let dpi_y = dpi_y.clamp(100, 30000); 431 | 432 | report.arguments[report_idx+0] = stage_idx; 433 | report.arguments[report_idx+1] = ((dpi_x >> 8) & 0xFF) as u8; 434 | report.arguments[report_idx+2] = (dpi_x & 0xFF) as u8; 435 | report.arguments[report_idx+3] = ((dpi_y >> 8) & 0xFF) as u8; 436 | report.arguments[report_idx+4] = (dpi_y & 0xFF) as u8; 437 | report.arguments[report_idx+5] = 0x00; 438 | report.arguments[report_idx+6] = 0x00; 439 | 440 | stage_idx += 1; 441 | report_idx += 7; 442 | } 443 | 444 | report 445 | } 446 | 447 | pub(crate) fn razer_chroma_misc_get_polling_rate() -> RazerReport { 448 | RazerReport::init(0x00, 0x85, 0x01) 449 | } 450 | 451 | pub(crate) fn razer_chroma_misc_set_polling_rate(polling_rate: PollingRate) -> RazerReport { 452 | RazerReport::new(0x00, 0x05, &[ 453 | polling_rate as u8, 454 | ]) 455 | } 456 | 457 | pub(crate) fn razer_naga_trinity_effect_static( 458 | variable_storage: LedStorage, 459 | effect: LedEffect, 460 | logo_rgb: RGB8, 461 | scroll_rgb: RGB8, 462 | ) -> RazerReport { 463 | RazerReport::new(0x0f, 0x03, &[ 464 | variable_storage as u8, 465 | 0x00, // LED ID ? 466 | 0x00, // Unknown 467 | 0x00, // Unknown 468 | effect as u8, 469 | scroll_rgb.r, scroll_rgb.g, scroll_rgb.b, 470 | logo_rgb.r, logo_rgb.g, logo_rgb.b, 471 | ]) 472 | } 473 | 474 | fn razer_chroma_extended_matrix_effect_base( 475 | arg_size: u8, 476 | variable_storage: LedStorage, 477 | led: Led, 478 | effect: LedEffect, 479 | ) -> RazerReport { 480 | let mut report = RazerReport::init(0x0f, 0x02, arg_size); 481 | report.arguments[0] = variable_storage as u8; 482 | report.arguments[1] = led as u8; 483 | report.arguments[2] = effect as u8; 484 | report 485 | } 486 | 487 | #[allow(dead_code)] 488 | pub(crate) fn razer_chroma_extended_matrix_effect_none( 489 | variable_storage: LedStorage, 490 | led: Led, 491 | ) -> RazerReport { 492 | razer_chroma_extended_matrix_effect_base( 493 | 0x06, variable_storage, led, LedEffect::None) 494 | } 495 | 496 | pub(crate) fn razer_chroma_extended_matrix_effect_static( 497 | variable_storage: LedStorage, 498 | led: Led, 499 | rgb: RGB8, 500 | ) -> RazerReport { 501 | let mut report = razer_chroma_extended_matrix_effect_base( 502 | 0x09, variable_storage, led, LedEffect::Static); 503 | report.arguments[5] = 0x01; 504 | report.arguments[6] = rgb.r; 505 | report.arguments[7] = rgb.g; 506 | report.arguments[8] = rgb.b; 507 | report 508 | } 509 | 510 | pub(crate) fn razer_chroma_extended_matrix_brightness( 511 | variable_storage: LedStorage, 512 | led: Led, 513 | brightness: u8, 514 | ) -> RazerReport { 515 | RazerReport::new(0x0F, 0x04, &[ 516 | variable_storage as u8, 517 | led as u8, 518 | brightness, // in the [0-255] range 519 | ]) 520 | } 521 | 522 | pub(crate) fn razer_chroma_extended_matrix_get_brightness( 523 | variable_storage: LedStorage, 524 | led: Led, 525 | ) -> RazerReport { 526 | RazerReport::new(0x0F, 0x84, &[ 527 | variable_storage as u8, 528 | led as u8, 529 | 0x00, // brightness 530 | ]) 531 | } 532 | } 533 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /gui/src/gui.rs: -------------------------------------------------------------------------------- 1 | #![windows_subsystem = "windows"] 2 | 3 | use std::sync::Arc; 4 | use std::ptr; 5 | use std::{cell::RefCell, sync::Mutex}; 6 | use std::thread; 7 | use hidapi_rusb::{HidError, HidApi, HidDevice}; 8 | use windows::{ 9 | core::{s, PCSTR}, 10 | Win32::{ 11 | System::Diagnostics::Debug::OutputDebugStringA, 12 | Foundation::{HWND, WPARAM, LPARAM, HINSTANCE}, 13 | UI::{ 14 | Controls::{TBS_TOOLTIPS, TBS_BOTTOM, TBS_DOWNISLEFT, TBM_SETLINESIZE, 15 | TBM_SETPAGESIZE, TBM_SETTICFREQ, TBS_NOTIFYBEFOREMOVE, 16 | }, 17 | WindowsAndMessaging::{SendMessageA, GetWindowLongA, SetWindowLongA, 18 | GWL_STYLE, MessageBoxA, MB_OK, MB_ICONERROR, BS_TOP, 19 | SetCursor, LoadCursorW, IDC_HAND, IDC_ARROW, 20 | WM_GETMINMAXINFO, MINMAXINFO, 21 | }, 22 | }, 23 | }, 24 | }; 25 | use native_windows_gui as nwg; 26 | use native_windows_derive as nwd; 27 | use nwd::{NwgUi, NwgPartial}; 28 | use nwg::{NativeUi, RadioButtonState}; 29 | 30 | use rgb::RGB8; 31 | use librazer::{cfg::Config, device::UsbDevice, common::PollingRate}; 32 | use librazer::device::{DeathAdderV2, RazerDevice, RazerMouse}; 33 | 34 | pub mod color_chooser; 35 | use color_chooser::ColorDialog; 36 | 37 | /* 38 | * Log messages to the debugger using OutputDebugString (only for command line 39 | * invocation). Use DebugView by Mark Russinovich to view 40 | */ 41 | macro_rules! dbglog { 42 | ($($args: tt)*) => {{ 43 | let msg = format!($($args)*); 44 | let msg_sz = format!("{}{}", msg, "\0"); 45 | println!("{}", msg); 46 | unsafe { 47 | OutputDebugStringA(PCSTR::from_raw(msg_sz.as_ptr())); 48 | } 49 | }} 50 | } 51 | 52 | // macro_rules! dbgpanic { 53 | // ($($args: tt)*) => {{ 54 | // let msg = format!($($args)*); 55 | // let msg_sz = format!("{}{}", msg, "\0"); 56 | // unsafe { 57 | // OutputDebugStringA(PCSTR::from_raw(msg_sz.as_ptr())); 58 | // } 59 | // panic!("{}", msg); 60 | // }} 61 | // } 62 | 63 | macro_rules! msgboxpanic { 64 | ($($args: tt)*) => {{ 65 | let msg = format!($($args)*); 66 | let msg_sz = format!("{}{}", msg, "\0"); 67 | unsafe { 68 | let msg_ptr = PCSTR::from_raw(msg_sz.as_ptr()); 69 | MessageBoxA(HWND(0), msg_ptr, s!("Error"), MB_OK | MB_ICONERROR); 70 | } 71 | panic!("{}", msg); 72 | }} 73 | } 74 | 75 | macro_rules! msgboxerror { 76 | ($($args: tt)*) => {{ 77 | let msg = format!($($args)*); 78 | let msg_sz = format!("{}{}", msg, "\0"); 79 | eprintln!("{}", msg); 80 | unsafe { 81 | let msg_ptr = PCSTR::from_raw(msg_sz.as_ptr()); 82 | MessageBoxA(HWND(0), msg_ptr, s!("Error"), MB_OK | MB_ICONERROR); 83 | } 84 | }} 85 | } 86 | 87 | /// convert bool to nwg::CheckBoxState 88 | macro_rules! to_check_state { 89 | ($b:expr) => { 90 | if $b { nwg::CheckBoxState::Checked } else { nwg::CheckBoxState::Unchecked } 91 | }; 92 | } 93 | 94 | /// convert nwg::CheckBoxState to bool 95 | macro_rules! from_check_state { 96 | ($s:expr) => { 97 | match $s { 98 | nwg::CheckBoxState::Checked => true, 99 | _ => false, 100 | } 101 | }; 102 | } 103 | 104 | fn configure_trackbar(bar: &nwg::TrackBar, line: isize, page: isize, tick: usize) { 105 | unsafe { 106 | let hbar = HWND(bar.handle.hwnd().unwrap() as isize); 107 | SendMessageA(hbar, TBM_SETLINESIZE, WPARAM(0), LPARAM(line)); 108 | SendMessageA(hbar, TBM_SETPAGESIZE, WPARAM(0), LPARAM(page)); 109 | SendMessageA(hbar, TBM_SETTICFREQ, WPARAM(tick), LPARAM(0)); 110 | add_style(&bar.handle, 111 | (TBS_TOOLTIPS | TBS_BOTTOM | TBS_DOWNISLEFT | TBS_NOTIFYBEFOREMOVE) as i32); 112 | } 113 | } 114 | 115 | fn add_style(handle: &nwg::ControlHandle, style: i32) { 116 | unsafe { 117 | let hwnd = HWND(handle.hwnd().unwrap() as isize); 118 | let style = style | GetWindowLongA(hwnd, GWL_STYLE); 119 | SetWindowLongA(hwnd, GWL_STYLE, style); 120 | } 121 | } 122 | 123 | #[derive(Default, NwgPartial)] 124 | pub struct DpiStagesUI { 125 | #[nwg_layout(margin: [0, 0, 0, 0], max_column: Some(5)/* , max_size: [1000, 150]*/)] 126 | grid: nwg::GridLayout, 127 | 128 | #[nwg_control(text: "2000", flags: "VISIBLE | GROUP")] 129 | #[nwg_layout_item(layout: grid, col: 0)] 130 | rad_dpi_1: nwg::RadioButton, 131 | 132 | #[nwg_control(text: "5000")] 133 | #[nwg_layout_item(layout: grid, col: 1)] 134 | rad_dpi_2: nwg::RadioButton, 135 | 136 | #[nwg_control(text: "10000")] 137 | #[nwg_layout_item(layout: grid, col: 2)] 138 | rad_dpi_3: nwg::RadioButton, 139 | 140 | #[nwg_control(text: "15000")] 141 | #[nwg_layout_item(layout: grid, col: 3)] 142 | rad_dpi_4: nwg::RadioButton, 143 | 144 | #[nwg_control(text: "20000")] 145 | #[nwg_layout_item(layout: grid, col: 4)] 146 | rad_dpi_5: nwg::RadioButton, 147 | } 148 | 149 | #[derive(Default, NwgUi)] 150 | pub struct DeathAdderv2App { 151 | #[nwg_control(size: (700, 400), center: true, title: "Razer DeathAdder v2 configuration")] 152 | #[nwg_events( OnWindowClose: [DeathAdderv2App::window_close(SELF)])] 153 | window: nwg::Window, 154 | 155 | #[nwg_layout(parent: window, min_size: [400, 200], max_column: Some(11))] 156 | grid: nwg::GridLayout, 157 | 158 | #[nwg_control(text: "Device:", h_align: nwg::HTextAlign::Right, v_align: nwg::VTextAlign::Top)] 159 | #[nwg_layout_item(layout: grid, col_span: 3)] 160 | lbl_device: nwg::Label, 161 | 162 | #[nwg_control(v_align: nwg::VTextAlign::Top)] // has trouble aligning vertically 163 | #[nwg_layout_item(layout: grid, col: 3, col_span: 7)] 164 | #[nwg_events( OnComboxBoxSelection: [DeathAdderv2App::device_selected(SELF)])] 165 | cmb_device: nwg::ComboBox, 166 | 167 | /* 168 | * DPI stages 169 | */ 170 | #[nwg_control(v_align: nwg::VTextAlign::Top, // has trouble aligning vertically 171 | collection: vec!["1 DPI stage", "2 DPI stages", "3 DPI stages", "4 DPI stages", "5 DPI stages"], 172 | selected_index: Some(0))] 173 | #[nwg_layout_item(layout: grid, row: 1, col: 1, col_span: 2)] 174 | #[nwg_events( OnComboxBoxSelection: [DeathAdderv2App::numstages_selected(SELF)])] 175 | cmb_numstages: nwg::ComboBox<&'static str>, 176 | 177 | #[nwg_control(text: "Stage DPI:", h_align: nwg::HTextAlign::Right, v_align: nwg::VTextAlign::Top)] 178 | #[nwg_layout_item(layout: grid, row: 2, col_span: 3)] 179 | lbl_stagedpi: nwg::Label, 180 | 181 | #[nwg_control(flags: "VISIBLE")] 182 | #[nwg_layout_item(layout: grid, row: 1, col: 3, col_span: 6)] 183 | frm_stages: nwg::Frame, 184 | 185 | #[nwg_partial(parent: frm_stages)] 186 | #[nwg_events( 187 | (rad_dpi_1, OnButtonClick): [DeathAdderv2App::stage_selected(SELF)], 188 | (rad_dpi_2, OnButtonClick): [DeathAdderv2App::stage_selected(SELF)], 189 | (rad_dpi_3, OnButtonClick): [DeathAdderv2App::stage_selected(SELF)], 190 | (rad_dpi_4, OnButtonClick): [DeathAdderv2App::stage_selected(SELF)], 191 | (rad_dpi_5, OnButtonClick): [DeathAdderv2App::stage_selected(SELF)], 192 | )] 193 | par_stages: DpiStagesUI, 194 | 195 | #[nwg_control(range: Some(100..20000), pos: Some(20000))] 196 | #[nwg_layout_item(layout: grid, row: 2, col: 3, col_span: 5)] 197 | #[nwg_events( 198 | // Unfortunately 'TrackBarUpdated' doesn't trigger with keyboard or 199 | // scroll, so we update on each change, even if during mouse drag 200 | // this might be spamming the device 201 | OnHorizontalScroll: [DeathAdderv2App::stage_dpi_selected(SELF)], 202 | )] 203 | bar_stagedpi: nwg::TrackBar, 204 | 205 | /* 206 | * Current DPI 207 | */ 208 | #[nwg_control(text: "Current DPI:", h_align: nwg::HTextAlign::Right, v_align: nwg::VTextAlign::Top)] 209 | #[nwg_layout_item(layout: grid, row: 3, col_span: 3)] 210 | lbl_currdpi: nwg::Label, 211 | 212 | #[nwg_control(range: Some(100..20000), pos: Some(20000))] 213 | #[nwg_layout_item(layout: grid, row: 3, col: 3, col_span: 5)] 214 | #[nwg_events( 215 | // Unfortunately 'TrackBarUpdated' doesn't trigger with keyboard or 216 | // scroll, so we update on each change, even if during mouse drag 217 | // this might be spamming the device 218 | OnHorizontalScroll: [DeathAdderv2App::current_dpi_selected(SELF)], 219 | )] 220 | bar_currdpi: nwg::TrackBar, 221 | 222 | #[nwg_control(text: "20000", h_align: nwg::HTextAlign::Left, v_align: nwg::VTextAlign::Top)] 223 | #[nwg_layout_item(layout: grid, row: 3, col: 8, col_span: 2)] 224 | txt_currdpi: nwg::Label, 225 | 226 | /* 227 | * Polling rate 228 | */ 229 | #[nwg_control(text: "Polling rate:", h_align: nwg::HTextAlign::Right, v_align: nwg::VTextAlign::Top)] 230 | #[nwg_layout_item(layout: grid, row: 4, col_span: 3)] 231 | lbl_pollrate: nwg::Label, 232 | 233 | #[nwg_control(collection: PollingRate::all(), v_align: nwg::VTextAlign::Top)] 234 | #[nwg_layout_item(layout: grid, row: 4, col: 3, col_span: 2)] 235 | #[nwg_events( OnComboxBoxSelection: [DeathAdderv2App::pollrate_selected(SELF)])] 236 | cmb_pollrate: nwg::ComboBox, 237 | 238 | /* 239 | * Logo color 240 | */ 241 | #[nwg_control(text: "Logo color:", h_align: nwg::HTextAlign::Right)] 242 | #[nwg_layout_item(layout: grid, row: 5, col_span: 3)] 243 | lbl_logocolor: nwg::Label, 244 | 245 | #[nwg_control(text: "", line_height: Some(20))] 246 | #[nwg_layout_item(layout: grid, row: 5, col: 3, col_span: 2)] 247 | #[nwg_events( 248 | MousePressLeftUp: [DeathAdderv2App::logo_color_clicked(SELF)], 249 | OnMouseMove: [DeathAdderv2App::set_cursor_hand(SELF)], 250 | )] 251 | btn_logocolor: nwg::RichLabel, 252 | 253 | /* 254 | * Scroll color 255 | */ 256 | #[nwg_control(text: "Scroll wheel color:", h_align: nwg::HTextAlign::Right)] 257 | #[nwg_layout_item(layout: grid, row: 6, col_span: 3)] 258 | lbl_scrollcolor: nwg::Label, 259 | 260 | #[nwg_control(text: "", line_height: Some(20))] 261 | #[nwg_layout_item(layout: grid, row: 6, col: 3, col_span: 2)] 262 | #[nwg_events( 263 | MousePressLeftUp: [DeathAdderv2App::scroll_color_clicked(SELF)], 264 | OnMouseMove: [DeathAdderv2App::set_cursor_hand(SELF)], 265 | )] 266 | btn_scrollcolor: nwg::RichLabel, 267 | 268 | #[nwg_control(text: "Same as logo")] 269 | #[nwg_layout_item(layout: grid, row: 6, col: 5, col_span: 3)] 270 | #[nwg_events( 271 | MousePressLeftUp: [DeathAdderv2App::same_color_changed(SELF, EVT, EVT_DATA)], 272 | OnKeyRelease: [DeathAdderv2App::same_color_changed(SELF, EVT, EVT_DATA)] 273 | )] 274 | chk_samecolor: nwg::CheckBox, 275 | 276 | /* 277 | * Logo brightness 278 | */ 279 | #[nwg_control(text: "Logo brightness:", h_align: nwg::HTextAlign::Right, v_align: nwg::VTextAlign::Top)] 280 | #[nwg_layout_item(layout: grid, row: 7, col_span: 3)] 281 | lbl_logobright: nwg::Label, 282 | 283 | #[nwg_control(range: Some(0..100), pos: Some(50))] 284 | #[nwg_layout_item(layout: grid, row: 7, col: 3, col_span: 4)] 285 | #[nwg_events( 286 | // Unfortunately 'TrackBarUpdated' doesn't trigger with keyboard or 287 | // scroll, so we update on each change, even if during mouse drag 288 | // this might be spamming the device 289 | OnHorizontalScroll: [DeathAdderv2App::logo_brightness_selected(SELF)], 290 | )] 291 | bar_logobright: nwg::TrackBar, 292 | 293 | #[nwg_control(text: "50", h_align: nwg::HTextAlign::Left, v_align: nwg::VTextAlign::Top)] 294 | #[nwg_layout_item(layout: grid, row: 7, col: 7)] 295 | txt_logobright: nwg::Label, 296 | 297 | /* 298 | * Scroll brightness 299 | */ 300 | #[nwg_control(text: "Scroll wheel brightness:", h_align: nwg::HTextAlign::Right, v_align: nwg::VTextAlign::Top)] 301 | #[nwg_layout_item(layout: grid, row: 8, col_span: 3)] 302 | lbl_scrollbright: nwg::Label, 303 | 304 | #[nwg_control(range: Some(0..100), pos: Some(50))] 305 | #[nwg_layout_item(layout: grid, row: 8, col: 3, col_span: 4)] 306 | #[nwg_events( 307 | // Unfortunately 'TrackBarUpdated' doesn't trigger with keyboard or 308 | // scroll, so we update on each change, even if during mouse drag 309 | // this might be spamming the device 310 | OnHorizontalScroll: [DeathAdderv2App::scroll_brightness_selected(SELF)], 311 | )] 312 | bar_scrollbright: nwg::TrackBar, 313 | 314 | #[nwg_control(text: "50", h_align: nwg::HTextAlign::Left, v_align: nwg::VTextAlign::Top)] 315 | #[nwg_layout_item(layout: grid, row: 8, col: 7)] 316 | txt_scrollbright: nwg::Label, 317 | 318 | /* 319 | * Same brightness check box 320 | */ 321 | #[nwg_control(text: "Same as logo")] 322 | #[nwg_layout_item(layout: grid, row: 8, col: 8, col_span: 3)] 323 | #[nwg_events( 324 | MousePressLeftUp: [DeathAdderv2App::same_brightness_changed(SELF, EVT, EVT_DATA)], 325 | OnKeyRelease: [DeathAdderv2App::same_brightness_changed(SELF, EVT, EVT_DATA)] 326 | )] 327 | chk_samebright: nwg::CheckBox, 328 | 329 | /* 330 | * Events coming from the device 331 | */ 332 | #[nwg_control] 333 | #[nwg_events(OnNotice: [DeathAdderv2App::update_dpi_selection])] 334 | dev_dpi_notice: nwg::Notice, 335 | dev_dpi_thread: RefCell>>>, 336 | dev_dpi_keepalive: RefCell>>, 337 | 338 | /* 339 | * Other members 340 | */ 341 | device: RefCell>, 342 | config: RefCell, 343 | ui_events_enabled: RefCell, 344 | } 345 | 346 | impl DeathAdderv2App { 347 | /// Sugar to avoid typing self.device.borrow().as_ref().map 348 | /// Note: will not execute if device is None 349 | fn with_device(&self, dav2: F) -> Option 350 | where 351 | F: FnOnce(&DeathAdderV2) -> U, 352 | { 353 | self.device.borrow().as_ref().map(dav2) 354 | } 355 | 356 | /// Borrow config and apply closure 357 | fn with_config(&self, cfg_cb: F) -> U 358 | where 359 | F: FnOnce(&Config) -> U, 360 | { 361 | let cfg = self.config.borrow(); 362 | cfg_cb(&cfg) 363 | } 364 | 365 | /// Borrow mutable config and apply closure 366 | fn with_mut_config(&self, cfg_cb: F) -> U 367 | where 368 | F: FnOnce(&mut Config) -> U, 369 | { 370 | let mut cfg = self.config.borrow_mut(); 371 | cfg_cb(&mut (*cfg)) 372 | } 373 | 374 | fn rad_dpistages(&self) -> Vec<&nwg::RadioButton> { 375 | vec![&self.par_stages.rad_dpi_1, 376 | &self.par_stages.rad_dpi_2, 377 | &self.par_stages.rad_dpi_3, 378 | &self.par_stages.rad_dpi_4, 379 | &self.par_stages.rad_dpi_5] 380 | } 381 | 382 | fn set_device_controls_enabled(&self, enabled: bool) { 383 | self.frm_stages.set_enabled(enabled); 384 | self.cmb_numstages.set_enabled(enabled); 385 | self.bar_stagedpi.set_enabled(enabled); 386 | self.bar_currdpi.set_enabled(enabled); 387 | self.cmb_pollrate.set_enabled(enabled); 388 | self.chk_samecolor.set_enabled(enabled); 389 | self.bar_logobright.set_enabled(enabled); 390 | self.bar_scrollbright.set_enabled(enabled); 391 | self.chk_samebright.set_enabled(enabled); 392 | } 393 | 394 | // mainly called by the device DPI listener 395 | fn update_dpi_selection(&self) { 396 | if !*self.ui_events_enabled.borrow() { 397 | return; 398 | } 399 | 400 | // we will be modifying controls here; some of them fire 'change' 401 | // events while we do so; we don't want that here 402 | self.ui_events_enabled.replace(false); 403 | 404 | self.with_device(|dav2| { 405 | match dav2.get_dpi_stages() { 406 | Ok((dpi_stages, current)) => { 407 | let rad_stages = self.rad_dpistages(); 408 | let ui_current = rad_stages.iter().position(|&rad| 409 | rad.check_state() == RadioButtonState::Checked 410 | ).unwrap_or(100); 411 | 412 | // assume no other app is changing the stages in parallel 413 | // in other words: only interested in device DPI 414 | // button-triggered events 415 | if ui_current == current as usize { 416 | return; 417 | } 418 | 419 | self.cmb_numstages.set_selection(Some(dpi_stages.len()-1)); 420 | let mut i = 0; 421 | let mut stages = dpi_stages.iter(); 422 | for rad in rad_stages { 423 | match stages.next() { 424 | Some(&(dpi, _)) => { 425 | rad.set_visible(true); 426 | rad.set_text(&dpi.to_string()); 427 | }, 428 | None => { 429 | rad.set_visible(false); 430 | }, 431 | } 432 | 433 | rad.set_check_state(if i == current { 434 | RadioButtonState::Checked 435 | } else { 436 | RadioButtonState::Unchecked 437 | }); 438 | i += 1; 439 | } 440 | 441 | if ui_current != current as usize { 442 | self.set_stage_dpi_ui(dpi_stages[current as usize].0 as usize); 443 | } 444 | }, 445 | Err(e) => { 446 | msgboxerror!("Failed to get DPI stages: {}", e); 447 | self.frm_stages.set_enabled(false); 448 | self.bar_stagedpi.set_enabled(false); 449 | } 450 | }; 451 | }); 452 | 453 | // re-enable events 454 | self.ui_events_enabled.replace(true); 455 | } 456 | 457 | fn update_ui_values(&self) { 458 | self.update_dpi_selection(); 459 | 460 | // we will be modifying controls here; some of them fire 'change' 461 | // events while we do so; we don't want that here 462 | let ui_events_enabled = self.ui_events_enabled.replace(false); 463 | 464 | self.set_device_controls_enabled(self.device.borrow().is_some()); 465 | 466 | match self.device.borrow().as_ref() { 467 | Some(dav2) => { 468 | 469 | match dav2.get_dpi() { 470 | Ok((dpi, _)) => self.bar_currdpi.set_pos(dpi as usize), 471 | Err(e) => { 472 | msgboxerror!("Failed to get current DPI: {}", e); 473 | self.bar_currdpi.set_enabled(false); 474 | } 475 | }; 476 | 477 | match dav2.get_poll_rate() { 478 | Ok(pollrate) => { 479 | let collection = self.cmb_pollrate.collection(); 480 | let index = collection.iter().position(|&p| p == pollrate); 481 | self.cmb_pollrate.set_selection(index); 482 | }, 483 | Err(e) => { 484 | msgboxerror!("Failed to get polling rate: {}", e); 485 | self.cmb_pollrate.set_enabled(false); 486 | } 487 | }; 488 | 489 | match dav2.get_logo_brightness() { 490 | Ok(b) => self.bar_logobright.set_pos(b as usize), 491 | Err(e) => { 492 | msgboxerror!("Failed to get logo brightness: {}", e); 493 | self.bar_logobright.set_enabled(false); 494 | } 495 | }; 496 | 497 | match dav2.get_scroll_brightness() { 498 | Ok(b) => self.bar_scrollbright.set_pos(b as usize), 499 | Err(e) => { 500 | msgboxerror!("Failed to get scroll whell brightness: {}", e); 501 | self.bar_scrollbright.set_enabled(false); 502 | } 503 | }; 504 | }, 505 | 506 | None => { // no device; set some defaults 507 | self.set_stage_dpi_ui(self.bar_stagedpi.range_min()); 508 | self.cmb_pollrate.set_selection(None); 509 | self.bar_logobright.set_pos(self.bar_logobright.range_min()); 510 | self.bar_scrollbright.set_pos(self.bar_scrollbright.range_min()); 511 | }, 512 | }; 513 | 514 | // updates that need to happen irrespective of the result 515 | self.txt_currdpi.set_text(&self.bar_currdpi.pos().to_string()); 516 | self.txt_logobright.set_text(&self.bar_logobright.pos().to_string()); 517 | self.txt_scrollbright.set_text(&self.bar_scrollbright.pos().to_string()); 518 | 519 | self.with_config(|cfg| { 520 | // can't take these from the device; assume they're what the config says 521 | self.set_logo_color(cfg.logo_color); 522 | self.set_scroll_color(cfg.scroll_color); 523 | self.set_same_color(cfg.same_color, true); 524 | self.set_same_brightness(cfg.same_brightness, true); 525 | }); 526 | 527 | // re-enable events 528 | self.ui_events_enabled.replace(ui_events_enabled); 529 | } 530 | 531 | fn spawn_dev_dpi_listener_thread(&self, dav2: &DeathAdderV2) { 532 | let vid = dav2.vid(); 533 | let pid = dav2.pid(); 534 | // wish we could use the serial to pick the specific device 535 | // but hidapi (or windows?) won't report the serial so i 536 | // don't have a way to match it; In any case, even if more than 537 | // one DeathAdderV2s are connected, it doesn't harm to get an 538 | // extra event here and there and make an extra update in the UI 539 | 540 | self.dev_dpi_keepalive.replace(Arc::new(Mutex::new(true))); 541 | let keepalive = Arc::clone(&self.dev_dpi_keepalive.borrow()); 542 | let sender = self.dev_dpi_notice.sender(); 543 | *self.dev_dpi_thread.borrow_mut() = Some(thread::spawn(move || { 544 | 545 | const REPORT_SIZE: usize = 16; 546 | 547 | // we will be filtering mutli-reporting of the same event 548 | let mut last_dev_noticed: Option<&HidDevice> = None; 549 | let mut last_buf_noticed = [0; REPORT_SIZE]; 550 | 551 | let api = HidApi::new()?; 552 | 553 | // and here we have another problem: DeathAdderV2 has 2 HID 554 | // devices with the exact same i/f num, usage and usage page 555 | // and i don't know how to distinguish between the 2 without 556 | // looking in the path, which is supposed to be opaque anyways; 557 | // the solution i chose is to open and listen on both of them 558 | // and split the reads and their timeout evenly among them; 559 | // if any of them reports a DPI change, we update the UI. In 560 | // theory, if there's many of them, it could add delay-to-read 561 | // but in practise it isn't noticeable 562 | let devinfos = api.device_list().filter(|d| { 563 | d.vendor_id() == vid && d.product_id() == pid && 564 | d.interface_number() == 1 && d.usage() == 0 && 565 | d.usage_page() == 1 566 | }); 567 | 568 | let devs = devinfos.filter_map(|devinfo| { 569 | devinfo.open_device(&api).ok() 570 | }).collect::>(); 571 | 572 | let timeout = (300 / devs.len()) as i32; 573 | loop { 574 | 575 | // find a device that reports a (new) DPI event 576 | let dpi_reporting_dev = devs.iter().find(|&dev| { 577 | let mut buf = [0; REPORT_SIZE]; 578 | match dev.read_timeout(&mut buf[..], timeout) { 579 | Ok(REPORT_SIZE) => { 580 | if buf[0] == 0x05 && buf[1] == 0x02 && ( 581 | last_dev_noticed.is_none() || 582 | !ptr::eq(last_dev_noticed.unwrap(), dev) || 583 | buf != last_buf_noticed 584 | ) { 585 | last_dev_noticed = Some(dev); 586 | last_buf_noticed = buf; 587 | return true; 588 | } 589 | false 590 | }, 591 | _ => false, 592 | } 593 | }); 594 | 595 | let keepalive_lock = keepalive.lock(); 596 | if !*keepalive_lock.unwrap() { 597 | // signaled to stop; prob another device selected 598 | return Ok(()); 599 | } 600 | 601 | if dpi_reporting_dev.is_some() { 602 | sender.notice(); 603 | } 604 | } // end of main thread loop 605 | })); // actual end of thread 606 | } 607 | 608 | fn device_selected(&self) { 609 | // block any previous DPI threads before changing the current device 610 | let prev_keepalive_ref = self.dev_dpi_keepalive.borrow(); 611 | let prev_keepalive_mutex = prev_keepalive_ref.as_ref(); 612 | let prev_keepalive_lock = prev_keepalive_mutex.lock(); 613 | 614 | // attempt to open the newly selected device (using DeathAdderV2::from(..)) 615 | let collection = self.cmb_device.collection(); 616 | let dev = self.cmb_device.selection().and_then(|i| collection.get(i)); 617 | let dav2 = dev.and_then(|d| { 618 | match DeathAdderV2::from(d) { 619 | Ok(d) => Some(d), 620 | Err(e) => { 621 | msgboxerror!("Error opening device: {}", e); 622 | None 623 | } 624 | } 625 | }); 626 | 627 | // update the UI accordingly 628 | self.device.replace(dav2); 629 | self.update_ui_values(); 630 | 631 | // join the previous thread 632 | let prev_thread = self.dev_dpi_thread.take(); 633 | prev_thread.map(|thread| { 634 | *prev_keepalive_lock.unwrap() = false; 635 | _ = thread.join(); 636 | }); 637 | 638 | // drop these to allow for self.dev_dpi_keepalive.replace below 639 | drop(prev_keepalive_mutex); 640 | drop(prev_keepalive_ref); 641 | 642 | // if we opened a new device, start a new listener thread 643 | self.with_device(|dav2| { 644 | self.spawn_dev_dpi_listener_thread(dav2); 645 | }); 646 | } 647 | 648 | fn numstages_selected(&self) { 649 | if !*self.ui_events_enabled.borrow() { 650 | return; 651 | } 652 | 653 | _ = self.cmb_numstages.selection().and_then(|index| { 654 | let num_stages = index + 1; 655 | let rad_stages = self.rad_dpistages(); 656 | let mut stages: Vec<(u16, u16)> = Vec::new(); 657 | let mut i = 0; 658 | let mut current = 0; 659 | for &rad_stage in rad_stages.iter() { 660 | if i < num_stages { 661 | rad_stage.set_visible(true); 662 | let dpi = rad_stage.text().parse::().unwrap(); 663 | stages.push((dpi, dpi)); 664 | if rad_stage.check_state() == RadioButtonState::Checked { 665 | current = i; 666 | } 667 | } else { 668 | rad_stage.set_visible(false); 669 | if rad_stage.check_state() == RadioButtonState::Checked { 670 | rad_stage.set_check_state(RadioButtonState::Unchecked); 671 | current = num_stages - 1; 672 | } 673 | } 674 | 675 | i += 1; 676 | } 677 | 678 | rad_stages[current].set_check_state(RadioButtonState::Checked); 679 | self.set_stage_dpi_ui(stages.get(current).unwrap().0 as usize); 680 | self.with_device(|dav2| dav2.set_dpi_stages(&stages, current as u8)) 681 | }); 682 | } 683 | 684 | fn stage_selected(&self) { 685 | if !*self.ui_events_enabled.borrow() { 686 | return; 687 | } 688 | 689 | let rad_stages = self.rad_dpistages(); 690 | let mut stages: Vec<(u16, u16)> = Vec::new(); 691 | let mut current: u8 = 0; 692 | let mut i = 0; 693 | for rad_stage in rad_stages { 694 | if !rad_stage.visible() { 695 | break; 696 | } 697 | 698 | let dpi = rad_stage.text().parse::().unwrap(); 699 | stages.push((dpi, dpi)); 700 | if rad_stage.check_state() == RadioButtonState::Checked { 701 | current = i; 702 | } 703 | 704 | i += 1; 705 | } 706 | 707 | self.set_stage_dpi_ui(stages.get(current as usize).unwrap().0 as usize); 708 | self.with_device(|dav2| dav2.set_dpi_stages(&stages, current)); 709 | } 710 | 711 | fn stage_dpi_selected(&self) { 712 | if !*self.ui_events_enabled.borrow() { 713 | return; 714 | } 715 | 716 | let rad_stages = self.rad_dpistages(); 717 | let mut stages: Vec<(u16, u16)> = Vec::new(); 718 | let mut current = 0; 719 | let mut i = 0; 720 | for rad_stage in rad_stages { 721 | if !rad_stage.visible() { 722 | break; 723 | } 724 | 725 | if rad_stage.check_state() == RadioButtonState::Checked { 726 | current = i; 727 | let dpi = self.bar_stagedpi.pos() as u16; 728 | rad_stage.set_text(&dpi.to_string()); 729 | stages.push((dpi, dpi)); 730 | } else { 731 | let dpi = rad_stage.text().parse::().unwrap(); 732 | stages.push((dpi, dpi)); 733 | } 734 | 735 | i += 1; 736 | } 737 | 738 | self.set_current_dpi_ui(self.bar_stagedpi.pos()); 739 | self.with_device(|dav2| dav2.set_dpi_stages(&stages, current)); 740 | } 741 | 742 | fn set_stage_dpi_ui(&self, dpi: usize) { 743 | let ui_events_enabled = self.ui_events_enabled.replace(false); 744 | self.bar_stagedpi.set_pos(dpi); 745 | 746 | // update this since the device will be returning as current 747 | // DPI the one we set through the stages API 748 | self.set_current_dpi_ui(self.bar_stagedpi.pos()); 749 | self.ui_events_enabled.replace(ui_events_enabled); 750 | } 751 | 752 | fn current_dpi_selected(&self) { 753 | if !*self.ui_events_enabled.borrow() { 754 | return; 755 | } 756 | 757 | let dpi = self.bar_currdpi.pos() as u16; 758 | self.txt_currdpi.set_text(&self.bar_currdpi.pos().to_string()); 759 | self.with_device(|dav2| dav2.set_dpi(dpi, dpi)); 760 | } 761 | 762 | fn set_current_dpi_ui(&self, dpi: usize) { 763 | let ui_events_enabled = self.ui_events_enabled.replace(false); 764 | self.bar_currdpi.set_pos(dpi); 765 | self.txt_currdpi.set_text(&self.bar_currdpi.pos().to_string()); 766 | self.ui_events_enabled.replace(ui_events_enabled); 767 | } 768 | 769 | fn pollrate_selected(&self) { 770 | if !*self.ui_events_enabled.borrow() { 771 | return; 772 | } 773 | 774 | let collection = self.cmb_pollrate.collection(); 775 | self.cmb_pollrate.selection() 776 | .and_then(|i| collection.get(i)) 777 | .map(|&pollrate| { 778 | self.with_device(|dav2| dav2.set_poll_rate(pollrate)); 779 | }); 780 | } 781 | 782 | fn set_cursor_hand(&self) { 783 | let lpcursorname = match self.device.borrow().as_ref() { 784 | Some(_) => IDC_HAND, 785 | None => IDC_ARROW, 786 | }; 787 | 788 | unsafe { 789 | _ = LoadCursorW(HINSTANCE(0), lpcursorname) 790 | .map(|cursor| SetCursor(cursor)); 791 | } 792 | } 793 | 794 | fn logo_color_clicked(&self) { 795 | if !*self.ui_events_enabled.borrow() { 796 | return; 797 | } 798 | 799 | self.with_mut_config(|cfg| { 800 | self.with_device(|dav2| { 801 | 802 | // dav2 here must outlive dialog and therefore change_cb 803 | let mut dialog = ColorDialog::new(); 804 | 805 | // ColorDialog arguments 806 | let parent = HWND(self.window.handle.hwnd().unwrap() as isize); 807 | let init_logo = Some(cfg.logo_color); 808 | let init_scroll = cfg.scroll_color; 809 | let same_color = cfg.same_color; 810 | let change_cb = Some(move |_: &ColorDialog, &color: &RGB8| { 811 | _ = dav2.preview_static( 812 | color, if same_color { color } else { init_scroll }); 813 | }); 814 | 815 | // show the dialog and choose what to apply (either initial or new) 816 | let color = match dialog.show(parent, init_logo, change_cb) { 817 | Some(chosen_color) => chosen_color, 818 | None => cfg.logo_color, 819 | }; 820 | 821 | // set the color 822 | cfg.logo_color = color; 823 | self.set_logo_color(color); 824 | if same_color { 825 | self.set_scroll_color(color); 826 | } 827 | 828 | }); // <- dialog, change_cb dropped here 829 | }); 830 | } 831 | 832 | fn logo_color(&self) -> RGB8 { 833 | self.with_config(|cfg| cfg.logo_color) 834 | } 835 | 836 | /// Does not update the config 837 | fn set_logo_color(&self, color: RGB8) { 838 | self.with_device(|dav2| dav2.set_logo_color(color)); 839 | self.btn_logocolor.set_background_color(color.into()); 840 | } 841 | 842 | fn scroll_color_clicked(&self) { 843 | if !*self.ui_events_enabled.borrow() { 844 | return; 845 | } 846 | 847 | self.with_mut_config(|cfg| { 848 | self.with_device(|dav2| { 849 | 850 | // dav2 here must outlive dialog and therefore change_cb 851 | let mut dialog = ColorDialog::new(); 852 | 853 | // ColorDialog arguments 854 | let parent = HWND(self.window.handle.hwnd().unwrap() as isize); 855 | let logo_color = cfg.logo_color; 856 | let init_scroll = Some(if cfg.same_color { 857 | cfg.logo_color 858 | } else { 859 | cfg.scroll_color 860 | }); 861 | let change_cb = Some(move |_: &ColorDialog, &color: &RGB8| { 862 | _ = dav2.preview_static(logo_color, color); 863 | }); 864 | 865 | // show the dialog and choose what to apply (either initial or new) 866 | let color = match dialog.show(parent, init_scroll, change_cb) { 867 | Some(chosen_color) => { 868 | // if the user pressed ok, we no longer use same colors 869 | cfg.same_color = false; 870 | self.chk_samecolor.set_check_state(to_check_state!(false)); 871 | cfg.scroll_color = chosen_color; 872 | chosen_color 873 | }, 874 | None => { 875 | // if the user pressed cancel, revert (nothing to save in cfg) 876 | if cfg.same_color { 877 | logo_color 878 | } else { 879 | cfg.scroll_color 880 | } 881 | }, 882 | }; 883 | 884 | // set the color 885 | self.set_scroll_color(color); 886 | 887 | }); // <- dialog, change_cb dropped here 888 | }); 889 | } 890 | 891 | fn scroll_color(&self) -> RGB8 { 892 | self.with_config(|cfg| cfg.scroll_color) 893 | } 894 | 895 | /// Does not update the config 896 | fn set_scroll_color(&self, color: RGB8) { 897 | self.with_device(|dav2| dav2.set_scroll_color(color)); 898 | self.btn_scrollcolor.set_background_color(color.into()); 899 | } 900 | 901 | fn same_color_changed(&self, evt: nwg::Event, evtdata: &nwg::EventData) { 902 | if !*self.ui_events_enabled.borrow() { 903 | return; 904 | } 905 | 906 | // only interested in space key 907 | if evt == nwg::Event::OnKeyRelease && evtdata.on_key() != 32u32 { 908 | return 909 | } 910 | 911 | // unfortunately there is no 'state_changed' event so we get the 912 | // mouse up and space key events which trigger before the state 913 | // has actually changed so we negate it to get what will become 914 | 915 | let same = !from_check_state!(self.chk_samecolor.check_state()); 916 | self.set_same_color(same, false); 917 | self.with_mut_config(|cfg| cfg.same_color = same); 918 | } 919 | 920 | /// Does not update the config 921 | fn set_same_color(&self, same: bool, update_ui: bool) { 922 | if update_ui { 923 | self.chk_samecolor.set_check_state(to_check_state!(same)); 924 | } 925 | if same { 926 | self.set_scroll_color(self.logo_color()); 927 | } else { 928 | self.set_scroll_color(self.scroll_color()); 929 | } 930 | } 931 | 932 | fn logo_brightness_selected(&self) { 933 | if !*self.ui_events_enabled.borrow() { 934 | return; 935 | } 936 | 937 | let brightness = self.bar_logobright.pos() as u8; 938 | self.txt_logobright.set_text(&brightness.to_string()); 939 | self.with_device(|dav2| dav2.set_logo_brightness(brightness)); 940 | self.with_config(|cfg| if cfg.same_brightness { 941 | self.set_scroll_brightness(brightness as usize); 942 | }); 943 | } 944 | 945 | fn scroll_brightness_selected(&self) { 946 | if !*self.ui_events_enabled.borrow() { 947 | return; 948 | } 949 | 950 | let brightness = self.bar_scrollbright.pos(); 951 | self.txt_scrollbright.set_text(&brightness.to_string()); 952 | self.with_device(|dav2| dav2.set_scroll_brightness(brightness as u8)); 953 | } 954 | 955 | /// Does not update the config 956 | fn set_scroll_brightness(&self, brightness: usize) { 957 | self.ui_events_enabled.replace(false); 958 | self.txt_scrollbright.set_text(&brightness.to_string()); 959 | self.bar_scrollbright.set_pos(brightness); 960 | self.with_device(|dav2| dav2.set_scroll_brightness(brightness as u8)); 961 | self.ui_events_enabled.replace(true); 962 | } 963 | 964 | fn same_brightness_changed(&self, evt: nwg::Event, evtdata: &nwg::EventData) { 965 | if !*self.ui_events_enabled.borrow() { 966 | return; 967 | } 968 | 969 | // only interested in space key 970 | if evt == nwg::Event::OnKeyRelease && evtdata.on_key() != 32u32 { 971 | return 972 | } 973 | 974 | // unfortunately there is no 'state_changed' event so we get the 975 | // mouse up and space key events which trigger before the state 976 | // has actually changed so we negate it to get what will become 977 | 978 | let same = !from_check_state!(self.chk_samebright.check_state()); 979 | self.set_same_brightness(same, false); 980 | self.with_mut_config(|cfg| cfg.same_brightness = same); 981 | } 982 | 983 | /// Does not update the config 984 | fn set_same_brightness(&self, same: bool, update_ui: bool) { 985 | if update_ui { 986 | self.chk_samebright.set_check_state(to_check_state!(same)); 987 | } 988 | 989 | self.bar_scrollbright.set_enabled(!same); 990 | 991 | if same { 992 | self.set_scroll_brightness(self.bar_logobright.pos()); 993 | } else { 994 | self.with_device(|dav2| match dav2.get_scroll_brightness() { 995 | Ok(brightness) => self.set_scroll_brightness(brightness as usize), 996 | Err(_) => () 997 | }); 998 | } 999 | } 1000 | 1001 | fn window_close(&self) { 1002 | // signal the thread to stop, if any 1003 | let prev_keepalive_ref = self.dev_dpi_keepalive.borrow(); 1004 | let prev_keepalive_mutex = prev_keepalive_ref.as_ref(); 1005 | *prev_keepalive_mutex.lock().unwrap() = false; 1006 | 1007 | _ = self.with_config(|cfg| cfg.save()).map_err(|e|{ 1008 | msgboxerror!("Failed to save config: {}", e); 1009 | }); 1010 | 1011 | // join the previous thread 1012 | self.dev_dpi_thread.take().map(|thread| { 1013 | _ = thread.join(); 1014 | }); 1015 | 1016 | nwg::stop_thread_dispatch(); 1017 | } 1018 | } 1019 | 1020 | fn main() { 1021 | _ = nwg::init().map_err( 1022 | |e| msgboxpanic!("Failed to init Native Windows GUI: {}", e)); 1023 | _ = nwg::Font::set_global_family("Segoe UI").map_err( 1024 | |e| dbglog!("Failed to set default font: {}", e)); 1025 | 1026 | let app = DeathAdderv2App::build_ui(Default::default()) 1027 | .unwrap_or_else(|e| msgboxpanic!("Failed to build UI: {}", e)); 1028 | 1029 | app.ui_events_enabled.replace(true); 1030 | app.config.replace(Config::load().unwrap_or(Config::default())); 1031 | 1032 | // default to false and if a valid device is selected they will be enabled 1033 | app.set_device_controls_enabled(false); 1034 | 1035 | // configure a few things on the trackbars 1036 | configure_trackbar(&app.bar_stagedpi, 1, 1000, 1000); 1037 | configure_trackbar(&app.bar_currdpi, 1, 1000, 1000); 1038 | configure_trackbar(&app.bar_logobright, 1, 5, 5); 1039 | configure_trackbar(&app.bar_scrollbright, 1, 5, 5); 1040 | 1041 | // v_align some controls that nwg does provide the option 1042 | add_style(&app.chk_samebright.handle, BS_TOP); 1043 | for rad_stage in app.rad_dpistages() { 1044 | add_style(&rad_stage.handle, BS_TOP); 1045 | } 1046 | 1047 | // set the minimum window size 1048 | _ = nwg::bind_raw_event_handler(&app.window.handle, 0x10000, |_hwnd, msg, _w, l| { 1049 | match msg { 1050 | WM_GETMINMAXINFO => { 1051 | let minmax_ptr = l as *mut MINMAXINFO; 1052 | unsafe { 1053 | let mut minmax = &mut minmax_ptr.read(); 1054 | minmax.ptMinTrackSize.x = 710; 1055 | minmax.ptMinTrackSize.y = 405; 1056 | minmax_ptr.write(*minmax); 1057 | } 1058 | }, 1059 | _ => {} 1060 | } 1061 | None 1062 | }); 1063 | 1064 | let available_devices = DeathAdderV2::list().unwrap_or_else( 1065 | |e| msgboxpanic!("Error querying DeathAdder v2 devices: {}", e) 1066 | ); 1067 | 1068 | app.cmb_device.set_collection(available_devices); 1069 | // if only 1, select it by default and show appropriate error if failed to open 1070 | if app.cmb_device.len() == 1 { 1071 | app.cmb_device.set_selection(Some(0)); 1072 | app.device_selected(); 1073 | } 1074 | nwg::dispatch_thread_events(); 1075 | } 1076 | --------------------------------------------------------------------------------