by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
main
Colby Knox
0.2.105: find Altium installed on any drive from the registry; documents folders per install (#40)
6ee0d7f
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
//! Where Altium is installed. Each install records itself under HKLM\SOFTWARE\Altium\Builds\<name> with its program
//! folder (ProgramsInstallPath), its documents folder (DocumentsInstallPath: Examples, Templates, OutputJobs) and its
//! version. Only C:\Program Files\Altium was searched until 0.2.104, so an install on another drive was never found
//! (#40). The registry is read first; \Program Files\Altium on every fixed drive is still searched, for an install
//! whose registry entry is missing.
use serde_json::{json, Value};
/// One install as Altium recorded it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Build {
pub name: String,
pub programs: String,
pub documents: String,
pub version: String,
}
#[cfg(windows)]
mod reg {
use super::Build;
type Hkey = isize;
const HKEY_LOCAL_MACHINE: Hkey = 0x8000_0002u32 as i32 as isize;
const KEY_READ: u32 = 0x2_0019;
const KEY_WOW64_64KEY: u32 = 0x0100;
const RRF_RT_REG_SZ: u32 = 0x0002;
#[link(name = "advapi32")]
extern "system" {
fn RegOpenKeyExW(key: Hkey, sub: *const u16, opts: u32, sam: u32, out: *mut Hkey) -> i32;
fn RegEnumKeyExW(key: Hkey, idx: u32, name: *mut u16, len: *mut u32, res: *mut u32, class: *mut u16, clen: *mut u32, ft: *mut u64) -> i32;
fn RegGetValueW(key: Hkey, sub: *const u16, value: *const u16, flags: u32, ty: *mut u32, data: *mut u8, len: *mut u32) -> i32;
fn RegCloseKey(key: Hkey) -> i32;
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
fn open(parent: Hkey, path: &str) -> Option<Hkey> {
let p = wide(path);
let mut out: Hkey = 0;
(unsafe { RegOpenKeyExW(parent, p.as_ptr(), 0, KEY_READ | KEY_WOW64_64KEY, &mut out) } == 0).then_some(out)
}
fn string(key: Hkey, name: &str) -> String {
let n = wide(name);
let mut buf = vec![0u16; 2048];
let mut len = (buf.len() * 2) as u32;
let r = unsafe { RegGetValueW(key, std::ptr::null(), n.as_ptr(), RRF_RT_REG_SZ, std::ptr::null_mut(), buf.as_mut_ptr() as *mut u8, &mut len) };
if r != 0 { return String::new(); }
let chars = (len as usize / 2).min(buf.len());
String::from_utf16_lossy(&buf[..chars]).trim_end_matches('\0').to_string()
}
pub fn builds() -> Vec<Build> {
let Some(root) = open(HKEY_LOCAL_MACHINE, r"SOFTWARE\Altium\Builds") else { return Vec::new() };
let mut out = Vec::new();
for idx in 0..64u32 {
let mut name = vec![0u16; 256];
let mut len = name.len() as u32;
let r = unsafe { RegEnumKeyExW(root, idx, name.as_mut_ptr(), &mut len, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()) };
if r != 0 { break; }
let sub = String::from_utf16_lossy(&name[..len as usize]);
if let Some(k) = open(root, &sub) {
let shown = string(k, "Display Name");
out.push(Build {
name: if shown.is_empty() { string(k, "Name") } else { shown },
programs: string(k, "ProgramsInstallPath"),
documents: string(k, "DocumentsInstallPath"),
version: { let v = string(k, "FullBuild"); if v.is_empty() { string(k, "Version") } else { v } },
});
unsafe { RegCloseKey(k) };
}
}
unsafe { RegCloseKey(root) };
out
}
#[link(name = "kernel32")]
extern "system" {
fn GetLogicalDrives() -> u32;
fn GetDriveTypeW(root: *const u16) -> u32;
}
/// The fixed drives (C:, D:, ...): a network or removable drive can take seconds to answer.
pub fn fixed_drives() -> Vec<char> {
let mask = unsafe { GetLogicalDrives() };
(0..26u8).filter(|i| mask & (1 << i) != 0).map(|i| (b'A' + i) as char)
.filter(|d| { let r = wide(&format!("{d}:\\")); (unsafe { GetDriveTypeW(r.as_ptr()) }) == 3 }).collect()
}
}
#[cfg(not(windows))]
mod reg {
pub fn builds() -> Vec<super::Build> { Vec::new() }
pub fn fixed_drives() -> Vec<char> { vec!['C'] }
}
fn trim_dir(p: &str) -> String {
p.trim().trim_end_matches(['\\', '/']).to_string()
}
/// The digits of the install folder's name (AD26 -> 26, ADDevelop -> 0): the order installs have always been tried
/// in, so the default Altium stays the same.
fn folder_major(base: &str) -> i64 {
let name = base.rsplit(['\\', '/']).next().unwrap_or("");
name.chars().filter(|c| c.is_ascii_digit()).collect::<String>().parse().unwrap_or(0)
}
/// Every install with an X2.EXE: the registry's first, then folders found on disk that it does not list. Newest
/// numbered folder first, as before. Pure apart from `has_exe`.
pub fn merge(builds: &[Build], folders: &[String], has_exe: impl Fn(&str) -> bool) -> Vec<Value> {
let mut out: Vec<(i64, Value)> = Vec::new();
let mut seen: Vec<String> = Vec::new();
let mut add = |base: String, b: Option<&Build>, out: &mut Vec<(i64, Value)>| {
if base.is_empty() || seen.contains(&base.to_lowercase()) { return; }
let exe = format!(r"{base}\X2.EXE");
if !has_exe(&exe) { return; }
seen.push(base.to_lowercase());
let major = folder_major(&base);
let mut v = json!({"installed": true, "base_dir": base, "exe": exe, "system_dir": format!(r"{base}\System"),
"major": major.to_string(), "source": if b.is_some() { "registry" } else { "folder" }});
if let Some(b) = b {
if !b.name.is_empty() { v["name"] = json!(b.name); }
if !b.version.is_empty() { v["version"] = json!(b.version); }
if !b.documents.trim().is_empty() { v["documents_dir"] = json!(trim_dir(&b.documents)); }
}
out.push((major, v));
};
for b in builds { add(trim_dir(&b.programs), Some(b), &mut out); }
for f in folders { add(trim_dir(f), None, &mut out); }
out.sort_by_key(|(m, _)| -m);
out.into_iter().map(|(_, v)| v).collect()
}
/// The AD* folders under \Program Files\Altium and \Program Files (x86)\Altium on every fixed drive.
fn folders_on_disk() -> Vec<String> {
let mut out = Vec::new();
for d in reg::fixed_drives() {
for pf in ["Program Files", "Program Files (x86)"] {
let altium = format!(r"{d}:\{pf}\Altium");
let Ok(rd) = std::fs::read_dir(&altium) else { continue };
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if name.to_uppercase().starts_with("AD") { out.push(format!(r"{altium}\{name}")); }
}
}
}
out
}
/// Every Altium install on the box.
pub fn detect() -> Vec<Value> {
merge(®::builds(), &folders_on_disk(), |p| std::path::Path::new(p).is_file())
}
/// The documents folders of the installs (Examples, Templates, OutputJobs live there), the one for `exe` first.
pub fn documents_dirs(installs: &[Value], exe: Option<&str>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let want = exe.map(|e| e.replace('/', "\\").to_lowercase());
let mut push = |d: &str| { if !out.iter().any(|x| x.eq_ignore_ascii_case(d)) { out.push(d.to_string()); } };
for i in installs {
if want.as_deref().is_some_and(|w| i["exe"].as_str().map(|e| e.to_lowercase()) == Some(w.to_string())) {
if let Some(d) = i["documents_dir"].as_str() { push(d); }
}
}
for i in installs { if let Some(d) = i["documents_dir"].as_str() { push(d); } }
out
}
#[cfg(test)]
mod tests {
use super::*;
fn b(programs: &str, documents: &str, version: &str) -> Build {
Build { name: "Altium Designer".into(), programs: programs.into(), documents: documents.into(), version: version.into() }
}
#[test]
fn an_install_on_another_drive_is_found_from_the_registry() {
let builds = vec![b(r"D:\Program Files\Altium\AD25\", r"D:\Users\Public\Documents\Altium\AD25", "25.8.1.18")];
let found = merge(&builds, &[], |p| p == r"D:\Program Files\Altium\AD25\X2.EXE");
assert_eq!(found.len(), 1);
assert_eq!(found[0]["exe"], json!(r"D:\Program Files\Altium\AD25\X2.EXE"));
assert_eq!(found[0]["documents_dir"], json!(r"D:\Users\Public\Documents\Altium\AD25"));
assert_eq!(found[0]["version"], json!("25.8.1.18"));
assert_eq!(found[0]["major"], json!("25"));
}
#[test]
fn the_registry_and_the_folders_are_merged_once_each_in_the_old_order() {
let builds = vec![b(r"C:\Program Files\Altium\ADDevelop", r"C:\Users\Public\Documents\Altium\ADDevelop", "26.9.1.9"),
b(r"C:\Program Files\Altium\AD26", r"C:\Users\Public\Documents\Altium\AD26", "26.11.1.5"),
b(r"E:\Gone\AD24", "", "24.1")];
let folders = vec![r"C:\Program Files\Altium\AD26".to_string(), r"D:\Program Files\Altium\AD23".to_string()];
let found = merge(&builds, &folders, |p| !p.starts_with("E:"));
let exes: Vec<&str> = found.iter().map(|i| i["exe"].as_str().unwrap()).collect();
assert_eq!(exes, vec![r"C:\Program Files\Altium\AD26\X2.EXE", r"D:\Program Files\Altium\AD23\X2.EXE", r"C:\Program Files\Altium\ADDevelop\X2.EXE"]);
assert_eq!(found[1]["source"], json!("folder"));
assert!(found[1].get("documents_dir").is_none());
}
#[test]
fn the_running_installs_documents_come_first() {
let found = merge(&[b(r"C:\Program Files\Altium\AD26", r"C:\Docs\AD26", "26"), b(r"D:\Altium\ADDevelop", r"D:\Docs\ADDevelop", "26")], &[], |_| true);
assert_eq!(documents_dirs(&found, Some("D:/Altium/ADDevelop/X2.EXE")), vec![r"D:\Docs\ADDevelop", r"C:\Docs\AD26"]);
assert_eq!(documents_dirs(&found, None), vec![r"C:\Docs\AD26", r"D:\Docs\ADDevelop"]);
}
}