Skip to main content

razers_device_registry/
upstream.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2
3//! Read-only, source-derived device facts that are not RazeRS support claims.
4//!
5//! 来自上游源码的只读设备事实,不等同于 RazeRS 的支持承诺。
6
7use std::{
8    collections::BTreeSet,
9    fs, io,
10    path::{Path, PathBuf},
11};
12
13use serde::Deserialize;
14use thiserror::Error;
15
16pub const SUPPORTED_UPSTREAM_SCHEMA_VERSION: u32 = 1;
17
18#[derive(Clone, Debug, Deserialize)]
19#[serde(deny_unknown_fields)]
20pub struct UpstreamCatalog {
21    pub schema_version: u32,
22    pub source: UpstreamSource,
23    pub devices: Vec<UpstreamDevice>,
24}
25
26#[derive(Clone, Debug, Deserialize)]
27#[serde(deny_unknown_fields)]
28pub struct UpstreamSource {
29    pub name: String,
30    pub repository: String,
31    pub commit: String,
32    pub path: String,
33    pub license: String,
34    pub generated_by: String,
35}
36
37#[derive(Clone, Debug, Deserialize)]
38#[serde(deny_unknown_fields)]
39pub struct UpstreamDevice {
40    pub name: String,
41    pub kind: UpstreamDeviceKind,
42    pub vid: u16,
43    pub pid: u16,
44    pub source_path: String,
45    pub source_symbol: String,
46    #[serde(default)]
47    pub upstream_features: Vec<UpstreamFeature>,
48    #[serde(default)]
49    pub methods: Vec<String>,
50    pub matrix: Option<[u16; 2]>,
51    pub max_dpi: Option<u32>,
52    #[serde(default)]
53    pub poll_rates_hz: Vec<u32>,
54}
55
56#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
57#[serde(rename_all = "kebab-case")]
58pub enum UpstreamDeviceKind {
59    Accessory,
60    Core,
61    Headset,
62    Keyboard,
63    Keypad,
64    Monitor,
65    Mouse,
66    MouseMat,
67}
68
69impl UpstreamDeviceKind {
70    pub const fn as_str(self) -> &'static str {
71        match self {
72            Self::Accessory => "accessory",
73            Self::Core => "core",
74            Self::Headset => "headset",
75            Self::Keyboard => "keyboard",
76            Self::Keypad => "keypad",
77            Self::Monitor => "monitor",
78            Self::Mouse => "mouse",
79            Self::MouseMat => "mouse-mat",
80        }
81    }
82}
83
84#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
85#[serde(rename_all = "kebab-case")]
86pub enum UpstreamFeature {
87    Battery,
88    Dpi,
89    GameMode,
90    Identity,
91    Layout,
92    Lighting,
93    Macro,
94    PollingRate,
95    ScrollMode,
96}
97
98impl UpstreamFeature {
99    pub const fn as_str(self) -> &'static str {
100        match self {
101            Self::Battery => "battery",
102            Self::Dpi => "dpi",
103            Self::GameMode => "game-mode",
104            Self::Identity => "identity",
105            Self::Layout => "layout",
106            Self::Lighting => "lighting",
107            Self::Macro => "macro",
108            Self::PollingRate => "polling-rate",
109            Self::ScrollMode => "scroll-mode",
110        }
111    }
112}
113
114pub const SUPPORTED_OPENRGB_SCHEMA_VERSION: u32 = 1;
115
116#[derive(Clone, Debug, Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct OpenRgbCatalog {
119    pub schema_version: u32,
120    pub source: UpstreamSource,
121    pub devices: Vec<OpenRgbDevice>,
122}
123
124#[derive(Clone, Debug, Deserialize)]
125#[serde(deny_unknown_fields)]
126pub struct OpenRgbDevice {
127    pub name: String,
128    pub kind: OpenRgbDeviceKind,
129    pub vid: u16,
130    pub pid: u16,
131    pub pid_symbol: String,
132    pub source_path: String,
133    pub source_symbol: String,
134    pub matrix_family: MatrixFamily,
135    pub transaction_id: u8,
136    pub matrix: [u16; 2],
137    #[serde(default)]
138    pub zones: Vec<String>,
139    pub layout: Option<String>,
140}
141
142#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
143#[serde(rename_all = "kebab-case")]
144pub enum OpenRgbDeviceKind {
145    Accessory,
146    Cooler,
147    Gpu,
148    Headset,
149    HeadsetStand,
150    Keyboard,
151    Keypad,
152    Laptop,
153    LedStrip,
154    Light,
155    Microphone,
156    Mouse,
157    MouseMat,
158    Speaker,
159}
160
161impl OpenRgbDeviceKind {
162    pub const fn as_str(self) -> &'static str {
163        match self {
164            Self::Accessory => "accessory",
165            Self::Cooler => "cooler",
166            Self::Gpu => "gpu",
167            Self::Headset => "headset",
168            Self::HeadsetStand => "headset-stand",
169            Self::Keyboard => "keyboard",
170            Self::Keypad => "keypad",
171            Self::Laptop => "laptop",
172            Self::LedStrip => "led-strip",
173            Self::Light => "light",
174            Self::Microphone => "microphone",
175            Self::Mouse => "mouse",
176            Self::MouseMat => "mouse-mat",
177            Self::Speaker => "speaker",
178        }
179    }
180}
181
182#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
183#[serde(rename_all = "kebab-case")]
184pub enum MatrixFamily {
185    Custom,
186    Extended,
187    ExtendedArgb,
188    Linear,
189    None,
190    Standard,
191}
192
193impl MatrixFamily {
194    pub const fn as_str(self) -> &'static str {
195        match self {
196            Self::Custom => "custom",
197            Self::Extended => "extended",
198            Self::ExtendedArgb => "extended-argb",
199            Self::Linear => "linear",
200            Self::None => "none",
201            Self::Standard => "standard",
202        }
203    }
204}
205
206#[derive(Clone, Copy, Debug, Eq, PartialEq)]
207pub struct CatalogComparison {
208    pub overlap: usize,
209    pub openrazer_only: usize,
210    pub openrgb_only: usize,
211    pub name_differences: usize,
212    pub matrix_differences: usize,
213}
214
215pub const SUPPORTED_IRAZER_SCHEMA_VERSION: u32 = 1;
216
217#[derive(Clone, Debug, Deserialize)]
218#[serde(deny_unknown_fields)]
219pub struct IrazerCatalog {
220    pub schema_version: u32,
221    pub source: UpstreamSource,
222    pub devices: Vec<IrazerDevice>,
223}
224
225#[derive(Clone, Debug, Deserialize)]
226#[serde(deny_unknown_fields)]
227pub struct IrazerDevice {
228    pub source_id: String,
229    pub name: String,
230    pub kind: OpenRgbDeviceKind,
231    pub vid: u16,
232    pub pid: u16,
233    pub upstream_support: UpstreamSupportClaim,
234    #[serde(default)]
235    pub capability_labels: Vec<String>,
236    pub matrix_family: MatrixFamily,
237    pub transaction_id: u8,
238    pub source_path: String,
239    pub source_symbol: String,
240}
241
242#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
243#[serde(rename_all = "kebab-case")]
244pub enum UpstreamSupportClaim {
245    Experimental,
246    Planned,
247    Supported,
248}
249
250impl UpstreamSupportClaim {
251    pub const fn as_str(self) -> &'static str {
252        match self {
253            Self::Experimental => "experimental",
254            Self::Planned => "planned",
255            Self::Supported => "supported",
256        }
257    }
258}
259
260/// One upstream implementation contributing facts about a USB identity.
261///
262/// 为某个 USB 标识提供事实的一个上游实现。
263#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
264pub enum EvidenceSource {
265    OpenRazer,
266    OpenRgb,
267    Irazer,
268}
269
270impl EvidenceSource {
271    pub const fn as_str(self) -> &'static str {
272        match self {
273            Self::OpenRazer => "OpenRazer",
274            Self::OpenRgb => "OpenRGB",
275            Self::Irazer => "iRazer",
276        }
277    }
278}
279
280/// Whether independent sources can be compared for one fact and agree on it.
281///
282/// 独立来源对某项事实是否可比、是否一致。
283#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
284pub enum EvidenceAgreement {
285    NotComparable,
286    Agree,
287    Disagree,
288}
289
290impl EvidenceAgreement {
291    pub const fn as_str(self) -> &'static str {
292        match self {
293            Self::NotComparable => "not-comparable",
294            Self::Agree => "agree",
295            Self::Disagree => "disagree",
296        }
297    }
298}
299
300/// Review readiness derived from source coverage and recorded disagreements.
301///
302/// This is a research aid, not an automatic support or live-I/O decision.
303///
304/// 按来源覆盖与已记录差异评估研究就绪程度;仅辅助研究,不自动决定设备支持或实时读写权限。
305#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
306pub enum EvidenceReadiness {
307    Corroborated,
308    NeedsResearch,
309    SingleSource,
310}
311
312impl EvidenceReadiness {
313    pub const fn as_str(self) -> &'static str {
314        match self {
315            Self::Corroborated => "corroborated",
316            Self::NeedsResearch => "needs-research",
317            Self::SingleSource => "single-source",
318        }
319    }
320}
321
322/// Field-level assessment for one USB identity across all imported catalogs.
323///
324/// 跨所有已导入目录,对某个 USB 标识做字段级评估。
325#[derive(Clone, Debug, Eq, PartialEq)]
326pub struct EvidenceAssessment {
327    pub vid: u16,
328    pub pid: u16,
329    pub sources: Vec<EvidenceSource>,
330    pub name_agreement: EvidenceAgreement,
331    pub kind_agreement: EvidenceAgreement,
332    pub matrix_agreement: EvidenceAgreement,
333    pub protocol_agreement: EvidenceAgreement,
334    pub readiness: EvidenceReadiness,
335    pub openrazer_features: Vec<UpstreamFeature>,
336    pub irazer_support: Option<UpstreamSupportClaim>,
337}
338
339/// Reconcile source coverage without silently selecting any disputed value.
340///
341/// 核对来源覆盖情况,不会擅自选择有争议的值。
342pub fn assess_evidence(
343    openrazer: &UpstreamCatalog,
344    openrgb: &OpenRgbCatalog,
345    irazer: &IrazerCatalog,
346) -> Vec<EvidenceAssessment> {
347    let identities = openrazer
348        .devices
349        .iter()
350        .map(|device| (device.vid, device.pid))
351        .chain(
352            openrgb
353                .devices
354                .iter()
355                .map(|device| (device.vid, device.pid)),
356        )
357        .chain(irazer.devices.iter().map(|device| (device.vid, device.pid)))
358        .collect::<BTreeSet<_>>();
359
360    identities
361        .into_iter()
362        .map(|(vid, pid)| {
363            let openrazer_device = openrazer.find_usb(vid, pid);
364            let openrgb_device = openrgb.find_usb(vid, pid);
365            let irazer_device = irazer.find_usb(vid, pid);
366
367            let mut sources = Vec::new();
368            if openrazer_device.is_some() {
369                sources.push(EvidenceSource::OpenRazer);
370            }
371            if openrgb_device.is_some() {
372                sources.push(EvidenceSource::OpenRgb);
373            }
374            if irazer_device.is_some() {
375                sources.push(EvidenceSource::Irazer);
376            }
377
378            let names = openrazer_device
379                .map(|device| device.name.as_str())
380                .into_iter()
381                .chain(openrgb_device.map(|device| device.name.as_str()))
382                .chain(irazer_device.map(|device| device.name.as_str()))
383                .collect::<Vec<_>>();
384            let kinds = openrazer_device
385                .map(|device| device.kind.as_str())
386                .into_iter()
387                .chain(openrgb_device.map(|device| device.kind.as_str()))
388                .chain(irazer_device.map(|device| device.kind.as_str()))
389                .collect::<Vec<_>>();
390
391            let matrix_agreement = match (
392                openrazer_device.and_then(|device| device.matrix),
393                openrgb_device.map(|device| device.matrix),
394            ) {
395                (Some(left), Some(right)) if left == right => EvidenceAgreement::Agree,
396                (Some(_), Some(_)) => EvidenceAgreement::Disagree,
397                _ => EvidenceAgreement::NotComparable,
398            };
399            let protocol_agreement = match (openrgb_device, irazer_device) {
400                (Some(left), Some(right))
401                    if left.matrix_family == right.matrix_family
402                        && left.transaction_id == right.transaction_id =>
403                {
404                    EvidenceAgreement::Agree
405                }
406                (Some(_), Some(_)) => EvidenceAgreement::Disagree,
407                _ => EvidenceAgreement::NotComparable,
408            };
409            let name_agreement = string_agreement(&names, true);
410            let kind_agreement = string_agreement(&kinds, false);
411            let has_material_disagreement = [kind_agreement, matrix_agreement, protocol_agreement]
412                .contains(&EvidenceAgreement::Disagree);
413            let readiness = if has_material_disagreement {
414                EvidenceReadiness::NeedsResearch
415            } else if sources.len() >= 2 {
416                EvidenceReadiness::Corroborated
417            } else {
418                EvidenceReadiness::SingleSource
419            };
420
421            EvidenceAssessment {
422                vid,
423                pid,
424                sources,
425                name_agreement,
426                kind_agreement,
427                matrix_agreement,
428                protocol_agreement,
429                readiness,
430                openrazer_features: openrazer_device
431                    .map(|device| device.upstream_features.clone())
432                    .unwrap_or_default(),
433                irazer_support: irazer_device.map(|device| device.upstream_support),
434            }
435        })
436        .collect()
437}
438
439fn string_agreement(values: &[&str], case_insensitive: bool) -> EvidenceAgreement {
440    let Some((first, rest)) = values.split_first() else {
441        return EvidenceAgreement::NotComparable;
442    };
443    if rest.is_empty() {
444        return EvidenceAgreement::NotComparable;
445    }
446    let agrees = rest.iter().all(|value| {
447        if case_insensitive {
448            first.eq_ignore_ascii_case(value)
449        } else {
450            first == value
451        }
452    });
453    if agrees {
454        EvidenceAgreement::Agree
455    } else {
456        EvidenceAgreement::Disagree
457    }
458}
459
460impl UpstreamCatalog {
461    pub fn load_file(path: impl AsRef<Path>) -> Result<Self, UpstreamCatalogError> {
462        let path = path.as_ref();
463        let source = fs::read_to_string(path).map_err(|source| UpstreamCatalogError::Io {
464            path: path.to_path_buf(),
465            source,
466        })?;
467        let catalog: Self =
468            toml::from_str(&source).map_err(|source| UpstreamCatalogError::Parse {
469                path: path.to_path_buf(),
470                source,
471            })?;
472        let problems = catalog.validate();
473        if problems.is_empty() {
474            Ok(catalog)
475        } else {
476            Err(UpstreamCatalogError::Validation {
477                path: path.to_path_buf(),
478                problems,
479            })
480        }
481    }
482
483    pub fn validate(&self) -> Vec<String> {
484        let mut problems = Vec::new();
485        if self.schema_version != SUPPORTED_UPSTREAM_SCHEMA_VERSION {
486            problems.push(format!(
487                "schema_version must be {SUPPORTED_UPSTREAM_SCHEMA_VERSION}, found {}",
488                self.schema_version
489            ));
490        }
491        if self.source.name.trim().is_empty()
492            || self.source.path.trim().is_empty()
493            || self.source.license.trim().is_empty()
494            || self.source.generated_by.trim().is_empty()
495        {
496            problems.push("source name, path, license, and generated_by are required".into());
497        }
498        if !valid_repository(&self.source.repository) {
499            problems.push("source repository must use owner/name form".into());
500        }
501        if !valid_commit(&self.source.commit) {
502            problems.push("source commit must be a full 40-character Git SHA".into());
503        }
504        if self.devices.is_empty() {
505            problems.push("catalog must contain at least one device".into());
506        }
507
508        let mut identities = BTreeSet::new();
509        for device in &self.devices {
510            let identity = (device.vid, device.pid);
511            if !identities.insert(identity) {
512                problems.push(format!(
513                    "duplicate USB identity {:04x}:{:04x}",
514                    device.vid, device.pid
515                ));
516            }
517            if device.name.trim().is_empty() || device.source_symbol.trim().is_empty() {
518                problems.push(format!(
519                    "device {:04x}:{:04x} requires a name and source_symbol",
520                    device.vid, device.pid
521                ));
522            }
523            if device.vid == 0 || device.pid == 0 {
524                problems.push(format!(
525                    "device '{}': VID and PID must be non-zero",
526                    device.name
527                ));
528            }
529            if !device.source_path.starts_with(&self.source.path)
530                || !device.source_path.ends_with(".py")
531            {
532                problems.push(format!(
533                    "device '{}': source_path must be a Python file below the source root",
534                    device.name
535                ));
536            }
537            if device.methods.is_empty() {
538                problems.push(format!(
539                    "device '{}': at least one upstream method is required",
540                    device.name
541                ));
542            }
543            if let Some([rows, columns]) = device.matrix {
544                if rows == 0 || columns == 0 {
545                    problems.push(format!(
546                        "device '{}': matrix dimensions must be non-zero",
547                        device.name
548                    ));
549                }
550            }
551            if device.max_dpi == Some(0) {
552                problems.push(format!(
553                    "device '{}': max_dpi must be non-zero",
554                    device.name
555                ));
556            }
557            if device.poll_rates_hz.contains(&0) {
558                problems.push(format!(
559                    "device '{}': poll_rates_hz must not contain zero",
560                    device.name
561                ));
562            }
563            let unique_rates = device
564                .poll_rates_hz
565                .iter()
566                .copied()
567                .collect::<BTreeSet<_>>();
568            if unique_rates.len() != device.poll_rates_hz.len() {
569                problems.push(format!(
570                    "device '{}': poll_rates_hz contains duplicates",
571                    device.name
572                ));
573            }
574        }
575        problems
576    }
577
578    pub fn find_usb(&self, vid: u16, pid: u16) -> Option<&UpstreamDevice> {
579        self.devices
580            .iter()
581            .find(|device| device.vid == vid && device.pid == pid)
582    }
583
584    pub fn compare_openrgb(&self, openrgb: &OpenRgbCatalog) -> CatalogComparison {
585        let openrazer_identities = self
586            .devices
587            .iter()
588            .map(|device| ((device.vid, device.pid), device))
589            .collect::<std::collections::BTreeMap<_, _>>();
590        let openrgb_identities = openrgb
591            .devices
592            .iter()
593            .map(|device| ((device.vid, device.pid), device))
594            .collect::<std::collections::BTreeMap<_, _>>();
595        let overlap = openrazer_identities
596            .keys()
597            .filter(|identity| openrgb_identities.contains_key(identity))
598            .count();
599        let name_differences = openrazer_identities
600            .iter()
601            .filter_map(|(identity, openrazer)| {
602                openrgb_identities
603                    .get(identity)
604                    .map(|openrgb| (*openrazer, *openrgb))
605            })
606            .filter(|(openrazer, openrgb)| !openrazer.name.eq_ignore_ascii_case(&openrgb.name))
607            .count();
608        let matrix_differences = openrazer_identities
609            .iter()
610            .filter_map(|(identity, openrazer)| {
611                openrgb_identities
612                    .get(identity)
613                    .map(|openrgb| (*openrazer, *openrgb))
614            })
615            .filter(|(openrazer, openrgb)| {
616                openrazer
617                    .matrix
618                    .is_some_and(|matrix| matrix != openrgb.matrix)
619            })
620            .count();
621
622        CatalogComparison {
623            overlap,
624            openrazer_only: openrazer_identities.len() - overlap,
625            openrgb_only: openrgb_identities.len() - overlap,
626            name_differences,
627            matrix_differences,
628        }
629    }
630}
631
632impl OpenRgbCatalog {
633    pub fn load_file(path: impl AsRef<Path>) -> Result<Self, OpenRgbCatalogError> {
634        let path = path.as_ref();
635        let source = fs::read_to_string(path).map_err(|source| OpenRgbCatalogError::Io {
636            path: path.to_path_buf(),
637            source,
638        })?;
639        let catalog: Self =
640            toml::from_str(&source).map_err(|source| OpenRgbCatalogError::Parse {
641                path: path.to_path_buf(),
642                source,
643            })?;
644        let problems = catalog.validate();
645        if problems.is_empty() {
646            Ok(catalog)
647        } else {
648            Err(OpenRgbCatalogError::Validation {
649                path: path.to_path_buf(),
650                problems,
651            })
652        }
653    }
654
655    pub fn validate(&self) -> Vec<String> {
656        let mut problems = Vec::new();
657        if self.schema_version != SUPPORTED_OPENRGB_SCHEMA_VERSION {
658            problems.push(format!(
659                "schema_version must be {SUPPORTED_OPENRGB_SCHEMA_VERSION}, found {}",
660                self.schema_version
661            ));
662        }
663        validate_source(&self.source, &mut problems);
664        if self.devices.is_empty() {
665            problems.push("catalog must contain at least one device".into());
666        }
667
668        let source_root = Path::new(&self.source.path);
669        let mut identities = BTreeSet::new();
670        for device in &self.devices {
671            if !identities.insert((device.vid, device.pid)) {
672                problems.push(format!(
673                    "duplicate USB identity {:04x}:{:04x}",
674                    device.vid, device.pid
675                ));
676            }
677            if device.vid == 0 || device.pid == 0 {
678                problems.push(format!(
679                    "device '{}': VID and PID must be non-zero",
680                    device.name
681                ));
682            }
683            if device.name.trim().is_empty()
684                || device.pid_symbol.trim().is_empty()
685                || device.source_symbol.trim().is_empty()
686            {
687                problems.push(format!(
688                    "device {:04x}:{:04x} requires name, pid_symbol, and source_symbol",
689                    device.vid, device.pid
690                ));
691            }
692            let source_path = Path::new(&device.source_path);
693            if source_path.is_absolute()
694                || !source_path.starts_with(source_root)
695                || source_path
696                    .extension()
697                    .is_none_or(|extension| extension != "cpp")
698            {
699                problems.push(format!(
700                    "device '{}': source_path must be a C++ file below the source root",
701                    device.name
702                ));
703            }
704            if device.matrix.contains(&0) {
705                problems.push(format!(
706                    "device '{}': matrix dimensions must be non-zero",
707                    device.name
708                ));
709            }
710            let unique_zones = device.zones.iter().collect::<BTreeSet<_>>();
711            if unique_zones.len() != device.zones.len() {
712                problems.push(format!(
713                    "device '{}': zones contains duplicates",
714                    device.name
715                ));
716            }
717        }
718        problems
719    }
720
721    pub fn find_usb(&self, vid: u16, pid: u16) -> Option<&OpenRgbDevice> {
722        self.devices
723            .iter()
724            .find(|device| device.vid == vid && device.pid == pid)
725    }
726}
727
728impl IrazerCatalog {
729    pub fn load_file(path: impl AsRef<Path>) -> Result<Self, IrazerCatalogError> {
730        let path = path.as_ref();
731        let source = fs::read_to_string(path).map_err(|source| IrazerCatalogError::Io {
732            path: path.to_path_buf(),
733            source,
734        })?;
735        let catalog: Self =
736            toml::from_str(&source).map_err(|source| IrazerCatalogError::Parse {
737                path: path.to_path_buf(),
738                source,
739            })?;
740        let problems = catalog.validate();
741        if problems.is_empty() {
742            Ok(catalog)
743        } else {
744            Err(IrazerCatalogError::Validation {
745                path: path.to_path_buf(),
746                problems,
747            })
748        }
749    }
750
751    pub fn validate(&self) -> Vec<String> {
752        let mut problems = Vec::new();
753        if self.schema_version != SUPPORTED_IRAZER_SCHEMA_VERSION {
754            problems.push(format!(
755                "schema_version must be {SUPPORTED_IRAZER_SCHEMA_VERSION}, found {}",
756                self.schema_version
757            ));
758        }
759        validate_source(&self.source, &mut problems);
760        if self.devices.is_empty() {
761            problems.push("catalog must contain at least one device".into());
762        }
763
764        let source_root = Path::new(&self.source.path);
765        let mut identities = BTreeSet::new();
766        let mut source_ids = BTreeSet::new();
767        for device in &self.devices {
768            if !identities.insert((device.vid, device.pid)) {
769                problems.push(format!(
770                    "duplicate USB identity {:04x}:{:04x}",
771                    device.vid, device.pid
772                ));
773            }
774            if !source_ids.insert(device.source_id.as_str()) {
775                problems.push(format!("duplicate source_id '{}'", device.source_id));
776            }
777            if device.vid == 0 || device.pid == 0 {
778                problems.push(format!(
779                    "device '{}': VID and PID must be non-zero",
780                    device.name
781                ));
782            }
783            if device.name.trim().is_empty()
784                || device.source_id.trim().is_empty()
785                || device.source_symbol.trim().is_empty()
786            {
787                problems.push(format!(
788                    "device {:04x}:{:04x} requires name, source_id, and source_symbol",
789                    device.vid, device.pid
790                ));
791            }
792            let source_path = Path::new(&device.source_path);
793            if source_path.is_absolute()
794                || !source_path.starts_with(source_root)
795                || source_path
796                    .extension()
797                    .is_none_or(|extension| extension != "swift")
798            {
799                problems.push(format!(
800                    "device '{}': source_path must be a Swift file below the source root",
801                    device.name
802                ));
803            }
804            if device.capability_labels.is_empty() {
805                problems.push(format!(
806                    "device '{}': capability_labels must not be empty",
807                    device.name
808                ));
809            }
810            let unique_labels = device
811                .capability_labels
812                .iter()
813                .map(String::as_str)
814                .collect::<BTreeSet<_>>();
815            if unique_labels.len() != device.capability_labels.len() {
816                problems.push(format!(
817                    "device '{}': capability_labels contains duplicates",
818                    device.name
819                ));
820            }
821        }
822        problems
823    }
824
825    pub fn find_usb(&self, vid: u16, pid: u16) -> Option<&IrazerDevice> {
826        self.devices
827            .iter()
828            .find(|device| device.vid == vid && device.pid == pid)
829    }
830}
831
832fn validate_source(source: &UpstreamSource, problems: &mut Vec<String>) {
833    if source.name.trim().is_empty()
834        || source.path.trim().is_empty()
835        || source.license.trim().is_empty()
836        || source.generated_by.trim().is_empty()
837    {
838        problems.push("source name, path, license, and generated_by are required".into());
839    }
840    if !valid_repository(&source.repository) {
841        problems.push("source repository must use owner/name form".into());
842    }
843    if !valid_commit(&source.commit) {
844        problems.push("source commit must be a full 40-character Git SHA".into());
845    }
846}
847
848fn valid_commit(commit: &str) -> bool {
849    commit.len() == 40 && commit.bytes().all(|byte| byte.is_ascii_hexdigit())
850}
851
852fn valid_repository(repository: &str) -> bool {
853    repository.contains('/') && !repository.contains("://")
854}
855
856#[derive(Debug, Error)]
857pub enum UpstreamCatalogError {
858    #[error("unable to read '{}': {source}", path.display())]
859    Io {
860        path: PathBuf,
861        #[source]
862        source: io::Error,
863    },
864    #[error("unable to parse '{}': {source}", path.display())]
865    Parse {
866        path: PathBuf,
867        #[source]
868        source: toml::de::Error,
869    },
870    #[error("invalid upstream catalog '{}': {}", path.display(), problems.join("; "))]
871    Validation {
872        path: PathBuf,
873        problems: Vec<String>,
874    },
875}
876
877#[derive(Debug, Error)]
878pub enum OpenRgbCatalogError {
879    #[error("unable to read '{}': {source}", path.display())]
880    Io {
881        path: PathBuf,
882        #[source]
883        source: io::Error,
884    },
885    #[error("unable to parse '{}': {source}", path.display())]
886    Parse {
887        path: PathBuf,
888        #[source]
889        source: toml::de::Error,
890    },
891    #[error("invalid OpenRGB catalog '{}': {}", path.display(), problems.join("; "))]
892    Validation {
893        path: PathBuf,
894        problems: Vec<String>,
895    },
896}
897
898#[derive(Debug, Error)]
899pub enum IrazerCatalogError {
900    #[error("unable to read '{}': {source}", path.display())]
901    Io {
902        path: PathBuf,
903        #[source]
904        source: io::Error,
905    },
906    #[error("unable to parse '{}': {source}", path.display())]
907    Parse {
908        path: PathBuf,
909        #[source]
910        source: toml::de::Error,
911    },
912    #[error("invalid iRazer catalog '{}': {}", path.display(), problems.join("; "))]
913    Validation {
914        path: PathBuf,
915        problems: Vec<String>,
916    },
917}
918
919#[cfg(test)]
920mod tests {
921    use super::*;
922
923    const VALID: &str = r#"
924schema_version = 1
925
926[source]
927name = "OpenRazer"
928repository = "openrazer/openrazer"
929commit = "0123456789abcdef0123456789abcdef01234567"
930path = "daemon/openrazer_daemon/hardware"
931license = "GPL-2.0-or-later"
932generated_by = "tools/import_openrazer.py"
933
934[[devices]]
935name = "Razer Test Mouse"
936kind = "mouse"
937vid = 0x1532
938pid = 0x0001
939source_path = "daemon/openrazer_daemon/hardware/mouse.py"
940source_symbol = "RazerTestMouse"
941upstream_features = ["identity", "dpi"]
942methods = ["get_device_type_mouse", "get_dpi_xy"]
943max_dpi = 16000
944matrix = [1, 2]
945"#;
946
947    const OPENRGB_VALID: &str = r#"
948schema_version = 1
949
950[source]
951name = "OpenRGB"
952repository = "owner/openrgb"
953commit = "0123456789abcdef0123456789abcdef01234567"
954path = "Controllers/RazerController"
955license = "GPL-2.0-or-later"
956generated_by = "tools/import_openrgb.py"
957
958[[devices]]
959name = "Razer Differently Named Mouse"
960kind = "mouse"
961vid = 0x1532
962pid = 0x0001
963pid_symbol = "RAZER_TEST_MOUSE_PID"
964source_path = "Controllers/RazerController/RazerDevices.cpp"
965source_symbol = "test_mouse_device"
966matrix_family = "extended"
967transaction_id = 0x1f
968matrix = [1, 2]
969zones = ["test_mouse_zone"]
970"#;
971
972    const IRAZER_VALID: &str = r#"
973schema_version = 1
974
975[source]
976name = "iRazer"
977repository = "owner/irazer"
978commit = "0123456789abcdef0123456789abcdef01234567"
979path = "Sources/iRazer"
980license = "MIT"
981generated_by = "tools/import_irazer.py"
982
983[[devices]]
984source_id = "test-mouse"
985name = "Razer Test Mouse"
986kind = "mouse"
987vid = 0x1532
988pid = 0x0001
989upstream_support = "supported"
990capability_labels = ["Lighting"]
991matrix_family = "extended"
992transaction_id = 0x1f
993source_path = "Sources/iRazer/DeviceCatalog.swift"
994source_symbol = "DeviceCatalog.all:test-mouse"
995"#;
996
997    #[test]
998    fn parses_and_matches_a_catalog_entry() {
999        let catalog: UpstreamCatalog = toml::from_str(VALID).unwrap();
1000        assert!(catalog.validate().is_empty());
1001        assert_eq!(
1002            catalog.find_usb(0x1532, 0x0001).unwrap().name,
1003            "Razer Test Mouse"
1004        );
1005    }
1006
1007    #[test]
1008    fn rejects_duplicate_usb_identities() {
1009        let source = format!(
1010            "{VALID}\n[[devices]]{}",
1011            VALID.split("[[devices]]").nth(1).unwrap()
1012        );
1013        let catalog: UpstreamCatalog = toml::from_str(&source).unwrap();
1014        assert!(
1015            catalog
1016                .validate()
1017                .iter()
1018                .any(|problem| problem.contains("duplicate USB identity"))
1019        );
1020    }
1021
1022    #[test]
1023    fn compares_overlapping_catalogs_without_merging_disagreements() {
1024        let openrazer: UpstreamCatalog = toml::from_str(VALID).unwrap();
1025        let openrgb: OpenRgbCatalog = toml::from_str(OPENRGB_VALID).unwrap();
1026
1027        assert!(openrgb.validate().is_empty());
1028        assert_eq!(
1029            openrazer.compare_openrgb(&openrgb),
1030            CatalogComparison {
1031                overlap: 1,
1032                openrazer_only: 0,
1033                openrgb_only: 0,
1034                name_differences: 1,
1035                matrix_differences: 0,
1036            }
1037        );
1038    }
1039
1040    #[test]
1041    fn corroborates_identity_and_matching_protocol_facts_across_catalogs() {
1042        let openrazer: UpstreamCatalog = toml::from_str(VALID).unwrap();
1043        let openrgb: OpenRgbCatalog = toml::from_str(OPENRGB_VALID).unwrap();
1044        let irazer: IrazerCatalog = toml::from_str(IRAZER_VALID).unwrap();
1045
1046        let assessments = assess_evidence(&openrazer, &openrgb, &irazer);
1047
1048        assert_eq!(assessments.len(), 1);
1049        assert_eq!(
1050            assessments[0].sources,
1051            [
1052                EvidenceSource::OpenRazer,
1053                EvidenceSource::OpenRgb,
1054                EvidenceSource::Irazer
1055            ]
1056        );
1057        assert_eq!(assessments[0].name_agreement, EvidenceAgreement::Disagree);
1058        assert_eq!(assessments[0].kind_agreement, EvidenceAgreement::Agree);
1059        assert_eq!(assessments[0].matrix_agreement, EvidenceAgreement::Agree);
1060        assert_eq!(assessments[0].protocol_agreement, EvidenceAgreement::Agree);
1061        assert_eq!(assessments[0].readiness, EvidenceReadiness::Corroborated);
1062        assert_eq!(
1063            assessments[0].irazer_support,
1064            Some(UpstreamSupportClaim::Supported)
1065        );
1066    }
1067
1068    #[test]
1069    fn sends_material_disagreements_to_research_without_selecting_a_value() {
1070        let openrazer: UpstreamCatalog = toml::from_str(VALID).unwrap();
1071        let openrgb: OpenRgbCatalog =
1072            toml::from_str(&OPENRGB_VALID.replace("matrix = [1, 2]", "matrix = [2, 1]")).unwrap();
1073        let irazer: IrazerCatalog = toml::from_str(IRAZER_VALID).unwrap();
1074
1075        let assessments = assess_evidence(&openrazer, &openrgb, &irazer);
1076
1077        assert_eq!(assessments[0].matrix_agreement, EvidenceAgreement::Disagree);
1078        assert_eq!(assessments[0].readiness, EvidenceReadiness::NeedsResearch);
1079    }
1080
1081    #[test]
1082    fn identifies_single_source_records_without_promoting_them() {
1083        let openrazer: UpstreamCatalog = toml::from_str(VALID).unwrap();
1084        let openrgb = OpenRgbCatalog {
1085            schema_version: SUPPORTED_OPENRGB_SCHEMA_VERSION,
1086            source: openrazer.source.clone(),
1087            devices: Vec::new(),
1088        };
1089        let irazer = IrazerCatalog {
1090            schema_version: SUPPORTED_IRAZER_SCHEMA_VERSION,
1091            source: openrazer.source.clone(),
1092            devices: Vec::new(),
1093        };
1094
1095        let assessments = assess_evidence(&openrazer, &openrgb, &irazer);
1096
1097        assert_eq!(assessments[0].sources, [EvidenceSource::OpenRazer]);
1098        assert_eq!(assessments[0].readiness, EvidenceReadiness::SingleSource);
1099        assert_eq!(
1100            assessments[0].matrix_agreement,
1101            EvidenceAgreement::NotComparable
1102        );
1103    }
1104
1105    #[test]
1106    fn preserves_an_upstream_support_label_as_a_source_claim() {
1107        let catalog: IrazerCatalog = toml::from_str(
1108            r#"
1109schema_version = 1
1110
1111[source]
1112name = "iRazer"
1113repository = "owner/irazer"
1114commit = "0123456789abcdef0123456789abcdef01234567"
1115path = "Sources/iRazer"
1116license = "MIT"
1117generated_by = "tools/import_irazer.py"
1118
1119[[devices]]
1120source_id = "nommo-v2"
1121name = "Razer Nommo V2"
1122kind = "speaker"
1123vid = 0x1532
1124pid = 0x055c
1125upstream_support = "supported"
1126capability_labels = ["Brightness", "EQ"]
1127matrix_family = "extended"
1128transaction_id = 0x3f
1129source_path = "Sources/iRazer/DeviceCatalog.swift"
1130source_symbol = "DeviceCatalog.all:nommo-v2"
1131"#,
1132        )
1133        .unwrap();
1134
1135        assert!(catalog.validate().is_empty());
1136        assert_eq!(
1137            catalog.find_usb(0x1532, 0x055c).unwrap().upstream_support,
1138            UpstreamSupportClaim::Supported
1139        );
1140    }
1141}