1pub mod upstream;
8
9use std::{
10 collections::{BTreeMap, BTreeSet},
11 fs, io,
12 path::{Path, PathBuf},
13};
14
15use razers_types::{ConnectionId, DeviceId, PersistenceScope, SupportStatus};
16use serde::Deserialize;
17use thiserror::Error;
18
19pub const SUPPORTED_SCHEMA_VERSION: u32 = 1;
20
21#[derive(Clone, Debug, Deserialize)]
22#[serde(deny_unknown_fields)]
23pub struct DeviceDescriptor {
24 pub schema_version: u32,
25 pub id: DeviceId,
26 pub display_name: String,
27 pub kind: DeviceKind,
28 pub support: SupportDescriptor,
29 pub connections: Vec<ConnectionDescriptor>,
30 pub capabilities: Capabilities,
31 #[serde(default)]
32 pub evidence: Vec<Evidence>,
33 #[serde(default)]
34 pub verification: Vec<Verification>,
35}
36
37#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
38#[serde(rename_all = "kebab-case")]
39pub enum DeviceKind {
40 Mouse,
41 Keyboard,
42 Headset,
43 Speaker,
44 MouseMat,
45 Laptop,
46 Receiver,
47 Accessory,
48}
49
50#[derive(Clone, Debug, Deserialize)]
51#[serde(deny_unknown_fields)]
52pub struct SupportDescriptor {
53 pub status: SupportStatus,
54 pub notes: String,
55}
56
57#[derive(Clone, Debug, Deserialize)]
58#[serde(deny_unknown_fields)]
59pub struct ConnectionDescriptor {
60 pub id: ConnectionId,
61 pub role: String,
62 pub transport: TransportKind,
63 #[serde(rename = "match")]
64 pub identity: MatchDescriptor,
65 pub protocol: ProtocolDescriptor,
66}
67
68#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
69#[serde(rename_all = "kebab-case")]
70pub enum TransportKind {
71 UsbHidFeature,
72 UsbHidOutput,
73 BleGatt,
74 OsAudio,
75}
76
77#[derive(Clone, Debug, Deserialize)]
78#[serde(deny_unknown_fields)]
79pub struct MatchDescriptor {
80 pub vid: u16,
81 pub pid: u16,
82 pub usage_page: Option<u16>,
83 pub usage: Option<u16>,
84 pub interface_number: Option<u8>,
85}
86
87impl MatchDescriptor {
88 pub fn matches_hid(
92 &self,
93 vendor_id: u16,
94 product_id: u16,
95 usage_page: u16,
96 usage: u16,
97 interface_number: i32,
98 ) -> bool {
99 self.vid == vendor_id
100 && self.pid == product_id
101 && self
102 .usage_page
103 .is_none_or(|expected| expected == usage_page)
104 && self.usage.is_none_or(|expected| expected == usage)
105 && self
106 .interface_number
107 .is_none_or(|expected| i32::from(expected) == interface_number)
108 }
109}
110
111#[derive(Clone, Debug, Deserialize)]
112#[serde(deny_unknown_fields)]
113pub struct ProtocolDescriptor {
114 pub family: String,
115 pub report_id: u8,
116 pub transaction_id: u8,
117 pub response_delay_us: u64,
118 pub busy_retries: u8,
119 #[serde(default)]
120 pub quirks: ProtocolQuirks,
121}
122
123#[derive(Clone, Debug, Default, Deserialize)]
124#[serde(default, deny_unknown_fields)]
125pub struct ProtocolQuirks {
126 pub include_report_id_in_payload: bool,
127 pub validate_response_crc: bool,
128 pub validate_command_echo: bool,
129}
130
131#[derive(Clone, Debug, Default, Deserialize)]
132#[serde(default, deny_unknown_fields)]
133pub struct Capabilities {
134 pub dpi: Option<DpiCapability>,
135 pub polling_rate: Option<PollingRateCapability>,
136 pub lighting: Option<LightingCapability>,
137 pub battery: Option<BatteryCapability>,
138}
139
140impl Capabilities {
141 pub fn count(&self) -> usize {
142 [
143 self.dpi.is_some(),
144 self.polling_rate.is_some(),
145 self.lighting.is_some(),
146 self.battery.is_some(),
147 ]
148 .into_iter()
149 .filter(|present| *present)
150 .count()
151 }
152
153 pub fn names(&self) -> impl Iterator<Item = &'static str> {
154 [
155 self.dpi.as_ref().map(|_| "dpi"),
156 self.polling_rate.as_ref().map(|_| "polling-rate"),
157 self.lighting.as_ref().map(|_| "lighting"),
158 self.battery.as_ref().map(|_| "battery"),
159 ]
160 .into_iter()
161 .flatten()
162 }
163}
164
165#[derive(Clone, Debug, Deserialize)]
166#[serde(deny_unknown_fields)]
167pub struct DpiCapability {
168 pub status: SupportStatus,
169 pub driver: String,
170 pub minimum: u32,
171 pub maximum: u32,
172 pub step: u32,
173 pub axes: DpiAxes,
174 #[serde(default)]
175 pub persistence: Vec<PersistenceScope>,
176}
177
178#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
179#[serde(rename_all = "kebab-case")]
180pub enum DpiAxes {
181 Single,
182 Xy,
183}
184
185#[derive(Clone, Debug, Deserialize)]
186#[serde(deny_unknown_fields)]
187pub struct PollingRateCapability {
188 pub status: SupportStatus,
189 pub driver: String,
190 #[serde(default)]
191 pub values_hz: Vec<u32>,
192 #[serde(default)]
193 pub persistence: Vec<PersistenceScope>,
194}
195
196#[derive(Clone, Debug, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct LightingCapability {
199 pub status: SupportStatus,
200 pub driver: String,
201 pub rows: u16,
202 pub columns: u16,
203 pub effects: Vec<String>,
204 #[serde(default)]
205 pub zones: Vec<LightingZone>,
206 #[serde(default)]
207 pub persistence: Vec<PersistenceScope>,
208}
209
210#[derive(Clone, Debug, Deserialize)]
211#[serde(deny_unknown_fields)]
212pub struct LightingZone {
213 pub id: String,
214 pub protocol_led_id: u8,
215}
216
217#[derive(Clone, Debug, Deserialize)]
218#[serde(deny_unknown_fields)]
219pub struct BatteryCapability {
220 pub status: SupportStatus,
221 pub driver: String,
222 pub read_only: bool,
223}
224
225#[derive(Clone, Debug, Deserialize)]
226#[serde(deny_unknown_fields)]
227pub struct Evidence {
228 pub source: String,
229 pub repository: String,
230 pub commit: String,
231 pub path: String,
232 pub symbol: String,
233 pub license: String,
234}
235
236#[derive(Clone, Debug, Deserialize)]
237#[serde(deny_unknown_fields)]
238pub struct Verification {
239 pub platform: String,
240 pub firmware: String,
241 pub result: VerificationResult,
242 #[serde(default)]
243 pub capabilities: Vec<String>,
244 pub notes: String,
245}
246
247#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
248#[serde(rename_all = "kebab-case")]
249pub enum VerificationResult {
250 Passed,
251 Partial,
252 Failed,
253}
254
255#[derive(Clone, Debug)]
256pub struct Registry {
257 devices: BTreeMap<DeviceId, LoadedDevice>,
258}
259
260#[derive(Clone, Debug)]
261pub struct LoadedDevice {
262 pub source_path: PathBuf,
263 pub descriptor: DeviceDescriptor,
264}
265
266impl Registry {
267 pub fn load_dir(path: impl AsRef<Path>) -> Result<Self, RegistryError> {
268 let path = path.as_ref();
269 let mut manifest_paths = fs::read_dir(path)
270 .map_err(|source| RegistryError::Io {
271 path: path.to_path_buf(),
272 source,
273 })?
274 .map(|entry| {
275 entry
276 .map(|entry| entry.path())
277 .map_err(|source| RegistryError::Io {
278 path: path.to_path_buf(),
279 source,
280 })
281 })
282 .collect::<Result<Vec<_>, _>>()?;
283 manifest_paths.retain(|path| {
284 path.extension()
285 .is_some_and(|extension| extension == "toml")
286 });
287 manifest_paths.sort();
288
289 let mut devices = BTreeMap::new();
290 for source_path in manifest_paths {
291 let source = fs::read_to_string(&source_path).map_err(|source| RegistryError::Io {
292 path: source_path.clone(),
293 source,
294 })?;
295 let descriptor = parse_manifest(&source, &source_path)?;
296 let id = descriptor.id.clone();
297 if let Some(previous) = devices.insert(
298 id.clone(),
299 LoadedDevice {
300 source_path: source_path.clone(),
301 descriptor,
302 },
303 ) {
304 return Err(RegistryError::DuplicateDevice {
305 id,
306 first: previous.source_path,
307 second: source_path,
308 });
309 }
310 }
311
312 Ok(Self { devices })
313 }
314
315 pub fn len(&self) -> usize {
316 self.devices.len()
317 }
318
319 pub fn is_empty(&self) -> bool {
320 self.devices.is_empty()
321 }
322
323 pub fn iter(&self) -> impl Iterator<Item = &LoadedDevice> {
324 self.devices.values()
325 }
326
327 pub fn get(&self, id: &DeviceId) -> Option<&LoadedDevice> {
328 self.devices.get(id)
329 }
330}
331
332pub fn parse_manifest(
333 source: &str,
334 source_path: impl AsRef<Path>,
335) -> Result<DeviceDescriptor, RegistryError> {
336 let source_path = source_path.as_ref();
337 let descriptor: DeviceDescriptor =
338 toml::from_str(source).map_err(|source| RegistryError::Parse {
339 path: source_path.to_path_buf(),
340 source,
341 })?;
342 let problems = validate(&descriptor);
343 if problems.is_empty() {
344 Ok(descriptor)
345 } else {
346 Err(RegistryError::Validation {
347 path: source_path.to_path_buf(),
348 problems,
349 })
350 }
351}
352
353pub fn validate(descriptor: &DeviceDescriptor) -> Vec<String> {
354 let mut problems = Vec::new();
355
356 if descriptor.schema_version != SUPPORTED_SCHEMA_VERSION {
357 problems.push(format!(
358 "schema_version must be {SUPPORTED_SCHEMA_VERSION}, found {}",
359 descriptor.schema_version
360 ));
361 }
362 if descriptor.display_name.trim().is_empty() {
363 problems.push("display_name must not be empty".into());
364 }
365 if descriptor.support.notes.trim().is_empty() {
366 problems.push("support.notes must explain the current support state".into());
367 }
368 if descriptor.connections.is_empty() {
369 problems.push("at least one connection is required".into());
370 }
371 if descriptor.capabilities.count() == 0 {
372 problems.push("at least one capability is required".into());
373 }
374 if descriptor.evidence.is_empty() {
375 problems.push("at least one pinned evidence source is required".into());
376 }
377 if descriptor.support.status == SupportStatus::Verified && descriptor.verification.is_empty() {
378 problems.push("verified devices require at least one verification record".into());
379 }
380
381 let mut connection_ids = BTreeSet::new();
382 for connection in &descriptor.connections {
383 if !connection_ids.insert(connection.id.clone()) {
384 problems.push(format!("duplicate connection id '{}'", connection.id));
385 }
386 if connection.role.trim().is_empty() {
387 problems.push(format!(
388 "connection '{}': role must not be empty",
389 connection.id
390 ));
391 }
392 if connection.identity.vid == 0 || connection.identity.pid == 0 {
393 problems.push(format!(
394 "connection '{}': VID and PID must be non-zero",
395 connection.id
396 ));
397 }
398 if connection.protocol.family.trim().is_empty() {
399 problems.push(format!(
400 "connection '{}': protocol family must not be empty",
401 connection.id
402 ));
403 }
404 if connection.protocol.response_delay_us > 10_000_000 {
405 problems.push(format!(
406 "connection '{}': response_delay_us exceeds the 10 second safety limit",
407 connection.id
408 ));
409 }
410 if connection.protocol.busy_retries > 20 {
411 problems.push(format!(
412 "connection '{}': busy_retries exceeds the limit of 20",
413 connection.id
414 ));
415 }
416 }
417
418 if let Some(dpi) = &descriptor.capabilities.dpi {
419 if dpi.minimum == 0 || dpi.minimum > dpi.maximum {
420 problems.push("capabilities.dpi must have 0 < minimum <= maximum".into());
421 }
422 if dpi.step == 0 {
423 problems.push("capabilities.dpi.step must be non-zero".into());
424 }
425 if dpi.driver.trim().is_empty() {
426 problems.push("capabilities.dpi.driver must not be empty".into());
427 }
428 }
429
430 if let Some(polling_rate) = &descriptor.capabilities.polling_rate {
431 if polling_rate.driver.trim().is_empty() {
432 problems.push("capabilities.polling_rate.driver must not be empty".into());
433 }
434 if polling_rate.values_hz.contains(&0) {
435 problems.push("capabilities.polling_rate.values_hz must not contain zero".into());
436 }
437 let unique = polling_rate
438 .values_hz
439 .iter()
440 .copied()
441 .collect::<BTreeSet<_>>();
442 if unique.len() != polling_rate.values_hz.len() {
443 problems.push("capabilities.polling_rate.values_hz contains duplicates".into());
444 }
445 }
446
447 if let Some(lighting) = &descriptor.capabilities.lighting {
448 if lighting.driver.trim().is_empty() {
449 problems.push("capabilities.lighting.driver must not be empty".into());
450 }
451 if lighting.rows == 0 || lighting.columns == 0 {
452 problems.push("capabilities.lighting dimensions must be non-zero".into());
453 }
454 if lighting.effects.is_empty() {
455 problems.push("capabilities.lighting.effects must not be empty".into());
456 }
457 let mut zone_ids = BTreeSet::new();
458 for zone in &lighting.zones {
459 if zone.id.trim().is_empty() {
460 problems.push("lighting zone id must not be empty".into());
461 } else if !zone_ids.insert(&zone.id) {
462 problems.push(format!("duplicate lighting zone id '{}'", zone.id));
463 }
464 }
465 }
466
467 if let Some(battery) = &descriptor.capabilities.battery {
468 if battery.driver.trim().is_empty() {
469 problems.push("capabilities.battery.driver must not be empty".into());
470 }
471 }
472
473 for evidence in &descriptor.evidence {
474 if evidence.commit.len() != 40
475 || !evidence.commit.bytes().all(|byte| byte.is_ascii_hexdigit())
476 {
477 problems.push(format!(
478 "evidence source '{}': commit must be a full 40-character Git SHA",
479 evidence.source
480 ));
481 }
482 if !evidence.repository.contains('/') || evidence.repository.contains("://") {
483 problems.push(format!(
484 "evidence source '{}': repository must use owner/name form",
485 evidence.source
486 ));
487 }
488 if evidence.path.trim().is_empty()
489 || evidence.symbol.trim().is_empty()
490 || evidence.license.trim().is_empty()
491 {
492 problems.push(format!(
493 "evidence source '{}': path, symbol, and license are required",
494 evidence.source
495 ));
496 }
497 }
498
499 problems
500}
501
502#[derive(Debug, Error)]
503pub enum RegistryError {
504 #[error("unable to read '{}': {source}", path.display())]
505 Io {
506 path: PathBuf,
507 #[source]
508 source: io::Error,
509 },
510 #[error("unable to parse '{}': {source}", path.display())]
511 Parse {
512 path: PathBuf,
513 #[source]
514 source: toml::de::Error,
515 },
516 #[error("invalid device manifest '{}': {}", path.display(), problems.join("; "))]
517 Validation {
518 path: PathBuf,
519 problems: Vec<String>,
520 },
521 #[error("device '{id}' is declared by both '{}' and '{}'", first.display(), second.display())]
522 DuplicateDevice {
523 id: DeviceId,
524 first: PathBuf,
525 second: PathBuf,
526 },
527}
528
529#[cfg(test)]
530mod tests {
531 use super::*;
532
533 const VALID: &str = r#"
534schema_version = 1
535id = "razer.test-device"
536display_name = "Razer Test Device"
537kind = "mouse"
538
539[support]
540status = "detected"
541notes = "Schema test only."
542
543[[connections]]
544id = "wired"
545role = "control"
546transport = "usb-hid-feature"
547
548[connections.match]
549vid = 5426
550pid = 1
551
552[connections.protocol]
553family = "razer-report-90"
554report_id = 0
555transaction_id = 0
556response_delay_us = 600
557busy_retries = 5
558
559[capabilities.dpi]
560status = "experimental"
561driver = "dpi-u16-xy"
562minimum = 100
563maximum = 1000
564step = 50
565axes = "xy"
566
567[[evidence]]
568source = "test"
569repository = "owner/repository"
570commit = "0123456789abcdef0123456789abcdef01234567"
571path = "tests/device.toml"
572symbol = "test"
573license = "GPL-2.0-or-later"
574"#;
575
576 #[test]
577 fn parses_and_validates_a_manifest() {
578 let descriptor = parse_manifest(VALID, "test.toml").unwrap();
579 assert_eq!(descriptor.id.as_str(), "razer.test-device");
580 assert_eq!(descriptor.capabilities.count(), 1);
581 }
582
583 #[test]
584 fn reports_multiple_semantic_problems() {
585 let invalid = VALID
586 .replace("schema_version = 1", "schema_version = 2")
587 .replace("minimum = 100", "minimum = 2000");
588
589 let RegistryError::Validation { problems, .. } =
590 parse_manifest(&invalid, "invalid.toml").unwrap_err()
591 else {
592 panic!("expected validation failure")
593 };
594 assert!(
595 problems
596 .iter()
597 .any(|problem| problem.contains("schema_version"))
598 );
599 assert!(problems.iter().any(|problem| problem.contains("minimum")));
600 }
601
602 #[test]
603 fn matches_only_the_declared_hid_interface_constraints() {
604 let identity = MatchDescriptor {
605 vid: 0x1532,
606 pid: 0x0099,
607 usage_page: Some(0xff00),
608 usage: None,
609 interface_number: Some(2),
610 };
611
612 assert!(identity.matches_hid(0x1532, 0x0099, 0xff00, 1, 2));
613 assert!(!identity.matches_hid(0x1532, 0x0099, 0x0001, 1, 2));
614 assert!(!identity.matches_hid(0x1532, 0x0099, 0xff00, 1, 1));
615 assert!(!identity.matches_hid(0x1234, 0x0099, 0xff00, 1, 2));
616 }
617}