A high-performance inference engine for AI models
introduce power sampling
eugene5cc511a776e3
diff --git a/Cargo.lock b/Cargo.lockindex 84b4c59c5..6b5ea6999 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -72,7 +72,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"dependencies = ["alsa-sys",- "bitflags 2.11.1",+ "bitflags 2.13.0","cfg-if","libc",]@@ -138,7 +138,7 @@ version = "1.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"dependencies = [- "windows-sys 0.61.2",+ "windows-sys 0.60.2",][[package]]@@ -149,7 +149,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"dependencies = ["anstyle","once_cell_polyfill",- "windows-sys 0.61.2",+ "windows-sys 0.60.2",][[package]]@@ -169,6 +169,15 @@ dependencies = ["security-framework",]+[[package]]+name = "approx"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"+dependencies = [+ "num-traits",+]+[[package]]name = "arbitrary"version = "1.4.2"@@ -459,7 +468,7 @@ dependencies = ["anyhow","async-trait","bindgen",- "bitflags 2.11.1",+ "bitflags 2.13.0","blake3","bytemuck","bytesize",@@ -484,6 +493,7 @@ dependencies = ["mtl-rs","ndarray","num-traits",+ "obfstr","objc2","objc2-foundation","prettyplease",@@ -497,7 +507,7 @@ dependencies = ["regex","rhai","rstest",- "rustix 1.1.4",+ "rustix","schemars 1.2.1","serde","serde_json",@@ -579,7 +589,7 @@ version = "0.72.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","cexpr","clang-sys","itertools 0.13.0",@@ -666,12 +676,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"[[package]]name = "bitflags"-version = "2.11.1"+version = "2.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"-dependencies = [- "serde_core",-]+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"[[package]]name = "bitstream-io"@@ -752,6 +759,12 @@ version = "3.20.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"+[[package]]+name = "by_address"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"+[[package]]name = "bytecount"version = "0.6.9"@@ -1038,7 +1051,7 @@ name = "cli-storage"version = "0.5.12"dependencies = ["clap",- "crossterm 0.29.0",+ "crossterm","dotenvy","download-manager","futures-util",@@ -1087,7 +1100,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"dependencies = ["serde","termcolor",- "unicode-width 0.2.2",+ "unicode-width 0.1.14",][[package]]@@ -1108,7 +1121,7 @@ version = "3.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"dependencies = [- "windows-sys 0.61.2",+ "windows-sys 0.59.0",][[package]]@@ -1258,7 +1271,7 @@ version = "0.14.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","libc","objc2-audio-toolbox","objc2-core-audio",@@ -1377,6 +1390,12 @@ dependencies = ["itertools 0.13.0",]+[[package]]+name = "critical-section"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"+[[package]]name = "crossbeam-channel"version = "0.5.15"@@ -1411,38 +1430,20 @@ version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"-[[package]]-name = "crossterm"-version = "0.28.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"-dependencies = [- "bitflags 2.11.1",- "crossterm_winapi",- "mio",- "parking_lot",- "rustix 0.38.44",- "serde",- "signal-hook",- "signal-hook-mio",- "winapi",-]-[[package]]name = "crossterm"version = "0.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","crossterm_winapi","derive_more","document-features","futures-core","mio","parking_lot",- "rustix 1.1.4",- "serde",+ "rustix","signal-hook","signal-hook-mio","winapi",@@ -1768,7 +1769,7 @@ version = "0.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b035a542cf7abf01f2e3c4d5a7acbaebfefe120ae4efc7bde3df98186e4b8af7"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","proc-macro2","proc-macro2-diagnostics","quote",@@ -1803,7 +1804,7 @@ dependencies = ["libc","option-ext","redox_users",- "windows-sys 0.61.2",+ "windows-sys 0.59.0",][[package]]@@ -1812,7 +1813,7 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","block2","libc","objc2",@@ -1947,7 +1948,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.61.2",+ "windows-sys 0.59.0",][[package]]@@ -2065,6 +2066,12 @@ dependencies = ["regex-syntax",]+[[package]]+name = "fast-srgb8"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd2e7510819d6fbf51a5545c8f922716ecfb14df168a3242f7d33e0239efe6a1"+[[package]]name = "fastrand"version = "2.4.1"@@ -2539,6 +2546,11 @@ name = "hashbrown"version = "0.17.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash 0.2.0",+][[package]]name = "heck"@@ -3022,8 +3034,8 @@ version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec09d74eb53878be6a7bd49f0ecb0e68d7322963d0a4fbbade67465083f38dbd"dependencies = [- "bitflags 2.11.1",- "crossterm 0.29.0",+ "bitflags 2.13.0",+ "crossterm","futures","generational-box","iocraft-macros",@@ -3069,7 +3081,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"dependencies = ["hermit-abi","libc",- "windows-sys 0.61.2",+ "windows-sys 0.59.0",][[package]]@@ -3261,6 +3273,25 @@ dependencies = ["uuid-simd",]+[[package]]+name = "kanka"+version = "0.5.12"+dependencies = [+ "libc",+ "obfstr",+ "objc2-core-foundation",+]++[[package]]+name = "kanshi"+version = "0.5.12"+dependencies = [+ "crossterm",+ "keisoku",+ "ratatui",+ "sysinfo",+]+[[package]]name = "kasuari"version = "0.4.12"@@ -3272,6 +3303,21 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "keisoku"+version = "0.5.12"+dependencies = [+ "kanka",+ "libc",+ "obfstr",+ "objc2-core-foundation",+ "objc2-io-kit",+ "ratatui",+ "serde",+ "serde_json",+ "sysinfo",+]+[[package]]name = "keyring-core"version = "1.0.0"@@ -3368,7 +3414,7 @@ version = "0.3.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f50e8f47623268b5407192d26876c4d7f89d686ca130fdc53bced4814cd29f8"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0",][[package]]@@ -3380,12 +3426,6 @@ dependencies = ["cc",]-[[package]]-name = "linux-raw-sys"-version = "0.4.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"-[[package]]name = "linux-raw-sys"version = "0.12.1"@@ -3490,11 +3530,11 @@ dependencies = [[[package]]name = "lru"-version = "0.16.4"+version = "0.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"+checksum = "8a860605968fce16869fd239cf4237a82f3ac470723415db603b0e8b6c8d4fb9"dependencies = [- "hashbrown 0.16.1",+ "hashbrown 0.17.1",][[package]]@@ -3522,23 +3562,6 @@ dependencies = ["libc",]-[[package]]-name = "macmon"-version = "0.7.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f5c39c83f05d6ebe9eb6c8ea95db95279bb085124bf244d3383e9c7b0abd2465"-dependencies = [- "chrono",- "clap",- "core-foundation 0.10.1",- "libc",- "num-traits",- "ratatui",- "serde",- "serde-inline-default",- "serde_json",-]-[[package]]name = "macro_rules_attribute"version = "0.2.2"@@ -3703,7 +3726,7 @@ name = "mock-registry"version = "0.5.12"dependencies = ["base64 0.22.1",- "bitflags 2.11.1",+ "bitflags 2.13.0","bytesize","crc32c","http 1.4.1",@@ -3755,7 +3778,7 @@ version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b5da07ba3cea3adad7b479c3d1b097875e8c56e9711830b72c8c2b5f5cf0ce8f"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","block2","dispatch2","objc2",@@ -3824,7 +3847,7 @@ version = "3.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f1d395473824516f38dd1071a1a37bc57daa7be65b293ebba4ead5f7abb017a2"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","ctor","futures","indexmap 2.14.0",@@ -3898,7 +3921,7 @@ version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","jni-sys 0.3.1","log","ndk-sys",@@ -3933,7 +3956,7 @@ version = "0.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","cfg-if","cfg_aliases","libc",@@ -3995,7 +4018,7 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.61.2",+ "windows-sys 0.59.0",][[package]]@@ -4153,10 +4176,10 @@ dependencies = [][[package]]-name = "numtoa"-version = "0.2.4"+name = "obfstr"+version = "0.4.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6aa2c4e539b869820a2b82e1aef6ff40aa85e65decdd5185e83fb4b1249cd00f"+checksum = "d0d354e9a302760d07e025701d40534f17dd1fe4c4db955b4e3bd2907c63bdee"[[package]]name = "objc-sys"@@ -4179,7 +4202,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","libc","objc2","objc2-core-audio",@@ -4217,7 +4240,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","objc2",]@@ -4227,7 +4250,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","block2","dispatch2","libc",@@ -4246,7 +4269,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","block2","libc","objc2",@@ -4269,7 +4292,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","libc","objc2","objc2-core-foundation",@@ -4282,7 +4305,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","block2","libc","objc2",@@ -4310,7 +4333,7 @@ version = "6.5.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","libc","once_cell","onig_sys",@@ -4402,6 +4425,30 @@ dependencies = ["winapi",]+[[package]]+name = "palette"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cbf71184cc5ecc2e4e1baccdb21026c20e5fc3dcf63028a086131b3ab00b6e6"+dependencies = [+ "approx",+ "fast-srgb8",+ "libm",+ "palette_derive",+]++[[package]]+name = "palette_derive"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f5030daf005bface118c096f510ffb781fc28f9ab6a32ab224d8631be6851d30"+dependencies = [+ "by_address",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "parking_lot"version = "0.12.5"@@ -4619,7 +4666,7 @@ version = "0.18.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","crc32fast","fdeflate","flate2",@@ -4742,7 +4789,7 @@ checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"dependencies = ["bit-set 0.8.0","bit-vec 0.8.0",- "bitflags 2.11.1",+ "bitflags 2.13.0","num-traits","rand 0.9.4","rand_chacha 0.9.0",@@ -5073,15 +5120,15 @@ checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68"[[package]]name = "ratatui"-version = "0.30.0"+version = "0.30.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d1ce67fb8ba4446454d1c8dbaeda0557ff5e94d39d5e5ed7f10a65eb4c8266bc"+checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d"dependencies = ["instability","ratatui-core","ratatui-crossterm","ratatui-macros",- "ratatui-termion",+ "ratatui-termina","ratatui-termwiz","ratatui-widgets","serde",@@ -5089,17 +5136,18 @@ dependencies = [[[package]]name = "ratatui-core"-version = "0.1.0"+version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5ef8dea09a92caaf73bff7adb70b76162e5937524058a7e5bff37869cbbec293"+checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","compact_str",- "hashbrown 0.16.1",- "indoc",+ "critical-section",+ "hashbrown 0.17.1","itertools 0.14.0","kasuari","lru",+ "palette","serde","strum","thiserror 2.0.18",@@ -5110,43 +5158,42 @@ dependencies = [[[package]]name = "ratatui-crossterm"-version = "0.1.0"+version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "577c9b9f652b4c121fb25c6a391dd06406d3b092ba68827e6d2f09550edc54b3"+checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0"dependencies = ["cfg-if",- "crossterm 0.28.1",- "crossterm 0.29.0",+ "crossterm","instability","ratatui-core",][[package]]name = "ratatui-macros"-version = "0.7.0"+version = "0.7.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a7f1342a13e83e4bb9d0b793d0ea762be633f9582048c892ae9041ef39c936f4"+checksum = "ed7dc68daa7498a43e4d68e0eb078427e10c38fbcfbb1e42d955f1fa2140d814"dependencies = ["ratatui-core","ratatui-widgets",][[package]]-name = "ratatui-termion"+name = "ratatui-termina"version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4cade85a8591fbc911e147951422f0d6fd40f4948b271b6216c7dc01838996f8"+checksum = "c0bf912d9e66f057a759d92e386a280ea886b352ab757d6ac4d653c7ed2c43c2"dependencies = ["instability","ratatui-core",- "termion",+ "termina",][[package]]name = "ratatui-termwiz"-version = "0.1.0"+version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0f76fe0bd0ed4295f0321b1676732e2454024c15a35d01904ddb315afd3d545c"+checksum = "faf03e0380b7744054d6cb74224fe3adf062a029754933f575ca1e3b4c2ce977"dependencies = ["ratatui-core","termwiz",@@ -5154,12 +5201,12 @@ dependencies = [[[package]]name = "ratatui-widgets"-version = "0.3.0"+version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d7dbfa023cd4e604c2553483820c5fe8aa9d71a42eea5aa77c6e7f35756612db"+checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1"dependencies = [- "bitflags 2.11.1",- "hashbrown 0.16.1",+ "bitflags 2.13.0",+ "hashbrown 0.17.1","indoc","instability","itertools 0.14.0",@@ -5265,7 +5312,7 @@ version = "0.5.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0",][[package]]@@ -5469,7 +5516,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dd4dd0f8c36625202a4ba553c416c19b719947cd2a31d1bda06126e4a5727daf"dependencies = ["ahash",- "bitflags 2.11.1",+ "bitflags 2.13.0","num-traits","once_cell","rhai_codegen",@@ -5649,30 +5696,17 @@ dependencies = ["semver",]-[[package]]-name = "rustix"-version = "0.38.44"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"-dependencies = [- "bitflags 2.11.1",- "errno",- "libc",- "linux-raw-sys 0.4.15",- "windows-sys 0.59.0",-]-[[package]]name = "rustix"version = "1.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","errno","libc",- "linux-raw-sys 0.12.1",- "windows-sys 0.61.2",+ "linux-raw-sys",+ "windows-sys 0.59.0",][[package]]@@ -5730,7 +5764,7 @@ dependencies = ["security-framework","security-framework-sys","webpki-root-certs",- "windows-sys 0.61.2",+ "windows-sys 0.59.0",][[package]]@@ -5941,7 +5975,7 @@ version = "3.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","core-foundation 0.10.1","core-foundation-sys","libc",@@ -5978,17 +6012,6 @@ dependencies = ["serde_derive",]-[[package]]-name = "serde-inline-default"-version = "1.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2bf03b7a5281cfd4013bc788d057b0f09fc634397d83bc8973c955bd4f32727a"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.117",-]-[[package]]name = "serde-wasm-bindgen"version = "0.6.5"@@ -6307,7 +6330,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"dependencies = ["libc",- "windows-sys 0.61.2",+ "windows-sys 0.60.2",][[package]]@@ -6378,18 +6401,18 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"[[package]]name = "strum"-version = "0.27.2"+version = "0.28.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"+checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"dependencies = ["strum_macros",][[package]]name = "strum_macros"-version = "0.27.2"+version = "0.28.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"+checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664"dependencies = ["heck","proc-macro2",@@ -6531,7 +6554,7 @@ version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","core-foundation 0.9.4","system-configuration-sys",]@@ -6574,8 +6597,8 @@ dependencies = ["fastrand","getrandom 0.4.2","once_cell",- "rustix 1.1.4",- "windows-sys 0.61.2",+ "rustix",+ "windows-sys 0.59.0",][[package]]@@ -6587,6 +6610,19 @@ dependencies = ["winapi-util",]+[[package]]+name = "termina"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9048a889effe34a5cddee0af7f53285198b16dca3be510858d38dfdb3e62a04e"+dependencies = [+ "bitflags 2.13.0",+ "parking_lot",+ "rustix",+ "signal-hook",+ "windows-sys 0.60.2",+]+[[package]]name = "terminfo"version = "0.9.0"@@ -6599,17 +6635,6 @@ dependencies = ["phf_codegen",]-[[package]]-name = "termion"-version = "4.0.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f44138a9ae08f0f502f24104d82517ef4da7330c35acd638f1f29d3cd5475ecb"-dependencies = [- "libc",- "numtoa",- "serde",-]-[[package]]name = "termios"version = "0.3.3"@@ -6627,7 +6652,7 @@ checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7"dependencies = ["anyhow","base64 0.22.1",- "bitflags 2.11.1",+ "bitflags 2.13.0","fancy-regex 0.11.0","filedescriptor","finl_unicode",@@ -6644,7 +6669,6 @@ dependencies = ["pest","pest_derive","phf",- "serde","sha2","signal-hook","siphasher",@@ -6667,7 +6691,7 @@ name = "test-runner"version = "0.5.12"dependencies = ["criterion",- "macmon",+ "keisoku","objc2","objc2-foundation",]@@ -7091,7 +7115,7 @@ version = "0.6.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","bytes","futures-util","http 1.4.1",@@ -7855,7 +7879,7 @@ version = "0.244.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.0","hashbrown 0.15.5","indexmap 2.14.0","semver",@@ -7932,7 +7956,6 @@ checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7"dependencies = ["getrandom 0.3.4","mac_address",- "serde","sha2","thiserror 1.0.69","uuid",@@ -7947,7 +7970,6 @@ dependencies = ["csscolorparser","deltae","lazy_static",- "serde","wezterm-dynamic",]@@ -8010,7 +8032,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.61.2",+ "windows-sys 0.59.0",][[package]]@@ -8542,7 +8564,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"dependencies = ["anyhow",- "bitflags 2.11.1",+ "bitflags 2.13.0","indexmap 2.14.0","log","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 1238c5b04..0aeaea46c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -18,6 +18,9 @@ members = ["crates/cli-storage","crates/cli-tools","crates/test-runner",+ "crates/keisoku",+ "crates/kanshi",+ "crates/kanka",]resolver = "3"@@ -57,6 +60,8 @@ nagare = { path = "crates/nagare", default-features = false }download-manager = { path = "crates/download-manager", default-features = false }mock-registry = { path = "crates/mock-registry", default-features = false }benchmarks = { path = "crates/benchmarks", default-features = false }+keisoku = { path = "crates/keisoku", default-features = false }+kanka = { path = "crates/kanka", default-features = false }uzu = { path = "crates/uzu", default-features = false }xgrammar = { package = "xgrammar-rs", git = "https://github.com/trymirai/xgrammar-rs.git", tag = "0.2.2", features = ["tokenizers"] }half = { version = "2.7", features = ["bytemuck", "num-traits"] }@@ -70,7 +75,10 @@ tokenizers = { version = "0.22", features = [], default-features = false }objc2 = "0.6.4"objc2-foundation = "0.3.2"+objc2-core-foundation = "0.3.2"+objc2-io-kit = { version = "0.3.2", default-features = false, features = ["libc", "ps"] }objc2-security = "0.3.2"+obfstr = "0.4.4"metal = { package = "mtl-rs", version = "0.1.12" }block2 = "0.6"bytemuck = "1.23"@@ -180,7 +188,7 @@ tsify = { version = "0.5.6", features = ["js"] }openai-harmony = "0.0.8"dirs = "6.0.0"dotenvy = "0.15.7"-ratatui = "0.30.0"+ratatui = "0.30.2"crossterm = "0.29.0"async-openai = { version = "0.35.0", features = ["chat-completion",@@ -208,7 +216,6 @@ rodio = { version = "0.22.2", default-features = false, features = ["playback","wav",] }-macmon = "0.7"[workspace.lints.clippy]# TODO: add large_stack_frames, large_stack_arrays, trivially_copy_pass_by_ref, needless_pass_by_value, map_err_ignore, use_self, cloned_instead_of_copied, manual_let_else, semicolon_if_nothing_returned, uninlined_format_args, lossy_float_literaldiff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.tomlindex 1380fa286..7fabdd676 100644--- a/crates/backend-uzu/Cargo.toml+++ b/crates/backend-uzu/Cargo.toml@@ -40,15 +40,14 @@ rustix.workspace = truefutures.workspace = truetokio-util.workspace = true-# grammar requires xgrammarxgrammar = { workspace = true, optional = true }-# metal on macos requires objc2, bytesize, metal[target.'cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "visionos"))'.dependencies]objc2 = { workspace = true, optional = true }objc2-foundation = { workspace = true, optional = true }bytesize = { workspace = true, optional = true }metal = { workspace = true, optional = true }+obfstr = { workspace = true, optional = true }[dev-dependencies]test-tag.workspace = true@@ -88,7 +87,6 @@ itertools.workspace = truecbindgen.workspace = truerhai.workspace = true-# metal on macos requires clang-ast for dsl build[target.'cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "visionos"))'.build-dependencies]clang-ast = { workspace = true, optional = true }@@ -101,6 +99,7 @@ metal = ["dep:objc2-foundation","dep:bytesize","dep:metal",+ "dep:obfstr",]grammar = ["dep:xgrammar"]tracing = []diff --git a/crates/backend-uzu/src/backends/metal/metal_extensions/device_extensions.rs b/crates/backend-uzu/src/backends/metal/metal_extensions/device_extensions.rsindex 9066dd628..1fbdec746 100644--- a/crates/backend-uzu/src/backends/metal/metal_extensions/device_extensions.rs+++ b/crates/backend-uzu/src/backends/metal/metal_extensions/device_extensions.rs@@ -1,11 +1,12 @@use core::mem::transmute;+use std::ffi::CString;use metal::MTLDevice;+use obfstr::obfstr;use objc2::{Message,ffi::objc_msgSend,runtime::{NSObjectProtocol, ProtocolObject, Sel},- sel,};// Used to bypass objc2's debug-mode class validation for proxy objects like@@ -24,33 +25,50 @@ unsafe fn raw_msg_send<T: Message + ?Sized, R>(unsafe { send(object_pointer, sel) }}+// Registers a selector by name at runtime, so the obfuscated private selector+// names are only ever materialized at runtime — never appearing verbatim in the+// binary the way a compile-time `sel!(...)` would.+fn register_selector(name: &str) -> Sel {+ Sel::register(&CString::new(name).expect("selector name has no interior NUL byte"))+}++// Sends a zero-argument selector by (obfuscated) name, returning `fallback` when+// the device does not implement it. The `respondsToSelector:` guard is the+// safety precondition for `raw_msg_send`, which bypasses objc2's debug-mode+// class check so the send also works on the `CaptureMTLDevice` forwarding proxy+// (where a typed `msg_send!` would panic) — this is why the typed `mtl-rs`+// accessors are not used here.+fn optional_selector_value<T, R>(+ device: &T,+ name: &str,+ fallback: R,+) -> R+where+ T: Message + NSObjectProtocol,+{+ let selector = register_selector(name);+ if device.respondsToSelector(selector) {+ unsafe { raw_msg_send(device, selector) }+ } else {+ fallback+ }+}+pub trait DeviceExt: MTLDevice + Message + NSObjectProtocol + Sized {/// Number of GPU shader cores.fn gpu_core_count(&self) -> u32 {- if self.respondsToSelector(sel!(gpuCoreCount)) {- unsafe { raw_msg_send(self, sel!(gpuCoreCount)) }- } else {- 8- }+ optional_selector_value(self, obfstr!("gpuCoreCount"), 8)}/// Whether the GPU has a Matrix eXtension Unit (neural accelerator for compute)./// True on M5+ (Gen18+), false on M1-M4.fn supports_mxu(&self) -> bool {- if self.respondsToSelector(sel!(supportsMXU)) {- unsafe { raw_msg_send(self, sel!(supportsMXU)) }- } else {- false- }+ optional_selector_value(self, obfstr!("supportsMXU"), false)}/// Whether the GPU supports placement sparse resources.fn supports_placement_sparse_resources(&self) -> bool {- if self.respondsToSelector(sel!(supportsPlacementSparse)) {- unsafe { raw_msg_send(self, sel!(supportsPlacementSparse)) }- } else {- false- }+ optional_selector_value(self, obfstr!("supportsPlacementSparse"), false)}}diff --git a/crates/kanka/Cargo.toml b/crates/kanka/Cargo.tomlnew file mode 100644index 000000000..e6df21352--- /dev/null+++ b/crates/kanka/Cargo.toml@@ -0,0 +1,22 @@+[package]+name = "kanka"+edition.workspace = true+rust-version.workspace = true+version.workspace = true+authors.workspace = true+homepage.workspace = true+repository.workspace = true+license.workspace = true+description = "Generic obfuscated dlsym bindings for private Apple framework APIs"++[lib]+name = "kanka"+path = "src/lib.rs"++[lints]+workspace = true++[target.'cfg(target_vendor = "apple")'.dependencies]+objc2-core-foundation.workspace = true+obfstr.workspace = true+libc.workspace = truediff --git a/crates/kanka/src/lib.rs b/crates/kanka/src/lib.rsnew file mode 100644index 000000000..958904b69--- /dev/null+++ b/crates/kanka/src/lib.rs@@ -0,0 +1,72 @@+//! `kanka` (甘果, "sweet fruit") — obfuscated `dlsym` bindings for private Apple frameworks.++#[cfg(target_vendor = "apple")]+pub use libc;+#[cfg(target_vendor = "apple")]+pub use obfstr;+#[cfg(target_vendor = "apple")]+pub use objc2_core_foundation;++/// Declares a struct of `dlsym`-resolved private C functions (names obfuscated),+/// with a `resolve()` and a `OnceLock`-cached `get()`.+#[macro_export]+macro_rules! ffi_table {+ (+ struct $table:ident from $framework:literal {+ $($field:ident = $symbol:literal: $signature:ty),* $(,)?+ }+ ) => {+ struct $table {+ $($field: $signature,)*+ }++ impl $table {+ fn resolve() -> ::core::option::Option<Self> {+ let path = ::std::ffi::CString::new($crate::obfstr::obfstr!($framework)).ok()?;+ let handle = unsafe { $crate::libc::dlopen(path.as_ptr(), $crate::libc::RTLD_LAZY) };+ if handle.is_null() {+ return ::core::option::Option::None;+ }+ ::core::option::Option::Some(Self {+ $($field: {+ let name = ::std::ffi::CString::new($crate::obfstr::obfstr!($symbol)).ok()?;+ let symbol = unsafe { $crate::libc::dlsym(handle, name.as_ptr()) };+ if symbol.is_null() {+ return ::core::option::Option::None;+ }+ unsafe {+ ::core::mem::transmute::<*mut ::core::ffi::c_void, $signature>(symbol)+ }+ },)*+ })+ }++ fn get() -> ::core::option::Option<&'static Self> {+ static TABLE: ::std::sync::OnceLock<::core::option::Option<$table>> =+ ::std::sync::OnceLock::new();+ TABLE.get_or_init(Self::resolve).as_ref()+ }+ }+ };+}++/// Declares an opaque CoreFoundation handle type usable with `CFRetained`.+#[macro_export]+macro_rules! opaque_cf_type {+ ($name:ident) => {+ #[repr(C)]+ #[allow(dead_code)]+ struct $name {+ inner: [u8; 0],+ _p: ::core::cell::UnsafeCell<+ ::core::marker::PhantomData<(+ *const ::core::cell::UnsafeCell<()>,+ ::core::marker::PhantomPinned,+ )>,+ >,+ }+ $crate::objc2_core_foundation::cf_type!(+ unsafe impl $name {}+ );+ };+}diff --git a/crates/kanshi/Cargo.toml b/crates/kanshi/Cargo.tomlnew file mode 100644index 000000000..aec918769--- /dev/null+++ b/crates/kanshi/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "kanshi"+edition.workspace = true+rust-version.workspace = true+version.workspace = true+authors.workspace = true+homepage.workspace = true+repository.workspace = true+license.workspace = true+description = "mactop-style live system monitor built on keisoku"++[[bin]]+name = "kanshi"+path = "src/main.rs"++[lints]+workspace = true++[dependencies]+keisoku.workspace = true+crossterm.workspace = true+ratatui.workspace = true+sysinfo.workspace = truediff --git a/crates/kanshi/src/chart.rs b/crates/kanshi/src/chart.rsnew file mode 100644index 000000000..cbad6d214--- /dev/null+++ b/crates/kanshi/src/chart.rs@@ -0,0 +1,80 @@+use std::collections::VecDeque;++use ratatui::{Frame, layout::Rect};++use crate::{+ state::{accent, background},+ widgets::panel_owned,+};++const BRAILLE_DOTS: [[u16; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];++pub(crate) fn render_chart(+ frame: &mut Frame,+ area: Rect,+ title: String,+ history: &VecDeque<f64>,+ ceiling: f64,+) {+ let block = panel_owned(title);+ let inner = block.inner(area);+ frame.render_widget(block, area);+ if inner.width == 0 || inner.height == 0 {+ return;+ }++ let columns = inner.width as usize;+ let shown: Vec<f64> = history.iter().rev().take(columns).rev().copied().collect();+ if shown.is_empty() {+ return;+ }+ let offset = columns - shown.len();+ let ceiling = ceiling.max(1e-9);+ let cell_rows = inner.height as usize;+ let sub_rows = cell_rows * 4;+ let last = shown.len() - 1;+ let color = accent();+ let background = background();++ let fill_at = |sub_x: usize| -> Option<usize> {+ let position = sub_x as f64 / 2.0 - offset as f64;+ if position < 0.0 {+ return None;+ }+ let low = (position.floor() as usize).min(last);+ let high = (low + 1).min(last);+ let blend = position - low as f64;+ let value = shown[low] * (1.0 - blend) + shown[high] * blend;+ Some(((value / ceiling).clamp(0.0, 1.0) * sub_rows as f64).round() as usize)+ };++ let buffer = frame.buffer_mut();+ for cell_x in 0..columns {+ let fills = [fill_at(cell_x * 2), fill_at(cell_x * 2 + 1)];+ if fills.iter().all(Option::is_none) {+ continue;+ }+ let x = inner.left() + cell_x as u16;+ for row in 0..cell_rows {+ let mut dots = 0u16;+ for (sub, fill) in fills.iter().enumerate() {+ let Some(fill) = fill else {+ continue;+ };+ for internal in 0..4 {+ if row * 4 + (3 - internal) < *fill {+ dots |= BRAILLE_DOTS[sub][internal];+ }+ }+ }+ if dots == 0 {+ continue;+ }+ let symbol = char::from_u32(0x2800 + dots as u32).unwrap_or(' ');+ let y = inner.bottom() - 1 - row as u16;+ if let Some(cell) = buffer.cell_mut((x, y)) {+ cell.set_char(symbol).set_fg(color).set_bg(background);+ }+ }+ }+}diff --git a/crates/kanshi/src/disk_row.rs b/crates/kanshi/src/disk_row.rsnew file mode 100644index 000000000..ee1fa3b12--- /dev/null+++ b/crates/kanshi/src/disk_row.rs@@ -0,0 +1,5 @@+pub(crate) struct DiskRow {+ pub(crate) name: String,+ pub(crate) used: u64,+ pub(crate) total: u64,+}diff --git a/crates/kanshi/src/format.rs b/crates/kanshi/src/format.rsnew file mode 100644index 000000000..89d319d28--- /dev/null+++ b/crates/kanshi/src/format.rs@@ -0,0 +1,35 @@+use keisoku::BatteryMetrics;++pub(crate) fn battery_status(battery: &BatteryMetrics) -> &'static str {+ if battery.charging {+ "charging"+ } else if battery.on_ac_power {+ "AC"+ } else {+ "battery"+ }+}++pub(crate) fn human_bytes(bytes: u64) -> String {+ const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];+ let mut value = bytes as f64;+ let mut unit = 0;+ while value >= 1024.0 && unit < UNITS.len() - 1 {+ value /= 1024.0;+ unit += 1;+ }+ if unit == 0 {+ format!("{bytes} B")+ } else {+ format!("{value:.1} {}", UNITS[unit])+ }+}++pub(crate) fn format_uptime(seconds: u64) -> String {+ let (hours, minutes) = (seconds / 3600, (seconds % 3600) / 60);+ if hours > 0 {+ format!("{hours}h {minutes}m")+ } else {+ format!("{minutes}m")+ }+}diff --git a/crates/kanshi/src/host_info.rs b/crates/kanshi/src/host_info.rsnew file mode 100644index 000000000..33a6a1f5c--- /dev/null+++ b/crates/kanshi/src/host_info.rs@@ -0,0 +1,7 @@+pub(crate) struct HostInfo {+ pub(crate) user: String,+ pub(crate) hostname: String,+ pub(crate) os: String,+ pub(crate) kernel: String,+ pub(crate) shell: String,+}diff --git a/crates/kanshi/src/info.rs b/crates/kanshi/src/info.rsnew file mode 100644index 000000000..db8fff5e5--- /dev/null+++ b/crates/kanshi/src/info.rs@@ -0,0 +1,170 @@+use ratatui::{+ Frame,+ layout::{Constraint, Rect},+ style::{Modifier, Style},+ text::{Line, Span},+ widgets::Paragraph,+};++use crate::{+ format::{battery_status, format_uptime, human_bytes},+ state::accent,+ telemetry::Telemetry,+ widgets::split_horizontal,+};++const APPLE_ART: [&str; 17] = [+ " 'c. ",+ " ,xNMM. ",+ " .OMMMMo ",+ " OMMM0, ",+ " .;loddo:' loolloddol;. ",+ " cKMMMMMMMMMMNWMMMMMMMMMM0: ",+ " .KMMMMMMMMMMMMMMMMMMMMMMMWd. ",+ " XMMMMMMMMMMMMMMMMMMMMMMMX. ",+ ";MMMMMMMMMMMMMMMMMMMMMMMM: ",+ ":MMMMMMMMMMMMMMMMMMMMMMMM: ",+ ".MMMMMMMMMMMMMMMMMMMMMMMMX. ",+ " kMMMMMMMMMMMMMMMMMMMMMMMMWd. ",+ " .XMMMMMMMMMMMMMMMMMMMMMMMMMMk ",+ " .XMMMMMMMMMMMMMMMMMMMMMMMMK. ",+ " kMMMMMMMMMMMMMMMMMMMMMMd ",+ " ;KMMMMMMMWXXWMMMMMMMk. ",+ " .cooc,. .,coo:. ",+];++pub(crate) fn render_info(+ frame: &mut Frame,+ area: Rect,+ state: &Telemetry,+) {+ let art_width = APPLE_ART.iter().map(|line| line.chars().count()).max().unwrap_or(0) as u16 + 2;+ let columns = split_horizontal(area, [Constraint::Length(art_width), Constraint::Min(0)]);++ let art: Vec<Line> = APPLE_ART.iter().map(|line| Line::from(*line)).collect();+ frame.render_widget(Paragraph::new(art).style(Style::default().fg(accent())), columns[0]);+ frame.render_widget(Paragraph::new(build_info_lines(state)).style(Style::default().fg(accent())), columns[1]);+}++fn info_line(+ label: &str,+ value: String,+) -> Line<'static> {+ Line::from(vec![+ Span::styled(format!("{label:<11}"), Style::default().fg(accent()).add_modifier(Modifier::BOLD)),+ Span::raw(value),+ ])+}++fn build_info_lines(state: &Telemetry) -> Vec<Line<'static>> {+ let snapshot = state.snapshot.as_ref();+ let mut lines = Vec::new();++ if let Some(host) = &state.host {+ lines.push(Line::from(Span::styled(+ format!("{}@{}", host.user, host.hostname),+ Style::default().fg(accent()).add_modifier(Modifier::BOLD),+ )));+ lines.push(Line::from("-".repeat(25)));+ lines.push(info_line("OS", host.os.clone()));+ if let Some(device) = &state.device {+ lines.push(info_line("Host", device.chip.clone()));+ }+ lines.push(info_line("Kernel", host.kernel.clone()));+ lines.push(info_line("Uptime", format_uptime(state.uptime_seconds)));+ lines.push(info_line("Shell", host.shell.clone()));+ }+ if let Some(device) = &state.device {+ lines.push(info_line(+ "CPU",+ format!("{} ({}E+{}P)", device.chip, device.efficiency_cores, device.performance_cores),+ ));+ lines.push(info_line("GPU", format!("{} Cores", device.gpu_cores)));+ }+ if let Some(memory) = snapshot.and_then(|s| s.memory.as_ref()) {+ lines.push(info_line(+ "Memory",+ format!(+ "{:.2} GB / {:.2} GB",+ memory.ram_usage.value() as f64 / 1e9,+ memory.ram_total.value() as f64 / 1e9+ ),+ ));+ lines.push(info_line(+ "Swap",+ format!(+ "{:.2} GB / {:.2} GB",+ memory.swap_usage.value() as f64 / 1e9,+ memory.swap_total.value() as f64 / 1e9+ ),+ ));+ }++ lines.push(Line::from(""));+ if let Some(cpu) = snapshot.and_then(|s| s.cpu.as_ref()) {+ lines.push(info_line("CPU Usage", format!("{:.2}%", cpu.usage.value())));+ }+ if let Some(gpu) = snapshot.and_then(|s| s.gpu.as_ref()) {+ lines.push(info_line("GPU Usage", format!("{:.0}%", gpu.usage.value())));+ }+ if let Some(ane) = snapshot.and_then(|s| s.neural_engine.as_ref()) {+ lines.push(info_line("ANE Usage", format!("{:.0}%", ane.active.value())));+ }+ if let Some(power) = snapshot.and_then(|s| s.power.as_ref()) {+ lines.push(info_line("Power", format!("{:.2} W (max {:.2} W)", power.package.value(), state.max_power)));+ }+ if let Some(temperatures) = snapshot.and_then(|s| s.temperatures.as_ref()) {+ let mut parts = Vec::new();+ if let Some(cpu) = temperatures.cpu_average {+ parts.push(format!("CPU {:.0}°C", cpu.value()));+ }+ if let Some(gpu) = temperatures.gpu_average {+ parts.push(format!("GPU {:.0}°C", gpu.value()));+ }+ if !parts.is_empty() {+ lines.push(info_line("Thermals", parts.join(" ")));+ }+ }+ lines.push(info_line(+ "Network",+ format!("↑ {}/s ↓ {}/s", human_bytes(state.network_up as u64), human_bytes(state.network_down as u64)),+ ));+ lines.push(info_line(+ "Disk",+ format!("R {}/s W {}/s", human_bytes(state.disk_read as u64), human_bytes(state.disk_written as u64)),+ ));+ if let Some(bandwidth) = snapshot.and_then(|s| s.bandwidth.as_ref()) {+ lines.push(info_line(+ "DRAM BW",+ format!(+ "R {:.1} W {:.1} ({:.1}) GB/s",+ bandwidth.dram_read.value(),+ bandwidth.dram_write.value(),+ bandwidth.dram_read.value() + bandwidth.dram_write.value(),+ ),+ ));+ }+ if let Some(battery) = snapshot.and_then(|s| s.battery.as_ref()).filter(|battery| battery.present) {+ let status = battery_status(battery);+ lines.push(info_line("Battery", format!("{:.0}% ({status})", battery.percent.value())));+ }++ if let Some(fans) = snapshot.and_then(|s| s.fans.as_ref()).filter(|fans| !fans.fans.is_empty()) {+ lines.push(Line::from(""));+ for (index, fan) in fans.fans.iter().enumerate() {+ lines.push(info_line(+ &format!("Fan {}", index + 1),+ format!("{:.0} rpm ({:.0}–{:.0})", fan.actual.value(), fan.minimum.value(), fan.maximum.value()),+ ));+ }+ }++ if !state.disks.is_empty() {+ lines.push(Line::from("-".repeat(25)));+ for disk in &state.disks {+ lines.push(info_line(&disk.name, format!("{} / {}", human_bytes(disk.used), human_bytes(disk.total))));+ }+ }++ lines+}diff --git a/crates/kanshi/src/main.rs b/crates/kanshi/src/main.rsnew file mode 100644index 000000000..6e8fe9768--- /dev/null+++ b/crates/kanshi/src/main.rs@@ -0,0 +1,145 @@+mod chart;+mod disk_row;+mod format;+mod host_info;+mod info;+mod net_interface;+mod panels;+mod process_row;+mod sampler;+mod state;+mod telemetry;+mod widgets;++use std::{+ io::{self, IsTerminal},+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+ time::Duration,+};++use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};+use keisoku::Collector;+use ratatui::DefaultTerminal;++use crate::{+ panels::draw,+ sampler::sample_loop,+ state::{cycle_theme, data_version, slow_down, speed_up, toggle_background, toggle_info},+ telemetry::Telemetry,+};++fn main() -> io::Result<()> {+ if std::env::args().any(|arg| arg == "--once") || !io::stdout().is_terminal() {+ return print_once();+ }++ let telemetry = Arc::new(Mutex::new(Telemetry::default()));+ let stop = Arc::new(AtomicBool::new(false));++ let sampler = {+ let telemetry = Arc::clone(&telemetry);+ let stop = Arc::clone(&stop);+ std::thread::spawn(move || sample_loop(&telemetry, &stop))+ };++ let mut terminal = ratatui::init();+ let result = run(&mut terminal, &telemetry);+ ratatui::restore();++ stop.store(true, Ordering::Relaxed);+ let _ = sampler.join();+ result+}++fn print_once() -> io::Result<()> {+ let mut collector = Collector::new();+ let device = collector.device();+ let snapshot = collector.sample(Duration::from_millis(300));+ let flag = |present: bool| {+ if present {+ "yes"+ } else {+ "--"+ }+ };++ println!("kanshi — available telemetry");+ println!(+ "device {} {}E+{}P {} GPU {:.1} GB",+ device.chip,+ device.efficiency_cores,+ device.performance_cores,+ device.gpu_cores,+ device.ram_total.value() as f64 / 1e9,+ );+ println!("cpu {}", flag(snapshot.cpu.is_some()));+ println!("gpu {}", flag(snapshot.gpu.is_some()));+ println!("neural {}", flag(snapshot.neural_engine.is_some()));+ println!("power {}", flag(snapshot.power.is_some()));+ println!("bandwidth {}", flag(snapshot.bandwidth.is_some()));+ println!("memory {}", flag(snapshot.memory.is_some()));+ println!("fans {}", flag(snapshot.fans.is_some()));+ println!("battery {}", flag(snapshot.battery.is_some()));+ println!("temps {}", flag(snapshot.temperatures.is_some()));+ println!("sensors {}", snapshot.sensors.len());++ if let Some(memory) = &snapshot.memory {+ println!(+ " ram {:.2} / {:.2} GB",+ memory.ram_usage.value() as f64 / 1e9,+ memory.ram_total.value() as f64 / 1e9,+ );+ }+ if let Some(temperatures) = &snapshot.temperatures {+ if let Some(cpu) = temperatures.cpu_average {+ println!(" cpu temp {:.1}°C", cpu.value());+ }+ if let Some(gpu) = temperatures.gpu_average {+ println!(" gpu temp {:.1}°C", gpu.value());+ }+ }+ for sensor in snapshot.sensors.iter().take(24) {+ println!(" {:<26} {:>8.2} [{}]", sensor.name, sensor.value, sensor.component);+ }+ Ok(())+}++fn run(+ terminal: &mut DefaultTerminal,+ telemetry: &Arc<Mutex<Telemetry>>,+) -> io::Result<()> {+ let mut shown_version = u64::MAX;+ let mut redraw = true;+ loop {+ let version = data_version();+ if redraw || version != shown_version {+ shown_version = version;+ redraw = false;+ let state = telemetry.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ terminal.draw(|frame| draw(frame, &state))?;+ }+ if event::poll(Duration::from_millis(200))? {+ match event::read()? {+ Event::Key(key) if key.kind == KeyEventKind::Press => {+ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);+ match key.code {+ KeyCode::Char('q') | KeyCode::Esc => return Ok(()),+ KeyCode::Char('c') if ctrl => return Ok(()),+ KeyCode::Char('c') => cycle_theme(),+ KeyCode::Char('b') => toggle_background(),+ KeyCode::Char('i') => toggle_info(),+ KeyCode::Char('+') | KeyCode::Char('=') => speed_up(),+ KeyCode::Char('-') | KeyCode::Char('_') => slow_down(),+ _ => {},+ }+ redraw = true;+ },+ Event::Resize(_, _) => redraw = true,+ _ => {},+ }+ }+ }+}diff --git a/crates/kanshi/src/net_interface.rs b/crates/kanshi/src/net_interface.rsnew file mode 100644index 000000000..7474eaca0--- /dev/null+++ b/crates/kanshi/src/net_interface.rs@@ -0,0 +1,5 @@+pub(crate) struct NetInterface {+ pub(crate) name: String,+ pub(crate) down: f64,+ pub(crate) up: f64,+}diff --git a/crates/kanshi/src/panels.rs b/crates/kanshi/src/panels.rsnew file mode 100644index 000000000..29f3d784a--- /dev/null+++ b/crates/kanshi/src/panels.rs@@ -0,0 +1,303 @@+use keisoku::Device;+use ratatui::{+ Frame,+ layout::{Constraint, Direction, Layout, Rect},+ style::Style,+ text::Line,+ widgets::{Block, BorderType, Borders, List, ListItem, Paragraph},+};++use crate::{+ chart::render_chart,+ format::{battery_status, format_uptime, human_bytes},+ info::render_info,+ state::{accent, background, interval_ms, show_info, theme},+ telemetry::Telemetry,+ widgets::{panel, split_horizontal, split_vertical},+};++pub(crate) fn draw(+ frame: &mut Frame,+ state: &Telemetry,+) {+ let outer = Block::default()+ .borders(Borders::ALL)+ .border_type(BorderType::Rounded)+ .style(Style::default().bg(background()))+ .border_style(Style::default().fg(accent()))+ .title_style(Style::default().fg(accent()))+ .title_top(Line::from(header_title(state.device.as_ref())))+ .title_top(Line::from(format!(" {} ", env!("CARGO_PKG_VERSION"))).right_aligned())+ .title_bottom(Line::from(format!(" {} ", theme().0)))+ .title_bottom(Line::from(" Info: i · Color: c · BG: b · Exit: q ").centered())+ .title_bottom(Line::from(format!(" -/+ {}ms ", interval_ms())).right_aligned());+ let area = outer.inner(frame.area());+ frame.render_widget(outer, frame.area());++ if show_info() {+ render_info(frame, area, state);+ return;+ }++ let rows = Layout::default()+ .direction(Direction::Vertical)+ .constraints([Constraint::Percentage(25), Constraint::Percentage(50), Constraint::Percentage(25)])+ .split(area);++ let top = split_horizontal(rows[0], [Constraint::Percentage(50), Constraint::Percentage(50)]);+ render_chart(frame, top[0], cpu_title(state), &state.cpu_history, 100.0);+ render_chart(frame, top[1], gpu_title(state), &state.gpu_history, 100.0);++ let middle = split_horizontal(rows[1], [Constraint::Percentage(50), Constraint::Percentage(50)]);++ let left = split_vertical(middle[0], [Constraint::Percentage(50), Constraint::Percentage(50)]);+ render_chart(frame, left[0], ane_title(state), &state.ane_history, 100.0);+ let left_bottom = split_horizontal(left[1], [Constraint::Percentage(50), Constraint::Percentage(50)]);+ render_power(frame, left_bottom[0], state);+ render_chart(frame, left_bottom[1], power_title(state), &state.power_history, state.max_power);++ let right = split_vertical(middle[1], [Constraint::Percentage(50), Constraint::Percentage(50)]);+ render_chart(frame, right[0], memory_title(state), &state.memory_history, 100.0);+ let right_bottom = split_horizontal(right[1], [Constraint::Percentage(50), Constraint::Percentage(50)]);+ render_model(frame, right_bottom[0], state);+ render_fans(frame, right_bottom[1], state);++ let bottom = split_horizontal(+ rows[2],+ [+ Constraint::Percentage(40),+ Constraint::Percentage(20),+ Constraint::Percentage(20),+ Constraint::Percentage(20),+ ],+ );+ render_processes(frame, bottom[0], state);+ render_io(frame, bottom[1], state);+ render_disk(frame, bottom[2], state);+ render_network(frame, bottom[3], state);+}++fn cpu_title(state: &Telemetry) -> String {+ let cpu = state.snapshot.as_ref().and_then(|s| s.cpu.as_ref());+ let temperature =+ state.snapshot.as_ref().and_then(|s| s.temperatures.as_ref()).and_then(|t| t.cpu_average).map(|c| c.value());+ match (cpu, state.device.as_ref()) {+ (Some(cpu), Some(device)) => format!(+ "{} Cores ({}E/{}P) {:.2}% @ E{:.1}/P{:.1} GHz ({:.0}°C)",+ device.efficiency_cores + device.performance_cores,+ device.efficiency_cores,+ device.performance_cores,+ cpu.usage.value(),+ cpu.ecpu_frequency.value() as f64 / 1000.0,+ cpu.pcpu_frequency.value() as f64 / 1000.0,+ temperature.unwrap_or(0.0),+ ),+ _ => "CPU Usage".to_string(),+ }+}++fn gpu_title(state: &Telemetry) -> String {+ let temperature =+ state.snapshot.as_ref().and_then(|s| s.temperatures.as_ref()).and_then(|t| t.gpu_average).map(|c| c.value());+ match state.snapshot.as_ref().and_then(|s| s.gpu.as_ref()) {+ Some(gpu) => format!(+ "GPU Usage: {:.0}% @ {} MHz ({:.0}°C)",+ gpu.usage.value(),+ gpu.frequency.value(),+ temperature.unwrap_or(0.0),+ ),+ None => "GPU Usage".to_string(),+ }+}++fn ane_title(state: &Telemetry) -> String {+ match state.snapshot.as_ref().and_then(|s| s.neural_engine.as_ref()) {+ Some(ane) => format!("ANE Usage: {:.2}% @ {:.2} W", ane.active.value(), ane.power.value()),+ None => "ANE Usage".to_string(),+ }+}++fn memory_title(state: &Telemetry) -> String {+ let bandwidth = state+ .snapshot+ .as_ref()+ .and_then(|s| s.bandwidth.as_ref())+ .map(|b| b.dram_read.value() + b.dram_write.value())+ .unwrap_or(0.0);+ match state.snapshot.as_ref().and_then(|s| s.memory.as_ref()) {+ Some(memory) => format!(+ "Mem: {:.2} GB / {:.2} GB (Swap: {:.2}/{:.2} GB) BW: {:.1} GB/s",+ memory.ram_usage.value() as f64 / 1e9,+ memory.ram_total.value() as f64 / 1e9,+ memory.swap_usage.value() as f64 / 1e9,+ memory.swap_total.value() as f64 / 1e9,+ bandwidth,+ ),+ None => "Memory Usage".to_string(),+ }+}++fn power_title(state: &Telemetry) -> String {+ let current = state.power_history.back().copied().unwrap_or(0.0);+ format!("{current:.2} W Total (Max: {:.2} W)", state.max_power)+}++fn render_power(+ frame: &mut Frame,+ area: Rect,+ state: &Telemetry,+) {+ let mut lines = Vec::new();+ if let Some(power) = state.snapshot.as_ref().and_then(|s| s.power.as_ref()) {+ lines.push(Line::from(format!(+ "{:<6}{:>6.2} W | {:<5}{:>6.2} W",+ "CPU:",+ power.cpu.value(),+ "GPU:",+ power.gpu.value() + power.gpu_sram.value(),+ )));+ lines.push(Line::from(format!(+ "{:<6}{:>6.2} W | {:<5}{:>6.2} W",+ "ANE:",+ power.ane.value(),+ "DRAM:",+ power.ram.value(),+ )));+ lines.push(Line::from(format!("{:<6}{:>6.2} W", "Total:", power.total.value())));+ lines.push(Line::from(format!("{:<6}{:>6.2} W", "Pkg:", power.package.value())));+ }+ let thermals =+ state.snapshot.as_ref().and_then(|s| s.thermal_pressure).map(|t| format!("{t:?}")).unwrap_or_default();+ lines.push(Line::from(format!("Thermals: {thermals}")));+ lines.push(Line::from(format!("Uptime: {}", format_uptime(state.uptime_seconds))));+ if let Some(battery) = state.snapshot.as_ref().and_then(|s| s.battery.as_ref()).filter(|b| b.present) {+ let status = battery_status(battery);+ lines.push(Line::from(format!("Battery: {:.0}% ({status})", battery.percent.value())));+ }+ frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Power Usage")), area);+}++fn render_model(+ frame: &mut Frame,+ area: Rect,+ state: &Telemetry,+) {+ let mut lines = Vec::new();+ if let Some(device) = &state.device {+ lines.push(Line::from(device.chip.clone()));+ lines.push(Line::from(format!("{} Cores", device.efficiency_cores + device.performance_cores)));+ lines.push(Line::from(format!("{} E-Cores", device.efficiency_cores)));+ lines.push(Line::from(format!("{} P-Cores", device.performance_cores)));+ lines.push(Line::from(format!("{} GPU Cores", device.gpu_cores)));+ }+ frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Apple Silicon")), area);+}++fn render_fans(+ frame: &mut Frame,+ area: Rect,+ state: &Telemetry,+) {+ let mut lines = Vec::new();+ if let Some(fans) = state.snapshot.as_ref().and_then(|s| s.fans.as_ref()) {+ for (index, fan) in fans.fans.iter().enumerate() {+ lines.push(Line::from(format!("Fan {}: {:.0} rpm", index + 1, fan.actual.value())));+ lines.push(Line::from(format!(+ " range {:.0}–{:.0} · target {:.0}",+ fan.minimum.value(),+ fan.maximum.value(),+ fan.target.value(),+ )));+ }+ }+ if lines.is_empty() {+ lines.push(Line::from("no fans"));+ }+ frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Fans")), area);+}++fn render_io(+ frame: &mut Frame,+ area: Rect,+ state: &Telemetry,+) {+ let lines = vec![+ Line::from(format!("R {}/s", human_bytes(state.disk_read as u64))),+ Line::from(format!("W {}/s", human_bytes(state.disk_written as u64))),+ ];+ frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("IO")), area);+}++fn render_disk(+ frame: &mut Frame,+ area: Rect,+ state: &Telemetry,+) {+ let lines: Vec<Line> = state+ .disks+ .iter()+ .map(|disk| Line::from(format!("{}: {} / {}", disk.name, human_bytes(disk.used), human_bytes(disk.total))))+ .collect();+ frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Disk")), area);+}++fn render_network(+ frame: &mut Frame,+ area: Rect,+ state: &Telemetry,+) {+ let mut lines = vec![+ Line::from(format!(+ "{:<6}↑ {}/s ↓ {}/s",+ "Rate",+ human_bytes(state.network_up as u64),+ human_bytes(state.network_down as u64),+ )),+ Line::from(format!("{:<6}↑ {:.0}/s ↓ {:.0}/s", "Pkts", state.network_packets_up, state.network_packets_down,)),+ Line::from(format!(+ "{:<6}↑ {} ↓ {}",+ "Total",+ human_bytes(state.network_total_up),+ human_bytes(state.network_total_down),+ )),+ ];+ for iface in &state.network_interfaces {+ lines.push(Line::from(format!(+ "{:<6}↑ {}/s ↓ {}/s",+ iface.name,+ human_bytes(iface.up as u64),+ human_bytes(iface.down as u64),+ )));+ }+ frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Network")), area);+}++fn render_processes(+ frame: &mut Frame,+ area: Rect,+ state: &Telemetry,+) {+ let items: Vec<ListItem> = state+ .processes+ .iter()+ .map(|process| {+ ListItem::new(format!("{:>6.1}% {:>9} {}", process.cpu, human_bytes(process.memory), process.name))+ })+ .collect();+ frame.render_widget(List::new(items).style(Style::default().fg(accent())).block(panel("Process List")), area);+}++fn header_title(device: Option<&Device>) -> String {+ match device {+ Some(device) => format!(+ " kanshi • {} • {}C ({}E+{}P) • {} GPU • {:.0} GB ",+ device.chip,+ device.efficiency_cores + device.performance_cores,+ device.efficiency_cores,+ device.performance_cores,+ device.gpu_cores,+ device.ram_total.value() as f64 / 1e9,+ ),+ None => " kanshi ".to_string(),+ }+}diff --git a/crates/kanshi/src/process_row.rs b/crates/kanshi/src/process_row.rsnew file mode 100644index 000000000..c8df27966--- /dev/null+++ b/crates/kanshi/src/process_row.rs@@ -0,0 +1,5 @@+pub(crate) struct ProcessRow {+ pub(crate) cpu: f32,+ pub(crate) memory: u64,+ pub(crate) name: String,+}diff --git a/crates/kanshi/src/sampler.rs b/crates/kanshi/src/sampler.rsnew file mode 100644index 000000000..b5b1c5d78--- /dev/null+++ b/crates/kanshi/src/sampler.rs@@ -0,0 +1,174 @@+use std::{+ collections::{HashSet, VecDeque},+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+ time::{Duration, Instant},+};++use keisoku::Collector;+use sysinfo::{Disks, Networks, ProcessRefreshKind, ProcessesToUpdate, System};++use crate::{+ disk_row::DiskRow,+ host_info::HostInfo,+ net_interface::NetInterface,+ process_row::ProcessRow,+ state::{bump_data_version, interval},+ telemetry::Telemetry,+};++const HISTORY: usize = 256;+const PROCESS_ROWS: usize = 8;+const NETWORK_ROWS: usize = 4;+const DISK_REFRESH: Duration = Duration::from_secs(3);++pub(crate) fn sample_loop(+ telemetry: &Arc<Mutex<Telemetry>>,+ stop: &Arc<AtomicBool>,+) {+ let mut collector = Collector::new();+ let device = collector.device();+ let host = HostInfo {+ user: std::env::var("USER").unwrap_or_else(|_| "user".into()),+ hostname: System::host_name().unwrap_or_default(),+ os: System::long_os_version().unwrap_or_default(),+ kernel: System::kernel_version().unwrap_or_default(),+ shell: std::env::var("SHELL")+ .ok()+ .and_then(|path| path.rsplit('/').next().map(str::to_owned))+ .unwrap_or_default(),+ };+ if let Ok(mut state) = telemetry.lock() {+ state.device = Some(device);+ state.host = Some(host);+ }++ let mut system = System::new();+ let mut networks = Networks::new_with_refreshed_list();+ let mut all_disks = Disks::new_with_refreshed_list();+ let mut last_disk_refresh: Option<Instant> = None;++ let process_kind = ProcessRefreshKind::nothing().with_cpu().with_memory().with_disk_usage();++ // Prime so the first sample's rates span the interval rather than reading+ // each counter's whole since-boot total as if it accrued in one tick.+ system.refresh_processes_specifics(ProcessesToUpdate::All, true, process_kind);+ networks.refresh(true);+ let mut last_refresh = Instant::now();++ while !stop.load(Ordering::Relaxed) {+ let snapshot = collector.sample(interval());++ system.refresh_processes_specifics(ProcessesToUpdate::All, true, process_kind);+ networks.refresh(true);+ let elapsed = last_refresh.elapsed().as_secs_f64().max(0.001);+ last_refresh = Instant::now();++ let (mut received, mut transmitted) = (0u64, 0u64);+ let (mut packets_in, mut packets_out) = (0u64, 0u64);+ let (mut total_in, mut total_out) = (0u64, 0u64);+ let mut interfaces: Vec<NetInterface> = Vec::new();+ for (name, data) in networks.iter() {+ received += data.received();+ transmitted += data.transmitted();+ packets_in += data.packets_received();+ packets_out += data.packets_transmitted();+ total_in += data.total_received();+ total_out += data.total_transmitted();++ if data.total_received() > 0 || data.total_transmitted() > 0 {+ interfaces.push(NetInterface {+ name: name.clone(),+ down: data.received() as f64 / elapsed,+ up: data.transmitted() as f64 / elapsed,+ });+ }+ }+ interfaces.sort_by(|a, b| (b.down + b.up).partial_cmp(&(a.down + a.up)).unwrap_or(std::cmp::Ordering::Equal));+ interfaces.truncate(NETWORK_ROWS);++ let disks = last_disk_refresh.is_none_or(|at| at.elapsed() >= DISK_REFRESH).then(|| {+ last_disk_refresh = Some(Instant::now());+ all_disks.refresh(true);+ let mut seen_disks = HashSet::new();+ all_disks+ .list()+ .iter()+ .filter(|disk| seen_disks.insert(disk.name().to_os_string()))+ .map(|disk| DiskRow {+ name: disk.name().to_string_lossy().into_owned(),+ used: disk.total_space().saturating_sub(disk.available_space()),+ total: disk.total_space(),+ })+ .collect::<Vec<_>>()+ });++ let (mut disk_read, mut disk_written) = (0u64, 0u64);+ for process in system.processes().values() {+ let io = process.disk_usage();+ disk_read += io.read_bytes;+ disk_written += io.written_bytes;+ }++ let mut processes = system+ .processes()+ .values()+ .map(|process| ProcessRow {+ cpu: process.cpu_usage(),+ memory: process.memory(),+ name: process.name().to_string_lossy().into_owned(),+ })+ .collect::<Vec<_>>();+ processes.sort_by(|a, b| b.cpu.partial_cmp(&a.cpu).unwrap_or(std::cmp::Ordering::Equal));+ processes.truncate(PROCESS_ROWS);++ let cpu = snapshot.cpu.as_ref().map(|c| c.usage.value() as f64).unwrap_or(0.0);+ let gpu = snapshot.gpu.as_ref().map(|g| g.usage.value() as f64).unwrap_or(0.0);+ let ane = snapshot.neural_engine.as_ref().map(|a| a.active.value() as f64).unwrap_or(0.0);+ let memory = snapshot+ .memory+ .as_ref()+ .filter(|m| m.ram_total.value() > 0)+ .map(|m| m.ram_usage.value() as f64 / m.ram_total.value() as f64 * 100.0)+ .unwrap_or(0.0);++ let power = snapshot.power.as_ref().map(|p| p.package.value() as f64).unwrap_or(0.0);++ if let Ok(mut state) = telemetry.lock() {+ push_history(&mut state.cpu_history, cpu);+ push_history(&mut state.gpu_history, gpu);+ push_history(&mut state.ane_history, ane);+ push_history(&mut state.memory_history, memory);+ push_history(&mut state.power_history, power);+ state.max_power = state.max_power.max(power);+ state.snapshot = Some(snapshot);+ state.uptime_seconds = System::uptime();+ state.network_down = received as f64 / elapsed;+ state.network_up = transmitted as f64 / elapsed;+ state.network_packets_down = packets_in as f64 / elapsed;+ state.network_packets_up = packets_out as f64 / elapsed;+ state.network_total_down = total_in;+ state.network_total_up = total_out;+ state.network_interfaces = interfaces;+ state.disk_read = disk_read as f64 / elapsed;+ state.disk_written = disk_written as f64 / elapsed;+ if let Some(disks) = disks {+ state.disks = disks;+ }+ state.processes = processes;+ }+ bump_data_version();+ }+}++fn push_history(+ history: &mut VecDeque<f64>,+ value: f64,+) {+ history.push_back(value);+ while history.len() > HISTORY {+ history.pop_front();+ }+}diff --git a/crates/kanshi/src/state.rs b/crates/kanshi/src/state.rsnew file mode 100644index 000000000..8a045de96--- /dev/null+++ b/crates/kanshi/src/state.rs@@ -0,0 +1,88 @@+use std::{+ sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},+ time::Duration,+};++use ratatui::style::Color;++const THEMES: [(&str, Color); 7] = [+ ("green", Color::Green),+ ("cyan", Color::Cyan),+ ("blue", Color::Blue),+ ("magenta", Color::Magenta),+ ("yellow", Color::Yellow),+ ("red", Color::Red),+ ("white", Color::White),+];++const MIN_INTERVAL_MS: u64 = 100;+const MAX_INTERVAL_MS: u64 = 5000;+const INTERVAL_STEP_MS: u64 = 100;++static INTERVAL_MS: AtomicU64 = AtomicU64::new(1000);+static THEME_INDEX: AtomicUsize = AtomicUsize::new(0);+static DARK_BACKGROUND: AtomicBool = AtomicBool::new(true);+static SHOW_INFO: AtomicBool = AtomicBool::new(false);+static DATA_VERSION: AtomicU64 = AtomicU64::new(0);++pub(crate) fn theme() -> (&'static str, Color) {+ THEMES[THEME_INDEX.load(Ordering::Relaxed) % THEMES.len()]+}++pub(crate) fn accent() -> Color {+ theme().1+}++pub(crate) fn background() -> Color {+ if DARK_BACKGROUND.load(Ordering::Relaxed) {+ Color::Black+ } else {+ Color::Reset+ }+}++pub(crate) fn interval() -> Duration {+ Duration::from_millis(INTERVAL_MS.load(Ordering::Relaxed))+}++pub(crate) fn interval_ms() -> u64 {+ INTERVAL_MS.load(Ordering::Relaxed)+}++pub(crate) fn cycle_theme() {+ THEME_INDEX.fetch_add(1, Ordering::Relaxed);+}++pub(crate) fn toggle_background() {+ DARK_BACKGROUND.fetch_xor(true, Ordering::Relaxed);+}++pub(crate) fn toggle_info() {+ SHOW_INFO.fetch_xor(true, Ordering::Relaxed);+}++pub(crate) fn show_info() -> bool {+ SHOW_INFO.load(Ordering::Relaxed)+}++pub(crate) fn speed_up() {+ adjust(-(INTERVAL_STEP_MS as i64));+}++pub(crate) fn slow_down() {+ adjust(INTERVAL_STEP_MS as i64);+}++fn adjust(delta: i64) {+ let current = INTERVAL_MS.load(Ordering::Relaxed) as i64;+ let next = (current + delta).clamp(MIN_INTERVAL_MS as i64, MAX_INTERVAL_MS as i64) as u64;+ INTERVAL_MS.store(next, Ordering::Relaxed);+}++pub(crate) fn bump_data_version() {+ DATA_VERSION.fetch_add(1, Ordering::Relaxed);+}++pub(crate) fn data_version() -> u64 {+ DATA_VERSION.load(Ordering::Relaxed)+}diff --git a/crates/kanshi/src/telemetry.rs b/crates/kanshi/src/telemetry.rsnew file mode 100644index 000000000..66e4660cc--- /dev/null+++ b/crates/kanshi/src/telemetry.rs@@ -0,0 +1,30 @@+use std::collections::VecDeque;++use keisoku::{Device, Snapshot};++use crate::{disk_row::DiskRow, host_info::HostInfo, net_interface::NetInterface, process_row::ProcessRow};++#[derive(Default)]+pub(crate) struct Telemetry {+ pub(crate) device: Option<Device>,+ pub(crate) host: Option<HostInfo>,+ pub(crate) snapshot: Option<Snapshot>,+ pub(crate) cpu_history: VecDeque<f64>,+ pub(crate) gpu_history: VecDeque<f64>,+ pub(crate) ane_history: VecDeque<f64>,+ pub(crate) memory_history: VecDeque<f64>,+ pub(crate) power_history: VecDeque<f64>,+ pub(crate) max_power: f64,+ pub(crate) uptime_seconds: u64,+ pub(crate) network_down: f64,+ pub(crate) network_up: f64,+ pub(crate) network_packets_down: f64,+ pub(crate) network_packets_up: f64,+ pub(crate) network_total_down: u64,+ pub(crate) network_total_up: u64,+ pub(crate) network_interfaces: Vec<NetInterface>,+ pub(crate) disk_read: f64,+ pub(crate) disk_written: f64,+ pub(crate) disks: Vec<DiskRow>,+ pub(crate) processes: Vec<ProcessRow>,+}diff --git a/crates/kanshi/src/widgets.rs b/crates/kanshi/src/widgets.rsnew file mode 100644index 000000000..e2dfe3d16--- /dev/null+++ b/crates/kanshi/src/widgets.rs@@ -0,0 +1,37 @@+use ratatui::{+ layout::{Constraint, Direction, Layout, Rect},+ style::Style,+ widgets::{Block, Borders},+};++use crate::state::accent;++pub(crate) fn panel(title: &str) -> Block<'_> {+ Block::default()+ .borders(Borders::ALL)+ .border_style(Style::default().fg(accent()))+ .title_style(Style::default().fg(accent()))+ .title(title)+}++pub(crate) fn panel_owned(title: String) -> Block<'static> {+ Block::default()+ .borders(Borders::ALL)+ .border_style(Style::default().fg(accent()))+ .title_style(Style::default().fg(accent()))+ .title(title)+}++pub(crate) fn split_horizontal<const N: usize>(+ area: Rect,+ constraints: [Constraint; N],+) -> std::rc::Rc<[Rect]> {+ Layout::default().direction(Direction::Horizontal).constraints(constraints).split(area)+}++pub(crate) fn split_vertical<const N: usize>(+ area: Rect,+ constraints: [Constraint; N],+) -> std::rc::Rc<[Rect]> {+ Layout::default().direction(Direction::Vertical).constraints(constraints).split(area)+}diff --git a/crates/keisoku/Cargo.toml b/crates/keisoku/Cargo.tomlnew file mode 100644index 000000000..eb63d28eb--- /dev/null+++ b/crates/keisoku/Cargo.toml@@ -0,0 +1,36 @@+[package]+name = "keisoku"+edition.workspace = true+rust-version.workspace = true+version.workspace = true+authors.workspace = true+homepage.workspace = true+repository.workspace = true+license.workspace = true+description = "System telemetry collector (CPU/GPU/RAM/power/sensors) for Apple platforms"++[lib]+name = "keisoku"+path = "src/lib.rs"++[lints]+workspace = true++[dependencies]+serde = { workspace = true, features = ["derive"] }+serde_json.workspace = true+sysinfo.workspace = true++# Used only by the on-device `table` test to render a snapshot via TestBackend.+[dev-dependencies]+ratatui.workspace = true++[target.'cfg(target_vendor = "apple")'.dependencies]+kanka.workspace = true+objc2-core-foundation.workspace = true+obfstr.workspace = true+libc.workspace = true++# IOReport/SoC traversal is macOS-only; IOKit service iteration via objc2-io-kit.+[target.'cfg(target_os = "macos")'.dependencies]+objc2-io-kit.workspace = truediff --git a/crates/keisoku/build.rs b/crates/keisoku/build.rsnew file mode 100644index 000000000..cca77318e--- /dev/null+++ b/crates/keisoku/build.rs@@ -0,0 +1,10 @@+fn main() {+ // IOReport private symbols are resolved at runtime via `kanka` (dlsym), so+ // only the public IOKit + CoreFoundation symbols (IOService*/IORegistry*, CF*)+ // are linked here. macOS only — iOS sandboxes IOReport/IORegistry telemetry.+ let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();+ if target_os == "macos" {+ println!("cargo:rustc-link-lib=framework=IOKit");+ println!("cargo:rustc-link-lib=framework=CoreFoundation");+ }+}diff --git a/crates/keisoku/src/cf/mod.rs b/crates/keisoku/src/cf/mod.rsnew file mode 100644index 000000000..5b80e3838--- /dev/null+++ b/crates/keisoku/src/cf/mod.rs@@ -0,0 +1,56 @@+use core::{ffi::c_void, ptr::NonNull};++use objc2_core_foundation::{CFData, CFDictionary, CFRetained, CFString, CFType, ConcreteType};++mod service_iterator;++pub use service_iterator::IoServiceIterator;++/// Convert a borrowed (Get-rule) `CFStringRef` returned by a C accessor into an+/// owned `String`. Used by the IOReport channel accessors, whose C functions+/// hand back a borrowed `CFStringRef` as `*const c_void`.+pub fn cf_string_to_string(value: *const c_void) -> String {+ match NonNull::new(value.cast_mut().cast::<CFString>()) {+ Some(pointer) => unsafe { pointer.as_ref() }.to_string(),+ None => String::new(),+ }+}++/// Look up `key` in a CF dictionary and downcast its value to the concrete CF+/// type `V`. The `<K, V>` generics on `CFDictionary` are `PhantomData`, so+/// viewing the opaque dictionary as `<CFString, CFType>` is a layout-sound+/// reference cast.+pub fn dictionary_get<V: ConcreteType>(+ dictionary: &CFDictionary,+ key: &str,+) -> Option<CFRetained<V>> {+ let dictionary: &CFDictionary<CFString, CFType> = unsafe { &*(dictionary as *const CFDictionary).cast() };+ dictionary.get(&CFString::from_str(key)).and_then(|value| value.downcast::<V>().ok())+}++/// Bytes of a `CFData`-valued key, or `None` if the key is absent or not data.+pub fn dictionary_data(+ dictionary: &CFDictionary,+ key: &str,+) -> Option<Vec<u8>> {+ dictionary_get::<CFData>(dictionary, key).map(|data| cf_data_to_vec(&data))+}++fn cf_data_to_vec(data: &CFData) -> Vec<u8> {+ let length = data.length();+ let bytes = data.byte_ptr();+ if length <= 0 || bytes.is_null() {+ return Vec::new();+ }+ unsafe { core::slice::from_raw_parts(bytes, length as usize) }.to_vec()+}++pub fn registry_properties(entry: objc2_io_kit::io_registry_entry_t) -> Option<CFRetained<CFDictionary>> {+ let mut properties = core::ptr::null_mut();+ let result = unsafe { objc2_io_kit::IORegistryEntryCreateCFProperties(entry, &mut properties, None, 0) };+ if result != 0 {+ return None;+ }+ let mutable = unsafe { CFRetained::from_raw(NonNull::new(properties)?) };+ Some(unsafe { CFRetained::from_raw(CFRetained::into_raw(mutable).cast()) })+}diff --git a/crates/keisoku/src/cf/service_iterator.rs b/crates/keisoku/src/cf/service_iterator.rsnew file mode 100644index 000000000..59f076ca0--- /dev/null+++ b/crates/keisoku/src/cf/service_iterator.rs@@ -0,0 +1,61 @@+use core::ffi::{CStr, c_char};++use objc2_core_foundation::CFRetained;+use objc2_io_kit::{+ IOIteratorNext, IOObjectRelease, IORegistryEntryGetName, IOServiceGetMatchingServices, IOServiceMatching,+ io_iterator_t, io_object_t, io_registry_entry_t,+};++pub struct IoServiceIterator {+ iterator: io_iterator_t,+ current_entry: io_object_t,+}++impl IoServiceIterator {+ pub fn new(service_name: &str) -> Option<Self> {+ let name = std::ffi::CString::new(service_name).ok()?;++ let matching = unsafe { IOServiceMatching(name.as_ptr()) }?;+ let matching = unsafe { CFRetained::from_raw(CFRetained::into_raw(matching).cast()) };+ let mut iterator: io_iterator_t = 0;+ let result = unsafe { IOServiceGetMatchingServices(0, Some(matching), &mut iterator) };+ if result != 0 {+ return None;+ }+ Some(Self {+ iterator,+ current_entry: 0,+ })+ }+}++impl Drop for IoServiceIterator {+ fn drop(&mut self) {+ if self.current_entry != 0 {+ IOObjectRelease(self.current_entry);+ }+ IOObjectRelease(self.iterator);+ }+}++impl Iterator for IoServiceIterator {+ type Item = (io_registry_entry_t, String);++ fn next(&mut self) -> Option<Self::Item> {+ if self.current_entry != 0 {+ IOObjectRelease(self.current_entry);+ self.current_entry = 0;+ }+ let entry = IOIteratorNext(self.iterator);+ if entry == 0 {+ return None;+ }+ self.current_entry = entry;+ let mut name_buffer = [0 as c_char; 128];+ if unsafe { IORegistryEntryGetName(entry, &mut name_buffer) } != 0 {+ return None;+ }+ let name = unsafe { CStr::from_ptr(name_buffer.as_ptr()) }.to_string_lossy().into_owned();+ Some((entry, name))+ }+}diff --git a/crates/keisoku/src/client/event_system_client.rs b/crates/keisoku/src/client/event_system_client.rsnew file mode 100644index 000000000..36ade95ea--- /dev/null+++ b/crates/keisoku/src/client/event_system_client.rs@@ -0,0 +1,58 @@+use core::ptr::NonNull;++use obfstr::obfstr;+use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFRetained, CFString};++use super::{IOHIDEventSystemClient, IOHIDServiceClient, IOKit, service_client::ServiceClient};++pub(super) struct EventSystemClient {+ io_kit: &'static IOKit,+ inner: CFRetained<IOHIDEventSystemClient>,+}++impl EventSystemClient {+ pub(super) fn new() -> Option<Self> {+ let io_kit = IOKit::get()?;+ let pointer = unsafe { (io_kit.create)(None) };+ let inner = unsafe { CFRetained::from_raw(NonNull::new(pointer)?) };+ Some(Self {+ io_kit,+ inner,+ })+ }++ /// Match HID services for the given usage page/usage and return them as+ /// owning [`ServiceClient`]s. `CFArray::to_vec` retains each element, so the+ /// returned clients no longer depend on the matched array staying alive.+ pub(super) fn services(+ &self,+ page: i32,+ usage: i32,+ ) -> Vec<ServiceClient> {+ let io_kit = self.io_kit;+ let Some(array) = self.services_matching(page, usage) else {+ return Vec::new();+ };+ array.to_vec().into_iter().map(|inner| ServiceClient::new(io_kit, inner)).collect()+ }++ fn services_matching(+ &self,+ page: i32,+ usage: i32,+ ) -> Option<CFRetained<CFArray<IOHIDServiceClient>>> {+ let page_key = CFString::from_str(obfstr!("PrimaryUsagePage"));+ let usage_key = CFString::from_str(obfstr!("PrimaryUsage"));+ let page_value = CFNumber::new_i32(page);+ let usage_value = CFNumber::new_i32(usage);+ let matching = CFDictionary::from_slices(&[&*page_key, &*usage_key], &[&*page_value, &*usage_value]);++ let _ = unsafe { (self.io_kit.set_matching)(&self.inner, &matching) };++ // `CFArray`'s generic is `PhantomData`, so typing the matched array as+ // `CFArray<IOHIDServiceClient>` is a layout-sound pointer cast.+ let services = unsafe { (self.io_kit.copy_services)(&self.inner) };+ let services = NonNull::new(services.cast::<CFArray<IOHIDServiceClient>>())?;+ Some(unsafe { CFRetained::from_raw(services) })+ }+}diff --git a/crates/keisoku/src/client/mod.rs b/crates/keisoku/src/client/mod.rsnew file mode 100644index 000000000..a510610c7--- /dev/null+++ b/crates/keisoku/src/client/mod.rs@@ -0,0 +1,162 @@+use std::time::{Duration, Instant};++use obfstr::obfstr;+use objc2_core_foundation::{CFAllocator, CFArray, CFDictionary, CFNumber, CFString, CFType};++use self::{event_system_client::EventSystemClient, service_client::ServiceClient};+use crate::{+ component::{Component, classify},+ sensor::{Sensor, SensorKind},+ sys,+};++const COLD_REFRESH: Duration = Duration::from_millis(3000);++fn is_hot(component: Component) -> bool {+ matches!(component, Component::Cpu | Component::Gpu | Component::Soc | Component::NeuralEngine)+}++kanka::opaque_cf_type!(IOHIDEventSystemClient);+kanka::opaque_cf_type!(IOHIDServiceClient);+kanka::opaque_cf_type!(IOHIDEvent);++kanka::ffi_table! {+ struct IOKit from "/System/Library/Frameworks/IOKit.framework/IOKit" {+ create = "IOHIDEventSystemClientCreate":+ unsafe extern "C" fn(Option<&CFAllocator>) -> *mut IOHIDEventSystemClient,+ set_matching = "IOHIDEventSystemClientSetMatching":+ unsafe extern "C" fn(&IOHIDEventSystemClient, &CFDictionary<CFString, CFNumber>) -> i32,+ copy_services = "IOHIDEventSystemClientCopyServices":+ unsafe extern "C" fn(&IOHIDEventSystemClient) -> *mut CFArray,+ copy_property = "IOHIDServiceClientCopyProperty":+ unsafe extern "C" fn(&IOHIDServiceClient, &CFString) -> *mut CFType,+ copy_event = "IOHIDServiceClientCopyEvent":+ unsafe extern "C" fn(&IOHIDServiceClient, i64, i32, i64) -> *mut IOHIDEvent,+ get_float_value = "IOHIDEventGetFloatValue":+ unsafe extern "C" fn(&IOHIDEvent, i32) -> f64,+ get_registry_id = "IOHIDServiceClientGetRegistryID":+ unsafe extern "C" fn(&IOHIDServiceClient) -> u64,+ }+}++mod event_system_client;+mod service_client;++pub(crate) fn is_available() -> bool {+ IOKit::get().is_some()+}++pub(crate) fn collect(kind: SensorKind) -> Vec<Sensor> {+ let Some(client) = EventSystemClient::new() else {+ return Vec::new();+ };+ let (page, usage) = kind.matching();+ let event_type = kind.event_type();+ let event_field = sys::event_field_base(event_type);++ let mut readings = Vec::new();+ for service in client.services(page, usage) {+ let Some(value) = service.f64_value(event_type, event_field) else {+ continue;+ };+ let name = service.string(obfstr!("Product")).unwrap_or_default();+ readings.push(Sensor {+ component: classify(&name),+ manufacturer: service.string(obfstr!("Manufacturer")),+ category: service.string(obfstr!("Category")),+ location_id: service.i64_value(obfstr!("LocationID")),+ registry_id: service.registry_id(),+ name,+ value,+ kind,+ });+ }+ readings+}++struct CachedSensor {+ service: ServiceClient,+ name: String,+ component: Component,+ manufacturer: Option<String>,+ category: Option<String>,+ location_id: Option<i64>,+ registry_id: u64,+ hot: bool,+ value: f64,+}++pub(crate) struct SensorReader {+ kind: SensorKind,+ event_type: i64,+ event_field: i32,+ sensors: Vec<CachedSensor>,+ last_cold_read: Option<Instant>,+ _client: EventSystemClient,+}++impl SensorReader {+ pub(crate) fn new(kind: SensorKind) -> Option<Self> {+ let client = EventSystemClient::new()?;+ let (page, usage) = kind.matching();+ let event_type = kind.event_type();+ let event_field = sys::event_field_base(event_type);++ let mut sensors = Vec::new();+ for service in client.services(page, usage) {+ let Some(value) = service.f64_value(event_type, event_field) else {+ continue;+ };+ let name = service.string(obfstr!("Product")).unwrap_or_default();+ let component = classify(&name);+ sensors.push(CachedSensor {+ manufacturer: service.string(obfstr!("Manufacturer")),+ category: service.string(obfstr!("Category")),+ location_id: service.i64_value(obfstr!("LocationID")),+ registry_id: service.registry_id(),+ hot: is_hot(component),+ component,+ name,+ value,+ service,+ });+ }++ Some(Self {+ kind,+ event_type,+ event_field,+ sensors,+ last_cold_read: None,+ _client: client,+ })+ }++ pub(crate) fn read(&mut self) -> Vec<Sensor> {+ let refresh_cold = self.last_cold_read.is_none_or(|at| at.elapsed() >= COLD_REFRESH);+ if refresh_cold {+ self.last_cold_read = Some(Instant::now());+ }+ let (kind, event_type, event_field) = (self.kind, self.event_type, self.event_field);+ self.sensors+ .iter_mut()+ .map(|cached| {+ let refreshed =+ (cached.hot || refresh_cold).then(|| cached.service.f64_value(event_type, event_field)).flatten();+ if let Some(value) = refreshed {+ cached.value = value;+ }+ Sensor {+ component: cached.component,+ manufacturer: cached.manufacturer.clone(),+ category: cached.category.clone(),+ location_id: cached.location_id,+ registry_id: cached.registry_id,+ name: cached.name.clone(),+ value: cached.value,+ kind,+ }+ })+ .collect()+ }+}diff --git a/crates/keisoku/src/client/service_client.rs b/crates/keisoku/src/client/service_client.rsnew file mode 100644index 000000000..b7f26f700--- /dev/null+++ b/crates/keisoku/src/client/service_client.rs@@ -0,0 +1,60 @@+use core::ptr::NonNull;++use objc2_core_foundation::{CFNumber, CFRetained, CFString, CFType, ConcreteType};++use super::{IOHIDEvent, IOHIDServiceClient, IOKit};++pub(super) struct ServiceClient {+ io_kit: &'static IOKit,+ inner: CFRetained<IOHIDServiceClient>,+}++impl ServiceClient {+ pub(super) fn new(+ io_kit: &'static IOKit,+ inner: CFRetained<IOHIDServiceClient>,+ ) -> Self {+ Self {+ io_kit,+ inner,+ }+ }++ fn property<T: ConcreteType>(+ &self,+ key: &str,+ ) -> Option<CFRetained<T>> {+ let key = CFString::from_str(key);+ let value = unsafe { (self.io_kit.copy_property)(&self.inner, &key) };+ let value: CFRetained<CFType> = unsafe { CFRetained::from_raw(NonNull::new(value)?) };+ value.downcast::<T>().ok()+ }++ pub(super) fn string(+ &self,+ key: &str,+ ) -> Option<String> {+ self.property::<CFString>(key).map(|string| string.to_string())+ }++ pub(super) fn i64_value(+ &self,+ key: &str,+ ) -> Option<i64> {+ self.property::<CFNumber>(key).and_then(|number| number.as_i64())+ }++ pub(super) fn f64_value(+ &self,+ event_type: i64,+ event_field: i32,+ ) -> Option<f64> {+ let event = unsafe { (self.io_kit.copy_event)(&self.inner, event_type, 0, 0) };+ let event: CFRetained<IOHIDEvent> = unsafe { CFRetained::from_raw(NonNull::new(event)?) };+ Some(unsafe { (self.io_kit.get_float_value)(&event, event_field) })+ }++ pub(super) fn registry_id(&self) -> u64 {+ unsafe { (self.io_kit.get_registry_id)(&self.inner) }+ }+}diff --git a/crates/keisoku/src/collector.rs b/crates/keisoku/src/collector.rsnew file mode 100644index 000000000..78f055162--- /dev/null+++ b/crates/keisoku/src/collector.rs@@ -0,0 +1,184 @@+use std::time::Duration;++#[cfg(target_os = "macos")]+use crate::units::{GigabytesPerSecond, Megahertz, Percent, Watts};+use crate::{+ metrics::{BandwidthMetrics, CpuMetrics, GpuMetrics, NeuralEngineMetrics, PowerMetrics, Temperatures},+ sensor::{Sensor, SensorKind},+ snapshot::Snapshot,+ units::{Celsius, Milliseconds},+};++#[derive(Default)]+struct SocMetrics {+ cpu: Option<CpuMetrics>,+ gpu: Option<GpuMetrics>,+ neural_engine: Option<NeuralEngineMetrics>,+ power: Option<PowerMetrics>,+ bandwidth: Option<BandwidthMetrics>,+}++pub struct Collector {+ #[cfg(target_os = "macos")]+ soc: Option<crate::soc::SocInfo>,+ #[cfg(target_os = "macos")]+ ioreport: Option<crate::ioreport::IoReport>,+ #[cfg(target_os = "macos")]+ cpu_load: crate::cpu_load::CpuLoad,+ #[cfg(target_os = "macos")]+ smc: Option<crate::smc::Smc>,+ #[cfg(target_vendor = "apple")]+ temperature_reader: Option<crate::client::SensorReader>,+}++impl Default for Collector {+ fn default() -> Self {+ Self::new()+ }+}++impl Collector {+ pub fn new() -> Self {+ Self {+ #[cfg(target_os = "macos")]+ soc: crate::soc::SocInfo::new(),+ #[cfg(target_os = "macos")]+ ioreport: crate::ioreport::IoReport::new(),+ #[cfg(target_os = "macos")]+ cpu_load: crate::cpu_load::CpuLoad::new(),+ #[cfg(target_os = "macos")]+ smc: crate::smc::Smc::new(),+ #[cfg(target_vendor = "apple")]+ temperature_reader: crate::client::SensorReader::new(SensorKind::Temperature),+ }+ }++ #[cfg(target_os = "macos")]+ pub fn soc(&self) -> Option<&crate::soc::SocInfo> {+ self.soc.as_ref()+ }++ pub fn device(&self) -> crate::Device {+ crate::Device::detect(self)+ }++ pub fn sample(+ &mut self,+ interval: Duration,+ ) -> Snapshot {+ let soc = self.sample_soc(interval);+ let memory = crate::metrics::read_memory();+ let fans = self.read_fans();+ let battery = crate::metrics::read_battery();+ let thermal_pressure = crate::metrics::read_thermal_pressure();+ #[cfg(target_vendor = "apple")]+ let sensors = self.temperature_reader.as_mut().map(crate::client::SensorReader::read).unwrap_or_default();+ #[cfg(not(target_vendor = "apple"))]+ let sensors = crate::sensors(SensorKind::Temperature);+ let temperatures = (!sensors.is_empty()).then(|| temperatures_from(&sensors));+ Snapshot {+ elapsed: Milliseconds(0),+ cpu: soc.cpu,+ gpu: soc.gpu,+ neural_engine: soc.neural_engine,+ power: soc.power,+ memory,+ bandwidth: soc.bandwidth,+ fans,+ battery,+ temperatures,+ thermal_pressure,+ sensors,+ }+ }++ #[cfg(target_os = "macos")]+ fn sample_soc(+ &mut self,+ interval: Duration,+ ) -> SocMetrics {+ let (Some(ioreport), Some(soc)) = (&self.ioreport, &self.soc) else {+ std::thread::sleep(interval);+ return SocMetrics::default();+ };+ let sample = ioreport.sample(soc, interval);+ let per_core = self.cpu_load.sample();+ let package = self.smc.as_ref().and_then(|smc| smc.package_watts()).unwrap_or(Watts(sample.total_power));+ SocMetrics {+ cpu: Some(CpuMetrics {+ usage: Percent(sample.cpu_usage_percent * 100.0),+ ecpu_frequency: Megahertz(sample.ecpu_usage.0),+ ecpu_usage: Percent(sample.ecpu_usage.1 * 100.0),+ pcpu_frequency: Megahertz(sample.pcpu_usage.0),+ pcpu_usage: Percent(sample.pcpu_usage.1 * 100.0),+ per_core,+ }),+ gpu: Some(GpuMetrics {+ frequency: Megahertz(sample.gpu_usage.0),+ usage: Percent(sample.gpu_usage.1 * 100.0),+ }),+ neural_engine: Some(NeuralEngineMetrics {+ power: Watts(sample.ane_power),+ active: Percent(sample.ane_active_percent),+ read_bandwidth: GigabytesPerSecond(sample.ane_read_gbps),+ write_bandwidth: GigabytesPerSecond(sample.ane_write_gbps),+ }),+ power: Some(PowerMetrics {+ cpu: Watts(sample.cpu_power),+ gpu: Watts(sample.gpu_power),+ gpu_sram: Watts(sample.gpu_ram_power),+ ane: Watts(sample.ane_power),+ ram: Watts(sample.ram_power),+ total: Watts(sample.total_power),+ package,+ }),+ bandwidth: Some(BandwidthMetrics {+ dram_read: GigabytesPerSecond(sample.dram_read_gbps),+ dram_write: GigabytesPerSecond(sample.dram_write_gbps),+ }),+ }+ }++ #[cfg(not(target_os = "macos"))]+ fn sample_soc(+ &mut self,+ interval: Duration,+ ) -> SocMetrics {+ std::thread::sleep(interval);+ SocMetrics::default()+ }++ #[cfg(target_os = "macos")]+ fn read_fans(&self) -> Option<crate::metrics::FanMetrics> {+ self.smc.as_ref().map(|smc| smc.fans())+ }++ #[cfg(not(target_os = "macos"))]+ fn read_fans(&self) -> Option<crate::metrics::FanMetrics> {+ None+ }+}++fn average(values: &[f32]) -> f32 {+ if values.is_empty() {+ 0.0+ } else {+ values.iter().sum::<f32>() / values.len() as f32+ }+}++fn temperatures_from(sensors: &[Sensor]) -> Temperatures {+ use crate::Component;+ let average_of = |components: &[Component]| {+ let values: Vec<f32> = sensors+ .iter()+ .filter(|sensor| components.contains(&sensor.component) && (1.0..150.0).contains(&sensor.value))+ .map(|sensor| sensor.value as f32)+ .collect();+ (!values.is_empty()).then(|| Celsius(average(&values)))+ };+ Temperatures {+ cpu_average: average_of(&[Component::Cpu, Component::Soc]),+ gpu_average: average_of(&[Component::Gpu]),+ }+}diff --git a/crates/keisoku/src/component.rs b/crates/keisoku/src/component.rsnew file mode 100644index 000000000..f7020e698--- /dev/null+++ b/crates/keisoku/src/component.rs@@ -0,0 +1,127 @@+use core::fmt;++use serde::{Deserialize, Serialize};++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum Component {+ Cpu,+ Gpu,+ NeuralEngine,+ Soc,+ PowerManagementUnit,+ Charger,+ Battery,+ Storage,+ Display,+ Unknown,+}++impl Component {+ pub fn label(self) -> &'static str {+ match self {+ Component::Cpu => "CPU",+ Component::Gpu => "GPU",+ Component::NeuralEngine => "Neural Engine",+ Component::Soc => "SoC",+ Component::PowerManagementUnit => "Power Management Unit",+ Component::Charger => "Charger",+ Component::Battery => "Battery",+ Component::Storage => "Storage",+ Component::Display => "Display",+ Component::Unknown => "Unknown",+ }+ }+}++impl fmt::Display for Component {+ fn fmt(+ &self,+ formatter: &mut fmt::Formatter<'_>,+ ) -> fmt::Result {+ formatter.write_str(self.label())+ }+}++pub fn classify(name: &str) -> Component {+ let name = name.to_ascii_lowercase();++ if name.contains("battery") || name.contains("gas gauge") || name.contains("fuel gauge") {+ return Component::Battery;+ }+ if name.contains("charger") {+ return Component::Charger;+ }+ if name.contains("nand") || name.contains("ssd") || name.contains("flash") {+ return Component::Storage;+ }+ if name.contains("display") || name.contains("lcd") || name.contains("oled") || name.contains("backlight") {+ return Component::Display;+ }+ if name.contains("ane") || name.contains("neural") {+ return Component::NeuralEngine;+ }+ if name.contains("gpu") || thermal_probe_block(&name) == Some('g') {+ return Component::Gpu;+ }+ if name.contains("cpu") || name.contains("pcore") || name.contains("ecore") {+ return Component::Cpu;+ }+ if name.contains("soc")+ || name.contains("tdie")+ || name.contains("tjunc")+ || thermal_probe_block(&name) == Some('s')+ {+ return Component::Soc;+ }+ if name.contains("pmu")+ || name.contains("tdev")+ || name.contains("tcal")+ || name.contains("buck")+ || name.contains("ldo")+ {+ return Component::PowerManagementUnit;+ }+ Component::Unknown+}++fn thermal_probe_block(name: &str) -> Option<char> {+ name.split_whitespace().find_map(|token| {+ let rest = token.strip_prefix("tp")?;+ let block = rest.chars().last()?;+ let digits = &rest[..rest.len() - block.len_utf8()];+ if block.is_ascii_alphabetic() && !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) {+ Some(block)+ } else {+ None+ }+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn classifies_observed_names() {+ assert_eq!(classify("gas gauge battery"), Component::Battery);+ assert_eq!(classify("NAND CH0 temp"), Component::Storage);+ assert_eq!(classify("PMU TP3g"), Component::Gpu);+ assert_eq!(classify("PMU TP1s"), Component::Soc);+ assert_eq!(classify("PMU tdie1"), Component::Soc);+ assert_eq!(classify("PMU tjunc"), Component::Soc);+ assert_eq!(classify("PMU tdev1"), Component::PowerManagementUnit);+ assert_eq!(classify("PMU tcal"), Component::PowerManagementUnit);+ assert_eq!(classify("PMU vbuck0"), Component::PowerManagementUnit);+ assert_eq!(classify("PMU ildo3"), Component::PowerManagementUnit);+ assert_eq!(classify("Charger TQ0j"), Component::Charger);+ assert_eq!(classify("ANE temp"), Component::NeuralEngine);+ assert_eq!(classify("GPU die"), Component::Gpu);+ assert_eq!(classify("something weird"), Component::Unknown);+ }++ #[test]+ fn labels_are_human_readable() {+ assert_eq!(Component::NeuralEngine.label(), "Neural Engine");+ assert_eq!(Component::PowerManagementUnit.to_string(), "Power Management Unit");+ }+}diff --git a/crates/keisoku/src/cpu_load.rs b/crates/keisoku/src/cpu_load.rsnew file mode 100644index 000000000..371b7693a--- /dev/null+++ b/crates/keisoku/src/cpu_load.rs@@ -0,0 +1,86 @@+use crate::units::Percent;++const STATES: usize = libc::CPU_STATE_MAX as usize;++pub struct CpuLoad {+ last: Vec<[u64; STATES]>,+}++impl CpuLoad {+ pub fn new() -> Self {+ Self {+ last: Vec::new(),+ }+ }++ pub fn sample(&mut self) -> Vec<Percent> {+ let Some(ticks) = read_ticks() else {+ return Vec::new();+ };+ if ticks.len() != self.last.len() {+ self.last = ticks;+ return vec![Percent(0.0); self.last.len()];+ }+ let usage = ticks+ .iter()+ .zip(&self.last)+ .map(|(current, previous)| {+ let delta = |state: usize| current[state].saturating_sub(previous[state]) as f64;+ let active = delta(libc::CPU_STATE_USER as usize)+ + delta(libc::CPU_STATE_SYSTEM as usize)+ + delta(libc::CPU_STATE_NICE as usize);+ let total = active + delta(libc::CPU_STATE_IDLE as usize);+ let percent = if total > 0.0 {+ (active / total * 100.0) as f32+ } else {+ 0.0+ };+ Percent(percent.clamp(0.0, 100.0))+ })+ .collect();+ self.last = ticks;+ usage+ }+}++#[allow(deprecated)]+fn read_ticks() -> Option<Vec<[u64; STATES]>> {+ let mut cpu_count: libc::natural_t = 0;+ let mut info: libc::processor_info_array_t = core::ptr::null_mut();+ let mut info_count: libc::mach_msg_type_number_t = 0;+ let result = unsafe {+ libc::host_processor_info(+ libc::mach_host_self(),+ libc::PROCESSOR_CPU_LOAD_INFO,+ &mut cpu_count,+ &mut info,+ &mut info_count,+ )+ };+ if result != libc::KERN_SUCCESS || info.is_null() {+ return None;+ }++ let loads =+ unsafe { core::slice::from_raw_parts(info as *const libc::processor_cpu_load_info, cpu_count as usize) };+ let ticks = loads+ .iter()+ .map(|load| {+ [+ load.cpu_ticks[libc::CPU_STATE_USER as usize] as u64,+ load.cpu_ticks[libc::CPU_STATE_SYSTEM as usize] as u64,+ load.cpu_ticks[libc::CPU_STATE_IDLE as usize] as u64,+ load.cpu_ticks[libc::CPU_STATE_NICE as usize] as u64,+ ]+ })+ .collect();++ unsafe {+ libc::vm_deallocate(+ libc::mach_task_self(),+ info as libc::vm_address_t,+ info_count as usize * core::mem::size_of::<libc::c_int>(),+ );+ }+ Some(ticks)+}diff --git a/crates/keisoku/src/ioreport/bandwidth.rs b/crates/keisoku/src/ioreport/bandwidth.rsnew file mode 100644index 000000000..bce8e9b25--- /dev/null+++ b/crates/keisoku/src/ioreport/bandwidth.rs@@ -0,0 +1,171 @@+use obfstr::obfstr;++use super::{+ SocSample,+ channel::{ResidencyState, residency_active_percent, residency_weighted_gbps},+};++#[derive(Clone, Copy)]+enum Flow {+ Read,+ Write,+ Combined,+}++#[derive(Clone, Copy)]+enum Subsystem {+ Dram,+ NeuralEngine,+}++#[derive(Default)]+pub(super) struct BandwidthAccumulator {+ dram_read_bytes: f64,+ dram_write_bytes: f64,+ dram_combined_bytes: f64,+ ane_read_bytes: f64,+ ane_write_bytes: f64,+ ane_combined_bytes: f64,+ dram_read_histogram_gbps: f32,+ dram_write_histogram_gbps: f32,+ ane_read_histogram_gbps: f32,+ ane_write_histogram_gbps: f32,+}++impl BandwidthAccumulator {+ fn add_dram_bytes(+ &mut self,+ flow: Flow,+ bytes: f64,+ ) {+ match flow {+ Flow::Read => self.dram_read_bytes += bytes,+ Flow::Write => self.dram_write_bytes += bytes,+ Flow::Combined => self.dram_combined_bytes += bytes,+ }+ }++ fn add_ane_bytes(+ &mut self,+ flow: Flow,+ bytes: f64,+ ) {+ match flow {+ Flow::Read => self.ane_read_bytes += bytes,+ Flow::Write => self.ane_write_bytes += bytes,+ Flow::Combined => self.ane_combined_bytes += bytes,+ }+ }++ pub(super) fn finish(+ mut self,+ window_milliseconds: u64,+ result: &mut SocSample,+ ) {+ let window_seconds = (window_milliseconds as f64 / 1000.0).max(0.001);+ let to_gbps = |bytes: f64| (bytes / window_seconds / 1e9) as f32;++ if self.dram_read_bytes == 0.0 && self.dram_write_bytes == 0.0 && self.dram_combined_bytes > 0.0 {+ self.dram_read_bytes = self.dram_combined_bytes / 2.0;+ self.dram_write_bytes = self.dram_combined_bytes / 2.0;+ }+ if self.ane_read_bytes == 0.0 && self.ane_write_bytes == 0.0 && self.ane_combined_bytes > 0.0 {+ self.ane_read_bytes = self.ane_combined_bytes / 2.0;+ self.ane_write_bytes = self.ane_combined_bytes / 2.0;+ }++ result.dram_read_gbps = if self.dram_read_bytes > 0.0 {+ to_gbps(self.dram_read_bytes)+ } else {+ self.dram_read_histogram_gbps+ };+ result.dram_write_gbps = if self.dram_write_bytes > 0.0 {+ to_gbps(self.dram_write_bytes)+ } else {+ self.dram_write_histogram_gbps+ };+ result.ane_read_gbps = if self.ane_read_bytes > 0.0 {+ to_gbps(self.ane_read_bytes)+ } else {+ self.ane_read_histogram_gbps+ };+ result.ane_write_gbps = if self.ane_write_bytes > 0.0 {+ to_gbps(self.ane_write_bytes)+ } else {+ self.ane_write_histogram_gbps+ };+ }+}++pub(super) fn accumulate_amc_bandwidth(+ bytes: i64,+ channel: &str,+ bandwidth: &mut BandwidthAccumulator,+) {+ let aggregate = strip_die_prefix(channel);+ let target = if aggregate == obfstr!("DCS RD") {+ (Subsystem::Dram, Flow::Read)+ } else if aggregate == obfstr!("DCS WR") {+ (Subsystem::Dram, Flow::Write)+ } else if aggregate == obfstr!("ANE DCS RD") {+ (Subsystem::NeuralEngine, Flow::Read)+ } else if aggregate == obfstr!("ANE DCS WR") {+ (Subsystem::NeuralEngine, Flow::Write)+ } else {+ return;+ };+ let bytes = bytes as f64;+ if bytes <= 0.0 {+ return;+ }+ match target.0 {+ Subsystem::Dram => bandwidth.add_dram_bytes(target.1, bytes),+ Subsystem::NeuralEngine => bandwidth.add_ane_bytes(target.1, bytes),+ }+}++pub(super) fn accumulate_pmp(+ states: &[ResidencyState],+ subgroup: &str,+ channel: &str,+ bandwidth: &mut BandwidthAccumulator,+ result: &mut SocSample,+) {+ if subgroup.contains(obfstr!("Floor")) && (channel == obfstr!("ANE-AF-BW") || channel == obfstr!("ANE-DCS-BW")) {+ result.ane_active_percent = result.ane_active_percent.max(residency_active_percent(states));+ } else if subgroup == obfstr!("AF BW") {+ if channel == obfstr!("ANE0 RD") {+ bandwidth.ane_read_histogram_gbps = bandwidth.ane_read_histogram_gbps.max(residency_weighted_gbps(states));+ } else if channel == obfstr!("ANE0 WR") {+ bandwidth.ane_write_histogram_gbps =+ bandwidth.ane_write_histogram_gbps.max(residency_weighted_gbps(states));+ }+ } else if subgroup == obfstr!("DRAM BW") {+ let gbps = residency_weighted_gbps(states);+ match flow(channel) {+ Flow::Read => bandwidth.dram_read_histogram_gbps = bandwidth.dram_read_histogram_gbps.max(gbps),+ Flow::Write => bandwidth.dram_write_histogram_gbps = bandwidth.dram_write_histogram_gbps.max(gbps),+ Flow::Combined => {},+ }+ }+}++fn strip_die_prefix(channel: &str) -> &str {+ let Some(rest) = channel.strip_prefix(obfstr!("DIE")) else {+ return channel;+ };+ let rest = rest.trim_start_matches(|character: char| character.is_ascii_digit());+ rest.strip_prefix(' ').unwrap_or(channel)+}++fn flow(channel: &str) -> Flow {+ if channel.contains(obfstr!("RD+WR")) || channel.ends_with(obfstr!("RW")) {+ Flow::Combined+ } else if channel.contains(obfstr!("WR")) {+ Flow::Write+ } else if channel.contains(obfstr!("RD")) {+ Flow::Read+ } else {+ Flow::Combined+ }+}diff --git a/crates/keisoku/src/ioreport/channel.rs b/crates/keisoku/src/ioreport/channel.rsnew file mode 100644index 000000000..6feba20a8--- /dev/null+++ b/crates/keisoku/src/ioreport/channel.rs@@ -0,0 +1,93 @@+use core::ffi::c_void;++use obfstr::obfstr;+use objc2_core_foundation::{CFArray, CFDictionary, CFRetained, CFType};++use super::IoReportFunctions;+use crate::cf::{cf_string_to_string, dictionary_get};++pub(super) struct ResidencyState {+ pub name: String,+ pub residency: i64,+}++pub(super) struct ChannelSample {+ pub group: String,+ pub subgroup: String,+ pub name: String,+ pub unit: String,+ pub integer_value: i64,+ pub states: Vec<ResidencyState>,+}++pub(super) fn decode_channels(+ functions: &IoReportFunctions,+ delta: &CFDictionary,+) -> Vec<ChannelSample> {+ let Some(channels) = dictionary_get::<CFArray>(delta, obfstr!("IOReportChannels")) else {+ return Vec::new();+ };+ let channels: CFRetained<CFArray<CFType>> = unsafe { CFRetained::from_raw(CFRetained::into_raw(channels).cast()) };+ channels.iter().map(|channel| decode_channel(functions, &channel)).collect()+}++fn decode_channel(+ functions: &IoReportFunctions,+ channel: &CFType,+) -> ChannelSample {+ let item: *const c_void = core::ptr::from_ref(channel).cast();+ let states = (0..unsafe { (functions.state_get_count)(item) })+ .map(|index| ResidencyState {+ name: cf_string_to_string(unsafe { (functions.state_get_name_for_index)(item, index) }),+ residency: unsafe { (functions.state_get_residency)(item, index) },+ })+ .collect();+ ChannelSample {+ group: cf_string_to_string(unsafe { (functions.channel_get_group)(item) }),+ subgroup: cf_string_to_string(unsafe { (functions.channel_get_subgroup)(item) }),+ name: cf_string_to_string(unsafe { (functions.channel_get_channel_name)(item) }),+ unit: cf_string_to_string(unsafe { (functions.channel_get_unit_label)(item) }),+ integer_value: unsafe { (functions.simple_get_integer_value)(item, 0) },+ states,+ }+}++pub(super) fn residency_active_percent(states: &[ResidencyState]) -> f32 {+ let total: f64 = states.iter().map(|state| state.residency as f64).sum();+ if total <= 0.0 {+ return 0.0;+ }+ let active: f64 =+ states.iter().filter(|state| !is_idle_state(&state.name)).map(|state| state.residency as f64).sum();+ (active / total * 100.0) as f32+}++pub(super) fn residency_weighted_gbps(states: &[ResidencyState]) -> f32 {+ let mut weighted = 0f64;+ let mut total = 0f64;+ for state in states {+ weighted += parse_leading_number(&state.name) * (state.residency as f64);+ total += state.residency as f64;+ }+ if total <= 0.0 {+ 0.0+ } else {+ (weighted / total) as f32+ }+}++pub(super) fn is_idle_state(name: &str) -> bool {+ name == obfstr!("OFF")+ || name == obfstr!("IDLE")+ || name == obfstr!("DOWN")+ || name == obfstr!("SLEEP")+ || name == obfstr!("VMIN")+ || name == obfstr!("F1")+ || name == obfstr!("0%")+}++fn parse_leading_number(name: &str) -> f64 {+ let digits: String =+ name.trim().chars().take_while(|character| character.is_ascii_digit() || *character == '.').collect();+ digits.parse().unwrap_or(0.0)+}diff --git a/crates/keisoku/src/ioreport/frequency.rs b/crates/keisoku/src/ioreport/frequency.rsnew file mode 100644index 000000000..c19715c39--- /dev/null+++ b/crates/keisoku/src/ioreport/frequency.rs@@ -0,0 +1,56 @@+use super::channel::{ResidencyState, is_idle_state};++pub(super) fn calculate_frequency(+ states: &[ResidencyState],+ frequencies: &[u32],+) -> (u32, f32) {+ if states.len() <= frequencies.len() || frequencies.is_empty() {+ return (0, 0.0);+ }++ let Some(offset) = states.iter().position(|state| !is_idle_state(&state.name)) else {+ return (0, 0.0);+ };+ let active: f64 = states.iter().skip(offset).map(|state| state.residency as f64).sum();+ let total: f64 = states.iter().map(|state| state.residency as f64).sum();++ let mut average_frequency = 0f64;+ for (index, &frequency) in frequencies.iter().enumerate() {+ let Some(state) = states.get(index + offset) else {+ break;+ };+ let percent = divide_or_zero(state.residency as f64, active);+ average_frequency += percent * frequency as f64;+ }+ let usage_ratio = divide_or_zero(active, total);+ let minimum_frequency = *frequencies.first().unwrap() as f64;+ let maximum_frequency = *frequencies.last().unwrap() as f64;+ let fraction_of_max = (average_frequency.max(minimum_frequency) * usage_ratio) / maximum_frequency;+ (average_frequency as u32, fraction_of_max as f32)+}++pub(super) fn average_cluster_frequency(+ readings: &[(u32, f32)],+ frequencies: &[u32],+) -> (u32, f32) {+ if readings.is_empty() || frequencies.is_empty() {+ return (0, 0.0);+ }+ let average_frequency =+ divide_or_zero(readings.iter().map(|reading| reading.0 as f32).sum::<f32>(), readings.len() as f32);+ let average_percent = divide_or_zero(readings.iter().map(|reading| reading.1).sum::<f32>(), readings.len() as f32);+ let minimum_frequency = *frequencies.first().unwrap() as f32;+ (average_frequency.max(minimum_frequency) as u32, average_percent)+}++pub(super) fn divide_or_zero<T: core::ops::Div<Output = T> + Default + PartialEq>(+ numerator: T,+ denominator: T,+) -> T {+ let zero = T::default();+ if denominator == zero {+ zero+ } else {+ numerator / denominator+ }+}diff --git a/crates/keisoku/src/ioreport/mod.rs b/crates/keisoku/src/ioreport/mod.rsnew file mode 100644index 000000000..e29a03af9--- /dev/null+++ b/crates/keisoku/src/ioreport/mod.rs@@ -0,0 +1,103 @@+use core::{ffi::c_void, ptr::NonNull};++use objc2_core_foundation::{CFDictionary, CFMutableDictionary, CFRetained, CFString, CFType, Type};++mod bandwidth;+mod channel;+mod frequency;+mod report;+mod sample;+mod subscription;++pub use report::IoReport;+pub use sample::SocSample;++kanka::ffi_table! {+ struct IoReportFunctions from "/usr/lib/libIOReport.dylib" {+ copy_channels_in_group = "IOReportCopyChannelsInGroup":+ unsafe extern "C" fn(*const c_void, *const c_void, u64, u64, u64) -> *const c_void,+ merge_channels = "IOReportMergeChannels":+ unsafe extern "C" fn(*const c_void, *const c_void, *const c_void),+ create_subscription = "IOReportCreateSubscription":+ unsafe extern "C" fn(*const c_void, *mut c_void, *mut *mut c_void, u64, *const c_void) -> *const c_void,+ create_samples = "IOReportCreateSamples":+ unsafe extern "C" fn(*const c_void, *mut c_void, *const c_void) -> *const c_void,+ create_samples_delta = "IOReportCreateSamplesDelta":+ unsafe extern "C" fn(*const c_void, *const c_void, *const c_void) -> *const c_void,+ channel_get_group = "IOReportChannelGetGroup":+ unsafe extern "C" fn(*const c_void) -> *const c_void,+ channel_get_subgroup = "IOReportChannelGetSubGroup":+ unsafe extern "C" fn(*const c_void) -> *const c_void,+ channel_get_channel_name = "IOReportChannelGetChannelName":+ unsafe extern "C" fn(*const c_void) -> *const c_void,+ channel_get_unit_label = "IOReportChannelGetUnitLabel":+ unsafe extern "C" fn(*const c_void) -> *const c_void,+ simple_get_integer_value = "IOReportSimpleGetIntegerValue":+ unsafe extern "C" fn(*const c_void, i32) -> i64,+ state_get_count = "IOReportStateGetCount":+ unsafe extern "C" fn(*const c_void) -> i32,+ state_get_name_for_index = "IOReportStateGetNameForIndex":+ unsafe extern "C" fn(*const c_void, i32) -> *const c_void,+ state_get_residency = "IOReportStateGetResidency":+ unsafe extern "C" fn(*const c_void, i32) -> i64,+ }+}++impl IoReportFunctions {+ fn copy_channels_in_group(+ &self,+ group: &CFString,+ subgroup: Option<&CFString>,+ ) -> Option<CFRetained<CFDictionary>> {+ let subgroup_pointer = subgroup.map_or(core::ptr::null_mut(), raw);+ let channels = unsafe { (self.copy_channels_in_group)(raw(group), subgroup_pointer, 0, 0, 0) };+ retained_dictionary(channels)+ }++ fn merge_channels(+ &self,+ first: &CFDictionary,+ other: &CFDictionary,+ ) {+ unsafe { (self.merge_channels)(raw(first), raw(other), core::ptr::null()) };+ }++ fn create_subscription(+ &self,+ channels: &CFMutableDictionary,+ ) -> Option<(CFRetained<CFType>, Option<CFRetained<CFDictionary>>)> {+ let mut subscribed: *mut c_void = core::ptr::null_mut();+ let subscription = unsafe {+ (self.create_subscription)(core::ptr::null(), raw(channels), &mut subscribed, 0, core::ptr::null())+ };+ let subscription = unsafe { CFRetained::from_raw(NonNull::new(subscription.cast_mut().cast::<CFType>())?) };+ Some((subscription, retained_dictionary(subscribed)))+ }++ fn create_samples(+ &self,+ subscription: &CFType,+ channels: &CFMutableDictionary,+ ) -> Option<CFRetained<CFDictionary>> {+ let samples = unsafe { (self.create_samples)(raw(subscription), raw(channels), core::ptr::null()) };+ retained_dictionary(samples)+ }++ fn create_samples_delta(+ &self,+ previous: &CFDictionary,+ next: &CFDictionary,+ ) -> Option<CFRetained<CFDictionary>> {+ let delta = unsafe { (self.create_samples_delta)(raw(previous), raw(next), core::ptr::null()) };+ retained_dictionary(delta)+ }+}++fn raw<T: Type>(value: &T) -> *mut c_void {+ let pointer: *const T = value;+ pointer.cast::<c_void>().cast_mut()+}++fn retained_dictionary(value: *const c_void) -> Option<CFRetained<CFDictionary>> {+ NonNull::new(value.cast_mut().cast::<CFDictionary>()).map(|pointer| unsafe { CFRetained::from_raw(pointer) })+}diff --git a/crates/keisoku/src/ioreport/report.rs b/crates/keisoku/src/ioreport/report.rsnew file mode 100644index 000000000..35cbef54d--- /dev/null+++ b/crates/keisoku/src/ioreport/report.rs@@ -0,0 +1,124 @@+use std::time::{Duration, Instant};++use obfstr::obfstr;++use super::{+ IoReportFunctions, SocSample,+ bandwidth::{BandwidthAccumulator, accumulate_amc_bandwidth, accumulate_pmp},+ channel::decode_channels,+ frequency::{average_cluster_frequency, calculate_frequency, divide_or_zero},+ subscription::Subscription,+};+use crate::soc::SocInfo;++const ANE_MAX_POWER_WATTS: f32 = 8.0;++pub struct IoReport {+ functions: &'static IoReportFunctions,+ subscription: Subscription,+}++impl IoReport {+ pub fn new() -> Option<Self> {+ let functions = IoReportFunctions::get()?;+ let subscription = Subscription::new(functions)?;+ Some(Self {+ functions,+ subscription,+ })+ }++ pub fn sample(+ &self,+ soc: &SocInfo,+ interval: Duration,+ ) -> SocSample {+ let functions = self.functions;++ let Some(previous) = self.subscription.snapshot(functions) else {+ std::thread::sleep(interval);+ return SocSample::default();+ };+ let started = Instant::now();+ std::thread::sleep(interval);+ let next = self.subscription.snapshot(functions);+ let elapsed = started.elapsed();+ let Some(next) = next else {+ return SocSample::default();+ };+ let Some(delta) = functions.create_samples_delta(&previous, &next) else {+ return SocSample::default();+ };++ let mut result = SocSample::default();+ let mut ecpu_readings = Vec::new();+ let mut pcpu_readings = Vec::new();+ let window_milliseconds = elapsed.as_millis().max(1) as u64;+ let mut bandwidth = BandwidthAccumulator::default();++ for channel in decode_channels(functions, &delta) {+ if channel.group == obfstr!("CPU Stats") && channel.subgroup == obfstr!("CPU Core Performance States") {+ if channel.name.starts_with(obfstr!("PCPU")) {+ pcpu_readings.push(calculate_frequency(&channel.states, &soc.pcpu_frequencies));+ } else if channel.name.starts_with(obfstr!("ECPU")) || channel.name.starts_with(obfstr!("MCPU")) {+ ecpu_readings.push(calculate_frequency(&channel.states, &soc.ecpu_frequencies));+ }+ } else if channel.group == obfstr!("GPU Stats") && channel.subgroup == obfstr!("GPU Performance States") {+ if channel.name == obfstr!("GPUPH") && soc.gpu_frequencies.len() > 1 {+ result.gpu_usage = calculate_frequency(&channel.states, &soc.gpu_frequencies[1..]);+ }+ } else if channel.group == obfstr!("Energy Model") {+ let watts = watts(channel.integer_value, channel.unit.trim(), window_milliseconds);+ if channel.name == obfstr!("GPU Energy") {+ result.gpu_power += watts;+ } else if channel.name.ends_with(obfstr!("CPU Energy")) {+ result.cpu_power += watts;+ } else if channel.name.starts_with(obfstr!("ANE")) {+ result.ane_power += watts;+ } else if channel.name.starts_with(obfstr!("DRAM")) {+ result.ram_power += watts;+ } else if channel.name.starts_with(obfstr!("GPU SRAM")) {+ result.gpu_ram_power += watts;+ }+ } else if channel.group == obfstr!("AMC Stats") {+ accumulate_amc_bandwidth(channel.integer_value, &channel.name, &mut bandwidth);+ } else if channel.group == obfstr!("PMP") {+ accumulate_pmp(&channel.states, &channel.subgroup, &channel.name, &mut bandwidth, &mut result);+ }+ }++ ecpu_readings.retain(|&(_, percent)| percent > 0.0);+ result.ecpu_usage = average_cluster_frequency(&ecpu_readings, &soc.ecpu_frequencies);+ result.pcpu_usage = average_cluster_frequency(&pcpu_readings, &soc.pcpu_frequencies);+ let efficiency_cores = soc.ecpu_cores as f32;+ let performance_cores = soc.pcpu_cores as f32;+ result.cpu_usage_percent = divide_or_zero(+ result.ecpu_usage.1 * efficiency_cores + result.pcpu_usage.1 * performance_cores,+ efficiency_cores + performance_cores,+ );+ result.total_power = result.cpu_power + result.gpu_power + result.ane_power;++ bandwidth.finish(window_milliseconds, &mut result);+ if result.ane_active_percent == 0.0 && result.ane_power > 0.0 {+ result.ane_active_percent = (result.ane_power / ANE_MAX_POWER_WATTS * 100.0).min(100.0);+ }+ result+ }+}++fn watts(+ energy: i64,+ unit: &str,+ window_milliseconds: u64,+) -> f32 {+ let power = energy as f32 / (window_milliseconds as f32 / 1000.0);+ if unit == obfstr!("mJ") {+ power / 1e3+ } else if unit == obfstr!("uJ") {+ power / 1e6+ } else if unit == obfstr!("nJ") {+ power / 1e9+ } else {+ 0.0+ }+}diff --git a/crates/keisoku/src/ioreport/sample.rs b/crates/keisoku/src/ioreport/sample.rsnew file mode 100644index 000000000..7dc7ea481--- /dev/null+++ b/crates/keisoku/src/ioreport/sample.rs@@ -0,0 +1,18 @@+#[derive(Debug, Default, Clone)]+pub struct SocSample {+ pub cpu_power: f32,+ pub gpu_power: f32,+ pub ane_power: f32,+ pub ram_power: f32,+ pub gpu_ram_power: f32,+ pub total_power: f32,+ pub ecpu_usage: (u32, f32),+ pub pcpu_usage: (u32, f32),+ pub cpu_usage_percent: f32,+ pub gpu_usage: (u32, f32),+ pub ane_active_percent: f32,+ pub ane_read_gbps: f32,+ pub ane_write_gbps: f32,+ pub dram_read_gbps: f32,+ pub dram_write_gbps: f32,+}diff --git a/crates/keisoku/src/ioreport/subscription.rs b/crates/keisoku/src/ioreport/subscription.rsnew file mode 100644index 000000000..5b1018fa9--- /dev/null+++ b/crates/keisoku/src/ioreport/subscription.rs@@ -0,0 +1,56 @@+use obfstr::obfstr;+use objc2_core_foundation::{CFDictionary, CFMutableDictionary, CFRetained, CFString, CFType};++use super::IoReportFunctions;++pub(super) struct Channels(CFRetained<CFMutableDictionary>);++impl Channels {+ fn new(functions: &IoReportFunctions) -> Option<Self> {+ let mut groups: Vec<CFRetained<CFDictionary>> = Vec::with_capacity(5);+ for (group, subgroup) in [+ (obfstr!("Energy Model"), None::<&str>),+ (obfstr!("CPU Stats"), Some(obfstr!("CPU Core Performance States"))),+ (obfstr!("GPU Stats"), Some(obfstr!("GPU Performance States"))),+ (obfstr!("AMC Stats"), None),+ (obfstr!("PMP"), None),+ ] {+ let group_name = CFString::from_str(group);+ let subgroup_name = subgroup.map(CFString::from_str);+ if let Some(group_channels) = functions.copy_channels_in_group(&group_name, subgroup_name.as_deref()) {+ groups.push(group_channels);+ }+ }++ let (first, rest) = groups.split_first()?;+ for other in rest {+ functions.merge_channels(first, other);+ }+ let channels = unsafe { CFMutableDictionary::new_copy(None, first.count(), Some(&**first)) }?;+ Some(Self(channels))+ }+}++pub(super) struct Subscription {+ handle: CFRetained<CFType>,+ channels: Channels,+}++impl Subscription {+ pub(super) fn new(functions: &IoReportFunctions) -> Option<Self> {+ let channels = Channels::new(functions)?;+ let (handle, subscribed) = functions.create_subscription(&channels.0)?;+ drop(subscribed);+ Some(Self {+ handle,+ channels,+ })+ }++ pub(super) fn snapshot(+ &self,+ functions: &IoReportFunctions,+ ) -> Option<CFRetained<CFDictionary>> {+ functions.create_samples(&self.handle, &self.channels.0)+ }+}diff --git a/crates/keisoku/src/lib.rs b/crates/keisoku/src/lib.rsnew file mode 100644index 000000000..8a6e02309--- /dev/null+++ b/crates/keisoku/src/lib.rs@@ -0,0 +1,81 @@+mod collector;+mod component;+mod metrics;+mod recorder;+mod sensor;+mod snapshot;+mod units;++#[cfg(target_os = "macos")]+mod cf;+#[cfg(target_vendor = "apple")]+mod client;+#[cfg(target_os = "macos")]+mod cpu_load;+#[cfg(target_os = "macos")]+mod ioreport;+#[cfg(target_os = "macos")]+mod smc;+#[cfg(target_os = "macos")]+mod soc;+#[cfg(target_vendor = "apple")]+mod sys;++pub use collector::Collector;+pub use component::{Component, classify};+pub use metrics::{+ BandwidthMetrics, BatteryMetrics, CpuMetrics, Fan, FanMetrics, GpuMetrics, MemoryMetrics, NeuralEngineMetrics,+ PowerMetrics, Temperatures, ThermalPressure,+};+pub use recorder::{Config, Device, Marker, RecorderHandle, Session, start};+pub use sensor::{Sensor, SensorKind, current_sensors, thermal_sensors, voltage_sensors};+pub use snapshot::Snapshot;+pub use units::{Bytes, Celsius, GigabytesPerSecond, Megahertz, Milliseconds, Percent, Rpm, Watts};++#[cfg(target_vendor = "apple")]+pub fn sensors(kind: SensorKind) -> Vec<Sensor> {+ client::collect(kind)+}++#[cfg(target_vendor = "apple")]+pub fn sensors_available() -> bool {+ client::is_available()+}++#[cfg(not(target_vendor = "apple"))]+pub fn sensors(_kind: SensorKind) -> Vec<Sensor> {+ Vec::new()+}++#[cfg(not(target_vendor = "apple"))]+pub fn sensors_available() -> bool {+ false+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sensor_queries_do_not_panic() {+ let _ = sensors_available();+ for kind in [SensorKind::Temperature, SensorKind::Voltage, SensorKind::Current] {+ for sensor in sensors(kind) {+ assert_eq!(sensor.kind, kind);+ assert!(sensor.value.is_finite());+ }+ }+ }++ #[test]+ fn one_snapshot_is_well_formed() {+ let mut collector = Collector::new();+ let snapshot = collector.sample(std::time::Duration::from_millis(120));+ if let Some(power) = &snapshot.power {+ assert!(power.total.value().is_finite() && power.total.value() >= 0.0);+ }+ if let Some(memory) = &snapshot.memory {+ assert!(memory.ram_total >= memory.ram_usage);+ }+ }+}diff --git a/crates/keisoku/src/metrics/bandwidth.rs b/crates/keisoku/src/metrics/bandwidth.rsnew file mode 100644index 000000000..d8ec13248--- /dev/null+++ b/crates/keisoku/src/metrics/bandwidth.rs@@ -0,0 +1,9 @@+use serde::{Deserialize, Serialize};++use crate::units::GigabytesPerSecond;++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct BandwidthMetrics {+ pub dram_read: GigabytesPerSecond,+ pub dram_write: GigabytesPerSecond,+}diff --git a/crates/keisoku/src/metrics/battery.rs b/crates/keisoku/src/metrics/battery.rsnew file mode 100644index 000000000..e0f4f0357--- /dev/null+++ b/crates/keisoku/src/metrics/battery.rs@@ -0,0 +1,70 @@+use serde::{Deserialize, Serialize};++use crate::units::Percent;++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct BatteryMetrics {+ pub present: bool,+ pub percent: Percent,+ pub charging: bool,+ pub on_ac_power: bool,+}++#[cfg(target_os = "macos")]+pub(crate) fn read() -> Option<BatteryMetrics> {+ use objc2_core_foundation::{CFBoolean, CFNumber, CFString, CFType};+ use objc2_io_kit::{+ IOPSCopyPowerSourcesInfo, IOPSCopyPowerSourcesList, IOPSGetPowerSourceDescription, kIOPSCurrentCapacityKey,+ kIOPSInternalBatteryType, kIOPSIsChargingKey, kIOPSMaxCapacityKey, kIOPSPowerSourceStateKey, kIOPSTypeKey,+ };++ use crate::cf::dictionary_get;++ let info = IOPSCopyPowerSourcesInfo()?;+ let info_ref: &CFType = &info;+ let list = unsafe { IOPSCopyPowerSourcesList(Some(info_ref)) }?;+ let internal = kIOPSInternalBatteryType.to_str().ok()?;++ for index in 0..list.count() {+ let source = unsafe { list.value_at_index(index) };+ let Some(source) = (unsafe { (source as *const CFType).as_ref() }) else {+ continue;+ };+ let Some(description) = (unsafe { IOPSGetPowerSourceDescription(Some(info_ref), Some(source)) }) else {+ continue;+ };+ let string =+ |key: &core::ffi::CStr| dictionary_get::<CFString>(&description, key.to_str().ok()?).map(|s| s.to_string());+ let number = |key: &core::ffi::CStr| {+ dictionary_get::<CFNumber>(&description, key.to_str().ok()?).and_then(|n| n.as_i64())+ };+ let boolean =+ |key: &core::ffi::CStr| dictionary_get::<CFBoolean>(&description, key.to_str().ok()?).map(|b| b.value());++ if string(kIOPSTypeKey)? != internal {+ continue;+ }+ let current = number(kIOPSCurrentCapacityKey)?;+ let maximum = number(kIOPSMaxCapacityKey)?;+ let charging = boolean(kIOPSIsChargingKey).unwrap_or(false);+ let on_ac_power = string(kIOPSPowerSourceStateKey).is_some_and(|state| state.eq_ignore_ascii_case("AC Power"));+ let percent = if maximum > 0 {+ (current * 100 / maximum) as f32+ } else {+ 0.0+ };++ return Some(BatteryMetrics {+ present: true,+ percent: Percent(percent),+ charging,+ on_ac_power,+ });+ }+ None+}++#[cfg(not(target_os = "macos"))]+pub(crate) fn read() -> Option<BatteryMetrics> {+ None+}diff --git a/crates/keisoku/src/metrics/cpu.rs b/crates/keisoku/src/metrics/cpu.rsnew file mode 100644index 000000000..84f27ab66--- /dev/null+++ b/crates/keisoku/src/metrics/cpu.rs@@ -0,0 +1,13 @@+use serde::{Deserialize, Serialize};++use crate::units::{Megahertz, Percent};++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct CpuMetrics {+ pub usage: Percent,+ pub ecpu_frequency: Megahertz,+ pub ecpu_usage: Percent,+ pub pcpu_frequency: Megahertz,+ pub pcpu_usage: Percent,+ pub per_core: Vec<Percent>,+}diff --git a/crates/keisoku/src/metrics/fans.rs b/crates/keisoku/src/metrics/fans.rsnew file mode 100644index 000000000..ebda9791f--- /dev/null+++ b/crates/keisoku/src/metrics/fans.rs@@ -0,0 +1,16 @@+use serde::{Deserialize, Serialize};++use crate::units::Rpm;++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct Fan {+ pub actual: Rpm,+ pub minimum: Rpm,+ pub maximum: Rpm,+ pub target: Rpm,+}++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct FanMetrics {+ pub fans: Vec<Fan>,+}diff --git a/crates/keisoku/src/metrics/gpu.rs b/crates/keisoku/src/metrics/gpu.rsnew file mode 100644index 000000000..6d13dd2e5--- /dev/null+++ b/crates/keisoku/src/metrics/gpu.rs@@ -0,0 +1,9 @@+use serde::{Deserialize, Serialize};++use crate::units::{Megahertz, Percent};++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct GpuMetrics {+ pub frequency: Megahertz,+ pub usage: Percent,+}diff --git a/crates/keisoku/src/metrics/memory.rs b/crates/keisoku/src/metrics/memory.rsnew file mode 100644index 000000000..3eb32ed88--- /dev/null+++ b/crates/keisoku/src/metrics/memory.rs@@ -0,0 +1,94 @@+use serde::{Deserialize, Serialize};++use crate::units::Bytes;++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct MemoryMetrics {+ pub ram_total: Bytes,+ pub ram_usage: Bytes,+ pub swap_total: Bytes,+ pub swap_usage: Bytes,+}++#[cfg(target_os = "macos")]+pub(crate) fn read() -> Option<MemoryMetrics> {+ let mut ram_total = 0u64;+ unsafe {+ let mut name = [libc::CTL_HW, libc::HW_MEMSIZE];+ let mut size = core::mem::size_of::<u64>();+ if libc::sysctl(+ name.as_mut_ptr(),+ name.len() as _,+ &mut ram_total as *mut _ as *mut _,+ &mut size,+ core::ptr::null_mut(),+ 0,+ ) != 0+ {+ return None;+ }+ }++ let ram_usage = unsafe {+ let mut count: u32 = libc::HOST_VM_INFO64_COUNT as _;+ let mut statistics = core::mem::zeroed::<libc::vm_statistics64>();+ #[allow(deprecated)]+ let result = libc::host_statistics64(+ libc::mach_host_self(),+ libc::HOST_VM_INFO64,+ &mut statistics as *mut _ as *mut _,+ &mut count,+ );+ if result != 0 {+ return None;+ }+ let page_size = libc::sysconf(libc::_SC_PAGESIZE) as u64;+ (statistics.active_count as u64+ + statistics.inactive_count as u64+ + statistics.wire_count as u64+ + statistics.speculative_count as u64+ + statistics.compressor_page_count as u64+ - statistics.purgeable_count as u64+ - statistics.external_page_count as u64)+ * page_size+ };++ let (swap_usage, swap_total) = unsafe {+ let mut name = [libc::CTL_VM, libc::VM_SWAPUSAGE];+ let mut size = core::mem::size_of::<libc::xsw_usage>();+ let mut swap = core::mem::zeroed::<libc::xsw_usage>();+ if libc::sysctl(+ name.as_mut_ptr(),+ name.len() as _,+ &mut swap as *mut _ as *mut _,+ &mut size,+ core::ptr::null_mut(),+ 0,+ ) == 0+ {+ (swap.xsu_used, swap.xsu_total)+ } else {+ (0, 0)+ }+ };++ Some(MemoryMetrics {+ ram_total: Bytes(ram_total),+ ram_usage: Bytes(ram_usage),+ swap_total: Bytes(swap_total),+ swap_usage: Bytes(swap_usage),+ })+}++#[cfg(not(target_os = "macos"))]+pub(crate) fn read() -> Option<MemoryMetrics> {+ use sysinfo::System;+ let mut system = System::new();+ system.refresh_memory();+ Some(MemoryMetrics {+ ram_total: Bytes(system.total_memory()),+ ram_usage: Bytes(system.used_memory()),+ swap_total: Bytes(system.total_swap()),+ swap_usage: Bytes(system.used_swap()),+ })+}diff --git a/crates/keisoku/src/metrics/mod.rs b/crates/keisoku/src/metrics/mod.rsnew file mode 100644index 000000000..0e09cf6cf--- /dev/null+++ b/crates/keisoku/src/metrics/mod.rs@@ -0,0 +1,24 @@+mod bandwidth;+mod battery;+mod cpu;+mod fans;+mod gpu;+mod memory;+mod neural_engine;+mod power;+mod temperatures;+mod thermal_pressure;++pub use bandwidth::BandwidthMetrics;+pub use battery::BatteryMetrics;+pub(crate) use battery::read as read_battery;+pub use cpu::CpuMetrics;+pub use fans::{Fan, FanMetrics};+pub use gpu::GpuMetrics;+pub use memory::MemoryMetrics;+pub(crate) use memory::read as read_memory;+pub use neural_engine::NeuralEngineMetrics;+pub use power::PowerMetrics;+pub use temperatures::Temperatures;+pub use thermal_pressure::ThermalPressure;+pub(crate) use thermal_pressure::read as read_thermal_pressure;diff --git a/crates/keisoku/src/metrics/neural_engine.rs b/crates/keisoku/src/metrics/neural_engine.rsnew file mode 100644index 000000000..4ae9aee17--- /dev/null+++ b/crates/keisoku/src/metrics/neural_engine.rs@@ -0,0 +1,11 @@+use serde::{Deserialize, Serialize};++use crate::units::{GigabytesPerSecond, Percent, Watts};++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct NeuralEngineMetrics {+ pub power: Watts,+ pub active: Percent,+ pub read_bandwidth: GigabytesPerSecond,+ pub write_bandwidth: GigabytesPerSecond,+}diff --git a/crates/keisoku/src/metrics/power.rs b/crates/keisoku/src/metrics/power.rsnew file mode 100644index 000000000..d8bc4e67b--- /dev/null+++ b/crates/keisoku/src/metrics/power.rs@@ -0,0 +1,16 @@+use serde::{Deserialize, Serialize};++use crate::units::Watts;++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct PowerMetrics {+ pub cpu: Watts,+ pub gpu: Watts,+ pub gpu_sram: Watts,+ pub ane: Watts,+ pub ram: Watts,++ pub total: Watts,++ pub package: Watts,+}diff --git a/crates/keisoku/src/metrics/temperatures.rs b/crates/keisoku/src/metrics/temperatures.rsnew file mode 100644index 000000000..a89142aec--- /dev/null+++ b/crates/keisoku/src/metrics/temperatures.rs@@ -0,0 +1,9 @@+use serde::{Deserialize, Serialize};++use crate::units::Celsius;++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct Temperatures {+ pub cpu_average: Option<Celsius>,+ pub gpu_average: Option<Celsius>,+}diff --git a/crates/keisoku/src/metrics/thermal_pressure.rs b/crates/keisoku/src/metrics/thermal_pressure.rsnew file mode 100644index 000000000..0dcac88c4--- /dev/null+++ b/crates/keisoku/src/metrics/thermal_pressure.rs@@ -0,0 +1,59 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub enum ThermalPressure {+ Nominal,+ Moderate,+ Heavy,+ Trapping,+ Sleeping,+}++#[cfg(target_vendor = "apple")]+impl ThermalPressure {+ fn from_level(level: u64) -> Option<Self> {+ match level {+ 0 => Some(ThermalPressure::Nominal),+ 1 => Some(ThermalPressure::Moderate),+ 2 => Some(ThermalPressure::Heavy),+ 3 => Some(ThermalPressure::Trapping),+ 4 => Some(ThermalPressure::Sleeping),+ _ => None,+ }+ }+}++#[cfg(target_vendor = "apple")]+pub(crate) fn read() -> Option<ThermalPressure> {+ use core::ffi::c_char;++ unsafe extern "C" {+ fn notify_register_check(+ name: *const c_char,+ out_token: *mut i32,+ ) -> u32;+ fn notify_get_state(+ token: i32,+ out_state: *mut u64,+ ) -> u32;+ fn notify_cancel(token: i32) -> u32;+ }++ let name = std::ffi::CString::new("com.apple.system.thermalpressurelevel").ok()?;+ let mut token = 0i32;+ if unsafe { notify_register_check(name.as_ptr(), &mut token) } != 0 {+ return None;+ }+ let mut level = 0u64;+ let result = unsafe { notify_get_state(token, &mut level) };+ unsafe { notify_cancel(token) };+ if result != 0 {+ return None;+ }+ ThermalPressure::from_level(level)+}++#[cfg(not(target_vendor = "apple"))]+pub(crate) fn read() -> Option<ThermalPressure> {+ None+}diff --git a/crates/keisoku/src/recorder/config.rs b/crates/keisoku/src/recorder/config.rsnew file mode 100644index 000000000..f63797b3a--- /dev/null+++ b/crates/keisoku/src/recorder/config.rs@@ -0,0 +1,14 @@+use std::time::Duration;++#[derive(Debug, Clone)]+pub struct Config {+ pub interval: Duration,+}++impl Default for Config {+ fn default() -> Self {+ Self {+ interval: Duration::from_millis(1000),+ }+ }+}diff --git a/crates/keisoku/src/recorder/device.rs b/crates/keisoku/src/recorder/device.rsnew file mode 100644index 000000000..7d908e543--- /dev/null+++ b/crates/keisoku/src/recorder/device.rs@@ -0,0 +1,103 @@+use serde::{Deserialize, Serialize};++use crate::{Collector, units::Bytes};++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct Device {+ pub os: String,+ pub chip: String,+ pub ram_total: Bytes,+ pub efficiency_cores: u8,+ pub performance_cores: u8,+ pub gpu_cores: u8,+}++impl Device {+ pub(crate) fn detect(#[allow(unused_variables)] collector: &Collector) -> Device {+ let os = sysinfo::System::long_os_version().unwrap_or_default();+ let mut system = sysinfo::System::new_all();+ system.refresh_all();+ let chip = system.cpus().first().map(|c| c.brand().trim().to_string()).unwrap_or_default();+ let ram_total = Bytes(system.total_memory());++ #[cfg(target_os = "macos")]+ if let Some(soc) = collector.soc() {+ return Device {+ os,+ chip: if soc.chip_name.is_empty() {+ chip+ } else {+ soc.chip_name.clone()+ },+ ram_total,+ efficiency_cores: soc.ecpu_cores,+ performance_cores: soc.pcpu_cores,+ gpu_cores: soc.gpu_cores,+ };+ }++ #[cfg(all(target_vendor = "apple", not(target_os = "macos")))]+ #[allow(clippy::needless_return)]+ {+ let (performance_cores, efficiency_cores) = perflevel_cores();+ return Device {+ os,+ chip: sysctl_string("hw.machine").filter(|model| !model.is_empty()).unwrap_or(chip),+ ram_total,+ efficiency_cores,+ performance_cores,+ gpu_cores: 0,+ };+ }++ #[cfg(not(all(target_vendor = "apple", not(target_os = "macos"))))]+ Device {+ os,+ chip,+ ram_total,+ ..Default::default()+ }+ }+}++#[cfg(all(target_vendor = "apple", not(target_os = "macos")))]+fn sysctl_string(name: &str) -> Option<String> {+ let name = std::ffi::CString::new(name).ok()?;+ let mut len = 0usize;+ let probe = unsafe { libc::sysctlbyname(name.as_ptr(), std::ptr::null_mut(), &mut len, std::ptr::null_mut(), 0) };+ if probe != 0 || len == 0 {+ return None;+ }+ let mut buffer = vec![0u8; len];+ let read =+ unsafe { libc::sysctlbyname(name.as_ptr(), buffer.as_mut_ptr().cast(), &mut len, std::ptr::null_mut(), 0) };+ if read != 0 {+ return None;+ }+ if let Some(nul) = buffer.iter().position(|&byte| byte == 0) {+ buffer.truncate(nul);+ }+ String::from_utf8(buffer).ok()+}++#[cfg(all(target_vendor = "apple", not(target_os = "macos")))]+fn sysctl_u32(name: &str) -> Option<u32> {+ let name = std::ffi::CString::new(name).ok()?;+ let mut value = 0u32;+ let mut len = std::mem::size_of::<u32>();+ let read = unsafe {+ libc::sysctlbyname(name.as_ptr(), std::ptr::addr_of_mut!(value).cast(), &mut len, std::ptr::null_mut(), 0)+ };+ (read == 0).then_some(value)+}++#[cfg(all(target_vendor = "apple", not(target_os = "macos")))]+fn perflevel_cores() -> (u8, u8) {+ let performance = sysctl_u32("hw.perflevel0.logicalcpu").unwrap_or(0);+ let efficiency = if sysctl_u32("hw.nperflevels").unwrap_or(1) > 1 {+ sysctl_u32("hw.perflevel1.logicalcpu").unwrap_or(0)+ } else {+ 0+ };+ (performance as u8, efficiency as u8)+}diff --git a/crates/keisoku/src/recorder/handle.rs b/crates/keisoku/src/recorder/handle.rsnew file mode 100644index 000000000..a2f721dff--- /dev/null+++ b/crates/keisoku/src/recorder/handle.rs@@ -0,0 +1,89 @@+use std::{+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+ thread::JoinHandle,+ time::{Duration, Instant},+};++use super::{Config, Device, Marker, Session};+use crate::{Collector, snapshot::Snapshot, units::Milliseconds};++pub struct RecorderHandle {+ started_at: Instant,+ interval: Duration,+ stop_flag: Arc<AtomicBool>,+ markers: Arc<Mutex<Vec<Marker>>>,+ worker: Option<JoinHandle<(Device, Vec<Snapshot>)>>,+}++impl RecorderHandle {+ pub fn mark(+ &self,+ label: impl Into<String>,+ ) {+ let elapsed = Milliseconds(self.started_at.elapsed().as_millis() as u64);+ if let Ok(mut markers) = self.markers.lock() {+ markers.push(Marker {+ elapsed,+ label: label.into(),+ });+ }+ }++ pub fn stop(mut self) -> Session {+ self.stop_flag.store(true, Ordering::Relaxed);+ let (device, snapshots) = match self.worker.take().map(JoinHandle::join) {+ Some(Ok(result)) => result,+ _ => (Device::default(), Vec::new()),+ };+ let markers = self.markers.lock().map(|markers| markers.clone()).unwrap_or_default();+ Session {+ device,+ interval: Milliseconds(self.interval.as_millis() as u64),+ snapshots,+ markers,+ }+ }+}++impl Drop for RecorderHandle {+ fn drop(&mut self) {+ self.stop_flag.store(true, Ordering::Relaxed);+ if let Some(worker) = self.worker.take() {+ let _ = worker.join();+ }+ }+}++pub fn start(config: Config) -> RecorderHandle {+ let started_at = Instant::now();+ let interval = config.interval;+ let stop_flag = Arc::new(AtomicBool::new(false));+ let markers = Arc::new(Mutex::new(Vec::new()));++ let worker = {+ let stop_flag = Arc::clone(&stop_flag);++ std::thread::spawn(move || {+ let mut collector = Collector::new();+ let device = Device::detect(&collector);+ let mut snapshots = Vec::new();+ while !stop_flag.load(Ordering::Relaxed) {+ let mut snapshot = collector.sample(interval);+ snapshot.elapsed = Milliseconds(started_at.elapsed().as_millis() as u64);+ snapshots.push(snapshot);+ }+ (device, snapshots)+ })+ };++ RecorderHandle {+ started_at,+ interval,+ stop_flag,+ markers,+ worker: Some(worker),+ }+}diff --git a/crates/keisoku/src/recorder/marker.rs b/crates/keisoku/src/recorder/marker.rsnew file mode 100644index 000000000..065be0f61--- /dev/null+++ b/crates/keisoku/src/recorder/marker.rs@@ -0,0 +1,9 @@+use serde::{Deserialize, Serialize};++use crate::units::Milliseconds;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Marker {+ pub elapsed: Milliseconds,+ pub label: String,+}diff --git a/crates/keisoku/src/recorder/mod.rs b/crates/keisoku/src/recorder/mod.rsnew file mode 100644index 000000000..93fec7811--- /dev/null+++ b/crates/keisoku/src/recorder/mod.rs@@ -0,0 +1,11 @@+mod config;+mod device;+mod handle;+mod marker;+mod session;++pub use config::Config;+pub use device::Device;+pub use handle::{RecorderHandle, start};+pub use marker::Marker;+pub use session::Session;diff --git a/crates/keisoku/src/recorder/session.rs b/crates/keisoku/src/recorder/session.rsnew file mode 100644index 000000000..bb5d1ea82--- /dev/null+++ b/crates/keisoku/src/recorder/session.rs@@ -0,0 +1,26 @@+use serde::{Deserialize, Serialize};++use super::{Device, Marker};+use crate::{snapshot::Snapshot, units::Milliseconds};++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct Session {+ pub device: Device,+ pub interval: Milliseconds,+ pub snapshots: Vec<Snapshot>,+ pub markers: Vec<Marker>,+}++impl Session {+ pub fn to_json(&self) -> serde_json::Result<String> {+ serde_json::to_string_pretty(self)+ }++ pub fn write_json(+ &self,+ path: impl AsRef<std::path::Path>,+ ) -> std::io::Result<()> {+ let json = self.to_json().map_err(std::io::Error::other)?;+ std::fs::write(path, json)+ }+}diff --git a/crates/keisoku/src/sensor/kind.rs b/crates/keisoku/src/sensor/kind.rsnew file mode 100644index 000000000..016f14314--- /dev/null+++ b/crates/keisoku/src/sensor/kind.rs@@ -0,0 +1,39 @@+use serde::{Deserialize, Serialize};++#[cfg(target_vendor = "apple")]+use crate::sys;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum SensorKind {+ Temperature,+ Voltage,+ Current,+}++impl SensorKind {+ pub fn unit(self) -> &'static str {+ match self {+ SensorKind::Temperature => "°C",+ SensorKind::Voltage => "V",+ SensorKind::Current => "A",+ }+ }+}++#[cfg(target_vendor = "apple")]+impl SensorKind {+ pub(crate) fn matching(self) -> (i32, i32) {+ match self {+ SensorKind::Temperature => (sys::HID_PAGE_APPLE_VENDOR, sys::HID_USAGE_TEMPERATURE_SENSOR),+ SensorKind::Voltage => (sys::HID_PAGE_APPLE_VENDOR_POWER, sys::HID_USAGE_POWER_VOLTAGE),+ SensorKind::Current => (sys::HID_PAGE_APPLE_VENDOR_POWER, sys::HID_USAGE_POWER_CURRENT),+ }+ }++ pub(crate) fn event_type(self) -> i64 {+ match self {+ SensorKind::Temperature => sys::EVENT_TYPE_TEMPERATURE,+ SensorKind::Voltage | SensorKind::Current => sys::EVENT_TYPE_POWER,+ }+ }+}diff --git a/crates/keisoku/src/sensor/mod.rs b/crates/keisoku/src/sensor/mod.rsnew file mode 100644index 000000000..ff6735e2d--- /dev/null+++ b/crates/keisoku/src/sensor/mod.rs@@ -0,0 +1,17 @@+mod kind;+mod reading;++pub use kind::SensorKind;+pub use reading::Sensor;++pub fn thermal_sensors() -> Vec<Sensor> {+ crate::sensors(SensorKind::Temperature)+}++pub fn voltage_sensors() -> Vec<Sensor> {+ crate::sensors(SensorKind::Voltage)+}++pub fn current_sensors() -> Vec<Sensor> {+ crate::sensors(SensorKind::Current)+}diff --git a/crates/keisoku/src/sensor/reading.rs b/crates/keisoku/src/sensor/reading.rsnew file mode 100644index 000000000..3b7e27882--- /dev/null+++ b/crates/keisoku/src/sensor/reading.rs@@ -0,0 +1,16 @@+use serde::{Deserialize, Serialize};++use super::SensorKind;+use crate::component::Component;++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Sensor {+ pub name: String,+ pub value: f64,+ pub kind: SensorKind,+ pub component: Component,+ pub manufacturer: Option<String>,+ pub category: Option<String>,+ pub location_id: Option<i64>,+ pub registry_id: u64,+}diff --git a/crates/keisoku/src/smc/mod.rs b/crates/keisoku/src/smc/mod.rsnew file mode 100644index 000000000..80c3dcd96--- /dev/null+++ b/crates/keisoku/src/smc/mod.rs@@ -0,0 +1,186 @@+use core::ffi::c_void;++use obfstr::obfstr;+use objc2_core_foundation::{CFDictionary, CFRetained};+use objc2_io_kit::{+ IOConnectCallStructMethod, IOIteratorNext, IOObjectRelease, IOServiceClose, IOServiceGetMatchingServices,+ IOServiceMatching, IOServiceOpen, io_connect_t, io_iterator_t,+};++use crate::{+ metrics::{Fan, FanMetrics},+ units::{Rpm, Watts},+};++const KERNEL_INDEX_SMC: u32 = 2;+const SMC_CMD_READ_BYTES: u8 = 5;+const SMC_CMD_READ_KEYINFO: u8 = 9;++#[repr(C)]+#[derive(Clone, Copy, Default)]+struct SmcVersion {+ major: u8,+ minor: u8,+ build: u8,+ reserved: u8,+ release: u16,+}++#[repr(C)]+#[derive(Clone, Copy, Default)]+struct SmcLimitData {+ version: u16,+ length: u16,+ cpu_plimit: u32,+ gpu_plimit: u32,+ mem_plimit: u32,+}++#[repr(C)]+#[derive(Clone, Copy, Default)]+struct SmcKeyInfo {+ data_size: u32,+ data_type: u32,+ data_attributes: u8,+}++#[repr(C)]+#[derive(Clone, Copy, Default)]+struct SmcKeyData {+ key: u32,+ version: SmcVersion,+ limit: SmcLimitData,+ key_info: SmcKeyInfo,+ result: u8,+ status: u8,+ data8: u8,+ data32: u32,+ bytes: [u8; 32],+}++const _: () = assert!(core::mem::size_of::<SmcKeyData>() == 80);++pub struct Smc {+ connection: io_connect_t,+}++impl Smc {+ #[allow(deprecated)]+ pub fn new() -> Option<Self> {+ let name = std::ffi::CString::new(obfstr!("AppleSMC")).ok()?;+ let matching = unsafe { IOServiceMatching(name.as_ptr()) }?;+ let matching: CFRetained<CFDictionary> = unsafe { CFRetained::from_raw(CFRetained::into_raw(matching).cast()) };+ let mut iterator: io_iterator_t = 0;+ if unsafe { IOServiceGetMatchingServices(0, Some(matching), &mut iterator) } != 0 {+ return None;+ }+ let device = IOIteratorNext(iterator);+ IOObjectRelease(iterator);+ if device == 0 {+ return None;+ }+ let mut connection: io_connect_t = 0;+ let result = unsafe { IOServiceOpen(device, libc::mach_task_self(), 0, &mut connection) };+ IOObjectRelease(device);+ (result == 0).then_some(Self {+ connection,+ })+ }++ pub fn package_watts(&self) -> Option<Watts> {+ self.read_f32(obfstr!("PSTR")).map(Watts)+ }++ pub fn fans(&self) -> FanMetrics {+ let count = self.read_u8(obfstr!("FNum")).unwrap_or(0);+ let fans = (0..count)+ .map(|index| Fan {+ actual: Rpm(self.fan_speed(index, obfstr!("Ac"))),+ minimum: Rpm(self.fan_speed(index, obfstr!("Mn"))),+ maximum: Rpm(self.fan_speed(index, obfstr!("Mx"))),+ target: Rpm(self.fan_speed(index, obfstr!("Tg"))),+ })+ .collect();+ FanMetrics {+ fans,+ }+ }++ fn fan_speed(+ &self,+ index: u8,+ suffix: &str,+ ) -> f32 {+ self.read_f32(&format!("{}{}{}", obfstr!("F"), index, suffix)).unwrap_or(0.0)+ }++ fn read_f32(+ &self,+ key: &str,+ ) -> Option<f32> {+ let (data_type, bytes) = self.read_key(key)?;+ (data_type == fourcc(obfstr!("flt "))?).then(|| f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))+ }++ fn read_u8(+ &self,+ key: &str,+ ) -> Option<u8> {+ self.read_key(key).map(|(_, bytes)| bytes[0])+ }++ fn read_key(+ &self,+ key: &str,+ ) -> Option<(u32, [u8; 32])> {+ let key = fourcc(key)?;+ let info = self.call(&SmcKeyData {+ key,+ data8: SMC_CMD_READ_KEYINFO,+ ..Default::default()+ })?;+ let value = self.call(&SmcKeyData {+ key,+ key_info: SmcKeyInfo {+ data_size: info.key_info.data_size,+ ..Default::default()+ },+ data8: SMC_CMD_READ_BYTES,+ ..Default::default()+ })?;+ Some((info.key_info.data_type, value.bytes))+ }++ fn call(+ &self,+ input: &SmcKeyData,+ ) -> Option<SmcKeyData> {+ let mut output = SmcKeyData::default();+ let mut output_size = core::mem::size_of::<SmcKeyData>();+ let result = unsafe {+ IOConnectCallStructMethod(+ self.connection,+ KERNEL_INDEX_SMC,+ (input as *const SmcKeyData).cast::<c_void>(),+ core::mem::size_of::<SmcKeyData>(),+ (&mut output as *mut SmcKeyData).cast::<c_void>(),+ &mut output_size,+ )+ };+ (result == 0 && output.result == 0).then_some(output)+ }+}++impl Drop for Smc {+ fn drop(&mut self) {+ IOServiceClose(self.connection);+ }+}++fn fourcc(key: &str) -> Option<u32> {+ let bytes = key.as_bytes();+ if bytes.len() != 4 {+ return None;+ }+ Some((bytes[0] as u32) << 24 | (bytes[1] as u32) << 16 | (bytes[2] as u32) << 8 | bytes[3] as u32)+}diff --git a/crates/keisoku/src/snapshot.rs b/crates/keisoku/src/snapshot.rsnew file mode 100644index 000000000..b503c2e78--- /dev/null+++ b/crates/keisoku/src/snapshot.rs@@ -0,0 +1,26 @@+use serde::{Deserialize, Serialize};++use crate::{+ metrics::{+ BandwidthMetrics, BatteryMetrics, CpuMetrics, FanMetrics, GpuMetrics, MemoryMetrics, NeuralEngineMetrics,+ PowerMetrics, Temperatures, ThermalPressure,+ },+ sensor::Sensor,+ units::Milliseconds,+};++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+pub struct Snapshot {+ pub elapsed: Milliseconds,+ pub cpu: Option<CpuMetrics>,+ pub gpu: Option<GpuMetrics>,+ pub neural_engine: Option<NeuralEngineMetrics>,+ pub power: Option<PowerMetrics>,+ pub memory: Option<MemoryMetrics>,+ pub bandwidth: Option<BandwidthMetrics>,+ pub fans: Option<FanMetrics>,+ pub battery: Option<BatteryMetrics>,+ pub temperatures: Option<Temperatures>,+ pub thermal_pressure: Option<ThermalPressure>,+ pub sensors: Vec<Sensor>,+}diff --git a/crates/keisoku/src/soc.rs b/crates/keisoku/src/soc.rsnew file mode 100644index 000000000..64f70ac25--- /dev/null+++ b/crates/keisoku/src/soc.rs@@ -0,0 +1,166 @@+use objc2_core_foundation::CFDictionary;+use serde::Serialize;++use crate::cf::{IoServiceIterator, dictionary_data, registry_properties};++#[derive(Debug, Default, Clone, Serialize)]+pub struct SocInfo {+ pub chip_name: String,+ pub mac_model: String,+ pub memory_gigabytes: u8,+ pub ecpu_cores: u8,+ pub pcpu_cores: u8,+ pub ecpu_label: String,+ pub pcpu_label: String,+ pub gpu_cores: u8,+ pub ecpu_frequencies: Vec<u32>,+ pub pcpu_frequencies: Vec<u32>,+ pub gpu_frequencies: Vec<u32>,+}++fn dvfs_frequencies(+ dictionary: &CFDictionary,+ key: &str,+) -> Option<Vec<u32>> {+ let bytes = dictionary_data(dictionary, key)?;+ if bytes.len() < 8 {+ return None;+ }+ let frequencies =+ bytes.chunks_exact(8).map(|chunk| u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])).collect();+ Some(frequencies)+}++fn to_megahertz(+ frequencies: Vec<u32>,+ scale: u32,+) -> Vec<u32> {+ frequencies.iter().map(|frequency| frequency / scale).collect()+}++fn cluster_voltage_state_keys(dictionary: &CFDictionary) -> Option<(String, String)> {+ let data = dictionary_data(dictionary, "acc-clusters")?;+ if data.len() < 8 {+ return None;+ }+ let mut clusters: Vec<(u8, String)> =+ data.chunks_exact(8).map(|cluster| (cluster[1], format!("voltage-states{}-sram", cluster[0]))).collect();+ clusters.sort_by_key(|cluster| cluster.0);+ if clusters.len() < 2 {+ return None;+ }+ let ecpu_key = clusters[clusters.len() - 2].1.clone();+ let pcpu_key = clusters[clusters.len() - 1].1.clone();+ Some((ecpu_key, pcpu_key))+}++fn cpu_frequencies(+ dictionary: &CFDictionary,+ key: &str,+ is_efficiency_cluster: bool,+ scale: u32,+) -> Option<Vec<u32>> {+ if let Some(frequencies) = dvfs_frequencies(dictionary, key) {+ return Some(to_megahertz(frequencies, scale));+ }+ let (ecpu_key, pcpu_key) = cluster_voltage_state_keys(dictionary)?;+ let key = if is_efficiency_cluster {+ ecpu_key+ } else {+ pcpu_key+ };+ Some(to_megahertz(dvfs_frequencies(dictionary, &key)?, scale))+}++fn parse_cpu_cores(processors: &str) -> (u64, u64, bool) {+ let counts: Vec<u64> =+ processors.strip_prefix("proc ").unwrap_or("").split(':').map(|count| count.parse().unwrap_or(0)).collect();+ match counts.len() {+ 4 => {+ let (efficiency_cores, media_cores) = (counts[2], counts[3]);+ if media_cores > 0 {+ (media_cores, counts[1], true)+ } else {+ (efficiency_cores, counts[1], false)+ }+ },+ 3 => (counts[2], counts[1], false),+ _ => (0, 0, false),+ }+}++fn run_system_profiler() -> Option<serde_json::Value> {+ let output = std::process::Command::new("system_profiler")+ .args(["SPHardwareDataType", "SPDisplaysDataType", "-json"])+ .output()+ .ok()?;+ serde_json::from_slice(&output.stdout).ok()+}++impl SocInfo {+ pub fn new() -> Option<Self> {+ let profiler = run_system_profiler()?;+ let hardware = &profiler["SPHardwareDataType"][0];++ let chip_name = hardware["chip_type"].as_str().unwrap_or("Unknown chip").to_string();+ let mac_model = hardware["machine_model"].as_str().unwrap_or("Unknown model").to_string();+ let memory_gigabytes = hardware["physical_memory"]+ .as_str()+ .and_then(|memory| memory.strip_suffix(" GB"))+ .and_then(|gigabytes| gigabytes.parse::<u64>().ok())+ .unwrap_or(0) as u8;+ let (ecpu_cores, pcpu_cores, has_media_cluster) =+ parse_cpu_cores(hardware["number_processors"].as_str().unwrap_or(""));+ let gpu_cores = profiler["SPDisplaysDataType"][0]["sppci_cores"]+ .as_str()+ .and_then(|cores| cores.parse::<u64>().ok())+ .unwrap_or(0) as u8;++ let before_m4 = chip_name.contains("M1") || chip_name.contains("M2") || chip_name.contains("M3");+ let cpu_scale: u32 = if before_m4 {+ 1000 * 1000+ } else {+ 1000+ };+ let gpu_scale: u32 = 1000 * 1000;++ let mut soc_info = SocInfo {+ chip_name,+ mac_model,+ memory_gigabytes,+ ecpu_cores: ecpu_cores as u8,+ pcpu_cores: pcpu_cores as u8,+ ecpu_label: if has_media_cluster {+ "P".into()+ } else {+ "E".into()+ },+ pcpu_label: if has_media_cluster {+ "S".into()+ } else {+ "P".into()+ },+ gpu_cores,+ ..Default::default()+ };++ for (entry, name) in IoServiceIterator::new("AppleARMIODevice")? {+ if name != "pmgr" {+ continue;+ }+ if let Some(properties) = registry_properties(entry) {+ if let Some(frequencies) = cpu_frequencies(&properties, "voltage-states1-sram", true, cpu_scale) {+ soc_info.ecpu_frequencies = frequencies;+ }+ if let Some(frequencies) = cpu_frequencies(&properties, "voltage-states5-sram", false, cpu_scale) {+ soc_info.pcpu_frequencies = frequencies;+ }+ if let Some(frequencies) = dvfs_frequencies(&properties, "voltage-states9") {+ soc_info.gpu_frequencies = to_megahertz(frequencies, gpu_scale);+ }+ }+ }++ Some(soc_info)+ }+}diff --git a/crates/keisoku/src/sys.rs b/crates/keisoku/src/sys.rsnew file mode 100644index 000000000..98bef9e24--- /dev/null+++ b/crates/keisoku/src/sys.rs@@ -0,0 +1,12 @@+pub(crate) const HID_PAGE_APPLE_VENDOR: i32 = 0xff00;+pub(crate) const HID_PAGE_APPLE_VENDOR_POWER: i32 = 0xff08;+pub(crate) const HID_USAGE_TEMPERATURE_SENSOR: i32 = 0x0005;+pub(crate) const HID_USAGE_POWER_VOLTAGE: i32 = 0x0003;+pub(crate) const HID_USAGE_POWER_CURRENT: i32 = 0x0002;++pub(crate) const EVENT_TYPE_TEMPERATURE: i64 = 15;+pub(crate) const EVENT_TYPE_POWER: i64 = 25;++pub(crate) const fn event_field_base(event_type: i64) -> i32 {+ (event_type as i32) << 16+}diff --git a/crates/keisoku/src/units.rs b/crates/keisoku/src/units.rsnew file mode 100644index 000000000..9404d4f24--- /dev/null+++ b/crates/keisoku/src/units.rs@@ -0,0 +1,42 @@+use serde::{Deserialize, Serialize};++macro_rules! unit {+ ($(#[$doc:meta])* $name:ident($inner:ty) = $suffix:literal) => {+ $(#[$doc])*+ #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Serialize, Deserialize)]+ #[serde(transparent)]+ #[repr(transparent)]+ pub struct $name(pub $inner);++ impl $name {++ pub const fn value(self) -> $inner {+ self.0+ }+ }++ impl core::fmt::Display for $name {+ fn fmt(+ &self,+ formatter: &mut core::fmt::Formatter<'_>,+ ) -> core::fmt::Result {+ write!(formatter, "{} {}", self.0, $suffix)+ }+ }++ impl From<$inner> for $name {+ fn from(value: $inner) -> Self {+ Self(value)+ }+ }+ };+}++unit!(Watts(f32) = "W");+unit!(Percent(f32) = "%");+unit!(Celsius(f32) = "°C");+unit!(Megahertz(u32) = "MHz");+unit!(GigabytesPerSecond(f32) = "GB/s");+unit!(Bytes(u64) = "B");+unit!(Milliseconds(u64) = "ms");+unit!(Rpm(f32) = "rpm");diff --git a/crates/keisoku/tests/table.rs b/crates/keisoku/tests/table.rsnew file mode 100644index 000000000..cbf5c3f26--- /dev/null+++ b/crates/keisoku/tests/table.rs@@ -0,0 +1,78 @@+use std::time::Duration;++use keisoku::Collector;+use ratatui::{+ Terminal,+ backend::TestBackend,+ layout::Constraint,+ style::{Color, Modifier, Style},+ widgets::{Block, Borders, Row, Table},+};++#[test]+fn render_table() {+ let mut collector = Collector::new();+ let device = collector.device();+ let snapshot = collector.sample(Duration::from_millis(300));++ let na = "—";+ let mut lines: Vec<[String; 3]> = vec![+ ["CPU".into(), snapshot.cpu.as_ref().map_or(na.into(), |c| format!("{:.1} %", c.usage.value())), String::new()],+ ["GPU".into(), snapshot.gpu.as_ref().map_or(na.into(), |g| format!("{:.0} %", g.usage.value())), String::new()],+ [+ "ANE".into(),+ snapshot.neural_engine.as_ref().map_or(na.into(), |a| format!("{:.0} %", a.active.value())),+ String::new(),+ ],+ [+ "Power".into(),+ snapshot.power.as_ref().map_or(na.into(), |p| format!("{:.2} W", p.package.value())),+ String::new(),+ ],+ [+ "Memory".into(),+ snapshot.memory.as_ref().map_or(na.into(), |m| {+ format!("{:.1} / {:.1} GB", m.ram_usage.value() as f64 / 1e9, m.ram_total.value() as f64 / 1e9)+ }),+ String::new(),+ ],+ [+ "CPU temp".into(),+ snapshot+ .temperatures+ .as_ref()+ .and_then(|t| t.cpu_average)+ .map_or(na.into(), |c| format!("{:.1} °C", c.value())),+ String::new(),+ ],+ [+ "GPU temp".into(),+ snapshot+ .temperatures+ .as_ref()+ .and_then(|t| t.gpu_average)+ .map_or(na.into(), |g| format!("{:.1} °C", g.value())),+ String::new(),+ ],+ ["────────".into(), "──────".into(), "──────────".into()],+ ];+ for sensor in &snapshot.sensors {+ lines.push([sensor.name.clone(), format!("{:.1}", sensor.value), sensor.component.to_string()]);+ }++ let accent = Style::default().fg(Color::Green);+ let height = (lines.len() + 4) as u16;+ let header = Row::new(["Metric", "Value", "Detail"]).style(accent.add_modifier(Modifier::BOLD));+ let rows: Vec<Row> = lines.into_iter().map(Row::new).collect();+ let table = Table::new(rows, [Constraint::Length(20), Constraint::Length(16), Constraint::Min(22)])+ .header(header)+ .block(Block::default().borders(Borders::ALL).border_style(accent).title(format!(+ " kanshi · {} · {:.0} GB ",+ device.chip,+ device.ram_total.value() as f64 / 1e9+ )));++ let mut terminal = Terminal::new(TestBackend::new(66, height)).unwrap();+ terminal.draw(|frame| frame.render_widget(table, frame.area())).unwrap();+ println!("\n{}", terminal.backend());+}diff --git a/crates/keisoku/tests/telemetry.rs b/crates/keisoku/tests/telemetry.rsnew file mode 100644index 000000000..cf888e9d7--- /dev/null+++ b/crates/keisoku/tests/telemetry.rs@@ -0,0 +1,56 @@+use std::time::Duration;++use keisoku::Collector;++#[test]+fn available_telemetry() {+ let mut collector = Collector::new();+ let device = collector.device();+ let snapshot = collector.sample(Duration::from_millis(300));+ let flag = |present: bool| {+ if present {+ "yes"+ } else {+ "--"+ }+ };++ println!("--- keisoku available telemetry ---");+ println!(+ "device {} {}E+{}P {} GPU {:.1} GB",+ device.chip,+ device.efficiency_cores,+ device.performance_cores,+ device.gpu_cores,+ device.ram_total.value() as f64 / 1e9,+ );+ println!("cpu {}", flag(snapshot.cpu.is_some()));+ println!("gpu {}", flag(snapshot.gpu.is_some()));+ println!("neural {}", flag(snapshot.neural_engine.is_some()));+ println!("power {}", flag(snapshot.power.is_some()));+ println!("bandwidth {}", flag(snapshot.bandwidth.is_some()));+ println!("memory {}", flag(snapshot.memory.is_some()));+ println!("fans {}", flag(snapshot.fans.is_some()));+ println!("battery {}", flag(snapshot.battery.is_some()));+ println!("temps {}", flag(snapshot.temperatures.is_some()));+ println!("sensors {}", snapshot.sensors.len());++ if let Some(memory) = &snapshot.memory {+ println!(+ " ram {:.2} / {:.2} GB",+ memory.ram_usage.value() as f64 / 1e9,+ memory.ram_total.value() as f64 / 1e9,+ );+ }+ if let Some(temperatures) = &snapshot.temperatures {+ if let Some(cpu) = temperatures.cpu_average {+ println!(" cpu temp {:.1} C", cpu.value());+ }+ if let Some(gpu) = temperatures.gpu_average {+ println!(" gpu temp {:.1} C", gpu.value());+ }+ }+ for sensor in snapshot.sensors.iter().take(24) {+ println!(" {:<26} {:>8.2} [{}]", sensor.name, sensor.value, sensor.component);+ }+}diff --git a/crates/test-runner/Cargo.toml b/crates/test-runner/Cargo.tomlindex c7346f78c..c41ddb424 100644--- a/crates/test-runner/Cargo.toml+++ b/crates/test-runner/Cargo.toml@@ -17,10 +17,8 @@ nightly-harness = [][dependencies]criterion.workspace = true--[target.'cfg(target_os = "macos")'.dependencies]# for getting gpu temperature-macmon.workspace = true+keisoku.workspace = true[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]objc2 = { workspace = true, optional = true }diff --git a/crates/test-runner/src/metrics.rs b/crates/test-runner/src/metrics.rsindex 32e502630..cfb29f94f 100644--- a/crates/test-runner/src/metrics.rs+++ b/crates/test-runner/src/metrics.rs@@ -3,16 +3,15 @@ use std::{thread::sleep, time::Duration};const COOL_GPU_TEMP: f32 = 60.0;fn get_gpu_temp() -> f32 {- #[cfg(target_os = "macos")]- {- use macmon::Sampler;- let mut sample = Sampler::new().unwrap();- let metrics = sample.get_metrics(0).unwrap();- metrics.temp.gpu_temp_avg+ let (sum, count) = keisoku::thermal_sensors()+ .iter()+ .filter(|sensor| sensor.component == keisoku::Component::Gpu)+ .fold((0.0f32, 0u32), |(sum, count), sensor| (sum + sensor.value as f32, count + 1));+ if count == 0 {+ 0.0+ } else {+ sum / count as f32}-- #[cfg(not(target_os = "macos"))]- 0.0f32}pub fn wait_gpu_cooldown() {