commit c3a95699189ee03057178a197bf0406fd7c86d55 Author: RarDog Date: Sun Sep 13 18:29:47 2026 +0300 feat: initial commit of diagd - unified Linux/BSD/macOS/Windows diagnostic tool (TUI + GUI) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ff20cd4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,64 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Rust / Cargo +/target/ +**/*.rs.bk +*.pdb + +# Ephemeral Flutter folders +linux/flutter/ephemeral/ +windows/flutter/ephemeral/ +macos/Flutter/ephemeral/ +.flutter-plugins +.flutter-plugins-dependencies + +# Debug archives +*.tar.gz +*.zip + +# Widget Preview related +.widget_preview/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..f6b002e --- /dev/null +++ b/.metadata @@ -0,0 +1,33 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "e8113bf45620cbeb8aff64947ee4c93e16adb4cf" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: e8113bf45620cbeb8aff64947ee4c93e16adb4cf + base_revision: e8113bf45620cbeb8aff64947ee4c93e16adb4cf + - platform: macos + create_revision: e8113bf45620cbeb8aff64947ee4c93e16adb4cf + base_revision: e8113bf45620cbeb8aff64947ee4c93e16adb4cf + - platform: windows + create_revision: e8113bf45620cbeb8aff64947ee4c93e16adb4cf + base_revision: e8113bf45620cbeb8aff64947ee4c93e16adb4cf + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..2b983c4 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2496 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allo-isolate" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "449e356a4864c017286dbbec0e12767ea07efba29e3b7d984194c2a7ff3c4550" +dependencies = [ + "anyhow", + "atomic", + "backtrace", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_log-sys" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d" + +[[package]] +name = "android_logger" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbb4e440d04be07da1f1bf44fb4495ebd58669372fe0cffa6e48595ac5bd88a3" +dependencies = [ + "android_log-sys", + "env_filter", + "log", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "atomic" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "backtrace" +version = "0.3.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide 0.8.9", + "object", + "rustc-demangle", + "windows-link", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "build-target" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "832133bbabbbaa9fbdba793456a2827627a7d2b8fb96032fa1e7666d7895832b" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "compact_str" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix 0.38.44", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.5", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "dart-sys" +version = "4.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57967e4b200d767d091b961d6ab42cc7d0cc14fe9e052e75d0d3cf9eb732d895" +dependencies = [ + "cc", +] + +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "delegate-attr" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a84c9a9c129b98e707ac9a31e204c10c064dd9f949b7da362310ff1a8b137d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "diagd-core" +version = "0.1.0" +dependencies = [ + "chrono", + "flate2", + "libc", + "regex", + "reqwest", + "serde", + "serde_json", + "tar", + "tokio", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "encoding_rs" +version = "0.8.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5ef0006ac9ab233c38522f5ae99cae3625151de8f706cacee1cba4b8e2832a" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "env_filter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "flutter_rust_bridge" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24a973d15b8fc7de9fb29cdfbec58a2ac41f6252492d3b882abfdc603e32b34f" +dependencies = [ + "allo-isolate", + "android_logger", + "anyhow", + "build-target", + "bytemuck", + "byteorder", + "console_error_panic_hook", + "dart-sys", + "delegate-attr", + "flutter_rust_bridge_macros", + "futures", + "js-sys", + "lazy_static", + "log", + "oslog", + "portable-atomic", + "threadpool", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "flutter_rust_bridge_macros" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901eec2d226107dad1c55b30f7421c4687bebcf70ed43ca44d1b447ca087b238" +dependencies = [ + "hex", + "md-5", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf84e73fa6f27f299dec58e13223cf70db80da872eb921d4f6138342a0eabc8" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ca4bea16ffc3f443cf7d866912118196bfef4c6a1556ca00f9f9b00bb43f7c" +dependencies = [ + "multiversion-macros", +] + +[[package]] +name = "multiversion-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d416831a7317ef4b08bee00b69cbbb9c8763da7959a7026244d6266869f9c83" +dependencies = [ + "proc-macro2", + "quote", + "rustversion", + "syn 3.0.5", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "object" +version = "0.37.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "oslog" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d2043d1f61d77cb2f4b1f7b7b2295f40507f5f8e9d1c8bf10a1ca5f97a3969" +dependencies = [ + "cc", + "dashmap", + "log", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools", + "lru", + "paste", + "strum", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-core", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rust_lib_diagd" +version = "0.1.0" +dependencies = [ + "chrono", + "crossterm", + "diagd-core", + "flutter_rust_bridge", + "ratatui", + "regex", + "reqwest", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "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", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6725596c3f2c3a0aef021139e145d4eafe314a6623e4680ca83852b2c67ab2ba" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.1.14", +] + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.5", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.4", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..aaf02b0 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[workspace] +resolver = "2" +members = [ + "crates/core", + "rust", +] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4289410 --- /dev/null +++ b/Makefile @@ -0,0 +1,30 @@ +.PHONY: all tui gui clean help + +all: tui gui + +help: + @echo "Использование: make [цель]" + @echo "" + @echo "Цели:" + @echo " tui Собрать консольный интерактивный TUI (Linux / BSD, без Flutter/GTK)" + @echo " gui Собрать графический Flutter Desktop GUI (Linux GTK)" + @echo " all Собрать оба интерфейса" + @echo " clean Очистить артефакты сборки Cargo и Flutter" + @echo "" + @echo "Примеры:" + @echo " make tui -> target/release/diagd" + @echo " make gui -> build/linux/x64/release/bundle/diagd" + +tui: + @echo "==> Сборка автономного TUI (Ratatui, Linux + BSD)..." + cargo build --release -p rust_lib_diagd --no-default-features --features tui --bin diagd + @echo "✓ Готово: target/release/diagd" + +gui: + @echo "==> Сборка графического интерфейса GUI (Flutter Desktop Linux)..." + flutter build linux --release + @echo "✓ Готово: build/linux/x64/release/bundle/diagd" + +clean: + cargo clean + flutter clean diff --git a/README.md b/README.md new file mode 100644 index 0000000..1f34ef9 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# diagd + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..2cb8f46 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,36 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +analyzer: + exclude: + - build/** + - linux/** + + - rust_builder/cargokit/** + - windows/** + - macos/** +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/build.bat b/build.bat new file mode 100644 index 0000000..01da947 --- /dev/null +++ b/build.bat @@ -0,0 +1,48 @@ +@echo off +setlocal + +set TARGET=%1 +if "%TARGET%"=="" set TARGET=help + +if "%TARGET%"=="tui" goto build_tui +if "%TARGET%"=="gui" goto build_gui +if "%TARGET%"=="all" goto build_all +if "%TARGET%"=="help" goto show_help + +:show_help +echo Использование: build.bat {tui^|gui^|all} +echo. +echo tui - Собрать автономный консольный TUI (diagd.exe) +echo gui - Собрать графический интерфейс Flutter Desktop (Windows) +echo all - Собрать оба варианта +exit /b 0 + +:build_tui +echo ==^> Сборка автономного консольного TUI под Windows... +cargo build --release -p rust_lib_diagd --no-default-features --features tui --bin diagd +if %ERRORLEVEL% equ 0 ( + echo [OK] Успешно собрано: target\release\diagd.exe +) else ( + echo [ERROR] Ошибка сборки TUI + exit /b %ERRORLEVEL% +) +exit /b 0 + +:build_gui +echo ==^> Сборка графического GUI (Flutter Desktop Windows)... +flutter build windows --release +if %ERRORLEVEL% equ 0 ( + echo [OK] Успешно собрано: build\windows\x64\runner\Release\diagd.exe +) else ( + echo [ERROR] Ошибка сборки GUI + exit /b %ERRORLEVEL% +) +exit /b 0 + +:build_all +call :build_tui +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% +call :build_gui +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% +echo [OK] Все компоненты успешно собраны! +exit /b 0 diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..23cd4ac --- /dev/null +++ b/build.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -e + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" +cd "$DIR" + +TARGET="${1:-help}" + +case "$TARGET" in + tui) + echo "==> Сборка автономного консольного TUI (Linux / BSD)..." + cargo build --release -p rust_lib_diagd --no-default-features --features tui --bin diagd + echo "✓ Успешно собрано: $DIR/target/release/diagd" + ;; + gui) + echo "==> Сборка графического GUI (Flutter Desktop Linux)..." + flutter build linux --release + echo "✓ Успешно собрано: $DIR/build/linux/x64/release/bundle/diagd" + ;; + all) + echo "==> Сборка TUI и GUI..." + cargo build --release -p rust_lib_diagd --no-default-features --features tui --bin diagd + flutter build linux --release + echo "✓ Все интерфейсы собраны!" + ;; + *) + echo "Использование: $0 {tui|gui|all}" + echo "" + echo " tui - собрать консольный TUI (на базе Ratatui, работает на Linux и BSD)" + echo " gui - собрать графический интерфейс (на базе Flutter Desktop для Linux)" + echo " all - собрать оба варианта" + exit 1 + ;; +esac diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml new file mode 100644 index 0000000..f402e10 --- /dev/null +++ b/crates/core/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "diagd-core" +version = "0.1.0" +edition = "2021" +description = "Core diagnostic engine for Linux and BSD systems" + +[dependencies] +tokio = { version = "1", features = ["full"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +regex = "1.10" +reqwest = { version = "0.12", features = ["json"] } +chrono = { version = "0.4", features = ["serde"] } +libc = "0.2" +flate2 = "1.0" +tar = "0.4" diff --git a/crates/core/src/analyst.rs b/crates/core/src/analyst.rs new file mode 100644 index 0000000..f436133 --- /dev/null +++ b/crates/core/src/analyst.rs @@ -0,0 +1,810 @@ +use crate::models::{ + DiagnosticIssue, FixSuggestion, IssueItem, Severity, Subsystem, SubsystemStatus, SystemReport, +}; +use crate::sanitize::DataSanitizer; +use crate::scanner::UnifiedRawData; +use serde::Serialize; + +#[derive(Serialize)] +pub struct LlmDiagnosticPrompt { + pub role: String, + pub system_instruction: String, + pub os_family: String, + pub init_system: String, + pub is_root: bool, + pub sanitized_context: SanitizedContextPayload, +} + +#[derive(Serialize)] +pub struct SanitizedContextPayload { + pub failed_services: Vec, + pub kernel_summary: KernelSummaryPayload, + pub system_limits: LimitsSummaryPayload, + pub storage_alerts: Vec, + pub hardware_summary: HardwareSummaryPayload, + pub network_summary: NetworkSummaryPayload, + pub raw_sanitized_logs: String, +} + +#[derive(Serialize)] +pub struct HardwareSummaryPayload { + pub max_cpu_temp_c: f32, + pub thermal_throttled_cores: usize, + pub total_throttle_events: u64, + pub is_actively_throttling: bool, + pub battery_degraded: bool, + pub edac_memory_errors: u64, +} + +#[derive(Serialize)] +pub struct NetworkSummaryPayload { + pub dns_broken_symlink: bool, + pub dns_resolution_ok: bool, + pub dns_latency_ms: Option, + pub has_default_gateway: bool, + pub firewall_conflict: Option, + pub wifi_drops_count: usize, +} + +#[derive(Serialize)] +pub struct FailedServiceSummary { + pub name: String, + pub init_system: String, + pub state: String, + pub error_snippet: String, +} + +#[derive(Serialize)] +pub struct KernelSummaryPayload { + pub tainted_flags: Vec, + pub oom_events_count: usize, + pub gpu_hangs_count: usize, + pub io_errors_count: usize, + pub csum_errors_count: usize, + pub permission_denied: bool, +} + +#[derive(Serialize)] +pub struct LimitsSummaryPayload { + pub file_descriptors_exhausted: bool, + pub recent_coredumps: Vec, + pub memory_pressure_avg10: f32, + pub io_pressure_avg10: f32, +} + +impl LlmDiagnosticPrompt { + pub fn build(data: &UnifiedRawData) -> (String, Self) { + let failed_summary: Vec = data + .failed_services + .iter() + .map(|s| FailedServiceSummary { + name: s.name.clone(), + init_system: s.init_system.clone(), + state: s.state.clone(), + error_snippet: DataSanitizer::sanitize(&s.logs) + .lines() + .take(6) + .collect::>() + .join("\n"), + }) + .collect(); + + let kernel_summary = KernelSummaryPayload { + tainted_flags: data.kernel_scan.tainted_flags.clone(), + oom_events_count: data.kernel_scan.oom_events.len(), + gpu_hangs_count: data.kernel_scan.gpu_hangs.len(), + io_errors_count: data.kernel_scan.io_errors.len(), + csum_errors_count: data.kernel_scan.csum_errors.len(), + permission_denied: data.kernel_scan.permission_denied, + }; + + let limits_summary = LimitsSummaryPayload { + file_descriptors_exhausted: data.limits_scan.file_descriptors_exhausted, + recent_coredumps: data.limits_scan.recent_coredumps.clone(), + memory_pressure_avg10: data.pressure_scan.mem_some_avg10, + io_pressure_avg10: data.pressure_scan.io_some_avg10, + }; + + let storage_alerts: Vec = data + .storage_mounts + .iter() + .filter(|m| m.is_critical) + .map(|m| { + format!( + "Mount {}: space used {:.1}%, inode used {:.1}%", + m.mount_point, m.used_percent, m.inode_used_percent + ) + }) + .collect(); + + let hardware_summary = HardwareSummaryPayload { + max_cpu_temp_c: data.hardware_scan.max_cpu_temp_c, + thermal_throttled_cores: data.hardware_scan.thermal_throttled_cores, + total_throttle_events: data.hardware_scan.total_throttle_events, + is_actively_throttling: data.hardware_scan.is_actively_throttling, + battery_degraded: data.hardware_scan.battery_health.as_ref().map(|b| b.is_degraded).unwrap_or(false), + edac_memory_errors: data.hardware_scan.edac_ce_count + data.hardware_scan.edac_ue_count, + }; + + let network_summary = NetworkSummaryPayload { + dns_broken_symlink: data.network_deep_scan.dns_broken_symlink, + dns_resolution_ok: data.network_deep_scan.dns_resolution_ok, + dns_latency_ms: data.network_deep_scan.dns_latency_ms, + has_default_gateway: data.network_deep_scan.has_default_gateway, + firewall_conflict: data.network_deep_scan.firewall_conflict.clone(), + wifi_drops_count: data.network_deep_scan.wifi_drop_events.len(), + }; + + let mut combined_logs = String::new(); + combined_logs.push_str(&DataSanitizer::sanitize(&data.kernel_scan.raw_logs)); + combined_logs.push_str("\n"); + combined_logs.push_str(&DataSanitizer::sanitize(&data.service_logs)); + + let payload = SanitizedContextPayload { + failed_services: failed_summary, + kernel_summary, + system_limits: limits_summary, + storage_alerts, + hardware_summary, + network_summary, + raw_sanitized_logs: combined_logs, + }; + + let prompt_obj = Self { + role: "Unix/Linux Systems Reliability Engineer & AI Diagnostic Analyst".to_string(), + system_instruction: format!( + "Analyze the sanitized {} ({}) system diagnostics. Identify all anomalies, assign severity (Critical/Warning/Info), determine exact root cause, and provide precise bash/sh commands specifically tailored for init system '{}' and this OS family.", + data.os_name, data.init_name, data.init_name + ), + os_family: data.os_name.clone(), + init_system: data.init_name.clone(), + is_root: data.is_root, + sanitized_context: payload, + }; + + let json_preview = serde_json::to_string_pretty(&prompt_obj).unwrap_or_default(); + (json_preview, prompt_obj) + } +} + +pub async fn try_query_llm(prompt: &str) -> Option { + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(4)) + .build() + .ok()?; + + let body = serde_json::json!({ + "model": "llama3:latest", + "prompt": prompt, + "stream": false + }); + + let res = client + .post("http://127.0.0.1:11434/api/generate") + .json(&body) + .send() + .await + .ok()?; + + if res.status().is_success() { + let json_res: serde_json::Value = res.json().await.ok()?; + json_res.get("response").and_then(|r| r.as_str()).map(|s| s.to_string()) + } else { + None + } +} + +pub fn heuristic_ai_analyze(data: &UnifiedRawData) -> (Vec, Vec, String) { + let mut issues = Vec::new(); + + // 1. Анализ сбойных служб Init (systemd, OpenRC, runit, etc.) + let mut init_status = "Healthy".to_string(); + let mut init_issue_count = 0; + + for (idx, svc) in data.failed_services.iter().enumerate() { + init_issue_count += 1; + init_status = "Failed".to_string(); + + let clean_log = DataSanitizer::sanitize(&svc.logs); + let snippet = clean_log + .lines() + .take(10) + .collect::>() + .join("\n"); + + issues.push(DiagnosticIssue { + id: format!("init-{}", idx + 1), + title: format!("Служба '{}' в состоянии сбоя ({})", svc.name, svc.init_system), + subsystem: Subsystem::Systemd, + severity: Severity::Critical, + root_cause: format!("Процесс службы {} аварийно остановился под управлением {}.", svc.name, svc.init_system), + explanation: svc.description.clone(), + fix: Some(FixSuggestion { + title: format!("Перезапуск службы {}", svc.name), + command: svc.restart_command.clone(), + explanation: format!("Команда перезапуска, адаптированная под систему инициализации {}.", svc.init_system), + }), + raw_log: if snippet.is_empty() { clean_log } else { snippet }, + sanitized: true, + permission_denied: false, + }); + } + + // 2. Анализ Kernel Space + let mut kernel_status = "Healthy".to_string(); + let mut kernel_issue_count = 0; + + if data.kernel_scan.permission_denied { + issues.push(DiagnosticIssue { + id: "kern-perm".to_string(), + title: "Доступ к кольцевому буферу ядра (dmesg) ограничен".to_string(), + subsystem: Subsystem::Kernel, + severity: Severity::Warning, + root_cause: "В системе включен dmesg_restrict, чтение системных логов ядра требует прав суперпользователя.".to_string(), + explanation: "Сканирование продолжено в unprivileged-режиме. Для доступа к полному логу dmesg запустите приложение с правами sudo/pkexec.".to_string(), + fix: Some(FixSuggestion { + title: "Запуск диагностического сканирования с sudo".to_string(), + command: "sudo diagd-tui".to_string(), + explanation: "Предоставляет приложению временные привилегии для глубокого аудита оборудования.".to_string(), + }), + raw_log: "Operation not permitted reading dmesg/kmsg".to_string(), + sanitized: true, + permission_denied: true, + }); + } + + if !data.kernel_scan.oom_events.is_empty() { + kernel_status = "Failed".to_string(); + kernel_issue_count += 1; + issues.push(DiagnosticIssue { + id: "kern-oom".to_string(), + title: "Сработал OOM-Killer: принудительное завершение процессов из-за нехватки памяти".to_string(), + subsystem: Subsystem::Kernel, + severity: Severity::Critical, + root_cause: "Система исчерпала физическую RAM и swap-пространство, ядро завершило наиболее прожорливые процессы.".to_string(), + explanation: "Необходимо проанализировать потребление памяти приложениями или увеличить объем файла подкачки (swap).".to_string(), + fix: Some(FixSuggestion { + title: "Проверка текущего распределения памяти и процессов".to_string(), + command: "free -h && ps aux --sort=-%mem | head -n 10".to_string(), + explanation: "Выводит доступную память и топ-10 процессов по потреблению RAM.".to_string(), + }), + raw_log: data.kernel_scan.oom_events.join("\n"), + sanitized: true, + permission_denied: false, + }); + } + + if !data.kernel_scan.gpu_hangs.is_empty() { + kernel_status = "Failed".to_string(); + kernel_issue_count += 1; + issues.push(DiagnosticIssue { + id: "kern-gpu".to_string(), + title: "Зафиксировано зависание или аварийный сброс видеодрайвера (GPU Hang)".to_string(), + subsystem: Subsystem::Kernel, + severity: Severity::Critical, + root_cause: "Драйвер графического ускорителя сообщил о таймауте выполнения команд (Xid / amdgpu reset / ring hang).".to_string(), + explanation: "Возможен перегрев видеокарты, нестабильность драйвера или аппаратная деградация GPU.".to_string(), + fix: Some(FixSuggestion { + title: "Проверка статуса видеодрайвера".to_string(), + command: "nvidia-smi || lspci -k | grep -EA3 'VGA|3D'".to_string(), + explanation: "Запрашивает состояние видеоускорителя и используемый драйвер ядра.".to_string(), + }), + raw_log: data.kernel_scan.gpu_hangs.join("\n"), + sanitized: true, + permission_denied: false, + }); + } + + if !data.kernel_scan.csum_errors.is_empty() { + kernel_status = "Failed".to_string(); + kernel_issue_count += 1; + issues.push(DiagnosticIssue { + id: "kern-csum".to_string(), + title: "Нарушение контрольных сумм данных (Btrfs/ZFS Checksum Error)".to_string(), + subsystem: Subsystem::Storage, + severity: Severity::Critical, + root_cause: "Файловая система обнаружила несовпадение csum при чтении блоков. Возможен 'silent data corruption'.".to_string(), + explanation: "Проверьте стабильность модулей оперативной памяти (memtest) и SMART-статус накопителя.".to_string(), + fix: Some(FixSuggestion { + title: "Запуск scrub для верификации и восстановления данных".to_string(), + command: "sudo btrfs scrub start / || sudo zpool scrub $(zpool list -H -o name)".to_string(), + explanation: "Инициирует полную проверку целостности данных файловой системы.".to_string(), + }), + raw_log: data.kernel_scan.csum_errors.join("\n"), + sanitized: true, + permission_denied: false, + }); + } + + // 3. Анализ давления PSI и системных лимитов + if data.pressure_scan.mem_some_avg10 > 25.0 { + issues.push(DiagnosticIssue { + id: "psi-mem".to_string(), + title: format!("Критическое давление на память (PSI Memory avg10: {:.1}%)", data.pressure_scan.mem_some_avg10), + subsystem: Subsystem::Kernel, + severity: Severity::Warning, + root_cause: "Процессы проводят значительное время в ожидании выделения страниц оперативной памяти.".to_string(), + explanation: "Высокий показатель PSI Memory указывает на активный трэшинг подсистемы подкачки (swap trashing).".to_string(), + fix: None, + raw_log: format!("PSI: mem_some_avg10={:.2}%, mem_full_avg10={:.2}%", data.pressure_scan.mem_some_avg10, data.pressure_scan.mem_full_avg10), + sanitized: true, + permission_denied: false, + }); + } + + if data.limits_scan.file_descriptors_exhausted { + issues.push(DiagnosticIssue { + id: "limit-fd".to_string(), + title: "Исчерпание системного лимита файловых дескрипторов (file-nr)".to_string(), + subsystem: Subsystem::Kernel, + severity: Severity::Critical, + root_cause: format!("Использовано {} из {} файловых дескрипторов (>95%).", data.limits_scan.file_nr_allocated, data.limits_scan.file_nr_max), + explanation: "Новые процессы и сетевые сокеты не смогут открываться, вызывая ошибку 'Too many open files'.".to_string(), + fix: Some(FixSuggestion { + title: "Увеличение лимита файловых дескрипторов fs.file-max".to_string(), + command: "sudo sysctl -w fs.file-max=2097152".to_string(), + explanation: "Увеличивает максимальное количество одновременно открытых файлов в системе.".to_string(), + }), + raw_log: format!("file-nr allocated: {}, max: {}", data.limits_scan.file_nr_allocated, data.limits_scan.file_nr_max), + sanitized: true, + permission_denied: false, + }); + } + + if !data.limits_scan.recent_coredumps.is_empty() { + issues.push(DiagnosticIssue { + id: "app-crash".to_string(), + title: "Зафиксированы недавние аварийные сбои приложений (Coredumps)".to_string(), + subsystem: Subsystem::Systemd, + severity: Severity::Warning, + root_cause: "Пользовательские или системные программы завершились с сигналом SIGSEGV, SIGABRT или SIGBUS.".to_string(), + explanation: "Служба coredumpctl сохранила дампы памяти упавших приложений для отладки.".to_string(), + fix: Some(FixSuggestion { + title: "Просмотр информации о последнем дампе памяти".to_string(), + command: "coredumpctl info".to_string(), + explanation: "Выводит стек вызовов и причину падения последнего сбойного процесса.".to_string(), + }), + raw_log: data.limits_scan.recent_coredumps.join("\n"), + sanitized: true, + permission_denied: false, + }); + } + + // 4. Анализ Storage Mounts (дисковое пространство и inode) + let mut storage_status = "Healthy".to_string(); + let mut storage_issue_count = 0; + + for mount in &data.storage_mounts { + if mount.is_critical { + storage_status = "Failed".to_string(); + storage_issue_count += 1; + + let reason = if mount.used_percent >= 90.0 { + format!("Заполнено {:.1}% дискового пространства на точке монтирования '{}'", mount.used_percent, mount.mount_point) + } else { + format!("Исчерпано {:.1}% inode на точке монтирования '{}'", mount.inode_used_percent, mount.mount_point) + }; + + issues.push(DiagnosticIssue { + id: format!("stor-{}", mount.mount_point.replace('/', "-")), + title: reason.clone(), + subsystem: Subsystem::Storage, + severity: Severity::Critical, + root_cause: reason, + explanation: format!("Переполнение раздела {} ({}) может заблокировать запись журналов и работу системных баз данных.", mount.mount_point, mount.filesystem), + fix: Some(FixSuggestion { + title: format!("Поиск 10 самых объемных директорий на {}", mount.mount_point), + command: format!("sudo du -xh --max-depth=1 {} | sort -hr | head -n 10", mount.mount_point), + explanation: "Локализует каталоги, занимающие максимальное пространство на проблемном разделе.".to_string(), + }), + raw_log: format!("Mount: {}, FSType: {}, Used: {:.1}%, Free: {} MB, Inodes Free: {}", mount.mount_point, mount.filesystem, mount.used_percent, mount.free_bytes / (1024 * 1024), mount.inodes_free), + sanitized: true, + permission_denied: false, + }); + } + } + + // 5. Анализ аппаратного обеспечения и перегрева (Hardware & Thermals) + if data.hardware_scan.total_throttle_events > 0 || data.hardware_scan.max_cpu_temp_c >= 90.0 { + kernel_issue_count += 1; + let is_crit = data.hardware_scan.max_cpu_temp_c >= 90.0; + issues.push(DiagnosticIssue { + id: "hw-throttling".to_string(), + title: format!( + "Зафиксирован Thermal Throttling CPU (макс. темп: {:.1}°C, событий: {})", + data.hardware_scan.max_cpu_temp_c, data.hardware_scan.total_throttle_events + ), + subsystem: Subsystem::Kernel, + severity: if is_crit { Severity::Critical } else { Severity::Warning }, + root_cause: format!( + "Температура ядер процессора достигла лимита троттлинга. Ядро зафиксировало {} событий сброса частоты на {} ядрах.", + data.hardware_scan.total_throttle_events, data.hardware_scan.thermal_throttled_cores + ), + explanation: "Длительный перегрев приводит к деградации кремния и просадкам производительности. Проверьте кулеры и термопасту.".to_string(), + fix: Some(FixSuggestion { + title: "Мониторинг температур датчиков в реальном времени".to_string(), + command: "sensors || cat /sys/class/thermal/thermal_zone*/temp".to_string(), + explanation: "Отображает текущую температуру ядер и обороты вентиляторов охлаждения.".to_string(), + }), + raw_log: format!( + "CPU Temp: {:.1} C, Throttled Cores: {}, Total Events: {}", + data.hardware_scan.max_cpu_temp_c, + data.hardware_scan.thermal_throttled_cores, + data.hardware_scan.total_throttle_events + ), + sanitized: true, + permission_denied: false, + }); + } + + if let Some(ref batt) = data.hardware_scan.battery_health { + if batt.is_degraded { + issues.push(DiagnosticIssue { + id: "hw-battery".to_string(), + title: format!("Деградация аккумулятора {} (остаток: {:.1}%, циклов: {})", batt.name, batt.health_percent, batt.cycle_count), + subsystem: Subsystem::Kernel, + severity: Severity::Warning, + root_cause: format!("Здоровье батареи снизилось до {:.1}% от проектной емкости при {} циклах перезарядки.", batt.health_percent, batt.cycle_count), + explanation: "Износ батареи может приводить к внезапным отключениям ноутбука под пиковой нагрузкой.".to_string(), + fix: Some(FixSuggestion { + title: "Подробный отчет энергопотребления".to_string(), + command: "upower -i $(upower -e | grep 'BAT')".to_string(), + explanation: "Показывает детальную статистику батареи и контроллера питания.".to_string(), + }), + raw_log: format!("Battery: {}, Capacity: {}%, Health: {:.1}%, Cycles: {}", batt.name, batt.capacity_percent, batt.health_percent, batt.cycle_count), + sanitized: true, + permission_denied: false, + }); + } + } + + if data.hardware_scan.edac_ue_count > 0 { + kernel_status = "Failed".to_string(); + kernel_issue_count += 1; + issues.push(DiagnosticIssue { + id: "hw-edac-ue".to_string(), + title: format!("Критические неисправимые ошибки памяти (EDAC UE: {})", data.hardware_scan.edac_ue_count), + subsystem: Subsystem::Kernel, + severity: Severity::Critical, + root_cause: "Контроллер памяти зафиксировал неисправимые (Uncorrected) аппаратные сбои DRAM.".to_string(), + explanation: "Возможен дефект планки оперативной памяти. Рекомендуется немедленная замена модуля RAM.".to_string(), + fix: Some(FixSuggestion { + title: "Просмотр журналов EDAC".to_string(), + command: "edac-util -v || dmesg | grep -i edac".to_string(), + explanation: "Локализует проблемный слот памяти (DIMM / Channel).".to_string(), + }), + raw_log: format!("EDAC Uncorrected Errors: {}, Corrected Errors: {}", data.hardware_scan.edac_ue_count, data.hardware_scan.edac_ce_count), + sanitized: true, + permission_denied: false, + }); + } + + // 6. Анализ сети, DNS и брандмауэра (Network & DNS) + let mut network_status = "Healthy".to_string(); + let mut network_issue_count = 0; + + if data.network_deep_scan.dns_broken_symlink { + network_status = "Failed".to_string(); + network_issue_count += 1; + issues.push(DiagnosticIssue { + id: "net-resolv-symlink".to_string(), + title: "Сломанная ссылка /etc/resolv.conf (битый симлинк DNS)".to_string(), + subsystem: Subsystem::Network, + severity: Severity::Critical, + root_cause: "Файл /etc/resolv.conf указывает на несуществующий целевой путь (systemd-resolved или сетевой менеджер не инициализирован).".to_string(), + explanation: "Программы не могут преобразовать доменные имена в IP-адреса.".to_string(), + fix: Some(FixSuggestion { + title: "Восстановление конфигурации resolv.conf".to_string(), + command: "sudo ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf || echo 'nameserver 1.1.1.1' | sudo tee /etc/resolv.conf".to_string(), + explanation: "Пересоздает симлинк на stub-резолвер systemd или задает публичный DNS.".to_string(), + }), + raw_log: "Symlink /etc/resolv.conf is dangling".to_string(), + sanitized: true, + permission_denied: false, + }); + } + + if !data.network_deep_scan.dns_resolution_ok { + network_status = "Failed".to_string(); + network_issue_count += 1; + issues.push(DiagnosticIssue { + id: "net-dns-fail".to_string(), + title: "Сбой разрешения DNS-имен (DNS Lookup Failed)".to_string(), + subsystem: Subsystem::Network, + severity: Severity::Critical, + root_cause: format!("Ни один из настроенных DNS-серверов {:?} не отвечает на запросы разрешения имен.", data.network_deep_scan.dns_servers), + explanation: "Интернет-соединение может быть физически доступно, но браузеры и сервисы не открывают сайты по доменам.".to_string(), + fix: Some(FixSuggestion { + title: "Проверка статуса DNS резолвера".to_string(), + command: "resolvectl status || nslookup cloudflare.com".to_string(), + explanation: "Диагностирует опрос апстрим DNS-серверов.".to_string(), + }), + raw_log: format!("DNS servers: {:?}, resolution_ok: false", data.network_deep_scan.dns_servers), + sanitized: true, + permission_denied: false, + }); + } + + if !data.network_deep_scan.has_default_gateway { + network_status = "Failed".to_string(); + network_issue_count += 1; + issues.push(DiagnosticIssue { + id: "net-no-gateway".to_string(), + title: "Отсутствует маршрут по умолчанию (Default Gateway Missing)".to_string(), + subsystem: Subsystem::Network, + severity: Severity::Critical, + root_cause: "В таблице маршрутизации ядра нет шлюза 0.0.0.0. Пакеты во внешнюю сеть не могут быть смаршрутизированы.".to_string(), + explanation: "Сетевой адаптер не получил адрес шлюза по DHCP или интерфейс отключен.".to_string(), + fix: Some(FixSuggestion { + title: "Проверка сетевых интерфейсов и получение аренды DHCP".to_string(), + command: "ip route show && ip link".to_string(), + explanation: "Выводит текущую таблицу маршрутизации и состояние линков.".to_string(), + }), + raw_log: "No default gateway (00000000) found in /proc/net/route".to_string(), + sanitized: true, + permission_denied: false, + }); + } + + if let Some(ref conflict) = data.network_deep_scan.firewall_conflict { + network_issue_count += 1; + issues.push(DiagnosticIssue { + id: "net-firewall-conflict".to_string(), + title: "Конфликт нескольких брандмауэров (Firewall Conflict)".to_string(), + subsystem: Subsystem::Network, + severity: Severity::Warning, + root_cause: conflict.clone(), + explanation: "Одновременная работа нескольких фаерволов (например, UFW и Firewalld) приводит к гонкам в nftables/iptables и внезапным обрывам соединений.".to_string(), + fix: Some(FixSuggestion { + title: "Отключение конфликтующей службы firewalld".to_string(), + command: "sudo systemctl disable --now firewalld".to_string(), + explanation: "Оставляет активным только один брандмауэр.".to_string(), + }), + raw_log: conflict.clone(), + sanitized: true, + permission_denied: false, + }); + } + + if !data.network_deep_scan.wifi_drop_events.is_empty() { + network_issue_count += 1; + issues.push(DiagnosticIssue { + id: "net-wifi-drop".to_string(), + title: format!("Обнаружены сбросы Wi-Fi сессий (событий: {})", data.network_deep_scan.wifi_drop_events.len()), + subsystem: Subsystem::Network, + severity: Severity::Warning, + root_cause: "Беспроводной адаптер зафиксировал деаутентификацию или потерю маяков точки доступа (beacon loss).".to_string(), + explanation: "Возможен слабый сигнал, помехи на частоте или агрессивный режим энергосбережения Wi-Fi адаптера.".to_string(), + fix: Some(FixSuggestion { + title: "Просмотр детальных логов Wi-Fi демона".to_string(), + command: "journalctl -u wpa_supplicant -u iwd -e".to_string(), + explanation: "Показывает причины деаутентификации Wi-Fi модуля.".to_string(), + }), + raw_log: data.network_deep_scan.wifi_drop_events.join("\n"), + sanitized: true, + permission_denied: false, + }); + } + + // Если проблем нет вообще, сформируем Info + if issues.is_empty() { + issues.push(DiagnosticIssue { + id: "ok-1".to_string(), + title: format!("Все подсистемы {} ({}) функционируют стабильно", data.os_name, data.init_name), + subsystem: Subsystem::Systemd, + severity: Severity::Info, + root_cause: "Сбоев служб, ошибок ядра dmesg, переполнения дисков и превышения PSI не обнаружено.".to_string(), + explanation: format!("Глубокий аудит проверил супервизор {}, кольцевой буфер ядра, файловые системы и лимиты ОС. Система в норме.", data.init_name), + fix: None, + raw_log: format!("OS: {}, Init: {}, Root: {}. All checks HEALTHY.", data.os_name, data.init_name, data.is_root), + sanitized: true, + permission_denied: false, + }); + } + + // 7. Анализ аварийных сбоев (Crash Dumps) + let mut crashes_status = "Healthy".to_string(); + let mut crashes_issue_count = 0; + + for (idx, crash) in data.crashes.iter().enumerate() { + crashes_issue_count += 1; + crashes_status = "Warning".to_string(); + issues.push(DiagnosticIssue { + id: format!("crash-{}", idx + 1), + title: format!("Аварийный сбой процесса '{}' ({})", crash.process_name, crash.signal_or_code), + subsystem: Subsystem::Crashes, + severity: if crash.signal_or_code.contains("SIGSEGV") || crash.signal_or_code.contains("Access Violation") { + Severity::Critical + } else { + Severity::Warning + }, + root_cause: format!("Процесс завершился аварийно с кодом/сигналом {}.", crash.signal_or_code), + explanation: crash.stack_trace_snippet.clone(), + fix: crash.dump_path.as_ref().map(|p| FixSuggestion { + title: format!("Анализ дампа {}", crash.process_name), + command: format!("gdb {} {} || coredumpctl gdb {}", crash.process_name, p, crash.pid.unwrap_or(0)), + explanation: "Запуск отладчика для исследования стека вызовов и локализации сбойной инструкции.".to_string(), + }), + raw_log: crash.stack_trace_snippet.clone(), + sanitized: true, + permission_denied: false, + }); + } + + // 8. Анализ безопасности и открытых портов + let mut sec_status = "Healthy".to_string(); + let mut sec_issue_count = 0; + + for (idx, port) in data.security.exposed_ports.iter().filter(|p| p.is_public && p.risk_level != Severity::Info).enumerate() { + sec_issue_count += 1; + if port.risk_level == Severity::Critical { + sec_status = "Critical".to_string(); + } else if sec_status != "Critical" { + sec_status = "Warning".to_string(); + } + issues.push(DiagnosticIssue { + id: format!("sec-port-{}", idx + 1), + title: format!("Опасный порт {}: {} слушает на 0.0.0.0", port.port, port.process_name), + subsystem: Subsystem::Security, + severity: port.risk_level.clone(), + root_cause: format!("Служба {} привязана к публичному адресу {} без сетевой изоляции.", port.process_name, port.local_address), + explanation: port.recommendation.clone(), + fix: Some(FixSuggestion { + title: format!("Изоляция порта {}", port.port), + command: format!("sudo ufw deny {}/{} || iptables -A INPUT -p {} --dport {} -j DROP", port.port, port.protocol.to_lowercase(), port.protocol.to_lowercase(), port.port), + explanation: "Блокировка внешних подключений к порту через системный брандмауэр.".to_string(), + }), + raw_log: format!("{} {} pid={:?}", port.protocol, port.local_address, port.pid), + sanitized: true, + permission_denied: false, + }); + } + + for (idx, suid) in data.security.suid_anomalies.iter().enumerate() { + sec_issue_count += 1; + sec_status = "Critical".to_string(); + issues.push(DiagnosticIssue { + id: format!("sec-suid-{}", idx + 1), + title: format!("Подозрительный SUID файл: {}", suid.path), + subsystem: Subsystem::Security, + severity: Severity::Critical, + root_cause: suid.risk_reason.clone(), + explanation: format!("Файл {} имеет права {} и установлен бит SUID/SGID.", suid.path, suid.permissions), + fix: Some(FixSuggestion { + title: format!("Снятие SUID-бита с {}", suid.path), + command: format!("sudo chmod -s {}", suid.path), + explanation: "Удаление флага setuid/setgid для предотвращения эскалации привилегий.".to_string(), + }), + raw_log: format!("path={} perms={}", suid.path, suid.permissions), + sanitized: true, + permission_denied: false, + }); + } + + for check in &data.security.hardening_checks { + if !check.is_secure && check.remediation.is_some() { + sec_issue_count += 1; + if sec_status == "Healthy" { + sec_status = "Warning".to_string(); + } + issues.push(DiagnosticIssue { + id: format!("sec-check-{}", check.name.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect::()), + title: format!("{}: {}", check.name, check.status), + subsystem: Subsystem::Security, + severity: Severity::Warning, + root_cause: check.description.clone(), + explanation: format!("Параметр безопасности '{}' в состоянии '{}'.", check.name, check.status), + fix: check.remediation.as_ref().map(|rem| FixSuggestion { + title: format!("Усиление защиты: {}", check.name), + command: rem.clone(), + explanation: "Применение рекомендуемого безопасного значения конфигурации.".to_string(), + }), + raw_log: format!("{}: {}", check.name, check.status), + sanitized: true, + permission_denied: false, + }); + } + } + + let statuses = vec![ + SubsystemStatus { + name: Subsystem::Systemd, + status: init_status, + issue_count: init_issue_count, + details: format!("{}: сбойных служб — {}", data.init_name, data.failed_services.len()), + }, + SubsystemStatus { + name: Subsystem::Kernel, + status: kernel_status, + issue_count: kernel_issue_count, + details: if data.kernel_scan.tainted_value > 0 { + format!("Tainted: {}", data.kernel_scan.tainted_flags.join(", ")) + } else if data.hardware_scan.total_throttle_events > 0 { + format!("Thermal throttled: {} раз", data.hardware_scan.total_throttle_events) + } else { + "Буфер ядра чист, tainted=0".to_string() + }, + }, + SubsystemStatus { + name: Subsystem::Storage, + status: storage_status, + issue_count: storage_issue_count, + details: format!("Проверено точек монтирования: {}", data.storage_mounts.len()), + }, + SubsystemStatus { + name: Subsystem::Network, + status: network_status, + issue_count: network_issue_count, + details: if let Some(ms) = data.network_deep_scan.dns_latency_ms { + format!("DNS: {} ms | Шлюз: {}", ms, data.network_deep_scan.default_gateway_ip.as_deref().unwrap_or("нет")) + } else if data.network_deep_scan.has_default_gateway { + format!("Шлюз: {}", data.network_deep_scan.default_gateway_ip.as_deref().unwrap_or("OK")) + } else { + "Маршрут по умолчанию отсутствует".to_string() + }, + }, + SubsystemStatus { + name: Subsystem::Security, + status: sec_status, + issue_count: sec_issue_count, + details: format!("Защищенность: {}% | Открытых портов: {}", data.security.security_score, data.security.exposed_ports.len()), + }, + SubsystemStatus { + name: Subsystem::Crashes, + status: crashes_status, + issue_count: crashes_issue_count, + details: format!("Зафиксировано сбоев: {}", data.crashes.len()), + }, + SubsystemStatus { + name: Subsystem::Audio, + status: "Healthy".to_string(), + issue_count: 0, + details: "Аудио подсистема в норме".to_string(), + }, + ]; + + let summary = format!( + "Аудит {} ({}): инцидентов — {}, сбоев — {}, безопасность — {}%, root: {}.", + data.os_name, + data.init_name, + issues.len(), + data.crashes.len(), + data.security.security_score, + if data.is_root { "да" } else { "нет" } + ); + + (issues, statuses, summary) +} + +pub async fn run_scan() -> Result { + run_scan_with_mode(crate::auth::AuthMode::Tui).await +} + +pub async fn run_scan_with_mode(mode: crate::auth::AuthMode) -> Result { + let raw_data = tokio::task::spawn_blocking(move || UnifiedRawData::collect(Some(mode))) + .await + .map_err(|e| e.to_string())?; + + let (prompt_preview, _) = LlmDiagnosticPrompt::build(&raw_data); + let llm_res = try_query_llm(&prompt_preview).await; + let llm_analyzed = llm_res.is_some(); + + let (issues, subsystems, summary) = heuristic_ai_analyze(&raw_data); + let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(); + + Ok(SystemReport { + timestamp, + os_family: raw_data.os_name, + init_system: raw_data.init_name, + is_root: raw_data.is_root, + subsystems, + issues, + failed_services: raw_data.failed_services, + hardware: raw_data.hardware_info, + crashes: raw_data.crashes, + security: raw_data.security, + llm_analyzed, + summary, + prompt_preview, + }) +} diff --git a/crates/core/src/auth.rs b/crates/core/src/auth.rs new file mode 100644 index 0000000..f518716 --- /dev/null +++ b/crates/core/src/auth.rs @@ -0,0 +1,224 @@ +use std::io::Write; +use std::process::{Command, Stdio}; +use std::sync::RwLock; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AuthMode { + Tui, + Gui, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PrivilegeStatus { + AlreadyRoot, + Elevated, + Unprivileged { reason: String }, +} + +#[allow(dead_code)] +static CACHED_PRIV_STATUS: RwLock> = RwLock::new(None); + +pub struct PrivilegeManager; + +impl PrivilegeManager { + /// Проверяет, запущен ли текущий процесс с UID 0 (root) + pub fn is_current_user_root() -> bool { + #[cfg(unix)] + { + unsafe { libc::geteuid() == 0 } + } + #[cfg(not(unix))] + { + false + } + } + + /// Возвращает статус привилегий или запрашивает их однократно за сессию + pub fn ensure_privileges(mode: AuthMode) -> PrivilegeStatus { + #[cfg(test)] + { + let _ = mode; + if Self::is_current_user_root() { + return PrivilegeStatus::AlreadyRoot; + } + if let Ok(status) = Command::new("sudo") + .args(["-n", "true"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + { + if status.success() { + return PrivilegeStatus::Elevated; + } + } + return PrivilegeStatus::Unprivileged { + reason: "Non-interactive test mode".to_string(), + }; + } + + #[cfg(not(test))] + { + if let Ok(guard) = CACHED_PRIV_STATUS.read() { + if let Some(ref status) = *guard { + return status.clone(); + } + } + + let status = Self::request_privileges(mode); + + if let Ok(mut guard) = CACHED_PRIV_STATUS.write() { + *guard = Some(status.clone()); + } + + status + } + } + + /// Однократный запрос повышения привилегий: + /// - Если уже root, не запрашивает повторно. + /// - В TUI-режиме: интерактивный `sudo -v` с кэшированием временного токена sudoers. + /// - В GUI-режиме: графический диалог (Zenity / Polkit pkexec). + /// - При отказе или отмене возвращает `PrivilegeStatus::Unprivileged`. + pub fn request_privileges(mode: AuthMode) -> PrivilegeStatus { + if Self::is_current_user_root() { + return PrivilegeStatus::AlreadyRoot; + } + + // Проверяем, есть ли уже действующий кэш sudo без ввода пароля (sudo -n true) + if let Ok(status) = Command::new("sudo") + .args(["-n", "true"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + { + if status.success() { + return PrivilegeStatus::Elevated; + } + } + + match mode { + AuthMode::Tui => { + println!("\n\x1b[1;36m[diagd]\x1b[0m Для полного аудита ядра (dmesg) и системных журналов требуются права суперпользователя."); + println!("\x1b[1;33m[diagd]\x1b[0m Запрос авторизации sudo:"); + + match Command::new("sudo").arg("-v").status() { + Ok(status) if status.success() => { + println!("\x1b[1;32m[diagd]\x1b[0m Привилегии суперпользователя успешно получены.\n"); + PrivilegeStatus::Elevated + } + Ok(_) => { + println!("\x1b[1;33m[diagd]\x1b[0m Пароль не введен или отклонен. Сканирование продолжится в unprivileged-режиме.\n"); + PrivilegeStatus::Unprivileged { + reason: "Пользователь отменил ввод пароля sudo".to_string(), + } + } + Err(e) => PrivilegeStatus::Unprivileged { + reason: format!("Утилита sudo недоступна: {}", e), + }, + } + } + AuthMode::Gui => { + #[cfg(target_os = "macos")] + { + if let Ok(status) = Command::new("osascript") + .args(["-e", "do shell script \"sudo -v\" with administrator privileges"]) + .status() + { + if status.success() { + return PrivilegeStatus::Elevated; + } + } + } + + #[cfg(target_os = "windows")] + { + let ps_check = "([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)"; + if let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_check]).output() { + if String::from_utf8_lossy(&output.stdout).trim() == "True" { + return PrivilegeStatus::Elevated; + } + } + } + + // В Linux GUI пробуем графический ввод через zenity или pkexec + if let Ok(output) = Command::new("zenity") + .args(["--password", "--title=diagd • Запрос прав суперпользователя"]) + .output() + { + if output.status.success() { + let pass = String::from_utf8_lossy(&output.stdout); + let trimmed_pass = pass.trim_end_matches(&['\r', '\n'][..]); + + if let Ok(mut child) = Command::new("sudo") + .args(["-S", "-v"]) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + { + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(format!("{}\n", trimmed_pass).as_bytes()); + } + if let Ok(exit) = child.wait() { + if exit.success() { + return PrivilegeStatus::Elevated; + } + } + } + } + } + + // Fallback: pkexec + match Command::new("pkexec").args(["true"]).status() { + Ok(status) if status.success() => PrivilegeStatus::Elevated, + Ok(_) => PrivilegeStatus::Unprivileged { + reason: "Авторизация Polkit отклонена пользователем".to_string(), + }, + Err(e) => PrivilegeStatus::Unprivileged { + reason: format!("Polkit (pkexec) недоступен: {}", e), + }, + } + } + } + } + + /// Выполняет команду с правами суперпользователя (через sudo -n, если доступно), + /// либо делает откат к обычному вызову + pub fn exec_privileged(cmd: &str, args: &[&str]) -> std::io::Result { + if Self::is_current_user_root() { + return Command::new(cmd).args(args).output(); + } + + // Если активен sudo кэш, выполняем через sudo -n + if let Ok(privileged_cmd) = Command::new("sudo") + .arg("-n") + .arg(cmd) + .args(args) + .output() + { + if privileged_cmd.status.success() { + return Ok(privileged_cmd); + } else { + let err = String::from_utf8_lossy(&privileged_cmd.stderr); + // Если sudo -n отклонен, пробуем обычный вызов + if !err.contains("a password is required") { + return Ok(privileged_cmd); + } + } + } + + // Обычный вызов без sudo + Command::new(cmd).args(args).output() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_privilege_check() { + let is_root = PrivilegeManager::is_current_user_root(); + assert_eq!(is_root, is_root); + } +} diff --git a/crates/core/src/export.rs b/crates/core/src/export.rs new file mode 100644 index 0000000..3860dcb --- /dev/null +++ b/crates/core/src/export.rs @@ -0,0 +1,466 @@ +use crate::models::{Severity, SystemReport}; +use flate2::write::GzEncoder; +use flate2::Compression; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +pub struct BundleExporter; + +impl BundleExporter { + /// Экспортирует полный архив Debug Bundle: + /// - `report.html` (интерактивный dark HTML) + /// - `report.md` (Markdown для баг-трекера) + /// - `system_report.json` (структурированный дамп) + /// Упаковывает всё в tar.gz и возвращает путь к файлу архива. + pub fn export_bundle(report: &SystemReport) -> Result { + let timestamp_safe = report.timestamp.replace([':', ' '], "-"); + let filename = format!("diagd-bundle-{}.tar.gz", timestamp_safe); + + // Определяем каталог для сохранения: $HOME или /tmp + let output_dir = std::env::var("HOME") + .map(PathBuf::from) + .unwrap_or_else(|_| std::env::temp_dir()); + + let bundle_path = output_dir.join(&filename); + + let tar_gz_file = File::create(&bundle_path) + .map_err(|e| format!("Не удалось создать файл {}: {}", bundle_path.display(), e))?; + + let enc = GzEncoder::new(tar_gz_file, Compression::default()); + let mut tar = tar::Builder::new(enc); + + // 1. Создаем HTML отчет + let html_content = Self::generate_html(report); + let mut html_header = tar::Header::new_gnu(); + html_header.set_size(html_content.len() as u64); + html_header.set_mode(0o644); + html_header.set_cksum(); + tar.append_data(&mut html_header, "report.html", html_content.as_bytes()) + .map_err(|e| format!("Ошибка добавления report.html в архив: {}", e))?; + + // 2. Создаем Markdown отчет + let md_content = Self::generate_markdown(report); + let mut md_header = tar::Header::new_gnu(); + md_header.set_size(md_content.len() as u64); + md_header.set_mode(0o644); + md_header.set_cksum(); + tar.append_data(&mut md_header, "report.md", md_content.as_bytes()) + .map_err(|e| format!("Ошибка добавления report.md в архив: {}", e))?; + + // 3. Создаем system_report.json + let json_content = serde_json::to_string_pretty(report).unwrap_or_default(); + let mut json_header = tar::Header::new_gnu(); + json_header.set_size(json_content.len() as u64); + json_header.set_mode(0o644); + json_header.set_cksum(); + tar.append_data(&mut json_header, "system_report.json", json_content.as_bytes()) + .map_err(|e| format!("Ошибка добавления system_report.json в архив: {}", e))?; + + tar.finish() + .map_err(|e| format!("Ошибка финализации архива tar.gz: {}", e))?; + + // Также сохраняем отдельную копию HTML для моментального открытия в браузере + let standalone_html = output_dir.join(format!("diagd-report-{}.html", timestamp_safe)); + if let Ok(mut f) = File::create(&standalone_html) { + let _ = f.write_all(html_content.as_bytes()); + } + + Ok(bundle_path.to_string_lossy().to_string()) + } + + pub fn generate_markdown(report: &SystemReport) -> String { + let mut md = String::new(); + md.push_str(&format!("# Отчет диагностики diagd • {}\n\n", report.timestamp)); + md.push_str(&format!("- **ОС**: {}\n", report.os_family)); + md.push_str(&format!("- **Init System**: {}\n", report.init_system)); + md.push_str(&format!("- **Root**: {}\n", if report.is_root { "Да" } else { "Нет (unprivileged)" })); + md.push_str(&format!("- **Сводка**: {}\n\n", report.summary)); + + md.push_str("## Статус подсистем\n\n"); + md.push_str("| Подсистема | Статус | Ошибок | Детали |\n"); + md.push_str("|------------|--------|--------|--------|\n"); + for sub in &report.subsystems { + md.push_str(&format!( + "| {:?} | {} | {} | {} |\n", + sub.name, sub.status, sub.issue_count, sub.details + )); + } + + md.push_str("\n## Обнаруженные проблемы\n\n"); + for issue in &report.issues { + let badge = match issue.severity { + Severity::Critical => "🔴 CRITICAL", + Severity::Warning => "🟡 WARNING", + Severity::Info => "🔵 INFO", + }; + md.push_str(&format!("### {} {}\n\n", badge, issue.title)); + md.push_str(&format!("- **Подсистема**: `{:?}`\n", issue.subsystem)); + md.push_str(&format!("- **Корень проблемы**: {}\n", issue.root_cause)); + md.push_str(&format!("- **Объяснение**: {}\n", issue.explanation)); + + if let Some(ref fix) = issue.fix { + md.push_str(&format!("\n**Рекомендуемое решение:** {}\n", fix.title)); + md.push_str("```bash\n"); + md.push_str(&fix.command); + md.push_str("\n```\n"); + } + + if !issue.raw_log.trim().is_empty() { + md.push_str("\n
Сырой лог\n\n```text\n"); + md.push_str(&issue.raw_log); + md.push_str("\n```\n
\n"); + } + md.push_str("\n---\n\n"); + } + + let hw = &report.hardware; + md.push_str("## Спецификация оборудования (Hardware Profile)\n\n"); + md.push_str(&format!("- **Процессор (CPU)**: {} ({} ядер / {} потоков, arch: {})\n", hw.cpu.model_name, hw.cpu.physical_cores, hw.cpu.logical_threads, hw.cpu.architecture)); + if let Some(freq) = hw.cpu.current_frequency_mhz { + md.push_str(&format!(" - Частота: {:.0} MHz | Кэш: {}\n", freq, hw.cpu.l1_cache)); + } + if let Some(ref virt) = hw.cpu.virtualization { + md.push_str(&format!(" - Виртуализация: {}\n", virt)); + } + md.push_str(&format!("- **Материнская плата**: {} {} (BIOS: {} {})\n", hw.motherboard.vendor, hw.motherboard.product_name, hw.motherboard.bios_vendor, hw.motherboard.bios_version)); + let ram_total_gb = hw.memory.total_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let ram_used_gb = hw.memory.used_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + md.push_str(&format!("- **Память (RAM)**: Всего: {:.1} GB | Занято: {:.1} GB | Ошибки ECC (CE: {}, UE: {})\n", ram_total_gb, ram_used_gb, hw.memory.edac_ce_count, hw.memory.edac_ue_count)); + + if !hw.gpus.is_empty() { + md.push_str("- **Графика (GPU)**:\n"); + for gpu in &hw.gpus { + md.push_str(&format!(" - {} (драйвер: {}, слот: {})\n", gpu.model, gpu.driver, gpu.pci_slot)); + } + } + + if !hw.disks.is_empty() { + md.push_str("- **Накопители (Disks)**:\n"); + for disk in &hw.disks { + let size_gb = disk.size_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let smart_str = if !disk.smart_status.is_empty() { format!(" | SMART: {}", disk.smart_status) } else { "".to_string() }; + let health_str = disk.health_percent.map(|h| format!(" | Здоровье: {}%", h)).unwrap_or_default(); + let wear_str = disk.wear_percent.map(|w| format!(" | Износ: {}%", w)).unwrap_or_default(); + let temp_str = disk.temperature_c.map(|t| format!(" | Темп: {}°C", t)).unwrap_or_default(); + let pwr_str = disk.power_on_hours.map(|p| format!(" | Наработка: {} ч.", p)).unwrap_or_default(); + let sn_str = if !disk.serial.is_empty() { format!(" | S/N: {}", disk.serial) } else { "".to_string() }; + md.push_str(&format!(" - `{}` — {} ({:.1} GB, {}{}{}{}{}{}{})\n", disk.name, disk.model, size_gb, disk.disk_type, smart_str, health_str, wear_str, temp_str, pwr_str, sn_str)); + for part in &disk.partitions { + let part_gb = part.size_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let mount = part.mount_point.as_deref().unwrap_or("не смонтирован"); + md.push_str(&format!(" - `{}` ({:.1} GB, {}) -> {}\n", part.name, part_gb, part.fs_type, mount)); + } + } + } + + if let Some(ref batt) = hw.battery { + md.push_str(&format!("- **Батарея**: {} (емкость: {}%, здоровье: {:.1}%, циклов: {}, статус: {})\n", batt.name, batt.capacity_percent, batt.health_percent, batt.cycle_count, batt.status)); + } + + md.push_str(&format!("- **Температура / Охлаждение**: Макс. темп CPU: {:.1}°C | Троттлинг: {} событий\n\n", hw.thermals.max_cpu_temp_c, hw.thermals.total_throttle_events)); + + if !report.crashes.is_empty() { + md.push_str("## Зафиксированные падения и аварийные дампы (Crashes)\n\n"); + md.push_str("| Время | Процесс | Сигнал / Код | Сбойный модуль | Дамп |\n"); + md.push_str("|---|---|---|---|---|\n"); + for c in &report.crashes { + md.push_str(&format!( + "| {} | `{}` | `{}` | {} | {} |\n", + c.timestamp, + c.process_name, + c.signal_or_code, + c.fault_module.as_deref().unwrap_or("—"), + c.dump_path.as_deref().unwrap_or("—") + )); + } + md.push_str("\n"); + } + + md.push_str(&format!("## Аудит безопасности (Оценка защищенности: {}%)\n\n", report.security.security_score)); + if !report.security.exposed_ports.is_empty() { + md.push_str("### Открытые порты и сетевые службы\n\n"); + md.push_str("| Протокол | Адрес:Порт | Процесс | Доступность | Уровень риска |\n"); + md.push_str("|---|---|---|---|---|\n"); + for p in &report.security.exposed_ports { + let pub_badge = if p.is_public { "🌐 Публичный" } else { "🔒 Локальный" }; + let risk_badge = match p.risk_level { + Severity::Critical => "🔴 КРИТИЧЕСКИЙ", + Severity::Warning => "🟡 ВНИМАНИЕ", + Severity::Info => "🔵 ИНФО", + }; + md.push_str(&format!( + "| {} | `{}` | `{}` | {} | {} |\n", + p.protocol, p.local_address, p.process_name, pub_badge, risk_badge + )); + } + md.push_str("\n"); + } + + md + } + + pub fn generate_html(report: &SystemReport) -> String { + let mut html = String::new(); + html.push_str(r#" + + + + +diagd • Отчет диагностики системы + + + +
+
+

diagd • Linux / BSD AI Diagnostic Report

+
+ Дата: "#); + html.push_str(&report.timestamp); + html.push_str(r#" | ОС: "#); + html.push_str(&report.os_family); + html.push_str(r#" | Init: "#); + html.push_str(&report.init_system); + html.push_str(r#" | Права root: "#); + html.push_str(if report.is_root { "Да" } else { "Нет (unprivileged)" }); + html.push_str(r#" +
+
"#); + html.push_str(&report.summary); + html.push_str(r#"
+
+ +

Состояние подсистем

+
"#); + + for sub in &report.subsystems { + let color_class = if sub.status == "Healthy" { "color: var(--green);" } else { "color: var(--red);" }; + html.push_str(&format!( + r#"
+
{:?}
+
{}
+
Ошибок: {}
+
"#, + sub.name, color_class, sub.status, sub.issue_count + )); + } + + html.push_str(r#"
+

Обнаруженные инциденты

"#); + + for issue in &report.issues { + let (badge_cls, badge_txt) = match issue.severity { + Severity::Critical => ("badge-crit", "CRITICAL"), + Severity::Warning => ("badge-warn", "WARNING"), + Severity::Info => ("badge-info", "INFO"), + }; + + html.push_str(&format!( + r#"
+ {} + {:?} +

{}

+
Корень проблемы: {}
+
{}
"#, + badge_cls, badge_txt, issue.subsystem, issue.title, issue.root_cause, issue.explanation + )); + + if let Some(ref fix) = issue.fix { + html.push_str(&format!( + r#"
+
✓ {}
+ $ {} +
"#, + fix.title, fix.command + )); + } + + if !issue.raw_log.trim().is_empty() { + html.push_str(&format!( + r#"
+ Показать сырой лог +
{}
+
"#, + issue.raw_log + )); + } + + html.push_str("
"); + } + + let hw = &report.hardware; + let ram_total_gb = hw.memory.total_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let ram_used_gb = hw.memory.used_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + + html.push_str(r#" +

Спецификация оборудования (Hardware Profile)

+
+
+
Процессор (CPU)
+
"#); + html.push_str(&hw.cpu.model_name); + html.push_str(&format!(r#"
+
Ядер: {} | Потоков: {} | Кэш: {}
+
+
+
Материнская плата & BIOS
+
{} {}
+
BIOS: {} {} ({})
+
+
+
Оперативная память (RAM)
+
{:.1} GB (занято {:.1} GB)
+
ECC сбои: CE={}, UE={}
+
+
+
Термометрия & Батарея
+
Макс. темп: {:.1}°C
+
Троттлинг: {} событий
+
+
+"#, + hw.cpu.physical_cores, hw.cpu.logical_threads, hw.cpu.l1_cache, + hw.motherboard.vendor, hw.motherboard.product_name, + hw.motherboard.bios_vendor, hw.motherboard.bios_version, hw.motherboard.bios_date, + ram_total_gb, ram_used_gb, + hw.memory.edac_ce_count, hw.memory.edac_ue_count, + hw.thermals.max_cpu_temp_c, + hw.thermals.total_throttle_events + )); + + html.push_str("

Накопители данных (Disks)

\n
"); + for disk in &hw.disks { + let size_gb = disk.size_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let health_val = disk.health_percent.unwrap_or(100); + let wear_val = disk.wear_percent.unwrap_or(0); + let bar_color = if health_val >= 80 { "var(--green)" } else if health_val >= 50 { "var(--warn)" } else { "var(--red)" }; + + html.push_str(&format!( + r#"
+
+
+ {} + {} + {} +
+
SMART: {}
+
+
+ Здоровье: {}% (Износ: {}%) • Емкость: {:.1} GB + {} {} +
+
+
+
+ "#, + disk.name, disk.model, disk.disk_type, disk.smart_status, + health_val, wear_val, size_gb, + disk.temperature_c.map(|t| format!("• Температура: {}°C", t)).unwrap_or_default(), + disk.power_on_hours.map(|p| format!("• Наработка: {} ч.", p)).unwrap_or_default(), + bar_color, health_val + )); + + if !disk.partitions.is_empty() { + html.push_str("
Разделы: "); + for (idx, part) in disk.partitions.iter().enumerate() { + let p_gb = part.size_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let mount = part.mount_point.as_deref().unwrap_or("не смонтирован"); + if idx > 0 { html.push_str(" | "); } + html.push_str(&format!("{} ({:.1} GB, {}) ➔ {}", part.name, p_gb, part.fs_type, mount)); + } + html.push_str("
"); + } + + html.push_str("
"); + } + html.push_str("
"); + + html.push_str(r#" +
+ +"#); + + html + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs new file mode 100644 index 0000000..96545b1 --- /dev/null +++ b/crates/core/src/lib.rs @@ -0,0 +1,38 @@ +pub mod auth; +pub mod models; +pub mod sanitize; +pub mod scanner; +pub mod analyst; +pub mod export; + +pub use auth::{AuthMode, PrivilegeManager, PrivilegeStatus}; +pub use models::*; +pub use sanitize::DataSanitizer; +pub use analyst::{run_scan, run_scan_with_mode}; +pub use export::BundleExporter; +pub use scanner::init::{detect_init_system, InitSystemProvider, ScanError}; +pub use scanner::live::LiveMetricsScanner; + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_core_deep_scan() { + let report = run_scan().await; + assert!(report.is_ok()); + let rep = report.unwrap(); + println!("=== DISKS SCANNED: {} ===", rep.hardware.disks.len()); + for d in &rep.hardware.disks { + println!("Disk: {} ({}) | SMART: {} | Health: {:?}% | Wear: {:?}% | Temp: {:?}°C | Hours: {:?} | TBW: {:?} TB | Partitions: {}", + d.name, d.model, d.smart_status, d.health_percent, d.wear_percent, d.temperature_c, d.power_on_hours, d.total_written_tb, d.partitions.len()); + for p in &d.partitions { + println!(" -> Part: {} ({}) mount: {:?}", p.name, p.fs_type, p.mount_point); + } + } + assert!(!rep.subsystems.is_empty()); + assert!(!rep.issues.is_empty()); + assert!(!rep.init_system.is_empty()); + assert!(!rep.hardware.disks.is_empty()); + } +} diff --git a/crates/core/src/models.rs b/crates/core/src/models.rs new file mode 100644 index 0000000..35140d4 --- /dev/null +++ b/crates/core/src/models.rs @@ -0,0 +1,270 @@ +use serde::{Deserialize, Serialize}; + +/// Уровень критичности обнаруженной проблемы +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +pub enum Severity { + Critical, + Warning, + #[default] + Info, +} + +/// Исследуемая подсистема ОС (Linux/BSD) +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub enum Subsystem { + Systemd, // Службы Init (systemd, openrc, runit, etc.) + Kernel, + Storage, + Audio, + Network, + Security, + Crashes, +} + +/// Статус состояния подсистемы для сводного дашборда +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct SubsystemStatus { + pub name: Subsystem, + pub status: String, // "Healthy", "Degraded", "Failed" + pub issue_count: u32, + pub details: String, +} + +/// Предложение по устранению ошибки с готовой CLI-командой +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct FixSuggestion { + pub title: String, + pub command: String, + pub explanation: String, +} + +/// Информация о сбойной системной службе (в независимости от Init: systemd, OpenRC, runit...) +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct FailedService { + pub name: String, + pub init_system: String, + pub state: String, + pub description: String, + pub logs: String, + pub restart_command: String, + pub status_command: String, +} + +/// Элемент диагностического отчета (проблема) +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct DiagnosticIssue { + pub id: String, + pub title: String, + pub subsystem: Subsystem, + pub severity: Severity, + pub root_cause: String, + pub explanation: String, + pub fix: Option, + pub raw_log: String, + pub sanitized: bool, + pub permission_denied: bool, +} + +pub type IssueItem = DiagnosticIssue; + +/// Подробный отчет об аппаратном обеспечении системы +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct HardwareInfo { + pub cpu: CpuInfo, + pub memory: MemoryInfo, + pub motherboard: MotherboardInfo, + pub gpus: Vec, + pub disks: Vec, + pub network_adapters: Vec, + pub battery: Option, + pub thermals: ThermalsInfo, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct CpuInfo { + pub model_name: String, + pub architecture: String, + pub physical_cores: usize, + pub logical_threads: usize, + pub base_frequency_mhz: Option, + pub current_frequency_mhz: Option, + pub l1_cache: String, + pub l2_cache: String, + pub l3_cache: String, + pub virtualization: Option, + pub flags: Vec, + pub microcode: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct MemoryInfo { + pub total_bytes: u64, + pub available_bytes: u64, + pub used_bytes: u64, + pub swap_total_bytes: u64, + pub swap_used_bytes: u64, + pub edac_ce_count: u64, + pub edac_ue_count: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct MotherboardInfo { + pub vendor: String, + pub product_name: String, + pub version: String, + pub bios_vendor: String, + pub bios_version: String, + pub bios_date: String, + pub chassis_type: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct GpuInfo { + pub vendor: String, + pub model: String, + pub driver: String, + pub pci_slot: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct PartitionInfo { + pub name: String, + pub path: String, + pub mount_point: Option, + pub fs_type: String, + pub size_bytes: u64, + pub used_bytes: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct DiskInfo { + pub name: String, + pub model: String, + pub serial: String, + pub size_bytes: u64, + pub disk_type: String, + pub rotational_speed_rpm: Option, + pub smart_status: String, + pub health_percent: Option, + pub wear_percent: Option, + pub nvme_wear_percent: Option, + pub temperature_c: Option, + pub power_on_hours: Option, + pub power_cycle_count: Option, + pub bad_sectors_count: Option, + pub total_written_tb: Option, + pub partitions: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct NetworkAdapterInfo { + pub interface_name: String, + pub if_type: String, + pub state: String, + pub speed_mbps: Option, + pub mac_address: String, + pub driver: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct BatteryInfo { + pub name: String, + pub capacity_percent: u8, + pub health_percent: f32, + pub cycle_count: u32, + pub status: String, + pub is_degraded: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct ThermalsInfo { + pub max_cpu_temp_c: f32, + pub thermal_throttled_cores: usize, + pub total_throttle_events: u64, + pub is_actively_throttling: bool, +} + +// --- LIVE METRICS --- +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct LiveMetricsSnapshot { + pub cpu_usage_percent: f32, + pub ram_used_bytes: u64, + pub ram_total_bytes: u64, + pub swap_used_bytes: u64, + pub swap_total_bytes: u64, + pub max_cpu_temp_c: f32, + pub is_throttling: bool, + pub disk_read_kbps: u64, + pub disk_write_kbps: u64, + pub net_rx_kbps: u64, + pub net_tx_kbps: u64, +} + +// --- CRASH DUMPS --- +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct CrashReportInfo { + pub timestamp: String, + pub process_name: String, + pub pid: Option, + pub signal_or_code: String, + pub fault_module: Option, + pub stack_trace_snippet: String, + pub dump_path: Option, +} + +// --- SECURITY AUDIT --- +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct ListeningPortInfo { + pub protocol: String, + pub local_address: String, + pub port: u16, + pub process_name: String, + pub pid: Option, + pub is_public: bool, + pub risk_level: Severity, + pub recommendation: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct SuidAnomalyInfo { + pub path: String, + pub owner: String, + pub permissions: String, + pub risk_reason: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct SecurityCheckItem { + pub category: String, + pub name: String, + pub status: String, + pub is_secure: bool, + pub description: String, + pub remediation: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct SecurityAuditReport { + pub exposed_ports: Vec, + pub suid_anomalies: Vec, + pub hardening_checks: Vec, + pub security_score: u8, +} + +/// Общий итоговый отчет диагностики +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct SystemReport { + pub timestamp: String, + pub os_family: String, // "Linux", "FreeBSD", "OpenBSD", etc. + pub init_system: String, // "systemd", "openrc", "runit", "s6", "dinit", "bsd-rc" + pub is_root: bool, + pub subsystems: Vec, + pub issues: Vec, + pub failed_services: Vec, + pub hardware: HardwareInfo, + pub crashes: Vec, + pub security: SecurityAuditReport, + pub llm_analyzed: bool, + pub summary: String, + pub prompt_preview: String, +} diff --git a/crates/core/src/sanitize.rs b/crates/core/src/sanitize.rs new file mode 100644 index 0000000..8a057ae --- /dev/null +++ b/crates/core/src/sanitize.rs @@ -0,0 +1,75 @@ +use regex::Regex; +use std::sync::OnceLock; + +pub struct DataSanitizer; + +static RE_HOME_PATH: OnceLock = OnceLock::new(); +static RE_USR_HOME_PATH: OnceLock = OnceLock::new(); +static RE_IPV4: OnceLock = OnceLock::new(); +static RE_MAC_ADDR: OnceLock = OnceLock::new(); +static RE_AUTH_TOKEN: OnceLock = OnceLock::new(); +static RE_UUID: OnceLock = OnceLock::new(); + +impl DataSanitizer { + /// Очищает системные логи от персональных данных: + /// - Домашние пути (/home// и /usr/home// на BSD -> /home/[USER]/) + /// - IPv4 адреса (192.168.x.x, внешние IP) + /// - MAC-адреса + /// - Токены/секреты/пароли + /// - Аппаратные UUID + pub fn sanitize(raw: &str) -> String { + let home_re = RE_HOME_PATH.get_or_init(|| { + Regex::new(r"/home/[a-zA-Z0-9_\-]+").expect("Invalid home regex") + }); + let usr_home_re = RE_USR_HOME_PATH.get_or_init(|| { + Regex::new(r"/usr/home/[a-zA-Z0-9_\-]+").expect("Invalid BSD usr home regex") + }); + let ipv4_re = RE_IPV4.get_or_init(|| { + Regex::new(r"\b(?:\d{1,3}\.){3}\d{1,3}\b").expect("Invalid IPv4 regex") + }); + let mac_re = RE_MAC_ADDR.get_or_init(|| { + Regex::new(r"(?i)\b([0-9a-f]{2}[:-]){5}([0-9a-f]{2})\b").expect("Invalid MAC regex") + }); + let auth_re = RE_AUTH_TOKEN.get_or_init(|| { + Regex::new(r"(?i)(bearer|token|password|secret|api[_-]?key)[=:\s]+[A-Za-z0-9_\-\.\/]{8,}").expect("Invalid secret regex") + }); + let uuid_re = RE_UUID.get_or_init(|| { + Regex::new(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b").expect("Invalid UUID regex") + }); + + let mut clean = home_re.replace_all(raw, "/home/[USER]").to_string(); + clean = usr_home_re.replace_all(&clean, "/home/[USER]").to_string(); + clean = auth_re.replace_all(&clean, "$1=[REDACTED_SECRET]").to_string(); + clean = mac_re.replace_all(&clean, "[MAC_ADDR]").to_string(); + clean = uuid_re.replace_all(&clean, "[UUID]").to_string(); + + clean = ipv4_re.replace_all(&clean, |caps: ®ex::Captures| { + let ip = &caps[0]; + if ip.starts_with("127.") { + ip.to_string() + } else { + "[IP_ADDR]".to_string() + } + }).to_string(); + + clean + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_sanitizer() { + let text = "Error for /usr/home/bsduser/file.txt and /home/linuxuser/app.rs at 10.0.0.4 with token=xyzSecret12345"; + let clean = DataSanitizer::sanitize(text); + assert!(!clean.contains("bsduser")); + assert!(!clean.contains("linuxuser")); + assert!(!clean.contains("10.0.0.4")); + assert!(!clean.contains("xyzSecret12345")); + assert!(clean.contains("/home/[USER]")); + assert!(clean.contains("[IP_ADDR]")); + assert!(clean.contains("[REDACTED_SECRET]")); + } +} diff --git a/crates/core/src/scanner/bsd.rs b/crates/core/src/scanner/bsd.rs new file mode 100644 index 0000000..7725470 --- /dev/null +++ b/crates/core/src/scanner/bsd.rs @@ -0,0 +1,95 @@ +use std::process::Command; + +pub struct BsdRawData { + pub failed_services: Vec, + pub service_logs: String, + pub kernel_logs: String, + pub storage_logs: String, + pub network_logs: String, + pub audio_logs: String, +} + +impl BsdRawData { + pub fn collect() -> Self { + // 1. Опрос сервисов: в FreeBSD/OpenBSD проверяем service / rcctl + let mut failed_services = Vec::new(); + let mut service_logs = String::new(); + + // Проверка OpenBSD rcctl ls failed + if let Ok(output) = Command::new("rcctl").args(["ls", "failed"]).output() { + let str_out = String::from_utf8_lossy(&output.stdout); + for line in str_out.lines() { + let trimmed = line.trim(); + if !trimmed.is_empty() { + failed_services.push(trimmed.to_string()); + } + } + } + + // 2. Чтение логов ядра dmesg + let kernel_logs = Command::new("dmesg") + .output() + .map(|o| { + let text = String::from_utf8_lossy(&o.stdout); + // Фильтруем последние 40 строк dmesg + text.lines() + .rev() + .take(40) + .collect::>() + .into_iter() + .rev() + .collect::>() + .join("\n") + }) + .unwrap_or_default(); + + // 3. Дисковая подсистема: zpool status (ZFS популярен на FreeBSD) или dmesg + let storage_logs = Command::new("zpool") + .args(["status", "-x"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_else(|_| { + // Ищем ошибки дисков в dmesg + kernel_logs + .lines() + .filter(|l| l.contains("error") || l.contains("CAM") || l.contains("GEOM")) + .collect::>() + .join("\n") + }); + + // 4. Сеть: ifconfig или /var/log/messages + let network_logs = Command::new("ifconfig") + .args(["-a"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_default(); + + // 5. Звук: cat /dev/sndstat (FreeBSD) + let audio_logs = std::fs::read_to_string("/dev/sndstat").unwrap_or_else(|_| { + "Audio driver: default BSD sound subsystem".to_string() + }); + + // Логи из /var/log/messages, если есть + if let Ok(messages) = std::fs::read_to_string("/var/log/messages") { + let errors = messages + .lines() + .rev() + .filter(|l| l.contains("error") || l.contains("fail") || l.contains("crit")) + .take(25) + .collect::>() + .join("\n"); + if !errors.is_empty() { + service_logs.push_str(&format!("--- Recent /var/log/messages ---\n{}\n", errors)); + } + } + + Self { + failed_services, + service_logs, + kernel_logs, + storage_logs, + network_logs, + audio_logs, + } + } +} diff --git a/crates/core/src/scanner/crashes.rs b/crates/core/src/scanner/crashes.rs new file mode 100644 index 0000000..f149dc5 --- /dev/null +++ b/crates/core/src/scanner/crashes.rs @@ -0,0 +1,213 @@ +use crate::models::CrashReportInfo; +use std::path::Path; +use std::process::Command; + +pub struct CrashScanner; + +impl CrashScanner { + pub fn scan() -> Vec { + let mut crashes = Vec::new(); + + #[cfg(target_os = "linux")] + { + Self::scan_linux_coredumps(&mut crashes); + Self::scan_linux_var_crash(&mut crashes); + Self::scan_linux_dmesg_segfaults(&mut crashes); + } + + #[cfg(target_os = "windows")] + { + Self::scan_windows_minidumps(&mut crashes); + Self::scan_windows_event_crashes(&mut crashes); + } + + #[cfg(target_os = "macos")] + { + Self::scan_macos_diagnostic_reports(&mut crashes); + } + + // Generic fallback if empty (e.g. BSD or systems without coredumpctl) + if crashes.is_empty() { + Self::scan_generic_system_logs(&mut crashes); + } + + // Limit to 20 most recent crashes + crashes.truncate(20); + crashes + } + + #[cfg(target_os = "linux")] + fn scan_linux_coredumps(crashes: &mut Vec) { + if let Ok(output) = Command::new("coredumpctl") + .args(["list", "--no-legend", "-n", "10"]) + .output() + { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() >= 5 { + let time = parts[0..parts.len().saturating_sub(6)].join(" "); + let pid = parts.iter().find_map(|p| p.parse::().ok()); + let signal = parts.iter().find(|p| p.starts_with("SIG") || **p == "11" || **p == "6").copied().unwrap_or("SIGSEGV"); + let exe = parts.last().unwrap_or(&"unknown"); + + crashes.push(CrashReportInfo { + timestamp: if time.is_empty() { "Недавний".to_string() } else { time }, + process_name: exe.to_string(), + pid, + signal_or_code: signal.to_string(), + fault_module: None, + stack_trace_snippet: format!("Core dump сохранен systemd-coredump для исполняемого файла {}", exe), + dump_path: Some(format!("coredumpctl info {}", pid.unwrap_or(0))), + }); + } + } + } + } + + #[cfg(target_os = "linux")] + fn scan_linux_var_crash(crashes: &mut Vec) { + let crash_dir = Path::new("/var/crash"); + if let Ok(entries) = std::fs::read_dir(crash_dir) { + for entry in entries.flatten() { + let path = entry.path(); + let filename = path.file_name().unwrap_or_default().to_string_lossy().to_string(); + if filename.ends_with(".crash") { + let proc_name = filename.trim_end_matches(".crash").to_string(); + let metadata = std::fs::metadata(&path).ok(); + let time_str = metadata + .and_then(|m| m.modified().ok()) + .map(|t| format!("{:?}", t)) + .unwrap_or_else(|| "Архивный".to_string()); + + crashes.push(CrashReportInfo { + timestamp: time_str, + process_name: proc_name, + pid: None, + signal_or_code: "Crash Dump".to_string(), + fault_module: None, + stack_trace_snippet: format!("Дамп аварийного завершения в /var/crash/{}", filename), + dump_path: Some(path.to_string_lossy().to_string()), + }); + } + } + } + } + + #[cfg(target_os = "linux")] + fn scan_linux_dmesg_segfaults(crashes: &mut Vec) { + // Поиск segfaults в dmesg через неинтерактивный вызов + if let Ok(output) = Command::new("dmesg").args(["-T", "-l", "err,warn"]).output() { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + if line.contains("segfault at") || line.contains("general protection fault") { + let mut proc = "kernel".to_string(); + let mut fault_mod = None; + + if let Some(idx) = line.find("[") { + if let Some(_end) = line[idx..].find("]") { + let candidate = line[..idx].trim().split_whitespace().last().unwrap_or(""); + if !candidate.is_empty() { + proc = candidate.to_string(); + } + } + } + + if let Some(in_idx) = line.find(" in ") { + let after_in = &line[in_idx + 4..]; + let mod_name = after_in.split_whitespace().next().unwrap_or(""); + if !mod_name.is_empty() { + fault_mod = Some(mod_name.to_string()); + } + } + + crashes.push(CrashReportInfo { + timestamp: "Из dmesg".to_string(), + process_name: proc, + pid: None, + signal_or_code: "SIGSEGV (Segmentation Fault)".to_string(), + fault_module: fault_mod, + stack_trace_snippet: line.trim().to_string(), + dump_path: None, + }); + } + } + } + } + + #[cfg(target_os = "windows")] + fn scan_windows_minidumps(crashes: &mut Vec) { + let minidump_dir = Path::new(r"C:\Windows\Minidump"); + if let Ok(entries) = std::fs::read_dir(minidump_dir) { + for entry in entries.flatten() { + let path = entry.path(); + let name = path.file_name().unwrap_or_default().to_string_lossy().to_string(); + if name.ends_with(".dmp") { + crashes.push(CrashReportInfo { + timestamp: "BSOD Crash Dump".to_string(), + process_name: "ntoskrnl.exe (Kernel BSOD)".to_string(), + pid: Some(4), + signal_or_code: "BUGCHECK_DUMP".to_string(), + fault_module: Some("Kernel".to_string()), + stack_trace_snippet: format!("Дамп аварийного синего экрана смерти: {}", path.display()), + dump_path: Some(path.to_string_lossy().to_string()), + }); + } + } + } + } + + #[cfg(target_os = "windows")] + fn scan_windows_event_crashes(crashes: &mut Vec) { + let ps_cmd = "Get-WinEvent -FilterHashtable @{LogName='Application'; ProviderName='Application Error'} -MaxEvents 5 -ErrorAction SilentlyContinue | Select-Object TimeCreated, Message | ConvertTo-Json -Compress"; + if let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]).output() { + if let Ok(val) = serde_json::from_str::(&String::from_utf8_lossy(&output.stdout)) { + let items = match val { + serde_json::Value::Array(a) => a, + serde_json::Value::Object(_) => vec![val], + _ => vec![], + }; + for item in items { + let msg = item["Message"].as_str().unwrap_or(""); + let time = item["TimeCreated"].as_str().unwrap_or("Недавно"); + crashes.push(CrashReportInfo { + timestamp: time.to_string(), + process_name: "Application Error".to_string(), + pid: None, + signal_or_code: "0xC0000005 (Access Violation)".to_string(), + fault_module: None, + stack_trace_snippet: msg.trim().to_string(), + dump_path: None, + }); + } + } + } + } + + #[cfg(target_os = "macos")] + fn scan_macos_diagnostic_reports(crashes: &mut Vec) { + let reports_dir = Path::new("/Library/Logs/DiagnosticReports"); + if let Ok(entries) = std::fs::read_dir(reports_dir) { + for entry in entries.flatten() { + let path = entry.path(); + let name = path.file_name().unwrap_or_default().to_string_lossy().to_string(); + if name.ends_with(".ips") || name.ends_with(".crash") { + let proc = name.split(['_', '-']).next().unwrap_or(&name).to_string(); + crashes.push(CrashReportInfo { + timestamp: "Diagnostic Report".to_string(), + process_name: proc, + pid: None, + signal_or_code: "EXC_BAD_ACCESS / Crash".to_string(), + fault_module: None, + stack_trace_snippet: format!("macOS Crash Report: {}", path.display()), + dump_path: Some(path.to_string_lossy().to_string()), + }); + } + } + } + } + + fn scan_generic_system_logs(_crashes: &mut Vec) { + // Fallback placeholder + } +} diff --git a/crates/core/src/scanner/hardware.rs b/crates/core/src/scanner/hardware.rs new file mode 100644 index 0000000..99bfbcd --- /dev/null +++ b/crates/core/src/scanner/hardware.rs @@ -0,0 +1,1332 @@ +use crate::models::{ + BatteryInfo, CpuInfo, DiskInfo, GpuInfo, HardwareInfo, MemoryInfo, MotherboardInfo, + NetworkAdapterInfo, PartitionInfo, ThermalsInfo, +}; +use std::collections::HashSet; +use std::path::Path; +use std::process::Command; + +#[derive(Default, Clone, Debug)] +struct SmartDiskData { + serial: String, + smart_status: String, + health_percent: Option, + wear_percent: Option, + temperature_c: Option, + power_on_hours: Option, + power_cycle_count: Option, + bad_sectors_count: Option, + total_written_tb: Option, + rotational_speed_rpm: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct HardwareAuditResult { + pub max_cpu_temp_c: f32, + pub thermal_throttled_cores: usize, + pub total_throttle_events: u64, + pub is_actively_throttling: bool, + pub battery_health: Option, + pub nvme_health: Vec, + pub edac_ce_count: u64, + pub edac_ue_count: u64, +} + +#[derive(Debug, Clone, Default)] +pub struct BatteryHealth { + pub name: String, + pub capacity_percent: u8, + pub health_percent: f32, + pub cycle_count: u32, + pub is_degraded: bool, +} + +#[derive(Debug, Clone, Default)] +pub struct NvmeHealth { + pub device: String, + pub percentage_used: Option, + pub temperature_c: Option, + pub critical_warning: bool, +} + +pub struct HardwareScanner; + +impl HardwareScanner { + pub fn scan() -> (HardwareAuditResult, HardwareInfo) { + let (ce, ue) = Self::scan_edac(); + let (thermal_throttled_cores, total_throttle_events) = Self::scan_cpu_throttling(); + let max_cpu_temp_c = Self::scan_thermal_zones(); + let is_actively_throttling = max_cpu_temp_c >= 90.0 || total_throttle_events > 0; + + let battery_health = Self::scan_battery(); + let nvme_health = Self::scan_nvme(); + + let audit = HardwareAuditResult { + max_cpu_temp_c, + thermal_throttled_cores, + total_throttle_events, + is_actively_throttling, + battery_health: battery_health.as_ref().map(|b| BatteryHealth { + name: b.name.clone(), + capacity_percent: b.capacity_percent, + health_percent: b.health_percent, + cycle_count: b.cycle_count, + is_degraded: b.is_degraded, + }), + nvme_health, + edac_ce_count: ce, + edac_ue_count: ue, + }; + + let cpu = Self::scan_cpu(); + let motherboard = Self::scan_motherboard(); + let memory = Self::scan_memory(ce, ue); + let gpus = Self::scan_gpus(); + let disks = Self::scan_disks(); + let network_adapters = Self::scan_network(); + let thermals = ThermalsInfo { + max_cpu_temp_c, + thermal_throttled_cores, + total_throttle_events, + is_actively_throttling, + }; + + let detailed = HardwareInfo { + cpu, + memory, + motherboard, + gpus, + disks, + network_adapters, + battery: battery_health, + thermals, + }; + + (audit, detailed) + } + + fn scan_thermal_zones() -> f32 { + let mut max_temp = 0.0f32; + if let Ok(entries) = std::fs::read_dir("/sys/class/thermal") { + for entry in entries.flatten() { + let path = entry.path(); + if path.file_name().map(|n| n.to_string_lossy().starts_with("thermal_zone")).unwrap_or(false) { + let temp_file = path.join("temp"); + if let Ok(content) = std::fs::read_to_string(temp_file) { + if let Ok(milli_c) = content.trim().parse::() { + let c = milli_c as f32 / 1000.0; + if c > max_temp && c < 150.0 { + max_temp = c; + } + } + } + } + } + } + max_temp + } + + fn scan_cpu_throttling() -> (usize, u64) { + let mut throttled_cores = 0; + let mut total_events = 0u64; + + if let Ok(entries) = std::fs::read_dir("/sys/devices/system/cpu") { + for entry in entries.flatten() { + let path = entry.path(); + let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + if name.starts_with("cpu") && name[3..].chars().all(|c| c.is_ascii_digit()) { + let throttle_dir = path.join("thermal_throttle"); + let core_file = throttle_dir.join("core_throttle_count"); + if let Ok(content) = std::fs::read_to_string(core_file) { + if let Ok(count) = content.trim().parse::() { + if count > 0 { + throttled_cores += 1; + total_events += count; + } + } + } + } + } + } + + (throttled_cores, total_events) + } + + // --- BATTERY SCANNING --- + fn scan_battery() -> Option { + if let Ok(entries) = std::fs::read_dir("/sys/class/power_supply") { + for entry in entries.flatten() { + let path = entry.path(); + let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + if name.starts_with("BAT") { + let capacity = std::fs::read_to_string(path.join("capacity")) + .ok() + .and_then(|s| s.trim().parse::().ok()) + .unwrap_or(100); + + let full_energy = std::fs::read_to_string(path.join("energy_full")) + .or_else(|_| std::fs::read_to_string(path.join("charge_full"))) + .ok() + .and_then(|s| s.trim().parse::().ok()); + + let design_energy = std::fs::read_to_string(path.join("energy_full_design")) + .or_else(|_| std::fs::read_to_string(path.join("charge_full_design"))) + .ok() + .and_then(|s| s.trim().parse::().ok()); + + let cycle_count = std::fs::read_to_string(path.join("cycle_count")) + .ok() + .and_then(|s| s.trim().parse::().ok()) + .unwrap_or(0); + + let status = std::fs::read_to_string(path.join("status")) + .unwrap_or_else(|_| "Discharging".to_string()) + .trim() + .to_string(); + + let health_percent = if let (Some(full), Some(design)) = (full_energy, design_energy) { + if design > 0.0 { + (full / design) * 100.0 + } else { + 100.0 + } + } else { + 100.0 + }; + + let is_degraded = health_percent < 70.0 || cycle_count > 600; + + return Some(BatteryInfo { + name, + capacity_percent: capacity, + health_percent, + cycle_count, + status, + is_degraded, + }); + } + } + } + None + } + + fn scan_nvme() -> Vec { + let mut list = Vec::new(); + if let Ok(entries) = std::fs::read_dir("/sys/class/nvme") { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + list.push(NvmeHealth { + device: format!("/dev/{}", name), + percentage_used: None, + temperature_c: None, + critical_warning: false, + }); + } + } + list + } + + fn scan_edac() -> (u64, u64) { + let mut ce_total = 0u64; + let mut ue_total = 0u64; + + let edac_mc = Path::new("/sys/devices/system/edac/mc"); + if edac_mc.exists() { + if let Ok(entries) = std::fs::read_dir(edac_mc) { + for entry in entries.flatten() { + let path = entry.path(); + let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + if name.starts_with("mc") { + if let Ok(c) = std::fs::read_to_string(path.join("ce_count")) { + ce_total += c.trim().parse::().unwrap_or(0); + } + if let Ok(u) = std::fs::read_to_string(path.join("ue_count")) { + ue_total += u.trim().parse::().unwrap_or(0); + } + } + } + } + } + + (ce_total, ue_total) + } + + // --- CPU SCANNING --- + fn scan_cpu() -> CpuInfo { + let mut info = CpuInfo { + architecture: std::env::consts::ARCH.to_string(), + ..Default::default() + }; + + if let Ok(cpuinfo) = std::fs::read_to_string("/proc/cpuinfo") { + let mut physical_ids = HashSet::new(); + let mut core_ids = HashSet::new(); + let mut threads = 0; + let mut model_found = false; + + for block in cpuinfo.split("\n\n") { + if block.trim().is_empty() { + continue; + } + threads += 1; + let mut current_phys_id = 0; + + for line in block.lines() { + let mut parts = line.splitn(2, ':'); + let key = parts.next().unwrap_or("").trim(); + let val = parts.next().unwrap_or("").trim(); + + match key { + "model name" | "Processor" if !model_found => { + info.model_name = val.to_string(); + model_found = true; + } + "cpu MHz" if info.current_frequency_mhz.is_none() => { + info.current_frequency_mhz = val.parse::().ok(); + } + "microcode" if info.microcode.is_empty() => { + info.microcode = val.to_string(); + } + "physical id" => { + current_phys_id = val.parse::().unwrap_or(0); + physical_ids.insert(current_phys_id); + } + "core id" => { + let core_id = val.parse::().unwrap_or(0); + core_ids.insert((current_phys_id, core_id)); + } + "flags" | "Features" if info.flags.is_empty() => { + let flags: Vec<&str> = val.split_whitespace().collect(); + if flags.contains(&"vmx") { + info.virtualization = Some(if Path::new("/dev/kvm").exists() { + "Intel VT-x (KVM ready)".to_string() + } else { + "Intel VT-x".to_string() + }); + } else if flags.contains(&"svm") { + info.virtualization = Some(if Path::new("/dev/kvm").exists() { + "AMD-V / SVM (KVM ready)".to_string() + } else { + "AMD-V / SVM".to_string() + }); + } + + let important = [ + "aes", "avx", "avx2", "avx512f", "fma", "sse4_2", "rdrand", "sha_ni", + "smep", "smap", "pcid", "pdpe1gb", + ]; + info.flags = flags + .iter() + .filter(|f| important.contains(&f.to_ascii_lowercase().as_str())) + .map(|f| f.to_ascii_uppercase()) + .collect(); + } + _ => {} + } + } + } + + info.logical_threads = threads; + info.physical_cores = if !core_ids.is_empty() { + core_ids.len() + } else { + threads + }; + // macOS / Windows / BSD fallback + #[cfg(target_os = "macos")] + { + if let Ok(output) = Command::new("sysctl").args(["-n", "machdep.cpu.brand_string"]).output() { + info.model_name = String::from_utf8_lossy(&output.stdout).trim().to_string(); + } + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.physicalcpu"]).output() { + info.physical_cores = String::from_utf8_lossy(&output.stdout).trim().parse::().unwrap_or(1); + } + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.logicalcpu"]).output() { + info.logical_threads = String::from_utf8_lossy(&output.stdout).trim().parse::().unwrap_or(1); + } + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.cpufrequency"]).output() { + if let Ok(hz) = String::from_utf8_lossy(&output.stdout).trim().parse::() { + info.current_frequency_mhz = Some(hz / 1_000_000.0); + } + } + } + + #[cfg(target_os = "windows")] + { + let ps_cmd = "Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessors, MaxClockSpeed | ConvertTo-Json -Compress"; + if let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]).output() { + if let Ok(val) = serde_json::from_str::(&String::from_utf8_lossy(&output.stdout)) { + let obj = match val { + serde_json::Value::Array(ref arr) => arr.first().cloned().unwrap_or(val.clone()), + _ => val, + }; + if let Some(name) = obj["Name"].as_str() { + info.model_name = name.trim().to_string(); + } + if let Some(cores) = obj["NumberOfCores"].as_u64() { + info.physical_cores = cores as usize; + } + if let Some(threads) = obj["NumberOfLogicalProcessors"].as_u64() { + info.logical_threads = threads as usize; + } + if let Some(mhz) = obj["MaxClockSpeed"].as_f64() { + info.current_frequency_mhz = Some(mhz as f32); + info.base_frequency_mhz = Some(mhz as f32); + } + } + } + } + + // Generic Unix / BSD fallback via sysctl + if info.model_name.is_empty() { + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.model"]).output() { + info.model_name = String::from_utf8_lossy(&output.stdout).trim().to_string(); + } + } + if info.logical_threads == 0 { + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.ncpu"]).output() { + let ncpu = String::from_utf8_lossy(&output.stdout).trim().parse::().unwrap_or(1); + info.logical_threads = ncpu; + info.physical_cores = ncpu; + } + } + if info.current_frequency_mhz.is_none() { + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.clockrate"]).output() { + info.current_frequency_mhz = String::from_utf8_lossy(&output.stdout).trim().parse::().ok(); + } + } + } + + // Кэши CPU из /sys/devices/system/cpu/cpu0/cache/ + if let Ok(entries) = std::fs::read_dir("/sys/devices/system/cpu/cpu0/cache") { + let mut l1d = String::new(); + let mut l1i = String::new(); + for entry in entries.flatten() { + let p = entry.path(); + let level = std::fs::read_to_string(p.join("level")).unwrap_or_default(); + let c_type = std::fs::read_to_string(p.join("type")).unwrap_or_default(); + let size = std::fs::read_to_string(p.join("size")).unwrap_or_default(); + let level = level.trim(); + let c_type = c_type.trim(); + let size = size.trim(); + + match level { + "1" => { + if c_type == "Data" { + l1d = format!("L1d {}", size); + } else if c_type == "Instruction" { + l1i = format!("L1i {}", size); + } + } + "2" => info.l2_cache = format!("L2 {}", size), + "3" => info.l3_cache = format!("L3 {}", size), + _ => {} + } + } + info.l1_cache = if !l1d.is_empty() && !l1i.is_empty() { + format!("{}, {}", l1d, l1i) + } else if !l1d.is_empty() { + l1d + } else { + "L1 64KB".to_string() + }; + } + + info + } + + // --- MOTHERBOARD / DMI SCANNING --- + fn scan_motherboard() -> MotherboardInfo { + let mut info = MotherboardInfo::default(); + let dmi_dir = Path::new("/sys/class/dmi/id"); + + if dmi_dir.exists() { + info.vendor = read_dmi_field(dmi_dir, "board_vendor") + .or_else(|| read_dmi_field(dmi_dir, "sys_vendor")) + .unwrap_or_else(|| "Unknown".to_string()); + + info.product_name = read_dmi_field(dmi_dir, "product_name") + .or_else(|| read_dmi_field(dmi_dir, "board_name")) + .unwrap_or_else(|| "Standard PC".to_string()); + + info.version = read_dmi_field(dmi_dir, "product_version") + .or_else(|| read_dmi_field(dmi_dir, "board_version")) + .unwrap_or_default(); + + info.bios_vendor = read_dmi_field(dmi_dir, "bios_vendor").unwrap_or_default(); + info.bios_version = read_dmi_field(dmi_dir, "bios_version").unwrap_or_default(); + info.bios_date = read_dmi_field(dmi_dir, "bios_date").unwrap_or_default(); + + let chassis_code = read_dmi_field(dmi_dir, "chassis_type").unwrap_or_default(); + info.chassis_type = decode_chassis_type(&chassis_code); + } else { + #[cfg(target_os = "macos")] + { + info.vendor = "Apple Inc.".to_string(); + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.model"]).output() { + let model = String::from_utf8_lossy(&output.stdout).trim().to_string(); + info.product_name = model.clone(); + info.chassis_type = if model.contains("Book") { "Laptop".to_string() } else { "Desktop".to_string() }; + } + info.bios_vendor = "Apple EFI".to_string(); + } + + #[cfg(target_os = "windows")] + { + let ps_cmd = "Get-CimInstance Win32_BaseBoard | Select-Object Manufacturer, Product | ConvertTo-Json -Compress"; + if let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]).output() { + if let Ok(val) = serde_json::from_str::(&String::from_utf8_lossy(&output.stdout)) { + if let Some(m) = val["Manufacturer"].as_str() { + info.vendor = m.trim().to_string(); + } + if let Some(p) = val["Product"].as_str() { + info.product_name = p.trim().to_string(); + } + } + } + let ps_bios = "Get-CimInstance Win32_BIOS | Select-Object Manufacturer, SMBIOSBIOSVersion, ReleaseDate | ConvertTo-Json -Compress"; + if let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_bios]).output() { + if let Ok(val) = serde_json::from_str::(&String::from_utf8_lossy(&output.stdout)) { + if let Some(m) = val["Manufacturer"].as_str() { + info.bios_vendor = m.trim().to_string(); + } + if let Some(v) = val["SMBIOSBIOSVersion"].as_str() { + info.bios_version = v.trim().to_string(); + } + if let Some(d) = val["ReleaseDate"].as_str() { + info.bios_date = d.trim().to_string(); + } + } + } + } + + // BSD fallback via kenv + if info.product_name.is_empty() { + if let Ok(output) = Command::new("kenv").arg("smbios.system.product").output() { + let val = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if !val.is_empty() { + info.product_name = val; + } + } + } + if info.bios_vendor.is_empty() { + if let Ok(output) = Command::new("kenv").arg("smbios.bios.vendor").output() { + info.bios_vendor = String::from_utf8_lossy(&output.stdout).trim().to_string(); + } + } + if info.bios_version.is_empty() { + if let Ok(output) = Command::new("kenv").arg("smbios.bios.version").output() { + info.bios_version = String::from_utf8_lossy(&output.stdout).trim().to_string(); + } + } + if info.vendor.is_empty() { + info.vendor = "System Board".to_string(); + } + } + + info + } + + // --- MEMORY SCANNING --- + fn scan_memory(ce: u64, ue: u64) -> MemoryInfo { + let mut info = MemoryInfo { + edac_ce_count: ce, + edac_ue_count: ue, + ..Default::default() + }; + + if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") { + for line in meminfo.lines() { + let mut parts = line.split(':'); + let key = parts.next().unwrap_or("").trim(); + let val_str = parts.next().unwrap_or("").trim(); + let kb = val_str.split_whitespace().next().and_then(|v| v.parse::().ok()).unwrap_or(0); + let bytes = kb * 1024; + + match key { + "MemTotal" => info.total_bytes = bytes, + "MemAvailable" => info.available_bytes = bytes, + "SwapTotal" => info.swap_total_bytes = bytes, + "SwapFree" => { + let swap_free = bytes; + if info.swap_total_bytes >= swap_free { + info.swap_used_bytes = info.swap_total_bytes - swap_free; + } + } + _ => {} + } + } + if info.total_bytes >= info.available_bytes { + info.used_bytes = info.total_bytes - info.available_bytes; + } + } else { + #[cfg(target_os = "macos")] + { + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.memsize"]).output() { + info.total_bytes = String::from_utf8_lossy(&output.stdout).trim().parse::().unwrap_or(0); + } + if let Ok(output) = Command::new("vm_stat").output() { + let text = String::from_utf8_lossy(&output.stdout); + let mut free_pages = 0u64; + for line in text.lines() { + if line.contains("Pages free:") { + if let Some(val) = line.split(':').nth(1) { + free_pages += val.trim().trim_end_matches('.').parse::().unwrap_or(0); + } + } + } + let free_bytes = free_pages * 4096; + info.available_bytes = free_bytes; + if info.total_bytes >= free_bytes { + info.used_bytes = info.total_bytes - free_bytes; + } + } + } + + #[cfg(target_os = "windows")] + { + let ps_cmd = "Get-CimInstance Win32_OperatingSystem | Select-Object TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory | ConvertTo-Json -Compress"; + if let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]).output() { + if let Ok(val) = serde_json::from_str::(&String::from_utf8_lossy(&output.stdout)) { + let total_kb = val["TotalVisibleMemorySize"].as_u64().unwrap_or(0); + let free_kb = val["FreePhysicalMemory"].as_u64().unwrap_or(0); + let total_v_kb = val["TotalVirtualMemorySize"].as_u64().unwrap_or(0); + let free_v_kb = val["FreeVirtualMemory"].as_u64().unwrap_or(0); + + info.total_bytes = total_kb * 1024; + info.available_bytes = free_kb * 1024; + if info.total_bytes >= info.available_bytes { + info.used_bytes = info.total_bytes - info.available_bytes; + } + + let swap_total = total_v_kb.saturating_sub(total_kb) * 1024; + let swap_free = free_v_kb.saturating_sub(free_kb) * 1024; + info.swap_total_bytes = swap_total; + info.swap_used_bytes = swap_total.saturating_sub(swap_free); + } + } + } + + // BSD fallback + if info.total_bytes == 0 { + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.physmem"]).output() { + info.total_bytes = String::from_utf8_lossy(&output.stdout).trim().parse::().unwrap_or(0); + } + if let Ok(output) = Command::new("sysctl").args(["-n", "hw.usermem"]).output() { + info.available_bytes = String::from_utf8_lossy(&output.stdout).trim().parse::().unwrap_or(0); + if info.total_bytes >= info.available_bytes { + info.used_bytes = info.total_bytes - info.available_bytes; + } + } + } + } + + info + } + + // --- GPU SCANNING --- + fn scan_gpus() -> Vec { + let mut gpus = Vec::new(); + let pci_dir = Path::new("/sys/bus/pci/devices"); + + if let Ok(entries) = std::fs::read_dir(pci_dir) { + for entry in entries.flatten() { + let path = entry.path(); + if let Ok(class_content) = std::fs::read_to_string(path.join("class")) { + let class = class_content.trim(); + if class.starts_with("0x0300") || class.starts_with("0x0302") || class.starts_with("0x0380") { + let pci_slot = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let vendor_hex = std::fs::read_to_string(path.join("vendor")).unwrap_or_default(); + let device_hex = std::fs::read_to_string(path.join("device")).unwrap_or_default(); + let driver = std::fs::read_link(path.join("driver")) + .ok() + .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string())) + .unwrap_or_else(|| "None".to_string()); + + let vendor_id = vendor_hex.trim().to_lowercase(); + let vendor_name = match vendor_id.as_str() { + "0x10de" => "NVIDIA Corporation", + "0x1002" => "Advanced Micro Devices, Inc. (AMD/ATI)", + "0x8086" => "Intel Corporation", + "0x1af4" => "Red Hat, Inc. (VirtIO GPU)", + _ => "Unknown Vendor", + }; + + gpus.push(GpuInfo { + vendor: vendor_name.to_string(), + model: format!("Device {}", device_hex.trim()), + driver, + pci_slot, + }); + } + } + } + } + + if let Ok(output) = Command::new("lspci").output() { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + if line.contains("VGA compatible controller") || line.contains("3D controller") { + let parts: Vec<&str> = line.splitn(2, ':').collect(); + if parts.len() == 2 { + let desc = parts[1].trim(); + for gpu in &mut gpus { + if desc.to_lowercase().contains(&gpu.vendor.split_whitespace().next().unwrap_or("").to_lowercase()) { + gpu.model = desc.to_string(); + } + } + } + } + } + } + + gpus + } + + // --- DISKS SCANNING --- + fn get_fs_usage(mount_point: &str) -> (u64, u64) { + use std::ffi::CString; + use std::mem::MaybeUninit; + let mut stat = MaybeUninit::::uninit(); + if let Ok(c_path) = CString::new(mount_point) { + let res = unsafe { libc::statvfs(c_path.as_ptr(), stat.as_mut_ptr()) }; + if res == 0 { + let s = unsafe { stat.assume_init() }; + let total = s.f_blocks as u64 * s.f_frsize as u64; + let free = s.f_bavail as u64 * s.f_frsize as u64; + let used = total.saturating_sub(free); + return (total, used); + } + } + (0, 0) + } + + fn parse_tbw_from_raw(raw: u64, is_ssd: bool) -> f64 { + if raw == 0 { + return 0.0; + } + + // 1. Packed 48-bit value (e.g. Seagate and Western Digital HDDs) + if raw > 1_000_000_000_000 { + let b = raw.to_le_bytes(); + let high16 = u16::from_le_bytes([b[4], b[5]]) as f64; + let low32 = u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as f64; + if high16 > 0.0 { + return high16 / 1024.0 + (low32 * 512.0 / 1_000_000_000_000.0); + } else { + return (raw as f64 * 512.0) / 1_000_000_000_000.0; + } + } + + // 2. SATA SSDs (Silicon Motion, Phison, Realtek, Maxio, Yeestor, etc.) + if is_ssd { + if raw >= 500_000 { + // Megabytes counter: raw MB / 1048576 = TB + return raw as f64 / 1_048_576.0; + } else if raw >= 50_000 { + // 32 MiB blocks: raw * 32 / 1048576 = TB + return (raw as f64 * 32.0) / 1_048_576.0; + } else { + // GiB counter + return raw as f64 / 1024.0; + } + } + + // 3. Standard 512-byte sectors fallback + (raw as f64 * 512.0) / 1_000_000_000_000.0 + } + + fn collect_smart_map() -> std::collections::HashMap { + let mut map = std::collections::HashMap::new(); + let Ok(dump_output) = Command::new("udisksctl").arg("dump").output() else { + return map; + }; + let dump_str = String::from_utf8_lossy(&dump_output.stdout); + + let mut block_to_drive: std::collections::HashMap = std::collections::HashMap::new(); + let mut drive_blocks: std::collections::HashMap = std::collections::HashMap::new(); + + for section in dump_str.split("\n/org/freedesktop/UDisks2/") { + if section.starts_with("block_devices/") { + let mut dev = None; + let mut drive = None; + for line in section.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("Device:") { + dev = trimmed.strip_prefix("Device:").map(|s| s.trim().to_string()); + } else if trimmed.starts_with("Drive:") { + let d = trimmed.strip_prefix("Drive:").unwrap_or("").trim().trim_matches('\''); + if let Some(drv_name) = d.strip_prefix("/org/freedesktop/UDisks2/drives/") { + drive = Some(drv_name.to_string()); + } + } + } + if let (Some(d), Some(drv)) = (dev, drive) { + block_to_drive.insert(d, drv); + } + } else if section.starts_with("drives/") { + let header = section.lines().next().unwrap_or(""); + let drive_id = header + .split(':') + .next() + .unwrap_or("") + .trim_start_matches("drives/") + .trim() + .to_string(); + if drive_id.is_empty() { + continue; + } + + let mut data = SmartDiskData::default(); + data.smart_status = "UNKNOWN".to_string(); + + for line in section.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("Serial:") { + data.serial = trimmed.strip_prefix("Serial:").unwrap_or("").trim().to_string(); + } else if trimmed.starts_with("RotationRate:") { + if let Ok(rpm) = trimmed.strip_prefix("RotationRate:").unwrap_or("").trim().parse::() { + data.rotational_speed_rpm = Some(rpm); + } + } else if trimmed.starts_with("SmartFailing:") { + let is_failing = trimmed.strip_prefix("SmartFailing:").unwrap_or("").trim() == "true"; + data.smart_status = if is_failing { + "FAILED".to_string() + } else { + "PASSED".to_string() + }; + } else if trimmed.starts_with("SmartPowerOnSeconds:") { + if let Ok(sec) = trimmed.strip_prefix("SmartPowerOnSeconds:").unwrap_or("").trim().parse::() { + data.power_on_hours = Some(sec / 3600); + } + } else if trimmed.starts_with("SmartTemperature:") { + if let Ok(kelvin) = trimmed.strip_prefix("SmartTemperature:").unwrap_or("").trim().parse::() { + if kelvin > 100.0 { + data.temperature_c = Some((kelvin - 273.15).round() as i32); + } + } + } else if trimmed.starts_with("SmartNumBadSectors:") { + if let Ok(bad) = trimmed.strip_prefix("SmartNumBadSectors:").unwrap_or("").trim().parse::() { + data.bad_sectors_count = Some(bad); + } + } + } + + // Call busctl to get SmartGetAttributes for ATA drive + let bus_path = format!("/org/freedesktop/UDisks2/drives/{}", drive_id); + if let Ok(bus_out) = Command::new("busctl") + .args([ + "call", + "org.freedesktop.UDisks2", + &bus_path, + "org.freedesktop.UDisks2.Drive.Ata", + "SmartGetAttributes", + "a{sv}", + "0", + ]) + .output() + { + let bus_str = String::from_utf8_lossy(&bus_out.stdout); + + // Parse endurance remaining (attribute 232) + if let Some(pos) = bus_str.find("\"endurance-remaining\"") { + let snippet = &bus_str[pos..std::cmp::min(pos + 100, bus_str.len())]; + let parts: Vec<&str> = snippet.split_whitespace().collect(); + if let Some(val_str) = parts.iter().skip(5).find(|s| s.parse::().is_ok()) { + if let Ok(val) = val_str.parse::() { + data.health_percent = Some(val.min(100) as u8); + data.wear_percent = Some(100 - val.min(100) as u8); + } + } + } + + // Attribute 231 "ssd-life-left" + if data.health_percent.is_none() { + if let Some(pos) = bus_str.find("\"ssd-life-left\"") { + let snippet = &bus_str[pos..std::cmp::min(pos + 100, bus_str.len())]; + let parts: Vec<&str> = snippet.split_whitespace().collect(); + if let Some(val_str) = parts.iter().skip(5).find(|s| s.parse::().is_ok()) { + if let Ok(val) = val_str.parse::() { + data.health_percent = Some(val.min(100) as u8); + data.wear_percent = Some(100 - val.min(100) as u8); + } + } + } + } + + // Power cycle count (attribute 12) + if let Some(pos) = bus_str.find("\"power-cycle-count\"") { + let snippet = &bus_str[pos..std::cmp::min(pos + 80, bus_str.len())]; + for token in snippet.split_whitespace().skip(5) { + if let Ok(cyc) = token.parse::() { + if cyc > 0 && cyc < 1_000_000 { + data.power_cycle_count = Some(cyc); + break; + } + } + } + } + + // Total LBAs written (attribute 241) + if let Some(pos) = bus_str.find("\"total-lbas-written\"") { + let snippet = &bus_str[pos..std::cmp::min(pos + 80, bus_str.len())]; + let is_ssd = data.rotational_speed_rpm == Some(0); + for token in snippet.split_whitespace().skip(5) { + if let Ok(lba) = token.parse::() { + if lba > 1000 { + data.total_written_tb = Some(Self::parse_tbw_from_raw(lba, is_ssd)); + break; + } + } + } + } + } + + // If health wasn't explicitly found in attributes but drive is healthy: + if data.health_percent.is_none() && data.smart_status == "PASSED" { + let bad = data.bad_sectors_count.unwrap_or(0); + if bad == 0 { + data.health_percent = Some(100); + data.wear_percent = Some(0); + } else { + let h = 100u8.saturating_sub(bad.min(100) as u8); + data.health_percent = Some(h); + data.wear_percent = Some(100 - h); + } + } + + drive_blocks.insert(drive_id, data); + } + } + + for (dev, drv_id) in block_to_drive { + if let Some(data) = drive_blocks.get(&drv_id) { + map.insert(dev, data.clone()); + } + } + + map + } + + fn scan_disks() -> Vec { + let mut disks = Vec::new(); + let smart_map = Self::collect_smart_map(); + + // 1. Primary: Use lsblk for full disk & partition topology + if let Ok(lsblk_out) = Command::new("lsblk") + .args(["-b", "-J", "-o", "NAME,PATH,SIZE,TYPE,MOUNTPOINTS,FSTYPE,MODEL,ROTA"]) + .output() + { + if let Ok(json) = serde_json::from_slice::(&lsblk_out.stdout) { + if let Some(devices) = json.get("blockdevices").and_then(|v| v.as_array()) { + for dev in devices { + let dev_type = dev.get("type").and_then(|v| v.as_str()).unwrap_or(""); + if dev_type != "disk" { + continue; + } + let name = dev.get("name").and_then(|v| v.as_str()).unwrap_or(""); + if name.starts_with("loop") + || name.starts_with("ram") + || name.starts_with("zram") + || name.starts_with("sr") + { + continue; + } + + let path = dev + .get("path") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) + .unwrap_or_else(|| format!("/dev/{}", name)); + + let size_bytes = dev.get("size").and_then(|v| v.as_u64()).unwrap_or(0); + if size_bytes == 0 { + continue; + } + + let model = dev + .get("model") + .and_then(|v| v.as_str()) + .unwrap_or(name) + .trim() + .to_string(); + + let rota = dev.get("rota").and_then(|v| v.as_bool()).unwrap_or(true); + let smart = smart_map.get(&path).cloned().unwrap_or_default(); + + let disk_type = if name.starts_with("nvme") { + "NVMe SSD".to_string() + } else if !rota || smart.rotational_speed_rpm == Some(0) { + "SATA SSD".to_string() + } else { + "HDD".to_string() + }; + + // Parse partitions + let mut partitions = Vec::new(); + if let Some(children) = dev.get("children").and_then(|v| v.as_array()) { + for child in children { + let part_name = child.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(); + let part_path = child.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string(); + let part_size = child.get("size").and_then(|v| v.as_u64()).unwrap_or(0); + let fs_type = child.get("fstype").and_then(|v| v.as_str()).unwrap_or("").to_string(); + let mount_points = child.get("mountpoints").and_then(|v| v.as_array()); + + let mount_str = mount_points.map(|arr| { + arr.iter() + .filter_map(|x| x.as_str()) + .collect::>() + .join(", ") + }); + let mount_point = if let Some(ref m) = mount_str { + if m.trim().is_empty() { + None + } else { + Some(m.clone()) + } + } else { + None + }; + + let first_mount = mount_points.and_then(|arr| arr.first()).and_then(|v| v.as_str()); + let mut used_bytes = 0; + if let Some(m) = first_mount { + let (_, used) = Self::get_fs_usage(m); + used_bytes = used; + } + + partitions.push(PartitionInfo { + name: part_name, + path: part_path, + mount_point, + fs_type, + size_bytes: part_size, + used_bytes, + }); + } + } + + disks.push(DiskInfo { + name: path, + model, + serial: smart.serial, + size_bytes, + disk_type, + rotational_speed_rpm: smart.rotational_speed_rpm, + smart_status: smart.smart_status, + health_percent: smart.health_percent, + wear_percent: smart.wear_percent, + nvme_wear_percent: smart.wear_percent, + temperature_c: smart.temperature_c, + power_on_hours: smart.power_on_hours, + power_cycle_count: smart.power_cycle_count, + bad_sectors_count: smart.bad_sectors_count, + total_written_tb: smart.total_written_tb, + partitions, + }); + } + } + } + } + + // 2. Fallback if lsblk was not available or produced 0 disks + if disks.is_empty() { + let block_dir = Path::new("/sys/block"); + if let Ok(entries) = std::fs::read_dir(block_dir) { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if name.starts_with("loop") + || name.starts_with("ram") + || name.starts_with("zram") + || name.starts_with("sr") + { + continue; + } + + let path = entry.path(); + let size_sectors = std::fs::read_to_string(path.join("size")) + .ok() + .and_then(|s| s.trim().parse::().ok()) + .unwrap_or(0); + let size_bytes = size_sectors * 512; + if size_bytes == 0 { + continue; + } + + let model = std::fs::read_to_string(path.join("device/model")) + .or_else(|_| std::fs::read_to_string(path.join("model"))) + .unwrap_or_else(|_| name.clone()) + .trim() + .to_string(); + + let rotational = std::fs::read_to_string(path.join("queue/rotational")) + .ok() + .and_then(|s| s.trim().parse::().ok()) + .unwrap_or(1); + + let disk_type = if name.starts_with("nvme") { + "NVMe SSD".to_string() + } else if rotational == 0 { + "SATA SSD".to_string() + } else { + "HDD".to_string() + }; + + let dev_path = format!("/dev/{}", name); + let smart = smart_map.get(&dev_path).cloned().unwrap_or_default(); + + disks.push(DiskInfo { + name: dev_path, + model, + serial: smart.serial, + size_bytes, + disk_type, + rotational_speed_rpm: smart.rotational_speed_rpm, + smart_status: smart.smart_status, + health_percent: smart.health_percent, + wear_percent: smart.wear_percent, + nvme_wear_percent: smart.wear_percent, + temperature_c: smart.temperature_c, + power_on_hours: smart.power_on_hours, + power_cycle_count: smart.power_cycle_count, + bad_sectors_count: smart.bad_sectors_count, + total_written_tb: smart.total_written_tb, + partitions: Vec::new(), + }); + } + } + } + + // 3. macOS fallback via system_profiler + #[cfg(target_os = "macos")] + if disks.is_empty() { + if let Ok(output) = Command::new("system_profiler").args(["SPStorageDataType", "-json"]).output() { + if let Ok(json) = serde_json::from_slice::(&output.stdout) { + if let Some(arr) = json.get("SPStorageDataType").and_then(|v| v.as_array()) { + for item in arr { + let name = item.get("_name").and_then(|v| v.as_str()).unwrap_or("Macintosh HD").to_string(); + let size = item.get("size_in_bytes").and_then(|v| v.as_u64()).unwrap_or(0); + let free = item.get("free_space_in_bytes").and_then(|v| v.as_u64()).unwrap_or(0); + let fs = item.get("file_system").and_then(|v| v.as_str()).unwrap_or("APFS").to_string(); + let mount = item.get("mount_point").and_then(|v| v.as_str()).map(|s| s.to_string()); + let bsd_name = item.get("bsd_name").and_then(|v| v.as_str()).unwrap_or("disk1s1").to_string(); + let used_bytes = if size >= free { size - free } else { 0 }; + let partitions = vec![PartitionInfo { + name: bsd_name.clone(), + path: format!("/dev/{}", bsd_name), + mount_point: mount, + fs_type: fs, + size_bytes: size, + used_bytes, + }]; + disks.push(DiskInfo { + name: bsd_name, + path: format!("/dev/{}", name), + model: name, + serial: String::new(), + size_bytes: size, + disk_type: "Apple SSD".to_string(), + rotational_speed_rpm: Some(0), + smart_status: "PASSED".to_string(), + health_percent: Some(100), + wear_percent: Some(0), + nvme_wear_percent: Some(0), + temperature_c: None, + power_on_hours: None, + power_cycle_count: None, + bad_sectors_count: Some(0), + total_written_tb: None, + partitions, + }); + } + } + } + } + } + + // 4. Windows fallback via PowerShell Get-PhysicalDisk + #[cfg(target_os = "windows")] + if disks.is_empty() { + let ps_cmd = "Get-PhysicalDisk | Select-Object DeviceId, FriendlyName, MediaType, Size, OperationalStatus, HealthStatus | ConvertTo-Json -Compress"; + if let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]).output() { + if let Ok(val) = serde_json::from_str::(&String::from_utf8_lossy(&output.stdout)) { + let items = match val { + serde_json::Value::Array(a) => a, + serde_json::Value::Object(_) => vec![val], + _ => vec![], + }; + for item in items { + let dev_id = item["DeviceId"].as_str().unwrap_or("0"); + let name = item["FriendlyName"].as_str().unwrap_or("PhysicalDrive").to_string(); + let media = item["MediaType"].as_str().unwrap_or("SSD").to_string(); + let size = item["Size"].as_u64().unwrap_or(0); + let health = item["HealthStatus"].as_str().unwrap_or("Healthy"); + let smart_status = if health.eq_ignore_ascii_case("Healthy") { "PASSED" } else { "WARNING" }; + + disks.push(DiskInfo { + name: format!("Disk {}", dev_id), + path: format!(r"\\.\PhysicalDrive{}", dev_id), + model: name, + serial: String::new(), + size_bytes: size, + disk_type: media, + rotational_speed_rpm: None, + smart_status: smart_status.to_string(), + health_percent: Some(100), + wear_percent: Some(0), + nvme_wear_percent: Some(0), + temperature_c: None, + power_on_hours: None, + power_cycle_count: None, + bad_sectors_count: Some(0), + total_written_tb: None, + partitions: Vec::new(), + }); + } + } + } + } + + disks + } + + // --- NETWORK ADAPTERS SCANNING --- + fn scan_network() -> Vec { + let mut adapters = Vec::new(); + let net_dir = Path::new("/sys/class/net"); + + if let Ok(entries) = std::fs::read_dir(net_dir) { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if name == "lo" { + continue; + } + + let path = entry.path(); + let mac = std::fs::read_to_string(path.join("address")) + .unwrap_or_default() + .trim() + .to_string(); + + let operstate = std::fs::read_to_string(path.join("operstate")) + .unwrap_or_else(|_| "unknown".to_string()) + .trim() + .to_ascii_uppercase(); + + let speed_mbps = std::fs::read_to_string(path.join("speed")) + .ok() + .and_then(|s| s.trim().parse::().ok()) + .and_then(|s| if s > 0 { Some(s as u32) } else { None }); + + let is_wifi = path.join("wireless").exists() + || std::fs::read_to_string(path.join("uevent")) + .map(|u| u.contains("DEVTYPE=wlan")) + .unwrap_or(false); + + let if_type = if is_wifi { + "Wi-Fi".to_string() + } else if path.join("device").exists() { + "Ethernet".to_string() + } else { + "Virtual / Bridge".to_string() + }; + + let driver = std::fs::read_link(path.join("device/driver")) + .ok() + .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string())) + .unwrap_or_else(|| "virtual".to_string()); + + adapters.push(NetworkAdapterInfo { + interface_name: name, + if_type, + state: operstate, + speed_mbps, + mac_address: mac, + driver, + }); + } + } + + #[cfg(target_os = "macos")] + if adapters.is_empty() { + if let Ok(output) = Command::new("networksetup").args(["-listallhardwareports"]).output() { + let text = String::from_utf8_lossy(&output.stdout); + let mut cur_port = String::new(); + let mut cur_dev = String::new(); + for line in text.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("Hardware Port:") { + cur_port = trimmed["Hardware Port:".len()..].trim().to_string(); + } else if trimmed.starts_with("Device:") { + cur_dev = trimmed["Device:".len()..].trim().to_string(); + } else if trimmed.starts_with("Ethernet Address:") { + let mac = trimmed["Ethernet Address:".len()..].trim().to_string(); + let if_type = if cur_port.contains("Wi-Fi") { "Wi-Fi".to_string() } else { "Ethernet".to_string() }; + adapters.push(NetworkAdapterInfo { + interface_name: cur_dev.clone(), + if_type, + state: "UP".to_string(), + speed_mbps: None, + mac_address: mac, + driver: "Apple Native".to_string(), + }); + } + } + } + } + + #[cfg(target_os = "windows")] + if adapters.is_empty() { + let ps_cmd = "Get-NetAdapter | Select-Object Name, InterfaceDescription, Status, LinkSpeed, MacAddress | ConvertTo-Json -Compress"; + if let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]).output() { + if let Ok(val) = serde_json::from_str::(&String::from_utf8_lossy(&output.stdout)) { + let items = match val { + serde_json::Value::Array(a) => a, + serde_json::Value::Object(_) => vec![val], + _ => vec![], + }; + for item in items { + let name = item["Name"].as_str().unwrap_or("Ethernet").to_string(); + let desc = item["InterfaceDescription"].as_str().unwrap_or("Network Adapter").to_string(); + let status = item["Status"].as_str().unwrap_or("Up").to_ascii_uppercase(); + let mac = item["MacAddress"].as_str().unwrap_or("").to_string(); + let if_type = if desc.contains("Wireless") || desc.contains("Wi-Fi") || name.contains("Wi-Fi") { + "Wi-Fi".to_string() + } else { + "Ethernet".to_string() + }; + adapters.push(NetworkAdapterInfo { + interface_name: name, + if_type, + state: status, + speed_mbps: None, + mac_address: mac, + driver: desc, + }); + } + } + } + } + + adapters + } +} + +fn read_dmi_field(dir: &Path, file_name: &str) -> Option { + std::fs::read_to_string(dir.join(file_name)) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty() && s != "None" && s != "Default string") +} + +fn decode_chassis_type(code: &str) -> String { + match code { + "8" | "9" | "10" | "14" => "Laptop / Notebook".to_string(), + "3" | "4" | "6" | "7" | "13" => "Desktop / Workstation".to_string(), + "17" | "23" | "28" => "Server".to_string(), + "11" => "Handheld / Mobile".to_string(), + "30" | "31" => "Tablet / Convertible".to_string(), + other if !other.is_empty() => format!("Chassis #{}", other), + _ => "Standard Chassis".to_string(), + } +} diff --git a/crates/core/src/scanner/init/bsd_rc.rs b/crates/core/src/scanner/init/bsd_rc.rs new file mode 100644 index 0000000..55563ef --- /dev/null +++ b/crates/core/src/scanner/init/bsd_rc.rs @@ -0,0 +1,59 @@ +use super::provider::{InitSystemProvider, ScanError}; +use crate::models::FailedService; +use std::process::Command; + +pub struct BsdRcProvider; + +impl BsdRcProvider { + pub fn new() -> Self { + Self + } +} + +impl Default for BsdRcProvider { + fn default() -> Self { + Self::new() + } +} + +impl InitSystemProvider for BsdRcProvider { + fn name(&self) -> &'static str { + "bsd-rc" + } + + fn is_active(&self) -> bool { + #[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] + { + true + } + #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))] + { + false + } + } + + fn get_failed_services(&self) -> Result, ScanError> { + let mut failed = Vec::new(); + + // 1. OpenBSD rcctl + if let Ok(output) = Command::new("rcctl").args(["ls", "failed"]).output() { + let stdout = String::from_utf8_lossy(&output.stdout); + for line in stdout.lines() { + let trimmed = line.trim(); + if !trimmed.is_empty() { + failed.push(FailedService { + name: trimmed.to_string(), + init_system: "bsd-rc".to_string(), + state: "failed".to_string(), + description: format!("Daemon {} failed in OpenBSD rcctl", trimmed), + logs: "Check /var/log/messages or /var/log/daemon".to_string(), + restart_command: format!("sudo rcctl restart {0} && rcctl check {0}", trimmed), + status_command: format!("rcctl check {0}", trimmed), + }); + } + } + } + + Ok(failed) + } +} diff --git a/crates/core/src/scanner/init/launchd.rs b/crates/core/src/scanner/init/launchd.rs new file mode 100644 index 0000000..c7080f8 --- /dev/null +++ b/crates/core/src/scanner/init/launchd.rs @@ -0,0 +1,91 @@ +use super::provider::{InitSystemProvider, ScanError}; +use crate::models::FailedService; +use std::process::Command; + +pub struct LaunchdProvider; + +impl LaunchdProvider { + pub fn new() -> Self { + Self + } +} + +impl Default for LaunchdProvider { + fn default() -> Self { + Self::new() + } +} + +impl InitSystemProvider for LaunchdProvider { + fn name(&self) -> &'static str { + "launchd" + } + + fn is_active(&self) -> bool { + #[cfg(target_os = "macos")] + { + true + } + #[cfg(not(target_os = "macos"))] + { + false + } + } + + fn get_failed_services(&self) -> Result, ScanError> { + let mut failed = Vec::new(); + + // 1. Опрос списка служб launchctl list + if let Ok(output) = Command::new("launchctl").arg("list").output() { + let stdout = String::from_utf8_lossy(&output.stdout); + for line in stdout.lines().skip(1) { + // Строка имеет вид: PID \t Status \t Label + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() >= 3 { + let pid_str = parts[0]; + let status_str = parts[1]; + let label = parts[2]; + + // Игнорируем стандартные успешные статусы (0) + if let Ok(exit_code) = status_str.parse::() { + if exit_code != 0 && exit_code != -9 && exit_code != -15 { + // Получаем короткий журнал сбоя через `log show` + let logs = Self::collect_logs(label); + + failed.push(FailedService { + name: label.to_string(), + init_system: "launchd".to_string(), + state: format!("exit({}) PID: {}", exit_code, pid_str), + description: format!("Служба launchd завершилась с кодом ошибки {}", exit_code), + logs, + restart_command: format!("launchctl kickstart -k gui/$(id -u)/{0} || sudo launchctl kickstart -k system/{0}", label), + status_command: format!("launchctl print gui/$(id -u)/{0} || launchctl print system/{0}", label), + }); + } + } + } + } + } + + Ok(failed) + } +} + +impl LaunchdProvider { + fn collect_logs(label: &str) -> String { + let predicate = format!("subsystem contains \"{}\" OR process contains \"{}\"", label, label); + if let Ok(output) = Command::new("log") + .args(["show", "--predicate", &predicate, "--last", "15m", "--style", "compact"]) + .output() + { + let text = String::from_utf8_lossy(&output.stdout); + if !text.trim().is_empty() { + let lines: Vec<&str> = text.lines().rev().take(30).collect(); + let mut rev_lines = lines; + rev_lines.reverse(); + return rev_lines.join("\n"); + } + } + format!("Записи о падении {} в unified log отсутствуют.", label) + } +} diff --git a/crates/core/src/scanner/init/mod.rs b/crates/core/src/scanner/init/mod.rs new file mode 100644 index 0000000..c8de2b0 --- /dev/null +++ b/crates/core/src/scanner/init/mod.rs @@ -0,0 +1,73 @@ +pub mod provider; +pub mod systemd; +pub mod openrc; +pub mod runit; +pub mod bsd_rc; +pub mod launchd; +pub mod windows_scm; + +pub use provider::{InitSystemProvider, ScanError}; +pub use systemd::SystemdProvider; +pub use openrc::OpenRcProvider; +pub use runit::RunitProvider; +pub use bsd_rc::BsdRcProvider; +pub use launchd::LaunchdProvider; +pub use windows_scm::WindowsScmProvider; + +/// Автоматически определяет активную систему инициализации в текущем окружении +pub fn detect_init_system() -> Box { + // 1. macOS launchd + let launchd = LaunchdProvider::new(); + if launchd.is_active() { + return Box::new(launchd); + } + + // 2. Windows SCM + let win_scm = WindowsScmProvider::new(); + if win_scm.is_active() { + return Box::new(win_scm); + } + + // 3. systemd + let systemd = SystemdProvider::new(); + if systemd.is_active() { + return Box::new(systemd); + } + + // 4. OpenRC + let openrc = OpenRcProvider::new(); + if openrc.is_active() { + return Box::new(openrc); + } + + // 5. runit + let runit = RunitProvider::new(); + if runit.is_active() { + return Box::new(runit); + } + + // 6. BSD rc + let bsd = BsdRcProvider::new(); + if bsd.is_active() { + return Box::new(bsd); + } + + // Fallback: если ничего явно не определилось + #[cfg(target_os = "windows")] + return Box::new(WindowsScmProvider::new()); + #[cfg(target_os = "macos")] + return Box::new(LaunchdProvider::new()); + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + Box::new(SystemdProvider::new()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_detect_init_system() { + let init = detect_init_system(); + assert!(!init.name().is_empty()); + } +} diff --git a/crates/core/src/scanner/init/openrc.rs b/crates/core/src/scanner/init/openrc.rs new file mode 100644 index 0000000..2998251 --- /dev/null +++ b/crates/core/src/scanner/init/openrc.rs @@ -0,0 +1,83 @@ +use super::provider::{InitSystemProvider, ScanError}; +use crate::models::FailedService; +use std::path::Path; +use std::process::Command; + +pub struct OpenRcProvider; + +impl OpenRcProvider { + pub fn new() -> Self { + Self + } +} + +impl Default for OpenRcProvider { + fn default() -> Self { + Self::new() + } +} + +impl InitSystemProvider for OpenRcProvider { + fn name(&self) -> &'static str { + "openrc" + } + + fn is_active(&self) -> bool { + if Path::new("/run/openrc").exists() || Path::new("/etc/init.d").exists() && Path::new("/sbin/rc-status").exists() { + return true; + } + if let Ok(comm) = std::fs::read_to_string("/proc/1/comm") { + if comm.trim() == "openrc-init" { + return true; + } + } + false + } + + fn get_failed_services(&self) -> Result, ScanError> { + // Опрос crashed сервисов через rc-status -c + let output = Command::new("rc-status") + .args(["-c"]) + .output() + .or_else(|_| Command::new("rc-status").args(["-s"]).output()) + .map_err(|e| ScanError::CommandFailed(e.to_string()))?; + + let stdout = String::from_utf8_lossy(&output.stdout); + let mut failed = Vec::new(); + + for line in stdout.lines() { + let line_trimmed = line.trim(); + if line_trimmed.contains("crashed") || line_trimmed.contains("failed") || line_trimmed.contains("broken") { + let parts: Vec<&str> = line_trimmed.split_whitespace().collect(); + if let Some(service) = parts.first() { + let svc_name = service.to_string(); + + // Читаем логи из /var/log/rc.log или syslog + let logs = std::fs::read_to_string("/var/log/rc.log") + .unwrap_or_default() + .lines() + .rev() + .filter(|l| l.contains(&svc_name)) + .take(30) + .collect::>() + .into_iter() + .rev() + .collect::>() + .join("\n"); + + failed.push(FailedService { + name: svc_name.clone(), + init_system: "openrc".to_string(), + state: "crashed".to_string(), + description: format!("Service {} crashed under OpenRC supervision", svc_name), + logs: if logs.is_empty() { "No entries in /var/log/rc.log".to_string() } else { logs }, + restart_command: format!("sudo rc-service {0} restart && sudo rc-service {0} status", svc_name), + status_command: format!("rc-service {0} status", svc_name), + }); + } + } + } + + Ok(failed) + } +} diff --git a/crates/core/src/scanner/init/provider.rs b/crates/core/src/scanner/init/provider.rs new file mode 100644 index 0000000..6ec8dde --- /dev/null +++ b/crates/core/src/scanner/init/provider.rs @@ -0,0 +1,35 @@ +use crate::models::FailedService; +use std::fmt; + +#[derive(Debug, Clone)] +pub enum ScanError { + CommandFailed(String), + PermissionDenied(String), + Io(String), + NotSupported(String), +} + +impl fmt::Display for ScanError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ScanError::CommandFailed(e) => write!(f, "Init command error: {}", e), + ScanError::PermissionDenied(e) => write!(f, "Permission denied: {}", e), + ScanError::Io(e) => write!(f, "I/O error: {}", e), + ScanError::NotSupported(e) => write!(f, "Init system not supported: {}", e), + } + } +} + +impl std::error::Error for ScanError {} + +/// Единый трейт для взаимодействия с системами инициализации ОС +pub trait InitSystemProvider: Send + Sync { + /// Имя системы инициализации (systemd, openrc, runit, s6, dinit, bsd-rc) + fn name(&self) -> &'static str; + + /// Проверка, активна ли данная система инициализации в текущем окружении + fn is_active(&self) -> bool; + + /// Получение списка упавших или аварийно завершенных служб + fn get_failed_services(&self) -> Result, ScanError>; +} diff --git a/crates/core/src/scanner/init/runit.rs b/crates/core/src/scanner/init/runit.rs new file mode 100644 index 0000000..3e4519f --- /dev/null +++ b/crates/core/src/scanner/init/runit.rs @@ -0,0 +1,87 @@ +use super::provider::{InitSystemProvider, ScanError}; +use crate::models::FailedService; +use std::path::Path; +use std::process::Command; + +pub struct RunitProvider; + +impl RunitProvider { + pub fn new() -> Self { + Self + } +} + +impl Default for RunitProvider { + fn default() -> Self { + Self::new() + } +} + +impl InitSystemProvider for RunitProvider { + fn name(&self) -> &'static str { + "runit" + } + + fn is_active(&self) -> bool { + if Path::new("/run/runit").exists() || Path::new("/var/service").exists() && Path::new("/usr/bin/sv").exists() { + return true; + } + if let Ok(comm) = std::fs::read_to_string("/proc/1/comm") { + if comm.trim() == "runit" || comm.trim() == "runit-init" { + return true; + } + } + false + } + + fn get_failed_services(&self) -> Result, ScanError> { + let output = Command::new("sh") + .args(["-c", "sv status /var/service/* 2>&1"]) + .output() + .map_err(|e| ScanError::CommandFailed(e.to_string()))?; + + let stdout = String::from_utf8_lossy(&output.stdout); + let mut failed = Vec::new(); + + for line in stdout.lines() { + let line_trimmed = line.trim(); + // runit выводит: "down: /var/service/sshd: 0s, normally up, want up" или "fail: ..." + if line_trimmed.starts_with("down:") || line_trimmed.starts_with("fail:") { + let parts: Vec<&str> = line_trimmed.split_whitespace().collect(); + if parts.len() >= 2 { + let full_path = parts[1].trim_end_matches(':'); + let svc_name = Path::new(full_path) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(full_path) + .to_string(); + + // Читаем логи svlogd: /var/log//current + let log_path = format!("/var/log/{}/current", svc_name); + let logs = std::fs::read_to_string(&log_path) + .unwrap_or_default() + .lines() + .rev() + .take(30) + .collect::>() + .into_iter() + .rev() + .collect::>() + .join("\n"); + + failed.push(FailedService { + name: svc_name.clone(), + init_system: "runit".to_string(), + state: "down/failed".to_string(), + description: format!("Service {} is down or failed in runit", svc_name), + logs: if logs.is_empty() { format!("No svlogd logs at {}", log_path) } else { logs }, + restart_command: format!("sudo sv restart {0} && sv status {0}", svc_name), + status_command: format!("sv status {0}", svc_name), + }); + } + } + } + + Ok(failed) + } +} diff --git a/crates/core/src/scanner/init/systemd.rs b/crates/core/src/scanner/init/systemd.rs new file mode 100644 index 0000000..ea8c5e8 --- /dev/null +++ b/crates/core/src/scanner/init/systemd.rs @@ -0,0 +1,84 @@ +use super::provider::{InitSystemProvider, ScanError}; +use crate::models::FailedService; +use std::path::Path; +use std::process::Command; + +pub struct SystemdProvider; + +impl SystemdProvider { + pub fn new() -> Self { + Self + } +} + +impl Default for SystemdProvider { + fn default() -> Self { + Self::new() + } +} + +impl InitSystemProvider for SystemdProvider { + fn name(&self) -> &'static str { + "systemd" + } + + fn is_active(&self) -> bool { + // 1. Проверка /run/systemd/system + if Path::new("/run/systemd/system").exists() { + return true; + } + // 2. Проверка /proc/1/comm == "systemd" + if let Ok(comm) = std::fs::read_to_string("/proc/1/comm") { + if comm.trim() == "systemd" { + return true; + } + } + false + } + + fn get_failed_services(&self) -> Result, ScanError> { + let output = Command::new("systemctl") + .args(["--failed", "--all", "--no-legend", "--plain"]) + .output() + .map_err(|e| ScanError::CommandFailed(e.to_string()))?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + if stderr.contains("Access denied") || stderr.contains("Permission denied") { + return Err(ScanError::PermissionDenied(stderr.to_string())); + } + return Err(ScanError::CommandFailed(stderr.to_string())); + } + + let stdout = String::from_utf8_lossy(&output.stdout); + let mut failed = Vec::new(); + + for line in stdout.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.is_empty() { + continue; + } + let unit = parts[0].to_string(); + + // Читаем журнал юнита: journalctl -u -b -n 40 --no-pager + let logs = crate::auth::PrivilegeManager::exec_privileged( + "journalctl", + &["-u", &unit, "-b", "-n", "40", "--no-pager"], + ) + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_default(); + + failed.push(FailedService { + name: unit.clone(), + init_system: "systemd".to_string(), + state: "failed".to_string(), + description: format!("Unit {} is in failed state in systemd", unit), + logs, + restart_command: format!("sudo systemctl restart {0} && systemctl status {0}", unit), + status_command: format!("systemctl status {0} -l", unit), + }); + } + + Ok(failed) + } +} diff --git a/crates/core/src/scanner/init/windows_scm.rs b/crates/core/src/scanner/init/windows_scm.rs new file mode 100644 index 0000000..5fd176f --- /dev/null +++ b/crates/core/src/scanner/init/windows_scm.rs @@ -0,0 +1,95 @@ +use super::provider::{InitSystemProvider, ScanError}; +use crate::models::FailedService; +use std::process::Command; + +pub struct WindowsScmProvider; + +impl WindowsScmProvider { + pub fn new() -> Self { + Self + } +} + +impl Default for WindowsScmProvider { + fn default() -> Self { + Self::new() + } +} + +impl InitSystemProvider for WindowsScmProvider { + fn name(&self) -> &'static str { + "windows-scm" + } + + fn is_active(&self) -> bool { + #[cfg(target_os = "windows")] + { + true + } + #[cfg(not(target_os = "windows"))] + { + false + } + } + + fn get_failed_services(&self) -> Result, ScanError> { + let mut failed = Vec::new(); + + // 1. Поиск служб Windows с автоматическим запуском, находящихся в остановленном состоянии + let ps_cmd = "Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -ne 'Running' } | Select-Object Name, DisplayName, State, ExitCode | ConvertTo-Json -Compress"; + + if let Ok(output) = Command::new("powershell") + .args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]) + .output() + { + let stdout = String::from_utf8_lossy(&output.stdout); + if let Ok(val) = serde_json::from_str::(&stdout) { + let items = match val { + serde_json::Value::Array(arr) => arr, + serde_json::Value::Object(_) => vec![val], + _ => vec![], + }; + + for item in items { + let name = item["Name"].as_str().unwrap_or("Unknown").to_string(); + let display_name = item["DisplayName"].as_str().unwrap_or(&name).to_string(); + let state = item["State"].as_str().unwrap_or("Stopped").to_string(); + let exit_code = item["ExitCode"].as_i64().unwrap_or(0); + + let logs = Self::collect_event_logs(&name); + + failed.push(FailedService { + name: name.clone(), + init_system: "windows-scm".to_string(), + state: format!("{} (ExitCode: {})", state, exit_code), + description: format!("Служба Windows '{}' ({}) не запущена", display_name, name), + logs, + restart_command: format!("Start-Service -Name '{}'", name), + status_command: format!("Get-Service -Name '{}'", name), + }); + } + } + } + + Ok(failed) + } +} + +impl WindowsScmProvider { + fn collect_event_logs(service_name: &str) -> String { + let ps_cmd = format!( + "Get-WinEvent -FilterHashtable @{{LogName='System'; ProviderName='Service Control Manager'}} -MaxEvents 5 -ErrorAction SilentlyContinue | Where-Object {{ $_.Message -like '*{}*' }} | ForEach-Object {{ $_.TimeCreated.ToString('s') + ' ' + $_.Message }}", + service_name + ); + if let Ok(output) = Command::new("powershell") + .args(["-NoProfile", "-NonInteractive", "-Command", &ps_cmd]) + .output() + { + let text = String::from_utf8_lossy(&output.stdout); + if !text.trim().is_empty() { + return text.trim().to_string(); + } + } + format!("События сбоя службы {} в журнале System Event Log не найдены.", service_name) + } +} diff --git a/crates/core/src/scanner/kernel.rs b/crates/core/src/scanner/kernel.rs new file mode 100644 index 0000000..40edd68 --- /dev/null +++ b/crates/core/src/scanner/kernel.rs @@ -0,0 +1,111 @@ + +#[derive(Debug, Clone, Default)] +pub struct KernelScanResult { + pub raw_logs: String, + pub oom_events: Vec, + pub gpu_hangs: Vec, + pub io_errors: Vec, + pub csum_errors: Vec, + pub tainted_value: u64, + pub tainted_flags: Vec, + pub permission_denied: bool, +} + +pub struct KernelScanner; + +impl KernelScanner { + pub fn scan() -> KernelScanResult { + let mut result = KernelScanResult::default(); + + // 1. Читаем /proc/sys/kernel/tainted + if let Ok(tainted_str) = std::fs::read_to_string("/proc/sys/kernel/tainted") { + if let Ok(val) = tainted_str.trim().parse::() { + result.tainted_value = val; + result.tainted_flags = Self::decode_tainted(val); + } + } + + // 2. Читаем dmesg / /dev/kmsg + let dmesg_out = crate::auth::PrivilegeManager::exec_privileged("dmesg", &["--level=err,crit,alert,emerg"]) + .or_else(|_| crate::auth::PrivilegeManager::exec_privileged("dmesg", &[])); + + let logs = match dmesg_out { + Ok(output) => { + if !output.status.success() { + let err = String::from_utf8_lossy(&output.stderr); + if err.contains("Operation not permitted") || err.contains("Permission denied") { + result.permission_denied = true; + } + String::new() + } else { + String::from_utf8_lossy(&output.stdout).to_string() + } + } + Err(_) => { + // Попытка прямого чтения /dev/kmsg + match std::fs::read_to_string("/dev/kmsg") { + Ok(kmsg) => kmsg, + Err(e) => { + if e.kind() == std::io::ErrorKind::PermissionDenied { + result.permission_denied = true; + } + String::new() + } + } + } + }; + + result.raw_logs = logs.clone(); + + // 3. Парсинг критических паттернов + for line in logs.lines() { + let lower = line.to_lowercase(); + + // OOM-Killer + if lower.contains("out of memory") || lower.contains("oom-killer") || lower.contains("invoked oom-killer") { + result.oom_events.push(line.to_string()); + } + + // GPU Hangs (NVIDIA Xid, AMDGPU reset, Intel i915 hang) + if line.contains("NVRM: Xid") || lower.contains("amdgpu reset") || lower.contains("gpu hang") || lower.contains("drm/i915: reset") { + result.gpu_hangs.push(line.to_string()); + } + + // I/O Errors + if lower.contains("i/o error") || lower.contains("blk_update_request") || lower.contains("ext4-fs error") || lower.contains("btrfs: error") { + result.io_errors.push(line.to_string()); + } + + // Checksum errors (Btrfs / ZFS csum) + if lower.contains("checksum error") || lower.contains("csum failed") || lower.contains("checksum mismatch") { + result.csum_errors.push(line.to_string()); + } + } + + result + } + + /// Декодирует флаги /proc/sys/kernel/tainted + pub fn decode_tainted(val: u64) -> Vec { + let mut flags = Vec::new(); + if val & (1 << 0) != 0 { flags.push("P: Proprietary module loaded".to_string()); } + if val & (1 << 1) != 0 { flags.push("F: Module force loaded".to_string()); } + if val & (1 << 2) != 0 { flags.push("S: SMP with CPUs not designed for SMP".to_string()); } + if val & (1 << 3) != 0 { flags.push("R: Module force unloaded".to_string()); } + if val & (1 << 4) != 0 { flags.push("M: Machine Check Exception occurred".to_string()); } + if val & (1 << 5) != 0 { flags.push("B: Bad page referenced".to_string()); } + if val & (1 << 6) != 0 { flags.push("U: User requested taint".to_string()); } + if val & (1 << 7) != 0 { flags.push("D: Kernel died / oops".to_string()); } + if val & (1 << 8) != 0 { flags.push("A: ACPI table overridden".to_string()); } + if val & (1 << 9) != 0 { flags.push("W: Kernel warning issued".to_string()); } + if val & (1 << 10) != 0 { flags.push("C: Staging driver loaded".to_string()); } + if val & (1 << 11) != 0 { flags.push("I: Firmware workaround active".to_string()); } + if val & (1 << 12) != 0 { flags.push("O: External out-of-tree module loaded".to_string()); } + if val & (1 << 13) != 0 { flags.push("E: Unsigned module loaded".to_string()); } + if val & (1 << 14) != 0 { flags.push("L: Soft lockup occurred".to_string()); } + if val & (1 << 15) != 0 { flags.push("K: Kernel livepatched".to_string()); } + if val & (1 << 16) != 0 { flags.push("X: Auxiliary taint".to_string()); } + if val & (1 << 17) != 0 { flags.push("T: Built with struct layout randomization".to_string()); } + flags + } +} diff --git a/crates/core/src/scanner/limits.rs b/crates/core/src/scanner/limits.rs new file mode 100644 index 0000000..adbd67f --- /dev/null +++ b/crates/core/src/scanner/limits.rs @@ -0,0 +1,59 @@ +use std::process::Command; + +#[derive(Debug, Clone, Default)] +pub struct SystemLimitsResult { + pub max_user_watches: u64, + pub file_nr_allocated: u64, + pub file_nr_max: u64, + pub pid_max: u64, + pub file_descriptors_exhausted: bool, + pub recent_coredumps: Vec, +} + +pub struct LimitsScanner; + +impl LimitsScanner { + pub fn scan() -> SystemLimitsResult { + let mut result = SystemLimitsResult::default(); + + // 1. inotify max_user_watches + if let Ok(val) = std::fs::read_to_string("/proc/sys/fs/inotify/max_user_watches") { + result.max_user_watches = val.trim().parse().unwrap_or(0); + } + + // 2. file-nr: allocated, unused, max + if let Ok(val) = std::fs::read_to_string("/proc/sys/fs/file-nr") { + let parts: Vec<&str> = val.split_whitespace().collect(); + if parts.len() >= 3 { + result.file_nr_allocated = parts[0].parse().unwrap_or(0); + result.file_nr_max = parts[2].parse().unwrap_or(0); + if result.file_nr_max > 0 { + let ratio = result.file_nr_allocated as f64 / result.file_nr_max as f64; + if ratio >= 0.95 { + result.file_descriptors_exhausted = true; + } + } + } + } + + // 3. pid_max + if let Ok(val) = std::fs::read_to_string("/proc/sys/kernel/pid_max") { + result.pid_max = val.trim().parse().unwrap_or(0); + } + + // 4. coredumpctl + if let Ok(output) = Command::new("coredumpctl").args(["list", "--no-legend", "-n", "5"]).output() { + if output.status.success() { + let stdout = String::from_utf8_lossy(&output.stdout); + for line in stdout.lines() { + let trimmed = line.trim(); + if !trimmed.is_empty() { + result.recent_coredumps.push(trimmed.to_string()); + } + } + } + } + + result + } +} diff --git a/crates/core/src/scanner/linux.rs b/crates/core/src/scanner/linux.rs new file mode 100644 index 0000000..cdd2a02 --- /dev/null +++ b/crates/core/src/scanner/linux.rs @@ -0,0 +1,86 @@ +use std::process::Command; + +pub struct LinuxRawData { + pub failed_units: Vec, + pub systemd_logs: String, + pub kernel_logs: String, + pub storage_logs: String, + pub network_logs: String, + pub audio_logs: String, +} + +impl LinuxRawData { + pub fn collect() -> Self { + // 1. Опрос systemd на упавшие юниты + let failed_output = Command::new("systemctl") + .args(["--failed", "--no-legend", "--plain"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_default(); + + let mut failed_units = Vec::new(); + for line in failed_output.lines() { + if let Some(unit) = line.split_whitespace().next() { + if !unit.is_empty() { + failed_units.push(unit.to_string()); + } + } + } + + // Логи упавших сервисов + let mut systemd_logs = String::new(); + if !failed_units.is_empty() { + for unit in failed_units.iter().take(3) { + let status = Command::new("journalctl") + .args(["-u", unit, "-n", "20", "--no-pager"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_default(); + systemd_logs.push_str(&format!("--- Logs for {} ---\n{}\n", unit, status)); + } + } + + // 2. Критические логи ядра + let kernel_logs = Command::new("journalctl") + .args(["-k", "-p", "3", "-n", "30", "--no-pager"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_else(|_| { + Command::new("dmesg") + .args(["--level=err,crit,alert,emerg"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_default() + }); + + // 3. Дисковые ошибки + let storage_logs = Command::new("journalctl") + .args(["-g", "(I/O error|EXT4-fs error|BTRFS error|blk_update_request)", "-n", "20", "--no-pager"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_default(); + + // 4. Сеть + let network_logs = Command::new("journalctl") + .args(["-u", "NetworkManager", "-p", "4", "-n", "20", "--no-pager"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_default(); + + // 5. Звук + let audio_logs = Command::new("journalctl") + .args(["--user-unit", "pipewire", "-p", "4", "-n", "20", "--no-pager"]) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).to_string()) + .unwrap_or_default(); + + Self { + failed_units, + systemd_logs, + kernel_logs, + storage_logs, + network_logs, + audio_logs, + } + } +} diff --git a/crates/core/src/scanner/live.rs b/crates/core/src/scanner/live.rs new file mode 100644 index 0000000..57e5c64 --- /dev/null +++ b/crates/core/src/scanner/live.rs @@ -0,0 +1,202 @@ +use crate::models::LiveMetricsSnapshot; +use std::fs; +use std::sync::Mutex; +use std::time::Instant; + +static PREV_CPU_SAMPLE: Mutex> = Mutex::new(None); +static PREV_NET_SAMPLE: Mutex> = Mutex::new(None); +static PREV_DISK_SAMPLE: Mutex> = Mutex::new(None); + +pub struct LiveMetricsScanner; + +impl LiveMetricsScanner { + pub fn sample() -> LiveMetricsSnapshot { + let mut snap = LiveMetricsSnapshot::default(); + + snap.cpu_usage_percent = Self::sample_cpu_usage(); + Self::sample_memory(&mut snap); + Self::sample_thermals(&mut snap); + Self::sample_network_io(&mut snap); + Self::sample_disk_io(&mut snap); + + snap + } + + fn sample_cpu_usage() -> f32 { + #[cfg(target_os = "linux")] + if let Ok(content) = fs::read_to_string("/proc/stat") { + if let Some(first_line) = content.lines().next() { + let parts: Vec<&str> = first_line.split_whitespace().skip(1).collect(); + if parts.len() >= 4 { + let user: u64 = parts[0].parse().unwrap_or(0); + let nice: u64 = parts[1].parse().unwrap_or(0); + let system: u64 = parts[2].parse().unwrap_or(0); + let idle: u64 = parts[3].parse().unwrap_or(0); + let iowait: u64 = parts.get(4).and_then(|v| v.parse().ok()).unwrap_or(0); + let irq: u64 = parts.get(5).and_then(|v| v.parse().ok()).unwrap_or(0); + let softirq: u64 = parts.get(6).and_then(|v| v.parse().ok()).unwrap_or(0); + + let total_idle = idle + iowait; + let total_active = user + nice + system + irq + softirq; + let total = total_idle + total_active; + let now = Instant::now(); + + if let Ok(mut lock) = PREV_CPU_SAMPLE.lock() { + if let Some((prev_total, prev_idle, _)) = *lock { + let diff_total = total.saturating_sub(prev_total); + let diff_idle = total_idle.saturating_sub(prev_idle); + *lock = Some((total, total_idle, now)); + + if diff_total > 0 { + let usage = ((diff_total.saturating_sub(diff_idle)) as f32 / diff_total as f32) * 100.0; + return usage.clamp(0.0, 100.0); + } + } else { + *lock = Some((total, total_idle, now)); + return 15.0; // Значение по умолчанию на 1-м тике + } + } + } + } + } + + 20.0 + } + + fn sample_memory(snap: &mut LiveMetricsSnapshot) { + #[cfg(target_os = "linux")] + if let Ok(meminfo) = fs::read_to_string("/proc/meminfo") { + for line in meminfo.lines() { + let mut parts = line.split(':'); + let key = parts.next().unwrap_or("").trim(); + let val_str = parts.next().unwrap_or("").trim(); + let kb = val_str.split_whitespace().next().and_then(|v| v.parse::().ok()).unwrap_or(0); + let bytes = kb * 1024; + + match key { + "MemTotal" => snap.ram_total_bytes = bytes, + "MemAvailable" => { + let avail = bytes; + if snap.ram_total_bytes >= avail { + snap.ram_used_bytes = snap.ram_total_bytes - avail; + } + } + "SwapTotal" => snap.swap_total_bytes = bytes, + "SwapFree" => { + let free = bytes; + if snap.swap_total_bytes >= free { + snap.swap_used_bytes = snap.swap_total_bytes - free; + } + } + _ => {} + } + } + } + } + + fn sample_thermals(snap: &mut LiveMetricsSnapshot) { + let mut max_temp = 0.0f32; + #[cfg(target_os = "linux")] + if let Ok(entries) = fs::read_dir("/sys/class/thermal") { + for entry in entries.flatten() { + let p = entry.path(); + if p.file_name().map(|n| n.to_string_lossy().starts_with("thermal_zone")).unwrap_or(false) { + if let Ok(content) = fs::read_to_string(p.join("temp")) { + if let Ok(milli) = content.trim().parse::() { + let c = milli as f32 / 1000.0; + if c > max_temp && c < 150.0 { + max_temp = c; + } + } + } + } + } + } + + // Детекция активного троттлинга + let mut throttle = max_temp >= 90.0; + #[cfg(target_os = "linux")] + if let Ok(entries) = fs::read_dir("/sys/devices/system/cpu") { + for entry in entries.flatten() { + let p = entry.path().join("thermal_throttle/core_throttle_count"); + if let Ok(cnt) = fs::read_to_string(p) { + if let Ok(num) = cnt.trim().parse::() { + if num > 0 { + throttle = true; + } + } + } + } + } + + snap.max_cpu_temp_c = if max_temp > 0.0 { max_temp } else { 38.0 }; + snap.is_throttling = throttle; + } + + fn sample_network_io(snap: &mut LiveMetricsSnapshot) { + #[cfg(target_os = "linux")] + if let Ok(content) = fs::read_to_string("/proc/net/dev") { + let mut total_rx = 0u64; + let mut total_tx = 0u64; + for line in content.lines().skip(2) { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() >= 10 { + let iface = parts[0].trim_end_matches(':'); + if iface != "lo" { + let rx: u64 = parts[1].parse().unwrap_or(0); + let tx: u64 = parts[9].parse().unwrap_or(0); + total_rx += rx; + total_tx += tx; + } + } + } + + let now = Instant::now(); + if let Ok(mut lock) = PREV_NET_SAMPLE.lock() { + if let Some((prev_rx, prev_tx, prev_t)) = *lock { + let dt = now.duration_since(prev_t).as_secs_f32().max(0.1); + snap.net_rx_kbps = ((total_rx.saturating_sub(prev_rx)) as f32 / (dt * 1024.0)) as u64; + snap.net_tx_kbps = ((total_tx.saturating_sub(prev_tx)) as f32 / (dt * 1024.0)) as u64; + *lock = Some((total_rx, total_tx, now)); + } else { + *lock = Some((total_rx, total_tx, now)); + } + } + } + } + + fn sample_disk_io(snap: &mut LiveMetricsSnapshot) { + #[cfg(target_os = "linux")] + if let Ok(content) = fs::read_to_string("/proc/diskstats") { + let mut read_sectors = 0u64; + let mut write_sectors = 0u64; + for line in content.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() >= 14 { + let dev_name = parts[2]; + if dev_name.starts_with("sd") || dev_name.starts_with("nvme") { + if !dev_name.chars().last().unwrap_or(' ').is_ascii_digit() || dev_name.contains('n') { + let rs: u64 = parts[5].parse().unwrap_or(0); + let ws: u64 = parts[9].parse().unwrap_or(0); + read_sectors += rs; + write_sectors += ws; + } + } + } + } + + let now = Instant::now(); + if let Ok(mut lock) = PREV_DISK_SAMPLE.lock() { + if let Some((prev_r, prev_w, prev_t)) = *lock { + let dt = now.duration_since(prev_t).as_secs_f32().max(0.1); + // 1 sector = 512 bytes = 0.5 KB + snap.disk_read_kbps = ((read_sectors.saturating_sub(prev_r) * 512) as f32 / (dt * 1024.0)) as u64; + snap.disk_write_kbps = ((write_sectors.saturating_sub(prev_w) * 512) as f32 / (dt * 1024.0)) as u64; + *lock = Some((read_sectors, write_sectors, now)); + } else { + *lock = Some((read_sectors, write_sectors, now)); + } + } + } + } +} diff --git a/crates/core/src/scanner/mod.rs b/crates/core/src/scanner/mod.rs new file mode 100644 index 0000000..6464dcb --- /dev/null +++ b/crates/core/src/scanner/mod.rs @@ -0,0 +1,114 @@ +pub mod init; +pub mod kernel; +pub mod limits; +pub mod pressure; +pub mod storage; +pub mod hardware; +pub mod network_deep; +pub mod crashes; +pub mod security; +pub mod live; +pub mod linux; +pub mod bsd; + +use crate::auth::PrivilegeManager; +use crate::models::{CrashReportInfo, FailedService, SecurityAuditReport}; +pub use init::{detect_init_system, InitSystemProvider}; +pub use kernel::{KernelScanner, KernelScanResult}; +pub use limits::{LimitsScanner, SystemLimitsResult}; +pub use pressure::{PressureScanner, PsiMetrics}; +pub use storage::{StorageScanner, MountHealth}; +pub use hardware::{HardwareScanner, HardwareAuditResult}; +pub use network_deep::{NetworkDeepScanner, NetworkDeepScanResult}; +pub use crashes::CrashScanner; +pub use security::SecurityScanner; +pub use live::LiveMetricsScanner; + +pub struct UnifiedRawData { + pub os_name: String, + pub init_name: String, + pub is_root: bool, + pub failed_services: Vec, + pub kernel_scan: KernelScanResult, + pub limits_scan: SystemLimitsResult, + pub pressure_scan: PsiMetrics, + pub storage_mounts: Vec, + pub hardware_scan: HardwareAuditResult, + pub hardware_info: crate::models::HardwareInfo, + pub network_deep_scan: NetworkDeepScanResult, + pub crashes: Vec, + pub security: SecurityAuditReport, + pub service_logs: String, + pub network_logs: String, + pub audio_logs: String, +} + +impl UnifiedRawData { + pub fn collect(mode: Option) -> Self { + if let Some(m) = mode { + let _ = PrivilegeManager::ensure_privileges(m); + } + + let is_root = PrivilegeManager::is_current_user_root() + || matches!( + PrivilegeManager::ensure_privileges(mode.unwrap_or(crate::auth::AuthMode::Tui)), + crate::auth::PrivilegeStatus::Elevated + ); + let init_provider = detect_init_system(); + let init_name = init_provider.name().to_string(); + let failed_services = init_provider.get_failed_services().unwrap_or_default(); + + let kernel_scan = KernelScanner::scan(); + let limits_scan = LimitsScanner::scan(); + let pressure_scan = PressureScanner::scan(); + let storage_mounts = StorageScanner::scan(); + let (hardware_scan, hardware_info) = HardwareScanner::scan(); + let network_deep_scan = NetworkDeepScanner::scan(); + let crashes = CrashScanner::scan(); + let security = SecurityScanner::scan(); + + #[cfg(target_os = "linux")] + let (service_logs, network_logs, audio_logs) = { + let data = linux::LinuxRawData::collect(); + (data.systemd_logs, data.network_logs, data.audio_logs) + }; + + #[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] + let (service_logs, network_logs, audio_logs) = { + let data = bsd::BsdRawData::collect(); + (data.service_logs, data.network_logs, data.audio_logs) + }; + + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))] + let (service_logs, network_logs, audio_logs) = (String::new(), String::new(), String::new()); + + let os_name = if cfg!(target_os = "linux") { + "Linux".to_string() + } else if cfg!(target_os = "freebsd") { + "FreeBSD".to_string() + } else if cfg!(target_os = "openbsd") { + "OpenBSD".to_string() + } else { + std::env::consts::OS.to_string() + }; + + UnifiedRawData { + os_name, + init_name, + is_root, + failed_services, + kernel_scan, + limits_scan, + pressure_scan, + storage_mounts, + hardware_scan, + hardware_info, + network_deep_scan, + crashes, + security, + service_logs, + network_logs, + audio_logs, + } + } +} diff --git a/crates/core/src/scanner/network_deep.rs b/crates/core/src/scanner/network_deep.rs new file mode 100644 index 0000000..1f9e558 --- /dev/null +++ b/crates/core/src/scanner/network_deep.rs @@ -0,0 +1,199 @@ +use std::net::ToSocketAddrs; +use std::path::Path; +use std::time::Instant; + +#[derive(Debug, Clone, Default)] +pub struct NetworkDeepScanResult { + pub dns_broken_symlink: bool, + pub dns_servers: Vec, + pub dns_resolution_ok: bool, + pub dns_latency_ms: Option, + pub has_default_gateway: bool, + pub default_gateway_ip: Option, + pub firewall_conflict: Option, + pub wifi_drop_events: Vec, +} + +pub struct NetworkDeepScanner; + +impl NetworkDeepScanner { + pub fn scan() -> NetworkDeepScanResult { + let mut res = NetworkDeepScanResult::default(); + + // 1. Проверка /etc/resolv.conf + Self::check_resolv_conf(&mut res); + + // 2. Замер DNS задержки + Self::measure_dns(&mut res); + + // 3. Проверка шлюза по умолчанию + Self::check_default_gateway(&mut res); + + // 4. Конфликты брандмауэров + res.firewall_conflict = Self::check_firewall_conflicts(); + + // 5. Поиск сбросов Wi-Fi + res.wifi_drop_events = Self::scan_wifi_drops(); + + result_post_process(res) + } + + fn check_resolv_conf(res: &mut NetworkDeepScanResult) { + let resolv = Path::new("/etc/resolv.conf"); + if resolv.is_symlink() { + if let Ok(target) = std::fs::read_link(resolv) { + if !target.exists() && !resolv.exists() { + res.dns_broken_symlink = true; + } + } + } + + if let Ok(content) = std::fs::read_to_string(resolv) { + for line in content.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("nameserver") { + let parts: Vec<&str> = trimmed.split_whitespace().collect(); + if parts.len() >= 2 { + res.dns_servers.push(parts[1].to_string()); + } + } + } + } + + #[cfg(target_os = "macos")] + if res.dns_servers.is_empty() { + if let Ok(output) = std::process::Command::new("scutil").arg("--dns").output() { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("nameserver[0] :") || trimmed.starts_with("nameserver[1] :") { + if let Some(ip) = trimmed.split(':').nth(1) { + let ip_clean = ip.trim().to_string(); + if !res.dns_servers.contains(&ip_clean) { + res.dns_servers.push(ip_clean); + } + } + } + } + } + } + + #[cfg(target_os = "windows")] + if res.dns_servers.is_empty() { + let ps_cmd = "Get-DnsClientServerAddress -AddressFamily IPv4 | Select-Object -ExpandProperty ServerAddresses"; + if let Ok(output) = std::process::Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]).output() { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + let ip = line.trim().to_string(); + if !ip.is_empty() && !res.dns_servers.contains(&ip) { + res.dns_servers.push(ip); + } + } + } + } + } + + fn measure_dns(res: &mut NetworkDeepScanResult) { + let start = Instant::now(); + // Пытаемся зарезолвить надежный домен + match ("cloudflare.com", 80).to_socket_addrs() { + Ok(_) => { + res.dns_resolution_ok = true; + res.dns_latency_ms = Some(start.elapsed().as_millis()); + } + Err(_) => { + // Вторая попытка + match ("1.1.1.1", 80).to_socket_addrs() { + Ok(_) => { + res.dns_resolution_ok = false; // IP работает, а доменное имя нет -> DNS сломан! + } + Err(_) => { + res.dns_resolution_ok = false; + } + } + } + } + } + + fn check_default_gateway(res: &mut NetworkDeepScanResult) { + if let Ok(content) = std::fs::read_to_string("/proc/net/route") { + for line in content.lines().skip(1) { + let parts: Vec<&str> = line.split_whitespace().collect(); + // If destination is 00000000, it's default gateway + if parts.len() >= 3 && parts[1] == "00000000" { + res.has_default_gateway = true; + if let Ok(hex_ip) = u32::from_str_radix(parts[2], 16) { + let ip = std::net::Ipv4Addr::from(hex_ip.to_be()); + res.default_gateway_ip = Some(ip.to_string()); + } + break; + } + } + } + + #[cfg(target_os = "macos")] + if !res.has_default_gateway { + if let Ok(output) = std::process::Command::new("route").args(["-n", "get", "default"]).output() { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("gateway:") { + if let Some(gw) = trimmed.split(':').nth(1) { + res.has_default_gateway = true; + res.default_gateway_ip = Some(gw.trim().to_string()); + break; + } + } + } + } + } + + #[cfg(target_os = "windows")] + if !res.has_default_gateway { + let ps_cmd = "Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Select-Object -ExpandProperty NextHop"; + if let Ok(output) = std::process::Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", ps_cmd]).output() { + let gw = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if !gw.is_empty() { + res.has_default_gateway = true; + res.default_gateway_ip = Some(gw); + } + } + } + } + + fn check_firewall_conflicts() -> Option { + let ufw_active = Path::new("/run/ufw").exists() || Path::new("/etc/ufw").exists(); + let firewalld_active = Path::new("/run/firewalld").exists(); + + if ufw_active && firewalld_active { + return Some("Обнаружены одновременно активные службы UFW и firewalld. Это может вызывать сброс соединений.".to_string()); + } + + None + } + + fn scan_wifi_drops() -> Vec { + let mut drops = Vec::new(); + // Ищем в journalctl события деаутентификации wpa_supplicant или iwd + if let Ok(output) = crate::auth::PrivilegeManager::exec_privileged( + "journalctl", + &["-u", "wpa_supplicant", "-u", "iwd", "-n", "30", "--no-pager"], + ) { + let stdout = String::from_utf8_lossy(&output.stdout); + for line in stdout.lines() { + let lower = line.to_lowercase(); + if lower.contains("deauthenticated") || lower.contains("connection lost") || lower.contains("beacon loss") { + drops.push(line.to_string()); + } + } + } + drops + } +} + +fn result_post_process(mut res: NetworkDeepScanResult) -> NetworkDeepScanResult { + if res.dns_servers.is_empty() { + res.dns_resolution_ok = false; + } + res +} diff --git a/crates/core/src/scanner/pressure.rs b/crates/core/src/scanner/pressure.rs new file mode 100644 index 0000000..a63605b --- /dev/null +++ b/crates/core/src/scanner/pressure.rs @@ -0,0 +1,52 @@ +#[derive(Debug, Clone, Default)] +pub struct PsiMetrics { + pub cpu_some_avg10: f32, + pub mem_some_avg10: f32, + pub mem_full_avg10: f32, + pub io_some_avg10: f32, + pub io_full_avg10: f32, + pub is_supported: bool, +} + +pub struct PressureScanner; + +impl PressureScanner { + pub fn scan() -> PsiMetrics { + let mut psi = PsiMetrics::default(); + + // 1. /proc/pressure/cpu + if let Ok(content) = std::fs::read_to_string("/proc/pressure/cpu") { + psi.is_supported = true; + psi.cpu_some_avg10 = Self::extract_avg10(&content, "some"); + } + + // 2. /proc/pressure/memory + if let Ok(content) = std::fs::read_to_string("/proc/pressure/memory") { + psi.is_supported = true; + psi.mem_some_avg10 = Self::extract_avg10(&content, "some"); + psi.mem_full_avg10 = Self::extract_avg10(&content, "full"); + } + + // 3. /proc/pressure/io + if let Ok(content) = std::fs::read_to_string("/proc/pressure/io") { + psi.is_supported = true; + psi.io_some_avg10 = Self::extract_avg10(&content, "some"); + psi.io_full_avg10 = Self::extract_avg10(&content, "full"); + } + + psi + } + + fn extract_avg10(content: &str, line_prefix: &str) -> f32 { + for line in content.lines() { + if line.starts_with(line_prefix) { + for part in line.split_whitespace() { + if let Some(val_str) = part.strip_prefix("avg10=") { + return val_str.parse::().unwrap_or(0.0); + } + } + } + } + 0.0 + } +} diff --git a/crates/core/src/scanner/security.rs b/crates/core/src/scanner/security.rs new file mode 100644 index 0000000..d5ce143 --- /dev/null +++ b/crates/core/src/scanner/security.rs @@ -0,0 +1,364 @@ +use crate::models::{ + ListeningPortInfo, SecurityAuditReport, SecurityCheckItem, Severity, SuidAnomalyInfo, +}; +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::Command; + +pub struct SecurityScanner; + +impl SecurityScanner { + pub fn scan() -> SecurityAuditReport { + let mut report = SecurityAuditReport::default(); + + Self::scan_listening_ports(&mut report); + Self::scan_suid_anomalies(&mut report); + Self::scan_hardening_checks(&mut report); + Self::calculate_score(&mut report); + + report + } + + fn scan_listening_ports(report: &mut SecurityAuditReport) { + // 1. Используем утилиту ss -tulpn (или netstat) + if let Ok(output) = Command::new("ss").args(["-tulpn", "-H"]).output() { + let stdout = String::from_utf8_lossy(&output.stdout); + for line in stdout.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() >= 5 { + let proto = parts[0].to_ascii_uppercase(); + let local_addr = parts[4]; + + // Разбираем IP и порт (например: 0.0.0.0:22 или [::]:80 или 127.0.0.1:6379) + if let Some(colon_idx) = local_addr.rfind(':') { + let ip = &local_addr[..colon_idx]; + let port_str = &local_addr[colon_idx + 1..]; + if let Ok(port) = port_str.parse::() { + let is_public = ip == "0.0.0.0" || ip == "*" || ip == "::" || ip == "[::]"; + + // Извлекаем имя процесса и PID из последней колонки: users:(("sshd",pid=123,fd=3)) + let proc_info = parts.get(6).or_else(|| parts.get(5)).unwrap_or(&""); + let (proc_name, pid) = parse_process_info(proc_info); + + let (risk_level, rec) = assess_port_risk(port, is_public, &proc_name); + + report.exposed_ports.push(ListeningPortInfo { + protocol: proto, + local_address: local_addr.to_string(), + port, + process_name: proc_name, + pid, + is_public, + risk_level, + recommendation: rec, + }); + } + } + } + } + } else { + // Fallback через чтение /proc/net/tcp + Self::scan_proc_net_tcp(report); + } + + // Сортировка: сначала критические и публичные порты + report.exposed_ports.sort_by(|a, b| { + let rank = |sev: &Severity| match sev { + Severity::Critical => 0, + Severity::Warning => 1, + Severity::Info => 2, + }; + rank(&a.risk_level).cmp(&rank(&b.risk_level)).then(b.is_public.cmp(&a.is_public)) + }); + } + + fn scan_proc_net_tcp(report: &mut SecurityAuditReport) { + if let Ok(content) = fs::read_to_string("/proc/net/tcp") { + for line in content.lines().skip(1) { + let parts: Vec<&str> = line.split_whitespace().collect(); + // State 0A = TCP_LISTEN + if parts.len() >= 4 && parts[3] == "0A" { + if let Some(local) = parts.get(1) { + if let Some((_, port)) = parse_hex_socket(local) { + let is_public = local.starts_with("00000000:"); + let (risk_level, rec) = assess_port_risk(port, is_public, "tcp-service"); + report.exposed_ports.push(ListeningPortInfo { + protocol: "TCP".to_string(), + local_address: format!("*:{}", port), + port, + process_name: "unknown".to_string(), + pid: None, + is_public, + risk_level, + recommendation: rec, + }); + } + } + } + } + } + } + + fn scan_suid_anomalies(report: &mut SecurityAuditReport) { + // Проверяем директории, где SUID-бинарников быть не должно: /tmp, /var/tmp, /dev/shm + let suspect_dirs = ["/tmp", "/var/tmp", "/dev/shm"]; + for dir in suspect_dirs { + let path = Path::new(dir); + if path.exists() { + if let Ok(entries) = fs::read_dir(path) { + for entry in entries.flatten() { + let p = entry.path(); + if let Ok(meta) = p.metadata() { + let mode = meta.permissions().mode(); + // Бит SUID: 0o4000, SGID: 0o2000 + if mode & 0o4000 != 0 || mode & 0o2000 != 0 { + report.suid_anomalies.push(SuidAnomalyInfo { + path: p.to_string_lossy().to_string(), + owner: "root".to_string(), + permissions: format!("{:o}", mode & 0o7777), + risk_reason: format!("SUID/SGID файл обнаружен во временном каталоге {}. Потенциальный вектор эскалации привилегий.", dir), + }); + } + } + } + } + } + } + } + + fn scan_hardening_checks(report: &mut SecurityAuditReport) { + // 1. ASLR (randomize_va_space) + let aslr = fs::read_to_string("/proc/sys/kernel/randomize_va_space") + .unwrap_or_default() + .trim() + .to_string(); + let aslr_ok = aslr == "2"; + report.hardening_checks.push(SecurityCheckItem { + category: "Ядро".to_string(), + name: "ASLR (Address Space Layout Randomization)".to_string(), + status: if aslr_ok { "Активен (Full)" } else { "Уязвим / Отключен" }.to_string(), + is_secure: aslr_ok, + description: "Случайное распределение адресного пространства защищает от переполнения буфера.".to_string(), + remediation: if aslr_ok { None } else { Some("sysctl -w kernel.randomize_va_space=2".to_string()) }, + }); + + // 2. Ptrace Scope (Yama LSM) + let ptrace = fs::read_to_string("/proc/sys/kernel/yama/ptrace_scope") + .unwrap_or_default() + .trim() + .to_string(); + let ptrace_ok = ptrace == "1" || ptrace == "2" || ptrace == "3"; + report.hardening_checks.push(SecurityCheckItem { + category: "Ядро".to_string(), + name: "Yama ptrace_scope (Инъекция кода в процессы)".to_string(), + status: if ptrace_ok { "Защищен" } else { "Разрешена инъекция (0)" }.to_string(), + is_secure: ptrace_ok, + description: "Ограничивает возможность нерутовых процессов внедрять код в память других процессов через ptrace.".to_string(), + remediation: if ptrace_ok { None } else { Some("sysctl -w kernel.yama.ptrace_scope=1".to_string()) }, + }); + + // 3. Dmesg Restrict + let dmesg_res = fs::read_to_string("/proc/sys/kernel/dmesg_restrict") + .unwrap_or_default() + .trim() + .to_string(); + let dmesg_ok = dmesg_res == "1"; + report.hardening_checks.push(SecurityCheckItem { + category: "Ядро".to_string(), + name: "Защита буфера dmesg_restrict".to_string(), + status: if dmesg_ok { "Защищен" } else { "Открыт всем" }.to_string(), + is_secure: dmesg_ok, + description: "Запрещает непривилегированным пользователям читать адреса ядра из dmesg.".to_string(), + remediation: if dmesg_ok { None } else { Some("sysctl -w kernel.dmesg_restrict=1".to_string()) }, + }); + + // 4. Unprivileged BPF + let bpf = fs::read_to_string("/proc/sys/kernel/unprivileged_bpf_disabled") + .unwrap_or_default() + .trim() + .to_string(); + let bpf_ok = bpf == "1" || bpf == "2"; + report.hardening_checks.push(SecurityCheckItem { + category: "Ядро".to_string(), + name: "Unprivileged eBPF".to_string(), + status: if bpf_ok { "Заблокирован" } else { "Разрешен" }.to_string(), + is_secure: bpf_ok, + description: "Защищает ядро от Spectre-подобных атак через запуск eBPF обычными пользователями.".to_string(), + remediation: if bpf_ok { None } else { Some("sysctl -w kernel.unprivileged_bpf_disabled=1".to_string()) }, + }); + + // 5. AppArmor / SELinux + let apparmor_active = Path::new("/sys/kernel/security/apparmor").exists(); + let selinux_active = Path::new("/sys/fs/selinux").exists(); + let lsm_ok = apparmor_active || selinux_active; + report.hardening_checks.push(SecurityCheckItem { + category: "LSM".to_string(), + name: "Мандатный контроль доступа (LSM)".to_string(), + status: if apparmor_active { "AppArmor активен" } else if selinux_active { "SELinux активен" } else { "LSM отключен" }.to_string(), + is_secure: lsm_ok, + description: "Ограничивает права демонов даже при компрометации root прав.".to_string(), + remediation: if lsm_ok { None } else { Some("Включите AppArmor или SELinux в параметрах загрузки ядра.".to_string()) }, + }); + + // 6. Secure Boot + let sb_active = Path::new("/sys/firmware/efi/efivars").exists(); + report.hardening_checks.push(SecurityCheckItem { + category: "Прошивка".to_string(), + name: "UEFI Secure Boot".to_string(), + status: if sb_active { "UEFI режим" } else { "Legacy BIOS" }.to_string(), + is_secure: true, + description: "Проверяет криптографическую подпись модулей ядра при загрузке.".to_string(), + remediation: None, + }); + + // 7. SSH Configuration + Self::check_ssh_hardening(report); + } + + fn check_ssh_hardening(report: &mut SecurityAuditReport) { + let ssh_paths = ["/etc/ssh/sshd_config", "/etc/sshd_config"]; + for path_str in ssh_paths { + let path = Path::new(path_str); + if path.exists() { + if let Ok(content) = fs::read_to_string(path) { + let mut root_login_ok = true; + let mut empty_pass_ok = true; + + for line in content.lines() { + let trimmed = line.trim(); + if trimmed.starts_with('#') { + continue; + } + let lower = trimmed.to_lowercase(); + if lower.starts_with("permitrootlogin") && lower.contains("yes") { + root_login_ok = false; + } + if lower.starts_with("permitemptypasswords") && lower.contains("yes") { + empty_pass_ok = false; + } + } + + report.hardening_checks.push(SecurityCheckItem { + category: "SSH".to_string(), + name: "SSH PermitRootLogin".to_string(), + status: if root_login_ok { "Защищен" } else { "Разрешен вход root" }.to_string(), + is_secure: root_login_ok, + description: "Прямой вход суперпользователя по SSH без sudo.".to_string(), + remediation: if root_login_ok { None } else { Some("Установите 'PermitRootLogin prohibit-password' в /etc/ssh/sshd_config".to_string()) }, + }); + + report.hardening_checks.push(SecurityCheckItem { + category: "SSH".to_string(), + name: "SSH PermitEmptyPasswords".to_string(), + status: if empty_pass_ok { "Запрещены" } else { "Разрешены пустые пароли!" }.to_string(), + is_secure: empty_pass_ok, + description: "Разрешение авторизации учетных записей без паролей.".to_string(), + remediation: if empty_pass_ok { None } else { Some("Установите 'PermitEmptyPasswords no' в /etc/ssh/sshd_config".to_string()) }, + }); + return; + } + } + } + } + + fn calculate_score(report: &mut SecurityAuditReport) { + let mut score: i32 = 100; + + for port in &report.exposed_ports { + if port.is_public { + match port.risk_level { + Severity::Critical => score -= 20, + Severity::Warning => score -= 8, + Severity::Info => score -= 2, + } + } + } + + for _suid in &report.suid_anomalies { + score -= 25; + } + + for check in &report.hardening_checks { + if !check.is_secure { + score -= 10; + } + } + + report.security_score = score.clamp(10, 100) as u8; + } +} + +fn parse_process_info(text: &str) -> (String, Option) { + if let Some(start) = text.find('"') { + if let Some(end) = text[start + 1..].find('"') { + let name = &text[start + 1..start + 1 + end]; + let pid = text.find("pid=").and_then(|idx| { + let rest = &text[idx + 4..]; + let pid_str: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + pid_str.parse::().ok() + }); + return (name.to_string(), pid); + } + } + ("unknown".to_string(), None) +} + +fn assess_port_risk(port: u16, is_public: bool, proc_name: &str) -> (Severity, String) { + let lower_proc = proc_name.to_lowercase(); + match port { + 6379 if is_public => ( + Severity::Critical, + "Redis открыт на 0.0.0.0! Риск неавторизованного RCE. Привяжите к 127.0.0.1 (bind 127.0.0.1).".to_string(), + ), + 27017 if is_public => ( + Severity::Critical, + "MongoDB слушает на публичном интерфейсе. Ограничьте bindIp 127.0.0.1.".to_string(), + ), + 2375 | 2376 if is_public => ( + Severity::Critical, + "Docker Daemon API открыт в публичную сеть без TLS. Любой клиент имеет root-доступ к хосту!".to_string(), + ), + 9200 if is_public => ( + Severity::Critical, + "Elasticsearch HTTP порт доступен публично. Настройте аутентификацию и фаервол.".to_string(), + ), + 23 if is_public => ( + Severity::Critical, + "Telnet передает пароли в открытом виде. Отключите службу и перейдите на SSH.".to_string(), + ), + 5432 if is_public => ( + Severity::Warning, + "PostgreSQL слушает на всех интерфейсах. Убедитесь в надежности pg_hba.conf.".to_string(), + ), + 3306 if is_public => ( + Severity::Warning, + "MySQL/MariaDB порт открыт публично. Привяжите к bind-address = 127.0.0.1 при локальной работе.".to_string(), + ), + 5900 if is_public => ( + Severity::Warning, + "VNC сервер доступен публично. Рекомендуется доступ исключительно через SSH туннель.".to_string(), + ), + 22 if is_public => ( + Severity::Info, + "SSH порт 22 открыт наружу. Рекомендуется защита fail2ban/sshguard и вход по ключам.".to_string(), + ), + _ if is_public && (lower_proc.contains("redis") || lower_proc.contains("mongo")) => ( + Severity::Critical, + "База данных слушает на публичном интерфейсе!".to_string(), + ), + _ => ( + Severity::Info, + "Порт слушает входящие соединения.".to_string(), + ), + } +} + +fn parse_hex_socket(hex: &str) -> Option<(std::net::Ipv4Addr, u16)> { + let mut parts = hex.split(':'); + let ip_hex = parts.next()?; + let port_hex = parts.next()?; + let ip_num = u32::from_str_radix(ip_hex, 16).ok()?; + let port = u16::from_str_radix(port_hex, 16).ok()?; + Some((std::net::Ipv4Addr::from(ip_num.to_be()), port)) +} diff --git a/crates/core/src/scanner/storage.rs b/crates/core/src/scanner/storage.rs new file mode 100644 index 0000000..58f9d54 --- /dev/null +++ b/crates/core/src/scanner/storage.rs @@ -0,0 +1,91 @@ +use std::ffi::CString; +use std::mem::MaybeUninit; + +#[derive(Debug, Clone)] +pub struct MountHealth { + pub mount_point: String, + pub filesystem: String, + pub total_bytes: u64, + pub free_bytes: u64, + pub used_percent: f32, + pub inodes_total: u64, + pub inodes_free: u64, + pub inode_used_percent: f32, + pub is_critical: bool, +} + +pub struct StorageScanner; + +impl StorageScanner { + pub fn scan() -> Vec { + let mut results = Vec::new(); + + if let Ok(mounts) = std::fs::read_to_string("/proc/mounts") { + for line in mounts.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() < 3 { + continue; + } + let device = parts[0]; + let mount_point = parts[1]; + let fstype = parts[2]; + + // Фильтруем виртуальные ФС, оставляем реальные блочные устройства / ZFS / BTRFS + if !device.starts_with("/dev/") && fstype != "zfs" && fstype != "btrfs" { + continue; + } + + if let Some(health) = Self::check_mount(mount_point, fstype) { + results.push(health); + } + } + } + + results + } + + fn check_mount(mount_point: &str, fstype: &str) -> Option { + let c_path = CString::new(mount_point).ok()?; + unsafe { + let mut stat: MaybeUninit = MaybeUninit::uninit(); + if libc::statvfs(c_path.as_ptr(), stat.as_mut_ptr()) == 0 { + let stat = stat.assume_init(); + let bsize = if stat.f_frsize > 0 { stat.f_frsize } else { stat.f_bsize } as u64; + let total_bytes = stat.f_blocks * bsize; + let free_bytes = stat.f_bavail * bsize; + let used_bytes = total_bytes.saturating_sub(free_bytes); + + let used_percent = if total_bytes > 0 { + (used_bytes as f32 / total_bytes as f32) * 100.0 + } else { + 0.0 + }; + + let inodes_total = stat.f_files; + let inodes_free = stat.f_ffree; + let inodes_used = inodes_total.saturating_sub(inodes_free); + let inode_used_percent = if inodes_total > 0 { + (inodes_used as f32 / inodes_total as f32) * 100.0 + } else { + 0.0 + }; + + let is_critical = used_percent >= 90.0 || inode_used_percent >= 95.0; + + Some(MountHealth { + mount_point: mount_point.to_string(), + filesystem: fstype.to_string(), + total_bytes, + free_bytes, + used_percent, + inodes_total, + inodes_free, + inode_used_percent, + is_critical, + }) + } else { + None + } + } + } +} diff --git a/flutter_rust_bridge.yaml b/flutter_rust_bridge.yaml new file mode 100644 index 0000000..e15ed91 --- /dev/null +++ b/flutter_rust_bridge.yaml @@ -0,0 +1,3 @@ +rust_input: crate::api +rust_root: rust/ +dart_output: lib/src/rust \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..7b5cedb --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; +import 'package:diagd/screens/dashboard_screen.dart'; +import 'package:diagd/src/rust/frb_generated.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await RustLib.init(); + runApp(const DiagdApp()); +} + +class DiagdApp extends StatelessWidget { + const DiagdApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'diagd • Linux AI Diagnostic Analyst', + debugShowCheckedModeBanner: false, + themeMode: ThemeMode.dark, + darkTheme: ThemeData( + useMaterial3: true, + brightness: Brightness.dark, + scaffoldBackgroundColor: const Color(0xFF0D1117), + colorScheme: const ColorScheme.dark( + primary: Color(0xFF58A6FF), + secondary: Color(0xFF238636), + surface: Color(0xFF161B22), + error: Color(0xFFF85149), + ), + fontFamily: 'Inter', + ), + home: const DashboardScreen(), + ); + } +} diff --git a/lib/screens/dashboard_screen.dart b/lib/screens/dashboard_screen.dart new file mode 100644 index 0000000..db77493 --- /dev/null +++ b/lib/screens/dashboard_screen.dart @@ -0,0 +1,1078 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:diagd/src/rust/api/diagnostics.dart'; +import 'package:diagd/widgets/hardware_tab.dart'; +import 'package:diagd/widgets/live_monitor_tab.dart'; +import 'package:diagd/widgets/security_tab.dart'; +import 'package:diagd/widgets/crashes_tab.dart'; + +class DashboardScreen extends StatefulWidget { + const DashboardScreen({super.key}); + + @override + State createState() => _DashboardScreenState(); +} + +class _DashboardScreenState extends State { + bool _isLoading = false; + bool _isExporting = false; + int _selectedTab = 0; + SystemReport? _report; + String? _errorMessage; + + @override + void initState() { + super.initState(); + _performScan(); + } + + Future _performScan() async { + setState(() { + _isLoading = true; + _errorMessage = null; + }); + + try { + final report = await scanSystemAndAnalyze(); + setState(() { + _report = report; + _isLoading = false; + }); + } catch (e) { + setState(() { + _errorMessage = e.toString(); + _isLoading = false; + }); + } + } + + Future _exportDebugBundle() async { + if (_report == null) return; + setState(() { + _isExporting = true; + }); + + try { + final path = await exportDebugBundle(report: _report!); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Row( + children: [ + const Icon(Icons.check_circle_rounded, color: Color(0xFF3FB950), size: 20), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Debug Bundle экспортирован: $path', + style: const TextStyle(fontSize: 13), + ), + ), + ], + ), + backgroundColor: const Color(0xFF161B22), + duration: const Duration(seconds: 5), + action: SnackBarAction( + label: 'Копировать путь', + textColor: const Color(0xFF58A6FF), + onPressed: () { + Clipboard.setData(ClipboardData(text: path)); + }, + ), + ), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Ошибка экспорта: $e'), + backgroundColor: const Color(0xFFF85149), + ), + ); + } + } finally { + if (mounted) { + setState(() { + _isExporting = false; + }); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF0D1117), + appBar: _buildAppBar(), + body: _buildBody(), + ); + } + + PreferredSizeWidget _buildAppBar() { + return AppBar( + backgroundColor: const Color(0xFF161B22), + elevation: 0, + title: Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: const Color(0xFF238636).withAlpha(40), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF238636).withAlpha(80)), + ), + child: const Icon( + Icons.terminal_rounded, + color: Color(0xFF3FB950), + size: 22, + ), + ), + const SizedBox(width: 12), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'diagd • Linux AI Diagnostic Analyst', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + letterSpacing: 0.2, + ), + ), + Text( + _report != null + ? 'Последнее сканирование: ${_report!.timestamp}' + : 'Готов к диагностике системы', + style: const TextStyle( + fontSize: 12, + color: Color(0xFF8B949E), + ), + ), + ], + ), + ], + ), + actions: [ + if (_report != null && _report!.promptPreview.isNotEmpty) + TextButton.icon( + onPressed: () => _showPromptModal(context, _report!.promptPreview), + icon: const Icon(Icons.psychology_outlined, size: 18, color: Color(0xFF58A6FF)), + label: const Text( + 'LLM Prompt', + style: TextStyle(color: Color(0xFF58A6FF), fontSize: 13), + ), + ), + if (_report != null) ...[ + const SizedBox(width: 4), + TextButton.icon( + onPressed: _isExporting ? null : _exportDebugBundle, + icon: _isExporting + ? const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 2, color: Color(0xFF3FB950)), + ) + : const Icon(Icons.archive_outlined, size: 18, color: Color(0xFF3FB950)), + label: Text( + _isExporting ? 'Экспорт...' : 'Экспорт отчета', + style: const TextStyle(color: Color(0xFF3FB950), fontSize: 13), + ), + ), + ], + const SizedBox(width: 8), + Padding( + padding: const EdgeInsets.only(right: 16), + child: ElevatedButton.icon( + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF238636), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + onPressed: _isLoading ? null : _performScan, + icon: _isLoading + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : const Icon(Icons.refresh_rounded, size: 18), + label: Text( + _isLoading ? 'Анализ...' : 'Начать сканирование', + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ), + ), + ], + bottom: _report != null + ? PreferredSize( + preferredSize: const Size.fromHeight(48), + child: Container( + decoration: const BoxDecoration( + color: Color(0xFF161B22), + border: Border(bottom: BorderSide(color: Color(0xFF30363D), width: 1)), + ), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + const SizedBox(width: 24), + _buildTabButton( + index: 0, + title: 'Диагностика', + badge: _report!.issues.isNotEmpty ? '${_report!.issues.length}' : null, + icon: Icons.troubleshoot_rounded, + ), + const SizedBox(width: 6), + _buildTabButton( + index: 1, + title: 'Оборудование', + icon: Icons.memory_rounded, + ), + const SizedBox(width: 6), + _buildTabButton( + index: 2, + title: 'Live Монитор', + icon: Icons.speed_rounded, + ), + const SizedBox(width: 6), + _buildTabButton( + index: 3, + title: 'Безопасность', + badge: '${_report!.security.securityScore}%', + icon: Icons.security_rounded, + ), + const SizedBox(width: 6), + _buildTabButton( + index: 4, + title: 'Аварии и Сбои', + badge: _report!.crashes.isNotEmpty ? '${_report!.crashes.length}' : null, + icon: Icons.bug_report_rounded, + ), + const SizedBox(width: 24), + ], + ), + ), + ), + ) + : null, + ); + } + + Widget _buildTabButton({ + required int index, + required String title, + required IconData icon, + String? badge, + }) { + final isSelected = _selectedTab == index; + return InkWell( + onTap: () { + setState(() { + _selectedTab = index; + }); + }, + borderRadius: const BorderRadius.vertical(top: Radius.circular(8)), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + border: Border( + bottom: BorderSide( + color: isSelected ? const Color(0xFFF78166) : Colors.transparent, + width: 2, + ), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: 16, + color: isSelected ? const Color(0xFFE6EDF3) : const Color(0xFF8B949E), + ), + const SizedBox(width: 8), + Text( + title, + style: TextStyle( + fontSize: 13, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, + color: isSelected ? const Color(0xFFE6EDF3) : const Color(0xFF8B949E), + ), + ), + if (badge != null) ...[ + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: const Color(0xFF30363D), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + badge, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Color(0xFFE6EDF3), + ), + ), + ), + ], + ], + ), + ), + ); + } + + Widget _buildBody() { + if (_isLoading && _report == null) { + return const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator(color: Color(0xFF58A6FF)), + SizedBox(height: 20), + Text( + 'Опрос systemd, чтение journalctl / dmesg и санитизация логов...', + style: TextStyle(color: Color(0xFF8B949E), fontSize: 14), + ), + ], + ), + ); + } + + if (_errorMessage != null && _report == null) { + return Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 600), + margin: const EdgeInsets.all(24), + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFF85149).withAlpha(100)), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.error_outline_rounded, color: Color(0xFFF85149), size: 48), + const SizedBox(height: 16), + const Text( + 'Ошибка сканирования системы', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white), + ), + const SizedBox(height: 8), + Text( + _errorMessage!, + textAlign: TextAlign.center, + style: const TextStyle(color: Color(0xFF8B949E), fontFamily: 'monospace'), + ), + const SizedBox(height: 20), + ElevatedButton( + onPressed: _performScan, + child: const Text('Повторить'), + ), + ], + ), + ), + ); + } + + if (_report == null) { + return const SizedBox.shrink(); + } + + if (_selectedTab == 1) { + return HardwareTab(hardware: _report!.hardware); + } else if (_selectedTab == 2) { + return const LiveMonitorTab(); + } else if (_selectedTab == 3) { + return SecurityTab(security: _report!.security); + } else if (_selectedTab == 4) { + return CrashesTab(crashes: _report!.crashes); + } + + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSummaryBanner(_report!), + const SizedBox(height: 24), + const Text( + 'СОСТОЯНИЕ ПОДСИСТЕМ', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 1.2, + color: Color(0xFF8B949E), + ), + ), + const SizedBox(height: 12), + _buildSubsystemsGrid(_report!.subsystems), + const SizedBox(height: 28), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'НАЙДЕННЫЕ ИНЦИДЕНТЫ (${_report!.issues.length})', + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 1.2, + color: Color(0xFF8B949E), + ), + ), + if (_report!.llmAnalyzed) + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: const Color(0xFF1F6FEB).withAlpha(40), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF58A6FF)), + ), + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.auto_awesome, size: 14, color: Color(0xFF58A6FF)), + SizedBox(width: 6), + Text( + 'Обработано LLM', + style: TextStyle(fontSize: 11, color: Color(0xFF58A6FF), fontWeight: FontWeight.w600), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 12), + _buildIssuesList(_report!.issues), + ], + ), + ); + } + + Widget _buildSummaryBanner(SystemReport report) { + final criticalCount = report.issues.where((i) => i.severity == Severity.critical).length; + final warningCount = report.issues.where((i) => i.severity == Severity.warning).length; + + final Color statusColor = criticalCount > 0 + ? const Color(0xFFF85149) + : (warningCount > 0 ? const Color(0xFFD29922) : const Color(0xFF3FB950)); + + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: statusColor.withAlpha(80)), + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: statusColor.withAlpha(30), + shape: BoxShape.circle, + ), + child: Icon( + criticalCount > 0 + ? Icons.warning_amber_rounded + : (warningCount > 0 ? Icons.info_outline_rounded : Icons.check_circle_outline_rounded), + color: statusColor, + size: 28, + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + criticalCount > 0 + ? 'Обнаружены критические сбои системы' + : (warningCount > 0 ? 'Обнаружены предупреждения' : 'Система полностью стабильна'), + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 4), + Text( + report.summary, + style: const TextStyle(fontSize: 13, color: Color(0xFF8B949E)), + ), + ], + ), + ), + Row( + children: [ + _buildStatChip('Критические', criticalCount, const Color(0xFFF85149)), + const SizedBox(width: 8), + _buildStatChip('Предупреждения', warningCount, const Color(0xFFD29922)), + ], + ), + ], + ), + ); + } + + Widget _buildStatChip(String label, int count, Color color) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: color.withAlpha(25), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: color.withAlpha(70)), + ), + child: Column( + children: [ + Text( + count.toString(), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: color, + ), + ), + Text( + label, + style: const TextStyle(fontSize: 10, color: Color(0xFF8B949E)), + ), + ], + ), + ); + } + + Widget _buildSubsystemsGrid(List subsystems) { + return LayoutBuilder( + builder: (context, constraints) { + final crossAxisCount = constraints.maxWidth > 900 ? 5 : (constraints.maxWidth > 550 ? 3 : 2); + return GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: subsystems.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: crossAxisCount, + mainAxisExtent: 110, + crossAxisSpacing: 12, + mainAxisSpacing: 12, + ), + itemBuilder: (context, index) { + final sub = subsystems[index]; + return _buildSubsystemCard(sub); + }, + ); + }, + ); + } + + Widget _buildSubsystemCard(SubsystemStatus sub) { + final (IconData icon, String name) = switch (sub.name) { + Subsystem.systemd => (Icons.settings_suggest_rounded, 'Systemd'), + Subsystem.kernel => (Icons.memory_rounded, 'Kernel'), + Subsystem.storage => (Icons.storage_rounded, 'Storage'), + Subsystem.audio => (Icons.volume_up_rounded, 'Audio'), + Subsystem.network => (Icons.lan_rounded, 'Network'), + Subsystem.security => (Icons.security_rounded, 'Security'), + Subsystem.crashes => (Icons.bug_report_rounded, 'Crashes'), + }; + + final isHealthy = sub.status == 'Healthy'; + final isFailed = sub.status == 'Failed'; + final color = isFailed + ? const Color(0xFFF85149) + : (isHealthy ? const Color(0xFF3FB950) : const Color(0xFFD29922)); + + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: color.withAlpha(60)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Icon(icon, color: const Color(0xFFE6EDF3), size: 20), + Container( + width: 8, + height: 8, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow(color: color.withAlpha(120), blurRadius: 4, spreadRadius: 1), + ], + ), + ), + ], + ), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + name, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 2), + Text( + sub.status, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: color, + ), + ), + ], + ), + ], + ), + ); + } + + Widget _buildIssuesList(List issues) { + if (issues.isEmpty) { + return Container( + padding: const EdgeInsets.all(32), + width: double.infinity, + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + ), + child: const Center( + child: Text( + 'Проблем не обнаружено', + style: TextStyle(color: Color(0xFF8B949E)), + ), + ), + ); + } + + return ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: issues.length, + separatorBuilder: (_, _) => const SizedBox(height: 16), + itemBuilder: (context, index) { + return _buildIssueCard(issues[index]); + }, + ); + } + + Widget _buildIssueCard(IssueItem issue) { + final (badgeColor, badgeText, badgeIcon) = switch (issue.severity) { + Severity.critical => ( + const Color(0xFFF85149), + 'CRITICAL', + Icons.error_outline_rounded, + ), + Severity.warning => ( + const Color(0xFFD29922), + 'WARNING', + Icons.warning_amber_rounded, + ), + Severity.info => ( + const Color(0xFF58A6FF), + 'INFO', + Icons.info_outline_rounded, + ), + }; + + return Container( + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Верхняя плашка: Бейдж критичности + Подсистема + Row( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: badgeColor.withAlpha(35), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: badgeColor.withAlpha(90)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(badgeIcon, size: 13, color: badgeColor), + const SizedBox(width: 4), + Text( + badgeText, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: badgeColor, + letterSpacing: 0.5, + ), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + issue.subsystem.name.toUpperCase(), + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Color(0xFF8B949E), + ), + ), + ), + const Spacer(), + if (issue.sanitized) + const Tooltip( + message: 'Логи очищены от персональных путей, IP и токенов', + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.shield_outlined, size: 14, color: Color(0xFF3FB950)), + SizedBox(width: 4), + Text( + 'Sanitized', + style: TextStyle(fontSize: 11, color: Color(0xFF3FB950)), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 12), + // Заголовок проблемы + Text( + issue.title, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 8), + // Корень проблемы (Root Cause) + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF0D1117), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF21262D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'КОРЕНЬ ПРОБЛЕМЫ (ROOT CAUSE)', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w700, + letterSpacing: 0.8, + color: Color(0xFF58A6FF), + ), + ), + const SizedBox(height: 4), + Text( + issue.rootCause, + style: const TextStyle( + fontSize: 13, + color: Color(0xFFC9D1D9), + height: 1.4, + ), + ), + const SizedBox(height: 8), + Text( + issue.explanation, + style: const TextStyle( + fontSize: 12, + color: Color(0xFF8B949E), + height: 1.3, + ), + ), + ], + ), + ), + // Блок с решением / командой + if (issue.fix != null) ...[ + const SizedBox(height: 14), + _buildFixCommandSection(issue.fix!), + ], + const SizedBox(height: 14), + // Кнопка показа сырого лога + Align( + alignment: Alignment.centerRight, + child: TextButton.icon( + onPressed: () => _showRawLogModal(context, issue.title, issue.rawLog), + icon: const Icon(Icons.code_rounded, size: 16, color: Color(0xFF8B949E)), + label: const Text( + 'Показать сырой лог', + style: TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _buildFixCommandSection(FixSuggestion fix) { + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF0D1117), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF388BFD).withAlpha(50)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.build_circle_outlined, size: 15, color: Color(0xFF3FB950)), + const SizedBox(width: 6), + Text( + fix.title, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Color(0xFF3FB950), + ), + ), + ], + ), + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Row( + children: [ + Expanded( + child: SelectableText( + fix.command, + style: const TextStyle( + fontFamily: 'monospace', + fontSize: 12, + color: Color(0xFF79C0FF), + ), + ), + ), + IconButton( + tooltip: 'Скопировать команду решения', + icon: const Icon(Icons.copy_rounded, size: 16, color: Color(0xFF58A6FF)), + onPressed: () { + Clipboard.setData(ClipboardData(text: fix.command)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Команда скопирована: ${fix.command}'), + duration: const Duration(seconds: 2), + backgroundColor: const Color(0xFF238636), + ), + ); + }, + ), + ], + ), + ), + if (fix.explanation.isNotEmpty) ...[ + const SizedBox(height: 6), + Text( + fix.explanation, + style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E)), + ), + ], + ], + ), + ); + } + + void _showRawLogModal(BuildContext context, String title, String rawLog) { + showDialog( + context: context, + builder: (context) { + return Dialog( + backgroundColor: const Color(0xFF161B22), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: const BorderSide(color: Color(0xFF30363D)), + ), + child: Container( + constraints: const BoxConstraints(maxWidth: 750, maxHeight: 600), + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text( + 'Системный лог: $title', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + ), + IconButton( + icon: const Icon(Icons.close_rounded, color: Color(0xFF8B949E)), + onPressed: () => Navigator.pop(context), + ), + ], + ), + const Divider(color: Color(0xFF30363D)), + const SizedBox(height: 8), + Expanded( + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF0D1117), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF21262D)), + ), + child: SingleChildScrollView( + child: SelectableText( + rawLog.isEmpty ? 'Лог пуст или нет дополнительных записей' : rawLog, + style: const TextStyle( + fontFamily: 'monospace', + fontSize: 12, + color: Color(0xFFC9D1D9), + height: 1.4, + ), + ), + ), + ), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton.icon( + onPressed: () { + Clipboard.setData(ClipboardData(text: rawLog)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Лог скопирован в буфер обмена'), + duration: Duration(seconds: 2), + ), + ); + }, + icon: const Icon(Icons.copy_rounded, size: 16), + label: const Text('Скопировать весь лог'), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => Navigator.pop(context), + child: const Text('Закрыть'), + ), + ], + ), + ], + ), + ), + ); + }, + ); + } + + void _showPromptModal(BuildContext context, String promptPreview) { + showDialog( + context: context, + builder: (context) { + return Dialog( + backgroundColor: const Color(0xFF161B22), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: const BorderSide(color: Color(0xFF30363D)), + ), + child: Container( + constraints: const BoxConstraints(maxWidth: 700, maxHeight: 600), + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Структурированный JSON-промпт для LLM', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + IconButton( + icon: const Icon(Icons.close_rounded, color: Color(0xFF8B949E)), + onPressed: () => Navigator.pop(context), + ), + ], + ), + const Divider(color: Color(0xFF30363D)), + const SizedBox(height: 8), + Expanded( + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF0D1117), + borderRadius: BorderRadius.circular(8), + ), + child: SingleChildScrollView( + child: SelectableText( + promptPreview, + style: const TextStyle( + fontFamily: 'monospace', + fontSize: 11, + color: Color(0xFF79C0FF), + ), + ), + ), + ), + ), + const SizedBox(height: 12), + Align( + alignment: Alignment.centerRight, + child: ElevatedButton( + onPressed: () => Navigator.pop(context), + child: const Text('Закрыть'), + ), + ), + ], + ), + ), + ); + }, + ); + } +} diff --git a/lib/src/rust/api/diagnostics.dart b/lib/src/rust/api/diagnostics.dart new file mode 100644 index 0000000..0d2fe41 --- /dev/null +++ b/lib/src/rust/api/diagnostics.dart @@ -0,0 +1,973 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import + +import '../frb_generated.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; + +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from` + +/// Запрашивает права суперпользователя в графическом режиме через Polkit (pkexec) +Future requestGuiPrivileges() => + RustLib.instance.api.crateApiDiagnosticsRequestGuiPrivileges(); + +/// Сканирует состояние системы, очищает логи от персональных данных, +/// генерирует структурированный промпт для LLM и формирует итоговый аналитический отчет. +Future scanSystemAndAnalyze() => + RustLib.instance.api.crateApiDiagnosticsScanSystemAndAnalyze(); + +/// Возвращает мгновенный снимок телеметрии системы в реальном времени (CPU %, RAM, частоты, температуры, IO) +Future getLiveMetrics() => + RustLib.instance.api.crateApiDiagnosticsGetLiveMetrics(); + +/// Экспортирует полный архив Debug Bundle (.tar.gz, standalone HTML и markdown). +/// Возвращает путь к сохраненному архиву. +Future exportDebugBundle({required SystemReport report}) => + RustLib.instance.api.crateApiDiagnosticsExportDebugBundle(report: report); + +class BatteryInfo { + final String name; + final int capacityPercent; + final double healthPercent; + final int cycleCount; + final String status; + final bool isDegraded; + + const BatteryInfo({ + required this.name, + required this.capacityPercent, + required this.healthPercent, + required this.cycleCount, + required this.status, + required this.isDegraded, + }); + + @override + int get hashCode => + name.hashCode ^ + capacityPercent.hashCode ^ + healthPercent.hashCode ^ + cycleCount.hashCode ^ + status.hashCode ^ + isDegraded.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is BatteryInfo && + runtimeType == other.runtimeType && + name == other.name && + capacityPercent == other.capacityPercent && + healthPercent == other.healthPercent && + cycleCount == other.cycleCount && + status == other.status && + isDegraded == other.isDegraded; +} + +class CpuInfo { + final String modelName; + final String architecture; + final BigInt physicalCores; + final BigInt logicalThreads; + final double? baseFrequencyMhz; + final double? currentFrequencyMhz; + final String l1Cache; + final String l2Cache; + final String l3Cache; + final String? virtualization; + final List flags; + final String microcode; + + const CpuInfo({ + required this.modelName, + required this.architecture, + required this.physicalCores, + required this.logicalThreads, + this.baseFrequencyMhz, + this.currentFrequencyMhz, + required this.l1Cache, + required this.l2Cache, + required this.l3Cache, + this.virtualization, + required this.flags, + required this.microcode, + }); + + @override + int get hashCode => + modelName.hashCode ^ + architecture.hashCode ^ + physicalCores.hashCode ^ + logicalThreads.hashCode ^ + baseFrequencyMhz.hashCode ^ + currentFrequencyMhz.hashCode ^ + l1Cache.hashCode ^ + l2Cache.hashCode ^ + l3Cache.hashCode ^ + virtualization.hashCode ^ + flags.hashCode ^ + microcode.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is CpuInfo && + runtimeType == other.runtimeType && + modelName == other.modelName && + architecture == other.architecture && + physicalCores == other.physicalCores && + logicalThreads == other.logicalThreads && + baseFrequencyMhz == other.baseFrequencyMhz && + currentFrequencyMhz == other.currentFrequencyMhz && + l1Cache == other.l1Cache && + l2Cache == other.l2Cache && + l3Cache == other.l3Cache && + virtualization == other.virtualization && + flags == other.flags && + microcode == other.microcode; +} + +class CrashReportInfo { + final String timestamp; + final String processName; + final int? pid; + final String signalOrCode; + final String? faultModule; + final String stackTraceSnippet; + final String? dumpPath; + + const CrashReportInfo({ + required this.timestamp, + required this.processName, + this.pid, + required this.signalOrCode, + this.faultModule, + required this.stackTraceSnippet, + this.dumpPath, + }); + + static Future default_() => + RustLib.instance.api.crateApiDiagnosticsCrashReportInfoDefault(); + + @override + int get hashCode => + timestamp.hashCode ^ + processName.hashCode ^ + pid.hashCode ^ + signalOrCode.hashCode ^ + faultModule.hashCode ^ + stackTraceSnippet.hashCode ^ + dumpPath.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is CrashReportInfo && + runtimeType == other.runtimeType && + timestamp == other.timestamp && + processName == other.processName && + pid == other.pid && + signalOrCode == other.signalOrCode && + faultModule == other.faultModule && + stackTraceSnippet == other.stackTraceSnippet && + dumpPath == other.dumpPath; +} + +class DiskInfo { + final String name; + final String model; + final String serial; + final BigInt sizeBytes; + final String diskType; + final int? rotationalSpeedRpm; + final String smartStatus; + final int? healthPercent; + final int? wearPercent; + final int? nvmeWearPercent; + final int? temperatureC; + final BigInt? powerOnHours; + final BigInt? powerCycleCount; + final BigInt? badSectorsCount; + final double? totalWrittenTb; + final List partitions; + + const DiskInfo({ + required this.name, + required this.model, + required this.serial, + required this.sizeBytes, + required this.diskType, + this.rotationalSpeedRpm, + required this.smartStatus, + this.healthPercent, + this.wearPercent, + this.nvmeWearPercent, + this.temperatureC, + this.powerOnHours, + this.powerCycleCount, + this.badSectorsCount, + this.totalWrittenTb, + required this.partitions, + }); + + @override + int get hashCode => + name.hashCode ^ + model.hashCode ^ + serial.hashCode ^ + sizeBytes.hashCode ^ + diskType.hashCode ^ + rotationalSpeedRpm.hashCode ^ + smartStatus.hashCode ^ + healthPercent.hashCode ^ + wearPercent.hashCode ^ + nvmeWearPercent.hashCode ^ + temperatureC.hashCode ^ + powerOnHours.hashCode ^ + powerCycleCount.hashCode ^ + badSectorsCount.hashCode ^ + totalWrittenTb.hashCode ^ + partitions.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is DiskInfo && + runtimeType == other.runtimeType && + name == other.name && + model == other.model && + serial == other.serial && + sizeBytes == other.sizeBytes && + diskType == other.diskType && + rotationalSpeedRpm == other.rotationalSpeedRpm && + smartStatus == other.smartStatus && + healthPercent == other.healthPercent && + wearPercent == other.wearPercent && + nvmeWearPercent == other.nvmeWearPercent && + temperatureC == other.temperatureC && + powerOnHours == other.powerOnHours && + powerCycleCount == other.powerCycleCount && + badSectorsCount == other.badSectorsCount && + totalWrittenTb == other.totalWrittenTb && + partitions == other.partitions; +} + +/// Информация о сбойной системной службе +class FailedService { + final String name; + final String initSystem; + final String state; + final String description; + final String logs; + final String restartCommand; + final String statusCommand; + + const FailedService({ + required this.name, + required this.initSystem, + required this.state, + required this.description, + required this.logs, + required this.restartCommand, + required this.statusCommand, + }); + + @override + int get hashCode => + name.hashCode ^ + initSystem.hashCode ^ + state.hashCode ^ + description.hashCode ^ + logs.hashCode ^ + restartCommand.hashCode ^ + statusCommand.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is FailedService && + runtimeType == other.runtimeType && + name == other.name && + initSystem == other.initSystem && + state == other.state && + description == other.description && + logs == other.logs && + restartCommand == other.restartCommand && + statusCommand == other.statusCommand; +} + +/// Предложение по устранению ошибки с готовой CLI-командой +class FixSuggestion { + final String title; + final String command; + final String explanation; + + const FixSuggestion({ + required this.title, + required this.command, + required this.explanation, + }); + + @override + int get hashCode => title.hashCode ^ command.hashCode ^ explanation.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is FixSuggestion && + runtimeType == other.runtimeType && + title == other.title && + command == other.command && + explanation == other.explanation; +} + +class GpuInfo { + final String vendor; + final String model; + final String driver; + final String pciSlot; + + const GpuInfo({ + required this.vendor, + required this.model, + required this.driver, + required this.pciSlot, + }); + + @override + int get hashCode => + vendor.hashCode ^ model.hashCode ^ driver.hashCode ^ pciSlot.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is GpuInfo && + runtimeType == other.runtimeType && + vendor == other.vendor && + model == other.model && + driver == other.driver && + pciSlot == other.pciSlot; +} + +/// Подробный отчет об аппаратном обеспечении системы +class HardwareInfo { + final CpuInfo cpu; + final MemoryInfo memory; + final MotherboardInfo motherboard; + final List gpus; + final List disks; + final List networkAdapters; + final BatteryInfo? battery; + final ThermalsInfo thermals; + + const HardwareInfo({ + required this.cpu, + required this.memory, + required this.motherboard, + required this.gpus, + required this.disks, + required this.networkAdapters, + this.battery, + required this.thermals, + }); + + @override + int get hashCode => + cpu.hashCode ^ + memory.hashCode ^ + motherboard.hashCode ^ + gpus.hashCode ^ + disks.hashCode ^ + networkAdapters.hashCode ^ + battery.hashCode ^ + thermals.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is HardwareInfo && + runtimeType == other.runtimeType && + cpu == other.cpu && + memory == other.memory && + motherboard == other.motherboard && + gpus == other.gpus && + disks == other.disks && + networkAdapters == other.networkAdapters && + battery == other.battery && + thermals == other.thermals; +} + +/// Элемент диагностического отчета (проблема) +class IssueItem { + final String id; + final String title; + final Subsystem subsystem; + final Severity severity; + final String rootCause; + final String explanation; + final FixSuggestion? fix; + final String rawLog; + final bool sanitized; + final bool permissionDenied; + + const IssueItem({ + required this.id, + required this.title, + required this.subsystem, + required this.severity, + required this.rootCause, + required this.explanation, + this.fix, + required this.rawLog, + required this.sanitized, + required this.permissionDenied, + }); + + @override + int get hashCode => + id.hashCode ^ + title.hashCode ^ + subsystem.hashCode ^ + severity.hashCode ^ + rootCause.hashCode ^ + explanation.hashCode ^ + fix.hashCode ^ + rawLog.hashCode ^ + sanitized.hashCode ^ + permissionDenied.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is IssueItem && + runtimeType == other.runtimeType && + id == other.id && + title == other.title && + subsystem == other.subsystem && + severity == other.severity && + rootCause == other.rootCause && + explanation == other.explanation && + fix == other.fix && + rawLog == other.rawLog && + sanitized == other.sanitized && + permissionDenied == other.permissionDenied; +} + +class ListeningPortInfo { + final String protocol; + final String localAddress; + final int port; + final String processName; + final int? pid; + final bool isPublic; + final Severity riskLevel; + final String recommendation; + + const ListeningPortInfo({ + required this.protocol, + required this.localAddress, + required this.port, + required this.processName, + this.pid, + required this.isPublic, + required this.riskLevel, + required this.recommendation, + }); + + @override + int get hashCode => + protocol.hashCode ^ + localAddress.hashCode ^ + port.hashCode ^ + processName.hashCode ^ + pid.hashCode ^ + isPublic.hashCode ^ + riskLevel.hashCode ^ + recommendation.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is ListeningPortInfo && + runtimeType == other.runtimeType && + protocol == other.protocol && + localAddress == other.localAddress && + port == other.port && + processName == other.processName && + pid == other.pid && + isPublic == other.isPublic && + riskLevel == other.riskLevel && + recommendation == other.recommendation; +} + +class LiveMetricsSnapshot { + final double cpuUsagePercent; + final BigInt ramUsedBytes; + final BigInt ramTotalBytes; + final BigInt swapUsedBytes; + final BigInt swapTotalBytes; + final double maxCpuTempC; + final bool isThrottling; + final BigInt diskReadKbps; + final BigInt diskWriteKbps; + final BigInt netRxKbps; + final BigInt netTxKbps; + + const LiveMetricsSnapshot({ + required this.cpuUsagePercent, + required this.ramUsedBytes, + required this.ramTotalBytes, + required this.swapUsedBytes, + required this.swapTotalBytes, + required this.maxCpuTempC, + required this.isThrottling, + required this.diskReadKbps, + required this.diskWriteKbps, + required this.netRxKbps, + required this.netTxKbps, + }); + + static Future default_() => + RustLib.instance.api.crateApiDiagnosticsLiveMetricsSnapshotDefault(); + + @override + int get hashCode => + cpuUsagePercent.hashCode ^ + ramUsedBytes.hashCode ^ + ramTotalBytes.hashCode ^ + swapUsedBytes.hashCode ^ + swapTotalBytes.hashCode ^ + maxCpuTempC.hashCode ^ + isThrottling.hashCode ^ + diskReadKbps.hashCode ^ + diskWriteKbps.hashCode ^ + netRxKbps.hashCode ^ + netTxKbps.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is LiveMetricsSnapshot && + runtimeType == other.runtimeType && + cpuUsagePercent == other.cpuUsagePercent && + ramUsedBytes == other.ramUsedBytes && + ramTotalBytes == other.ramTotalBytes && + swapUsedBytes == other.swapUsedBytes && + swapTotalBytes == other.swapTotalBytes && + maxCpuTempC == other.maxCpuTempC && + isThrottling == other.isThrottling && + diskReadKbps == other.diskReadKbps && + diskWriteKbps == other.diskWriteKbps && + netRxKbps == other.netRxKbps && + netTxKbps == other.netTxKbps; +} + +class MemoryInfo { + final BigInt totalBytes; + final BigInt availableBytes; + final BigInt usedBytes; + final BigInt swapTotalBytes; + final BigInt swapUsedBytes; + final BigInt edacCeCount; + final BigInt edacUeCount; + + const MemoryInfo({ + required this.totalBytes, + required this.availableBytes, + required this.usedBytes, + required this.swapTotalBytes, + required this.swapUsedBytes, + required this.edacCeCount, + required this.edacUeCount, + }); + + @override + int get hashCode => + totalBytes.hashCode ^ + availableBytes.hashCode ^ + usedBytes.hashCode ^ + swapTotalBytes.hashCode ^ + swapUsedBytes.hashCode ^ + edacCeCount.hashCode ^ + edacUeCount.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is MemoryInfo && + runtimeType == other.runtimeType && + totalBytes == other.totalBytes && + availableBytes == other.availableBytes && + usedBytes == other.usedBytes && + swapTotalBytes == other.swapTotalBytes && + swapUsedBytes == other.swapUsedBytes && + edacCeCount == other.edacCeCount && + edacUeCount == other.edacUeCount; +} + +class MotherboardInfo { + final String vendor; + final String productName; + final String version; + final String biosVendor; + final String biosVersion; + final String biosDate; + final String chassisType; + + const MotherboardInfo({ + required this.vendor, + required this.productName, + required this.version, + required this.biosVendor, + required this.biosVersion, + required this.biosDate, + required this.chassisType, + }); + + @override + int get hashCode => + vendor.hashCode ^ + productName.hashCode ^ + version.hashCode ^ + biosVendor.hashCode ^ + biosVersion.hashCode ^ + biosDate.hashCode ^ + chassisType.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is MotherboardInfo && + runtimeType == other.runtimeType && + vendor == other.vendor && + productName == other.productName && + version == other.version && + biosVendor == other.biosVendor && + biosVersion == other.biosVersion && + biosDate == other.biosDate && + chassisType == other.chassisType; +} + +class NetworkAdapterInfo { + final String interfaceName; + final String ifType; + final String state; + final int? speedMbps; + final String macAddress; + final String driver; + + const NetworkAdapterInfo({ + required this.interfaceName, + required this.ifType, + required this.state, + this.speedMbps, + required this.macAddress, + required this.driver, + }); + + @override + int get hashCode => + interfaceName.hashCode ^ + ifType.hashCode ^ + state.hashCode ^ + speedMbps.hashCode ^ + macAddress.hashCode ^ + driver.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is NetworkAdapterInfo && + runtimeType == other.runtimeType && + interfaceName == other.interfaceName && + ifType == other.ifType && + state == other.state && + speedMbps == other.speedMbps && + macAddress == other.macAddress && + driver == other.driver; +} + +class PartitionInfo { + final String name; + final String path; + final String? mountPoint; + final String fsType; + final BigInt sizeBytes; + final BigInt usedBytes; + + const PartitionInfo({ + required this.name, + required this.path, + this.mountPoint, + required this.fsType, + required this.sizeBytes, + required this.usedBytes, + }); + + @override + int get hashCode => + name.hashCode ^ + path.hashCode ^ + mountPoint.hashCode ^ + fsType.hashCode ^ + sizeBytes.hashCode ^ + usedBytes.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is PartitionInfo && + runtimeType == other.runtimeType && + name == other.name && + path == other.path && + mountPoint == other.mountPoint && + fsType == other.fsType && + sizeBytes == other.sizeBytes && + usedBytes == other.usedBytes; +} + +class SecurityAuditReport { + final List exposedPorts; + final List suidAnomalies; + final List hardeningChecks; + final int securityScore; + + const SecurityAuditReport({ + required this.exposedPorts, + required this.suidAnomalies, + required this.hardeningChecks, + required this.securityScore, + }); + + static Future default_() => + RustLib.instance.api.crateApiDiagnosticsSecurityAuditReportDefault(); + + @override + int get hashCode => + exposedPorts.hashCode ^ + suidAnomalies.hashCode ^ + hardeningChecks.hashCode ^ + securityScore.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is SecurityAuditReport && + runtimeType == other.runtimeType && + exposedPorts == other.exposedPorts && + suidAnomalies == other.suidAnomalies && + hardeningChecks == other.hardeningChecks && + securityScore == other.securityScore; +} + +class SecurityCheckItem { + final String category; + final String name; + final String status; + final bool isSecure; + final String description; + final String? remediation; + + const SecurityCheckItem({ + required this.category, + required this.name, + required this.status, + required this.isSecure, + required this.description, + this.remediation, + }); + + static Future default_() => + RustLib.instance.api.crateApiDiagnosticsSecurityCheckItemDefault(); + + @override + int get hashCode => + category.hashCode ^ + name.hashCode ^ + status.hashCode ^ + isSecure.hashCode ^ + description.hashCode ^ + remediation.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is SecurityCheckItem && + runtimeType == other.runtimeType && + category == other.category && + name == other.name && + status == other.status && + isSecure == other.isSecure && + description == other.description && + remediation == other.remediation; +} + +/// Уровень критичности обнаруженной проблемы +enum Severity { critical, warning, info } + +/// Исследуемая подсистема ОС Linux / BSD +enum Subsystem { systemd, kernel, storage, audio, network, security, crashes } + +/// Статус состояния подсистемы для сводного дашборда +class SubsystemStatus { + final Subsystem name; + final String status; + final int issueCount; + final String details; + + const SubsystemStatus({ + required this.name, + required this.status, + required this.issueCount, + required this.details, + }); + + @override + int get hashCode => + name.hashCode ^ status.hashCode ^ issueCount.hashCode ^ details.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is SubsystemStatus && + runtimeType == other.runtimeType && + name == other.name && + status == other.status && + issueCount == other.issueCount && + details == other.details; +} + +class SuidAnomalyInfo { + final String path; + final String owner; + final String permissions; + final String riskReason; + + const SuidAnomalyInfo({ + required this.path, + required this.owner, + required this.permissions, + required this.riskReason, + }); + + static Future default_() => + RustLib.instance.api.crateApiDiagnosticsSuidAnomalyInfoDefault(); + + @override + int get hashCode => + path.hashCode ^ + owner.hashCode ^ + permissions.hashCode ^ + riskReason.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is SuidAnomalyInfo && + runtimeType == other.runtimeType && + path == other.path && + owner == other.owner && + permissions == other.permissions && + riskReason == other.riskReason; +} + +/// Общий итоговый отчет диагностики +class SystemReport { + final String timestamp; + final String osFamily; + final String initSystem; + final bool isRoot; + final List subsystems; + final List issues; + final List failedServices; + final HardwareInfo hardware; + final List crashes; + final SecurityAuditReport security; + final bool llmAnalyzed; + final String summary; + final String promptPreview; + + const SystemReport({ + required this.timestamp, + required this.osFamily, + required this.initSystem, + required this.isRoot, + required this.subsystems, + required this.issues, + required this.failedServices, + required this.hardware, + required this.crashes, + required this.security, + required this.llmAnalyzed, + required this.summary, + required this.promptPreview, + }); + + @override + int get hashCode => + timestamp.hashCode ^ + osFamily.hashCode ^ + initSystem.hashCode ^ + isRoot.hashCode ^ + subsystems.hashCode ^ + issues.hashCode ^ + failedServices.hashCode ^ + hardware.hashCode ^ + crashes.hashCode ^ + security.hashCode ^ + llmAnalyzed.hashCode ^ + summary.hashCode ^ + promptPreview.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is SystemReport && + runtimeType == other.runtimeType && + timestamp == other.timestamp && + osFamily == other.osFamily && + initSystem == other.initSystem && + isRoot == other.isRoot && + subsystems == other.subsystems && + issues == other.issues && + failedServices == other.failedServices && + hardware == other.hardware && + crashes == other.crashes && + security == other.security && + llmAnalyzed == other.llmAnalyzed && + summary == other.summary && + promptPreview == other.promptPreview; +} + +class ThermalsInfo { + final double maxCpuTempC; + final BigInt thermalThrottledCores; + final BigInt totalThrottleEvents; + final bool isActivelyThrottling; + + const ThermalsInfo({ + required this.maxCpuTempC, + required this.thermalThrottledCores, + required this.totalThrottleEvents, + required this.isActivelyThrottling, + }); + + @override + int get hashCode => + maxCpuTempC.hashCode ^ + thermalThrottledCores.hashCode ^ + totalThrottleEvents.hashCode ^ + isActivelyThrottling.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is ThermalsInfo && + runtimeType == other.runtimeType && + maxCpuTempC == other.maxCpuTempC && + thermalThrottledCores == other.thermalThrottledCores && + totalThrottleEvents == other.totalThrottleEvents && + isActivelyThrottling == other.isActivelyThrottling; +} diff --git a/lib/src/rust/api/simple.dart b/lib/src/rust/api/simple.dart new file mode 100644 index 0000000..ce276fb --- /dev/null +++ b/lib/src/rust/api/simple.dart @@ -0,0 +1,11 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import + +import '../frb_generated.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; + +String greet({required String name}) => + RustLib.instance.api.crateApiSimpleGreet(name: name); diff --git a/lib/src/rust/frb_generated.dart b/lib/src/rust/frb_generated.dart new file mode 100644 index 0000000..55cea1d --- /dev/null +++ b/lib/src/rust/frb_generated.dart @@ -0,0 +1,2596 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field + +import 'api/diagnostics.dart'; +import 'api/simple.dart'; + +import 'dart:async'; +import 'dart:convert'; + +import 'frb_generated.dart'; +import 'frb_generated.io.dart' + if (dart.library.js_interop) 'frb_generated.web.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; + +/// Main entrypoint of the Rust API +class RustLib extends BaseEntrypoint { + @internal + static final instance = RustLib._(); + + RustLib._(); + + /// Initialize flutter_rust_bridge + static Future init({ + RustLibApi? api, + BaseHandler? handler, + ExternalLibrary? externalLibrary, + bool forceSameCodegenVersion = true, + }) async { + await instance.initImpl( + api: api, + handler: handler, + externalLibrary: externalLibrary, + forceSameCodegenVersion: forceSameCodegenVersion, + ); + } + + /// Initialize flutter_rust_bridge in mock mode. + /// No libraries for FFI are loaded. + static void initMock({required RustLibApi api}) { + instance.initMockImpl(api: api); + } + + /// Dispose flutter_rust_bridge + /// + /// The call to this function is optional, since flutter_rust_bridge (and everything else) + /// is automatically disposed when the app stops. + static void dispose() => instance.disposeImpl(); + + @override + ApiImplConstructor get apiImplConstructor => + RustLibApiImpl.new; + + @override + WireConstructor get wireConstructor => + RustLibWire.fromExternalLibrary; + + @override + Future executeRustInitializers() async { + await api.crateApiSimpleInitApp(); + } + + @override + ExternalLibraryLoaderConfig get defaultExternalLibraryLoaderConfig => + kDefaultExternalLibraryLoaderConfig; + + @override + String get codegenVersion => '2.13.0'; + + @override + int get rustContentHash => 324119519; + + static const kDefaultExternalLibraryLoaderConfig = + ExternalLibraryLoaderConfig( + stem: 'rust_lib_diagd', + ioDirectory: 'rust/target/release/', + webPrefix: 'pkg/', + wasmBindgenName: 'wasm_bindgen', + ); +} + +abstract class RustLibApi extends BaseApi { + Future crateApiDiagnosticsCrashReportInfoDefault(); + + Future crateApiDiagnosticsExportDebugBundle({ + required SystemReport report, + }); + + Future crateApiDiagnosticsGetLiveMetrics(); + + String crateApiSimpleGreet({required String name}); + + Future crateApiSimpleInitApp(); + + Future crateApiDiagnosticsLiveMetricsSnapshotDefault(); + + Future crateApiDiagnosticsRequestGuiPrivileges(); + + Future crateApiDiagnosticsScanSystemAndAnalyze(); + + Future crateApiDiagnosticsSecurityAuditReportDefault(); + + Future crateApiDiagnosticsSecurityCheckItemDefault(); + + Future crateApiDiagnosticsSuidAnomalyInfoDefault(); +} + +class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { + RustLibApiImpl({ + required super.handler, + required super.wire, + required super.generalizedFrbRustBinding, + required super.portManager, + }); + + @override + Future crateApiDiagnosticsCrashReportInfoDefault() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 1, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_crash_report_info, + decodeErrorData: null, + ), + constMeta: kCrateApiDiagnosticsCrashReportInfoDefaultConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsCrashReportInfoDefaultConstMeta => + const TaskConstMeta(debugName: "crash_report_info_default", argNames: []); + + @override + Future crateApiDiagnosticsExportDebugBundle({ + required SystemReport report, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_system_report(report, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 2, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: sse_decode_String, + ), + constMeta: kCrateApiDiagnosticsExportDebugBundleConstMeta, + argValues: [report], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsExportDebugBundleConstMeta => + const TaskConstMeta( + debugName: "export_debug_bundle", + argNames: ["report"], + ); + + @override + Future crateApiDiagnosticsGetLiveMetrics() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 3, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_live_metrics_snapshot, + decodeErrorData: null, + ), + constMeta: kCrateApiDiagnosticsGetLiveMetricsConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsGetLiveMetricsConstMeta => + const TaskConstMeta(debugName: "get_live_metrics", argNames: []); + + @override + String crateApiSimpleGreet({required String name}) { + return handler.executeSync( + SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(name, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 4)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: null, + ), + constMeta: kCrateApiSimpleGreetConstMeta, + argValues: [name], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiSimpleGreetConstMeta => + const TaskConstMeta(debugName: "greet", argNames: ["name"]); + + @override + Future crateApiSimpleInitApp() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 5, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: null, + ), + constMeta: kCrateApiSimpleInitAppConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiSimpleInitAppConstMeta => + const TaskConstMeta(debugName: "init_app", argNames: []); + + @override + Future crateApiDiagnosticsLiveMetricsSnapshotDefault() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 6, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_live_metrics_snapshot, + decodeErrorData: null, + ), + constMeta: kCrateApiDiagnosticsLiveMetricsSnapshotDefaultConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsLiveMetricsSnapshotDefaultConstMeta => + const TaskConstMeta( + debugName: "live_metrics_snapshot_default", + argNames: [], + ); + + @override + Future crateApiDiagnosticsRequestGuiPrivileges() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 7, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiDiagnosticsRequestGuiPrivilegesConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsRequestGuiPrivilegesConstMeta => + const TaskConstMeta(debugName: "request_gui_privileges", argNames: []); + + @override + Future crateApiDiagnosticsScanSystemAndAnalyze() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 8, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_system_report, + decodeErrorData: sse_decode_String, + ), + constMeta: kCrateApiDiagnosticsScanSystemAndAnalyzeConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsScanSystemAndAnalyzeConstMeta => + const TaskConstMeta(debugName: "scan_system_and_analyze", argNames: []); + + @override + Future crateApiDiagnosticsSecurityAuditReportDefault() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 9, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_security_audit_report, + decodeErrorData: null, + ), + constMeta: kCrateApiDiagnosticsSecurityAuditReportDefaultConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsSecurityAuditReportDefaultConstMeta => + const TaskConstMeta( + debugName: "security_audit_report_default", + argNames: [], + ); + + @override + Future crateApiDiagnosticsSecurityCheckItemDefault() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 10, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_security_check_item, + decodeErrorData: null, + ), + constMeta: kCrateApiDiagnosticsSecurityCheckItemDefaultConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsSecurityCheckItemDefaultConstMeta => + const TaskConstMeta( + debugName: "security_check_item_default", + argNames: [], + ); + + @override + Future crateApiDiagnosticsSuidAnomalyInfoDefault() { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 11, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_suid_anomaly_info, + decodeErrorData: null, + ), + constMeta: kCrateApiDiagnosticsSuidAnomalyInfoDefaultConstMeta, + argValues: [], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiDiagnosticsSuidAnomalyInfoDefaultConstMeta => + const TaskConstMeta(debugName: "suid_anomaly_info_default", argNames: []); + + @protected + String dco_decode_String(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as String; + } + + @protected + BatteryInfo dco_decode_battery_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return BatteryInfo( + name: dco_decode_String(arr[0]), + capacityPercent: dco_decode_u_8(arr[1]), + healthPercent: dco_decode_f_32(arr[2]), + cycleCount: dco_decode_u_32(arr[3]), + status: dco_decode_String(arr[4]), + isDegraded: dco_decode_bool(arr[5]), + ); + } + + @protected + bool dco_decode_bool(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as bool; + } + + @protected + BatteryInfo dco_decode_box_autoadd_battery_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_battery_info(raw); + } + + @protected + double dco_decode_box_autoadd_f_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as double; + } + + @protected + double dco_decode_box_autoadd_f_64(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as double; + } + + @protected + FixSuggestion dco_decode_box_autoadd_fix_suggestion(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_fix_suggestion(raw); + } + + @protected + int dco_decode_box_autoadd_i_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + SystemReport dco_decode_box_autoadd_system_report(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_system_report(raw); + } + + @protected + int dco_decode_box_autoadd_u_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + BigInt dco_decode_box_autoadd_u_64(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_u_64(raw); + } + + @protected + int dco_decode_box_autoadd_u_8(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + CpuInfo dco_decode_cpu_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 12) + throw Exception('unexpected arr length: expect 12 but see ${arr.length}'); + return CpuInfo( + modelName: dco_decode_String(arr[0]), + architecture: dco_decode_String(arr[1]), + physicalCores: dco_decode_usize(arr[2]), + logicalThreads: dco_decode_usize(arr[3]), + baseFrequencyMhz: dco_decode_opt_box_autoadd_f_32(arr[4]), + currentFrequencyMhz: dco_decode_opt_box_autoadd_f_32(arr[5]), + l1Cache: dco_decode_String(arr[6]), + l2Cache: dco_decode_String(arr[7]), + l3Cache: dco_decode_String(arr[8]), + virtualization: dco_decode_opt_String(arr[9]), + flags: dco_decode_list_String(arr[10]), + microcode: dco_decode_String(arr[11]), + ); + } + + @protected + CrashReportInfo dco_decode_crash_report_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 7) + throw Exception('unexpected arr length: expect 7 but see ${arr.length}'); + return CrashReportInfo( + timestamp: dco_decode_String(arr[0]), + processName: dco_decode_String(arr[1]), + pid: dco_decode_opt_box_autoadd_u_32(arr[2]), + signalOrCode: dco_decode_String(arr[3]), + faultModule: dco_decode_opt_String(arr[4]), + stackTraceSnippet: dco_decode_String(arr[5]), + dumpPath: dco_decode_opt_String(arr[6]), + ); + } + + @protected + DiskInfo dco_decode_disk_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 16) + throw Exception('unexpected arr length: expect 16 but see ${arr.length}'); + return DiskInfo( + name: dco_decode_String(arr[0]), + model: dco_decode_String(arr[1]), + serial: dco_decode_String(arr[2]), + sizeBytes: dco_decode_u_64(arr[3]), + diskType: dco_decode_String(arr[4]), + rotationalSpeedRpm: dco_decode_opt_box_autoadd_u_32(arr[5]), + smartStatus: dco_decode_String(arr[6]), + healthPercent: dco_decode_opt_box_autoadd_u_8(arr[7]), + wearPercent: dco_decode_opt_box_autoadd_u_8(arr[8]), + nvmeWearPercent: dco_decode_opt_box_autoadd_u_8(arr[9]), + temperatureC: dco_decode_opt_box_autoadd_i_32(arr[10]), + powerOnHours: dco_decode_opt_box_autoadd_u_64(arr[11]), + powerCycleCount: dco_decode_opt_box_autoadd_u_64(arr[12]), + badSectorsCount: dco_decode_opt_box_autoadd_u_64(arr[13]), + totalWrittenTb: dco_decode_opt_box_autoadd_f_64(arr[14]), + partitions: dco_decode_list_partition_info(arr[15]), + ); + } + + @protected + double dco_decode_f_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as double; + } + + @protected + double dco_decode_f_64(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as double; + } + + @protected + FailedService dco_decode_failed_service(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 7) + throw Exception('unexpected arr length: expect 7 but see ${arr.length}'); + return FailedService( + name: dco_decode_String(arr[0]), + initSystem: dco_decode_String(arr[1]), + state: dco_decode_String(arr[2]), + description: dco_decode_String(arr[3]), + logs: dco_decode_String(arr[4]), + restartCommand: dco_decode_String(arr[5]), + statusCommand: dco_decode_String(arr[6]), + ); + } + + @protected + FixSuggestion dco_decode_fix_suggestion(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 3) + throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + return FixSuggestion( + title: dco_decode_String(arr[0]), + command: dco_decode_String(arr[1]), + explanation: dco_decode_String(arr[2]), + ); + } + + @protected + GpuInfo dco_decode_gpu_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return GpuInfo( + vendor: dco_decode_String(arr[0]), + model: dco_decode_String(arr[1]), + driver: dco_decode_String(arr[2]), + pciSlot: dco_decode_String(arr[3]), + ); + } + + @protected + HardwareInfo dco_decode_hardware_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 8) + throw Exception('unexpected arr length: expect 8 but see ${arr.length}'); + return HardwareInfo( + cpu: dco_decode_cpu_info(arr[0]), + memory: dco_decode_memory_info(arr[1]), + motherboard: dco_decode_motherboard_info(arr[2]), + gpus: dco_decode_list_gpu_info(arr[3]), + disks: dco_decode_list_disk_info(arr[4]), + networkAdapters: dco_decode_list_network_adapter_info(arr[5]), + battery: dco_decode_opt_box_autoadd_battery_info(arr[6]), + thermals: dco_decode_thermals_info(arr[7]), + ); + } + + @protected + int dco_decode_i_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + IssueItem dco_decode_issue_item(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 10) + throw Exception('unexpected arr length: expect 10 but see ${arr.length}'); + return IssueItem( + id: dco_decode_String(arr[0]), + title: dco_decode_String(arr[1]), + subsystem: dco_decode_subsystem(arr[2]), + severity: dco_decode_severity(arr[3]), + rootCause: dco_decode_String(arr[4]), + explanation: dco_decode_String(arr[5]), + fix: dco_decode_opt_box_autoadd_fix_suggestion(arr[6]), + rawLog: dco_decode_String(arr[7]), + sanitized: dco_decode_bool(arr[8]), + permissionDenied: dco_decode_bool(arr[9]), + ); + } + + @protected + List dco_decode_list_String(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_String).toList(); + } + + @protected + List dco_decode_list_crash_report_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_crash_report_info).toList(); + } + + @protected + List dco_decode_list_disk_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_disk_info).toList(); + } + + @protected + List dco_decode_list_failed_service(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_failed_service).toList(); + } + + @protected + List dco_decode_list_gpu_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_gpu_info).toList(); + } + + @protected + List dco_decode_list_issue_item(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_issue_item).toList(); + } + + @protected + List dco_decode_list_listening_port_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_listening_port_info).toList(); + } + + @protected + List dco_decode_list_network_adapter_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_network_adapter_info).toList(); + } + + @protected + List dco_decode_list_partition_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_partition_info).toList(); + } + + @protected + Uint8List dco_decode_list_prim_u_8_strict(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as Uint8List; + } + + @protected + List dco_decode_list_security_check_item(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_security_check_item).toList(); + } + + @protected + List dco_decode_list_subsystem_status(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_subsystem_status).toList(); + } + + @protected + List dco_decode_list_suid_anomaly_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_suid_anomaly_info).toList(); + } + + @protected + ListeningPortInfo dco_decode_listening_port_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 8) + throw Exception('unexpected arr length: expect 8 but see ${arr.length}'); + return ListeningPortInfo( + protocol: dco_decode_String(arr[0]), + localAddress: dco_decode_String(arr[1]), + port: dco_decode_u_16(arr[2]), + processName: dco_decode_String(arr[3]), + pid: dco_decode_opt_box_autoadd_u_32(arr[4]), + isPublic: dco_decode_bool(arr[5]), + riskLevel: dco_decode_severity(arr[6]), + recommendation: dco_decode_String(arr[7]), + ); + } + + @protected + LiveMetricsSnapshot dco_decode_live_metrics_snapshot(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 11) + throw Exception('unexpected arr length: expect 11 but see ${arr.length}'); + return LiveMetricsSnapshot( + cpuUsagePercent: dco_decode_f_32(arr[0]), + ramUsedBytes: dco_decode_u_64(arr[1]), + ramTotalBytes: dco_decode_u_64(arr[2]), + swapUsedBytes: dco_decode_u_64(arr[3]), + swapTotalBytes: dco_decode_u_64(arr[4]), + maxCpuTempC: dco_decode_f_32(arr[5]), + isThrottling: dco_decode_bool(arr[6]), + diskReadKbps: dco_decode_u_64(arr[7]), + diskWriteKbps: dco_decode_u_64(arr[8]), + netRxKbps: dco_decode_u_64(arr[9]), + netTxKbps: dco_decode_u_64(arr[10]), + ); + } + + @protected + MemoryInfo dco_decode_memory_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 7) + throw Exception('unexpected arr length: expect 7 but see ${arr.length}'); + return MemoryInfo( + totalBytes: dco_decode_u_64(arr[0]), + availableBytes: dco_decode_u_64(arr[1]), + usedBytes: dco_decode_u_64(arr[2]), + swapTotalBytes: dco_decode_u_64(arr[3]), + swapUsedBytes: dco_decode_u_64(arr[4]), + edacCeCount: dco_decode_u_64(arr[5]), + edacUeCount: dco_decode_u_64(arr[6]), + ); + } + + @protected + MotherboardInfo dco_decode_motherboard_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 7) + throw Exception('unexpected arr length: expect 7 but see ${arr.length}'); + return MotherboardInfo( + vendor: dco_decode_String(arr[0]), + productName: dco_decode_String(arr[1]), + version: dco_decode_String(arr[2]), + biosVendor: dco_decode_String(arr[3]), + biosVersion: dco_decode_String(arr[4]), + biosDate: dco_decode_String(arr[5]), + chassisType: dco_decode_String(arr[6]), + ); + } + + @protected + NetworkAdapterInfo dco_decode_network_adapter_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return NetworkAdapterInfo( + interfaceName: dco_decode_String(arr[0]), + ifType: dco_decode_String(arr[1]), + state: dco_decode_String(arr[2]), + speedMbps: dco_decode_opt_box_autoadd_u_32(arr[3]), + macAddress: dco_decode_String(arr[4]), + driver: dco_decode_String(arr[5]), + ); + } + + @protected + String? dco_decode_opt_String(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_String(raw); + } + + @protected + BatteryInfo? dco_decode_opt_box_autoadd_battery_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_battery_info(raw); + } + + @protected + double? dco_decode_opt_box_autoadd_f_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_f_32(raw); + } + + @protected + double? dco_decode_opt_box_autoadd_f_64(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_f_64(raw); + } + + @protected + FixSuggestion? dco_decode_opt_box_autoadd_fix_suggestion(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_fix_suggestion(raw); + } + + @protected + int? dco_decode_opt_box_autoadd_i_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_i_32(raw); + } + + @protected + int? dco_decode_opt_box_autoadd_u_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_u_32(raw); + } + + @protected + BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_u_64(raw); + } + + @protected + int? dco_decode_opt_box_autoadd_u_8(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_u_8(raw); + } + + @protected + PartitionInfo dco_decode_partition_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return PartitionInfo( + name: dco_decode_String(arr[0]), + path: dco_decode_String(arr[1]), + mountPoint: dco_decode_opt_String(arr[2]), + fsType: dco_decode_String(arr[3]), + sizeBytes: dco_decode_u_64(arr[4]), + usedBytes: dco_decode_u_64(arr[5]), + ); + } + + @protected + SecurityAuditReport dco_decode_security_audit_report(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return SecurityAuditReport( + exposedPorts: dco_decode_list_listening_port_info(arr[0]), + suidAnomalies: dco_decode_list_suid_anomaly_info(arr[1]), + hardeningChecks: dco_decode_list_security_check_item(arr[2]), + securityScore: dco_decode_u_8(arr[3]), + ); + } + + @protected + SecurityCheckItem dco_decode_security_check_item(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return SecurityCheckItem( + category: dco_decode_String(arr[0]), + name: dco_decode_String(arr[1]), + status: dco_decode_String(arr[2]), + isSecure: dco_decode_bool(arr[3]), + description: dco_decode_String(arr[4]), + remediation: dco_decode_opt_String(arr[5]), + ); + } + + @protected + Severity dco_decode_severity(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return Severity.values[raw as int]; + } + + @protected + Subsystem dco_decode_subsystem(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return Subsystem.values[raw as int]; + } + + @protected + SubsystemStatus dco_decode_subsystem_status(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return SubsystemStatus( + name: dco_decode_subsystem(arr[0]), + status: dco_decode_String(arr[1]), + issueCount: dco_decode_u_32(arr[2]), + details: dco_decode_String(arr[3]), + ); + } + + @protected + SuidAnomalyInfo dco_decode_suid_anomaly_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return SuidAnomalyInfo( + path: dco_decode_String(arr[0]), + owner: dco_decode_String(arr[1]), + permissions: dco_decode_String(arr[2]), + riskReason: dco_decode_String(arr[3]), + ); + } + + @protected + SystemReport dco_decode_system_report(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 13) + throw Exception('unexpected arr length: expect 13 but see ${arr.length}'); + return SystemReport( + timestamp: dco_decode_String(arr[0]), + osFamily: dco_decode_String(arr[1]), + initSystem: dco_decode_String(arr[2]), + isRoot: dco_decode_bool(arr[3]), + subsystems: dco_decode_list_subsystem_status(arr[4]), + issues: dco_decode_list_issue_item(arr[5]), + failedServices: dco_decode_list_failed_service(arr[6]), + hardware: dco_decode_hardware_info(arr[7]), + crashes: dco_decode_list_crash_report_info(arr[8]), + security: dco_decode_security_audit_report(arr[9]), + llmAnalyzed: dco_decode_bool(arr[10]), + summary: dco_decode_String(arr[11]), + promptPreview: dco_decode_String(arr[12]), + ); + } + + @protected + ThermalsInfo dco_decode_thermals_info(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); + return ThermalsInfo( + maxCpuTempC: dco_decode_f_32(arr[0]), + thermalThrottledCores: dco_decode_usize(arr[1]), + totalThrottleEvents: dco_decode_u_64(arr[2]), + isActivelyThrottling: dco_decode_bool(arr[3]), + ); + } + + @protected + int dco_decode_u_16(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + int dco_decode_u_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + BigInt dco_decode_u_64(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dcoDecodeU64(raw); + } + + @protected + int dco_decode_u_8(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + + @protected + void dco_decode_unit(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return; + } + + @protected + BigInt dco_decode_usize(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dcoDecodeU64(raw); + } + + @protected + String sse_decode_String(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var inner = sse_decode_list_prim_u_8_strict(deserializer); + return utf8.decoder.convert(inner); + } + + @protected + BatteryInfo sse_decode_battery_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_name = sse_decode_String(deserializer); + var var_capacityPercent = sse_decode_u_8(deserializer); + var var_healthPercent = sse_decode_f_32(deserializer); + var var_cycleCount = sse_decode_u_32(deserializer); + var var_status = sse_decode_String(deserializer); + var var_isDegraded = sse_decode_bool(deserializer); + return BatteryInfo( + name: var_name, + capacityPercent: var_capacityPercent, + healthPercent: var_healthPercent, + cycleCount: var_cycleCount, + status: var_status, + isDegraded: var_isDegraded, + ); + } + + @protected + bool sse_decode_bool(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getUint8() != 0; + } + + @protected + BatteryInfo sse_decode_box_autoadd_battery_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_battery_info(deserializer)); + } + + @protected + double sse_decode_box_autoadd_f_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_f_32(deserializer)); + } + + @protected + double sse_decode_box_autoadd_f_64(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_f_64(deserializer)); + } + + @protected + FixSuggestion sse_decode_box_autoadd_fix_suggestion( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_fix_suggestion(deserializer)); + } + + @protected + int sse_decode_box_autoadd_i_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_i_32(deserializer)); + } + + @protected + SystemReport sse_decode_box_autoadd_system_report( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_system_report(deserializer)); + } + + @protected + int sse_decode_box_autoadd_u_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_u_32(deserializer)); + } + + @protected + BigInt sse_decode_box_autoadd_u_64(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_u_64(deserializer)); + } + + @protected + int sse_decode_box_autoadd_u_8(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_u_8(deserializer)); + } + + @protected + CpuInfo sse_decode_cpu_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_modelName = sse_decode_String(deserializer); + var var_architecture = sse_decode_String(deserializer); + var var_physicalCores = sse_decode_usize(deserializer); + var var_logicalThreads = sse_decode_usize(deserializer); + var var_baseFrequencyMhz = sse_decode_opt_box_autoadd_f_32(deserializer); + var var_currentFrequencyMhz = sse_decode_opt_box_autoadd_f_32(deserializer); + var var_l1Cache = sse_decode_String(deserializer); + var var_l2Cache = sse_decode_String(deserializer); + var var_l3Cache = sse_decode_String(deserializer); + var var_virtualization = sse_decode_opt_String(deserializer); + var var_flags = sse_decode_list_String(deserializer); + var var_microcode = sse_decode_String(deserializer); + return CpuInfo( + modelName: var_modelName, + architecture: var_architecture, + physicalCores: var_physicalCores, + logicalThreads: var_logicalThreads, + baseFrequencyMhz: var_baseFrequencyMhz, + currentFrequencyMhz: var_currentFrequencyMhz, + l1Cache: var_l1Cache, + l2Cache: var_l2Cache, + l3Cache: var_l3Cache, + virtualization: var_virtualization, + flags: var_flags, + microcode: var_microcode, + ); + } + + @protected + CrashReportInfo sse_decode_crash_report_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_timestamp = sse_decode_String(deserializer); + var var_processName = sse_decode_String(deserializer); + var var_pid = sse_decode_opt_box_autoadd_u_32(deserializer); + var var_signalOrCode = sse_decode_String(deserializer); + var var_faultModule = sse_decode_opt_String(deserializer); + var var_stackTraceSnippet = sse_decode_String(deserializer); + var var_dumpPath = sse_decode_opt_String(deserializer); + return CrashReportInfo( + timestamp: var_timestamp, + processName: var_processName, + pid: var_pid, + signalOrCode: var_signalOrCode, + faultModule: var_faultModule, + stackTraceSnippet: var_stackTraceSnippet, + dumpPath: var_dumpPath, + ); + } + + @protected + DiskInfo sse_decode_disk_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_name = sse_decode_String(deserializer); + var var_model = sse_decode_String(deserializer); + var var_serial = sse_decode_String(deserializer); + var var_sizeBytes = sse_decode_u_64(deserializer); + var var_diskType = sse_decode_String(deserializer); + var var_rotationalSpeedRpm = sse_decode_opt_box_autoadd_u_32(deserializer); + var var_smartStatus = sse_decode_String(deserializer); + var var_healthPercent = sse_decode_opt_box_autoadd_u_8(deserializer); + var var_wearPercent = sse_decode_opt_box_autoadd_u_8(deserializer); + var var_nvmeWearPercent = sse_decode_opt_box_autoadd_u_8(deserializer); + var var_temperatureC = sse_decode_opt_box_autoadd_i_32(deserializer); + var var_powerOnHours = sse_decode_opt_box_autoadd_u_64(deserializer); + var var_powerCycleCount = sse_decode_opt_box_autoadd_u_64(deserializer); + var var_badSectorsCount = sse_decode_opt_box_autoadd_u_64(deserializer); + var var_totalWrittenTb = sse_decode_opt_box_autoadd_f_64(deserializer); + var var_partitions = sse_decode_list_partition_info(deserializer); + return DiskInfo( + name: var_name, + model: var_model, + serial: var_serial, + sizeBytes: var_sizeBytes, + diskType: var_diskType, + rotationalSpeedRpm: var_rotationalSpeedRpm, + smartStatus: var_smartStatus, + healthPercent: var_healthPercent, + wearPercent: var_wearPercent, + nvmeWearPercent: var_nvmeWearPercent, + temperatureC: var_temperatureC, + powerOnHours: var_powerOnHours, + powerCycleCount: var_powerCycleCount, + badSectorsCount: var_badSectorsCount, + totalWrittenTb: var_totalWrittenTb, + partitions: var_partitions, + ); + } + + @protected + double sse_decode_f_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getFloat32(); + } + + @protected + double sse_decode_f_64(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getFloat64(); + } + + @protected + FailedService sse_decode_failed_service(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_name = sse_decode_String(deserializer); + var var_initSystem = sse_decode_String(deserializer); + var var_state = sse_decode_String(deserializer); + var var_description = sse_decode_String(deserializer); + var var_logs = sse_decode_String(deserializer); + var var_restartCommand = sse_decode_String(deserializer); + var var_statusCommand = sse_decode_String(deserializer); + return FailedService( + name: var_name, + initSystem: var_initSystem, + state: var_state, + description: var_description, + logs: var_logs, + restartCommand: var_restartCommand, + statusCommand: var_statusCommand, + ); + } + + @protected + FixSuggestion sse_decode_fix_suggestion(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_title = sse_decode_String(deserializer); + var var_command = sse_decode_String(deserializer); + var var_explanation = sse_decode_String(deserializer); + return FixSuggestion( + title: var_title, + command: var_command, + explanation: var_explanation, + ); + } + + @protected + GpuInfo sse_decode_gpu_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_vendor = sse_decode_String(deserializer); + var var_model = sse_decode_String(deserializer); + var var_driver = sse_decode_String(deserializer); + var var_pciSlot = sse_decode_String(deserializer); + return GpuInfo( + vendor: var_vendor, + model: var_model, + driver: var_driver, + pciSlot: var_pciSlot, + ); + } + + @protected + HardwareInfo sse_decode_hardware_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_cpu = sse_decode_cpu_info(deserializer); + var var_memory = sse_decode_memory_info(deserializer); + var var_motherboard = sse_decode_motherboard_info(deserializer); + var var_gpus = sse_decode_list_gpu_info(deserializer); + var var_disks = sse_decode_list_disk_info(deserializer); + var var_networkAdapters = sse_decode_list_network_adapter_info( + deserializer, + ); + var var_battery = sse_decode_opt_box_autoadd_battery_info(deserializer); + var var_thermals = sse_decode_thermals_info(deserializer); + return HardwareInfo( + cpu: var_cpu, + memory: var_memory, + motherboard: var_motherboard, + gpus: var_gpus, + disks: var_disks, + networkAdapters: var_networkAdapters, + battery: var_battery, + thermals: var_thermals, + ); + } + + @protected + int sse_decode_i_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getInt32(); + } + + @protected + IssueItem sse_decode_issue_item(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_id = sse_decode_String(deserializer); + var var_title = sse_decode_String(deserializer); + var var_subsystem = sse_decode_subsystem(deserializer); + var var_severity = sse_decode_severity(deserializer); + var var_rootCause = sse_decode_String(deserializer); + var var_explanation = sse_decode_String(deserializer); + var var_fix = sse_decode_opt_box_autoadd_fix_suggestion(deserializer); + var var_rawLog = sse_decode_String(deserializer); + var var_sanitized = sse_decode_bool(deserializer); + var var_permissionDenied = sse_decode_bool(deserializer); + return IssueItem( + id: var_id, + title: var_title, + subsystem: var_subsystem, + severity: var_severity, + rootCause: var_rootCause, + explanation: var_explanation, + fix: var_fix, + rawLog: var_rawLog, + sanitized: var_sanitized, + permissionDenied: var_permissionDenied, + ); + } + + @protected + List sse_decode_list_String(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_String(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_crash_report_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_crash_report_info(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_disk_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_disk_info(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_failed_service( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_failed_service(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_gpu_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_gpu_info(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_issue_item(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_issue_item(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_listening_port_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_listening_port_info(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_network_adapter_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_network_adapter_info(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_partition_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_partition_info(deserializer)); + } + return ans_; + } + + @protected + Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var len_ = sse_decode_i_32(deserializer); + return deserializer.buffer.getUint8List(len_); + } + + @protected + List sse_decode_list_security_check_item( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_security_check_item(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_subsystem_status( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_subsystem_status(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_suid_anomaly_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_suid_anomaly_info(deserializer)); + } + return ans_; + } + + @protected + ListeningPortInfo sse_decode_listening_port_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_protocol = sse_decode_String(deserializer); + var var_localAddress = sse_decode_String(deserializer); + var var_port = sse_decode_u_16(deserializer); + var var_processName = sse_decode_String(deserializer); + var var_pid = sse_decode_opt_box_autoadd_u_32(deserializer); + var var_isPublic = sse_decode_bool(deserializer); + var var_riskLevel = sse_decode_severity(deserializer); + var var_recommendation = sse_decode_String(deserializer); + return ListeningPortInfo( + protocol: var_protocol, + localAddress: var_localAddress, + port: var_port, + processName: var_processName, + pid: var_pid, + isPublic: var_isPublic, + riskLevel: var_riskLevel, + recommendation: var_recommendation, + ); + } + + @protected + LiveMetricsSnapshot sse_decode_live_metrics_snapshot( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_cpuUsagePercent = sse_decode_f_32(deserializer); + var var_ramUsedBytes = sse_decode_u_64(deserializer); + var var_ramTotalBytes = sse_decode_u_64(deserializer); + var var_swapUsedBytes = sse_decode_u_64(deserializer); + var var_swapTotalBytes = sse_decode_u_64(deserializer); + var var_maxCpuTempC = sse_decode_f_32(deserializer); + var var_isThrottling = sse_decode_bool(deserializer); + var var_diskReadKbps = sse_decode_u_64(deserializer); + var var_diskWriteKbps = sse_decode_u_64(deserializer); + var var_netRxKbps = sse_decode_u_64(deserializer); + var var_netTxKbps = sse_decode_u_64(deserializer); + return LiveMetricsSnapshot( + cpuUsagePercent: var_cpuUsagePercent, + ramUsedBytes: var_ramUsedBytes, + ramTotalBytes: var_ramTotalBytes, + swapUsedBytes: var_swapUsedBytes, + swapTotalBytes: var_swapTotalBytes, + maxCpuTempC: var_maxCpuTempC, + isThrottling: var_isThrottling, + diskReadKbps: var_diskReadKbps, + diskWriteKbps: var_diskWriteKbps, + netRxKbps: var_netRxKbps, + netTxKbps: var_netTxKbps, + ); + } + + @protected + MemoryInfo sse_decode_memory_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_totalBytes = sse_decode_u_64(deserializer); + var var_availableBytes = sse_decode_u_64(deserializer); + var var_usedBytes = sse_decode_u_64(deserializer); + var var_swapTotalBytes = sse_decode_u_64(deserializer); + var var_swapUsedBytes = sse_decode_u_64(deserializer); + var var_edacCeCount = sse_decode_u_64(deserializer); + var var_edacUeCount = sse_decode_u_64(deserializer); + return MemoryInfo( + totalBytes: var_totalBytes, + availableBytes: var_availableBytes, + usedBytes: var_usedBytes, + swapTotalBytes: var_swapTotalBytes, + swapUsedBytes: var_swapUsedBytes, + edacCeCount: var_edacCeCount, + edacUeCount: var_edacUeCount, + ); + } + + @protected + MotherboardInfo sse_decode_motherboard_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_vendor = sse_decode_String(deserializer); + var var_productName = sse_decode_String(deserializer); + var var_version = sse_decode_String(deserializer); + var var_biosVendor = sse_decode_String(deserializer); + var var_biosVersion = sse_decode_String(deserializer); + var var_biosDate = sse_decode_String(deserializer); + var var_chassisType = sse_decode_String(deserializer); + return MotherboardInfo( + vendor: var_vendor, + productName: var_productName, + version: var_version, + biosVendor: var_biosVendor, + biosVersion: var_biosVersion, + biosDate: var_biosDate, + chassisType: var_chassisType, + ); + } + + @protected + NetworkAdapterInfo sse_decode_network_adapter_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_interfaceName = sse_decode_String(deserializer); + var var_ifType = sse_decode_String(deserializer); + var var_state = sse_decode_String(deserializer); + var var_speedMbps = sse_decode_opt_box_autoadd_u_32(deserializer); + var var_macAddress = sse_decode_String(deserializer); + var var_driver = sse_decode_String(deserializer); + return NetworkAdapterInfo( + interfaceName: var_interfaceName, + ifType: var_ifType, + state: var_state, + speedMbps: var_speedMbps, + macAddress: var_macAddress, + driver: var_driver, + ); + } + + @protected + String? sse_decode_opt_String(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_String(deserializer)); + } else { + return null; + } + } + + @protected + BatteryInfo? sse_decode_opt_box_autoadd_battery_info( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_battery_info(deserializer)); + } else { + return null; + } + } + + @protected + double? sse_decode_opt_box_autoadd_f_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_f_32(deserializer)); + } else { + return null; + } + } + + @protected + double? sse_decode_opt_box_autoadd_f_64(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_f_64(deserializer)); + } else { + return null; + } + } + + @protected + FixSuggestion? sse_decode_opt_box_autoadd_fix_suggestion( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_fix_suggestion(deserializer)); + } else { + return null; + } + } + + @protected + int? sse_decode_opt_box_autoadd_i_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_i_32(deserializer)); + } else { + return null; + } + } + + @protected + int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_u_32(deserializer)); + } else { + return null; + } + } + + @protected + BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_u_64(deserializer)); + } else { + return null; + } + } + + @protected + int? sse_decode_opt_box_autoadd_u_8(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_u_8(deserializer)); + } else { + return null; + } + } + + @protected + PartitionInfo sse_decode_partition_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_name = sse_decode_String(deserializer); + var var_path = sse_decode_String(deserializer); + var var_mountPoint = sse_decode_opt_String(deserializer); + var var_fsType = sse_decode_String(deserializer); + var var_sizeBytes = sse_decode_u_64(deserializer); + var var_usedBytes = sse_decode_u_64(deserializer); + return PartitionInfo( + name: var_name, + path: var_path, + mountPoint: var_mountPoint, + fsType: var_fsType, + sizeBytes: var_sizeBytes, + usedBytes: var_usedBytes, + ); + } + + @protected + SecurityAuditReport sse_decode_security_audit_report( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_exposedPorts = sse_decode_list_listening_port_info(deserializer); + var var_suidAnomalies = sse_decode_list_suid_anomaly_info(deserializer); + var var_hardeningChecks = sse_decode_list_security_check_item(deserializer); + var var_securityScore = sse_decode_u_8(deserializer); + return SecurityAuditReport( + exposedPorts: var_exposedPorts, + suidAnomalies: var_suidAnomalies, + hardeningChecks: var_hardeningChecks, + securityScore: var_securityScore, + ); + } + + @protected + SecurityCheckItem sse_decode_security_check_item( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_category = sse_decode_String(deserializer); + var var_name = sse_decode_String(deserializer); + var var_status = sse_decode_String(deserializer); + var var_isSecure = sse_decode_bool(deserializer); + var var_description = sse_decode_String(deserializer); + var var_remediation = sse_decode_opt_String(deserializer); + return SecurityCheckItem( + category: var_category, + name: var_name, + status: var_status, + isSecure: var_isSecure, + description: var_description, + remediation: var_remediation, + ); + } + + @protected + Severity sse_decode_severity(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var inner = sse_decode_i_32(deserializer); + return Severity.values[inner]; + } + + @protected + Subsystem sse_decode_subsystem(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var inner = sse_decode_i_32(deserializer); + return Subsystem.values[inner]; + } + + @protected + SubsystemStatus sse_decode_subsystem_status(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_name = sse_decode_subsystem(deserializer); + var var_status = sse_decode_String(deserializer); + var var_issueCount = sse_decode_u_32(deserializer); + var var_details = sse_decode_String(deserializer); + return SubsystemStatus( + name: var_name, + status: var_status, + issueCount: var_issueCount, + details: var_details, + ); + } + + @protected + SuidAnomalyInfo sse_decode_suid_anomaly_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_path = sse_decode_String(deserializer); + var var_owner = sse_decode_String(deserializer); + var var_permissions = sse_decode_String(deserializer); + var var_riskReason = sse_decode_String(deserializer); + return SuidAnomalyInfo( + path: var_path, + owner: var_owner, + permissions: var_permissions, + riskReason: var_riskReason, + ); + } + + @protected + SystemReport sse_decode_system_report(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_timestamp = sse_decode_String(deserializer); + var var_osFamily = sse_decode_String(deserializer); + var var_initSystem = sse_decode_String(deserializer); + var var_isRoot = sse_decode_bool(deserializer); + var var_subsystems = sse_decode_list_subsystem_status(deserializer); + var var_issues = sse_decode_list_issue_item(deserializer); + var var_failedServices = sse_decode_list_failed_service(deserializer); + var var_hardware = sse_decode_hardware_info(deserializer); + var var_crashes = sse_decode_list_crash_report_info(deserializer); + var var_security = sse_decode_security_audit_report(deserializer); + var var_llmAnalyzed = sse_decode_bool(deserializer); + var var_summary = sse_decode_String(deserializer); + var var_promptPreview = sse_decode_String(deserializer); + return SystemReport( + timestamp: var_timestamp, + osFamily: var_osFamily, + initSystem: var_initSystem, + isRoot: var_isRoot, + subsystems: var_subsystems, + issues: var_issues, + failedServices: var_failedServices, + hardware: var_hardware, + crashes: var_crashes, + security: var_security, + llmAnalyzed: var_llmAnalyzed, + summary: var_summary, + promptPreview: var_promptPreview, + ); + } + + @protected + ThermalsInfo sse_decode_thermals_info(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_maxCpuTempC = sse_decode_f_32(deserializer); + var var_thermalThrottledCores = sse_decode_usize(deserializer); + var var_totalThrottleEvents = sse_decode_u_64(deserializer); + var var_isActivelyThrottling = sse_decode_bool(deserializer); + return ThermalsInfo( + maxCpuTempC: var_maxCpuTempC, + thermalThrottledCores: var_thermalThrottledCores, + totalThrottleEvents: var_totalThrottleEvents, + isActivelyThrottling: var_isActivelyThrottling, + ); + } + + @protected + int sse_decode_u_16(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getUint16(); + } + + @protected + int sse_decode_u_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getUint32(); + } + + @protected + BigInt sse_decode_u_64(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getBigUint64(); + } + + @protected + int sse_decode_u_8(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getUint8(); + } + + @protected + void sse_decode_unit(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + } + + @protected + BigInt sse_decode_usize(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return deserializer.buffer.getBigUint64(); + } + + @protected + void sse_encode_String(String self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_list_prim_u_8_strict(utf8.encoder.convert(self), serializer); + } + + @protected + void sse_encode_battery_info(BatteryInfo self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.name, serializer); + sse_encode_u_8(self.capacityPercent, serializer); + sse_encode_f_32(self.healthPercent, serializer); + sse_encode_u_32(self.cycleCount, serializer); + sse_encode_String(self.status, serializer); + sse_encode_bool(self.isDegraded, serializer); + } + + @protected + void sse_encode_bool(bool self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putUint8(self ? 1 : 0); + } + + @protected + void sse_encode_box_autoadd_battery_info( + BatteryInfo self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_battery_info(self, serializer); + } + + @protected + void sse_encode_box_autoadd_f_32(double self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_f_32(self, serializer); + } + + @protected + void sse_encode_box_autoadd_f_64(double self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_f_64(self, serializer); + } + + @protected + void sse_encode_box_autoadd_fix_suggestion( + FixSuggestion self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_fix_suggestion(self, serializer); + } + + @protected + void sse_encode_box_autoadd_i_32(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self, serializer); + } + + @protected + void sse_encode_box_autoadd_system_report( + SystemReport self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_system_report(self, serializer); + } + + @protected + void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_u_32(self, serializer); + } + + @protected + void sse_encode_box_autoadd_u_64(BigInt self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_u_64(self, serializer); + } + + @protected + void sse_encode_box_autoadd_u_8(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_u_8(self, serializer); + } + + @protected + void sse_encode_cpu_info(CpuInfo self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.modelName, serializer); + sse_encode_String(self.architecture, serializer); + sse_encode_usize(self.physicalCores, serializer); + sse_encode_usize(self.logicalThreads, serializer); + sse_encode_opt_box_autoadd_f_32(self.baseFrequencyMhz, serializer); + sse_encode_opt_box_autoadd_f_32(self.currentFrequencyMhz, serializer); + sse_encode_String(self.l1Cache, serializer); + sse_encode_String(self.l2Cache, serializer); + sse_encode_String(self.l3Cache, serializer); + sse_encode_opt_String(self.virtualization, serializer); + sse_encode_list_String(self.flags, serializer); + sse_encode_String(self.microcode, serializer); + } + + @protected + void sse_encode_crash_report_info( + CrashReportInfo self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.timestamp, serializer); + sse_encode_String(self.processName, serializer); + sse_encode_opt_box_autoadd_u_32(self.pid, serializer); + sse_encode_String(self.signalOrCode, serializer); + sse_encode_opt_String(self.faultModule, serializer); + sse_encode_String(self.stackTraceSnippet, serializer); + sse_encode_opt_String(self.dumpPath, serializer); + } + + @protected + void sse_encode_disk_info(DiskInfo self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.name, serializer); + sse_encode_String(self.model, serializer); + sse_encode_String(self.serial, serializer); + sse_encode_u_64(self.sizeBytes, serializer); + sse_encode_String(self.diskType, serializer); + sse_encode_opt_box_autoadd_u_32(self.rotationalSpeedRpm, serializer); + sse_encode_String(self.smartStatus, serializer); + sse_encode_opt_box_autoadd_u_8(self.healthPercent, serializer); + sse_encode_opt_box_autoadd_u_8(self.wearPercent, serializer); + sse_encode_opt_box_autoadd_u_8(self.nvmeWearPercent, serializer); + sse_encode_opt_box_autoadd_i_32(self.temperatureC, serializer); + sse_encode_opt_box_autoadd_u_64(self.powerOnHours, serializer); + sse_encode_opt_box_autoadd_u_64(self.powerCycleCount, serializer); + sse_encode_opt_box_autoadd_u_64(self.badSectorsCount, serializer); + sse_encode_opt_box_autoadd_f_64(self.totalWrittenTb, serializer); + sse_encode_list_partition_info(self.partitions, serializer); + } + + @protected + void sse_encode_f_32(double self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putFloat32(self); + } + + @protected + void sse_encode_f_64(double self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putFloat64(self); + } + + @protected + void sse_encode_failed_service(FailedService self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.name, serializer); + sse_encode_String(self.initSystem, serializer); + sse_encode_String(self.state, serializer); + sse_encode_String(self.description, serializer); + sse_encode_String(self.logs, serializer); + sse_encode_String(self.restartCommand, serializer); + sse_encode_String(self.statusCommand, serializer); + } + + @protected + void sse_encode_fix_suggestion(FixSuggestion self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.title, serializer); + sse_encode_String(self.command, serializer); + sse_encode_String(self.explanation, serializer); + } + + @protected + void sse_encode_gpu_info(GpuInfo self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.vendor, serializer); + sse_encode_String(self.model, serializer); + sse_encode_String(self.driver, serializer); + sse_encode_String(self.pciSlot, serializer); + } + + @protected + void sse_encode_hardware_info(HardwareInfo self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_cpu_info(self.cpu, serializer); + sse_encode_memory_info(self.memory, serializer); + sse_encode_motherboard_info(self.motherboard, serializer); + sse_encode_list_gpu_info(self.gpus, serializer); + sse_encode_list_disk_info(self.disks, serializer); + sse_encode_list_network_adapter_info(self.networkAdapters, serializer); + sse_encode_opt_box_autoadd_battery_info(self.battery, serializer); + sse_encode_thermals_info(self.thermals, serializer); + } + + @protected + void sse_encode_i_32(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putInt32(self); + } + + @protected + void sse_encode_issue_item(IssueItem self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.id, serializer); + sse_encode_String(self.title, serializer); + sse_encode_subsystem(self.subsystem, serializer); + sse_encode_severity(self.severity, serializer); + sse_encode_String(self.rootCause, serializer); + sse_encode_String(self.explanation, serializer); + sse_encode_opt_box_autoadd_fix_suggestion(self.fix, serializer); + sse_encode_String(self.rawLog, serializer); + sse_encode_bool(self.sanitized, serializer); + sse_encode_bool(self.permissionDenied, serializer); + } + + @protected + void sse_encode_list_String(List self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_String(item, serializer); + } + } + + @protected + void sse_encode_list_crash_report_info( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_crash_report_info(item, serializer); + } + } + + @protected + void sse_encode_list_disk_info( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_disk_info(item, serializer); + } + } + + @protected + void sse_encode_list_failed_service( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_failed_service(item, serializer); + } + } + + @protected + void sse_encode_list_gpu_info(List self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_gpu_info(item, serializer); + } + } + + @protected + void sse_encode_list_issue_item( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_issue_item(item, serializer); + } + } + + @protected + void sse_encode_list_listening_port_info( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_listening_port_info(item, serializer); + } + } + + @protected + void sse_encode_list_network_adapter_info( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_network_adapter_info(item, serializer); + } + } + + @protected + void sse_encode_list_partition_info( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_partition_info(item, serializer); + } + } + + @protected + void sse_encode_list_prim_u_8_strict( + Uint8List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + serializer.buffer.putUint8List(self); + } + + @protected + void sse_encode_list_security_check_item( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_security_check_item(item, serializer); + } + } + + @protected + void sse_encode_list_subsystem_status( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_subsystem_status(item, serializer); + } + } + + @protected + void sse_encode_list_suid_anomaly_info( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_suid_anomaly_info(item, serializer); + } + } + + @protected + void sse_encode_listening_port_info( + ListeningPortInfo self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.protocol, serializer); + sse_encode_String(self.localAddress, serializer); + sse_encode_u_16(self.port, serializer); + sse_encode_String(self.processName, serializer); + sse_encode_opt_box_autoadd_u_32(self.pid, serializer); + sse_encode_bool(self.isPublic, serializer); + sse_encode_severity(self.riskLevel, serializer); + sse_encode_String(self.recommendation, serializer); + } + + @protected + void sse_encode_live_metrics_snapshot( + LiveMetricsSnapshot self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_f_32(self.cpuUsagePercent, serializer); + sse_encode_u_64(self.ramUsedBytes, serializer); + sse_encode_u_64(self.ramTotalBytes, serializer); + sse_encode_u_64(self.swapUsedBytes, serializer); + sse_encode_u_64(self.swapTotalBytes, serializer); + sse_encode_f_32(self.maxCpuTempC, serializer); + sse_encode_bool(self.isThrottling, serializer); + sse_encode_u_64(self.diskReadKbps, serializer); + sse_encode_u_64(self.diskWriteKbps, serializer); + sse_encode_u_64(self.netRxKbps, serializer); + sse_encode_u_64(self.netTxKbps, serializer); + } + + @protected + void sse_encode_memory_info(MemoryInfo self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_u_64(self.totalBytes, serializer); + sse_encode_u_64(self.availableBytes, serializer); + sse_encode_u_64(self.usedBytes, serializer); + sse_encode_u_64(self.swapTotalBytes, serializer); + sse_encode_u_64(self.swapUsedBytes, serializer); + sse_encode_u_64(self.edacCeCount, serializer); + sse_encode_u_64(self.edacUeCount, serializer); + } + + @protected + void sse_encode_motherboard_info( + MotherboardInfo self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.vendor, serializer); + sse_encode_String(self.productName, serializer); + sse_encode_String(self.version, serializer); + sse_encode_String(self.biosVendor, serializer); + sse_encode_String(self.biosVersion, serializer); + sse_encode_String(self.biosDate, serializer); + sse_encode_String(self.chassisType, serializer); + } + + @protected + void sse_encode_network_adapter_info( + NetworkAdapterInfo self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.interfaceName, serializer); + sse_encode_String(self.ifType, serializer); + sse_encode_String(self.state, serializer); + sse_encode_opt_box_autoadd_u_32(self.speedMbps, serializer); + sse_encode_String(self.macAddress, serializer); + sse_encode_String(self.driver, serializer); + } + + @protected + void sse_encode_opt_String(String? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_String(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_battery_info( + BatteryInfo? self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_battery_info(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_f_32(double? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_f_32(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_f_64(double? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_f_64(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_fix_suggestion( + FixSuggestion? self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_fix_suggestion(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_i_32(int? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_i_32(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_u_32(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_u_64(self, serializer); + } + } + + @protected + void sse_encode_opt_box_autoadd_u_8(int? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_u_8(self, serializer); + } + } + + @protected + void sse_encode_partition_info(PartitionInfo self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.name, serializer); + sse_encode_String(self.path, serializer); + sse_encode_opt_String(self.mountPoint, serializer); + sse_encode_String(self.fsType, serializer); + sse_encode_u_64(self.sizeBytes, serializer); + sse_encode_u_64(self.usedBytes, serializer); + } + + @protected + void sse_encode_security_audit_report( + SecurityAuditReport self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_list_listening_port_info(self.exposedPorts, serializer); + sse_encode_list_suid_anomaly_info(self.suidAnomalies, serializer); + sse_encode_list_security_check_item(self.hardeningChecks, serializer); + sse_encode_u_8(self.securityScore, serializer); + } + + @protected + void sse_encode_security_check_item( + SecurityCheckItem self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.category, serializer); + sse_encode_String(self.name, serializer); + sse_encode_String(self.status, serializer); + sse_encode_bool(self.isSecure, serializer); + sse_encode_String(self.description, serializer); + sse_encode_opt_String(self.remediation, serializer); + } + + @protected + void sse_encode_severity(Severity self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.index, serializer); + } + + @protected + void sse_encode_subsystem(Subsystem self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.index, serializer); + } + + @protected + void sse_encode_subsystem_status( + SubsystemStatus self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_subsystem(self.name, serializer); + sse_encode_String(self.status, serializer); + sse_encode_u_32(self.issueCount, serializer); + sse_encode_String(self.details, serializer); + } + + @protected + void sse_encode_suid_anomaly_info( + SuidAnomalyInfo self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.path, serializer); + sse_encode_String(self.owner, serializer); + sse_encode_String(self.permissions, serializer); + sse_encode_String(self.riskReason, serializer); + } + + @protected + void sse_encode_system_report(SystemReport self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.timestamp, serializer); + sse_encode_String(self.osFamily, serializer); + sse_encode_String(self.initSystem, serializer); + sse_encode_bool(self.isRoot, serializer); + sse_encode_list_subsystem_status(self.subsystems, serializer); + sse_encode_list_issue_item(self.issues, serializer); + sse_encode_list_failed_service(self.failedServices, serializer); + sse_encode_hardware_info(self.hardware, serializer); + sse_encode_list_crash_report_info(self.crashes, serializer); + sse_encode_security_audit_report(self.security, serializer); + sse_encode_bool(self.llmAnalyzed, serializer); + sse_encode_String(self.summary, serializer); + sse_encode_String(self.promptPreview, serializer); + } + + @protected + void sse_encode_thermals_info(ThermalsInfo self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_f_32(self.maxCpuTempC, serializer); + sse_encode_usize(self.thermalThrottledCores, serializer); + sse_encode_u_64(self.totalThrottleEvents, serializer); + sse_encode_bool(self.isActivelyThrottling, serializer); + } + + @protected + void sse_encode_u_16(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putUint16(self); + } + + @protected + void sse_encode_u_32(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putUint32(self); + } + + @protected + void sse_encode_u_64(BigInt self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putBigUint64(self); + } + + @protected + void sse_encode_u_8(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putUint8(self); + } + + @protected + void sse_encode_unit(void self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + } + + @protected + void sse_encode_usize(BigInt self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + serializer.buffer.putBigUint64(self); + } +} diff --git a/lib/src/rust/frb_generated.io.dart b/lib/src/rust/frb_generated.io.dart new file mode 100644 index 0000000..05dbb69 --- /dev/null +++ b/lib/src/rust/frb_generated.io.dart @@ -0,0 +1,730 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field + +import 'api/diagnostics.dart'; +import 'api/simple.dart'; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi' as ffi; + +import 'frb_generated.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_io.dart'; + +abstract class RustLibApiImplPlatform extends BaseApiImpl { + RustLibApiImplPlatform({ + required super.handler, + required super.wire, + required super.generalizedFrbRustBinding, + required super.portManager, + }); + + @protected + String dco_decode_String(dynamic raw); + + @protected + BatteryInfo dco_decode_battery_info(dynamic raw); + + @protected + bool dco_decode_bool(dynamic raw); + + @protected + BatteryInfo dco_decode_box_autoadd_battery_info(dynamic raw); + + @protected + double dco_decode_box_autoadd_f_32(dynamic raw); + + @protected + double dco_decode_box_autoadd_f_64(dynamic raw); + + @protected + FixSuggestion dco_decode_box_autoadd_fix_suggestion(dynamic raw); + + @protected + int dco_decode_box_autoadd_i_32(dynamic raw); + + @protected + SystemReport dco_decode_box_autoadd_system_report(dynamic raw); + + @protected + int dco_decode_box_autoadd_u_32(dynamic raw); + + @protected + BigInt dco_decode_box_autoadd_u_64(dynamic raw); + + @protected + int dco_decode_box_autoadd_u_8(dynamic raw); + + @protected + CpuInfo dco_decode_cpu_info(dynamic raw); + + @protected + CrashReportInfo dco_decode_crash_report_info(dynamic raw); + + @protected + DiskInfo dco_decode_disk_info(dynamic raw); + + @protected + double dco_decode_f_32(dynamic raw); + + @protected + double dco_decode_f_64(dynamic raw); + + @protected + FailedService dco_decode_failed_service(dynamic raw); + + @protected + FixSuggestion dco_decode_fix_suggestion(dynamic raw); + + @protected + GpuInfo dco_decode_gpu_info(dynamic raw); + + @protected + HardwareInfo dco_decode_hardware_info(dynamic raw); + + @protected + int dco_decode_i_32(dynamic raw); + + @protected + IssueItem dco_decode_issue_item(dynamic raw); + + @protected + List dco_decode_list_String(dynamic raw); + + @protected + List dco_decode_list_crash_report_info(dynamic raw); + + @protected + List dco_decode_list_disk_info(dynamic raw); + + @protected + List dco_decode_list_failed_service(dynamic raw); + + @protected + List dco_decode_list_gpu_info(dynamic raw); + + @protected + List dco_decode_list_issue_item(dynamic raw); + + @protected + List dco_decode_list_listening_port_info(dynamic raw); + + @protected + List dco_decode_list_network_adapter_info(dynamic raw); + + @protected + List dco_decode_list_partition_info(dynamic raw); + + @protected + Uint8List dco_decode_list_prim_u_8_strict(dynamic raw); + + @protected + List dco_decode_list_security_check_item(dynamic raw); + + @protected + List dco_decode_list_subsystem_status(dynamic raw); + + @protected + List dco_decode_list_suid_anomaly_info(dynamic raw); + + @protected + ListeningPortInfo dco_decode_listening_port_info(dynamic raw); + + @protected + LiveMetricsSnapshot dco_decode_live_metrics_snapshot(dynamic raw); + + @protected + MemoryInfo dco_decode_memory_info(dynamic raw); + + @protected + MotherboardInfo dco_decode_motherboard_info(dynamic raw); + + @protected + NetworkAdapterInfo dco_decode_network_adapter_info(dynamic raw); + + @protected + String? dco_decode_opt_String(dynamic raw); + + @protected + BatteryInfo? dco_decode_opt_box_autoadd_battery_info(dynamic raw); + + @protected + double? dco_decode_opt_box_autoadd_f_32(dynamic raw); + + @protected + double? dco_decode_opt_box_autoadd_f_64(dynamic raw); + + @protected + FixSuggestion? dco_decode_opt_box_autoadd_fix_suggestion(dynamic raw); + + @protected + int? dco_decode_opt_box_autoadd_i_32(dynamic raw); + + @protected + int? dco_decode_opt_box_autoadd_u_32(dynamic raw); + + @protected + BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw); + + @protected + int? dco_decode_opt_box_autoadd_u_8(dynamic raw); + + @protected + PartitionInfo dco_decode_partition_info(dynamic raw); + + @protected + SecurityAuditReport dco_decode_security_audit_report(dynamic raw); + + @protected + SecurityCheckItem dco_decode_security_check_item(dynamic raw); + + @protected + Severity dco_decode_severity(dynamic raw); + + @protected + Subsystem dco_decode_subsystem(dynamic raw); + + @protected + SubsystemStatus dco_decode_subsystem_status(dynamic raw); + + @protected + SuidAnomalyInfo dco_decode_suid_anomaly_info(dynamic raw); + + @protected + SystemReport dco_decode_system_report(dynamic raw); + + @protected + ThermalsInfo dco_decode_thermals_info(dynamic raw); + + @protected + int dco_decode_u_16(dynamic raw); + + @protected + int dco_decode_u_32(dynamic raw); + + @protected + BigInt dco_decode_u_64(dynamic raw); + + @protected + int dco_decode_u_8(dynamic raw); + + @protected + void dco_decode_unit(dynamic raw); + + @protected + BigInt dco_decode_usize(dynamic raw); + + @protected + String sse_decode_String(SseDeserializer deserializer); + + @protected + BatteryInfo sse_decode_battery_info(SseDeserializer deserializer); + + @protected + bool sse_decode_bool(SseDeserializer deserializer); + + @protected + BatteryInfo sse_decode_box_autoadd_battery_info(SseDeserializer deserializer); + + @protected + double sse_decode_box_autoadd_f_32(SseDeserializer deserializer); + + @protected + double sse_decode_box_autoadd_f_64(SseDeserializer deserializer); + + @protected + FixSuggestion sse_decode_box_autoadd_fix_suggestion( + SseDeserializer deserializer, + ); + + @protected + int sse_decode_box_autoadd_i_32(SseDeserializer deserializer); + + @protected + SystemReport sse_decode_box_autoadd_system_report( + SseDeserializer deserializer, + ); + + @protected + int sse_decode_box_autoadd_u_32(SseDeserializer deserializer); + + @protected + BigInt sse_decode_box_autoadd_u_64(SseDeserializer deserializer); + + @protected + int sse_decode_box_autoadd_u_8(SseDeserializer deserializer); + + @protected + CpuInfo sse_decode_cpu_info(SseDeserializer deserializer); + + @protected + CrashReportInfo sse_decode_crash_report_info(SseDeserializer deserializer); + + @protected + DiskInfo sse_decode_disk_info(SseDeserializer deserializer); + + @protected + double sse_decode_f_32(SseDeserializer deserializer); + + @protected + double sse_decode_f_64(SseDeserializer deserializer); + + @protected + FailedService sse_decode_failed_service(SseDeserializer deserializer); + + @protected + FixSuggestion sse_decode_fix_suggestion(SseDeserializer deserializer); + + @protected + GpuInfo sse_decode_gpu_info(SseDeserializer deserializer); + + @protected + HardwareInfo sse_decode_hardware_info(SseDeserializer deserializer); + + @protected + int sse_decode_i_32(SseDeserializer deserializer); + + @protected + IssueItem sse_decode_issue_item(SseDeserializer deserializer); + + @protected + List sse_decode_list_String(SseDeserializer deserializer); + + @protected + List sse_decode_list_crash_report_info( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_disk_info(SseDeserializer deserializer); + + @protected + List sse_decode_list_failed_service( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_gpu_info(SseDeserializer deserializer); + + @protected + List sse_decode_list_issue_item(SseDeserializer deserializer); + + @protected + List sse_decode_list_listening_port_info( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_network_adapter_info( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_partition_info( + SseDeserializer deserializer, + ); + + @protected + Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer); + + @protected + List sse_decode_list_security_check_item( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_subsystem_status( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_suid_anomaly_info( + SseDeserializer deserializer, + ); + + @protected + ListeningPortInfo sse_decode_listening_port_info( + SseDeserializer deserializer, + ); + + @protected + LiveMetricsSnapshot sse_decode_live_metrics_snapshot( + SseDeserializer deserializer, + ); + + @protected + MemoryInfo sse_decode_memory_info(SseDeserializer deserializer); + + @protected + MotherboardInfo sse_decode_motherboard_info(SseDeserializer deserializer); + + @protected + NetworkAdapterInfo sse_decode_network_adapter_info( + SseDeserializer deserializer, + ); + + @protected + String? sse_decode_opt_String(SseDeserializer deserializer); + + @protected + BatteryInfo? sse_decode_opt_box_autoadd_battery_info( + SseDeserializer deserializer, + ); + + @protected + double? sse_decode_opt_box_autoadd_f_32(SseDeserializer deserializer); + + @protected + double? sse_decode_opt_box_autoadd_f_64(SseDeserializer deserializer); + + @protected + FixSuggestion? sse_decode_opt_box_autoadd_fix_suggestion( + SseDeserializer deserializer, + ); + + @protected + int? sse_decode_opt_box_autoadd_i_32(SseDeserializer deserializer); + + @protected + int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer); + + @protected + BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer); + + @protected + int? sse_decode_opt_box_autoadd_u_8(SseDeserializer deserializer); + + @protected + PartitionInfo sse_decode_partition_info(SseDeserializer deserializer); + + @protected + SecurityAuditReport sse_decode_security_audit_report( + SseDeserializer deserializer, + ); + + @protected + SecurityCheckItem sse_decode_security_check_item( + SseDeserializer deserializer, + ); + + @protected + Severity sse_decode_severity(SseDeserializer deserializer); + + @protected + Subsystem sse_decode_subsystem(SseDeserializer deserializer); + + @protected + SubsystemStatus sse_decode_subsystem_status(SseDeserializer deserializer); + + @protected + SuidAnomalyInfo sse_decode_suid_anomaly_info(SseDeserializer deserializer); + + @protected + SystemReport sse_decode_system_report(SseDeserializer deserializer); + + @protected + ThermalsInfo sse_decode_thermals_info(SseDeserializer deserializer); + + @protected + int sse_decode_u_16(SseDeserializer deserializer); + + @protected + int sse_decode_u_32(SseDeserializer deserializer); + + @protected + BigInt sse_decode_u_64(SseDeserializer deserializer); + + @protected + int sse_decode_u_8(SseDeserializer deserializer); + + @protected + void sse_decode_unit(SseDeserializer deserializer); + + @protected + BigInt sse_decode_usize(SseDeserializer deserializer); + + @protected + void sse_encode_String(String self, SseSerializer serializer); + + @protected + void sse_encode_battery_info(BatteryInfo self, SseSerializer serializer); + + @protected + void sse_encode_bool(bool self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_battery_info( + BatteryInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_f_32(double self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_f_64(double self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_fix_suggestion( + FixSuggestion self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_i_32(int self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_system_report( + SystemReport self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_u_64(BigInt self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_u_8(int self, SseSerializer serializer); + + @protected + void sse_encode_cpu_info(CpuInfo self, SseSerializer serializer); + + @protected + void sse_encode_crash_report_info( + CrashReportInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_disk_info(DiskInfo self, SseSerializer serializer); + + @protected + void sse_encode_f_32(double self, SseSerializer serializer); + + @protected + void sse_encode_f_64(double self, SseSerializer serializer); + + @protected + void sse_encode_failed_service(FailedService self, SseSerializer serializer); + + @protected + void sse_encode_fix_suggestion(FixSuggestion self, SseSerializer serializer); + + @protected + void sse_encode_gpu_info(GpuInfo self, SseSerializer serializer); + + @protected + void sse_encode_hardware_info(HardwareInfo self, SseSerializer serializer); + + @protected + void sse_encode_i_32(int self, SseSerializer serializer); + + @protected + void sse_encode_issue_item(IssueItem self, SseSerializer serializer); + + @protected + void sse_encode_list_String(List self, SseSerializer serializer); + + @protected + void sse_encode_list_crash_report_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_disk_info(List self, SseSerializer serializer); + + @protected + void sse_encode_list_failed_service( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_gpu_info(List self, SseSerializer serializer); + + @protected + void sse_encode_list_issue_item( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_listening_port_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_network_adapter_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_partition_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_prim_u_8_strict( + Uint8List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_security_check_item( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_subsystem_status( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_suid_anomaly_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_listening_port_info( + ListeningPortInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_live_metrics_snapshot( + LiveMetricsSnapshot self, + SseSerializer serializer, + ); + + @protected + void sse_encode_memory_info(MemoryInfo self, SseSerializer serializer); + + @protected + void sse_encode_motherboard_info( + MotherboardInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_network_adapter_info( + NetworkAdapterInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_opt_String(String? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_battery_info( + BatteryInfo? self, + SseSerializer serializer, + ); + + @protected + void sse_encode_opt_box_autoadd_f_32(double? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_f_64(double? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_fix_suggestion( + FixSuggestion? self, + SseSerializer serializer, + ); + + @protected + void sse_encode_opt_box_autoadd_i_32(int? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_u_8(int? self, SseSerializer serializer); + + @protected + void sse_encode_partition_info(PartitionInfo self, SseSerializer serializer); + + @protected + void sse_encode_security_audit_report( + SecurityAuditReport self, + SseSerializer serializer, + ); + + @protected + void sse_encode_security_check_item( + SecurityCheckItem self, + SseSerializer serializer, + ); + + @protected + void sse_encode_severity(Severity self, SseSerializer serializer); + + @protected + void sse_encode_subsystem(Subsystem self, SseSerializer serializer); + + @protected + void sse_encode_subsystem_status( + SubsystemStatus self, + SseSerializer serializer, + ); + + @protected + void sse_encode_suid_anomaly_info( + SuidAnomalyInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_system_report(SystemReport self, SseSerializer serializer); + + @protected + void sse_encode_thermals_info(ThermalsInfo self, SseSerializer serializer); + + @protected + void sse_encode_u_16(int self, SseSerializer serializer); + + @protected + void sse_encode_u_32(int self, SseSerializer serializer); + + @protected + void sse_encode_u_64(BigInt self, SseSerializer serializer); + + @protected + void sse_encode_u_8(int self, SseSerializer serializer); + + @protected + void sse_encode_unit(void self, SseSerializer serializer); + + @protected + void sse_encode_usize(BigInt self, SseSerializer serializer); +} + +// Section: wire_class + +class RustLibWire implements BaseWire { + factory RustLibWire.fromExternalLibrary(ExternalLibrary lib) => + RustLibWire(lib.ffiDynamicLibrary); + + /// Holds the symbol lookup function. + final ffi.Pointer Function(String symbolName) + _lookup; + + /// The symbols are looked up in [dynamicLibrary]. + RustLibWire(ffi.DynamicLibrary dynamicLibrary) + : _lookup = dynamicLibrary.lookup; +} diff --git a/lib/src/rust/frb_generated.web.dart b/lib/src/rust/frb_generated.web.dart new file mode 100644 index 0000000..5f69a51 --- /dev/null +++ b/lib/src/rust/frb_generated.web.dart @@ -0,0 +1,730 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +// ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field + +// Static analysis wrongly picks the IO variant, thus ignore this +// ignore_for_file: argument_type_not_assignable + +import 'api/diagnostics.dart'; +import 'api/simple.dart'; + +import 'dart:async'; +import 'dart:convert'; + +import 'frb_generated.dart'; + +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_web.dart'; + +abstract class RustLibApiImplPlatform extends BaseApiImpl { + RustLibApiImplPlatform({ + required super.handler, + required super.wire, + required super.generalizedFrbRustBinding, + required super.portManager, + }); + + @protected + String dco_decode_String(dynamic raw); + + @protected + BatteryInfo dco_decode_battery_info(dynamic raw); + + @protected + bool dco_decode_bool(dynamic raw); + + @protected + BatteryInfo dco_decode_box_autoadd_battery_info(dynamic raw); + + @protected + double dco_decode_box_autoadd_f_32(dynamic raw); + + @protected + double dco_decode_box_autoadd_f_64(dynamic raw); + + @protected + FixSuggestion dco_decode_box_autoadd_fix_suggestion(dynamic raw); + + @protected + int dco_decode_box_autoadd_i_32(dynamic raw); + + @protected + SystemReport dco_decode_box_autoadd_system_report(dynamic raw); + + @protected + int dco_decode_box_autoadd_u_32(dynamic raw); + + @protected + BigInt dco_decode_box_autoadd_u_64(dynamic raw); + + @protected + int dco_decode_box_autoadd_u_8(dynamic raw); + + @protected + CpuInfo dco_decode_cpu_info(dynamic raw); + + @protected + CrashReportInfo dco_decode_crash_report_info(dynamic raw); + + @protected + DiskInfo dco_decode_disk_info(dynamic raw); + + @protected + double dco_decode_f_32(dynamic raw); + + @protected + double dco_decode_f_64(dynamic raw); + + @protected + FailedService dco_decode_failed_service(dynamic raw); + + @protected + FixSuggestion dco_decode_fix_suggestion(dynamic raw); + + @protected + GpuInfo dco_decode_gpu_info(dynamic raw); + + @protected + HardwareInfo dco_decode_hardware_info(dynamic raw); + + @protected + int dco_decode_i_32(dynamic raw); + + @protected + IssueItem dco_decode_issue_item(dynamic raw); + + @protected + List dco_decode_list_String(dynamic raw); + + @protected + List dco_decode_list_crash_report_info(dynamic raw); + + @protected + List dco_decode_list_disk_info(dynamic raw); + + @protected + List dco_decode_list_failed_service(dynamic raw); + + @protected + List dco_decode_list_gpu_info(dynamic raw); + + @protected + List dco_decode_list_issue_item(dynamic raw); + + @protected + List dco_decode_list_listening_port_info(dynamic raw); + + @protected + List dco_decode_list_network_adapter_info(dynamic raw); + + @protected + List dco_decode_list_partition_info(dynamic raw); + + @protected + Uint8List dco_decode_list_prim_u_8_strict(dynamic raw); + + @protected + List dco_decode_list_security_check_item(dynamic raw); + + @protected + List dco_decode_list_subsystem_status(dynamic raw); + + @protected + List dco_decode_list_suid_anomaly_info(dynamic raw); + + @protected + ListeningPortInfo dco_decode_listening_port_info(dynamic raw); + + @protected + LiveMetricsSnapshot dco_decode_live_metrics_snapshot(dynamic raw); + + @protected + MemoryInfo dco_decode_memory_info(dynamic raw); + + @protected + MotherboardInfo dco_decode_motherboard_info(dynamic raw); + + @protected + NetworkAdapterInfo dco_decode_network_adapter_info(dynamic raw); + + @protected + String? dco_decode_opt_String(dynamic raw); + + @protected + BatteryInfo? dco_decode_opt_box_autoadd_battery_info(dynamic raw); + + @protected + double? dco_decode_opt_box_autoadd_f_32(dynamic raw); + + @protected + double? dco_decode_opt_box_autoadd_f_64(dynamic raw); + + @protected + FixSuggestion? dco_decode_opt_box_autoadd_fix_suggestion(dynamic raw); + + @protected + int? dco_decode_opt_box_autoadd_i_32(dynamic raw); + + @protected + int? dco_decode_opt_box_autoadd_u_32(dynamic raw); + + @protected + BigInt? dco_decode_opt_box_autoadd_u_64(dynamic raw); + + @protected + int? dco_decode_opt_box_autoadd_u_8(dynamic raw); + + @protected + PartitionInfo dco_decode_partition_info(dynamic raw); + + @protected + SecurityAuditReport dco_decode_security_audit_report(dynamic raw); + + @protected + SecurityCheckItem dco_decode_security_check_item(dynamic raw); + + @protected + Severity dco_decode_severity(dynamic raw); + + @protected + Subsystem dco_decode_subsystem(dynamic raw); + + @protected + SubsystemStatus dco_decode_subsystem_status(dynamic raw); + + @protected + SuidAnomalyInfo dco_decode_suid_anomaly_info(dynamic raw); + + @protected + SystemReport dco_decode_system_report(dynamic raw); + + @protected + ThermalsInfo dco_decode_thermals_info(dynamic raw); + + @protected + int dco_decode_u_16(dynamic raw); + + @protected + int dco_decode_u_32(dynamic raw); + + @protected + BigInt dco_decode_u_64(dynamic raw); + + @protected + int dco_decode_u_8(dynamic raw); + + @protected + void dco_decode_unit(dynamic raw); + + @protected + BigInt dco_decode_usize(dynamic raw); + + @protected + String sse_decode_String(SseDeserializer deserializer); + + @protected + BatteryInfo sse_decode_battery_info(SseDeserializer deserializer); + + @protected + bool sse_decode_bool(SseDeserializer deserializer); + + @protected + BatteryInfo sse_decode_box_autoadd_battery_info(SseDeserializer deserializer); + + @protected + double sse_decode_box_autoadd_f_32(SseDeserializer deserializer); + + @protected + double sse_decode_box_autoadd_f_64(SseDeserializer deserializer); + + @protected + FixSuggestion sse_decode_box_autoadd_fix_suggestion( + SseDeserializer deserializer, + ); + + @protected + int sse_decode_box_autoadd_i_32(SseDeserializer deserializer); + + @protected + SystemReport sse_decode_box_autoadd_system_report( + SseDeserializer deserializer, + ); + + @protected + int sse_decode_box_autoadd_u_32(SseDeserializer deserializer); + + @protected + BigInt sse_decode_box_autoadd_u_64(SseDeserializer deserializer); + + @protected + int sse_decode_box_autoadd_u_8(SseDeserializer deserializer); + + @protected + CpuInfo sse_decode_cpu_info(SseDeserializer deserializer); + + @protected + CrashReportInfo sse_decode_crash_report_info(SseDeserializer deserializer); + + @protected + DiskInfo sse_decode_disk_info(SseDeserializer deserializer); + + @protected + double sse_decode_f_32(SseDeserializer deserializer); + + @protected + double sse_decode_f_64(SseDeserializer deserializer); + + @protected + FailedService sse_decode_failed_service(SseDeserializer deserializer); + + @protected + FixSuggestion sse_decode_fix_suggestion(SseDeserializer deserializer); + + @protected + GpuInfo sse_decode_gpu_info(SseDeserializer deserializer); + + @protected + HardwareInfo sse_decode_hardware_info(SseDeserializer deserializer); + + @protected + int sse_decode_i_32(SseDeserializer deserializer); + + @protected + IssueItem sse_decode_issue_item(SseDeserializer deserializer); + + @protected + List sse_decode_list_String(SseDeserializer deserializer); + + @protected + List sse_decode_list_crash_report_info( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_disk_info(SseDeserializer deserializer); + + @protected + List sse_decode_list_failed_service( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_gpu_info(SseDeserializer deserializer); + + @protected + List sse_decode_list_issue_item(SseDeserializer deserializer); + + @protected + List sse_decode_list_listening_port_info( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_network_adapter_info( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_partition_info( + SseDeserializer deserializer, + ); + + @protected + Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer); + + @protected + List sse_decode_list_security_check_item( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_subsystem_status( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_suid_anomaly_info( + SseDeserializer deserializer, + ); + + @protected + ListeningPortInfo sse_decode_listening_port_info( + SseDeserializer deserializer, + ); + + @protected + LiveMetricsSnapshot sse_decode_live_metrics_snapshot( + SseDeserializer deserializer, + ); + + @protected + MemoryInfo sse_decode_memory_info(SseDeserializer deserializer); + + @protected + MotherboardInfo sse_decode_motherboard_info(SseDeserializer deserializer); + + @protected + NetworkAdapterInfo sse_decode_network_adapter_info( + SseDeserializer deserializer, + ); + + @protected + String? sse_decode_opt_String(SseDeserializer deserializer); + + @protected + BatteryInfo? sse_decode_opt_box_autoadd_battery_info( + SseDeserializer deserializer, + ); + + @protected + double? sse_decode_opt_box_autoadd_f_32(SseDeserializer deserializer); + + @protected + double? sse_decode_opt_box_autoadd_f_64(SseDeserializer deserializer); + + @protected + FixSuggestion? sse_decode_opt_box_autoadd_fix_suggestion( + SseDeserializer deserializer, + ); + + @protected + int? sse_decode_opt_box_autoadd_i_32(SseDeserializer deserializer); + + @protected + int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer); + + @protected + BigInt? sse_decode_opt_box_autoadd_u_64(SseDeserializer deserializer); + + @protected + int? sse_decode_opt_box_autoadd_u_8(SseDeserializer deserializer); + + @protected + PartitionInfo sse_decode_partition_info(SseDeserializer deserializer); + + @protected + SecurityAuditReport sse_decode_security_audit_report( + SseDeserializer deserializer, + ); + + @protected + SecurityCheckItem sse_decode_security_check_item( + SseDeserializer deserializer, + ); + + @protected + Severity sse_decode_severity(SseDeserializer deserializer); + + @protected + Subsystem sse_decode_subsystem(SseDeserializer deserializer); + + @protected + SubsystemStatus sse_decode_subsystem_status(SseDeserializer deserializer); + + @protected + SuidAnomalyInfo sse_decode_suid_anomaly_info(SseDeserializer deserializer); + + @protected + SystemReport sse_decode_system_report(SseDeserializer deserializer); + + @protected + ThermalsInfo sse_decode_thermals_info(SseDeserializer deserializer); + + @protected + int sse_decode_u_16(SseDeserializer deserializer); + + @protected + int sse_decode_u_32(SseDeserializer deserializer); + + @protected + BigInt sse_decode_u_64(SseDeserializer deserializer); + + @protected + int sse_decode_u_8(SseDeserializer deserializer); + + @protected + void sse_decode_unit(SseDeserializer deserializer); + + @protected + BigInt sse_decode_usize(SseDeserializer deserializer); + + @protected + void sse_encode_String(String self, SseSerializer serializer); + + @protected + void sse_encode_battery_info(BatteryInfo self, SseSerializer serializer); + + @protected + void sse_encode_bool(bool self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_battery_info( + BatteryInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_f_32(double self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_f_64(double self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_fix_suggestion( + FixSuggestion self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_i_32(int self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_system_report( + SystemReport self, + SseSerializer serializer, + ); + + @protected + void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_u_64(BigInt self, SseSerializer serializer); + + @protected + void sse_encode_box_autoadd_u_8(int self, SseSerializer serializer); + + @protected + void sse_encode_cpu_info(CpuInfo self, SseSerializer serializer); + + @protected + void sse_encode_crash_report_info( + CrashReportInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_disk_info(DiskInfo self, SseSerializer serializer); + + @protected + void sse_encode_f_32(double self, SseSerializer serializer); + + @protected + void sse_encode_f_64(double self, SseSerializer serializer); + + @protected + void sse_encode_failed_service(FailedService self, SseSerializer serializer); + + @protected + void sse_encode_fix_suggestion(FixSuggestion self, SseSerializer serializer); + + @protected + void sse_encode_gpu_info(GpuInfo self, SseSerializer serializer); + + @protected + void sse_encode_hardware_info(HardwareInfo self, SseSerializer serializer); + + @protected + void sse_encode_i_32(int self, SseSerializer serializer); + + @protected + void sse_encode_issue_item(IssueItem self, SseSerializer serializer); + + @protected + void sse_encode_list_String(List self, SseSerializer serializer); + + @protected + void sse_encode_list_crash_report_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_disk_info(List self, SseSerializer serializer); + + @protected + void sse_encode_list_failed_service( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_gpu_info(List self, SseSerializer serializer); + + @protected + void sse_encode_list_issue_item( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_listening_port_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_network_adapter_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_partition_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_prim_u_8_strict( + Uint8List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_security_check_item( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_subsystem_status( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_suid_anomaly_info( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_listening_port_info( + ListeningPortInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_live_metrics_snapshot( + LiveMetricsSnapshot self, + SseSerializer serializer, + ); + + @protected + void sse_encode_memory_info(MemoryInfo self, SseSerializer serializer); + + @protected + void sse_encode_motherboard_info( + MotherboardInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_network_adapter_info( + NetworkAdapterInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_opt_String(String? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_battery_info( + BatteryInfo? self, + SseSerializer serializer, + ); + + @protected + void sse_encode_opt_box_autoadd_f_32(double? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_f_64(double? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_fix_suggestion( + FixSuggestion? self, + SseSerializer serializer, + ); + + @protected + void sse_encode_opt_box_autoadd_i_32(int? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_u_64(BigInt? self, SseSerializer serializer); + + @protected + void sse_encode_opt_box_autoadd_u_8(int? self, SseSerializer serializer); + + @protected + void sse_encode_partition_info(PartitionInfo self, SseSerializer serializer); + + @protected + void sse_encode_security_audit_report( + SecurityAuditReport self, + SseSerializer serializer, + ); + + @protected + void sse_encode_security_check_item( + SecurityCheckItem self, + SseSerializer serializer, + ); + + @protected + void sse_encode_severity(Severity self, SseSerializer serializer); + + @protected + void sse_encode_subsystem(Subsystem self, SseSerializer serializer); + + @protected + void sse_encode_subsystem_status( + SubsystemStatus self, + SseSerializer serializer, + ); + + @protected + void sse_encode_suid_anomaly_info( + SuidAnomalyInfo self, + SseSerializer serializer, + ); + + @protected + void sse_encode_system_report(SystemReport self, SseSerializer serializer); + + @protected + void sse_encode_thermals_info(ThermalsInfo self, SseSerializer serializer); + + @protected + void sse_encode_u_16(int self, SseSerializer serializer); + + @protected + void sse_encode_u_32(int self, SseSerializer serializer); + + @protected + void sse_encode_u_64(BigInt self, SseSerializer serializer); + + @protected + void sse_encode_u_8(int self, SseSerializer serializer); + + @protected + void sse_encode_unit(void self, SseSerializer serializer); + + @protected + void sse_encode_usize(BigInt self, SseSerializer serializer); +} + +// Section: wire_class + +class RustLibWire implements BaseWire { + RustLibWire.fromExternalLibrary(ExternalLibrary lib); +} + +@JS('wasm_bindgen') +external RustLibWasmModule get wasmModule; + +@JS() +@anonymous +extension type RustLibWasmModule._(JSObject _) implements JSObject {} diff --git a/lib/widgets/crashes_tab.dart b/lib/widgets/crashes_tab.dart new file mode 100644 index 0000000..66a672d --- /dev/null +++ b/lib/widgets/crashes_tab.dart @@ -0,0 +1,486 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:diagd/src/rust/api/diagnostics.dart'; + +class CrashesTab extends StatefulWidget { + final List crashes; + + const CrashesTab({ + super.key, + required this.crashes, + }); + + @override + State createState() => _CrashesTabState(); +} + +class _CrashesTabState extends State { + int _selectedCrashIndex = 0; + + @override + Widget build(BuildContext context) { + if (widget.crashes.isEmpty) { + return Center( + child: Container( + constraints: const BoxConstraints(maxWidth: 550), + margin: const EdgeInsets.all(24), + padding: const EdgeInsets.all(32), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF238636).withAlpha(80)), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF238636).withAlpha(30), + shape: BoxShape.circle, + ), + child: const Icon( + Icons.verified_rounded, + color: Color(0xFF3FB950), + size: 44, + ), + ), + const SizedBox(height: 18), + const Text( + 'Аварийных падений не зафиксировано', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 8), + const Text( + 'В системных журналах coredumpctl, /var/crash, dmesg и crash reporter отсутствуют записи о падениях процессов по сигналам SIGSEGV, SIGABRT или сбоям ядра.', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 13, color: Color(0xFF8B949E), height: 1.4), + ), + ], + ), + ), + ); + } + + final selectedCrash = widget.crashes[_selectedCrashIndex.clamp(0, widget.crashes.length - 1)]; + + return LayoutBuilder( + builder: (context, constraints) { + final isWide = constraints.maxWidth > 850; + + if (isWide) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Left Column: Crash list + SizedBox( + width: 340, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildListHeader(), + const SizedBox(height: 10), + Expanded( + child: ListView.separated( + itemCount: widget.crashes.length, + separatorBuilder: (context, index) => const SizedBox(height: 8), + itemBuilder: (context, index) { + final crash = widget.crashes[index]; + final isSelected = index == _selectedCrashIndex; + return _buildCrashListItem(crash, isSelected, () { + setState(() { + _selectedCrashIndex = index; + }); + }); + }, + ), + ), + ], + ), + ), + const SizedBox(width: 20), + // Right Column: Crash details + Expanded( + child: SingleChildScrollView( + child: _buildCrashDetails(context, selectedCrash), + ), + ), + ], + ), + ); + } else { + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildListHeader(), + const SizedBox(height: 10), + SizedBox( + height: 180, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: widget.crashes.length, + separatorBuilder: (context, index) => const SizedBox(width: 10), + itemBuilder: (context, index) { + final crash = widget.crashes[index]; + final isSelected = index == _selectedCrashIndex; + return SizedBox( + width: 260, + child: _buildCrashListItem(crash, isSelected, () { + setState(() { + _selectedCrashIndex = index; + }); + }), + ); + }, + ), + ), + const SizedBox(height: 20), + _buildCrashDetails(context, selectedCrash), + ], + ), + ); + } + }, + ); + } + + Widget _buildListHeader() { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'ЖУРНАЛ АВАРИЙНЫХ СБОЕВ', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 1.2, + color: Color(0xFF8B949E), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFFF85149).withAlpha(25), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFF85149).withAlpha(70)), + ), + child: Text( + '${widget.crashes.length}', + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Color(0xFFF85149), + ), + ), + ), + ], + ); + } + + Widget _buildCrashListItem(CrashReportInfo crash, bool isSelected, VoidCallback onTap) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: isSelected ? const Color(0xFF21262D) : const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: isSelected ? const Color(0xFFF85149) : const Color(0xFF30363D), + width: isSelected ? 1.5 : 1.0, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFFF85149).withAlpha(30), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + crash.signalOrCode, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Color(0xFFF85149), + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + crash.processName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + ), + ], + ), + const SizedBox(height: 6), + Text( + crash.timestamp, + style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E)), + ), + if (crash.pid != null) ...[ + const SizedBox(height: 2), + Text( + 'PID: ${crash.pid}', + style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E), fontFamily: 'monospace'), + ), + ], + ], + ), + ), + ); + } + + Widget _buildCrashDetails(BuildContext context, CrashReportInfo crash) { + final debugCmd = crash.dumpPath != null && crash.dumpPath!.isNotEmpty + ? 'gdb ${crash.processName} ${crash.dumpPath!}' + : (crash.pid != null ? 'coredumpctl debug ${crash.pid}' : 'coredumpctl info ${crash.processName}'); + + return Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + const Icon(Icons.bug_report_rounded, color: Color(0xFFF85149), size: 24), + const SizedBox(width: 10), + Text( + crash.processName, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(width: 10), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: const Color(0xFFF85149).withAlpha(25), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: const Color(0xFFF85149).withAlpha(70)), + ), + child: Text( + crash.signalOrCode, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Color(0xFFF85149), + ), + ), + ), + ], + ), + if (crash.pid != null) + Text( + 'PID: ${crash.pid}', + style: const TextStyle( + fontSize: 13, + color: Color(0xFF8B949E), + fontFamily: 'monospace', + ), + ), + ], + ), + const SizedBox(height: 16), + + // Metadata Grid + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF0D1117), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF21262D)), + ), + child: Column( + children: [ + _buildMetaRow('Время падения:', crash.timestamp), + if (crash.faultModule != null && crash.faultModule!.isNotEmpty) + _buildMetaRow('Сбойный модуль:', crash.faultModule!), + if (crash.dumpPath != null && crash.dumpPath!.isNotEmpty) ...[ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox( + width: 130, + child: Text( + 'Файл Core Dump:', + style: TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ), + Expanded( + child: Text( + crash.dumpPath!, + style: const TextStyle( + fontSize: 12, + color: Color(0xFF58A6FF), + fontFamily: 'monospace', + ), + ), + ), + IconButton( + icon: const Icon(Icons.copy_rounded, size: 14, color: Color(0xFF8B949E)), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + tooltip: 'Копировать путь к дампу', + onPressed: () { + Clipboard.setData(ClipboardData(text: crash.dumpPath!)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Путь к Core Dump скопирован'), duration: Duration(seconds: 2)), + ); + }, + ), + ], + ), + ], + ], + ), + ), + const SizedBox(height: 20), + + // Debug CLI Command + const Text( + 'КОМАНДА ОТЛАДКИ (GDB / COREDUMPCTL)', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + letterSpacing: 1.0, + color: Color(0xFF8B949E), + ), + ), + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: const Color(0xFF0D1117), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Row( + children: [ + const Text( + '\$ ', + style: TextStyle(color: Color(0xFF3FB950), fontWeight: FontWeight.bold), + ), + Expanded( + child: Text( + debugCmd, + style: const TextStyle( + color: Color(0xFFE6EDF3), + fontFamily: 'monospace', + fontSize: 13, + ), + ), + ), + IconButton( + icon: const Icon(Icons.copy_rounded, size: 16, color: Color(0xFF8B949E)), + tooltip: 'Копировать команду', + onPressed: () { + Clipboard.setData(ClipboardData(text: debugCmd)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Команда отладки скопирована'), duration: Duration(seconds: 2)), + ); + }, + ), + ], + ), + ), + const SizedBox(height: 20), + + // Stack Trace / Backtrace + const Text( + 'СТЕК ВЫЗОВОВ (BACKTRACE / CRASH TRACE)', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + letterSpacing: 1.0, + color: Color(0xFF8B949E), + ), + ), + const SizedBox(height: 8), + Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF0D1117), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF21262D)), + ), + child: crash.stackTraceSnippet.isNotEmpty + ? SelectableText( + crash.stackTraceSnippet, + style: const TextStyle( + color: Color(0xFFE6EDF3), + fontFamily: 'monospace', + fontSize: 12, + height: 1.4, + ), + ) + : const Text( + 'Трассировка стека недоступна в данном дампе памяти.', + style: TextStyle(color: Color(0xFF8B949E), fontSize: 12), + ), + ), + ], + ), + ); + } + + Widget _buildMetaRow(String label, String value) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 130, + child: Text( + label, + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ), + Expanded( + child: Text( + value, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Color(0xFFE6EDF3), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/hardware_tab.dart b/lib/widgets/hardware_tab.dart new file mode 100644 index 0000000..1d35c89 --- /dev/null +++ b/lib/widgets/hardware_tab.dart @@ -0,0 +1,1249 @@ +import 'package:flutter/material.dart'; +import 'package:diagd/src/rust/api/diagnostics.dart'; + +class HardwareTab extends StatelessWidget { + final HardwareInfo hardware; + + const HardwareTab({super.key, required this.hardware}); + + static String _formatBytes(BigInt bytes) { + final b = bytes.toDouble(); + if (b >= 1024 * 1024 * 1024 * 1024) { + return '${(b / (1024 * 1024 * 1024 * 1024)).toStringAsFixed(1)} TB'; + } else if (b >= 1024 * 1024 * 1024) { + return '${(b / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB'; + } else if (b >= 1024 * 1024) { + return '${(b / (1024 * 1024)).toStringAsFixed(1)} MB'; + } else if (b >= 1024) { + return '${(b / 1024).toStringAsFixed(1)} KB'; + } + return '$bytes B'; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeaderBanner(), + const SizedBox(height: 20), + _buildCpuAndMotherboardRow(context), + const SizedBox(height: 20), + _buildMemoryAndSwapSection(), + const SizedBox(height: 20), + _buildGpuSection(), + const SizedBox(height: 20), + _buildStorageSection(), + const SizedBox(height: 20), + _buildNetworkSection(), + const SizedBox(height: 20), + _buildThermalsAndBatterySection(), + ], + ), + ); + } + + Widget _buildHeaderBanner() { + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF1F6FEB).withAlpha(40), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFF1F6FEB).withAlpha(100)), + ), + child: const Icon(Icons.memory_rounded, color: Color(0xFF58A6FF), size: 28), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Полный аппаратный профиль системы', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 4), + Text( + '${hardware.motherboard.vendor} ${hardware.motherboard.productName} • ${hardware.cpu.modelName}', + style: const TextStyle( + fontSize: 13, + color: Color(0xFF8B949E), + ), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + _buildChassisBadge(hardware.motherboard.chassisType), + ], + ), + ); + } + + Widget _buildChassisBadge(String chassis) { + IconData icon = Icons.computer_rounded; + final lower = chassis.toLowerCase(); + if (lower.contains('notebook') || + lower.contains('laptop') || + lower.contains('portable')) { + icon = Icons.laptop_rounded; + } else if (lower.contains('server') || + lower.contains('rack')) { + icon = Icons.dns_rounded; + } + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 16, color: const Color(0xFF8B949E)), + const SizedBox(width: 6), + Text( + chassis, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Color(0xFFE6EDF3), + ), + ), + ], + ), + ); + } + + Widget _buildCpuAndMotherboardRow(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) { + final isWide = constraints.maxWidth > 900; + if (isWide) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: _buildCpuCard()), + const SizedBox(width: 20), + Expanded(child: _buildMotherboardCard()), + ], + ); + } else { + return Column( + children: [ + _buildCpuCard(), + const SizedBox(height: 20), + _buildMotherboardCard(), + ], + ); + } + }, + ); + } + + Widget _buildCpuCard() { + final cpu = hardware.cpu; + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.speed_rounded, color: Color(0xFF58A6FF), size: 20), + const SizedBox(width: 8), + const Text( + 'Процессор (CPU)', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + const Spacer(), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Text( + cpu.architecture, + style: const TextStyle( + fontSize: 11, + fontFamily: 'monospace', + fontWeight: FontWeight.w600, + color: Color(0xFF58A6FF), + ), + ), + ), + ], + ), + const SizedBox(height: 14), + Text( + cpu.modelName, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 12), + const Divider(color: Color(0xFF21262D), height: 1), + const SizedBox(height: 12), + _buildInfoRow('Ядра / Потоки:', '${cpu.physicalCores} физич. / ${cpu.logicalThreads} логич.'), + _buildInfoRow( + 'Тактовая частота:', + '${cpu.currentFrequencyMhz != null ? "${cpu.currentFrequencyMhz!.toStringAsFixed(0)} MHz" : "N/A"} ' + '${cpu.baseFrequencyMhz != null ? "(база: ${cpu.baseFrequencyMhz!.toStringAsFixed(0)} MHz)" : ""}', + ), + _buildInfoRow('Кэш L1 / L2 / L3:', '${cpu.l1Cache} / ${cpu.l2Cache} / ${cpu.l3Cache}'), + _buildInfoRow('Виртуализация:', cpu.virtualization ?? 'Отсутствует / Отключена'), + _buildInfoRow('Микрокод:', cpu.microcode), + if (cpu.flags.isNotEmpty) ...[ + const SizedBox(height: 10), + const Text( + 'Инструкции & Флаги:', + style: TextStyle(fontSize: 12, color: Color(0xFF8B949E), fontWeight: FontWeight.w500), + ), + const SizedBox(height: 6), + Wrap( + spacing: 6, + runSpacing: 6, + children: cpu.flags.take(16).map((flag) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(4), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Text( + flag, + style: const TextStyle(fontSize: 10, fontFamily: 'monospace', color: Color(0xFFC9D1D9)), + ), + ); + }).toList(), + ), + if (cpu.flags.length > 16) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + '+ еще ${cpu.flags.length - 16} флагов', + style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E)), + ), + ), + ], + ], + ), + ); + } + + Widget _buildMotherboardCard() { + final mb = hardware.motherboard; + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Row( + children: [ + Icon(Icons.developer_board_rounded, color: Color(0xFF58A6FF), size: 20), + SizedBox(width: 8), + Text( + 'Материнская плата & BIOS', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + ], + ), + const SizedBox(height: 14), + Text( + '${mb.vendor} ${mb.productName}', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 12), + const Divider(color: Color(0xFF21262D), height: 1), + const SizedBox(height: 12), + _buildInfoRow('Производитель:', mb.vendor), + _buildInfoRow('Модель платы:', mb.productName), + _buildInfoRow('Ревизия / Версия:', mb.version), + _buildInfoRow('Тип шасси:', mb.chassisType), + const SizedBox(height: 8), + const Text( + 'Параметры BIOS / UEFI:', + style: TextStyle(fontSize: 12, color: Color(0xFF8B949E), fontWeight: FontWeight.w500), + ), + const SizedBox(height: 6), + _buildInfoRow('Разработчик BIOS:', mb.biosVendor), + _buildInfoRow('Версия BIOS:', mb.biosVersion), + _buildInfoRow('Дата релиза BIOS:', mb.biosDate), + ], + ), + ); + } + + Widget _buildMemoryAndSwapSection() { + final mem = hardware.memory; + final total = mem.totalBytes.toDouble(); + final used = mem.usedBytes.toDouble(); + final ramPercent = total > 0 ? (used / total).clamp(0.0, 1.0) : 0.0; + + final swapTotal = mem.swapTotalBytes.toDouble(); + final swapUsed = mem.swapUsedBytes.toDouble(); + final swapPercent = swapTotal > 0 ? (swapUsed / swapTotal).clamp(0.0, 1.0) : 0.0; + + final hasEccErrors = mem.edacCeCount > BigInt.zero || mem.edacUeCount > BigInt.zero; + + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.straighten_rounded, color: Color(0xFF58A6FF), size: 20), + const SizedBox(width: 8), + const Text( + 'Оперативная память (RAM) & Подкачка (Swap)', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + const Spacer(), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: hasEccErrors ? const Color(0xFFF85149).withAlpha(30) : const Color(0xFF3FB950).withAlpha(30), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: hasEccErrors ? const Color(0xFFF85149) : const Color(0xFF3FB950)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + hasEccErrors ? Icons.warning_amber_rounded : Icons.check_circle_outline_rounded, + size: 14, + color: hasEccErrors ? const Color(0xFFF85149) : const Color(0xFF3FB950), + ), + const SizedBox(width: 6), + Text( + hasEccErrors + ? 'EDAC Ошибки: ${mem.edacCeCount} CE / ${mem.edacUeCount} UE' + : 'ECC / EDAC: Ошибок нет', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: hasEccErrors ? const Color(0xFFF85149) : const Color(0xFF3FB950), + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 16), + // RAM Bar + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'RAM: ${_formatBytes(mem.usedBytes)} из ${_formatBytes(mem.totalBytes)} занято (${(ramPercent * 100).toStringAsFixed(1)}%)', + style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Color(0xFFE6EDF3)), + ), + Text( + 'Доступно: ${_formatBytes(mem.availableBytes)}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ], + ), + const SizedBox(height: 8), + ClipRRect( + borderRadius: BorderRadius.circular(6), + child: LinearProgressIndicator( + value: ramPercent, + minHeight: 10, + backgroundColor: const Color(0xFF21262D), + valueColor: AlwaysStoppedAnimation( + ramPercent > 0.9 ? const Color(0xFFF85149) : (ramPercent > 0.75 ? const Color(0xFFD29922) : const Color(0xFF3FB950)), + ), + ), + ), + const SizedBox(height: 16), + // Swap Bar + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + swapTotal > 0 + ? 'Swap: ${_formatBytes(mem.swapUsedBytes)} из ${_formatBytes(mem.swapTotalBytes)} занято (${(swapPercent * 100).toStringAsFixed(1)}%)' + : 'Swap: Раздел подкачки не настроен (0 B)', + style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Color(0xFFE6EDF3)), + ), + ], + ), + if (swapTotal > 0) ...[ + const SizedBox(height: 8), + ClipRRect( + borderRadius: BorderRadius.circular(6), + child: LinearProgressIndicator( + value: swapPercent, + minHeight: 8, + backgroundColor: const Color(0xFF21262D), + valueColor: AlwaysStoppedAnimation( + swapPercent > 0.8 ? const Color(0xFFF85149) : const Color(0xFF58A6FF), + ), + ), + ), + ], + ], + ), + ); + } + + Widget _buildGpuSection() { + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.videogame_asset_rounded, color: Color(0xFF58A6FF), size: 20), + const SizedBox(width: 8), + Text( + 'Графические ускорители (GPU) [${hardware.gpus.length}]', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + ], + ), + const SizedBox(height: 14), + if (hardware.gpus.isEmpty) + const Text('Дискретные или интегрированные GPU не обнаружены', style: TextStyle(color: Color(0xFF8B949E))) + else + ...hardware.gpus.map((gpu) { + return Container( + margin: const EdgeInsets.only(bottom: 10), + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + ), + child: const Icon(Icons.tv_rounded, color: Color(0xFF58A6FF), size: 22), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + gpu.model, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 4), + Text( + 'Вендор: ${gpu.vendor} • Слот PCI: ${gpu.pciSlot}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Text( + 'Драйвер: ${gpu.driver}', + style: const TextStyle( + fontSize: 11, + fontFamily: 'monospace', + color: Color(0xFF3FB950), + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ); + }), + ], + ), + ); + } + + Widget _buildStorageSection() { + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.storage_rounded, color: Color(0xFF58A6FF), size: 20), + const SizedBox(width: 8), + Text( + 'Накопители данных (NVMe / SSD / HDD) [${hardware.disks.length}]', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + ], + ), + const SizedBox(height: 14), + if (hardware.disks.isEmpty) + const Text('Дисковые накопители не обнаружены', style: TextStyle(color: Color(0xFF8B949E))) + else + ...hardware.disks.map((disk) { + return _buildDiskCard(disk); + }), + ], + ), + ); + } + + Widget _buildDiskCard(DiskInfo disk) { + final isSsd = disk.diskType.contains('SSD') || disk.diskType.contains('NVMe'); + final healthVal = disk.healthPercent ?? (disk.smartStatus == 'PASSED' ? 100 : (disk.smartStatus == 'FAILED' ? 30 : 100)); + final wearVal = disk.wearPercent ?? (100 - healthVal); + final healthProgress = (healthVal / 100.0).clamp(0.0, 1.0); + + final Color healthColor = healthVal >= 80 + ? const Color(0xFF3FB950) + : (healthVal >= 50 ? const Color(0xFFD29922) : const Color(0xFFF85149)); + + IconData diskIcon = Icons.album_rounded; + Color typeColor = const Color(0xFFD29922); + if (disk.diskType.contains('NVMe')) { + diskIcon = Icons.flash_on_rounded; + typeColor = const Color(0xFFBC8CFF); + } else if (disk.diskType.contains('SSD')) { + diskIcon = Icons.save_rounded; + typeColor = const Color(0xFF58A6FF); + } + + return Container( + margin: const EdgeInsets.only(bottom: 16), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header: Icon, Name, Model, Badges + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Icon(diskIcon, color: typeColor, size: 24), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + runSpacing: 4, + children: [ + Text( + disk.name, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + fontFamily: 'monospace', + color: Color(0xFFE6EDF3), + ), + ), + Text( + disk.model, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFFC9D1D9), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: typeColor.withAlpha(30), + borderRadius: BorderRadius.circular(4), + border: Border.all(color: typeColor.withAlpha(120)), + ), + child: Text( + disk.rotationalSpeedRpm != null && disk.rotationalSpeedRpm! > 0 + ? '${disk.diskType} • ${disk.rotationalSpeedRpm} RPM' + : disk.diskType, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: typeColor, + ), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + 'Объем: ${_formatBytes(disk.sizeBytes)}' + '${disk.serial.isNotEmpty ? " • S/N: ${disk.serial}" : ""}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ], + ), + ), + const SizedBox(width: 10), + // SMART & Temp Badges + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: disk.smartStatus == 'PASSED' + ? const Color(0xFF3FB950).withAlpha(30) + : (disk.smartStatus == 'FAILED' + ? const Color(0xFFF85149).withAlpha(30) + : const Color(0xFF30363D)), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: disk.smartStatus == 'PASSED' + ? const Color(0xFF3FB950) + : (disk.smartStatus == 'FAILED' + ? const Color(0xFFF85149) + : const Color(0xFF8B949E)), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + disk.smartStatus == 'PASSED' + ? Icons.check_circle_outline_rounded + : (disk.smartStatus == 'FAILED' + ? Icons.error_outline_rounded + : Icons.help_outline_rounded), + size: 13, + color: disk.smartStatus == 'PASSED' + ? const Color(0xFF3FB950) + : (disk.smartStatus == 'FAILED' + ? const Color(0xFFF85149) + : const Color(0xFF8B949E)), + ), + const SizedBox(width: 5), + Text( + 'SMART: ${disk.smartStatus}', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: disk.smartStatus == 'PASSED' + ? const Color(0xFF3FB950) + : (disk.smartStatus == 'FAILED' + ? const Color(0xFFF85149) + : const Color(0xFF8B949E)), + ), + ), + ], + ), + ), + if (disk.temperatureC != null) ...[ + const SizedBox(height: 6), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(4), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.thermostat_rounded, + size: 13, + color: disk.temperatureC! > 55 ? const Color(0xFFF85149) : const Color(0xFF3FB950), + ), + const SizedBox(width: 4), + Text( + '${disk.temperatureC}°C', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: disk.temperatureC! > 55 ? const Color(0xFFF85149) : const Color(0xFFE6EDF3), + ), + ), + ], + ), + ), + ], + ], + ), + ], + ), + const SizedBox(height: 14), + + // ПОЛОСКА ИЗНОСА И ЗДОРОВЬЯ НАКОПИТЕЛЯ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Icon( + isSsd ? Icons.speed_rounded : Icons.health_and_safety_rounded, + size: 15, + color: healthColor, + ), + const SizedBox(width: 6), + Text( + isSsd + ? 'Здоровье SSD: $healthVal% • Износ ячеек памяти: $wearVal%' + : 'Состояние HDD: ${healthVal >= 90 ? "Отличное" : "Внимание"} ($healthVal%)', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: healthColor, + ), + ), + ], + ), + Text( + isSsd ? 'Остаточный ресурс: $healthVal%' : 'Надежность: $healthVal%', + style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E)), + ), + ], + ), + const SizedBox(height: 8), + ClipRRect( + borderRadius: BorderRadius.circular(5), + child: LinearProgressIndicator( + value: healthProgress, + minHeight: 8, + backgroundColor: const Color(0xFF21262D), + valueColor: AlwaysStoppedAnimation(healthColor), + ), + ), + const SizedBox(height: 10), + // Метрики накопителя + Wrap( + spacing: 16, + runSpacing: 6, + children: [ + if (disk.powerOnHours != null) + _buildDiskMetric( + Icons.timer_outlined, + 'Наработка', + '${disk.powerOnHours} ч. (${(disk.powerOnHours!.toDouble() / 24.0).toStringAsFixed(0)} дн.)', + ), + if (disk.powerCycleCount != null) + _buildDiskMetric( + Icons.power_settings_new_rounded, + 'Включений', + '${disk.powerCycleCount} раз', + ), + _buildDiskMetric( + Icons.warning_amber_rounded, + 'Бэд-секторы', + '${disk.badSectorsCount ?? 0}', + highlightColor: (disk.badSectorsCount != null && disk.badSectorsCount! > BigInt.zero) + ? const Color(0xFFF85149) + : const Color(0xFF3FB950), + ), + if (disk.totalWrittenTb != null) + _buildDiskMetric( + Icons.data_exploration_rounded, + 'Записано (TBW)', + '${disk.totalWrittenTb!.toStringAsFixed(2)} TB', + ), + ], + ), + ], + ), + ), + + // РАЗДЕЛЫ И ТОЧКИ МОНТИРОВАНИЯ + if (disk.partitions.isNotEmpty) ...[ + const SizedBox(height: 12), + const Text( + 'Разделы и файловые системы:', + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF8B949E)), + ), + const SizedBox(height: 6), + ...disk.partitions.map((part) { + final pTotal = part.sizeBytes.toDouble(); + final pUsed = part.usedBytes.toDouble(); + final pPercent = pTotal > 0 && pUsed > 0 ? (pUsed / pTotal).clamp(0.0, 1.0) : 0.0; + final isMounted = part.mountPoint != null && part.mountPoint!.isNotEmpty; + + return Container( + margin: const EdgeInsets.only(bottom: 6), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + part.name, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + fontFamily: 'monospace', + color: Color(0xFF58A6FF), + ), + ), + if (part.fsType.isNotEmpty) ...[ + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + part.fsType, + style: const TextStyle(fontSize: 10, color: Color(0xFF8B949E)), + ), + ), + ], + const SizedBox(width: 8), + Text( + isMounted ? '➔ ${part.mountPoint}' : '• не смонтирован', + style: TextStyle( + fontSize: 12, + color: isMounted ? const Color(0xFFE6EDF3) : const Color(0xFF8B949E), + ), + ), + const Spacer(), + Text( + isMounted && pUsed > 0 + ? '${_formatBytes(part.usedBytes)} из ${_formatBytes(part.sizeBytes)} (${(pPercent * 100).toStringAsFixed(0)}%)' + : _formatBytes(part.sizeBytes), + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Color(0xFFC9D1D9), + ), + ), + ], + ), + if (isMounted && pUsed > 0) ...[ + const SizedBox(height: 6), + ClipRRect( + borderRadius: BorderRadius.circular(3), + child: LinearProgressIndicator( + value: pPercent, + minHeight: 4, + backgroundColor: const Color(0xFF21262D), + valueColor: AlwaysStoppedAnimation( + pPercent > 0.9 + ? const Color(0xFFF85149) + : (pPercent > 0.75 ? const Color(0xFFD29922) : const Color(0xFF58A6FF)), + ), + ), + ), + ], + ], + ), + ); + }), + ], + ], + ), + ); + } + + Widget _buildDiskMetric(IconData icon, String label, String value, {Color? highlightColor}) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 13, color: highlightColor ?? const Color(0xFF8B949E)), + const SizedBox(width: 4), + Text( + '$label: ', + style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E)), + ), + Text( + value, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: highlightColor ?? const Color(0xFFE6EDF3), + fontFamily: 'monospace', + ), + ), + ], + ); + } + + Widget _buildNetworkSection() { + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.settings_ethernet_rounded, color: Color(0xFF58A6FF), size: 20), + const SizedBox(width: 8), + Text( + 'Сетевые интерфейсы [${hardware.networkAdapters.length}]', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + ], + ), + const SizedBox(height: 14), + if (hardware.networkAdapters.isEmpty) + const Text('Сетевые интерфейсы не обнаружены', style: TextStyle(color: Color(0xFF8B949E))) + else + ...hardware.networkAdapters.map((nic) { + final isUp = nic.state.toUpperCase() == 'UP'; + return Container( + margin: const EdgeInsets.only(bottom: 10), + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + ), + child: Icon( + nic.ifType.contains('Wi-Fi') || nic.ifType.contains('Wireless') + ? Icons.wifi_rounded + : Icons.lan_rounded, + color: isUp ? const Color(0xFF3FB950) : const Color(0xFF8B949E), + size: 22, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + nic.interfaceName, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + fontFamily: 'monospace', + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + nic.ifType, + style: const TextStyle(fontSize: 10, color: Color(0xFF8B949E)), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + 'MAC: ${nic.macAddress} • Драйвер: ${nic.driver} ${nic.speedMbps != null ? "• ${nic.speedMbps} Mbps" : ""}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: isUp ? const Color(0xFF3FB950).withAlpha(30) : const Color(0xFF21262D), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: isUp ? const Color(0xFF3FB950) : const Color(0xFF30363D)), + ), + child: Text( + nic.state.toUpperCase(), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: isUp ? const Color(0xFF3FB950) : const Color(0xFF8B949E), + ), + ), + ), + ], + ), + ); + }), + ], + ), + ); + } + + Widget _buildThermalsAndBatterySection() { + final therm = hardware.thermals; + final bat = hardware.battery; + + return Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Row( + children: [ + Icon(Icons.thermostat_rounded, color: Color(0xFF58A6FF), size: 20), + SizedBox(width: 8), + Text( + 'Температурный режим & Электропитание', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + ], + ), + const SizedBox(height: 14), + Row( + children: [ + Expanded( + child: Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Температура CPU (макс.)', style: TextStyle(fontSize: 12, color: Color(0xFF8B949E))), + const SizedBox(height: 6), + Text( + therm.maxCpuTempC > 0 ? '${therm.maxCpuTempC.toStringAsFixed(1)} °C' : 'Н/Д', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + color: therm.maxCpuTempC > 80 + ? const Color(0xFFF85149) + : (therm.maxCpuTempC > 65 ? const Color(0xFFD29922) : const Color(0xFF3FB950)), + ), + ), + const SizedBox(height: 6), + Text( + therm.isActivelyThrottling + ? 'ВНИМАНИЕ: Троттлинг активен!' + : (therm.totalThrottleEvents > BigInt.zero + ? 'Событий троттлинга: ${therm.totalThrottleEvents}' + : 'Троттлинг не фиксировался'), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: therm.isActivelyThrottling ? const Color(0xFFF85149) : const Color(0xFF8B949E), + ), + ), + ], + ), + ), + ), + if (bat != null) ...[ + const SizedBox(width: 16), + Expanded( + child: Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Батарея: ${bat.name}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + Text( + bat.status, + style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Color(0xFF58A6FF)), + ), + ], + ), + const SizedBox(height: 6), + Text( + '${bat.capacityPercent}%', + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(height: 6), + Text( + 'Здоровье: ${bat.healthPercent.toStringAsFixed(1)}% • Циклов: ${bat.cycleCount} ${bat.isDegraded ? "• Износ высок!" : ""}', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: bat.isDegraded ? const Color(0xFFF85149) : const Color(0xFF8B949E), + ), + ), + ], + ), + ), + ), + ], + ], + ), + ], + ), + ); + } + + Widget _buildInfoRow(String label, String value) { + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 150, + child: Text( + label, + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ), + Expanded( + child: Text( + value, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Color(0xFFE6EDF3), + fontFamily: 'monospace', + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/live_monitor_tab.dart b/lib/widgets/live_monitor_tab.dart new file mode 100644 index 0000000..d6a72c5 --- /dev/null +++ b/lib/widgets/live_monitor_tab.dart @@ -0,0 +1,545 @@ +import 'dart:async'; +import 'dart:math'; +import 'package:flutter/material.dart'; +import 'package:diagd/src/rust/api/diagnostics.dart'; + +class LiveMonitorTab extends StatefulWidget { + const LiveMonitorTab({super.key}); + + @override + State createState() => _LiveMonitorTabState(); +} + +class _LiveMonitorTabState extends State { + Timer? _ticker; + LiveMetricsSnapshot? _snapshot; + final List _cpuHistory = []; + final List _ramHistory = []; + final List _tempHistory = []; + final List _netHistory = []; + final int _maxHistory = 60; + + @override + void initState() { + super.initState(); + _fetchMetrics(); + _ticker = Timer.periodic(const Duration(seconds: 1), (_) => _fetchMetrics()); + } + + @override + void dispose() { + _ticker?.cancel(); + super.dispose(); + } + + Future _fetchMetrics() async { + try { + final snap = await getLiveMetrics(); + if (!mounted) return; + setState(() { + _snapshot = snap; + _cpuHistory.add(snap.cpuUsagePercent.clamp(0.0, 100.0)); + if (_cpuHistory.length > _maxHistory) _cpuHistory.removeAt(0); + + final ramPct = snap.ramTotalBytes > BigInt.zero + ? (snap.ramUsedBytes.toDouble() / snap.ramTotalBytes.toDouble()) * 100.0 + : 0.0; + _ramHistory.add(ramPct.clamp(0.0, 100.0)); + if (_ramHistory.length > _maxHistory) _ramHistory.removeAt(0); + + _tempHistory.add(snap.maxCpuTempC.clamp(0.0, 120.0)); + if (_tempHistory.length > _maxHistory) _tempHistory.removeAt(0); + + final netKb = (snap.netRxKbps + snap.netTxKbps).toDouble(); + _netHistory.add(netKb); + if (_netHistory.length > _maxHistory) _netHistory.removeAt(0); + }); + } catch (_) {} + } + + @override + Widget build(BuildContext context) { + if (_snapshot == null) { + return const Center( + child: CircularProgressIndicator(color: Color(0xFF58A6FF)), + ); + } + + final snap = _snapshot!; + final ramUsedGb = snap.ramUsedBytes.toDouble() / (1024 * 1024 * 1024); + final ramTotalGb = snap.ramTotalBytes.toDouble() / (1024 * 1024 * 1024); + final ramPct = ramTotalGb > 0 ? (ramUsedGb / ramTotalGb) * 100.0 : 0.0; + + final swapUsedGb = snap.swapUsedBytes.toDouble() / (1024 * 1024 * 1024); + final swapTotalGb = snap.swapTotalBytes.toDouble() / (1024 * 1024 * 1024); + + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Throttling Alert Banner + if (snap.isThrottling) ...[ + Container( + padding: const EdgeInsets.all(16), + margin: const EdgeInsets.only(bottom: 20), + decoration: BoxDecoration( + color: const Color(0xFFF85149).withAlpha(30), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFF85149)), + ), + child: const Row( + children: [ + Icon(Icons.warning_rounded, color: Color(0xFFF85149), size: 28), + SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'КРИТИЧЕСКИЙ ПЕРЕГРЕВ: АКТИВЕН THERMAL THROTTLING!', + style: TextStyle( + color: Color(0xFFF85149), + fontWeight: FontWeight.bold, + fontSize: 15, + ), + ), + SizedBox(height: 4), + Text( + 'Процессор сбросил тактовые частоты из-за превышения температурного порога. Проверьте систему охлаждения и термопасту.', + style: TextStyle(color: Color(0xFFE6EDF3), fontSize: 13), + ), + ], + ), + ), + ], + ), + ), + ], + + // Top Metric Cards Grid + LayoutBuilder( + builder: (context, constraints) { + final cols = constraints.maxWidth > 900 ? 4 : (constraints.maxWidth > 550 ? 2 : 1); + return GridView.count( + crossAxisCount: cols, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + crossAxisSpacing: 14, + mainAxisSpacing: 14, + childAspectRatio: constraints.maxWidth > 900 ? 1.6 : 2.0, + children: [ + _buildMetricCard( + title: 'Загрузка CPU', + value: '${snap.cpuUsagePercent.toStringAsFixed(1)}%', + subvalue: 'Общая нагрузка ядер', + icon: Icons.memory_rounded, + color: snap.cpuUsagePercent > 85 + ? const Color(0xFFF85149) + : (snap.cpuUsagePercent > 60 ? const Color(0xFFD29922) : const Color(0xFF3FB950)), + progress: snap.cpuUsagePercent / 100.0, + ), + _buildMetricCard( + title: 'Оперативная память (RAM)', + value: '${ramUsedGb.toStringAsFixed(1)} / ${ramTotalGb.toStringAsFixed(1)} GB', + subvalue: '${ramPct.toStringAsFixed(0)}% использовано', + icon: Icons.storage_rounded, + color: ramPct > 90 + ? const Color(0xFFF85149) + : (ramPct > 75 ? const Color(0xFFD29922) : const Color(0xFF58A6FF)), + progress: ramPct / 100.0, + ), + _buildMetricCard( + title: 'Температура CPU', + value: '${snap.maxCpuTempC.toStringAsFixed(1)} °C', + subvalue: snap.isThrottling ? 'Троттлинг АКТИВЕН' : 'Охлаждение в норме', + icon: Icons.thermostat_rounded, + color: snap.maxCpuTempC > 85 + ? const Color(0xFFF85149) + : (snap.maxCpuTempC > 70 ? const Color(0xFFD29922) : const Color(0xFF3FB950)), + progress: (snap.maxCpuTempC.clamp(20.0, 105.0) - 20.0) / 85.0, + ), + _buildMetricCard( + title: 'Дисковый и Сетевой I/O', + value: '${((snap.diskReadKbps + snap.diskWriteKbps).toDouble() / 1024.0).toStringAsFixed(1)} MB/s', + subvalue: 'Сеть: ${snap.netRxKbps + snap.netTxKbps} KB/s (RX+TX)', + icon: Icons.swap_vert_rounded, + color: const Color(0xFFA371F7), + progress: null, + ), + ], + ); + }, + ), + const SizedBox(height: 24), + + // Realtime Sparklines / Charts + const Text( + 'ДИНАМИКА НАГРУЗКИ В РЕАЛЬНОМ ВРЕМЕНИ (ПОСЛЕДНИЕ 60 СЕК)', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 1.2, + color: Color(0xFF8B949E), + ), + ), + const SizedBox(height: 12), + + LayoutBuilder( + builder: (context, constraints) { + final isWide = constraints.maxWidth > 800; + if (isWide) { + return Row( + children: [ + Expanded( + child: _buildChartContainer( + title: 'Нагрузка CPU (%)', + color: const Color(0xFF58A6FF), + history: _cpuHistory, + maxVal: 100.0, + currentVal: '${snap.cpuUsagePercent.toStringAsFixed(1)}%', + ), + ), + const SizedBox(width: 14), + Expanded( + child: _buildChartContainer( + title: 'Использование RAM (%)', + color: const Color(0xFF3FB950), + history: _ramHistory, + maxVal: 100.0, + currentVal: '${ramPct.toStringAsFixed(1)}%', + ), + ), + ], + ); + } else { + return Column( + children: [ + _buildChartContainer( + title: 'Нагрузка CPU (%)', + color: const Color(0xFF58A6FF), + history: _cpuHistory, + maxVal: 100.0, + currentVal: '${snap.cpuUsagePercent.toStringAsFixed(1)}%', + ), + const SizedBox(height: 14), + _buildChartContainer( + title: 'Использование RAM (%)', + color: const Color(0xFF3FB950), + history: _ramHistory, + maxVal: 100.0, + currentVal: '${ramPct.toStringAsFixed(1)}%', + ), + ], + ); + } + }, + ), + const SizedBox(height: 14), + + LayoutBuilder( + builder: (context, constraints) { + final isWide = constraints.maxWidth > 800; + if (isWide) { + return Row( + children: [ + Expanded( + child: _buildChartContainer( + title: 'Температура CPU (°C)', + color: const Color(0xFFD29922), + history: _tempHistory, + maxVal: 105.0, + currentVal: '${snap.maxCpuTempC.toStringAsFixed(1)}°C', + ), + ), + const SizedBox(width: 14), + Expanded( + child: _buildChartContainer( + title: 'Сетевой трафик (KB/s)', + color: const Color(0xFFA371F7), + history: _netHistory, + maxVal: _netHistory.isEmpty ? 100.0 : max(100.0, _netHistory.reduce(max)), + currentVal: '${snap.netRxKbps + snap.netTxKbps} KB/s', + ), + ), + ], + ); + } else { + return Column( + children: [ + _buildChartContainer( + title: 'Температура CPU (°C)', + color: const Color(0xFFD29922), + history: _tempHistory, + maxVal: 105.0, + currentVal: '${snap.maxCpuTempC.toStringAsFixed(1)}°C', + ), + const SizedBox(height: 14), + _buildChartContainer( + title: 'Сетевой трафик (KB/s)', + color: const Color(0xFFA371F7), + history: _netHistory, + maxVal: _netHistory.isEmpty ? 100.0 : max(100.0, _netHistory.reduce(max)), + currentVal: '${snap.netRxKbps + snap.netTxKbps} KB/s', + ), + ], + ); + } + }, + ), + const SizedBox(height: 24), + + // Detailed Memory & Storage Row + Container( + padding: const EdgeInsets.all(18), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Row( + children: [ + Icon(Icons.info_outline_rounded, color: Color(0xFF58A6FF), size: 18), + SizedBox(width: 8), + Text( + 'Детализация виртуальной памяти и I/O накопителей', + style: TextStyle( + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + fontSize: 14, + ), + ), + ], + ), + const SizedBox(height: 14), + Row( + children: [ + Expanded( + child: _buildDetailRow( + 'Swap память:', + '${swapUsedGb.toStringAsFixed(2)} GB из ${swapTotalGb.toStringAsFixed(2)} GB', + ), + ), + Expanded( + child: _buildDetailRow( + 'Диск (Read / Write):', + '${(snap.diskReadKbps.toDouble() / 1024.0).toStringAsFixed(1)} MB/s / ${(snap.diskWriteKbps.toDouble() / 1024.0).toStringAsFixed(1)} MB/s', + ), + ), + Expanded( + child: _buildDetailRow( + 'Сеть (RX / TX):', + '${snap.netRxKbps} KB/s / ${snap.netTxKbps} KB/s', + ), + ), + ], + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildMetricCard({ + required String title, + required String value, + required String subvalue, + required IconData icon, + required Color color, + double? progress, + }) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: color.withAlpha(50)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: Color(0xFF8B949E), + ), + ), + Icon(icon, color: color, size: 20), + ], + ), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + value, + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: color, + ), + ), + const SizedBox(height: 2), + Text( + subvalue, + style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E)), + ), + ], + ), + if (progress != null) + ClipRRect( + borderRadius: BorderRadius.circular(3), + child: LinearProgressIndicator( + value: progress.clamp(0.0, 1.0), + backgroundColor: const Color(0xFF21262D), + valueColor: AlwaysStoppedAnimation(color), + minHeight: 4, + ), + ) + else + const SizedBox(height: 4), + ], + ), + ); + } + + Widget _buildChartContainer({ + required String title, + required Color color, + required List history, + required double maxVal, + required String currentVal, + }) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: Color(0xFFE6EDF3), + ), + ), + Text( + currentVal, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: color, + ), + ), + ], + ), + const SizedBox(height: 12), + SizedBox( + height: 90, + width: double.infinity, + child: CustomPaint( + painter: _SparklinePainter( + data: history, + color: color, + maxVal: maxVal, + ), + ), + ), + ], + ), + ); + } + + Widget _buildDetailRow(String label, String val) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E))), + const SizedBox(height: 3), + Text(val, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Color(0xFFE6EDF3))), + ], + ); + } +} + +class _SparklinePainter extends CustomPainter { + final List data; + final Color color; + final double maxVal; + + _SparklinePainter({ + required this.data, + required this.color, + required this.maxVal, + }); + + @override + void paint(Canvas canvas, Size size) { + if (data.isEmpty) return; + + final paintLine = Paint() + ..color = color + ..strokeWidth = 2.0 + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; + + final paintFill = Paint() + ..shader = LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + color.withAlpha(80), + color.withAlpha(0), + ], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)) + ..style = PaintingStyle.fill; + + final path = Path(); + final fillPath = Path(); + + final stepX = size.width / max(1, (60 - 1)); + final startIdx = 60 - data.length; + + for (int i = 0; i < data.length; i++) { + final x = (startIdx + i) * stepX; + final valNorm = (data[i] / (maxVal > 0 ? maxVal : 1.0)).clamp(0.0, 1.0); + final y = size.height - (valNorm * size.height); + + if (i == 0) { + path.moveTo(x, y); + fillPath.moveTo(x, size.height); + fillPath.lineTo(x, y); + } else { + path.lineTo(x, y); + fillPath.lineTo(x, y); + } + } + + fillPath.lineTo(size.width, size.height); + fillPath.close(); + + canvas.drawPath(fillPath, paintFill); + canvas.drawPath(path, paintLine); + } + + @override + bool shouldRepaint(covariant _SparklinePainter oldDelegate) => true; +} diff --git a/lib/widgets/security_tab.dart b/lib/widgets/security_tab.dart new file mode 100644 index 0000000..136a713 --- /dev/null +++ b/lib/widgets/security_tab.dart @@ -0,0 +1,497 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:diagd/src/rust/api/diagnostics.dart'; + +class SecurityTab extends StatelessWidget { + final SecurityAuditReport security; + + const SecurityTab({ + super.key, + required this.security, + }); + + @override + Widget build(BuildContext context) { + final score = security.securityScore; + final scoreColor = score >= 80 + ? const Color(0xFF3FB950) + : (score >= 50 ? const Color(0xFFD29922) : const Color(0xFFF85149)); + + final failedChecks = security.hardeningChecks.where((c) => !c.isSecure).length; + final passedChecks = security.hardeningChecks.where((c) => c.isSecure).length; + + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Security Score Hero Card + Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: scoreColor.withAlpha(70)), + ), + child: Row( + children: [ + Stack( + alignment: Alignment.center, + children: [ + SizedBox( + width: 80, + height: 80, + child: CircularProgressIndicator( + value: score / 100.0, + strokeWidth: 8, + backgroundColor: const Color(0xFF21262D), + valueColor: AlwaysStoppedAnimation(scoreColor), + ), + ), + Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '$score', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: scoreColor, + ), + ), + const Text( + '/100', + style: TextStyle(fontSize: 10, color: Color(0xFF8B949E)), + ), + ], + ), + ], + ), + const SizedBox(width: 24), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + 'Индекс защищенности системы (Security Score)', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: scoreColor.withAlpha(30), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: scoreColor.withAlpha(80)), + ), + child: Text( + score >= 80 ? 'ОТЛИЧНО' : (score >= 50 ? 'ТРЕБУЕТ ВНИМАНИЯ' : 'УЯЗВИМО'), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: scoreColor, + ), + ), + ), + ], + ), + const SizedBox(height: 6), + Text( + 'Аудит сетевого периметра, прав суперпользователя SUID/SGID, параметров защиты ядра (ASLR, ptrace, eBPF) и конфигурации SSH.', + style: const TextStyle(fontSize: 13, color: Color(0xFF8B949E)), + ), + const SizedBox(height: 12), + Row( + children: [ + _buildMiniBadge('Открытых портов (0.0.0.0): ${security.exposedPorts.length}', + security.exposedPorts.isNotEmpty ? const Color(0xFFD29922) : const Color(0xFF3FB950)), + const SizedBox(width: 10), + _buildMiniBadge('SUID аномалий: ${security.suidAnomalies.length}', + security.suidAnomalies.isNotEmpty ? const Color(0xFFF85149) : const Color(0xFF3FB950)), + const SizedBox(width: 10), + _buildMiniBadge('Пройдено тестов: $passedChecks / ${security.hardeningChecks.length}', + failedChecks > 0 ? const Color(0xFFD29922) : const Color(0xFF3FB950)), + ], + ), + ], + ), + ), + ], + ), + ), + const SizedBox(height: 24), + + // 1. Exposed Listening Ports + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'СЕТЕВОЙ ПЕРИМЕТР (ПОРТЫ, СЛУШАЮЩИЕ 0.0.0.0 И ::)', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 1.2, + color: Color(0xFF8B949E), + ), + ), + Text( + 'Всего: ${security.exposedPorts.length}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ], + ), + const SizedBox(height: 10), + if (security.exposedPorts.isEmpty) + _buildEmptyState('Открытых вовне портов не обнаружено. Локальный сетевой стек защищен.', Icons.verified_user_rounded) + else + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: security.exposedPorts.length, + separatorBuilder: (context, index) => const SizedBox(height: 8), + itemBuilder: (context, index) { + final port = security.exposedPorts[index]; + return _buildPortCard(context, port); + }, + ), + const SizedBox(height: 28), + + // 2. SUID / SGID Anomalies + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'ПОДОЗРИТЕЛЬНЫЕ SUID / SGID БИНАРНЫЕ ФАЙЛЫ', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 1.2, + color: Color(0xFF8B949E), + ), + ), + Text( + 'Аномалий: ${security.suidAnomalies.length}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + ], + ), + const SizedBox(height: 10), + if (security.suidAnomalies.isEmpty) + _buildEmptyState('Аномальных или небезопасных SUID/SGID файлов в общедоступных каталогах (/tmp, /dev/shm) не обнаружено.', Icons.check_circle_outline_rounded) + else + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: security.suidAnomalies.length, + separatorBuilder: (context, index) => const SizedBox(height: 8), + itemBuilder: (context, index) { + final suid = security.suidAnomalies[index]; + return _buildSuidCard(suid); + }, + ), + const SizedBox(height: 28), + + // 3. Kernel & OS Hardening Checklist + const Text( + 'ЧЕК-ЛИСТ ЗАЩИТЫ ЯДРА И ОПЕРАЦИОННОЙ СИСТЕМЫ (HARDENING)', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + letterSpacing: 1.2, + color: Color(0xFF8B949E), + ), + ), + const SizedBox(height: 10), + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: security.hardeningChecks.length, + separatorBuilder: (context, index) => const SizedBox(height: 8), + itemBuilder: (context, index) { + final check = security.hardeningChecks[index]; + return _buildHardeningCard(context, check); + }, + ), + ], + ), + ); + } + + Widget _buildMiniBadge(String text, Color color) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: color.withAlpha(20), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: color.withAlpha(60)), + ), + child: Text( + text, + style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: color), + ), + ); + } + + Widget _buildEmptyState(String text, IconData icon) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFF238636).withAlpha(50)), + ), + child: Row( + children: [ + Icon(icon, color: const Color(0xFF3FB950), size: 22), + const SizedBox(width: 12), + Expanded( + child: Text( + text, + style: const TextStyle(fontSize: 13, color: Color(0xFF8B949E)), + ), + ), + ], + ), + ); + } + + Widget _buildPortCard(BuildContext context, ListeningPortInfo port) { + final (Color badgeColor, String badgeText) = switch (port.riskLevel) { + Severity.critical => (const Color(0xFFF85149), 'CRITICAL'), + Severity.warning => (const Color(0xFFD29922), 'WARNING'), + Severity.info => (const Color(0xFF3FB950), 'INFO'), + }; + + return Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: badgeColor.withAlpha(60)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: badgeColor.withAlpha(25), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: badgeColor.withAlpha(80)), + ), + child: Text( + badgeText, + style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold, color: badgeColor), + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + '${port.protocol.toUpperCase()} ${port.port}', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + const SizedBox(width: 10), + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: const Color(0xFF21262D), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + port.processName.isNotEmpty ? port.processName : 'unknown process', + style: const TextStyle(fontSize: 12, color: Color(0xFF58A6FF), fontFamily: 'monospace'), + ), + ), + if (port.pid != null) ...[ + const SizedBox(width: 6), + Text('(PID: ${port.pid})', style: const TextStyle(fontSize: 11, color: Color(0xFF8B949E))), + ], + ], + ), + const SizedBox(height: 4), + Text( + 'Адрес прослушивания: ${port.localAddress}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + if (port.recommendation.isNotEmpty) ...[ + const SizedBox(height: 6), + Row( + children: [ + const Icon(Icons.arrow_right_rounded, size: 18, color: Color(0xFFD29922)), + Expanded( + child: Text( + port.recommendation, + style: TextStyle(fontSize: 12, color: badgeColor), + ), + ), + ], + ), + ], + ], + ), + ), + ], + ), + ); + } + + Widget _buildSuidCard(SuidAnomalyInfo suid) { + return Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: const Color(0xFFF85149).withAlpha(60)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon(Icons.warning_amber_rounded, color: Color(0xFFF85149), size: 22), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + suid.path, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + fontFamily: 'monospace', + ), + ), + const SizedBox(height: 4), + Text( + 'Владелец: ${suid.owner} | Права: ${suid.permissions}', + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + const SizedBox(height: 4), + Text( + suid.riskReason, + style: const TextStyle(fontSize: 12, color: Color(0xFFF85149)), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildHardeningCard(BuildContext context, SecurityCheckItem check) { + final isPass = check.isSecure; + final color = isPass ? const Color(0xFF3FB950) : const Color(0xFFF85149); + + return Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: const Color(0xFF161B22), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: color.withAlpha(50)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + isPass ? Icons.check_circle_rounded : Icons.cancel_rounded, + color: color, + size: 20, + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + check.name, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: Color(0xFFE6EDF3), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: color.withAlpha(20), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + check.status, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: color, + ), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + check.description, + style: const TextStyle(fontSize: 12, color: Color(0xFF8B949E)), + ), + if (!isPass && check.remediation != null && check.remediation!.isNotEmpty) ...[ + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: const Color(0xFF0D1117), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: const Color(0xFF30363D)), + ), + child: Row( + children: [ + const Icon(Icons.build_rounded, size: 14, color: Color(0xFFD29922)), + const SizedBox(width: 8), + Expanded( + child: Text( + check.remediation!, + style: const TextStyle(fontSize: 12, color: Color(0xFFE6EDF3), fontFamily: 'monospace'), + ), + ), + IconButton( + icon: const Icon(Icons.copy_rounded, size: 16, color: Color(0xFF8B949E)), + tooltip: 'Скопировать команду', + onPressed: () { + Clipboard.setData(ClipboardData(text: check.remediation!)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Команда устранения скопирована в буфер'), + duration: Duration(seconds: 2), + ), + ); + }, + ), + ], + ), + ), + ], + ], + ), + ), + ], + ), + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..a9a7ce0 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "diagd") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.diagd.diagd") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..90f66ad --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + rust_lib_diagd +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..5f21e02 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,30 @@ +#include "my_application.h" +#include +#include +#include + +int main(int argc, char** argv) { + for (int i = 1; i < argc; ++i) { + if (strcmp(argv[i], "--tui") == 0 || strcmp(argv[i], "-t") == 0) { + // Загрузка функции diagd_run_tui из bundled librust_lib_diagd.so + void* handle = dlopen("lib/librust_lib_diagd.so", RTLD_LAZY); + if (!handle) { + handle = dlopen("librust_lib_diagd.so", RTLD_LAZY); + } + if (handle) { + typedef int (*run_tui_fn)(); + run_tui_fn run_tui = (run_tui_fn)dlsym(handle, "diagd_run_tui"); + if (run_tui) { + int ret = run_tui(); + dlclose(handle); + return ret; + } + } + fprintf(stderr, "Не удалось загрузить модуль TUI из librust_lib_diagd.so: %s\n", dlerror()); + return 1; + } + } + + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..0f49c78 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "diagd"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "diagd"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..cccf817 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,10 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..1c1ce71 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* diagd.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "diagd.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* diagd.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* diagd.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.diagd.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/diagd.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/diagd"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.diagd.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/diagd.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/diagd"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.diagd.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/diagd.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/diagd"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..991e99a --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..e725e08 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = diagd + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.diagd + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..dda67b6 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,268 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + build_cli_annotations: + dependency: transitive + description: + name: build_cli_annotations + sha256: e563c2e01de8974566a1998410d3f6f03521788160a02503b0b1f1a46c7b3d95 + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_rust_bridge: + dependency: "direct main" + description: + name: flutter_rust_bridge + sha256: ec69331e2335ab4d456c0a9fc700892c2c85b72b9c0cb39df3ecfe8833d5d5c8 + url: "https://pub.dev" + source: hosted + version: "2.13.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d + url: "https://pub.dev" + source: hosted + version: "1.18.3" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + rust_lib_diagd: + dependency: "direct main" + description: + path: rust_builder + relative: true + source: path + version: "0.0.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + url: "https://pub.dev" + source: hosted + version: "0.7.12" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "1d774bbdf6b72a0b12122fc1560c9c2d2a67db5a4a4cc2bd8a5c990ab20e3188" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0" + url: "https://pub.dev" + source: hosted + version: "15.3.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" +sdks: + dart: ">=3.13.3 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..bfc0e18 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,92 @@ +name: diagd +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.13.3 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + flutter_rust_bridge: 2.13.0 + rust_lib_diagd: + path: rust_builder + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/rust/.gitignore b/rust/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/rust/.gitignore @@ -0,0 +1 @@ +/target diff --git a/rust/Cargo.lock b/rust/Cargo.lock new file mode 100644 index 0000000..b2ff3e6 --- /dev/null +++ b/rust/Cargo.lock @@ -0,0 +1,2090 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "aho-corasick" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" +dependencies = [ + "memchr", +] + +[[package]] +name = "allo-isolate" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "449e356a4864c017286dbbec0e12767ea07efba29e3b7d984194c2a7ff3c4550" +dependencies = [ + "anyhow", + "atomic", + "backtrace", +] + +[[package]] +name = "android_log-sys" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84521a3cf562bc62942e294181d9eef17eb38ceb8c68677bc49f144e4c3d4f8d" + +[[package]] +name = "android_logger" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbb4e440d04be07da1f1bf44fb4495ebd58669372fe0cffa6e48595ac5bd88a3" +dependencies = [ + "android_log-sys", + "env_filter", + "log", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.75" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" + +[[package]] +name = "atomic" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "backtrace" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "build-target" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "832133bbabbbaa9fbdba793456a2827627a7d2b8fb96032fa1e7666d7895832b" + +[[package]] +name = "bumpalo" +version = "3.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" + +[[package]] +name = "bytemuck" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "374d28ec25809ee0e23827c2ab573d729e293f281dfe393500e7ad618baa61c6" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link 0.2.1", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "dart-sys" +version = "4.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57967e4b200d767d091b961d6ab42cc7d0cc14fe9e052e75d0d3cf9eb732d895" +dependencies = [ + "cc", +] + +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "delegate-attr" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51aac4c99b2e6775164b412ea33ae8441b2fde2dbf05a20bc0052a63d08c475b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "encoding_rs" +version = "0.8.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5ef0006ac9ab233c38522f5ae99cae3625151de8f706cacee1cba4b8e2832a" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "env_filter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "flutter_rust_bridge" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24a973d15b8fc7de9fb29cdfbec58a2ac41f6252492d3b882abfdc603e32b34f" +dependencies = [ + "allo-isolate", + "android_logger", + "anyhow", + "build-target", + "bytemuck", + "byteorder", + "console_error_panic_hook", + "dart-sys", + "delegate-attr", + "flutter_rust_bridge_macros", + "futures", + "js-sys", + "lazy_static", + "log", + "oslog", + "portable-atomic", + "threadpool", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "flutter_rust_bridge_macros" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901eec2d226107dad1c55b30f7421c4687bebcf70ed43ca44d1b447ca087b238" +dependencies = [ + "hex", + "md-5", + "proc-macro2", + "quote", + "syn 2.0.39", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" + +[[package]] +name = "futures-executor" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa" + +[[package]] +name = "futures-macro" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + +[[package]] +name = "futures-sink" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" + +[[package]] +name = "futures-task" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" + +[[package]] +name = "futures-util" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "gimli" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hermit-abi" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc2b571658e38e0c01b1fdca3bbbe93c00d3d71693ff2770043f8c29bc7d6f80" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "miniz_oxide" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +dependencies = [ + "adler", +] + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ca4bea16ffc3f443cf7d866912118196bfef4c6a1556ca00f9f9b00bb43f7c" +dependencies = [ + "multiversion-macros", +] + +[[package]] +name = "multiversion-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d416831a7317ef4b08bee00b69cbbb9c8763da7959a7026244d6266869f9c83" +dependencies = [ + "proc-macro2", + "quote", + "rustversion", + "syn 3.0.5", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "native-tls" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "object" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "oslog" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d2043d1f61d77cb2f4b1f7b7b2295f40507f5f8e9d1c8bf10a1ca5f97a3969" +dependencies = [ + "cc", + "dashmap", + "log", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link 0.2.1", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-core", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rust_lib_diagd" +version = "0.1.0" +dependencies = [ + "chrono", + "flutter_rust_bridge", + "regex", + "reqwest", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustls" +version = "0.23.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6725596c3f2c3a0aef021139e145d4eafe314a6623e4680ca83852b2c67ab2ba" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + +[[package]] +name = "system-configuration" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" +dependencies = [ + "bitflags", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" +dependencies = [ + "cfg-if", + "fastrand", + "rustix", + "windows-sys 0.52.0", +] + +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.39", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50c24a44ec86bb68fbecd1b3efed7e85ea5621b39b35ef2766b66cd984f8010f" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" +dependencies = [ + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/rust/Cargo.toml b/rust/Cargo.toml new file mode 100644 index 0000000..5bf663d --- /dev/null +++ b/rust/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "rust_lib_diagd" +version = "0.1.0" +edition = "2021" + +[lib] +name = "rust_lib_diagd" +crate-type = ["cdylib", "staticlib", "rlib"] + +[[bin]] +name = "diagd" +path = "src/bin/diagd.rs" +required-features = ["tui"] + +[features] +default = ["tui", "gui"] +tui = ["dep:ratatui", "dep:crossterm"] +gui = ["dep:flutter_rust_bridge"] + +[dependencies] +diagd-core = { path = "../crates/core" } +tokio = { version = "1", features = ["full"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +regex = "1.10" +reqwest = { version = "0.12", features = ["json"] } +chrono = { version = "0.4", features = ["serde"] } + +# GUI-specific +flutter_rust_bridge = { version = "=2.13.0", optional = true } + +# TUI-specific +ratatui = { version = "0.29", optional = true } +crossterm = { version = "0.28", optional = true } + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] } diff --git a/rust/src/api/diagnostics.rs b/rust/src/api/diagnostics.rs new file mode 100644 index 0000000..8de9302 --- /dev/null +++ b/rust/src/api/diagnostics.rs @@ -0,0 +1,846 @@ +use serde::{Deserialize, Serialize}; + +/// Уровень критичности обнаруженной проблемы +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub enum Severity { + Critical, + Warning, + Info, +} + +/// Исследуемая подсистема ОС Linux / BSD +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub enum Subsystem { + Systemd, + Kernel, + Storage, + Audio, + Network, + Security, + Crashes, +} + +/// Статус состояния подсистемы для сводного дашборда +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SubsystemStatus { + pub name: Subsystem, + pub status: String, + pub issue_count: u32, + pub details: String, +} + +/// Предложение по устранению ошибки с готовой CLI-командой +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FixSuggestion { + pub title: String, + pub command: String, + pub explanation: String, +} + +/// Информация о сбойной системной службе +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FailedService { + pub name: String, + pub init_system: String, + pub state: String, + pub description: String, + pub logs: String, + pub restart_command: String, + pub status_command: String, +} + +/// Элемент диагностического отчета (проблема) +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct IssueItem { + pub id: String, + pub title: String, + pub subsystem: Subsystem, + pub severity: Severity, + pub root_cause: String, + pub explanation: String, + pub fix: Option, + pub raw_log: String, + pub sanitized: bool, + pub permission_denied: bool, +} + +/// Подробный отчет об аппаратном обеспечении системы +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HardwareInfo { + pub cpu: CpuInfo, + pub memory: MemoryInfo, + pub motherboard: MotherboardInfo, + pub gpus: Vec, + pub disks: Vec, + pub network_adapters: Vec, + pub battery: Option, + pub thermals: ThermalsInfo, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CpuInfo { + pub model_name: String, + pub architecture: String, + pub physical_cores: usize, + pub logical_threads: usize, + pub base_frequency_mhz: Option, + pub current_frequency_mhz: Option, + pub l1_cache: String, + pub l2_cache: String, + pub l3_cache: String, + pub virtualization: Option, + pub flags: Vec, + pub microcode: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MemoryInfo { + pub total_bytes: u64, + pub available_bytes: u64, + pub used_bytes: u64, + pub swap_total_bytes: u64, + pub swap_used_bytes: u64, + pub edac_ce_count: u64, + pub edac_ue_count: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MotherboardInfo { + pub vendor: String, + pub product_name: String, + pub version: String, + pub bios_vendor: String, + pub bios_version: String, + pub bios_date: String, + pub chassis_type: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GpuInfo { + pub vendor: String, + pub model: String, + pub driver: String, + pub pci_slot: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PartitionInfo { + pub name: String, + pub path: String, + pub mount_point: Option, + pub fs_type: String, + pub size_bytes: u64, + pub used_bytes: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DiskInfo { + pub name: String, + pub model: String, + pub serial: String, + pub size_bytes: u64, + pub disk_type: String, + pub rotational_speed_rpm: Option, + pub smart_status: String, + pub health_percent: Option, + pub wear_percent: Option, + pub nvme_wear_percent: Option, + pub temperature_c: Option, + pub power_on_hours: Option, + pub power_cycle_count: Option, + pub bad_sectors_count: Option, + pub total_written_tb: Option, + pub partitions: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct NetworkAdapterInfo { + pub interface_name: String, + pub if_type: String, + pub state: String, + pub speed_mbps: Option, + pub mac_address: String, + pub driver: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BatteryInfo { + pub name: String, + pub capacity_percent: u8, + pub health_percent: f32, + pub cycle_count: u32, + pub status: String, + pub is_degraded: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ThermalsInfo { + pub max_cpu_temp_c: f32, + pub thermal_throttled_cores: usize, + pub total_throttle_events: u64, + pub is_actively_throttling: bool, +} + +// --- LIVE METRICS --- +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct LiveMetricsSnapshot { + pub cpu_usage_percent: f32, + pub ram_used_bytes: u64, + pub ram_total_bytes: u64, + pub swap_used_bytes: u64, + pub swap_total_bytes: u64, + pub max_cpu_temp_c: f32, + pub is_throttling: bool, + pub disk_read_kbps: u64, + pub disk_write_kbps: u64, + pub net_rx_kbps: u64, + pub net_tx_kbps: u64, +} + +// --- CRASH DUMPS --- +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct CrashReportInfo { + pub timestamp: String, + pub process_name: String, + pub pid: Option, + pub signal_or_code: String, + pub fault_module: Option, + pub stack_trace_snippet: String, + pub dump_path: Option, +} + +// --- SECURITY AUDIT --- +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct ListeningPortInfo { + pub protocol: String, + pub local_address: String, + pub port: u16, + pub process_name: String, + pub pid: Option, + pub is_public: bool, + pub risk_level: Severity, + pub recommendation: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct SuidAnomalyInfo { + pub path: String, + pub owner: String, + pub permissions: String, + pub risk_reason: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct SecurityCheckItem { + pub category: String, + pub name: String, + pub status: String, + pub is_secure: bool, + pub description: String, + pub remediation: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct SecurityAuditReport { + pub exposed_ports: Vec, + pub suid_anomalies: Vec, + pub hardening_checks: Vec, + pub security_score: u8, +} + +/// Общий итоговый отчет диагностики +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SystemReport { + pub timestamp: String, + pub os_family: String, + pub init_system: String, + pub is_root: bool, + pub subsystems: Vec, + pub issues: Vec, + pub failed_services: Vec, + pub hardware: HardwareInfo, + pub crashes: Vec, + pub security: SecurityAuditReport, + pub llm_analyzed: bool, + pub summary: String, + pub prompt_preview: String, +} + +// Конвертеры из diagd-core в FRB структуры +impl From for Severity { + fn from(s: diagd_core::models::Severity) -> Self { + match s { + diagd_core::models::Severity::Critical => Severity::Critical, + diagd_core::models::Severity::Warning => Severity::Warning, + diagd_core::models::Severity::Info => Severity::Info, + } + } +} + +impl From for diagd_core::models::Severity { + fn from(s: Severity) -> Self { + match s { + Severity::Critical => diagd_core::models::Severity::Critical, + Severity::Warning => diagd_core::models::Severity::Warning, + Severity::Info => diagd_core::models::Severity::Info, + } + } +} + +impl From for Subsystem { + fn from(s: diagd_core::models::Subsystem) -> Self { + match s { + diagd_core::models::Subsystem::Systemd => Subsystem::Systemd, + diagd_core::models::Subsystem::Kernel => Subsystem::Kernel, + diagd_core::models::Subsystem::Storage => Subsystem::Storage, + diagd_core::models::Subsystem::Audio => Subsystem::Audio, + diagd_core::models::Subsystem::Network => Subsystem::Network, + diagd_core::models::Subsystem::Security => Subsystem::Security, + diagd_core::models::Subsystem::Crashes => Subsystem::Crashes, + } + } +} + +impl From for SubsystemStatus { + fn from(s: diagd_core::models::SubsystemStatus) -> Self { + SubsystemStatus { + name: s.name.into(), + status: s.status, + issue_count: s.issue_count, + details: s.details, + } + } +} + +impl From for FixSuggestion { + fn from(f: diagd_core::models::FixSuggestion) -> Self { + FixSuggestion { + title: f.title, + command: f.command, + explanation: f.explanation, + } + } +} + +impl From for FailedService { + fn from(f: diagd_core::models::FailedService) -> Self { + FailedService { + name: f.name, + init_system: f.init_system, + state: f.state, + description: f.description, + logs: f.logs, + restart_command: f.restart_command, + status_command: f.status_command, + } + } +} + +impl From for IssueItem { + fn from(i: diagd_core::models::IssueItem) -> Self { + IssueItem { + id: i.id, + title: i.title, + subsystem: i.subsystem.into(), + severity: i.severity.into(), + root_cause: i.root_cause, + explanation: i.explanation, + fix: i.fix.map(Into::into), + raw_log: i.raw_log, + sanitized: i.sanitized, + permission_denied: i.permission_denied, + } + } +} + +impl From for CpuInfo { + fn from(c: diagd_core::models::CpuInfo) -> Self { + Self { + model_name: c.model_name, + architecture: c.architecture, + physical_cores: c.physical_cores, + logical_threads: c.logical_threads, + base_frequency_mhz: c.base_frequency_mhz, + current_frequency_mhz: c.current_frequency_mhz, + l1_cache: c.l1_cache, + l2_cache: c.l2_cache, + l3_cache: c.l3_cache, + virtualization: c.virtualization, + flags: c.flags, + microcode: c.microcode, + } + } +} + +impl From for MemoryInfo { + fn from(m: diagd_core::models::MemoryInfo) -> Self { + Self { + total_bytes: m.total_bytes, + available_bytes: m.available_bytes, + used_bytes: m.used_bytes, + swap_total_bytes: m.swap_total_bytes, + swap_used_bytes: m.swap_used_bytes, + edac_ce_count: m.edac_ce_count, + edac_ue_count: m.edac_ue_count, + } + } +} + +impl From for MotherboardInfo { + fn from(m: diagd_core::models::MotherboardInfo) -> Self { + Self { + vendor: m.vendor, + product_name: m.product_name, + version: m.version, + bios_vendor: m.bios_vendor, + bios_version: m.bios_version, + bios_date: m.bios_date, + chassis_type: m.chassis_type, + } + } +} + +impl From for GpuInfo { + fn from(g: diagd_core::models::GpuInfo) -> Self { + Self { + vendor: g.vendor, + model: g.model, + driver: g.driver, + pci_slot: g.pci_slot, + } + } +} + +impl From for PartitionInfo { + fn from(p: diagd_core::models::PartitionInfo) -> Self { + Self { + name: p.name, + path: p.path, + mount_point: p.mount_point, + fs_type: p.fs_type, + size_bytes: p.size_bytes, + used_bytes: p.used_bytes, + } + } +} + +impl From for DiskInfo { + fn from(d: diagd_core::models::DiskInfo) -> Self { + Self { + name: d.name, + model: d.model, + serial: d.serial, + size_bytes: d.size_bytes, + disk_type: d.disk_type, + rotational_speed_rpm: d.rotational_speed_rpm, + smart_status: d.smart_status, + health_percent: d.health_percent, + wear_percent: d.wear_percent, + nvme_wear_percent: d.nvme_wear_percent, + temperature_c: d.temperature_c, + power_on_hours: d.power_on_hours, + power_cycle_count: d.power_cycle_count, + bad_sectors_count: d.bad_sectors_count, + total_written_tb: d.total_written_tb, + partitions: d.partitions.into_iter().map(Into::into).collect(), + } + } +} + +impl From for NetworkAdapterInfo { + fn from(n: diagd_core::models::NetworkAdapterInfo) -> Self { + Self { + interface_name: n.interface_name, + if_type: n.if_type, + state: n.state, + speed_mbps: n.speed_mbps, + mac_address: n.mac_address, + driver: n.driver, + } + } +} + +impl From for BatteryInfo { + fn from(b: diagd_core::models::BatteryInfo) -> Self { + Self { + name: b.name, + capacity_percent: b.capacity_percent, + health_percent: b.health_percent, + cycle_count: b.cycle_count, + status: b.status, + is_degraded: b.is_degraded, + } + } +} + +impl From for ThermalsInfo { + fn from(t: diagd_core::models::ThermalsInfo) -> Self { + Self { + max_cpu_temp_c: t.max_cpu_temp_c, + thermal_throttled_cores: t.thermal_throttled_cores, + total_throttle_events: t.total_throttle_events, + is_actively_throttling: t.is_actively_throttling, + } + } +} + +impl From for HardwareInfo { + fn from(h: diagd_core::models::HardwareInfo) -> Self { + Self { + cpu: h.cpu.into(), + memory: h.memory.into(), + motherboard: h.motherboard.into(), + gpus: h.gpus.into_iter().map(Into::into).collect(), + disks: h.disks.into_iter().map(Into::into).collect(), + network_adapters: h.network_adapters.into_iter().map(Into::into).collect(), + battery: h.battery.map(Into::into), + thermals: h.thermals.into(), + } + } +} + +impl From for diagd_core::models::HardwareInfo { + fn from(h: HardwareInfo) -> Self { + diagd_core::models::HardwareInfo { + cpu: diagd_core::models::CpuInfo { + model_name: h.cpu.model_name, + architecture: h.cpu.architecture, + physical_cores: h.cpu.physical_cores, + logical_threads: h.cpu.logical_threads, + base_frequency_mhz: h.cpu.base_frequency_mhz, + current_frequency_mhz: h.cpu.current_frequency_mhz, + l1_cache: h.cpu.l1_cache, + l2_cache: h.cpu.l2_cache, + l3_cache: h.cpu.l3_cache, + virtualization: h.cpu.virtualization, + flags: h.cpu.flags, + microcode: h.cpu.microcode, + }, + memory: diagd_core::models::MemoryInfo { + total_bytes: h.memory.total_bytes, + available_bytes: h.memory.available_bytes, + used_bytes: h.memory.used_bytes, + swap_total_bytes: h.memory.swap_total_bytes, + swap_used_bytes: h.memory.swap_used_bytes, + edac_ce_count: h.memory.edac_ce_count, + edac_ue_count: h.memory.edac_ue_count, + }, + motherboard: diagd_core::models::MotherboardInfo { + vendor: h.motherboard.vendor, + product_name: h.motherboard.product_name, + version: h.motherboard.version, + bios_vendor: h.motherboard.bios_vendor, + bios_version: h.motherboard.bios_version, + bios_date: h.motherboard.bios_date, + chassis_type: h.motherboard.chassis_type, + }, + gpus: h.gpus.into_iter().map(|g| diagd_core::models::GpuInfo { + vendor: g.vendor, + model: g.model, + driver: g.driver, + pci_slot: g.pci_slot, + }).collect(), + disks: h.disks.into_iter().map(|d| diagd_core::models::DiskInfo { + name: d.name, + model: d.model, + serial: d.serial, + size_bytes: d.size_bytes, + disk_type: d.disk_type, + rotational_speed_rpm: d.rotational_speed_rpm, + smart_status: d.smart_status, + health_percent: d.health_percent, + wear_percent: d.wear_percent, + nvme_wear_percent: d.nvme_wear_percent, + temperature_c: d.temperature_c, + power_on_hours: d.power_on_hours, + power_cycle_count: d.power_cycle_count, + bad_sectors_count: d.bad_sectors_count, + total_written_tb: d.total_written_tb, + partitions: d.partitions.into_iter().map(|p| diagd_core::models::PartitionInfo { + name: p.name, + path: p.path, + mount_point: p.mount_point, + fs_type: p.fs_type, + size_bytes: p.size_bytes, + used_bytes: p.used_bytes, + }).collect(), + }).collect(), + network_adapters: h.network_adapters.into_iter().map(|n| diagd_core::models::NetworkAdapterInfo { + interface_name: n.interface_name, + if_type: n.if_type, + state: n.state, + speed_mbps: n.speed_mbps, + mac_address: n.mac_address, + driver: n.driver, + }).collect(), + battery: h.battery.map(|b| diagd_core::models::BatteryInfo { + name: b.name, + capacity_percent: b.capacity_percent, + health_percent: b.health_percent, + cycle_count: b.cycle_count, + status: b.status, + is_degraded: b.is_degraded, + }), + thermals: diagd_core::models::ThermalsInfo { + max_cpu_temp_c: h.thermals.max_cpu_temp_c, + thermal_throttled_cores: h.thermals.thermal_throttled_cores, + total_throttle_events: h.thermals.total_throttle_events, + is_actively_throttling: h.thermals.is_actively_throttling, + }, + } + } +} + +impl From for LiveMetricsSnapshot { + fn from(s: diagd_core::models::LiveMetricsSnapshot) -> Self { + LiveMetricsSnapshot { + cpu_usage_percent: s.cpu_usage_percent, + ram_used_bytes: s.ram_used_bytes, + ram_total_bytes: s.ram_total_bytes, + swap_used_bytes: s.swap_used_bytes, + swap_total_bytes: s.swap_total_bytes, + max_cpu_temp_c: s.max_cpu_temp_c, + is_throttling: s.is_throttling, + disk_read_kbps: s.disk_read_kbps, + disk_write_kbps: s.disk_write_kbps, + net_rx_kbps: s.net_rx_kbps, + net_tx_kbps: s.net_tx_kbps, + } + } +} + +impl From for CrashReportInfo { + fn from(c: diagd_core::models::CrashReportInfo) -> Self { + CrashReportInfo { + timestamp: c.timestamp, + process_name: c.process_name, + pid: c.pid, + signal_or_code: c.signal_or_code, + fault_module: c.fault_module, + stack_trace_snippet: c.stack_trace_snippet, + dump_path: c.dump_path, + } + } +} + +impl From for diagd_core::models::CrashReportInfo { + fn from(c: CrashReportInfo) -> Self { + diagd_core::models::CrashReportInfo { + timestamp: c.timestamp, + process_name: c.process_name, + pid: c.pid, + signal_or_code: c.signal_or_code, + fault_module: c.fault_module, + stack_trace_snippet: c.stack_trace_snippet, + dump_path: c.dump_path, + } + } +} + +impl From for ListeningPortInfo { + fn from(p: diagd_core::models::ListeningPortInfo) -> Self { + ListeningPortInfo { + protocol: p.protocol, + local_address: p.local_address, + port: p.port, + process_name: p.process_name, + pid: p.pid, + is_public: p.is_public, + risk_level: p.risk_level.into(), + recommendation: p.recommendation, + } + } +} + +impl From for diagd_core::models::ListeningPortInfo { + fn from(p: ListeningPortInfo) -> Self { + diagd_core::models::ListeningPortInfo { + protocol: p.protocol, + local_address: p.local_address, + port: p.port, + process_name: p.process_name, + pid: p.pid, + is_public: p.is_public, + risk_level: p.risk_level.into(), + recommendation: p.recommendation, + } + } +} + +impl From for SuidAnomalyInfo { + fn from(s: diagd_core::models::SuidAnomalyInfo) -> Self { + SuidAnomalyInfo { + path: s.path, + owner: s.owner, + permissions: s.permissions, + risk_reason: s.risk_reason, + } + } +} + +impl From for diagd_core::models::SuidAnomalyInfo { + fn from(s: SuidAnomalyInfo) -> Self { + diagd_core::models::SuidAnomalyInfo { + path: s.path, + owner: s.owner, + permissions: s.permissions, + risk_reason: s.risk_reason, + } + } +} + +impl From for SecurityCheckItem { + fn from(c: diagd_core::models::SecurityCheckItem) -> Self { + SecurityCheckItem { + category: c.category, + name: c.name, + status: c.status, + is_secure: c.is_secure, + description: c.description, + remediation: c.remediation, + } + } +} + +impl From for diagd_core::models::SecurityCheckItem { + fn from(c: SecurityCheckItem) -> Self { + diagd_core::models::SecurityCheckItem { + category: c.category, + name: c.name, + status: c.status, + is_secure: c.is_secure, + description: c.description, + remediation: c.remediation, + } + } +} + +impl From for SecurityAuditReport { + fn from(s: diagd_core::models::SecurityAuditReport) -> Self { + SecurityAuditReport { + exposed_ports: s.exposed_ports.into_iter().map(Into::into).collect(), + suid_anomalies: s.suid_anomalies.into_iter().map(Into::into).collect(), + hardening_checks: s.hardening_checks.into_iter().map(Into::into).collect(), + security_score: s.security_score, + } + } +} + +impl From for diagd_core::models::SecurityAuditReport { + fn from(s: SecurityAuditReport) -> Self { + diagd_core::models::SecurityAuditReport { + exposed_ports: s.exposed_ports.into_iter().map(Into::into).collect(), + suid_anomalies: s.suid_anomalies.into_iter().map(Into::into).collect(), + hardening_checks: s.hardening_checks.into_iter().map(Into::into).collect(), + security_score: s.security_score, + } + } +} + +impl From for SystemReport { + fn from(r: diagd_core::models::SystemReport) -> Self { + SystemReport { + timestamp: r.timestamp, + os_family: r.os_family, + init_system: r.init_system, + is_root: r.is_root, + subsystems: r.subsystems.into_iter().map(Into::into).collect(), + issues: r.issues.into_iter().map(Into::into).collect(), + failed_services: r.failed_services.into_iter().map(Into::into).collect(), + hardware: r.hardware.into(), + crashes: r.crashes.into_iter().map(Into::into).collect(), + security: r.security.into(), + llm_analyzed: r.llm_analyzed, + summary: r.summary, + prompt_preview: r.prompt_preview, + } + } +} + +/// Запрашивает права суперпользователя в графическом режиме через Polkit (pkexec) +pub fn request_gui_privileges() -> bool { + let status = diagd_core::auth::PrivilegeManager::request_privileges(diagd_core::auth::AuthMode::Gui); + matches!(status, diagd_core::auth::PrivilegeStatus::AlreadyRoot | diagd_core::auth::PrivilegeStatus::Elevated) +} + +/// Сканирует состояние системы, очищает логи от персональных данных, +/// генерирует структурированный промпт для LLM и формирует итоговый аналитический отчет. +pub async fn scan_system_and_analyze() -> Result { + let core_report = diagd_core::analyst::run_scan_with_mode(diagd_core::auth::AuthMode::Gui).await?; + Ok(core_report.into()) +} + +/// Возвращает мгновенный снимок телеметрии системы в реальном времени (CPU %, RAM, частоты, температуры, IO) +pub fn get_live_metrics() -> LiveMetricsSnapshot { + diagd_core::LiveMetricsScanner::sample().into() +} + +/// Экспортирует полный архив Debug Bundle (.tar.gz, standalone HTML и markdown). +/// Возвращает путь к сохраненному архиву. +pub fn export_debug_bundle(report: SystemReport) -> Result { + let core_report = diagd_core::models::SystemReport { + timestamp: report.timestamp, + os_family: report.os_family, + init_system: report.init_system, + is_root: report.is_root, + subsystems: report.subsystems.into_iter().map(|s| diagd_core::models::SubsystemStatus { + name: match s.name { + Subsystem::Systemd => diagd_core::models::Subsystem::Systemd, + Subsystem::Kernel => diagd_core::models::Subsystem::Kernel, + Subsystem::Storage => diagd_core::models::Subsystem::Storage, + Subsystem::Audio => diagd_core::models::Subsystem::Audio, + Subsystem::Network => diagd_core::models::Subsystem::Network, + Subsystem::Security => diagd_core::models::Subsystem::Security, + Subsystem::Crashes => diagd_core::models::Subsystem::Crashes, + }, + status: s.status, + issue_count: s.issue_count, + details: s.details, + }).collect(), + issues: report.issues.into_iter().map(|i| diagd_core::models::IssueItem { + id: i.id, + title: i.title, + subsystem: match i.subsystem { + Subsystem::Systemd => diagd_core::models::Subsystem::Systemd, + Subsystem::Kernel => diagd_core::models::Subsystem::Kernel, + Subsystem::Storage => diagd_core::models::Subsystem::Storage, + Subsystem::Audio => diagd_core::models::Subsystem::Audio, + Subsystem::Network => diagd_core::models::Subsystem::Network, + Subsystem::Security => diagd_core::models::Subsystem::Security, + Subsystem::Crashes => diagd_core::models::Subsystem::Crashes, + }, + severity: match i.severity { + Severity::Critical => diagd_core::models::Severity::Critical, + Severity::Warning => diagd_core::models::Severity::Warning, + Severity::Info => diagd_core::models::Severity::Info, + }, + root_cause: i.root_cause, + explanation: i.explanation, + fix: i.fix.map(|f| diagd_core::models::FixSuggestion { + title: f.title, + command: f.command, + explanation: f.explanation, + }), + raw_log: i.raw_log, + sanitized: i.sanitized, + permission_denied: i.permission_denied, + }).collect(), + failed_services: report.failed_services.into_iter().map(|f| diagd_core::models::FailedService { + name: f.name, + init_system: f.init_system, + state: f.state, + description: f.description, + logs: f.logs, + restart_command: f.restart_command, + status_command: f.status_command, + }).collect(), + hardware: report.hardware.into(), + crashes: report.crashes.into_iter().map(Into::into).collect(), + security: report.security.into(), + llm_analyzed: report.llm_analyzed, + summary: report.summary, + prompt_preview: report.prompt_preview, + }; + + diagd_core::BundleExporter::export_bundle(&core_report) +} diff --git a/rust/src/api/mod.rs b/rust/src/api/mod.rs new file mode 100644 index 0000000..b47c2b0 --- /dev/null +++ b/rust/src/api/mod.rs @@ -0,0 +1,2 @@ +pub mod simple; +pub mod diagnostics; diff --git a/rust/src/api/simple.rs b/rust/src/api/simple.rs new file mode 100644 index 0000000..4360c82 --- /dev/null +++ b/rust/src/api/simple.rs @@ -0,0 +1,10 @@ +#[flutter_rust_bridge::frb(sync)] // Synchronous mode for simplicity of the demo +pub fn greet(name: String) -> String { + format!("Hello, {name}!") +} + +#[flutter_rust_bridge::frb(init)] +pub fn init_app() { + // Default utilities - feel free to customize + flutter_rust_bridge::setup_default_user_utils(); +} diff --git a/rust/src/bin/diagd.rs b/rust/src/bin/diagd.rs new file mode 100644 index 0000000..d247222 --- /dev/null +++ b/rust/src/bin/diagd.rs @@ -0,0 +1,3 @@ +fn main() -> Result<(), Box> { + rust_lib_diagd::tui::run_tui() +} diff --git a/rust/src/frb_generated.rs b/rust/src/frb_generated.rs new file mode 100644 index 0000000..d9773cc --- /dev/null +++ b/rust/src/frb_generated.rs @@ -0,0 +1,2636 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.13.0. + +#![allow( + non_camel_case_types, + unused, + non_snake_case, + clippy::needless_return, + clippy::redundant_closure_call, + clippy::redundant_closure, + clippy::useless_conversion, + clippy::unit_arg, + clippy::unused_unit, + clippy::double_parens, + clippy::let_and_return, + clippy::too_many_arguments, + clippy::match_single_binding, + clippy::clone_on_copy, + clippy::let_unit_value, + clippy::deref_addrof, + clippy::explicit_auto_deref, + clippy::borrow_deref_ref, + clippy::uninlined_format_args, + clippy::needless_borrow, + mismatched_lifetime_syntaxes +)] + +// Section: imports + +use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; +use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; +use flutter_rust_bridge::{Handler, IntoIntoDart}; + +// Section: boilerplate + +flutter_rust_bridge::frb_generated_boilerplate!( + default_stream_sink_codec = SseCodec, + default_rust_opaque = RustOpaqueMoi, + default_rust_auto_opaque = RustAutoOpaqueMoi, +); +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.13.0"; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 324119519; + +// Section: executor + +flutter_rust_bridge::frb_generated_default_handler!(); + +// Section: wire_funcs + +fn wire__crate__api__diagnostics__crash_report_info_default_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "crash_report_info_default", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = + Ok::<_, ()>(crate::api::diagnostics::CrashReportInfo::default())?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__diagnostics__export_debug_bundle_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "export_debug_bundle", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_report = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, String>((move || { + let output_ok = crate::api::diagnostics::export_debug_bundle(api_report)?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__diagnostics__get_live_metrics_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "get_live_metrics", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = Ok::<_, ()>(crate::api::diagnostics::get_live_metrics())?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__simple__greet_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "greet", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_name = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Ok::<_, ()>(crate::api::simple::greet(api_name))?; + std::result::Result::Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__simple__init_app_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "init_app", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = Ok::<_, ()>({ + crate::api::simple::init_app(); + })?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__diagnostics__live_metrics_snapshot_default_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "live_metrics_snapshot_default", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = + Ok::<_, ()>(crate::api::diagnostics::LiveMetricsSnapshot::default())?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__diagnostics__request_gui_privileges_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "request_gui_privileges", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = Ok::<_, ()>(crate::api::diagnostics::request_gui_privileges())?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__diagnostics__scan_system_and_analyze_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "scan_system_and_analyze", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| async move { + transform_result_sse::<_, String>( + (move || async move { + let output_ok = crate::api::diagnostics::scan_system_and_analyze().await?; + std::result::Result::Ok(output_ok) + })() + .await, + ) + } + }, + ) +} +fn wire__crate__api__diagnostics__security_audit_report_default_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "security_audit_report_default", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = + Ok::<_, ()>(crate::api::diagnostics::SecurityAuditReport::default())?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__diagnostics__security_check_item_default_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "security_check_item_default", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = + Ok::<_, ()>(crate::api::diagnostics::SecurityCheckItem::default())?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__diagnostics__suid_anomaly_info_default_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "suid_anomaly_info_default", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = + Ok::<_, ()>(crate::api::diagnostics::SuidAnomalyInfo::default())?; + std::result::Result::Ok(output_ok) + })()) + } + }, + ) +} + +// Section: dart2rust + +impl SseDecode for String { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = >::sse_decode(deserializer); + return String::from_utf8(inner).unwrap(); + } +} + +impl SseDecode for crate::api::diagnostics::BatteryInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_name = ::sse_decode(deserializer); + let mut var_capacityPercent = ::sse_decode(deserializer); + let mut var_healthPercent = ::sse_decode(deserializer); + let mut var_cycleCount = ::sse_decode(deserializer); + let mut var_status = ::sse_decode(deserializer); + let mut var_isDegraded = ::sse_decode(deserializer); + return crate::api::diagnostics::BatteryInfo { + name: var_name, + capacity_percent: var_capacityPercent, + health_percent: var_healthPercent, + cycle_count: var_cycleCount, + status: var_status, + is_degraded: var_isDegraded, + }; + } +} + +impl SseDecode for bool { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u8().unwrap() != 0 + } +} + +impl SseDecode for crate::api::diagnostics::CpuInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_modelName = ::sse_decode(deserializer); + let mut var_architecture = ::sse_decode(deserializer); + let mut var_physicalCores = ::sse_decode(deserializer); + let mut var_logicalThreads = ::sse_decode(deserializer); + let mut var_baseFrequencyMhz = >::sse_decode(deserializer); + let mut var_currentFrequencyMhz = >::sse_decode(deserializer); + let mut var_l1Cache = ::sse_decode(deserializer); + let mut var_l2Cache = ::sse_decode(deserializer); + let mut var_l3Cache = ::sse_decode(deserializer); + let mut var_virtualization = >::sse_decode(deserializer); + let mut var_flags = >::sse_decode(deserializer); + let mut var_microcode = ::sse_decode(deserializer); + return crate::api::diagnostics::CpuInfo { + model_name: var_modelName, + architecture: var_architecture, + physical_cores: var_physicalCores, + logical_threads: var_logicalThreads, + base_frequency_mhz: var_baseFrequencyMhz, + current_frequency_mhz: var_currentFrequencyMhz, + l1_cache: var_l1Cache, + l2_cache: var_l2Cache, + l3_cache: var_l3Cache, + virtualization: var_virtualization, + flags: var_flags, + microcode: var_microcode, + }; + } +} + +impl SseDecode for crate::api::diagnostics::CrashReportInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_timestamp = ::sse_decode(deserializer); + let mut var_processName = ::sse_decode(deserializer); + let mut var_pid = >::sse_decode(deserializer); + let mut var_signalOrCode = ::sse_decode(deserializer); + let mut var_faultModule = >::sse_decode(deserializer); + let mut var_stackTraceSnippet = ::sse_decode(deserializer); + let mut var_dumpPath = >::sse_decode(deserializer); + return crate::api::diagnostics::CrashReportInfo { + timestamp: var_timestamp, + process_name: var_processName, + pid: var_pid, + signal_or_code: var_signalOrCode, + fault_module: var_faultModule, + stack_trace_snippet: var_stackTraceSnippet, + dump_path: var_dumpPath, + }; + } +} + +impl SseDecode for crate::api::diagnostics::DiskInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_name = ::sse_decode(deserializer); + let mut var_model = ::sse_decode(deserializer); + let mut var_serial = ::sse_decode(deserializer); + let mut var_sizeBytes = ::sse_decode(deserializer); + let mut var_diskType = ::sse_decode(deserializer); + let mut var_rotationalSpeedRpm = >::sse_decode(deserializer); + let mut var_smartStatus = ::sse_decode(deserializer); + let mut var_healthPercent = >::sse_decode(deserializer); + let mut var_wearPercent = >::sse_decode(deserializer); + let mut var_nvmeWearPercent = >::sse_decode(deserializer); + let mut var_temperatureC = >::sse_decode(deserializer); + let mut var_powerOnHours = >::sse_decode(deserializer); + let mut var_powerCycleCount = >::sse_decode(deserializer); + let mut var_badSectorsCount = >::sse_decode(deserializer); + let mut var_totalWrittenTb = >::sse_decode(deserializer); + let mut var_partitions = + >::sse_decode(deserializer); + return crate::api::diagnostics::DiskInfo { + name: var_name, + model: var_model, + serial: var_serial, + size_bytes: var_sizeBytes, + disk_type: var_diskType, + rotational_speed_rpm: var_rotationalSpeedRpm, + smart_status: var_smartStatus, + health_percent: var_healthPercent, + wear_percent: var_wearPercent, + nvme_wear_percent: var_nvmeWearPercent, + temperature_c: var_temperatureC, + power_on_hours: var_powerOnHours, + power_cycle_count: var_powerCycleCount, + bad_sectors_count: var_badSectorsCount, + total_written_tb: var_totalWrittenTb, + partitions: var_partitions, + }; + } +} + +impl SseDecode for f32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_f32::().unwrap() + } +} + +impl SseDecode for f64 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_f64::().unwrap() + } +} + +impl SseDecode for crate::api::diagnostics::FailedService { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_name = ::sse_decode(deserializer); + let mut var_initSystem = ::sse_decode(deserializer); + let mut var_state = ::sse_decode(deserializer); + let mut var_description = ::sse_decode(deserializer); + let mut var_logs = ::sse_decode(deserializer); + let mut var_restartCommand = ::sse_decode(deserializer); + let mut var_statusCommand = ::sse_decode(deserializer); + return crate::api::diagnostics::FailedService { + name: var_name, + init_system: var_initSystem, + state: var_state, + description: var_description, + logs: var_logs, + restart_command: var_restartCommand, + status_command: var_statusCommand, + }; + } +} + +impl SseDecode for crate::api::diagnostics::FixSuggestion { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_title = ::sse_decode(deserializer); + let mut var_command = ::sse_decode(deserializer); + let mut var_explanation = ::sse_decode(deserializer); + return crate::api::diagnostics::FixSuggestion { + title: var_title, + command: var_command, + explanation: var_explanation, + }; + } +} + +impl SseDecode for crate::api::diagnostics::GpuInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_vendor = ::sse_decode(deserializer); + let mut var_model = ::sse_decode(deserializer); + let mut var_driver = ::sse_decode(deserializer); + let mut var_pciSlot = ::sse_decode(deserializer); + return crate::api::diagnostics::GpuInfo { + vendor: var_vendor, + model: var_model, + driver: var_driver, + pci_slot: var_pciSlot, + }; + } +} + +impl SseDecode for crate::api::diagnostics::HardwareInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_cpu = ::sse_decode(deserializer); + let mut var_memory = ::sse_decode(deserializer); + let mut var_motherboard = + ::sse_decode(deserializer); + let mut var_gpus = >::sse_decode(deserializer); + let mut var_disks = >::sse_decode(deserializer); + let mut var_networkAdapters = + >::sse_decode(deserializer); + let mut var_battery = + >::sse_decode(deserializer); + let mut var_thermals = ::sse_decode(deserializer); + return crate::api::diagnostics::HardwareInfo { + cpu: var_cpu, + memory: var_memory, + motherboard: var_motherboard, + gpus: var_gpus, + disks: var_disks, + network_adapters: var_networkAdapters, + battery: var_battery, + thermals: var_thermals, + }; + } +} + +impl SseDecode for i32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_i32::().unwrap() + } +} + +impl SseDecode for crate::api::diagnostics::IssueItem { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_id = ::sse_decode(deserializer); + let mut var_title = ::sse_decode(deserializer); + let mut var_subsystem = ::sse_decode(deserializer); + let mut var_severity = ::sse_decode(deserializer); + let mut var_rootCause = ::sse_decode(deserializer); + let mut var_explanation = ::sse_decode(deserializer); + let mut var_fix = + >::sse_decode(deserializer); + let mut var_rawLog = ::sse_decode(deserializer); + let mut var_sanitized = ::sse_decode(deserializer); + let mut var_permissionDenied = ::sse_decode(deserializer); + return crate::api::diagnostics::IssueItem { + id: var_id, + title: var_title, + subsystem: var_subsystem, + severity: var_severity, + root_cause: var_rootCause, + explanation: var_explanation, + fix: var_fix, + raw_log: var_rawLog, + sanitized: var_sanitized, + permission_denied: var_permissionDenied, + }; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode( + deserializer, + )); + } + return ans_; + } +} + +impl SseDecode for crate::api::diagnostics::ListeningPortInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_protocol = ::sse_decode(deserializer); + let mut var_localAddress = ::sse_decode(deserializer); + let mut var_port = ::sse_decode(deserializer); + let mut var_processName = ::sse_decode(deserializer); + let mut var_pid = >::sse_decode(deserializer); + let mut var_isPublic = ::sse_decode(deserializer); + let mut var_riskLevel = ::sse_decode(deserializer); + let mut var_recommendation = ::sse_decode(deserializer); + return crate::api::diagnostics::ListeningPortInfo { + protocol: var_protocol, + local_address: var_localAddress, + port: var_port, + process_name: var_processName, + pid: var_pid, + is_public: var_isPublic, + risk_level: var_riskLevel, + recommendation: var_recommendation, + }; + } +} + +impl SseDecode for crate::api::diagnostics::LiveMetricsSnapshot { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_cpuUsagePercent = ::sse_decode(deserializer); + let mut var_ramUsedBytes = ::sse_decode(deserializer); + let mut var_ramTotalBytes = ::sse_decode(deserializer); + let mut var_swapUsedBytes = ::sse_decode(deserializer); + let mut var_swapTotalBytes = ::sse_decode(deserializer); + let mut var_maxCpuTempC = ::sse_decode(deserializer); + let mut var_isThrottling = ::sse_decode(deserializer); + let mut var_diskReadKbps = ::sse_decode(deserializer); + let mut var_diskWriteKbps = ::sse_decode(deserializer); + let mut var_netRxKbps = ::sse_decode(deserializer); + let mut var_netTxKbps = ::sse_decode(deserializer); + return crate::api::diagnostics::LiveMetricsSnapshot { + cpu_usage_percent: var_cpuUsagePercent, + ram_used_bytes: var_ramUsedBytes, + ram_total_bytes: var_ramTotalBytes, + swap_used_bytes: var_swapUsedBytes, + swap_total_bytes: var_swapTotalBytes, + max_cpu_temp_c: var_maxCpuTempC, + is_throttling: var_isThrottling, + disk_read_kbps: var_diskReadKbps, + disk_write_kbps: var_diskWriteKbps, + net_rx_kbps: var_netRxKbps, + net_tx_kbps: var_netTxKbps, + }; + } +} + +impl SseDecode for crate::api::diagnostics::MemoryInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_totalBytes = ::sse_decode(deserializer); + let mut var_availableBytes = ::sse_decode(deserializer); + let mut var_usedBytes = ::sse_decode(deserializer); + let mut var_swapTotalBytes = ::sse_decode(deserializer); + let mut var_swapUsedBytes = ::sse_decode(deserializer); + let mut var_edacCeCount = ::sse_decode(deserializer); + let mut var_edacUeCount = ::sse_decode(deserializer); + return crate::api::diagnostics::MemoryInfo { + total_bytes: var_totalBytes, + available_bytes: var_availableBytes, + used_bytes: var_usedBytes, + swap_total_bytes: var_swapTotalBytes, + swap_used_bytes: var_swapUsedBytes, + edac_ce_count: var_edacCeCount, + edac_ue_count: var_edacUeCount, + }; + } +} + +impl SseDecode for crate::api::diagnostics::MotherboardInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_vendor = ::sse_decode(deserializer); + let mut var_productName = ::sse_decode(deserializer); + let mut var_version = ::sse_decode(deserializer); + let mut var_biosVendor = ::sse_decode(deserializer); + let mut var_biosVersion = ::sse_decode(deserializer); + let mut var_biosDate = ::sse_decode(deserializer); + let mut var_chassisType = ::sse_decode(deserializer); + return crate::api::diagnostics::MotherboardInfo { + vendor: var_vendor, + product_name: var_productName, + version: var_version, + bios_vendor: var_biosVendor, + bios_version: var_biosVersion, + bios_date: var_biosDate, + chassis_type: var_chassisType, + }; + } +} + +impl SseDecode for crate::api::diagnostics::NetworkAdapterInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_interfaceName = ::sse_decode(deserializer); + let mut var_ifType = ::sse_decode(deserializer); + let mut var_state = ::sse_decode(deserializer); + let mut var_speedMbps = >::sse_decode(deserializer); + let mut var_macAddress = ::sse_decode(deserializer); + let mut var_driver = ::sse_decode(deserializer); + return crate::api::diagnostics::NetworkAdapterInfo { + interface_name: var_interfaceName, + if_type: var_ifType, + state: var_state, + speed_mbps: var_speedMbps, + mac_address: var_macAddress, + driver: var_driver, + }; + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode( + deserializer, + )); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode( + deserializer, + )); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + +impl SseDecode for crate::api::diagnostics::PartitionInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_name = ::sse_decode(deserializer); + let mut var_path = ::sse_decode(deserializer); + let mut var_mountPoint = >::sse_decode(deserializer); + let mut var_fsType = ::sse_decode(deserializer); + let mut var_sizeBytes = ::sse_decode(deserializer); + let mut var_usedBytes = ::sse_decode(deserializer); + return crate::api::diagnostics::PartitionInfo { + name: var_name, + path: var_path, + mount_point: var_mountPoint, + fs_type: var_fsType, + size_bytes: var_sizeBytes, + used_bytes: var_usedBytes, + }; + } +} + +impl SseDecode for crate::api::diagnostics::SecurityAuditReport { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_exposedPorts = + >::sse_decode(deserializer); + let mut var_suidAnomalies = + >::sse_decode(deserializer); + let mut var_hardeningChecks = + >::sse_decode(deserializer); + let mut var_securityScore = ::sse_decode(deserializer); + return crate::api::diagnostics::SecurityAuditReport { + exposed_ports: var_exposedPorts, + suid_anomalies: var_suidAnomalies, + hardening_checks: var_hardeningChecks, + security_score: var_securityScore, + }; + } +} + +impl SseDecode for crate::api::diagnostics::SecurityCheckItem { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_category = ::sse_decode(deserializer); + let mut var_name = ::sse_decode(deserializer); + let mut var_status = ::sse_decode(deserializer); + let mut var_isSecure = ::sse_decode(deserializer); + let mut var_description = ::sse_decode(deserializer); + let mut var_remediation = >::sse_decode(deserializer); + return crate::api::diagnostics::SecurityCheckItem { + category: var_category, + name: var_name, + status: var_status, + is_secure: var_isSecure, + description: var_description, + remediation: var_remediation, + }; + } +} + +impl SseDecode for crate::api::diagnostics::Severity { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = ::sse_decode(deserializer); + return match inner { + 0 => crate::api::diagnostics::Severity::Critical, + 1 => crate::api::diagnostics::Severity::Warning, + 2 => crate::api::diagnostics::Severity::Info, + _ => unreachable!("Invalid variant for Severity: {}", inner), + }; + } +} + +impl SseDecode for crate::api::diagnostics::Subsystem { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = ::sse_decode(deserializer); + return match inner { + 0 => crate::api::diagnostics::Subsystem::Systemd, + 1 => crate::api::diagnostics::Subsystem::Kernel, + 2 => crate::api::diagnostics::Subsystem::Storage, + 3 => crate::api::diagnostics::Subsystem::Audio, + 4 => crate::api::diagnostics::Subsystem::Network, + 5 => crate::api::diagnostics::Subsystem::Security, + 6 => crate::api::diagnostics::Subsystem::Crashes, + _ => unreachable!("Invalid variant for Subsystem: {}", inner), + }; + } +} + +impl SseDecode for crate::api::diagnostics::SubsystemStatus { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_name = ::sse_decode(deserializer); + let mut var_status = ::sse_decode(deserializer); + let mut var_issueCount = ::sse_decode(deserializer); + let mut var_details = ::sse_decode(deserializer); + return crate::api::diagnostics::SubsystemStatus { + name: var_name, + status: var_status, + issue_count: var_issueCount, + details: var_details, + }; + } +} + +impl SseDecode for crate::api::diagnostics::SuidAnomalyInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_path = ::sse_decode(deserializer); + let mut var_owner = ::sse_decode(deserializer); + let mut var_permissions = ::sse_decode(deserializer); + let mut var_riskReason = ::sse_decode(deserializer); + return crate::api::diagnostics::SuidAnomalyInfo { + path: var_path, + owner: var_owner, + permissions: var_permissions, + risk_reason: var_riskReason, + }; + } +} + +impl SseDecode for crate::api::diagnostics::SystemReport { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_timestamp = ::sse_decode(deserializer); + let mut var_osFamily = ::sse_decode(deserializer); + let mut var_initSystem = ::sse_decode(deserializer); + let mut var_isRoot = ::sse_decode(deserializer); + let mut var_subsystems = + >::sse_decode(deserializer); + let mut var_issues = >::sse_decode(deserializer); + let mut var_failedServices = + >::sse_decode(deserializer); + let mut var_hardware = ::sse_decode(deserializer); + let mut var_crashes = + >::sse_decode(deserializer); + let mut var_security = + ::sse_decode(deserializer); + let mut var_llmAnalyzed = ::sse_decode(deserializer); + let mut var_summary = ::sse_decode(deserializer); + let mut var_promptPreview = ::sse_decode(deserializer); + return crate::api::diagnostics::SystemReport { + timestamp: var_timestamp, + os_family: var_osFamily, + init_system: var_initSystem, + is_root: var_isRoot, + subsystems: var_subsystems, + issues: var_issues, + failed_services: var_failedServices, + hardware: var_hardware, + crashes: var_crashes, + security: var_security, + llm_analyzed: var_llmAnalyzed, + summary: var_summary, + prompt_preview: var_promptPreview, + }; + } +} + +impl SseDecode for crate::api::diagnostics::ThermalsInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_maxCpuTempC = ::sse_decode(deserializer); + let mut var_thermalThrottledCores = ::sse_decode(deserializer); + let mut var_totalThrottleEvents = ::sse_decode(deserializer); + let mut var_isActivelyThrottling = ::sse_decode(deserializer); + return crate::api::diagnostics::ThermalsInfo { + max_cpu_temp_c: var_maxCpuTempC, + thermal_throttled_cores: var_thermalThrottledCores, + total_throttle_events: var_totalThrottleEvents, + is_actively_throttling: var_isActivelyThrottling, + }; + } +} + +impl SseDecode for u16 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u16::().unwrap() + } +} + +impl SseDecode for u32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u32::().unwrap() + } +} + +impl SseDecode for u64 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u64::().unwrap() + } +} + +impl SseDecode for u8 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u8().unwrap() + } +} + +impl SseDecode for () { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {} +} + +impl SseDecode for usize { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + deserializer.cursor.read_u64::().unwrap() as _ + } +} + +fn pde_ffi_dispatcher_primary_impl( + func_id: i32, + port: flutter_rust_bridge::for_generated::MessagePort, + ptr: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len: i32, + data_len: i32, +) { + // Codec=Pde (Serialization + dispatch), see doc to use other codecs + match func_id { + 1 => wire__crate__api__diagnostics__crash_report_info_default_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 2 => wire__crate__api__diagnostics__export_debug_bundle_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 3 => { + wire__crate__api__diagnostics__get_live_metrics_impl(port, ptr, rust_vec_len, data_len) + } + 5 => wire__crate__api__simple__init_app_impl(port, ptr, rust_vec_len, data_len), + 6 => wire__crate__api__diagnostics__live_metrics_snapshot_default_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 7 => wire__crate__api__diagnostics__request_gui_privileges_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 8 => wire__crate__api__diagnostics__scan_system_and_analyze_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 9 => wire__crate__api__diagnostics__security_audit_report_default_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 10 => wire__crate__api__diagnostics__security_check_item_default_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 11 => wire__crate__api__diagnostics__suid_anomaly_info_default_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + _ => unreachable!(), + } +} + +fn pde_ffi_dispatcher_sync_impl( + func_id: i32, + ptr: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len: i32, + data_len: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + // Codec=Pde (Serialization + dispatch), see doc to use other codecs + match func_id { + 4 => wire__crate__api__simple__greet_impl(ptr, rust_vec_len, data_len), + _ => unreachable!(), + } +} + +// Section: rust2dart + +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::BatteryInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.name.into_into_dart().into_dart(), + self.capacity_percent.into_into_dart().into_dart(), + self.health_percent.into_into_dart().into_dart(), + self.cycle_count.into_into_dart().into_dart(), + self.status.into_into_dart().into_dart(), + self.is_degraded.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::BatteryInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::BatteryInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::BatteryInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::CpuInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.model_name.into_into_dart().into_dart(), + self.architecture.into_into_dart().into_dart(), + self.physical_cores.into_into_dart().into_dart(), + self.logical_threads.into_into_dart().into_dart(), + self.base_frequency_mhz.into_into_dart().into_dart(), + self.current_frequency_mhz.into_into_dart().into_dart(), + self.l1_cache.into_into_dart().into_dart(), + self.l2_cache.into_into_dart().into_dart(), + self.l3_cache.into_into_dart().into_dart(), + self.virtualization.into_into_dart().into_dart(), + self.flags.into_into_dart().into_dart(), + self.microcode.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::CpuInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::CpuInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::CpuInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::CrashReportInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.timestamp.into_into_dart().into_dart(), + self.process_name.into_into_dart().into_dart(), + self.pid.into_into_dart().into_dart(), + self.signal_or_code.into_into_dart().into_dart(), + self.fault_module.into_into_dart().into_dart(), + self.stack_trace_snippet.into_into_dart().into_dart(), + self.dump_path.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::CrashReportInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::CrashReportInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::CrashReportInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::DiskInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.name.into_into_dart().into_dart(), + self.model.into_into_dart().into_dart(), + self.serial.into_into_dart().into_dart(), + self.size_bytes.into_into_dart().into_dart(), + self.disk_type.into_into_dart().into_dart(), + self.rotational_speed_rpm.into_into_dart().into_dart(), + self.smart_status.into_into_dart().into_dart(), + self.health_percent.into_into_dart().into_dart(), + self.wear_percent.into_into_dart().into_dart(), + self.nvme_wear_percent.into_into_dart().into_dart(), + self.temperature_c.into_into_dart().into_dart(), + self.power_on_hours.into_into_dart().into_dart(), + self.power_cycle_count.into_into_dart().into_dart(), + self.bad_sectors_count.into_into_dart().into_dart(), + self.total_written_tb.into_into_dart().into_dart(), + self.partitions.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::DiskInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::DiskInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::DiskInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::FailedService { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.name.into_into_dart().into_dart(), + self.init_system.into_into_dart().into_dart(), + self.state.into_into_dart().into_dart(), + self.description.into_into_dart().into_dart(), + self.logs.into_into_dart().into_dart(), + self.restart_command.into_into_dart().into_dart(), + self.status_command.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::FailedService +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::FailedService +{ + fn into_into_dart(self) -> crate::api::diagnostics::FailedService { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::FixSuggestion { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.title.into_into_dart().into_dart(), + self.command.into_into_dart().into_dart(), + self.explanation.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::FixSuggestion +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::FixSuggestion +{ + fn into_into_dart(self) -> crate::api::diagnostics::FixSuggestion { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::GpuInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.vendor.into_into_dart().into_dart(), + self.model.into_into_dart().into_dart(), + self.driver.into_into_dart().into_dart(), + self.pci_slot.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::GpuInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::GpuInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::GpuInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::HardwareInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.cpu.into_into_dart().into_dart(), + self.memory.into_into_dart().into_dart(), + self.motherboard.into_into_dart().into_dart(), + self.gpus.into_into_dart().into_dart(), + self.disks.into_into_dart().into_dart(), + self.network_adapters.into_into_dart().into_dart(), + self.battery.into_into_dart().into_dart(), + self.thermals.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::HardwareInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::HardwareInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::HardwareInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::IssueItem { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.id.into_into_dart().into_dart(), + self.title.into_into_dart().into_dart(), + self.subsystem.into_into_dart().into_dart(), + self.severity.into_into_dart().into_dart(), + self.root_cause.into_into_dart().into_dart(), + self.explanation.into_into_dart().into_dart(), + self.fix.into_into_dart().into_dart(), + self.raw_log.into_into_dart().into_dart(), + self.sanitized.into_into_dart().into_dart(), + self.permission_denied.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::IssueItem +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::IssueItem +{ + fn into_into_dart(self) -> crate::api::diagnostics::IssueItem { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::ListeningPortInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.protocol.into_into_dart().into_dart(), + self.local_address.into_into_dart().into_dart(), + self.port.into_into_dart().into_dart(), + self.process_name.into_into_dart().into_dart(), + self.pid.into_into_dart().into_dart(), + self.is_public.into_into_dart().into_dart(), + self.risk_level.into_into_dart().into_dart(), + self.recommendation.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::ListeningPortInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::ListeningPortInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::ListeningPortInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::LiveMetricsSnapshot { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.cpu_usage_percent.into_into_dart().into_dart(), + self.ram_used_bytes.into_into_dart().into_dart(), + self.ram_total_bytes.into_into_dart().into_dart(), + self.swap_used_bytes.into_into_dart().into_dart(), + self.swap_total_bytes.into_into_dart().into_dart(), + self.max_cpu_temp_c.into_into_dart().into_dart(), + self.is_throttling.into_into_dart().into_dart(), + self.disk_read_kbps.into_into_dart().into_dart(), + self.disk_write_kbps.into_into_dart().into_dart(), + self.net_rx_kbps.into_into_dart().into_dart(), + self.net_tx_kbps.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::LiveMetricsSnapshot +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::LiveMetricsSnapshot +{ + fn into_into_dart(self) -> crate::api::diagnostics::LiveMetricsSnapshot { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::MemoryInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.total_bytes.into_into_dart().into_dart(), + self.available_bytes.into_into_dart().into_dart(), + self.used_bytes.into_into_dart().into_dart(), + self.swap_total_bytes.into_into_dart().into_dart(), + self.swap_used_bytes.into_into_dart().into_dart(), + self.edac_ce_count.into_into_dart().into_dart(), + self.edac_ue_count.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::MemoryInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::MemoryInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::MemoryInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::MotherboardInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.vendor.into_into_dart().into_dart(), + self.product_name.into_into_dart().into_dart(), + self.version.into_into_dart().into_dart(), + self.bios_vendor.into_into_dart().into_dart(), + self.bios_version.into_into_dart().into_dart(), + self.bios_date.into_into_dart().into_dart(), + self.chassis_type.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::MotherboardInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::MotherboardInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::MotherboardInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::NetworkAdapterInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.interface_name.into_into_dart().into_dart(), + self.if_type.into_into_dart().into_dart(), + self.state.into_into_dart().into_dart(), + self.speed_mbps.into_into_dart().into_dart(), + self.mac_address.into_into_dart().into_dart(), + self.driver.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::NetworkAdapterInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::NetworkAdapterInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::NetworkAdapterInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::PartitionInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.name.into_into_dart().into_dart(), + self.path.into_into_dart().into_dart(), + self.mount_point.into_into_dart().into_dart(), + self.fs_type.into_into_dart().into_dart(), + self.size_bytes.into_into_dart().into_dart(), + self.used_bytes.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::PartitionInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::PartitionInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::PartitionInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::SecurityAuditReport { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.exposed_ports.into_into_dart().into_dart(), + self.suid_anomalies.into_into_dart().into_dart(), + self.hardening_checks.into_into_dart().into_dart(), + self.security_score.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::SecurityAuditReport +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::SecurityAuditReport +{ + fn into_into_dart(self) -> crate::api::diagnostics::SecurityAuditReport { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::SecurityCheckItem { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.category.into_into_dart().into_dart(), + self.name.into_into_dart().into_dart(), + self.status.into_into_dart().into_dart(), + self.is_secure.into_into_dart().into_dart(), + self.description.into_into_dart().into_dart(), + self.remediation.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::SecurityCheckItem +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::SecurityCheckItem +{ + fn into_into_dart(self) -> crate::api::diagnostics::SecurityCheckItem { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::Severity { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + match self { + Self::Critical => 0.into_dart(), + Self::Warning => 1.into_dart(), + Self::Info => 2.into_dart(), + _ => unreachable!(), + } + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::Severity +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::Severity +{ + fn into_into_dart(self) -> crate::api::diagnostics::Severity { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::Subsystem { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + match self { + Self::Systemd => 0.into_dart(), + Self::Kernel => 1.into_dart(), + Self::Storage => 2.into_dart(), + Self::Audio => 3.into_dart(), + Self::Network => 4.into_dart(), + Self::Security => 5.into_dart(), + Self::Crashes => 6.into_dart(), + _ => unreachable!(), + } + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::Subsystem +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::Subsystem +{ + fn into_into_dart(self) -> crate::api::diagnostics::Subsystem { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::SubsystemStatus { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.name.into_into_dart().into_dart(), + self.status.into_into_dart().into_dart(), + self.issue_count.into_into_dart().into_dart(), + self.details.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::SubsystemStatus +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::SubsystemStatus +{ + fn into_into_dart(self) -> crate::api::diagnostics::SubsystemStatus { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::SuidAnomalyInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.path.into_into_dart().into_dart(), + self.owner.into_into_dart().into_dart(), + self.permissions.into_into_dart().into_dart(), + self.risk_reason.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::SuidAnomalyInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::SuidAnomalyInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::SuidAnomalyInfo { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::SystemReport { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.timestamp.into_into_dart().into_dart(), + self.os_family.into_into_dart().into_dart(), + self.init_system.into_into_dart().into_dart(), + self.is_root.into_into_dart().into_dart(), + self.subsystems.into_into_dart().into_dart(), + self.issues.into_into_dart().into_dart(), + self.failed_services.into_into_dart().into_dart(), + self.hardware.into_into_dart().into_dart(), + self.crashes.into_into_dart().into_dart(), + self.security.into_into_dart().into_dart(), + self.llm_analyzed.into_into_dart().into_dart(), + self.summary.into_into_dart().into_dart(), + self.prompt_preview.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::SystemReport +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::SystemReport +{ + fn into_into_dart(self) -> crate::api::diagnostics::SystemReport { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::diagnostics::ThermalsInfo { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.max_cpu_temp_c.into_into_dart().into_dart(), + self.thermal_throttled_cores.into_into_dart().into_dart(), + self.total_throttle_events.into_into_dart().into_dart(), + self.is_actively_throttling.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::diagnostics::ThermalsInfo +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::diagnostics::ThermalsInfo +{ + fn into_into_dart(self) -> crate::api::diagnostics::ThermalsInfo { + self + } +} + +impl SseEncode for String { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + >::sse_encode(self.into_bytes(), serializer); + } +} + +impl SseEncode for crate::api::diagnostics::BatteryInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.name, serializer); + ::sse_encode(self.capacity_percent, serializer); + ::sse_encode(self.health_percent, serializer); + ::sse_encode(self.cycle_count, serializer); + ::sse_encode(self.status, serializer); + ::sse_encode(self.is_degraded, serializer); + } +} + +impl SseEncode for bool { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u8(self as _).unwrap(); + } +} + +impl SseEncode for crate::api::diagnostics::CpuInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.model_name, serializer); + ::sse_encode(self.architecture, serializer); + ::sse_encode(self.physical_cores, serializer); + ::sse_encode(self.logical_threads, serializer); + >::sse_encode(self.base_frequency_mhz, serializer); + >::sse_encode(self.current_frequency_mhz, serializer); + ::sse_encode(self.l1_cache, serializer); + ::sse_encode(self.l2_cache, serializer); + ::sse_encode(self.l3_cache, serializer); + >::sse_encode(self.virtualization, serializer); + >::sse_encode(self.flags, serializer); + ::sse_encode(self.microcode, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::CrashReportInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.timestamp, serializer); + ::sse_encode(self.process_name, serializer); + >::sse_encode(self.pid, serializer); + ::sse_encode(self.signal_or_code, serializer); + >::sse_encode(self.fault_module, serializer); + ::sse_encode(self.stack_trace_snippet, serializer); + >::sse_encode(self.dump_path, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::DiskInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.name, serializer); + ::sse_encode(self.model, serializer); + ::sse_encode(self.serial, serializer); + ::sse_encode(self.size_bytes, serializer); + ::sse_encode(self.disk_type, serializer); + >::sse_encode(self.rotational_speed_rpm, serializer); + ::sse_encode(self.smart_status, serializer); + >::sse_encode(self.health_percent, serializer); + >::sse_encode(self.wear_percent, serializer); + >::sse_encode(self.nvme_wear_percent, serializer); + >::sse_encode(self.temperature_c, serializer); + >::sse_encode(self.power_on_hours, serializer); + >::sse_encode(self.power_cycle_count, serializer); + >::sse_encode(self.bad_sectors_count, serializer); + >::sse_encode(self.total_written_tb, serializer); + >::sse_encode(self.partitions, serializer); + } +} + +impl SseEncode for f32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_f32::(self).unwrap(); + } +} + +impl SseEncode for f64 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_f64::(self).unwrap(); + } +} + +impl SseEncode for crate::api::diagnostics::FailedService { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.name, serializer); + ::sse_encode(self.init_system, serializer); + ::sse_encode(self.state, serializer); + ::sse_encode(self.description, serializer); + ::sse_encode(self.logs, serializer); + ::sse_encode(self.restart_command, serializer); + ::sse_encode(self.status_command, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::FixSuggestion { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.title, serializer); + ::sse_encode(self.command, serializer); + ::sse_encode(self.explanation, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::GpuInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.vendor, serializer); + ::sse_encode(self.model, serializer); + ::sse_encode(self.driver, serializer); + ::sse_encode(self.pci_slot, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::HardwareInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.cpu, serializer); + ::sse_encode(self.memory, serializer); + ::sse_encode(self.motherboard, serializer); + >::sse_encode(self.gpus, serializer); + >::sse_encode(self.disks, serializer); + >::sse_encode( + self.network_adapters, + serializer, + ); + >::sse_encode(self.battery, serializer); + ::sse_encode(self.thermals, serializer); + } +} + +impl SseEncode for i32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_i32::(self).unwrap(); + } +} + +impl SseEncode for crate::api::diagnostics::IssueItem { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.id, serializer); + ::sse_encode(self.title, serializer); + ::sse_encode(self.subsystem, serializer); + ::sse_encode(self.severity, serializer); + ::sse_encode(self.root_cause, serializer); + ::sse_encode(self.explanation, serializer); + >::sse_encode(self.fix, serializer); + ::sse_encode(self.raw_log, serializer); + ::sse_encode(self.sanitized, serializer); + ::sse_encode(self.permission_denied, serializer); + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for crate::api::diagnostics::ListeningPortInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.protocol, serializer); + ::sse_encode(self.local_address, serializer); + ::sse_encode(self.port, serializer); + ::sse_encode(self.process_name, serializer); + >::sse_encode(self.pid, serializer); + ::sse_encode(self.is_public, serializer); + ::sse_encode(self.risk_level, serializer); + ::sse_encode(self.recommendation, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::LiveMetricsSnapshot { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.cpu_usage_percent, serializer); + ::sse_encode(self.ram_used_bytes, serializer); + ::sse_encode(self.ram_total_bytes, serializer); + ::sse_encode(self.swap_used_bytes, serializer); + ::sse_encode(self.swap_total_bytes, serializer); + ::sse_encode(self.max_cpu_temp_c, serializer); + ::sse_encode(self.is_throttling, serializer); + ::sse_encode(self.disk_read_kbps, serializer); + ::sse_encode(self.disk_write_kbps, serializer); + ::sse_encode(self.net_rx_kbps, serializer); + ::sse_encode(self.net_tx_kbps, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::MemoryInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.total_bytes, serializer); + ::sse_encode(self.available_bytes, serializer); + ::sse_encode(self.used_bytes, serializer); + ::sse_encode(self.swap_total_bytes, serializer); + ::sse_encode(self.swap_used_bytes, serializer); + ::sse_encode(self.edac_ce_count, serializer); + ::sse_encode(self.edac_ue_count, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::MotherboardInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.vendor, serializer); + ::sse_encode(self.product_name, serializer); + ::sse_encode(self.version, serializer); + ::sse_encode(self.bios_vendor, serializer); + ::sse_encode(self.bios_version, serializer); + ::sse_encode(self.bios_date, serializer); + ::sse_encode(self.chassis_type, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::NetworkAdapterInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.interface_name, serializer); + ::sse_encode(self.if_type, serializer); + ::sse_encode(self.state, serializer); + >::sse_encode(self.speed_mbps, serializer); + ::sse_encode(self.mac_address, serializer); + ::sse_encode(self.driver, serializer); + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for crate::api::diagnostics::PartitionInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.name, serializer); + ::sse_encode(self.path, serializer); + >::sse_encode(self.mount_point, serializer); + ::sse_encode(self.fs_type, serializer); + ::sse_encode(self.size_bytes, serializer); + ::sse_encode(self.used_bytes, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::SecurityAuditReport { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + >::sse_encode( + self.exposed_ports, + serializer, + ); + >::sse_encode( + self.suid_anomalies, + serializer, + ); + >::sse_encode( + self.hardening_checks, + serializer, + ); + ::sse_encode(self.security_score, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::SecurityCheckItem { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.category, serializer); + ::sse_encode(self.name, serializer); + ::sse_encode(self.status, serializer); + ::sse_encode(self.is_secure, serializer); + ::sse_encode(self.description, serializer); + >::sse_encode(self.remediation, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::Severity { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode( + match self { + crate::api::diagnostics::Severity::Critical => 0, + crate::api::diagnostics::Severity::Warning => 1, + crate::api::diagnostics::Severity::Info => 2, + _ => { + unimplemented!(""); + } + }, + serializer, + ); + } +} + +impl SseEncode for crate::api::diagnostics::Subsystem { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode( + match self { + crate::api::diagnostics::Subsystem::Systemd => 0, + crate::api::diagnostics::Subsystem::Kernel => 1, + crate::api::diagnostics::Subsystem::Storage => 2, + crate::api::diagnostics::Subsystem::Audio => 3, + crate::api::diagnostics::Subsystem::Network => 4, + crate::api::diagnostics::Subsystem::Security => 5, + crate::api::diagnostics::Subsystem::Crashes => 6, + _ => { + unimplemented!(""); + } + }, + serializer, + ); + } +} + +impl SseEncode for crate::api::diagnostics::SubsystemStatus { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.name, serializer); + ::sse_encode(self.status, serializer); + ::sse_encode(self.issue_count, serializer); + ::sse_encode(self.details, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::SuidAnomalyInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.path, serializer); + ::sse_encode(self.owner, serializer); + ::sse_encode(self.permissions, serializer); + ::sse_encode(self.risk_reason, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::SystemReport { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.timestamp, serializer); + ::sse_encode(self.os_family, serializer); + ::sse_encode(self.init_system, serializer); + ::sse_encode(self.is_root, serializer); + >::sse_encode(self.subsystems, serializer); + >::sse_encode(self.issues, serializer); + >::sse_encode(self.failed_services, serializer); + ::sse_encode(self.hardware, serializer); + >::sse_encode(self.crashes, serializer); + ::sse_encode(self.security, serializer); + ::sse_encode(self.llm_analyzed, serializer); + ::sse_encode(self.summary, serializer); + ::sse_encode(self.prompt_preview, serializer); + } +} + +impl SseEncode for crate::api::diagnostics::ThermalsInfo { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.max_cpu_temp_c, serializer); + ::sse_encode(self.thermal_throttled_cores, serializer); + ::sse_encode(self.total_throttle_events, serializer); + ::sse_encode(self.is_actively_throttling, serializer); + } +} + +impl SseEncode for u16 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u16::(self).unwrap(); + } +} + +impl SseEncode for u32 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u32::(self).unwrap(); + } +} + +impl SseEncode for u64 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u64::(self).unwrap(); + } +} + +impl SseEncode for u8 { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer.cursor.write_u8(self).unwrap(); + } +} + +impl SseEncode for () { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {} +} + +impl SseEncode for usize { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + serializer + .cursor + .write_u64::(self as _) + .unwrap(); + } +} + +#[cfg(not(target_family = "wasm"))] +mod io { + // This file is automatically generated, so please do not edit it. + // @generated by `flutter_rust_bridge`@ 2.13.0. + + // Section: imports + + use super::*; + use flutter_rust_bridge::for_generated::byteorder::{ + NativeEndian, ReadBytesExt, WriteBytesExt, + }; + use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; + use flutter_rust_bridge::{Handler, IntoIntoDart}; + + // Section: boilerplate + + flutter_rust_bridge::frb_generated_boilerplate_io!(); +} +#[cfg(not(target_family = "wasm"))] +pub use io::*; + +/// cbindgen:ignore +#[cfg(target_family = "wasm")] +mod web { + // This file is automatically generated, so please do not edit it. + // @generated by `flutter_rust_bridge`@ 2.13.0. + + // Section: imports + + use super::*; + use flutter_rust_bridge::for_generated::byteorder::{ + NativeEndian, ReadBytesExt, WriteBytesExt, + }; + use flutter_rust_bridge::for_generated::wasm_bindgen; + use flutter_rust_bridge::for_generated::wasm_bindgen::prelude::*; + use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; + use flutter_rust_bridge::{Handler, IntoIntoDart}; + + // Section: boilerplate + + flutter_rust_bridge::frb_generated_boilerplate_web!(); +} +#[cfg(target_family = "wasm")] +pub use web::*; diff --git a/rust/src/lib.rs b/rust/src/lib.rs new file mode 100644 index 0000000..b62c491 --- /dev/null +++ b/rust/src/lib.rs @@ -0,0 +1,7 @@ +#[cfg(feature = "gui")] +pub mod api; +#[cfg(feature = "gui")] +mod frb_generated; + +#[cfg(feature = "tui")] +pub mod tui; diff --git a/rust/src/tui/app.rs b/rust/src/tui/app.rs new file mode 100644 index 0000000..099b343 --- /dev/null +++ b/rust/src/tui/app.rs @@ -0,0 +1,399 @@ +use diagd_core::models::SystemReport; + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum ActiveView { + Issues, + Hardware, + LiveMonitor, + Security, + Crashes, + RawLog, + LlmPrompt, +} + +pub struct App { + pub report: Option, + pub selected_issue_idx: usize, + pub selected_crash_idx: usize, + pub log_scroll: u16, + pub active_view: ActiveView, + pub status_message: String, + pub should_quit: bool, + pub live_snapshot: diagd_core::models::LiveMetricsSnapshot, + pub cpu_history: Vec, + pub ram_history: Vec, + pub temp_history: Vec, + pub net_history: Vec, + pub disk_history: Vec, +} + +impl App { + pub fn new(initial_report: Option) -> Self { + Self { + report: initial_report, + selected_issue_idx: 0, + selected_crash_idx: 0, + log_scroll: 0, + active_view: ActiveView::Issues, + status_message: "Готов к работе. Поддерживается клик и скролл мышкой. [s] Сканировать, [q] Выход.".to_string(), + should_quit: false, + live_snapshot: diagd_core::models::LiveMetricsSnapshot::default(), + cpu_history: Vec::with_capacity(60), + ram_history: Vec::with_capacity(60), + temp_history: Vec::with_capacity(60), + net_history: Vec::with_capacity(60), + disk_history: Vec::with_capacity(60), + } + } + + pub fn tick_live_metrics(&mut self) { + let snap = diagd_core::LiveMetricsScanner::sample(); + let cpu_val = snap.cpu_usage_percent.round() as u64; + self.cpu_history.push(cpu_val); + if self.cpu_history.len() > 60 { + self.cpu_history.remove(0); + } + + let ram_pct = if snap.ram_total_bytes > 0 { + ((snap.ram_used_bytes as f64 / snap.ram_total_bytes as f64) * 100.0).round() as u64 + } else { + 0 + }; + self.ram_history.push(ram_pct); + if self.ram_history.len() > 60 { + self.ram_history.remove(0); + } + + let temp_val = snap.max_cpu_temp_c.max(0.0).round() as u64; + self.temp_history.push(temp_val); + if self.temp_history.len() > 60 { + self.temp_history.remove(0); + } + + let net_kb = snap.net_rx_kbps + snap.net_tx_kbps; + self.net_history.push(net_kb); + if self.net_history.len() > 60 { + self.net_history.remove(0); + } + + let disk_kb = snap.disk_read_kbps + snap.disk_write_kbps; + self.disk_history.push(disk_kb); + if self.disk_history.len() > 60 { + self.disk_history.remove(0); + } + + self.live_snapshot = snap; + } + + pub fn next_crash(&mut self) { + if let Some(ref report) = self.report { + if !report.crashes.is_empty() { + if self.selected_crash_idx + 1 < report.crashes.len() { + self.selected_crash_idx += 1; + } else { + self.selected_crash_idx = 0; + } + self.log_scroll = 0; + } + } + } + + pub fn previous_crash(&mut self) { + if let Some(ref report) = self.report { + if !report.crashes.is_empty() { + if self.selected_crash_idx > 0 { + self.selected_crash_idx -= 1; + } else { + self.selected_crash_idx = report.crashes.len() - 1; + } + self.log_scroll = 0; + } + } + } + + pub fn next_issue(&mut self) { + if let Some(ref report) = self.report { + if !report.issues.is_empty() { + if self.selected_issue_idx + 1 < report.issues.len() { + self.selected_issue_idx += 1; + } else { + self.selected_issue_idx = 0; + } + self.log_scroll = 0; + } + } + } + + pub fn previous_issue(&mut self) { + if let Some(ref report) = self.report { + if !report.issues.is_empty() { + if self.selected_issue_idx > 0 { + self.selected_issue_idx -= 1; + } else { + self.selected_issue_idx = report.issues.len() - 1; + } + self.log_scroll = 0; + } + } + } + + pub fn scroll_log_down(&mut self) { + self.log_scroll = self.log_scroll.saturating_add(3); + } + + pub fn scroll_log_up(&mut self) { + self.log_scroll = self.log_scroll.saturating_sub(3); + } + + pub fn toggle_raw_log(&mut self) { + self.active_view = match self.active_view { + ActiveView::RawLog => ActiveView::Issues, + _ => { + self.log_scroll = 0; + ActiveView::RawLog + } + }; + } + + pub fn toggle_prompt(&mut self) { + self.active_view = match self.active_view { + ActiveView::LlmPrompt => ActiveView::Issues, + _ => { + self.log_scroll = 0; + ActiveView::LlmPrompt + } + }; + } + + pub fn toggle_hardware(&mut self) { + self.active_view = match self.active_view { + ActiveView::Hardware => ActiveView::Issues, + _ => { + self.log_scroll = 0; + ActiveView::Hardware + } + }; + } + + pub fn toggle_live_monitor(&mut self) { + self.active_view = match self.active_view { + ActiveView::LiveMonitor => ActiveView::Issues, + _ => { + self.log_scroll = 0; + ActiveView::LiveMonitor + } + }; + } + + pub fn toggle_security(&mut self) { + self.active_view = match self.active_view { + ActiveView::Security => ActiveView::Issues, + _ => { + self.log_scroll = 0; + ActiveView::Security + } + }; + } + + pub fn toggle_crashes(&mut self) { + self.active_view = match self.active_view { + ActiveView::Crashes => ActiveView::Issues, + _ => { + self.log_scroll = 0; + ActiveView::Crashes + } + }; + } + + pub fn copy_fix_command(&mut self) { + if let Some(ref report) = self.report { + if let Some(issue) = report.issues.get(self.selected_issue_idx) { + if let Some(ref fix) = issue.fix { + copy_to_clipboard(&fix.command); + self.status_message = format!("✓ Скопировано: {}", fix.command); + return; + } + } + } + self.status_message = "Нет команды для копирования.".to_string(); + } + + pub fn export_bundle(&mut self) { + if let Some(ref report) = self.report { + match diagd_core::BundleExporter::export_bundle(report) { + Ok(path) => { + self.status_message = format!("✓ Отчет и Debug Bundle сохранены: {}", path); + } + Err(err) => { + self.status_message = format!("Ошибка экспорта: {}", err); + } + } + } else { + self.status_message = "Нет данных для экспорта. Сначала выполните сканирование.".to_string(); + } + } + + /// Интерактивная обработка клика мыши + pub fn handle_mouse_click(&mut self, col: u16, row: u16, screen_width: u16, screen_height: u16) { + // 0. Клик в верхний Tab Bar (строки 0 или 1) + if row <= 2 { + if col < 35 { + self.active_view = ActiveView::Issues; + self.log_scroll = 0; + } else if col < 53 { + self.active_view = ActiveView::Hardware; + self.log_scroll = 0; + } else if col < 67 { + self.active_view = ActiveView::LiveMonitor; + self.log_scroll = 0; + } else if col < 84 { + self.active_view = ActiveView::Security; + self.log_scroll = 0; + } else if col < 95 { + self.active_view = ActiveView::Crashes; + self.log_scroll = 0; + } else if col < 105 { + self.toggle_raw_log(); + } else if col < 120 { + self.toggle_prompt(); + } + return; + } + + // 1. Клик в футер (горячие клавиши) + if row >= screen_height.saturating_sub(2) { + if col < 12 { + self.should_quit = true; + } else if col < 26 { + // [s] Сканировать + self.status_message = "Запрос повторного сканирования...".to_string(); + } else if col < 40 { + // [h] Железо + self.toggle_hardware(); + } else if col < 55 { + // Копировать + self.copy_fix_command(); + } else if col < 66 { + // Лог + self.toggle_raw_log(); + } else if col < 80 { + // Промпт + self.toggle_prompt(); + } else if col < 96 { + // Экспорт + self.export_bundle(); + } + return; + } + + // 2. Клик вне модального окна закрывает его + if self.active_view == ActiveView::RawLog || self.active_view == ActiveView::LlmPrompt { + if row <= 7 || row >= screen_height.saturating_sub(2) { + self.active_view = ActiveView::Issues; + } + return; + } + + // 3. Клик в список инцидентов (левая колонка: 0..width*38%) + let list_width = (screen_width as f32 * 0.38) as u16; + if self.active_view == ActiveView::Issues && col <= list_width && row >= 8 { + let item_index = (row - 8) as usize; + if let Some(ref report) = self.report { + if item_index < report.issues.len() { + self.selected_issue_idx = item_index; + self.log_scroll = 0; + self.status_message = format!("Выбрана проблема #{}", item_index + 1); + } + } + } else if self.active_view == ActiveView::Crashes && col <= list_width && row >= 8 { + let item_index = (row - 8) as usize; + if let Some(ref report) = self.report { + if item_index < report.crashes.len() { + self.selected_crash_idx = item_index; + self.log_scroll = 0; + self.status_message = format!("Выбран сбой #{}", item_index + 1); + } + } + } + } +} + +fn copy_to_clipboard(text: &str) { + use std::io::Write; + use std::process::{Command, Stdio}; + + let _ = Command::new("wl-copy") + .stdin(Stdio::piped()) + .spawn() + .and_then(|mut child| { + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(text.as_bytes())?; + } + child.wait() + }) + .or_else(|_| { + Command::new("xclip") + .args(["-selection", "clipboard"]) + .stdin(Stdio::piped()) + .spawn() + .and_then(|mut child| { + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(text.as_bytes())?; + } + child.wait() + }) + }) + .or_else(|_| { + // macOS pbcopy + Command::new("pbcopy") + .stdin(Stdio::piped()) + .spawn() + .and_then(|mut child| { + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(text.as_bytes())?; + } + child.wait() + }) + }) + .or_else(|_| { + // Windows clip + Command::new("clip") + .stdin(Stdio::piped()) + .spawn() + .and_then(|mut child| { + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(text.as_bytes())?; + } + child.wait() + }) + }); + + let b64 = base64_simple_encode(text.as_bytes()); + print!("\x1b]52;c;{}\x07", b64); + let _ = std::io::stdout().flush(); +} + +fn base64_simple_encode(input: &[u8]) -> String { + const CHARSET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for chunk in input.chunks(3) { + let b0 = chunk[0]; + let b1 = if chunk.len() > 1 { chunk[1] } else { 0 }; + let b2 = if chunk.len() > 2 { chunk[2] } else { 0 }; + + let n = ((b0 as u32) << 16) | ((b1 as u32) << 8) | (b2 as u32); + out.push(CHARSET[((n >> 18) & 63) as usize] as char); + out.push(CHARSET[((n >> 12) & 63) as usize] as char); + if chunk.len() > 1 { + out.push(CHARSET[((n >> 6) & 63) as usize] as char); + } else { + out.push('='); + } + if chunk.len() > 2 { + out.push(CHARSET[(n & 63) as usize] as char); + } else { + out.push('='); + } + } + out +} diff --git a/rust/src/tui/mod.rs b/rust/src/tui/mod.rs new file mode 100644 index 0000000..34813a1 --- /dev/null +++ b/rust/src/tui/mod.rs @@ -0,0 +1,295 @@ +pub mod app; +pub mod ui; + +use app::{ActiveView, App}; +use crossterm::{ + event::{ + self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers, + MouseButton, MouseEventKind, + }, + execute, + terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, +}; +use diagd_core::auth::{AuthMode, PrivilegeManager, PrivilegeStatus}; +use ratatui::{backend::CrosstermBackend, Terminal}; +use std::io; +use std::time::Duration; + +pub async fn run_tui_async() -> Result<(), Box> { + // 1. Однократная проверка/запрос привилегий перед входом в fullscreen TUI + let priv_status = PrivilegeManager::request_privileges(AuthMode::Tui); + + // 2. Инициализация терминала (Raw Mode + Alternate Screen + Mouse Capture) + enable_raw_mode()?; + let mut stdout = io::stdout(); + execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?; + let backend = CrosstermBackend::new(stdout); + let mut terminal = Terminal::new(backend)?; + + let mut app = App::new(None); + + let auth_msg = match priv_status { + PrivilegeStatus::AlreadyRoot => "Запущено от root".to_string(), + PrivilegeStatus::Elevated => "Привилегии sudo получены".to_string(), + PrivilegeStatus::Unprivileged { reason } => format!("Unprivileged режим: {}", reason), + }; + + app.status_message = format!("{} | Сканирование системы...", auth_msg); + terminal.draw(|f| ui::draw(f, &app))?; + + // 3. Запуск глубокого аудита + if let Ok(report) = diagd_core::run_scan().await { + app.status_message = format!( + "{} ({}) | Найдено проблем: {} | Кликайте мышкой по списку", + report.os_family, + report.init_system, + report.issues.len() + ); + app.report = Some(report); + } else { + app.status_message = "Ошибка при первичном сканировании системы.".to_string(); + } + + // 4. Основной цикл событий с поддержкой клавиатуры и мыши + let res = run_app(&mut terminal, &mut app).await; + + // 5. Корректное восстановление терминала (отключение мыши, возврат экрана) + disable_raw_mode()?; + execute!( + terminal.backend_mut(), + LeaveAlternateScreen, + DisableMouseCapture + )?; + terminal.show_cursor()?; + + if let Err(err) = res { + eprintln!("Ошибка работы TUI: {:?}", err); + } + + Ok(()) +} + +pub fn run_tui() -> Result<(), Box> { + let rt = tokio::runtime::Runtime::new()?; + rt.block_on(run_tui_async()) +} + +#[no_mangle] +pub extern "C" fn diagd_run_tui() -> i32 { + match run_tui() { + Ok(_) => 0, + Err(e) => { + eprintln!("Ошибка запуска TUI: {}", e); + 1 + } + } +} + +async fn run_app( + terminal: &mut Terminal, + app: &mut App, +) -> io::Result<()> { + let mut last_live_tick = std::time::Instant::now(); + app.tick_live_metrics(); + + loop { + terminal.draw(|f| ui::draw(f, app))?; + + if app.should_quit { + return Ok(()); + } + + if last_live_tick.elapsed() >= Duration::from_millis(1000) { + app.tick_live_metrics(); + last_live_tick = std::time::Instant::now(); + } + + let size = terminal.size()?; + + if event::poll(Duration::from_millis(100))? { + match event::read()? { + // Обработка МЫШИ (клик и колесико скролла) + Event::Mouse(mouse) => match mouse.kind { + MouseEventKind::Down(MouseButton::Left) => { + app.handle_mouse_click(mouse.column, mouse.row, size.width, size.height); + } + MouseEventKind::ScrollDown => { + app.scroll_log_down(); + } + MouseEventKind::ScrollUp => { + app.scroll_log_up(); + } + _ => {} + }, + + // Обработка КЛАВИАТУРЫ + Event::Key(key) => { + if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') { + return Ok(()); + } + + // Глобальные быстрые переключения вкладок + match key.code { + KeyCode::Char('1') => { + app.active_view = ActiveView::Issues; + continue; + } + KeyCode::Char('2') => { + app.active_view = ActiveView::Hardware; + continue; + } + KeyCode::Char('3') => { + app.active_view = ActiveView::LiveMonitor; + continue; + } + KeyCode::Char('4') => { + app.active_view = ActiveView::Security; + continue; + } + KeyCode::Char('5') => { + app.active_view = ActiveView::Crashes; + continue; + } + KeyCode::Char('6') => { + app.toggle_raw_log(); + continue; + } + KeyCode::Char('7') => { + app.toggle_prompt(); + continue; + } + _ => {} + } + + match app.active_view { + ActiveView::Issues => match key.code { + KeyCode::Char('q') => { + app.should_quit = true; + } + KeyCode::Char('s') => { + app.status_message = "Глубокое сканирование системы...".to_string(); + terminal.draw(|f| ui::draw(f, app))?; + if let Ok(report) = diagd_core::run_scan().await { + app.status_message = format!( + "{} ({}) | Проблем: {} | Клик мышью для выбора", + report.os_family, + report.init_system, + report.issues.len() + ); + app.report = Some(report); + app.selected_issue_idx = 0; + } else { + app.status_message = "Ошибка при выполнении сканирования!".to_string(); + } + } + KeyCode::Down | KeyCode::Char('j') => { + app.next_issue(); + } + KeyCode::Up | KeyCode::Char('k') => { + app.previous_issue(); + } + KeyCode::Char('c') => { + app.copy_fix_command(); + } + KeyCode::Char('h') => { + app.toggle_hardware(); + } + KeyCode::Char('m') => { + app.toggle_live_monitor(); + } + KeyCode::Char('b') => { + app.toggle_security(); + } + KeyCode::Char('x') => { + app.toggle_crashes(); + } + KeyCode::Char('l') | KeyCode::Enter => { + app.toggle_raw_log(); + } + KeyCode::Char('p') => { + app.toggle_prompt(); + } + KeyCode::Char('e') => { + app.export_bundle(); + } + _ => {} + }, + ActiveView::Hardware | ActiveView::Security => match key.code { + KeyCode::Esc | KeyCode::Char('q') => { + app.active_view = ActiveView::Issues; + } + KeyCode::Char('e') => { + app.export_bundle(); + } + KeyCode::Down | KeyCode::Char('j') => { + app.scroll_log_down(); + } + KeyCode::Up | KeyCode::Char('k') => { + app.scroll_log_up(); + } + KeyCode::PageDown => { + app.log_scroll = app.log_scroll.saturating_add(10); + } + KeyCode::PageUp => { + app.log_scroll = app.log_scroll.saturating_sub(10); + } + _ => {} + }, + ActiveView::LiveMonitor => match key.code { + KeyCode::Esc | KeyCode::Char('q') => { + app.active_view = ActiveView::Issues; + } + KeyCode::Char('e') => { + app.export_bundle(); + } + _ => {} + }, + ActiveView::Crashes => match key.code { + KeyCode::Esc | KeyCode::Char('q') => { + app.active_view = ActiveView::Issues; + } + KeyCode::Down | KeyCode::Char('j') => { + app.next_crash(); + } + KeyCode::Up | KeyCode::Char('k') => { + app.previous_crash(); + } + KeyCode::PageDown => { + app.log_scroll = app.log_scroll.saturating_add(10); + } + KeyCode::PageUp => { + app.log_scroll = app.log_scroll.saturating_sub(10); + } + KeyCode::Char('e') => { + app.export_bundle(); + } + _ => {} + }, + ActiveView::RawLog | ActiveView::LlmPrompt => match key.code { + KeyCode::Esc + | KeyCode::Char('q') + | KeyCode::Char('l') + | KeyCode::Char('p') => { + app.active_view = ActiveView::Issues; + } + KeyCode::Down | KeyCode::Char('j') => { + app.scroll_log_down(); + } + KeyCode::Up | KeyCode::Char('k') => { + app.scroll_log_up(); + } + KeyCode::PageDown => { + app.log_scroll = app.log_scroll.saturating_add(10); + } + KeyCode::PageUp => { + app.log_scroll = app.log_scroll.saturating_sub(10); + } + _ => {} + }, + } + } + _ => {} + } + } + } +} diff --git a/rust/src/tui/ui.rs b/rust/src/tui/ui.rs new file mode 100644 index 0000000..27dee97 --- /dev/null +++ b/rust/src/tui/ui.rs @@ -0,0 +1,1003 @@ +use super::app::{ActiveView, App}; +use diagd_core::models::{Severity, Subsystem}; +use ratatui::{ + layout::{Constraint, Direction, Layout, Rect}, + style::{Color, Modifier, Style}, + text::{Line, Span}, + widgets::{Block, Borders, Clear, Gauge, List, ListItem, Paragraph, Sparkline, Wrap}, + Frame, +}; + +pub fn draw(f: &mut Frame, app: &App) { + let chunks = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(3), // Заголовок + Constraint::Length(4), // Подсистемы + Constraint::Min(10), // Основная область + Constraint::Length(1), // Статус-бар / Горячие клавиши + ]) + .split(f.area()); + + draw_header(f, app, chunks[0]); + draw_subsystems(f, app, chunks[1]); + + match app.active_view { + ActiveView::Issues => draw_main_issues_view(f, app, chunks[2]), + ActiveView::Hardware => draw_hardware_view(f, app, chunks[2]), + ActiveView::LiveMonitor => draw_live_monitor_view(f, app, chunks[2]), + ActiveView::Security => draw_security_view(f, app, chunks[2]), + ActiveView::Crashes => draw_crashes_view(f, app, chunks[2]), + ActiveView::RawLog => draw_fullscreen_log(f, app, chunks[2]), + ActiveView::LlmPrompt => draw_fullscreen_prompt(f, app, chunks[2]), + } + + draw_footer(f, app, chunks[3]); +} + +fn draw_header(f: &mut Frame, app: &App, area: Rect) { + let os_badge = if let Some(ref r) = app.report { + format!(" [{}] ", r.os_family) + } else { + " [Unix] ".to_string() + }; + + let is_issues = app.active_view == ActiveView::Issues; + let is_hw = app.active_view == ActiveView::Hardware; + let is_live = app.active_view == ActiveView::LiveMonitor; + let is_sec = app.active_view == ActiveView::Security; + let is_crash = app.active_view == ActiveView::Crashes; + let is_log = app.active_view == ActiveView::RawLog; + let is_prompt = app.active_view == ActiveView::LlmPrompt; + + let tab_style = |active: bool, color: Color| { + if active { + Style::default().fg(Color::Black).bg(color).add_modifier(Modifier::BOLD) + } else { + Style::default().fg(color).add_modifier(Modifier::BOLD) + } + }; + + let title = Line::from(vec![ + Span::styled(" diagd ", Style::default().fg(Color::Black).bg(Color::Green).add_modifier(Modifier::BOLD)), + Span::styled(os_badge, Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + Span::raw(" "), + Span::styled(" [1] Диагностика ", tab_style(is_issues, Color::Green)), + Span::raw(" "), + Span::styled(" [2] Железо ", tab_style(is_hw, Color::LightYellow)), + Span::raw(" "), + Span::styled(" [3] Монитор ", tab_style(is_live, Color::Cyan)), + Span::raw(" "), + Span::styled(" [4] Безопасность ", tab_style(is_sec, Color::LightRed)), + Span::raw(" "), + Span::styled(" [5] Сбои ", tab_style(is_crash, Color::LightMagenta)), + Span::raw(" "), + Span::styled(" [6] Лог ", tab_style(is_log, Color::Magenta)), + Span::raw(" "), + Span::styled(" [7] Prompt ", tab_style(is_prompt, Color::LightBlue)), + Span::raw(" "), + Span::styled(&app.status_message, Style::default().fg(Color::Yellow)), + ]); + + let block = Block::default() + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::DarkGray)); + + let paragraph = Paragraph::new(title).block(block); + f.render_widget(paragraph, area); +} + +fn draw_subsystems(f: &mut Frame, app: &App, area: Rect) { + let sub_chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Ratio(1, 7), + Constraint::Ratio(1, 7), + Constraint::Ratio(1, 7), + Constraint::Ratio(1, 7), + Constraint::Ratio(1, 7), + Constraint::Ratio(1, 7), + Constraint::Ratio(1, 7), + ]) + .split(area); + + if let Some(ref report) = app.report { + for (idx, sub) in report.subsystems.iter().enumerate().take(7) { + let is_healthy = sub.status == "Healthy" || sub.status == "Normal"; + let is_failed = sub.status == "Failed" || sub.status == "Critical"; + let color = if is_failed { + Color::Red + } else if is_healthy { + Color::Green + } else { + Color::Yellow + }; + + let (icon, name) = match sub.name { + Subsystem::Systemd => ("⚙", if report.os_family.contains("BSD") { "Services" } else { "Systemd" }), + Subsystem::Kernel => ("⚡", "Kernel"), + Subsystem::Storage => ("💾", "Storage"), + Subsystem::Network => ("🌐", "Network"), + Subsystem::Audio => ("🔊", "Audio"), + Subsystem::Security => ("🛡", "Security"), + Subsystem::Crashes => ("💥", "Crashes"), + }; + + let text = vec![ + Line::from(vec![ + Span::styled(format!("{} {} ", icon, name), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + Span::styled(&sub.status, Style::default().fg(color).add_modifier(Modifier::BOLD)), + ]), + Line::from(vec![ + Span::styled(format!("Ошибок: {}", sub.issue_count), Style::default().fg(Color::Gray)), + ]), + ]; + + let block = Block::default() + .borders(Borders::ALL) + .border_style(Style::default().fg(color)); + + let p = Paragraph::new(text).block(block); + f.render_widget(p, sub_chunks[idx]); + } + } +} + +fn draw_main_issues_view(f: &mut Frame, app: &App, area: Rect) { + let main_chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage(38), + Constraint::Percentage(62), + ]) + .split(area); + + draw_issues_list(f, app, main_chunks[0]); + draw_issue_details(f, app, main_chunks[1]); +} + +fn draw_issues_list(f: &mut Frame, app: &App, area: Rect) { + let mut items = Vec::new(); + + if let Some(ref report) = app.report { + for (i, issue) in report.issues.iter().enumerate() { + let is_selected = i == app.selected_issue_idx; + let (badge, badge_color) = match issue.severity { + Severity::Critical => ("[CRIT]", Color::Red), + Severity::Warning => ("[WARN]", Color::Yellow), + Severity::Info => ("[INFO]", Color::Cyan), + }; + + let prefix = if is_selected { "▶ " } else { " " }; + let style = if is_selected { + Style::default().fg(Color::White).bg(Color::Rgb(30, 40, 60)).add_modifier(Modifier::BOLD) + } else { + Style::default().fg(Color::Gray) + }; + + let line = Line::from(vec![ + Span::raw(prefix), + Span::styled(badge, Style::default().fg(badge_color).add_modifier(Modifier::BOLD)), + Span::raw(" "), + Span::styled(&issue.title, style), + ]); + + items.push(ListItem::new(line)); + } + } + + let title = format!( + " Список проблем ({}) ", + app.report.as_ref().map(|r| r.issues.len()).unwrap_or(0) + ); + + let block = Block::default() + .title(Span::styled(title, Style::default().fg(Color::White).add_modifier(Modifier::BOLD))) + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::Cyan)); + + let list = List::new(items).block(block); + f.render_widget(list, area); +} + +fn draw_issue_details(f: &mut Frame, app: &App, area: Rect) { + if let Some(ref report) = app.report { + if let Some(issue) = report.issues.get(app.selected_issue_idx) { + let (badge, badge_fg, badge_bg) = match issue.severity { + Severity::Critical => (" КРИТИЧЕСКАЯ ", Color::Black, Color::Red), + Severity::Warning => (" ПРЕДУПРЕЖДЕНИЕ ", Color::Black, Color::Yellow), + Severity::Info => (" ИНФОРМАЦИЯ ", Color::Black, Color::Cyan), + }; + + let mut lines = Vec::new(); + + // Заголовок + lines.push(Line::from(vec![ + Span::styled(badge, Style::default().fg(badge_fg).bg(badge_bg).add_modifier(Modifier::BOLD)), + Span::raw(" "), + Span::styled(format!("[{:?}]", issue.subsystem), Style::default().fg(Color::DarkGray)), + Span::raw(" "), + if issue.sanitized { + Span::styled("[✓ Sanitized]", Style::default().fg(Color::Green)) + } else { + Span::raw("") + }, + ])); + lines.push(Line::raw("")); + + // Название проблемы + lines.push(Line::from(vec![ + Span::styled(&issue.title, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::raw("")); + + // Корень проблемы (Root Cause) + lines.push(Line::from(vec![ + Span::styled("▶ КОРЕНЬ ПРОБЛЕМЫ (ROOT CAUSE):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::from(vec![ + Span::styled(&issue.root_cause, Style::default().fg(Color::LightCyan)), + ])); + lines.push(Line::raw("")); + + // Анализ ИИ + lines.push(Line::from(vec![ + Span::styled("▶ АНАЛИЗ И ОБЪЯСНЕНИЕ:", Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::from(vec![ + Span::styled(&issue.explanation, Style::default().fg(Color::White)), + ])); + lines.push(Line::raw("")); + + // Команда исправления + if let Some(ref fix) = issue.fix { + lines.push(Line::from(vec![ + Span::styled("▶ РЕКОМЕНДУЕМОЕ РЕШЕНИЕ:", Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)), + Span::raw(" "), + Span::styled(&fix.title, Style::default().fg(Color::Gray)), + ])); + lines.push(Line::from(vec![ + Span::styled(" $ ", Style::default().fg(Color::DarkGray)), + Span::styled(&fix.command, Style::default().fg(Color::LightGreen).bg(Color::Rgb(15, 30, 15)).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::from(vec![ + Span::styled(format!(" (Нажмите [c] чтобы скопировать команду)"), Style::default().fg(Color::DarkGray)), + ])); + lines.push(Line::raw("")); + } + + // Превью лога + lines.push(Line::from(vec![ + Span::styled("▶ СЫРОЙ СИСТЕМНЫЙ ЛОГ (Нажмите [l] для полного экрана):", Style::default().fg(Color::Magenta).add_modifier(Modifier::BOLD)), + ])); + for log_line in issue.raw_log.lines().take(6) { + lines.push(Line::from(vec![ + Span::styled(format!(" {}", log_line), Style::default().fg(Color::DarkGray)), + ])); + } + + let block = Block::default() + .title(Span::styled(" Детализация и решение ИИ ", Style::default().fg(Color::White).add_modifier(Modifier::BOLD))) + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::Cyan)); + + let p = Paragraph::new(lines).block(block).wrap(Wrap { trim: false }); + f.render_widget(p, area); + return; + } + } + + let block = Block::default().borders(Borders::ALL); + let p = Paragraph::new("Нет данных для отображения").block(block); + f.render_widget(p, area); +} + +fn draw_fullscreen_log(f: &mut Frame, app: &App, area: Rect) { + let content = if let Some(ref report) = app.report { + if let Some(issue) = report.issues.get(app.selected_issue_idx) { + &issue.raw_log + } else { + "Лог пуст" + } + } else { + "Отчет не сформирован" + }; + + let block = Block::default() + .title(Span::styled(" Просмотр очищенного системного лога [Esc / l - закрыть] ", Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD))) + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::Yellow)); + + let p = Paragraph::new(content) + .block(block) + .scroll((app.log_scroll, 0)) + .wrap(Wrap { trim: false }); + + f.render_widget(Clear, area); + f.render_widget(p, area); +} + +fn draw_fullscreen_prompt(f: &mut Frame, app: &App, area: Rect) { + let content: &str = if let Some(ref report) = app.report { + &report.prompt_preview + } else { + "Промпт не сформирован" + }; + + let block = Block::default() + .title(Span::styled(" Структурированный JSON-промпт для LLM [Esc / p - закрыть] ", Style::default().fg(Color::Magenta).add_modifier(Modifier::BOLD))) + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::Magenta)); + + let p = Paragraph::new(content) + .block(block) + .scroll((app.log_scroll, 0)) + .wrap(Wrap { trim: false }); + + f.render_widget(Clear, area); + f.render_widget(p, area); +} + +fn draw_hardware_view(f: &mut Frame, app: &App, area: Rect) { + let mut lines = Vec::new(); + if let Some(ref report) = app.report { + let hw = &report.hardware; + + // Header + lines.push(Line::from(vec![ + Span::styled(" ПОЛНАЯ СПЕЦИФИКАЦИЯ ОБОРУДОВАНИЯ СИСТЕМЫ (HARDWARE PROFILE) ", Style::default().fg(Color::Black).bg(Color::LightYellow).add_modifier(Modifier::BOLD)), + Span::raw(" "), + Span::styled(format!("(ОС: {}, Init: {})", report.os_family, report.init_system), Style::default().fg(Color::DarkGray)), + ])); + lines.push(Line::raw("")); + + // 1. CPU + lines.push(Line::from(vec![ + Span::styled("▶ ПРОЦЕССОР (CPU & АРХИТЕКТУРА):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::from(vec![ + Span::styled(" Модель: ", Style::default().fg(Color::Gray)), + Span::styled(&hw.cpu.model_name, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + Span::styled(format!(" (Архитектура: {})", hw.cpu.architecture), Style::default().fg(Color::DarkGray)), + ])); + lines.push(Line::from(vec![ + Span::styled(format!(" Топология: {} физ. ядер / {} лог. потоков", hw.cpu.physical_cores, hw.cpu.logical_threads), Style::default().fg(Color::White)), + if let Some(freq) = hw.cpu.current_frequency_mhz { + Span::styled(format!(" | Текущая частота: {:.1} MHz", freq), Style::default().fg(Color::Green)) + } else { + Span::raw("") + }, + ])); + lines.push(Line::from(vec![ + Span::styled(" Кэши CPU: ", Style::default().fg(Color::Gray)), + Span::styled(format!("{} | {} | {}", hw.cpu.l1_cache, hw.cpu.l2_cache, hw.cpu.l3_cache), Style::default().fg(Color::LightGreen)), + if !hw.cpu.microcode.is_empty() { + Span::styled(format!(" (Microcode: {})", hw.cpu.microcode), Style::default().fg(Color::DarkGray)) + } else { + Span::raw("") + }, + ])); + if let Some(ref virt) = hw.cpu.virtualization { + lines.push(Line::from(vec![ + Span::styled(" Виртуализация: ", Style::default().fg(Color::Gray)), + Span::styled(virt, Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)), + ])); + } + if !hw.cpu.flags.is_empty() { + lines.push(Line::from(vec![ + Span::styled(" Инструкции/Флаги: ", Style::default().fg(Color::Gray)), + Span::styled(hw.cpu.flags.join(", "), Style::default().fg(Color::DarkGray)), + ])); + } + lines.push(Line::raw("")); + + // 2. Motherboard & BIOS + lines.push(Line::from(vec![ + Span::styled("▶ МАТЕРИНСКАЯ ПЛАТА И BIOS (DMI/SMBIOS):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::from(vec![ + Span::styled(format!(" Производитель: {} | Модель: {} {}", hw.motherboard.vendor, hw.motherboard.product_name, hw.motherboard.version), Style::default().fg(Color::White)), + ])); + lines.push(Line::from(vec![ + Span::styled(format!(" BIOS: {} v{} (Дата релиза: {}) | Корпус: {}", hw.motherboard.bios_vendor, hw.motherboard.bios_version, hw.motherboard.bios_date, hw.motherboard.chassis_type), Style::default().fg(Color::DarkGray)), + ])); + lines.push(Line::raw("")); + + // 3. Memory (RAM & Swap) + let ram_total = hw.memory.total_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let ram_used = hw.memory.used_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let ram_avail = hw.memory.available_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let swap_total = hw.memory.swap_total_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let swap_used = hw.memory.swap_used_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + + lines.push(Line::from(vec![ + Span::styled("▶ ОПЕРАТИВНАЯ ПАМЯТЬ И SWAP:", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::from(vec![ + Span::styled(format!(" RAM Всего: {:.2} GB | Занято: {:.2} GB | Доступно: {:.2} GB", ram_total, ram_used, ram_avail), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::from(vec![ + Span::styled(format!(" Swap Файл/Раздел: Всего: {:.2} GB | Использовано: {:.2} GB", swap_total, swap_used), Style::default().fg(Color::DarkGray)), + ])); + lines.push(Line::from(vec![ + Span::styled(format!(" Ошибки памяти EDAC/ECC: Corrected: {} | Uncorrected: {}", hw.memory.edac_ce_count, hw.memory.edac_ue_count), if hw.memory.edac_ue_count > 0 { Style::default().fg(Color::Red).add_modifier(Modifier::BOLD) } else { Style::default().fg(Color::Green) }), + ])); + lines.push(Line::raw("")); + + // 4. GPU + lines.push(Line::from(vec![ + Span::styled("▶ ГРАФИЧЕСКИЕ АДАПТЕРЫ (GPU):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + if hw.gpus.is_empty() { + lines.push(Line::from(vec![Span::styled(" Видеоускорители не обнаружены", Style::default().fg(Color::DarkGray))])); + } else { + for gpu in &hw.gpus { + lines.push(Line::from(vec![ + Span::styled(format!(" • {} — {}", gpu.vendor, gpu.model), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + Span::styled(format!(" [Драйвер: {} | Слот: {}]", gpu.driver, gpu.pci_slot), Style::default().fg(Color::DarkGray)), + ])); + } + } + lines.push(Line::raw("")); + + // 5. Disks + lines.push(Line::from(vec![ + Span::styled("▶ ДИСКОВЫЕ НАКОПИТЕЛИ (NVMe / SSD / HDD):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + if hw.disks.is_empty() { + lines.push(Line::from(vec![Span::styled(" Накопители не обнаружены", Style::default().fg(Color::DarkGray))])); + } else { + for disk in &hw.disks { + let size_gb = disk.size_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let smart_badge = if disk.smart_status == "PASSED" { + Span::styled(" [SMART: PASSED] ", Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)) + } else if disk.smart_status == "FAILED" { + Span::styled(" [SMART: FAILED] ", Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)) + } else { + Span::styled(" [SMART: OK] ", Style::default().fg(Color::LightGreen)) + }; + + let temp_str = disk.temperature_c.map(|t| format!(" | {}°C", t)).unwrap_or_default(); + let type_color = if disk.disk_type.contains("NVMe") { + Color::Magenta + } else if disk.disk_type.contains("SSD") { + Color::LightBlue + } else { + Color::Yellow + }; + + lines.push(Line::from(vec![ + Span::styled(format!(" • {} ", disk.name), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + Span::styled(format!("({}) — {} ", disk.model, disk.disk_type), Style::default().fg(type_color)), + Span::styled(format!("{:.1} GB", size_gb), Style::default().fg(Color::White)), + smart_badge, + Span::styled(temp_str, Style::default().fg(Color::LightGreen)), + ])); + + // Visual Health / Wear Bar + let health_val = disk.health_percent.unwrap_or(100); + let wear_val = disk.wear_percent.unwrap_or(0); + let bar_len = 20; + let filled = ((health_val as usize * bar_len) / 100).min(bar_len); + let bar_str = format!("[{}{}]", "█".repeat(filled), "░".repeat(bar_len - filled)); + let bar_color = if health_val >= 80 { Color::Green } else if health_val >= 50 { Color::Yellow } else { Color::Red }; + + let pwr_str = disk.power_on_hours.map(|p| format!(" | Наработка: {} ч.", p)).unwrap_or_default(); + let bad_str = disk.bad_sectors_count.map(|b| format!(" | Бэд-секторов: {}", b)).unwrap_or_default(); + let sn_str = if !disk.serial.is_empty() { format!(" | S/N: {}", disk.serial) } else { "".to_string() }; + + lines.push(Line::from(vec![ + Span::styled(" Здоровье: ", Style::default().fg(Color::Gray)), + Span::styled(format!("{}% (Износ: {}%) ", health_val, wear_val), Style::default().fg(bar_color).add_modifier(Modifier::BOLD)), + Span::styled(bar_str, Style::default().fg(bar_color)), + Span::styled(format!("{}{}{}", pwr_str, bad_str, sn_str), Style::default().fg(Color::DarkGray)), + ])); + + // Partitions list + if !disk.partitions.is_empty() { + let mut part_spans = vec![Span::styled(" Разделы: ", Style::default().fg(Color::DarkGray))]; + for (idx, p) in disk.partitions.iter().enumerate() { + let p_gb = p.size_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let m_str = p.mount_point.as_deref().unwrap_or("—"); + if idx > 0 { + part_spans.push(Span::styled(" | ", Style::default().fg(Color::DarkGray))); + } + part_spans.push(Span::styled(format!("{} ({:.1}G, {}) ➔ {}", p.name, p_gb, p.fs_type, m_str), Style::default().fg(Color::Gray))); + } + lines.push(Line::from(part_spans)); + } + lines.push(Line::raw("")); + } + } + + // 6. Network Adapters + lines.push(Line::from(vec![ + Span::styled("▶ СЕТЕВЫЕ ИНТЕРФЕЙСЫ (NETWORK ADAPTERS):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + for net in &hw.network_adapters { + let state_color = if net.state == "UP" { Color::Green } else { Color::DarkGray }; + let speed_txt = net.speed_mbps.map(|s| format!("{} Mbps", s)).unwrap_or_else(|| "N/A".to_string()); + lines.push(Line::from(vec![ + Span::styled(format!(" • {}: ", net.interface_name), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + Span::styled(format!("[{}] ", net.if_type), Style::default().fg(Color::Cyan)), + Span::styled(format!("[{}] ", net.state), Style::default().fg(state_color).add_modifier(Modifier::BOLD)), + Span::styled(format!("Скорость: {} | MAC: {} | Драйвер: {}", speed_txt, net.mac_address, net.driver), Style::default().fg(Color::DarkGray)), + ])); + } + lines.push(Line::raw("")); + + // 7. Battery & Thermals + lines.push(Line::from(vec![ + Span::styled("▶ ПИТАНИЕ, БАТАРЕЯ И ОХЛАЖДЕНИЕ:", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + if let Some(ref batt) = hw.battery { + let batt_col = if batt.is_degraded { Color::Red } else { Color::Green }; + lines.push(Line::from(vec![ + Span::styled(format!(" Аккумулятор {}: Емкость: {}% | Здоровье: {:.1}% | Циклов: {} | Статус: {}", batt.name, batt.capacity_percent, batt.health_percent, batt.cycle_count, batt.status), Style::default().fg(batt_col)), + ])); + } else { + lines.push(Line::from(vec![ + Span::styled(" Питание: Стационарное / Батарея не обнаружена", Style::default().fg(Color::DarkGray)), + ])); + } + lines.push(Line::from(vec![ + Span::styled(format!(" Температура CPU: {:.1}°C | Событий Thermal Throttling: {}", hw.thermals.max_cpu_temp_c, hw.thermals.total_throttle_events), if hw.thermals.is_actively_throttling { Style::default().fg(Color::Red).add_modifier(Modifier::BOLD) } else { Style::default().fg(Color::White) }), + ])); + } else { + lines.push(Line::from(vec![Span::styled("Данные об оборудовании еще не собраны. Нажмите [s] для сканирования.", Style::default().fg(Color::Yellow))])); + } + + let block = Block::default() + .title(Span::styled(" Спецификация оборудования [Колесико мыши / PgUp / PgDn - скролл] ", Style::default().fg(Color::LightYellow).add_modifier(Modifier::BOLD))) + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::LightYellow)); + + let p = Paragraph::new(lines) + .block(block) + .scroll((app.log_scroll, 0)) + .wrap(Wrap { trim: false }); + + f.render_widget(p, area); +} + +fn draw_live_monitor_view(f: &mut Frame, app: &App, area: Rect) { + let chunks = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(4), // Метрики в реальном времени + Constraint::Length(7), // Sparklines CPU и RAM + Constraint::Length(7), // Sparklines Temp и Network + Constraint::Min(5), // Детали и статус троттлинга + ]) + .split(area); + + let snap = &app.live_snapshot; + + // 1. Верхние счетчики + let stat_chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage(25), + Constraint::Percentage(25), + Constraint::Percentage(25), + Constraint::Percentage(25), + ]) + .split(chunks[0]); + + // CPU Gauge + let cpu_gauge = Gauge::default() + .block(Block::default().borders(Borders::ALL).title(" CPU Загрузка ")) + .gauge_style(Style::default().fg(if snap.cpu_usage_percent > 85.0 { Color::Red } else if snap.cpu_usage_percent > 60.0 { Color::Yellow } else { Color::Green })) + .percent(snap.cpu_usage_percent.clamp(0.0, 100.0) as u16) + .label(format!("{:.1}%", snap.cpu_usage_percent)); + f.render_widget(cpu_gauge, stat_chunks[0]); + + // RAM Gauge + let ram_pct = if snap.ram_total_bytes > 0 { + ((snap.ram_used_bytes as f64 / snap.ram_total_bytes as f64) * 100.0).clamp(0.0, 100.0) as u16 + } else { + 0 + }; + let ram_used_gb = snap.ram_used_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let ram_total_gb = snap.ram_total_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let ram_gauge = Gauge::default() + .block(Block::default().borders(Borders::ALL).title(" Оперативная память ")) + .gauge_style(Style::default().fg(if ram_pct > 90 { Color::Red } else if ram_pct > 75 { Color::Yellow } else { Color::Cyan })) + .percent(ram_pct) + .label(format!("{:.1}/{:.1} GB ({}%)", ram_used_gb, ram_total_gb, ram_pct)); + f.render_widget(ram_gauge, stat_chunks[1]); + + // CPU Temp Gauge + let temp_pct = (snap.max_cpu_temp_c.clamp(20.0, 105.0) - 20.0) / 85.0 * 100.0; + let temp_gauge = Gauge::default() + .block(Block::default().borders(Borders::ALL).title(" Температура CPU ")) + .gauge_style(Style::default().fg(if snap.max_cpu_temp_c > 85.0 { Color::Red } else if snap.max_cpu_temp_c > 70.0 { Color::Yellow } else { Color::LightGreen })) + .percent(temp_pct.clamp(0.0, 100.0) as u16) + .label(format!("{:.1}°C", snap.max_cpu_temp_c)); + f.render_widget(temp_gauge, stat_chunks[2]); + + // Throttling / IO Status Box + let throttle_style = if snap.is_throttling { + Style::default().fg(Color::White).bg(Color::Red).add_modifier(Modifier::BOLD) + } else { + Style::default().fg(Color::Green) + }; + let throttle_text = vec![ + Line::from(vec![ + Span::raw("Троттлинг: "), + Span::styled(if snap.is_throttling { "АКТИВЕН (ПЕРЕГРЕВ!)" } else { "Отсутствует (Норма)" }, throttle_style), + ]), + Line::from(vec![ + Span::styled(format!("Диск R/W: {:.1} MB/s | Сеть: {:.1} KB/s", + (snap.disk_read_kbps + snap.disk_write_kbps) as f64 / 1024.0, + (snap.net_rx_kbps + snap.net_tx_kbps) as f64), Style::default().fg(Color::Gray)), + ]), + ]; + let throttle_p = Paragraph::new(throttle_text).block(Block::default().borders(Borders::ALL).title(" Охлаждение и I/O ")); + f.render_widget(throttle_p, stat_chunks[3]); + + // 2. CPU & RAM Sparklines + let mid_chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) + .split(chunks[1]); + + let cpu_spark = Sparkline::default() + .block(Block::default().borders(Borders::ALL).title(" График загрузки CPU % (60 сек) ")) + .data(&app.cpu_history) + .max(100) + .style(Style::default().fg(Color::Cyan)); + f.render_widget(cpu_spark, mid_chunks[0]); + + let ram_spark = Sparkline::default() + .block(Block::default().borders(Borders::ALL).title(" График использования RAM % (60 сек) ")) + .data(&app.ram_history) + .max(100) + .style(Style::default().fg(Color::LightGreen)); + f.render_widget(ram_spark, mid_chunks[1]); + + // 3. Temp & Net Sparklines + let bot_spark_chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) + .split(chunks[2]); + + let temp_spark = Sparkline::default() + .block(Block::default().borders(Borders::ALL).title(" График температуры CPU °C (60 сек) ")) + .data(&app.temp_history) + .max(105) + .style(Style::default().fg(Color::Yellow)); + f.render_widget(temp_spark, bot_spark_chunks[0]); + + let net_spark = Sparkline::default() + .block(Block::default().borders(Borders::ALL).title(" График сетевого трафика KB/s (60 сек) ")) + .data(&app.net_history) + .style(Style::default().fg(Color::Magenta)); + f.render_widget(net_spark, bot_spark_chunks[1]); + + // 4. Нижняя сводка + let mut details_lines = Vec::new(); + if snap.is_throttling { + details_lines.push(Line::from(vec![ + Span::styled(" [!] ВНИМАНИЕ: Процессор находится в состоянии троттлинга! Частоты сброшены для предотвращения повреждения кристаллов. ", Style::default().fg(Color::White).bg(Color::Red).add_modifier(Modifier::BOLD)), + ])); + details_lines.push(Line::raw("")); + } + let swap_used_gb = snap.swap_used_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + let swap_total_gb = snap.swap_total_bytes as f64 / (1024.0 * 1024.0 * 1024.0); + details_lines.push(Line::from(vec![ + Span::styled(" Оперативная память: ", Style::default().fg(Color::Cyan)), + Span::styled(format!("{:.2} GB свободно из {:.2} GB | Swap: {:.2} GB из {:.2} GB", ram_total_gb - ram_used_gb, ram_total_gb, swap_used_gb, swap_total_gb), Style::default().fg(Color::White)), + ])); + details_lines.push(Line::from(vec![ + Span::styled(" Сетевой обмен: ", Style::default().fg(Color::Magenta)), + Span::styled(format!("RX: {} KB/s | TX: {} KB/s", snap.net_rx_kbps, snap.net_tx_kbps), Style::default().fg(Color::White)), + Span::styled(" Дисковый обмен: ", Style::default().fg(Color::Yellow)), + Span::styled(format!("Read: {:.1} MB/s | Write: {:.1} MB/s", snap.disk_read_kbps as f64 / 1024.0, snap.disk_write_kbps as f64 / 1024.0), Style::default().fg(Color::White)), + ])); + details_lines.push(Line::from(vec![ + Span::styled(" Совет: ", Style::default().fg(Color::DarkGray)), + Span::styled("Метрики обновляются в реальном времени каждую секунду. Переключение на другие вкладки: [1-5].", Style::default().fg(Color::DarkGray)), + ])); + + let details_p = Paragraph::new(details_lines) + .block(Block::default().borders(Borders::ALL).title(" Детализация сенсоров и нагрузки ")) + .wrap(Wrap { trim: false }); + f.render_widget(details_p, chunks[3]); +} + +fn draw_security_view(f: &mut Frame, app: &App, area: Rect) { + let chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage(45), // Сетевые порты 0.0.0.0 и SUID файлы + Constraint::Percentage(55), // Оценка защищенности и ядро + ]) + .split(area); + + if let Some(ref report) = app.report { + let sec = &report.security; + + // Левая колонка: Открытые порты и SUID + let mut left_lines = Vec::new(); + left_lines.push(Line::from(vec![ + Span::styled("▶ ОТКРЫТЫЕ СЕТЕВЫЕ ПОРТЫ (0.0.0.0 / ::):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + + if sec.exposed_ports.is_empty() { + left_lines.push(Line::from(vec![Span::styled(" Нет открытых вовне портов", Style::default().fg(Color::Green))])); + } else { + for port in &sec.exposed_ports { + let (badge, color) = match port.risk_level { + Severity::Critical => ("[CRIT]", Color::Red), + Severity::Warning => ("[WARN]", Color::Yellow), + Severity::Info => ("[INFO]", Color::Green), + }; + let proc_name = if port.process_name.is_empty() { "unknown" } else { &port.process_name }; + left_lines.push(Line::from(vec![ + Span::styled(format!(" {} ", badge), Style::default().fg(color).add_modifier(Modifier::BOLD)), + Span::styled(format!("{}:{} ", port.protocol, port.port), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + Span::styled(format!("({}) ", proc_name), Style::default().fg(Color::LightBlue)), + Span::styled(format!("[{}]", port.local_address), Style::default().fg(Color::DarkGray)), + ])); + if !port.recommendation.is_empty() { + left_lines.push(Line::from(vec![ + Span::styled(format!(" ↳ {}", port.recommendation), Style::default().fg(color)), + ])); + } + } + } + left_lines.push(Line::raw("")); + + left_lines.push(Line::from(vec![ + Span::styled("▶ ПОДОЗРИТЕЛЬНЫЕ SUID / SGID БИНАРНИКИ:", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + if sec.suid_anomalies.is_empty() { + left_lines.push(Line::from(vec![Span::styled(" Аномальных SUID бинарников в /tmp, /dev/shm не найдено", Style::default().fg(Color::Green))])); + } else { + for s in &sec.suid_anomalies { + left_lines.push(Line::from(vec![ + Span::styled(" [!] ", Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)), + Span::styled(&s.path, Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)), + Span::styled(format!(" (Владелец: {})", s.owner), Style::default().fg(Color::DarkGray)), + ])); + left_lines.push(Line::from(vec![ + Span::styled(format!(" ↳ {}", s.risk_reason), Style::default().fg(Color::Red)), + ])); + } + } + + let left_block = Block::default() + .borders(Borders::ALL) + .title(" Сетевой периметр и SUID-файлы [Колесико - скролл] ") + .border_style(Style::default().fg(Color::Cyan)); + let left_p = Paragraph::new(left_lines) + .block(left_block) + .scroll((app.log_scroll, 0)) + .wrap(Wrap { trim: false }); + f.render_widget(left_p, chunks[0]); + + // Правая колонка: Оценка и чек-лист защиты ядра/ОС + let right_chunks = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Length(4), // Оценка безопасности + Constraint::Min(8), // Чек-лист + ]) + .split(chunks[1]); + + let score_color = if sec.security_score >= 80 { + Color::Green + } else if sec.security_score >= 50 { + Color::Yellow + } else { + Color::Red + }; + + let score_gauge = Gauge::default() + .block(Block::default().borders(Borders::ALL).title(" Индекс безопасности системы (Hardening Score) ")) + .gauge_style(Style::default().fg(score_color)) + .percent(sec.security_score as u16) + .label(format!("{}/100 Баллов", sec.security_score)); + f.render_widget(score_gauge, right_chunks[0]); + + let mut right_lines = Vec::new(); + right_lines.push(Line::from(vec![ + Span::styled("▶ ПРОВЕРКА ЗАЩИТЫ ЯДРА И ПОДСИСТЕМ (HARDENING):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + for check in &sec.hardening_checks { + let (status_badge, status_color) = if check.is_secure { + ("[✓ PASS]", Color::Green) + } else { + ("[✗ FAIL]", Color::Red) + }; + + right_lines.push(Line::from(vec![ + Span::styled(format!(" {} ", status_badge), Style::default().fg(status_color).add_modifier(Modifier::BOLD)), + Span::styled(format!("{}: ", check.name), Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + Span::styled(&check.status, Style::default().fg(status_color)), + ])); + right_lines.push(Line::from(vec![ + Span::styled(format!(" {}", check.description), Style::default().fg(Color::Gray)), + ])); + if !check.is_secure { + if let Some(ref rem) = check.remediation { + right_lines.push(Line::from(vec![ + Span::styled(format!(" ➔ Рекомендация: {}", rem), Style::default().fg(Color::Yellow)), + ])); + } + } + right_lines.push(Line::raw("")); + } + + let right_block = Block::default() + .borders(Borders::ALL) + .title(" Параметры безопасности ядра ") + .border_style(Style::default().fg(score_color)); + let right_p = Paragraph::new(right_lines) + .block(right_block) + .scroll((app.log_scroll, 0)) + .wrap(Wrap { trim: false }); + f.render_widget(right_p, right_chunks[1]); + } else { + let p = Paragraph::new("Данные аудита безопасности еще не собраны. Нажмите [s] для сканирования.") + .block(Block::default().borders(Borders::ALL)); + f.render_widget(p, area); + } +} + +fn draw_crashes_view(f: &mut Frame, app: &App, area: Rect) { + let chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage(38), // Список аварий + Constraint::Percentage(62), // Детали сбоя и трассировка + ]) + .split(area); + + let crashes = app.report.as_ref().map(|r| &r.crashes); + + // Левая колонка: Список сбоев + let mut items = Vec::new(); + if let Some(crashes_list) = crashes { + for (i, crash) in crashes_list.iter().enumerate() { + let is_selected = i == app.selected_crash_idx; + let prefix = if is_selected { "▶ " } else { " " }; + let style = if is_selected { + Style::default().fg(Color::White).bg(Color::Rgb(50, 20, 20)).add_modifier(Modifier::BOLD) + } else { + Style::default().fg(Color::Gray) + }; + + let line = Line::from(vec![ + Span::raw(prefix), + Span::styled("[CRASH] ", Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)), + Span::styled(&crash.process_name, style), + Span::styled(format!(" ({})", crash.signal_or_code), Style::default().fg(Color::Yellow)), + ]); + items.push(ListItem::new(line)); + } + } + + let list_title = format!( + " Журнал аварийных падений ({}) ", + crashes.map(|c| c.len()).unwrap_or(0) + ); + let list_block = Block::default() + .title(Span::styled(list_title, Style::default().fg(Color::White).add_modifier(Modifier::BOLD))) + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::Red)); + let list_widget = List::new(items).block(list_block); + f.render_widget(list_widget, chunks[0]); + + // Правая колонка: Детали сбоя + if let Some(crashes_list) = crashes { + if let Some(crash) = crashes_list.get(app.selected_crash_idx) { + let mut lines = Vec::new(); + lines.push(Line::from(vec![ + Span::styled(" АВАРИЙНЫЙ СБОЙ ПРОЦЕССА (CORE DUMP / CRASH REPORT) ", Style::default().fg(Color::White).bg(Color::Red).add_modifier(Modifier::BOLD)), + ])); + lines.push(Line::raw("")); + + lines.push(Line::from(vec![ + Span::styled(" Исполняемый файл: ", Style::default().fg(Color::Gray)), + Span::styled(&crash.process_name, Style::default().fg(Color::White).add_modifier(Modifier::BOLD)), + if let Some(pid) = crash.pid { + Span::styled(format!(" (PID: {})", pid), Style::default().fg(Color::DarkGray)) + } else { + Span::raw("") + }, + ])); + lines.push(Line::from(vec![ + Span::styled(" Время падения: ", Style::default().fg(Color::Gray)), + Span::styled(&crash.timestamp, Style::default().fg(Color::LightBlue)), + Span::styled(" | Сигнал / Код: ", Style::default().fg(Color::Gray)), + Span::styled(&crash.signal_or_code, Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)), + ])); + if let Some(ref fm) = crash.fault_module { + lines.push(Line::from(vec![ + Span::styled(" Сбойный модуль/библиотека: ", Style::default().fg(Color::Gray)), + Span::styled(fm, Style::default().fg(Color::LightRed).add_modifier(Modifier::BOLD)), + ])); + } + if let Some(ref dp) = crash.dump_path { + lines.push(Line::from(vec![ + Span::styled(" Файл Core Dump: ", Style::default().fg(Color::Gray)), + Span::styled(dp, Style::default().fg(Color::LightCyan)), + ])); + } + lines.push(Line::raw("")); + + lines.push(Line::from(vec![ + Span::styled("▶ СТЕК ВЫЗОВОВ / СЛЕД ПАДЕНИЯ (BACKTRACE):", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + ])); + if crash.stack_trace_snippet.is_empty() { + lines.push(Line::from(vec![Span::styled(" Трассировка стека недоступна в дампе", Style::default().fg(Color::DarkGray))])); + } else { + for stack_line in crash.stack_trace_snippet.lines() { + lines.push(Line::from(vec![ + Span::styled(format!(" {}", stack_line), Style::default().fg(Color::White)), + ])); + } + } + lines.push(Line::raw("")); + + lines.push(Line::from(vec![ + Span::styled("▶ КОМАНДА ОТЛАДКИ В GDB / COREDUMPCTL:", Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)), + ])); + let debug_cmd = if let Some(ref dp) = crash.dump_path { + format!("gdb {} {}", crash.process_name, dp) + } else if let Some(pid) = crash.pid { + format!("coredumpctl debug {}", pid) + } else { + format!("coredumpctl info {}", crash.process_name) + }; + lines.push(Line::from(vec![ + Span::styled(" $ ", Style::default().fg(Color::DarkGray)), + Span::styled(&debug_cmd, Style::default().fg(Color::LightGreen).bg(Color::Rgb(15, 30, 15)).add_modifier(Modifier::BOLD)), + ])); + + let block = Block::default() + .title(Span::styled(" Анализ сбоя [PgUp / PgDn - скролл] ", Style::default().fg(Color::White).add_modifier(Modifier::BOLD))) + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::Red)); + + let p = Paragraph::new(lines) + .block(block) + .scroll((app.log_scroll, 0)) + .wrap(Wrap { trim: false }); + f.render_widget(p, chunks[1]); + return; + } + } + + let block = Block::default().borders(Borders::ALL); + let p = Paragraph::new("Аварийных сбоев процессов или дампов памяти не зафиксировано.").block(block); + f.render_widget(p, chunks[1]); +} + +fn draw_footer(f: &mut Frame, _app: &App, area: Rect) { + let keys = Line::from(vec![ + Span::styled(" [q]", Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)), + Span::raw(" Выход "), + Span::styled("[s]", Style::default().fg(Color::Green).add_modifier(Modifier::BOLD)), + Span::raw(" Скан "), + Span::styled("[1-5]", Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD)), + Span::raw(" Вкладки "), + Span::styled("[↑/↓/j/k]", Style::default().fg(Color::LightYellow).add_modifier(Modifier::BOLD)), + Span::raw(" Выбор "), + Span::styled("[c]", Style::default().fg(Color::LightGreen).add_modifier(Modifier::BOLD)), + Span::raw(" Копия "), + Span::styled("[6/l]", Style::default().fg(Color::Magenta).add_modifier(Modifier::BOLD)), + Span::raw(" Лог "), + Span::styled("[7/p]", Style::default().fg(Color::LightBlue).add_modifier(Modifier::BOLD)), + Span::raw(" Prompt "), + Span::styled("[e]", Style::default().fg(Color::LightYellow).add_modifier(Modifier::BOLD)), + Span::raw(" Экспорт "), + Span::styled("[PgUp/PgDn]", Style::default().fg(Color::DarkGray)), + Span::raw(" Скролл"), + ]); + + let p = Paragraph::new(keys); + f.render_widget(p, area); +} diff --git a/rust_builder/.gitignore b/rust_builder/.gitignore new file mode 100644 index 0000000..ac5aa98 --- /dev/null +++ b/rust_builder/.gitignore @@ -0,0 +1,29 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +build/ diff --git a/rust_builder/README.md b/rust_builder/README.md new file mode 100644 index 0000000..922615f --- /dev/null +++ b/rust_builder/README.md @@ -0,0 +1 @@ +Please ignore this folder, which is just glue to build Rust with Flutter. \ No newline at end of file diff --git a/rust_builder/android/.gitignore b/rust_builder/android/.gitignore new file mode 100644 index 0000000..161bdcd --- /dev/null +++ b/rust_builder/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/rust_builder/android/build.gradle b/rust_builder/android/build.gradle new file mode 100644 index 0000000..6d61f94 --- /dev/null +++ b/rust_builder/android/build.gradle @@ -0,0 +1,56 @@ +// The Android Gradle Plugin builds the native code with the Android NDK. + +group 'com.flutter_rust_bridge.rust_lib_diagd' +version '1.0' + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + // The Android Gradle Plugin knows how to build native code with the NDK. + classpath 'com.android.tools.build:gradle:7.3.0' + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: 'com.android.library' + +android { + if (project.android.hasProperty("namespace")) { + namespace 'com.flutter_rust_bridge.rust_lib_diagd' + } + + // Bumping the plugin compileSdkVersion requires all clients of this plugin + // to bump the version in their app. + compileSdkVersion 36 + + // Use the NDK version + // declared in /android/app/build.gradle file of the Flutter project. + // Replace it with a version number if this plugin requires a specfic NDK version. + // (e.g. ndkVersion "23.1.7779620") + ndkVersion android.ndkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + minSdkVersion 19 + } +} + +apply from: "../cargokit/gradle/plugin.gradle" +cargokit { + manifestDir = "../../rust" + libname = "rust_lib_diagd" +} diff --git a/rust_builder/android/settings.gradle b/rust_builder/android/settings.gradle new file mode 100644 index 0000000..2572463 --- /dev/null +++ b/rust_builder/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'rust_lib_diagd' diff --git a/rust_builder/android/src/main/AndroidManifest.xml b/rust_builder/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..d19199b --- /dev/null +++ b/rust_builder/android/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/rust_builder/cargokit/.gitignore b/rust_builder/cargokit/.gitignore new file mode 100644 index 0000000..cf7bb86 --- /dev/null +++ b/rust_builder/cargokit/.gitignore @@ -0,0 +1,4 @@ +target +.dart_tool +*.iml +!pubspec.lock diff --git a/rust_builder/cargokit/LICENSE b/rust_builder/cargokit/LICENSE new file mode 100644 index 0000000..d33a5fe --- /dev/null +++ b/rust_builder/cargokit/LICENSE @@ -0,0 +1,42 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +Copyright 2022 Matej Knopp + +================================================================================ + +MIT LICENSE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================================================================================ + +APACHE LICENSE, VERSION 2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + diff --git a/rust_builder/cargokit/README b/rust_builder/cargokit/README new file mode 100644 index 0000000..398474d --- /dev/null +++ b/rust_builder/cargokit/README @@ -0,0 +1,11 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +Experimental repository to provide glue for seamlessly integrating cargo build +with flutter plugins and packages. + +See https://matejknopp.com/post/flutter_plugin_in_rust_with_no_prebuilt_binaries/ +for a tutorial on how to use Cargokit. + +Example plugin available at https://github.com/irondash/hello_rust_ffi_plugin. + diff --git a/rust_builder/cargokit/build_pod.sh b/rust_builder/cargokit/build_pod.sh new file mode 100755 index 0000000..ed0e0d9 --- /dev/null +++ b/rust_builder/cargokit/build_pod.sh @@ -0,0 +1,58 @@ +#!/bin/sh +set -e + +BASEDIR=$(dirname "$0") + +# Workaround for https://github.com/dart-lang/pub/issues/4010 +BASEDIR=$(cd "$BASEDIR" ; pwd -P) + +# Remove XCode SDK from path. Otherwise this breaks tool compilation when building iOS project +NEW_PATH=`echo $PATH | tr ":" "\n" | grep -v "Contents/Developer/" | tr "\n" ":"` + +export PATH=${NEW_PATH%?} # remove trailing : + +env + +# Platform name (macosx, iphoneos, iphonesimulator) +export CARGOKIT_DARWIN_PLATFORM_NAME=$PLATFORM_NAME + +# Arctive architectures (arm64, armv7, x86_64), space separated. +export CARGOKIT_DARWIN_ARCHS=$ARCHS + +# Current build configuration (Debug, Release) +export CARGOKIT_CONFIGURATION=$CONFIGURATION + +# Path to directory containing Cargo.toml. +export CARGOKIT_MANIFEST_DIR=$PODS_TARGET_SRCROOT/$1 + +# Temporary directory for build artifacts. +export CARGOKIT_TARGET_TEMP_DIR=$TARGET_TEMP_DIR + +# Output directory for final artifacts. +export CARGOKIT_OUTPUT_DIR=$PODS_CONFIGURATION_BUILD_DIR/$PRODUCT_NAME + +# Directory to store built tool artifacts. +export CARGOKIT_TOOL_TEMP_DIR=$TARGET_TEMP_DIR/build_tool + +# Directory inside root project. Not necessarily the top level directory of root project. +export CARGOKIT_ROOT_PROJECT_DIR=$SRCROOT + +FLUTTER_EXPORT_BUILD_ENVIRONMENT=( + "$PODS_ROOT/../Flutter/ephemeral/flutter_export_environment.sh" # macOS + "$PODS_ROOT/../Flutter/flutter_export_environment.sh" # iOS +) + +for path in "${FLUTTER_EXPORT_BUILD_ENVIRONMENT[@]}" +do + if [[ -f "$path" ]]; then + source "$path" + fi +done + +sh "$BASEDIR/run_build_tool.sh" build-pod "$@" + +# Make a symlink from built framework to phony file, which will be used as input to +# build script. This should force rebuild (podspec currently doesn't support alwaysOutOfDate +# attribute on custom build phase) +ln -fs "$OBJROOT/XCBuildData/build.db" "${BUILT_PRODUCTS_DIR}/cargokit_phony" +ln -fs "${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}" "${BUILT_PRODUCTS_DIR}/cargokit_phony_out" diff --git a/rust_builder/cargokit/build_tool/README.md b/rust_builder/cargokit/build_tool/README.md new file mode 100644 index 0000000..a878c27 --- /dev/null +++ b/rust_builder/cargokit/build_tool/README.md @@ -0,0 +1,5 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +A sample command-line application with an entrypoint in `bin/`, library code +in `lib/`, and example unit test in `test/`. diff --git a/rust_builder/cargokit/build_tool/analysis_options.yaml b/rust_builder/cargokit/build_tool/analysis_options.yaml new file mode 100644 index 0000000..0e16a8b --- /dev/null +++ b/rust_builder/cargokit/build_tool/analysis_options.yaml @@ -0,0 +1,34 @@ +# This is copied from Cargokit (which is the official way to use it currently) +# Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +# This file configures the static analysis results for your project (errors, +# warnings, and lints). +# +# This enables the 'recommended' set of lints from `package:lints`. +# This set helps identify many issues that may lead to problems when running +# or consuming Dart code, and enforces writing Dart using a single, idiomatic +# style and format. +# +# If you want a smaller set of lints you can change this to specify +# 'package:lints/core.yaml'. These are just the most critical lints +# (the recommended set includes the core lints). +# The core lints are also what is used by pub.dev for scoring packages. + +include: package:lints/recommended.yaml + +# Uncomment the following section to specify additional rules. + +linter: + rules: + - prefer_relative_imports + - directives_ordering + +# analyzer: +# exclude: +# - path/to/excluded/files/** + +# For more information about the core and recommended set of lints, see +# https://dart.dev/go/core-lints + +# For additional information about configuring this file, see +# https://dart.dev/guides/language/analysis-options diff --git a/rust_builder/cargokit/build_tool/bin/build_tool.dart b/rust_builder/cargokit/build_tool/bin/build_tool.dart new file mode 100644 index 0000000..268eb52 --- /dev/null +++ b/rust_builder/cargokit/build_tool/bin/build_tool.dart @@ -0,0 +1,8 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'package:build_tool/build_tool.dart' as build_tool; + +void main(List arguments) { + build_tool.runMain(arguments); +} diff --git a/rust_builder/cargokit/build_tool/lib/build_tool.dart b/rust_builder/cargokit/build_tool/lib/build_tool.dart new file mode 100644 index 0000000..7c1bb75 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/build_tool.dart @@ -0,0 +1,8 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'src/build_tool.dart' as build_tool; + +Future runMain(List args) async { + return build_tool.runMain(args); +} diff --git a/rust_builder/cargokit/build_tool/lib/src/android_environment.dart b/rust_builder/cargokit/build_tool/lib/src/android_environment.dart new file mode 100644 index 0000000..37dec57 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/android_environment.dart @@ -0,0 +1,209 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; +import 'dart:isolate'; +import 'dart:math' as math; + +import 'package:collection/collection.dart'; +import 'package:path/path.dart' as path; +import 'package:version/version.dart'; + +import 'target.dart'; +import 'util.dart'; + +class AndroidEnvironment { + AndroidEnvironment({ + required this.sdkPath, + required this.ndkVersion, + required this.minSdkVersion, + required this.targetTempDir, + required this.target, + }); + + static void clangLinkerWrapper(List args) { + final clang = Platform.environment['_CARGOKIT_NDK_LINK_CLANG']; + if (clang == null) { + throw Exception( + "cargo-ndk rustc linker: didn't find _CARGOKIT_NDK_LINK_CLANG env var"); + } + final target = Platform.environment['_CARGOKIT_NDK_LINK_TARGET']; + if (target == null) { + throw Exception( + "cargo-ndk rustc linker: didn't find _CARGOKIT_NDK_LINK_TARGET env var"); + } + + runCommand(clang, [ + target, + ...args, + ]); + } + + /// Full path to Android SDK. + final String sdkPath; + + /// Full version of Android NDK. + final String ndkVersion; + + /// Minimum supported SDK version. + final int minSdkVersion; + + /// Target directory for build artifacts. + final String targetTempDir; + + /// Target being built. + final Target target; + + bool ndkIsInstalled() { + final ndkPath = path.join(sdkPath, 'ndk', ndkVersion); + final ndkPackageXml = File(path.join(ndkPath, 'package.xml')); + return ndkPackageXml.existsSync(); + } + + void installNdk({ + required String javaHome, + }) { + final sdkManagerExtension = Platform.isWindows ? '.bat' : ''; + final sdkManager = path.join( + sdkPath, + 'cmdline-tools', + 'latest', + 'bin', + 'sdkmanager$sdkManagerExtension', + ); + + log.info('Installing NDK $ndkVersion'); + runCommand(sdkManager, [ + '--install', + 'ndk;$ndkVersion', + ], environment: { + 'JAVA_HOME': javaHome, + }); + } + + Future> buildEnvironment() async { + final hostArch = Platform.isMacOS + ? "darwin-x86_64" + : (Platform.isLinux ? "linux-x86_64" : "windows-x86_64"); + + final ndkPath = path.join(sdkPath, 'ndk', ndkVersion); + final toolchainPath = path.join( + ndkPath, + 'toolchains', + 'llvm', + 'prebuilt', + hostArch, + 'bin', + ); + + final minSdkVersion = + math.max(target.androidMinSdkVersion!, this.minSdkVersion); + + final exe = Platform.isWindows ? '.exe' : ''; + + final arKey = 'AR_${target.rust}'; + final arValue = ['${target.rust}-ar', 'llvm-ar', 'llvm-ar.exe'] + .map((e) => path.join(toolchainPath, e)) + .firstWhereOrNull((element) => File(element).existsSync()); + if (arValue == null) { + throw Exception('Failed to find ar for $target in $toolchainPath'); + } + + final targetArg = '--target=${target.rust}$minSdkVersion'; + + final ccKey = 'CC_${target.rust}'; + final ccValue = path.join(toolchainPath, 'clang$exe'); + final cfFlagsKey = 'CFLAGS_${target.rust}'; + final cFlagsValue = targetArg; + + final cxxKey = 'CXX_${target.rust}'; + final cxxValue = path.join(toolchainPath, 'clang++$exe'); + final cxxFlagsKey = 'CXXFLAGS_${target.rust}'; + final cxxFlagsValue = targetArg; + + final linkerKey = + 'cargo_target_${target.rust.replaceAll('-', '_')}_linker'.toUpperCase(); + + final ranlibKey = 'RANLIB_${target.rust}'; + final ranlibValue = path.join(toolchainPath, 'llvm-ranlib$exe'); + + final ndkVersionParsed = Version.parse(ndkVersion); + final rustFlagsKey = 'CARGO_ENCODED_RUSTFLAGS'; + final rustFlagsValue = _libGccWorkaround(targetTempDir, ndkVersionParsed); + + final runRustTool = + Platform.isWindows ? 'run_build_tool.cmd' : 'run_build_tool.sh'; + + final packagePath = (await Isolate.resolvePackageUri( + Uri.parse('package:build_tool/buildtool.dart')))! + .toFilePath(); + final selfPath = path.canonicalize(path.join( + packagePath, + '..', + '..', + '..', + runRustTool, + )); + + // Make sure that run_build_tool is working properly even initially launched directly + // through dart run. + final toolTempDir = + Platform.environment['CARGOKIT_TOOL_TEMP_DIR'] ?? targetTempDir; + + return { + arKey: arValue, + ccKey: ccValue, + cfFlagsKey: cFlagsValue, + cxxKey: cxxValue, + cxxFlagsKey: cxxFlagsValue, + ranlibKey: ranlibValue, + rustFlagsKey: rustFlagsValue, + linkerKey: selfPath, + // Recognized by main() so we know when we're acting as a wrapper + '_CARGOKIT_NDK_LINK_TARGET': targetArg, + '_CARGOKIT_NDK_LINK_CLANG': ccValue, + 'CARGOKIT_TOOL_TEMP_DIR': toolTempDir, + }; + } + + // Workaround for libgcc missing in NDK23, inspired by cargo-ndk + String _libGccWorkaround(String buildDir, Version ndkVersion) { + final workaroundDir = path.join( + buildDir, + 'cargokit', + 'libgcc_workaround', + '${ndkVersion.major}', + ); + Directory(workaroundDir).createSync(recursive: true); + if (ndkVersion.major >= 23) { + File(path.join(workaroundDir, 'libgcc.a')) + .writeAsStringSync('INPUT(-lunwind)'); + } else { + // Other way around, untested, forward libgcc.a from libunwind once Rust + // gets updated for NDK23+. + File(path.join(workaroundDir, 'libunwind.a')) + .writeAsStringSync('INPUT(-lgcc)'); + } + + var rustFlags = Platform.environment['CARGO_ENCODED_RUSTFLAGS'] ?? ''; + if (rustFlags.isNotEmpty) { + rustFlags = '$rustFlags\x1f'; + } + if (["arm64-v8a", "x86_64"].contains(target.android)) { + rustFlags = '$rustFlags-L\x1f$workaroundDir\x1f'; + + const pageSizeArgs = [ + "-C", + "link-arg=-Wl,--hash-style=both", + "-C", + "link-arg=-Wl,-z,max-page-size=16384" + ]; + final pageSizeArgsString = pageSizeArgs.join("\x1f"); + + rustFlags = '$rustFlags$pageSizeArgsString'; + } else { + rustFlags = '$rustFlags-L\x1f$workaroundDir'; + } + return rustFlags; + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart b/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart new file mode 100644 index 0000000..e608cec --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart @@ -0,0 +1,266 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:http/http.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'builder.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'rustup.dart'; +import 'target.dart'; + +class Artifact { + /// File system location of the artifact. + final String path; + + /// Actual file name that the artifact should have in destination folder. + final String finalFileName; + + AritifactType get type { + if (finalFileName.endsWith('.dll') || + finalFileName.endsWith('.dll.lib') || + finalFileName.endsWith('.pdb') || + finalFileName.endsWith('.so') || + finalFileName.endsWith('.dylib')) { + return AritifactType.dylib; + } else if (finalFileName.endsWith('.lib') || finalFileName.endsWith('.a')) { + return AritifactType.staticlib; + } else { + throw Exception('Unknown artifact type for $finalFileName'); + } + } + + Artifact({ + required this.path, + required this.finalFileName, + }); +} + +final _log = Logger('artifacts_provider'); + +class ArtifactProvider { + ArtifactProvider({ + required this.environment, + required this.userOptions, + }); + + final BuildEnvironment environment; + final CargokitUserOptions userOptions; + + Future>> getArtifacts(List targets) async { + final result = await _getPrecompiledArtifacts(targets); + + final pendingTargets = List.of(targets); + pendingTargets.removeWhere((element) => result.containsKey(element)); + + if (pendingTargets.isEmpty) { + return result; + } + + final rustup = Rustup(); + for (final target in targets) { + final builder = RustBuilder(target: target, environment: environment); + builder.prepare(rustup); + _log.info('Building ${environment.crateInfo.packageName} for $target'); + final targetDir = await builder.build(); + // For local build accept both static and dynamic libraries. + final artifactNames = { + ...getArtifactNames( + target: target, + libraryName: environment.crateInfo.packageName, + aritifactType: AritifactType.dylib, + remote: false, + ), + ...getArtifactNames( + target: target, + libraryName: environment.crateInfo.packageName, + aritifactType: AritifactType.staticlib, + remote: false, + ) + }; + final artifacts = artifactNames + .map((artifactName) => Artifact( + path: path.join(targetDir, artifactName), + finalFileName: artifactName, + )) + .where((element) => File(element.path).existsSync()) + .toList(); + result[target] = artifacts; + } + return result; + } + + Future>> _getPrecompiledArtifacts( + List targets) async { + if (userOptions.usePrecompiledBinaries == false) { + _log.info('Precompiled binaries are disabled'); + return {}; + } + if (environment.crateOptions.precompiledBinaries == null) { + _log.fine('Precompiled binaries not enabled for this crate'); + return {}; + } + + final start = Stopwatch()..start(); + final crateHash = CrateHash.compute(environment.manifestDir, + tempStorage: environment.targetTempDir); + _log.fine( + 'Computed crate hash $crateHash in ${start.elapsedMilliseconds}ms'); + + final downloadedArtifactsDir = + path.join(environment.targetTempDir, 'precompiled', crateHash); + Directory(downloadedArtifactsDir).createSync(recursive: true); + + final res = >{}; + + for (final target in targets) { + final requiredArtifacts = getArtifactNames( + target: target, + libraryName: environment.crateInfo.packageName, + remote: true, + ); + final artifactsForTarget = []; + + for (final artifact in requiredArtifacts) { + final fileName = PrecompileBinaries.fileName(target, artifact); + final downloadedPath = path.join(downloadedArtifactsDir, fileName); + if (!File(downloadedPath).existsSync()) { + final signatureFileName = + PrecompileBinaries.signatureFileName(target, artifact); + await _tryDownloadArtifacts( + crateHash: crateHash, + fileName: fileName, + signatureFileName: signatureFileName, + finalPath: downloadedPath, + ); + } + if (File(downloadedPath).existsSync()) { + artifactsForTarget.add(Artifact( + path: downloadedPath, + finalFileName: artifact, + )); + } else { + break; + } + } + + // Only provide complete set of artifacts. + if (artifactsForTarget.length == requiredArtifacts.length) { + _log.fine('Found precompiled artifacts for $target'); + res[target] = artifactsForTarget; + } + } + + return res; + } + + static Future _get(Uri url, {Map? headers}) async { + int attempt = 0; + const maxAttempts = 10; + while (true) { + try { + return await get(url, headers: headers); + } on SocketException catch (e) { + // Try to detect reset by peer error and retry. + if (attempt++ < maxAttempts && + (e.osError?.errorCode == 54 || e.osError?.errorCode == 10054)) { + _log.severe( + 'Failed to download $url: $e, attempt $attempt of $maxAttempts, will retry...'); + await Future.delayed(Duration(seconds: 1)); + continue; + } else { + rethrow; + } + } + } + } + + Future _tryDownloadArtifacts({ + required String crateHash, + required String fileName, + required String signatureFileName, + required String finalPath, + }) async { + final precompiledBinaries = environment.crateOptions.precompiledBinaries!; + final prefix = precompiledBinaries.uriPrefix; + final url = Uri.parse('$prefix$crateHash/$fileName'); + final signatureUrl = Uri.parse('$prefix$crateHash/$signatureFileName'); + _log.fine('Downloading signature from $signatureUrl'); + final signature = await _get(signatureUrl); + if (signature.statusCode == 404) { + _log.warning( + 'Precompiled binaries not available for crate hash $crateHash ($fileName)'); + return; + } + if (signature.statusCode != 200) { + _log.severe( + 'Failed to download signature $signatureUrl: status ${signature.statusCode}'); + return; + } + _log.fine('Downloading binary from $url'); + final res = await _get(url); + if (res.statusCode != 200) { + _log.severe('Failed to download binary $url: status ${res.statusCode}'); + return; + } + if (verify( + precompiledBinaries.publicKey, res.bodyBytes, signature.bodyBytes)) { + File(finalPath).writeAsBytesSync(res.bodyBytes); + } else { + _log.shout('Signature verification failed! Ignoring binary.'); + } + } +} + +enum AritifactType { + staticlib, + dylib, +} + +AritifactType artifactTypeForTarget(Target target) { + if (target.darwinPlatform != null) { + return AritifactType.staticlib; + } else { + return AritifactType.dylib; + } +} + +List getArtifactNames({ + required Target target, + required String libraryName, + required bool remote, + AritifactType? aritifactType, +}) { + aritifactType ??= artifactTypeForTarget(target); + if (target.darwinArch != null) { + if (aritifactType == AritifactType.staticlib) { + return ['lib$libraryName.a']; + } else { + return ['lib$libraryName.dylib']; + } + } else if (target.rust.contains('-windows-')) { + if (aritifactType == AritifactType.staticlib) { + return ['$libraryName.lib']; + } else { + return [ + '$libraryName.dll', + '$libraryName.dll.lib', + if (!remote) '$libraryName.pdb' + ]; + } + } else if (target.rust.contains('-linux-')) { + if (aritifactType == AritifactType.staticlib) { + return ['lib$libraryName.a']; + } else { + return ['lib$libraryName.so']; + } + } else { + throw Exception("Unsupported target: ${target.rust}"); + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart b/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart new file mode 100644 index 0000000..6f3b2a4 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart @@ -0,0 +1,40 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; + +class BuildCMake { + final CargokitUserOptions userOptions; + + BuildCMake({required this.userOptions}); + + Future build() async { + final targetPlatform = Environment.targetPlatform; + final target = Target.forFlutterName(Environment.targetPlatform); + if (target == null) { + throw Exception("Unknown target platform: $targetPlatform"); + } + + final environment = BuildEnvironment.fromEnvironment(isAndroid: false); + final provider = + ArtifactProvider(environment: environment, userOptions: userOptions); + final artifacts = await provider.getArtifacts([target]); + + final libs = artifacts[target]!; + + for (final lib in libs) { + if (lib.type == AritifactType.dylib) { + File(lib.path) + .copySync(path.join(Environment.outputDir, lib.finalFileName)); + } + } + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart b/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart new file mode 100644 index 0000000..8d74d91 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart @@ -0,0 +1,55 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; + +final log = Logger('build_gradle'); + +class BuildGradle { + BuildGradle({required this.userOptions}); + + final CargokitUserOptions userOptions; + + Future build() async { + final targets = Environment.targetPlatforms + .map((arch) { + final target = Target.forFlutterName(arch); + if (target == null) { + throw Exception( + "Unknown darwin target or platform: $arch, ${Environment.darwinPlatformName}", + ); + } + return target; + }) + .toSet() + .toList(); + + final environment = BuildEnvironment.fromEnvironment(isAndroid: true); + final provider = ArtifactProvider( + environment: environment, + userOptions: userOptions, + ); + final artifacts = await provider.getArtifacts(targets); + + for (final target in targets) { + final libs = artifacts[target]!; + final outputDir = path.join(Environment.outputDir, target.android!); + Directory(outputDir).createSync(recursive: true); + + for (final lib in libs) { + if (lib.type == AritifactType.dylib) { + File(lib.path).copySync(path.join(outputDir, lib.finalFileName)); + } + } + } + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/build_pod.dart b/rust_builder/cargokit/build_tool/lib/src/build_pod.dart new file mode 100644 index 0000000..8a9c0db --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/build_pod.dart @@ -0,0 +1,89 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; +import 'util.dart'; + +class BuildPod { + BuildPod({required this.userOptions}); + + final CargokitUserOptions userOptions; + + Future build() async { + final targets = Environment.darwinArchs.map((arch) { + final target = Target.forDarwin( + platformName: Environment.darwinPlatformName, darwinAarch: arch); + if (target == null) { + throw Exception( + "Unknown darwin target or platform: $arch, ${Environment.darwinPlatformName}"); + } + return target; + }).toList(); + + final environment = BuildEnvironment.fromEnvironment(isAndroid: false); + final provider = + ArtifactProvider(environment: environment, userOptions: userOptions); + final artifacts = await provider.getArtifacts(targets); + + void performLipo(String targetFile, Iterable sourceFiles) { + runCommand("lipo", [ + '-create', + ...sourceFiles, + '-output', + targetFile, + ]); + } + + final outputDir = Environment.outputDir; + + Directory(outputDir).createSync(recursive: true); + + final staticLibs = artifacts.values + .expand((element) => element) + .where((element) => element.type == AritifactType.staticlib) + .toList(); + final dynamicLibs = artifacts.values + .expand((element) => element) + .where((element) => element.type == AritifactType.dylib) + .toList(); + + final libName = environment.crateInfo.packageName; + + // If there is static lib, use it and link it with pod + if (staticLibs.isNotEmpty) { + final finalTargetFile = path.join(outputDir, "lib$libName.a"); + performLipo(finalTargetFile, staticLibs.map((e) => e.path)); + } else { + // Otherwise try to replace bundle dylib with our dylib + final bundlePaths = [ + '$libName.framework/Versions/A/$libName', + '$libName.framework/$libName', + ]; + + for (final bundlePath in bundlePaths) { + final targetFile = path.join(outputDir, bundlePath); + if (File(targetFile).existsSync()) { + performLipo(targetFile, dynamicLibs.map((e) => e.path)); + + // Replace absolute id with @rpath one so that it works properly + // when moved to Frameworks. + runCommand("install_name_tool", [ + '-id', + '@rpath/$bundlePath', + targetFile, + ]); + return; + } + } + throw Exception('Unable to find bundle for dynamic library'); + } + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/build_tool.dart b/rust_builder/cargokit/build_tool/lib/src/build_tool.dart new file mode 100644 index 0000000..70dfe0e --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/build_tool.dart @@ -0,0 +1,276 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:args/command_runner.dart'; +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:github/github.dart'; +import 'package:hex/hex.dart'; +import 'package:logging/logging.dart'; + +import 'android_environment.dart'; +import 'build_cmake.dart'; +import 'build_gradle.dart'; +import 'build_pod.dart'; +import 'logging.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'target.dart'; +import 'util.dart'; +import 'verify_binaries.dart'; + +final log = Logger('build_tool'); + +abstract class BuildCommand extends Command { + Future runBuildCommand(CargokitUserOptions options); + + @override + Future run() async { + final options = CargokitUserOptions.load(); + + if (options.verboseLogging || + Platform.environment['CARGOKIT_VERBOSE'] == '1') { + enableVerboseLogging(); + } + + await runBuildCommand(options); + } +} + +class BuildPodCommand extends BuildCommand { + @override + final name = 'build-pod'; + + @override + final description = 'Build cocoa pod library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildPod(userOptions: options); + await build.build(); + } +} + +class BuildGradleCommand extends BuildCommand { + @override + final name = 'build-gradle'; + + @override + final description = 'Build android library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildGradle(userOptions: options); + await build.build(); + } +} + +class BuildCMakeCommand extends BuildCommand { + @override + final name = 'build-cmake'; + + @override + final description = 'Build CMake library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildCMake(userOptions: options); + await build.build(); + } +} + +class GenKeyCommand extends Command { + @override + final name = 'gen-key'; + + @override + final description = 'Generate key pair for signing precompiled binaries'; + + @override + void run() { + final kp = generateKey(); + final private = HEX.encode(kp.privateKey.bytes); + final public = HEX.encode(kp.publicKey.bytes); + print("Private Key: $private"); + print("Public Key: $public"); + } +} + +class PrecompileBinariesCommand extends Command { + PrecompileBinariesCommand() { + argParser + ..addOption( + 'repository', + mandatory: true, + help: 'Github repository slug in format owner/name', + ) + ..addOption( + 'manifest-dir', + mandatory: true, + help: 'Directory containing Cargo.toml', + ) + ..addMultiOption('target', + help: 'Rust target triple of artifact to build.\n' + 'Can be specified multiple times or omitted in which case\n' + 'all targets for current platform will be built.') + ..addOption( + 'android-sdk-location', + help: 'Location of Android SDK (if available)', + ) + ..addOption( + 'android-ndk-version', + help: 'Android NDK version (if available)', + ) + ..addOption( + 'android-min-sdk-version', + help: 'Android minimum rquired version (if available)', + ) + ..addOption( + 'temp-dir', + help: 'Directory to store temporary build artifacts', + ) + ..addOption( + 'glibc-version', + help: 'GLIBC version to use for linux builds', + ) + ..addFlag( + "verbose", + abbr: "v", + defaultsTo: false, + help: "Enable verbose logging", + ); + } + + @override + final name = 'precompile-binaries'; + + @override + final description = 'Prebuild and upload binaries\n' + 'Private key must be passed through PRIVATE_KEY environment variable. ' + 'Use gen_key through generate priave key.\n' + 'Github token must be passed as GITHUB_TOKEN environment variable.\n'; + + @override + Future run() async { + final verbose = argResults!['verbose'] as bool; + if (verbose) { + enableVerboseLogging(); + } + + final privateKeyString = Platform.environment['PRIVATE_KEY']; + if (privateKeyString == null) { + throw ArgumentError('Missing PRIVATE_KEY environment variable'); + } + final githubToken = Platform.environment['GITHUB_TOKEN']; + if (githubToken == null) { + throw ArgumentError('Missing GITHUB_TOKEN environment variable'); + } + final privateKey = HEX.decode(privateKeyString); + if (privateKey.length != 64) { + throw ArgumentError('Private key must be 64 bytes long'); + } + final manifestDir = argResults!['manifest-dir'] as String; + if (!Directory(manifestDir).existsSync()) { + throw ArgumentError('Manifest directory does not exist: $manifestDir'); + } + String? androidMinSdkVersionString = + argResults!['android-min-sdk-version'] as String?; + int? androidMinSdkVersion; + if (androidMinSdkVersionString != null) { + androidMinSdkVersion = int.tryParse(androidMinSdkVersionString); + if (androidMinSdkVersion == null) { + throw ArgumentError( + 'Invalid android-min-sdk-version: $androidMinSdkVersionString'); + } + } + final targetStrigns = argResults!['target'] as List; + final targets = targetStrigns.map((target) { + final res = Target.forRustTriple(target); + if (res == null) { + throw ArgumentError('Invalid target: $target'); + } + return res; + }).toList(growable: false); + final precompileBinaries = PrecompileBinaries( + privateKey: PrivateKey(privateKey), + githubToken: githubToken, + manifestDir: manifestDir, + repositorySlug: RepositorySlug.full(argResults!['repository'] as String), + targets: targets, + androidSdkLocation: argResults!['android-sdk-location'] as String?, + androidNdkVersion: argResults!['android-ndk-version'] as String?, + androidMinSdkVersion: androidMinSdkVersion, + tempDir: argResults!['temp-dir'] as String?, + glibcVersion: argResults!['glibc-version'] as String?, + ); + + await precompileBinaries.run(); + } +} + +class VerifyBinariesCommand extends Command { + VerifyBinariesCommand() { + argParser.addOption( + 'manifest-dir', + mandatory: true, + help: 'Directory containing Cargo.toml', + ); + } + + @override + final name = "verify-binaries"; + + @override + final description = 'Verifies published binaries\n' + 'Checks whether there is a binary published for each targets\n' + 'and checks the signature.'; + + @override + Future run() async { + final manifestDir = argResults!['manifest-dir'] as String; + final verifyBinaries = VerifyBinaries( + manifestDir: manifestDir, + ); + await verifyBinaries.run(); + } +} + +Future runMain(List args) async { + try { + // Init logging before options are loaded + initLogging(); + + if (Platform.environment['_CARGOKIT_NDK_LINK_TARGET'] != null) { + return AndroidEnvironment.clangLinkerWrapper(args); + } + + final runner = CommandRunner('build_tool', 'Cargokit built_tool') + ..addCommand(BuildPodCommand()) + ..addCommand(BuildGradleCommand()) + ..addCommand(BuildCMakeCommand()) + ..addCommand(GenKeyCommand()) + ..addCommand(PrecompileBinariesCommand()) + ..addCommand(VerifyBinariesCommand()); + + await runner.run(args); + } on ArgumentError catch (e) { + stderr.writeln(e.toString()); + exit(1); + } catch (e, s) { + log.severe(kDoubleSeparator); + log.severe('Cargokit BuildTool failed with error:'); + log.severe(kSeparator); + log.severe(e); + // This tells user to install Rust, there's no need to pollute the log with + // stack trace. + if (e is! RustupNotFoundException) { + log.severe(kSeparator); + log.severe(s); + log.severe(kSeparator); + log.severe('BuildTool arguments: $args'); + } + log.severe(kDoubleSeparator); + exit(1); + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/builder.dart b/rust_builder/cargokit/build_tool/lib/src/builder.dart new file mode 100644 index 0000000..c708917 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/builder.dart @@ -0,0 +1,261 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'android_environment.dart'; +import 'cargo.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'rustup.dart'; +import 'target.dart'; +import 'util.dart'; + +final _log = Logger('builder'); + +enum BuildConfiguration { + debug, + release, + profile, +} + +extension on BuildConfiguration { + bool get isDebug => this == BuildConfiguration.debug; + String get rustName => switch (this) { + BuildConfiguration.debug => 'debug', + BuildConfiguration.release => 'release', + BuildConfiguration.profile => 'release', + }; +} + +class BuildException implements Exception { + final String message; + + BuildException(this.message); + + @override + String toString() { + return 'BuildException: $message'; + } +} + +class BuildEnvironment { + final BuildConfiguration configuration; + final CargokitCrateOptions crateOptions; + final String targetTempDir; + final String manifestDir; + final CrateInfo crateInfo; + + final bool isAndroid; + final String? androidSdkPath; + final String? androidNdkVersion; + final int? androidMinSdkVersion; + final String? javaHome; + final String? ohosSdkHome; + + final String? glibcVersion; + + BuildEnvironment({ + required this.configuration, + required this.crateOptions, + required this.targetTempDir, + required this.manifestDir, + required this.crateInfo, + required this.isAndroid, + this.androidSdkPath, + this.androidNdkVersion, + this.androidMinSdkVersion, + this.javaHome, + this.glibcVersion, + this.ohosSdkHome, + }); + + static BuildConfiguration parseBuildConfiguration(String value) { + // XCode configuration adds the flavor to configuration name. + final firstSegment = value.split('-').first; + final buildConfiguration = BuildConfiguration.values.firstWhereOrNull( + (e) => e.name == firstSegment, + ); + if (buildConfiguration == null) { + _log.warning('Unknown build configuraiton $value, will assume release'); + return BuildConfiguration.release; + } + return buildConfiguration; + } + + static BuildEnvironment fromEnvironment({ + required bool isAndroid, + }) { + final buildConfiguration = + parseBuildConfiguration(Environment.configuration); + final manifestDir = Environment.manifestDir; + final crateOptions = CargokitCrateOptions.load( + manifestDir: manifestDir, + ); + final crateInfo = CrateInfo.load(manifestDir); + return BuildEnvironment( + configuration: buildConfiguration, + crateOptions: crateOptions, + targetTempDir: Environment.targetTempDir, + manifestDir: manifestDir, + crateInfo: crateInfo, + isAndroid: isAndroid, + androidSdkPath: isAndroid ? Environment.sdkPath : null, + androidNdkVersion: isAndroid ? Environment.ndkVersion : null, + androidMinSdkVersion: + isAndroid ? int.parse(Environment.minSdkVersion) : null, + javaHome: isAndroid ? Environment.javaHome : null, + ohosSdkHome: Environment.ohosSdkHome, + ); + } +} + +class RustBuilder { + final Target target; + final BuildEnvironment environment; + String? _resolvedToolchain; + + RustBuilder({ + required this.target, + required this.environment, + }); + + void prepare( + Rustup rustup, + ) { + final toolchain = _toolchain; + if (rustup.installedTargets(toolchain) == null) { + rustup.installToolchain(toolchain); + } + final resolvedToolchain = rustup.resolveToolchain(toolchain); + if (toolchain == 'nightly') { + rustup.installRustSrcForNightly(toolchain: resolvedToolchain); + } + if (!rustup.installedTargets(toolchain)!.contains(target.rust)) { + rustup.installTarget(target.rust, toolchain: resolvedToolchain); + } + if (environment.glibcVersion != null) { + rustup.installZigBuild(resolvedToolchain); + } + _resolvedToolchain = resolvedToolchain; + } + + CargoBuildOptions? get _buildOptions => + environment.crateOptions.cargo[environment.configuration]; + + String get _toolchain => _buildOptions?.toolchain.name ?? 'stable'; + String get _effectiveToolchain => _resolvedToolchain ?? _toolchain; + + /// Returns the path of directory containing build artifacts. + Future build() async { + final extraArgs = _buildOptions?.flags ?? []; + final manifestPath = path.join(environment.manifestDir, 'Cargo.toml'); + runCommand( + 'rustup', + [ + 'run', + _effectiveToolchain, + 'cargo', + (target.android == null && environment.glibcVersion != null) + ? 'zigbuild' + : 'build', + ...extraArgs, + '--manifest-path', + manifestPath, + '-p', + environment.crateInfo.packageName, + if (!environment.configuration.isDebug) '--release', + '--target', + target.rust + + ((target.android == null && environment.glibcVersion != null) + ? '.${environment.glibcVersion!}' + : ""), + '--target-dir', + environment.targetTempDir, + ], + environment: await _buildEnvironment(), + ); + return path.join( + environment.targetTempDir, + target.rust, + environment.configuration.rustName, + ); + } + + Future> _buildEnvironment() async { + if (target.ohos != null) { + return _buildOhosEnv(); + } + if (target.android != null) { + return _buildAndroidEnv(); + } + return {}; + } + + Future> _buildAndroidEnv() { + final sdkPath = environment.androidSdkPath; + final ndkVersion = environment.androidNdkVersion; + final minSdkVersion = environment.androidMinSdkVersion; + if (sdkPath == null) { + throw BuildException('androidSdkPath is not set'); + } + if (ndkVersion == null) { + throw BuildException('androidNdkVersion is not set'); + } + if (minSdkVersion == null) { + throw BuildException('androidMinSdkVersion is not set'); + } + final env = AndroidEnvironment( + sdkPath: sdkPath, + ndkVersion: ndkVersion, + minSdkVersion: minSdkVersion, + targetTempDir: environment.targetTempDir, + target: target, + ); + if (!env.ndkIsInstalled() && environment.javaHome != null) { + env.installNdk(javaHome: environment.javaHome!); + } + return env.buildEnvironment(); + } + + Map _buildOhosEnv() { + final sdkPath = environment.ohosSdkHome; + if (sdkPath == null) { + throw BuildException('OHOS SDK native path is not set'); + } + final exe = Platform.isWindows ? '.exe' : ''; + final clangPath = path.join(sdkPath, 'llvm', 'bin', 'clang$exe'); + final sysroot = path.join(sdkPath, 'sysroot'); + String clangTarget; + switch (target.ohos) { + case 'arm64-v8a': + clangTarget = 'aarch64-linux-ohos'; + break; + case 'armeabi-v7a': + clangTarget = 'arm-linux-ohos'; + break; + case 'x86_64': + clangTarget = 'x86_64-linux-ohos'; + break; + default: + clangTarget = 'aarch64-linux-ohos'; + } + final targetEnvName = target.rust.toUpperCase().replaceAll('-', '_'); + final linkerEnvVar = 'CARGO_TARGET_${targetEnvName}_LINKER'; + final rustFlagsEnvVar = 'CARGO_TARGET_${targetEnvName}_RUSTFLAGS'; + final rustFlags = '-C link-arg=--target=$clangTarget ' + '-C link-arg=-fuse-ld=lld ' + '-C link-arg=--sysroot=$sysroot ' + '-C link-arg=-D__MUSL__'; + return { + rustFlagsEnvVar: rustFlags, + linkerEnvVar: clangPath, + 'CC_${target.rust}': clangPath, + 'AR_${target.rust}': path.join(sdkPath, 'llvm', 'bin', 'llvm-ar$exe'), + }; + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/cargo.dart b/rust_builder/cargokit/build_tool/lib/src/cargo.dart new file mode 100644 index 0000000..0d8958f --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/cargo.dart @@ -0,0 +1,48 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:path/path.dart' as path; +import 'package:toml/toml.dart'; + +class ManifestException { + ManifestException(this.message, {required this.fileName}); + + final String? fileName; + final String message; + + @override + String toString() { + if (fileName != null) { + return 'Failed to parse package manifest at $fileName: $message'; + } else { + return 'Failed to parse package manifest: $message'; + } + } +} + +class CrateInfo { + CrateInfo({required this.packageName}); + + final String packageName; + + static CrateInfo parseManifest(String manifest, {final String? fileName}) { + final toml = TomlDocument.parse(manifest); + final package = toml.toMap()['package']; + if (package == null) { + throw ManifestException('Missing package section', fileName: fileName); + } + final name = package['name']; + if (name == null) { + throw ManifestException('Missing package name', fileName: fileName); + } + return CrateInfo(packageName: name); + } + + static CrateInfo load(String manifestDir) { + final manifestFile = File(path.join(manifestDir, 'Cargo.toml')); + final manifest = manifestFile.readAsStringSync(); + return parseManifest(manifest, fileName: manifestFile.path); + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart b/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart new file mode 100644 index 0000000..0c4d88d --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart @@ -0,0 +1,124 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:collection/collection.dart'; +import 'package:convert/convert.dart'; +import 'package:crypto/crypto.dart'; +import 'package:path/path.dart' as path; + +class CrateHash { + /// Computes a hash uniquely identifying crate content. This takes into account + /// content all all .rs files inside the src directory, as well as Cargo.toml, + /// Cargo.lock, build.rs and cargokit.yaml. + /// + /// If [tempStorage] is provided, computed hash is stored in a file in that directory + /// and reused on subsequent calls if the crate content hasn't changed. + static String compute(String manifestDir, {String? tempStorage}) { + return CrateHash._( + manifestDir: manifestDir, + tempStorage: tempStorage, + )._compute(); + } + + CrateHash._({ + required this.manifestDir, + required this.tempStorage, + }); + + String _compute() { + final files = getFiles(); + final tempStorage = this.tempStorage; + if (tempStorage != null) { + final quickHash = _computeQuickHash(files); + final quickHashFolder = Directory(path.join(tempStorage, 'crate_hash')); + quickHashFolder.createSync(recursive: true); + final quickHashFile = File(path.join(quickHashFolder.path, quickHash)); + if (quickHashFile.existsSync()) { + return quickHashFile.readAsStringSync(); + } + final hash = _computeHash(files); + quickHashFile.writeAsStringSync(hash); + return hash; + } else { + return _computeHash(files); + } + } + + /// Computes a quick hash based on files stat (without reading contents). This + /// is used to cache the real hash, which is slower to compute since it involves + /// reading every single file. + String _computeQuickHash(List files) { + final output = AccumulatorSink(); + final input = sha256.startChunkedConversion(output); + + final data = ByteData(8); + for (final file in files) { + input.add(utf8.encode(file.path)); + final stat = file.statSync(); + data.setUint64(0, stat.size); + input.add(data.buffer.asUint8List()); + data.setUint64(0, stat.modified.millisecondsSinceEpoch); + input.add(data.buffer.asUint8List()); + } + + input.close(); + return base64Url.encode(output.events.single.bytes); + } + + String _computeHash(List files) { + final output = AccumulatorSink(); + final input = sha256.startChunkedConversion(output); + + void addTextFile(File file) { + // text Files are hashed by lines in case we're dealing with github checkout + // that auto-converts line endings. + final splitter = LineSplitter(); + if (file.existsSync()) { + final data = file.readAsStringSync(); + final lines = splitter.convert(data); + for (final line in lines) { + input.add(utf8.encode(line)); + } + } + } + + for (final file in files) { + addTextFile(file); + } + + input.close(); + final res = output.events.single; + + // Truncate to 128bits. + final hash = res.bytes.sublist(0, 16); + return hex.encode(hash); + } + + List getFiles() { + final src = Directory(path.join(manifestDir, 'src')); + final files = src + .listSync(recursive: true, followLinks: false) + .whereType() + .toList(); + files.sortBy((element) => element.path); + void addFile(String relative) { + final file = File(path.join(manifestDir, relative)); + if (file.existsSync()) { + files.add(file); + } + } + + addFile('Cargo.toml'); + addFile('Cargo.lock'); + addFile('build.rs'); + addFile('cargokit.yaml'); + return files; + } + + final String manifestDir; + final String? tempStorage; +} diff --git a/rust_builder/cargokit/build_tool/lib/src/environment.dart b/rust_builder/cargokit/build_tool/lib/src/environment.dart new file mode 100644 index 0000000..d235616 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/environment.dart @@ -0,0 +1,74 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +extension on String { + String resolveSymlink() => File(this).resolveSymbolicLinksSync(); +} + +class Environment { + /// Current build configuration (debug or release). + static String get configuration => + _getEnv("CARGOKIT_CONFIGURATION").toLowerCase(); + + static bool get isDebug => configuration == 'debug'; + static bool get isRelease => configuration == 'release'; + + /// Temporary directory where Rust build artifacts are placed. + static String get targetTempDir => _getEnv("CARGOKIT_TARGET_TEMP_DIR"); + + /// Final output directory where the build artifacts are placed. + static String get outputDir => _getEnvPath('CARGOKIT_OUTPUT_DIR'); + + /// Path to the crate manifest (containing Cargo.toml). + static String get manifestDir => _getEnvPath('CARGOKIT_MANIFEST_DIR'); + + /// Directory inside root project. Not necessarily root folder. Symlinks are + /// not resolved on purpose. + static String get rootProjectDir => _getEnv('CARGOKIT_ROOT_PROJECT_DIR'); + + // Pod + + /// Platform name (macosx, iphoneos, iphonesimulator). + static String get darwinPlatformName => + _getEnv("CARGOKIT_DARWIN_PLATFORM_NAME"); + + /// List of architectures to build for (arm64, armv7, x86_64). + static List get darwinArchs => + _getEnv("CARGOKIT_DARWIN_ARCHS").split(' '); + + // Gradle + static String get minSdkVersion => _getEnv("CARGOKIT_MIN_SDK_VERSION"); + static String get ndkVersion => _getEnv("CARGOKIT_NDK_VERSION"); + static String get sdkPath => _getEnvPath("CARGOKIT_SDK_DIR"); + static String get javaHome => _getEnvPath("CARGOKIT_JAVA_HOME"); + static List get targetPlatforms => + _getEnv("CARGOKIT_TARGET_PLATFORMS").split(','); + + static String? get ohosSdkHome => _getEnvOptional("CARGOKIT_OHOS_SDK_HOME"); + + // CMAKE + static String get targetPlatform => _getEnv("CARGOKIT_TARGET_PLATFORM"); + + static String _getEnv(String key) { + final res = Platform.environment[key]; + if (res == null) { + throw Exception("Missing environment variable $key"); + } + return res; + } + + static String _getEnvPath(String key) { + final res = _getEnv(key); + if (Directory(res).existsSync()) { + return res.resolveSymlink(); + } else { + return res; + } + } + + static String? _getEnvOptional(String key) { + return Platform.environment[key]; + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/logging.dart b/rust_builder/cargokit/build_tool/lib/src/logging.dart new file mode 100644 index 0000000..5edd4fd --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/logging.dart @@ -0,0 +1,52 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:logging/logging.dart'; + +const String kSeparator = "--"; +const String kDoubleSeparator = "=="; + +bool _lastMessageWasSeparator = false; + +void _log(LogRecord rec) { + final prefix = '${rec.level.name}: '; + final out = rec.level == Level.SEVERE ? stderr : stdout; + if (rec.message == kSeparator) { + if (!_lastMessageWasSeparator) { + out.write(prefix); + out.writeln('-' * 80); + _lastMessageWasSeparator = true; + } + return; + } else if (rec.message == kDoubleSeparator) { + out.write(prefix); + out.writeln('=' * 80); + _lastMessageWasSeparator = true; + return; + } + out.write(prefix); + out.writeln(rec.message); + _lastMessageWasSeparator = false; +} + +void initLogging() { + Logger.root.level = Level.INFO; + Logger.root.onRecord.listen((LogRecord rec) { + final lines = rec.message.split('\n'); + for (final line in lines) { + if (line.isNotEmpty || lines.length == 1 || line != lines.last) { + _log(LogRecord( + rec.level, + line, + rec.loggerName, + )); + } + } + }); +} + +void enableVerboseLogging() { + Logger.root.level = Level.ALL; +} diff --git a/rust_builder/cargokit/build_tool/lib/src/options.dart b/rust_builder/cargokit/build_tool/lib/src/options.dart new file mode 100644 index 0000000..22aef1d --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/options.dart @@ -0,0 +1,309 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:hex/hex.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; +import 'package:source_span/source_span.dart'; +import 'package:yaml/yaml.dart'; + +import 'builder.dart'; +import 'environment.dart'; +import 'rustup.dart'; + +final _log = Logger('options'); + +/// A class for exceptions that have source span information attached. +class SourceSpanException implements Exception { + // This is a getter so that subclasses can override it. + /// A message describing the exception. + String get message => _message; + final String _message; + + // This is a getter so that subclasses can override it. + /// The span associated with this exception. + /// + /// This may be `null` if the source location can't be determined. + SourceSpan? get span => _span; + final SourceSpan? _span; + + SourceSpanException(this._message, this._span); + + /// Returns a string representation of `this`. + /// + /// [color] may either be a [String], a [bool], or `null`. If it's a string, + /// it indicates an ANSI terminal color escape that should be used to + /// highlight the span's text. If it's `true`, it indicates that the text + /// should be highlighted using the default color. If it's `false` or `null`, + /// it indicates that the text shouldn't be highlighted. + @override + String toString({Object? color}) { + if (span == null) return message; + return 'Error on ${span!.message(message, color: color)}'; + } +} + +enum Toolchain { + stable, + beta, + nightly, +} + +class CargoBuildOptions { + final Toolchain toolchain; + final List flags; + + CargoBuildOptions({ + required this.toolchain, + required this.flags, + }); + + static Toolchain _toolchainFromNode(YamlNode node) { + if (node case YamlScalar(value: String name)) { + final toolchain = + Toolchain.values.firstWhereOrNull((element) => element.name == name); + if (toolchain != null) { + return toolchain; + } + } + throw SourceSpanException( + 'Unknown toolchain. Must be one of ${Toolchain.values.map((e) => e.name)}.', + node.span); + } + + static CargoBuildOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargo options must be a map', node.span); + } + Toolchain toolchain = Toolchain.stable; + List flags = []; + for (final MapEntry(:key, :value) in node.nodes.entries) { + if (key case YamlScalar(value: 'toolchain')) { + toolchain = _toolchainFromNode(value); + } else if (key case YamlScalar(value: 'extra_flags')) { + if (value case YamlList(nodes: List list)) { + if (list.every((element) { + if (element case YamlScalar(value: String _)) { + return true; + } + return false; + })) { + flags = list.map((e) => e.value as String).toList(); + continue; + } + } + throw SourceSpanException( + 'Extra flags must be a list of strings', value.span); + } else { + throw SourceSpanException( + 'Unknown cargo option type. Must be "toolchain" or "extra_flags".', + key.span); + } + } + return CargoBuildOptions(toolchain: toolchain, flags: flags); + } +} + +extension on YamlMap { + /// Map that extracts keys so that we can do map case check on them. + Map get valueMap => + nodes.map((key, value) => MapEntry(key.value, value)); +} + +class PrecompiledBinaries { + final String uriPrefix; + final PublicKey publicKey; + + PrecompiledBinaries({ + required this.uriPrefix, + required this.publicKey, + }); + + static PublicKey _publicKeyFromHex(String key, SourceSpan? span) { + final bytes = HEX.decode(key); + if (bytes.length != 32) { + throw SourceSpanException( + 'Invalid public key. Must be 32 bytes long.', span); + } + return PublicKey(bytes); + } + + static PrecompiledBinaries parse(YamlNode node) { + if (node case YamlMap(valueMap: Map map)) { + if (map + case { + 'url_prefix': YamlNode urlPrefixNode, + 'public_key': YamlNode publicKeyNode, + }) { + final urlPrefix = switch (urlPrefixNode) { + YamlScalar(value: String urlPrefix) => urlPrefix, + _ => throw SourceSpanException( + 'Invalid URL prefix value.', urlPrefixNode.span), + }; + final publicKey = switch (publicKeyNode) { + YamlScalar(value: String publicKey) => + _publicKeyFromHex(publicKey, publicKeyNode.span), + _ => throw SourceSpanException( + 'Invalid public key value.', publicKeyNode.span), + }; + return PrecompiledBinaries( + uriPrefix: urlPrefix, + publicKey: publicKey, + ); + } + } + throw SourceSpanException( + 'Invalid precompiled binaries value. ' + 'Expected Map with "url_prefix" and "public_key".', + node.span); + } +} + +/// Cargokit options specified for Rust crate. +class CargokitCrateOptions { + CargokitCrateOptions({ + this.cargo = const {}, + this.precompiledBinaries, + }); + + final Map cargo; + final PrecompiledBinaries? precompiledBinaries; + + static CargokitCrateOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargokit options must be a map', node.span); + } + final options = {}; + PrecompiledBinaries? precompiledBinaries; + + for (final entry in node.nodes.entries) { + if (entry + case MapEntry( + key: YamlScalar(value: 'cargo'), + value: YamlNode node, + )) { + if (node is! YamlMap) { + throw SourceSpanException('Cargo options must be a map', node.span); + } + for (final MapEntry(:YamlNode key, :value) in node.nodes.entries) { + if (key case YamlScalar(value: String name)) { + final configuration = BuildConfiguration.values + .firstWhereOrNull((element) => element.name == name); + if (configuration != null) { + options[configuration] = CargoBuildOptions.parse(value); + continue; + } + } + throw SourceSpanException( + 'Unknown build configuration. Must be one of ${BuildConfiguration.values.map((e) => e.name)}.', + key.span); + } + } else if (entry.key case YamlScalar(value: 'precompiled_binaries')) { + precompiledBinaries = PrecompiledBinaries.parse(entry.value); + } else { + throw SourceSpanException( + 'Unknown cargokit option type. Must be "cargo" or "precompiled_binaries".', + entry.key.span); + } + } + return CargokitCrateOptions( + cargo: options, + precompiledBinaries: precompiledBinaries, + ); + } + + static CargokitCrateOptions load({ + required String manifestDir, + }) { + final uri = Uri.file(path.join(manifestDir, "cargokit.yaml")); + final file = File.fromUri(uri); + if (file.existsSync()) { + final contents = loadYamlNode(file.readAsStringSync(), sourceUrl: uri); + return parse(contents); + } else { + return CargokitCrateOptions(); + } + } +} + +class CargokitUserOptions { + // When Rustup is installed always build locally unless user opts into + // using precompiled binaries. + static bool defaultUsePrecompiledBinaries() { + return Rustup.executablePath() == null; + } + + CargokitUserOptions({ + required this.usePrecompiledBinaries, + required this.verboseLogging, + }); + + CargokitUserOptions._() + : usePrecompiledBinaries = defaultUsePrecompiledBinaries(), + verboseLogging = false; + + static CargokitUserOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargokit options must be a map', node.span); + } + bool usePrecompiledBinaries = defaultUsePrecompiledBinaries(); + bool verboseLogging = false; + + for (final entry in node.nodes.entries) { + if (entry.key case YamlScalar(value: 'use_precompiled_binaries')) { + if (entry.value case YamlScalar(value: bool value)) { + usePrecompiledBinaries = value; + continue; + } + throw SourceSpanException( + 'Invalid value for "use_precompiled_binaries". Must be a boolean.', + entry.value.span); + } else if (entry.key case YamlScalar(value: 'verbose_logging')) { + if (entry.value case YamlScalar(value: bool value)) { + verboseLogging = value; + continue; + } + throw SourceSpanException( + 'Invalid value for "verbose_logging". Must be a boolean.', + entry.value.span); + } else { + throw SourceSpanException( + 'Unknown cargokit option type. Must be "use_precompiled_binaries" or "verbose_logging".', + entry.key.span); + } + } + return CargokitUserOptions( + usePrecompiledBinaries: usePrecompiledBinaries, + verboseLogging: verboseLogging, + ); + } + + static CargokitUserOptions load() { + String fileName = "cargokit_options.yaml"; + var userProjectDir = Directory(Environment.rootProjectDir); + + while (userProjectDir.parent.path != userProjectDir.path) { + final configFile = File(path.join(userProjectDir.path, fileName)); + if (configFile.existsSync()) { + final contents = loadYamlNode( + configFile.readAsStringSync(), + sourceUrl: configFile.uri, + ); + final res = parse(contents); + if (res.verboseLogging) { + _log.info('Found user options file at ${configFile.path}'); + } + return res; + } + userProjectDir = userProjectDir.parent; + } + return CargokitUserOptions._(); + } + + final bool usePrecompiledBinaries; + final bool verboseLogging; +} diff --git a/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart b/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart new file mode 100644 index 0000000..019859c --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart @@ -0,0 +1,205 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:github/github.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'cargo.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'rustup.dart'; +import 'target.dart'; + +final _log = Logger('precompile_binaries'); + +class PrecompileBinaries { + PrecompileBinaries({ + required this.privateKey, + required this.githubToken, + required this.repositorySlug, + required this.manifestDir, + required this.targets, + this.androidSdkLocation, + this.androidNdkVersion, + this.androidMinSdkVersion, + this.tempDir, + this.glibcVersion, + }); + + final PrivateKey privateKey; + final String githubToken; + final RepositorySlug repositorySlug; + final String manifestDir; + final List targets; + final String? androidSdkLocation; + final String? androidNdkVersion; + final int? androidMinSdkVersion; + final String? tempDir; + final String? glibcVersion; + + static String fileName(Target target, String name) { + return '${target.rust}_$name'; + } + + static String signatureFileName(Target target, String name) { + return '${target.rust}_$name.sig'; + } + + Future run() async { + final crateInfo = CrateInfo.load(manifestDir); + + final targets = List.of(this.targets); + if (targets.isEmpty) { + targets.addAll([ + ...Target.buildableTargets(), + if (androidSdkLocation != null) ...Target.androidTargets(), + ]); + } + + _log.info('Precompiling binaries for $targets'); + + final hash = CrateHash.compute(manifestDir); + _log.info('Computed crate hash: $hash'); + + final String tagName = 'precompiled_$hash'; + + final github = GitHub(auth: Authentication.withToken(githubToken)); + final repo = github.repositories; + final release = await _getOrCreateRelease( + repo: repo, + tagName: tagName, + packageName: crateInfo.packageName, + hash: hash, + ); + + final tempDir = this.tempDir != null + ? Directory(this.tempDir!) + : Directory.systemTemp.createTempSync('precompiled_'); + + tempDir.createSync(recursive: true); + + final crateOptions = CargokitCrateOptions.load( + manifestDir: manifestDir, + ); + + final buildEnvironment = BuildEnvironment( + configuration: BuildConfiguration.release, + crateOptions: crateOptions, + targetTempDir: tempDir.path, + manifestDir: manifestDir, + crateInfo: crateInfo, + isAndroid: androidSdkLocation != null, + androidSdkPath: androidSdkLocation, + androidNdkVersion: androidNdkVersion, + androidMinSdkVersion: androidMinSdkVersion, + glibcVersion: glibcVersion, + ); + + final rustup = Rustup(); + + for (final target in targets) { + final artifactNames = getArtifactNames( + target: target, + libraryName: crateInfo.packageName, + remote: true, + ); + + if (artifactNames.every((name) { + final fileName = PrecompileBinaries.fileName(target, name); + return (release.assets ?? []).any((e) => e.name == fileName); + })) { + _log.info("All artifacts for $target already exist - skipping"); + continue; + } + + _log.info('Building for $target'); + + final builder = + RustBuilder(target: target, environment: buildEnvironment); + builder.prepare(rustup); + final res = await builder.build(); + + final assets = []; + for (final name in artifactNames) { + final file = File(path.join(res, name)); + if (!file.existsSync()) { + throw Exception('Missing artifact: ${file.path}'); + } + + final data = file.readAsBytesSync(); + final create = CreateReleaseAsset( + name: PrecompileBinaries.fileName(target, name), + contentType: "application/octet-stream", + assetData: data, + ); + final signature = sign(privateKey, data); + final signatureCreate = CreateReleaseAsset( + name: signatureFileName(target, name), + contentType: "application/octet-stream", + assetData: signature, + ); + bool verified = verify(public(privateKey), data, signature); + if (!verified) { + throw Exception('Signature verification failed'); + } + assets.add(create); + assets.add(signatureCreate); + } + _log.info('Uploading assets: ${assets.map((e) => e.name)}'); + for (final asset in assets) { + // This seems to be failing on CI so do it one by one + int retryCount = 0; + while (true) { + try { + await repo.uploadReleaseAssets(release, [asset]); + break; + } on Exception catch (e) { + if (retryCount == 10) { + rethrow; + } + ++retryCount; + _log.shout( + 'Upload failed (attempt $retryCount, will retry): ${e.toString()}'); + await Future.delayed(Duration(seconds: 2)); + } + } + } + } + + _log.info('Cleaning up'); + tempDir.deleteSync(recursive: true); + } + + Future _getOrCreateRelease({ + required RepositoriesService repo, + required String tagName, + required String packageName, + required String hash, + }) async { + Release release; + try { + _log.info('Fetching release $tagName'); + release = await repo.getReleaseByTagName(repositorySlug, tagName); + } on ReleaseNotFound { + _log.info('Release not found - creating release $tagName'); + release = await repo.createRelease( + repositorySlug, + CreateRelease.from( + tagName: tagName, + name: 'Precompiled binaries ${hash.substring(0, 8)}', + targetCommitish: null, + isDraft: false, + isPrerelease: false, + body: 'Precompiled binaries for crate $packageName, ' + 'crate hash $hash.', + )); + } + return release; + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/rustup.dart b/rust_builder/cargokit/build_tool/lib/src/rustup.dart new file mode 100644 index 0000000..cfb88f0 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/rustup.dart @@ -0,0 +1,171 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:path/path.dart' as path; + +import 'util.dart'; + +class _Toolchain { + _Toolchain( + this.name, + this.targets, + ); + + final String name; + final List targets; +} + +class Rustup { + List? installedTargets(String toolchain) { + final targets = _installedTargets(toolchain); + return targets != null ? List.unmodifiable(targets) : null; + } + + String resolveToolchain(String toolchain) => + _installedToolchains + .firstWhereOrNull( + (e) => _matchesRequestedToolchain( + installedName: e.name, + requestedToolchain: toolchain, + ), + ) + ?.name ?? + toolchain; + + void installToolchain(String toolchain) { + log.info("Installing Rust toolchain: $toolchain"); + runCommand("rustup", ['toolchain', 'install', toolchain]); + _installedToolchains + .add(_Toolchain(toolchain, _getInstalledTargets(toolchain))); + } + + void installTarget( + String target, { + required String toolchain, + }) { + log.info("Installing Rust target: $target"); + runCommand("rustup", ['target', 'add', '--toolchain', toolchain, target]); + _installedTargets(toolchain)?.add(target); + } + + bool _didInstallZigBuild = false; + + void installZigBuild(String toolchain) { + if (_didInstallZigBuild) { + return; + } + + log.info("Installing Zig build"); + runCommand("rustup", [ + 'run', + toolchain, + 'cargo', + 'install', + '--locked', + 'cargo-zigbuild', + ]); + _didInstallZigBuild = true; + } + + final List<_Toolchain> _installedToolchains; + + Rustup() : _installedToolchains = _getInstalledToolchains(); + + bool _matchesRequestedToolchain({ + required String installedName, + required String requestedToolchain, + }) => + installedName == requestedToolchain || + installedName.startsWith('$requestedToolchain-'); + + List? _installedTargets(String toolchain) => _installedToolchains + .firstWhereOrNull( + (e) => _matchesRequestedToolchain( + installedName: e.name, + requestedToolchain: toolchain, + ), + ) + ?.targets; + + static List<_Toolchain> _getInstalledToolchains() { + String extractToolchainName(String line) { + // ignore (default) after toolchain name + final parts = line.split(' '); + return parts[0]; + } + + final res = runCommand("rustup", ['toolchain', 'list']); + + // To list all non-custom toolchains, we need to filter out lines that + // don't start with "stable", "beta", or "nightly". + final nonCustom = RegExp(r'^(stable|beta|nightly)'); + final lines = res.stdout + .toString() + .split('\n') + .where((e) => e.isNotEmpty && nonCustom.hasMatch(e)) + .map(extractToolchainName) + .toList(growable: true); + + return lines + .map( + (name) => _Toolchain( + name, + _getInstalledTargets(name), + ), + ) + .toList(growable: true); + } + + static List _getInstalledTargets(String toolchain) { + final res = runCommand("rustup", [ + 'target', + 'list', + '--toolchain', + toolchain, + '--installed', + ]); + final lines = res.stdout + .toString() + .split('\n') + .where((e) => e.isNotEmpty) + .toList(growable: true); + return lines; + } + + bool _didInstallRustSrcForNightly = false; + + void installRustSrcForNightly({String toolchain = 'nightly'}) { + if (_didInstallRustSrcForNightly) { + return; + } + // Useful for -Z build-std + runCommand( + "rustup", + ['component', 'add', 'rust-src', '--toolchain', toolchain], + ); + _didInstallRustSrcForNightly = true; + } + + static String? executablePath() { + final envPath = Platform.environment['PATH']; + final envPathSeparator = Platform.isWindows ? ';' : ':'; + final home = Platform.isWindows + ? Platform.environment['USERPROFILE'] + : Platform.environment['HOME']; + final paths = [ + if (home != null) path.join(home, '.cargo', 'bin'), + if (envPath != null) ...envPath.split(envPathSeparator), + ]; + for (final p in paths) { + final rustup = Platform.isWindows ? 'rustup.exe' : 'rustup'; + final rustupPath = path.join(p, rustup); + if (File(rustupPath).existsSync()) { + return rustupPath; + } + } + return null; + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/target.dart b/rust_builder/cargokit/build_tool/lib/src/target.dart new file mode 100644 index 0000000..7e9bb25 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/target.dart @@ -0,0 +1,178 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:collection/collection.dart'; + +import 'util.dart'; + +class Target { + Target({ + required this.rust, + this.flutter, + this.android, + this.androidMinSdkVersion, + this.darwinPlatform, + this.darwinArch, + this.ohos, + }); + + static final all = [ + Target( + rust: 'armv7-linux-androideabi', + flutter: 'android-arm', + android: 'armeabi-v7a', + androidMinSdkVersion: 16, + ), + Target( + rust: 'aarch64-linux-android', + flutter: 'android-arm64', + android: 'arm64-v8a', + androidMinSdkVersion: 21, + ), + Target( + rust: 'i686-linux-android', + flutter: 'android-x86', + android: 'x86', + androidMinSdkVersion: 16, + ), + Target( + rust: 'x86_64-linux-android', + flutter: 'android-x64', + android: 'x86_64', + androidMinSdkVersion: 21, + ), + Target( + rust: 'x86_64-pc-windows-msvc', + flutter: 'windows-x64', + ), + Target( + rust: 'aarch64-pc-windows-msvc', + flutter: 'windows-arm64', + ), + Target( + rust: 'x86_64-unknown-linux-gnu', + flutter: 'linux-x64', + ), + Target( + rust: 'aarch64-unknown-linux-gnu', + flutter: 'linux-arm64', + ), + Target(rust: 'riscv64gc-unknown-linux-gnu', flutter: 'linux-riscv64'), + Target( + rust: 'x86_64-apple-darwin', + darwinPlatform: 'macosx', + darwinArch: 'x86_64', + ), + Target( + rust: 'aarch64-apple-darwin', + darwinPlatform: 'macosx', + darwinArch: 'arm64', + ), + Target( + rust: 'aarch64-apple-ios', + darwinPlatform: 'iphoneos', + darwinArch: 'arm64', + ), + Target( + rust: 'aarch64-apple-ios-sim', + darwinPlatform: 'iphonesimulator', + darwinArch: 'arm64', + ), + Target( + rust: 'x86_64-apple-ios', + darwinPlatform: 'iphonesimulator', + darwinArch: 'x86_64', + ), + Target( + rust: 'aarch64-unknown-linux-ohos', + flutter: 'ohos-arm64', + ohos: 'arm64-v8a', + ), + Target( + rust: 'armv7-unknown-linux-ohos', + flutter: 'ohos-arm', + ohos: 'armeabi-v7a', + ), + Target( + rust: 'x86_64-unknown-linux-ohos', + flutter: 'ohos-x64', + ohos: 'x86_64', + ), + ]; + + static Target? forFlutterName(String flutterName) { + return all.firstWhereOrNull((element) => element.flutter == flutterName); + } + + static Target? forDarwin({ + required String platformName, + required String darwinAarch, + }) { + return all.firstWhereOrNull((element) => // + element.darwinPlatform == platformName && + element.darwinArch == darwinAarch); + } + + static Target? forRustTriple(String triple) { + return all.firstWhereOrNull((element) => element.rust == triple); + } + + static List androidTargets() { + return all + .where((element) => element.android != null) + .toList(growable: false); + } + + static List ohosTargets() { + return all.where((element) => element.ohos != null).toList(growable: false); + } + + /// Returns buildable targets on current host platform ignoring Android targets. + static List buildableTargets() { + if (Platform.operatingSystem == 'ohos') { + final arch = (runCommand('arch', []).stdout as String).trim(); + if (arch.trim() == 'aarch64') { + return [Target.forRustTriple('aarch64-unknown-linux-ohos')!]; + } + if (arch == 'armv7') { + return [Target.forRustTriple('armv7-unknown-linux-ohos')!]; + } + return [Target.forRustTriple('x86_64-unknown-linux-ohos')!]; + } + if (Platform.isLinux) { + // Right now we don't support cross-compiling on Linux. So we just return + // the host target. + final arch = (runCommand('arch', []).stdout as String).trim(); + if (arch == 'aarch64') { + return [Target.forRustTriple('aarch64-unknown-linux-gnu')!]; + } else if (arch == 'riscv64') { + return [Target.forRustTriple('riscv64gc-unknown-linux-gnu')!]; + } else { + return [Target.forRustTriple('x86_64-unknown-linux-gnu')!]; + } + } + return all.where((target) { + if (Platform.isWindows) { + return target.rust.contains('-windows-'); + } else if (Platform.isMacOS) { + return target.darwinPlatform != null; + } + return false; + }).toList(growable: false); + } + + @override + String toString() { + return rust; + } + + final String? flutter; + final String rust; + final String? android; + final int? androidMinSdkVersion; + final String? darwinPlatform; + final String? darwinArch; + final String? ohos; +} diff --git a/rust_builder/cargokit/build_tool/lib/src/util.dart b/rust_builder/cargokit/build_tool/lib/src/util.dart new file mode 100644 index 0000000..8bb6a87 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/util.dart @@ -0,0 +1,172 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:convert'; +import 'dart:io'; + +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'logging.dart'; +import 'rustup.dart'; + +final log = Logger("process"); + +class CommandFailedException implements Exception { + final String executable; + final List arguments; + final ProcessResult result; + + CommandFailedException({ + required this.executable, + required this.arguments, + required this.result, + }); + + @override + String toString() { + final stdout = result.stdout.toString().trim(); + final stderr = result.stderr.toString().trim(); + return [ + "External Command: $executable ${arguments.map((e) => '"$e"').join(' ')}", + "Returned Exit Code: ${result.exitCode}", + kSeparator, + "STDOUT:", + if (stdout.isNotEmpty) stdout, + kSeparator, + "STDERR:", + if (stderr.isNotEmpty) stderr, + ].join('\n'); + } +} + +class TestRunCommandArgs { + final String executable; + final List arguments; + final String? workingDirectory; + final Map? environment; + final bool includeParentEnvironment; + final bool runInShell; + final Encoding? stdoutEncoding; + final Encoding? stderrEncoding; + + TestRunCommandArgs({ + required this.executable, + required this.arguments, + this.workingDirectory, + this.environment, + this.includeParentEnvironment = true, + this.runInShell = false, + this.stdoutEncoding, + this.stderrEncoding, + }); +} + +class TestRunCommandResult { + TestRunCommandResult({ + this.pid = 1, + this.exitCode = 0, + this.stdout = '', + this.stderr = '', + }); + + final int pid; + final int exitCode; + final String stdout; + final String stderr; +} + +TestRunCommandResult Function(TestRunCommandArgs args)? testRunCommandOverride; + +ProcessResult runCommand( + String executable, + List arguments, { + String? workingDirectory, + Map? environment, + bool includeParentEnvironment = true, + bool runInShell = false, + Encoding? stdoutEncoding = systemEncoding, + Encoding? stderrEncoding = systemEncoding, +}) { + if (testRunCommandOverride != null) { + final result = testRunCommandOverride!(TestRunCommandArgs( + executable: executable, + arguments: arguments, + workingDirectory: workingDirectory, + environment: environment, + includeParentEnvironment: includeParentEnvironment, + runInShell: runInShell, + stdoutEncoding: stdoutEncoding, + stderrEncoding: stderrEncoding, + )); + return ProcessResult( + result.pid, + result.exitCode, + result.stdout, + result.stderr, + ); + } + log.finer('Running command $executable ${arguments.join(' ')}'); + final res = Process.runSync( + _resolveExecutable(executable), + arguments, + workingDirectory: workingDirectory, + environment: environment, + includeParentEnvironment: includeParentEnvironment, + runInShell: runInShell, + stderrEncoding: stderrEncoding, + stdoutEncoding: stdoutEncoding, + ); + if (res.exitCode != 0) { + throw CommandFailedException( + executable: executable, + arguments: arguments, + result: res, + ); + } else { + return res; + } +} + +class RustupNotFoundException implements Exception { + @override + String toString() { + return [ + ' ', + 'rustup not found in PATH.', + ' ', + 'Maybe you need to install Rust? It only takes a minute:', + ' ', + if (Platform.isWindows) 'https://www.rust-lang.org/tools/install', + if (hasHomebrewRustInPath()) ...[ + '\$ brew unlink rust # Unlink homebrew Rust from PATH', + ], + if (!Platform.isWindows) + "\$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh", + ' ', + ].join('\n'); + } + + static bool hasHomebrewRustInPath() { + if (!Platform.isMacOS) { + return false; + } + final envPath = Platform.environment['PATH'] ?? ''; + final paths = envPath.split(':'); + return paths.any((p) { + return p.contains('homebrew') && File(path.join(p, 'rustc')).existsSync(); + }); + } +} + +String _resolveExecutable(String executable) { + if (executable == 'rustup') { + final resolved = Rustup.executablePath(); + if (resolved != null) { + return resolved; + } + throw RustupNotFoundException(); + } else { + return executable; + } +} diff --git a/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart b/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart new file mode 100644 index 0000000..2366b57 --- /dev/null +++ b/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart @@ -0,0 +1,84 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:http/http.dart'; + +import 'artifacts_provider.dart'; +import 'cargo.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'target.dart'; + +class VerifyBinaries { + VerifyBinaries({ + required this.manifestDir, + }); + + final String manifestDir; + + Future run() async { + final crateInfo = CrateInfo.load(manifestDir); + + final config = CargokitCrateOptions.load(manifestDir: manifestDir); + final precompiledBinaries = config.precompiledBinaries; + if (precompiledBinaries == null) { + stdout.writeln('Crate does not support precompiled binaries.'); + } else { + final crateHash = CrateHash.compute(manifestDir); + stdout.writeln('Crate hash: $crateHash'); + + for (final target in Target.all) { + final message = 'Checking ${target.rust}...'; + stdout.write(message.padRight(40)); + stdout.flush(); + + final artifacts = getArtifactNames( + target: target, + libraryName: crateInfo.packageName, + remote: true, + ); + + final prefix = precompiledBinaries.uriPrefix; + + bool ok = true; + + for (final artifact in artifacts) { + final fileName = PrecompileBinaries.fileName(target, artifact); + final signatureFileName = + PrecompileBinaries.signatureFileName(target, artifact); + + final url = Uri.parse('$prefix$crateHash/$fileName'); + final signatureUrl = + Uri.parse('$prefix$crateHash/$signatureFileName'); + + final signature = await get(signatureUrl); + if (signature.statusCode != 200) { + stdout.writeln('MISSING'); + ok = false; + break; + } + final asset = await get(url); + if (asset.statusCode != 200) { + stdout.writeln('MISSING'); + ok = false; + break; + } + + if (!verify(precompiledBinaries.publicKey, asset.bodyBytes, + signature.bodyBytes)) { + stdout.writeln('INVALID SIGNATURE'); + ok = false; + } + } + + if (ok) { + stdout.writeln('OK'); + } + } + } + } +} diff --git a/rust_builder/cargokit/build_tool/pubspec.lock b/rust_builder/cargokit/build_tool/pubspec.lock new file mode 100644 index 0000000..343bdd3 --- /dev/null +++ b/rust_builder/cargokit/build_tool/pubspec.lock @@ -0,0 +1,453 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 + url: "https://pub.dev" + source: hosted + version: "64.0.0" + adaptive_number: + dependency: transitive + description: + name: adaptive_number + sha256: "3a567544e9b5c9c803006f51140ad544aedc79604fd4f3f2c1380003f97c1d77" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" + url: "https://pub.dev" + source: hosted + version: "6.2.0" + args: + dependency: "direct main" + description: + name: args + sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + collection: + dependency: "direct main" + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + convert: + dependency: "direct main" + description: + name: convert + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + coverage: + dependency: transitive + description: + name: coverage + sha256: "2fb815080e44a09b85e0f2ca8a820b15053982b2e714b59267719e8a9ff17097" + url: "https://pub.dev" + source: hosted + version: "1.6.3" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + url: "https://pub.dev" + source: hosted + version: "3.0.3" + ed25519_edwards: + dependency: "direct main" + description: + name: ed25519_edwards + sha256: "6ce0112d131327ec6d42beede1e5dfd526069b18ad45dcf654f15074ad9276cd" + url: "https://pub.dev" + source: hosted + version: "0.3.1" + file: + dependency: transitive + description: + name: file + sha256: "1b92bec4fc2a72f59a8e15af5f52cd441e4a7860b49499d69dfa817af20e925d" + url: "https://pub.dev" + source: hosted + version: "6.1.4" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + github: + dependency: "direct main" + description: + name: github + sha256: "9966bc13bf612342e916b0a343e95e5f046c88f602a14476440e9b75d2295411" + url: "https://pub.dev" + source: hosted + version: "9.17.0" + glob: + dependency: transitive + description: + name: glob + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + hex: + dependency: "direct main" + description: + name: hex + sha256: "4e7cd54e4b59ba026432a6be2dd9d96e4c5205725194997193bf871703b82c4a" + url: "https://pub.dev" + source: hosted + version: "0.2.0" + http: + dependency: "direct main" + description: + name: http + sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + io: + dependency: transitive + description: + name: io + sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: b10a7b2ff83d83c777edba3c6a0f97045ddadd56c944e1a23a3fdf43a1bf4467 + url: "https://pub.dev" + source: hosted + version: "4.8.1" + lints: + dependency: "direct dev" + description: + name: lints + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + logging: + dependency: "direct main" + description: + name: logging + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" + url: "https://pub.dev" + source: hosted + version: "0.12.16" + meta: + dependency: transitive + description: + name: meta + sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + mime: + dependency: transitive + description: + name: mime + sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e + url: "https://pub.dev" + source: hosted + version: "1.0.4" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + package_config: + dependency: transitive + description: + name: package_config + sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + path: + dependency: "direct main" + description: + name: path + sha256: "2ad4cddff7f5cc0e2d13069f2a3f7a73ca18f66abd6f5ecf215219cdb3638edb" + url: "https://pub.dev" + source: hosted + version: "1.8.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: cb3798bef7fc021ac45b308f4b51208a152792445cce0448c9a4ba5879dd8750 + url: "https://pub.dev" + source: hosted + version: "5.4.0" + pool: + dependency: transitive + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + shelf: + dependency: transitive + description: + name: shelf + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.dev" + source: hosted + version: "1.4.1" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e + url: "https://pub.dev" + source: hosted + version: "1.1.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" + url: "https://pub.dev" + source: hosted + version: "0.10.12" + source_span: + dependency: "direct main" + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test: + dependency: "direct dev" + description: + name: test + sha256: "9b0dd8e36af4a5b1569029949d50a52cb2a2a2fdaa20cebb96e6603b9ae241f9" + url: "https://pub.dev" + source: hosted + version: "1.24.6" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + test_core: + dependency: transitive + description: + name: test_core + sha256: "4bef837e56375537055fdbbbf6dd458b1859881f4c7e6da936158f77d61ab265" + url: "https://pub.dev" + source: hosted + version: "0.5.6" + toml: + dependency: "direct main" + description: + name: toml + sha256: "157c5dca5160fced243f3ce984117f729c788bb5e475504f3dbcda881accee44" + url: "https://pub.dev" + source: hosted + version: "0.14.0" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.dev" + source: hosted + version: "1.3.2" + version: + dependency: "direct main" + description: + name: version + sha256: "2307e23a45b43f96469eeab946208ed63293e8afca9c28cd8b5241ff31c55f55" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0fae432c85c4ea880b33b497d32824b97795b04cdaa74d270219572a1f50268d" + url: "https://pub.dev" + source: hosted + version: "11.9.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b + url: "https://pub.dev" + source: hosted + version: "2.4.0" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "67d3a8b6c79e1987d19d848b0892e582dbb0c66c57cc1fef58a177dd2aa2823d" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + yaml: + dependency: "direct main" + description: + name: yaml + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + url: "https://pub.dev" + source: hosted + version: "3.1.2" +sdks: + dart: ">=3.0.0 <4.0.0" diff --git a/rust_builder/cargokit/build_tool/pubspec.yaml b/rust_builder/cargokit/build_tool/pubspec.yaml new file mode 100644 index 0000000..18c61e3 --- /dev/null +++ b/rust_builder/cargokit/build_tool/pubspec.yaml @@ -0,0 +1,33 @@ +# This is copied from Cargokit (which is the official way to use it currently) +# Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +name: build_tool +description: Cargokit build_tool. Facilitates the build of Rust crate during Flutter application build. +publish_to: none +version: 1.0.0 + +environment: + sdk: ">=3.0.0 <4.0.0" + +# Add regular dependencies here. +dependencies: + # these are pinned on purpose because the bundle_tool_runner doesn't have + # pubspec.lock. See run_build_tool.sh + logging: 1.2.0 + path: 1.8.0 + version: 3.0.0 + collection: 1.18.0 + ed25519_edwards: 0.3.1 + hex: 0.2.0 + yaml: 3.1.2 + source_span: 1.10.0 + github: 9.17.0 + args: 2.4.2 + crypto: 3.0.3 + convert: 3.1.1 + http: 1.1.0 + toml: 0.14.0 + +dev_dependencies: + lints: ^2.1.0 + test: ^1.24.0 diff --git a/rust_builder/cargokit/cmake/cargokit.cmake b/rust_builder/cargokit/cmake/cargokit.cmake new file mode 100644 index 0000000..3738bb4 --- /dev/null +++ b/rust_builder/cargokit/cmake/cargokit.cmake @@ -0,0 +1,126 @@ +SET(cargokit_cmake_root "${CMAKE_CURRENT_LIST_DIR}/..") + +# Workaround for https://github.com/dart-lang/pub/issues/4010 +get_filename_component(cargokit_cmake_root "${cargokit_cmake_root}" REALPATH) + +if(WIN32) + # REALPATH does not properly resolve symlinks on windows :-/ + execute_process(COMMAND powershell -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_LIST_DIR}/resolve_symlinks.ps1" "${cargokit_cmake_root}" OUTPUT_VARIABLE cargokit_cmake_root OUTPUT_STRIP_TRAILING_WHITESPACE) +endif() + +# Arguments +# - target: CMAKE target to which rust library is linked +# - manifest_dir: relative path from current folder to directory containing cargo manifest +# - lib_name: cargo package name +# - any_symbol_name: name of any exported symbol from the library. +# used on windows to force linking with library. +function(apply_cargokit target manifest_dir lib_name any_symbol_name) + + set(CARGOKIT_LIB_NAME "${lib_name}") + set(CARGOKIT_LIB_FULL_NAME "${CMAKE_SHARED_MODULE_PREFIX}${CARGOKIT_LIB_NAME}${CMAKE_SHARED_MODULE_SUFFIX}") + if (CMAKE_CONFIGURATION_TYPES) + set(CARGOKIT_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/$") + set(OUTPUT_LIB "${CMAKE_CURRENT_BINARY_DIR}/$/${CARGOKIT_LIB_FULL_NAME}") + else() + set(CARGOKIT_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}") + set(OUTPUT_LIB "${CMAKE_CURRENT_BINARY_DIR}/${CARGOKIT_LIB_FULL_NAME}") + endif() + set(CARGOKIT_TEMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/cargokit_build") + + if (FLUTTER_TARGET_PLATFORM) + set(CARGOKIT_TARGET_PLATFORM "${FLUTTER_TARGET_PLATFORM}") + else() + set(CARGOKIT_TARGET_PLATFORM "windows-x64") + endif() + set(CARGOKIT_OHOS_SDK_HOME $ENV{OHOS_SDK_HOME}) + + set(CARGOKIT_ENV + "CARGOKIT_CMAKE=${CMAKE_COMMAND}" + "CARGOKIT_CONFIGURATION=$" + "CARGOKIT_MANIFEST_DIR=${CMAKE_CURRENT_SOURCE_DIR}/${manifest_dir}" + "CARGOKIT_TARGET_TEMP_DIR=${CARGOKIT_TEMP_DIR}" + "CARGOKIT_OUTPUT_DIR=${CARGOKIT_OUTPUT_DIR}" + "CARGOKIT_TARGET_PLATFORM=${CARGOKIT_TARGET_PLATFORM}" + "CARGOKIT_TOOL_TEMP_DIR=${CARGOKIT_TEMP_DIR}/tool" + "CARGOKIT_ROOT_PROJECT_DIR=${CMAKE_SOURCE_DIR}" + "CARGOKIT_OHOS_SDK_HOME=${CARGOKIT_OHOS_SDK_HOME}" + ) + + if (WIN32) + set(SCRIPT_EXTENSION ".cmd") + set(IMPORT_LIB_EXTENSION ".lib") + elseif (CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-arm64" + OR CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-arm" + OR CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-x64") + if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") + set(SCRIPT_EXTENSION ".cmd") + else() + set(SCRIPT_EXTENSION ".sh") + execute_process(COMMAND chmod +x "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}") + endif() + set(IMPORT_LIB_EXTENSION "") + else() + set(SCRIPT_EXTENSION ".sh") + set(IMPORT_LIB_EXTENSION "") + execute_process(COMMAND chmod +x "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}") + endif() + + # Using generators in custom command is only supported in CMake 3.20+ + if (CMAKE_CONFIGURATION_TYPES AND ${CMAKE_VERSION} VERSION_LESS "3.20.0") + foreach(CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES) + add_custom_command( + OUTPUT + "${CMAKE_CURRENT_BINARY_DIR}/${CONFIG}/${CARGOKIT_LIB_FULL_NAME}" + "${CMAKE_CURRENT_BINARY_DIR}/_phony_" + COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV} + "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake + VERBATIM + ) + endforeach() + elseif (CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-arm64" + OR CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-arm" + OR CARGOKIT_TARGET_PLATFORM STREQUAL "ohos-x64") + set(SOURCE_LIB "../../ohos/.cxx/default/default/debug/${OHOS_ARCH}/lib${PROJECT_NAME}.so") + set(DEST_LIB "${TARGET_LIB_DIR}/lib${PROJECT_NAME}.so") + add_custom_command( + OUTPUT + ${OUTPUT_LIB} + "${CMAKE_CURRENT_BINARY_DIR}/_phony_" + COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV} + "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake + COMMAND ${CMAKE_COMMAND} -E copy ${OUTPUT_LIB} ${DEST_LIB} + COMMENT "Building and copying ${OUTPUT_LIB} to ${DEST_LIB}" + VERBATIM + ) + else() + add_custom_command( + OUTPUT + ${OUTPUT_LIB} + "${CMAKE_CURRENT_BINARY_DIR}/_phony_" + COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV} + "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake + VERBATIM + ) + endif() + + + set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/_phony_" PROPERTIES SYMBOLIC TRUE) + + if (TARGET ${target}) + # If we have actual cmake target provided create target and make existing + # target depend on it + add_custom_target("${target}_cargokit" DEPENDS ${OUTPUT_LIB}) + add_dependencies("${target}" "${target}_cargokit") + target_link_libraries("${target}" PRIVATE "${OUTPUT_LIB}${IMPORT_LIB_EXTENSION}") + if(WIN32) + target_link_options(${target} PRIVATE "/INCLUDE:${any_symbol_name}") + endif() + else() + # Otherwise (FFI) just use ALL to force building always + add_custom_target("${target}_cargokit" ALL DEPENDS ${OUTPUT_LIB}) + endif() + + # Allow adding the output library to plugin bundled libraries + set("${target}_cargokit_lib" ${OUTPUT_LIB} PARENT_SCOPE) + +endfunction() diff --git a/rust_builder/cargokit/cmake/resolve_symlinks.ps1 b/rust_builder/cargokit/cmake/resolve_symlinks.ps1 new file mode 100644 index 0000000..2ac593a --- /dev/null +++ b/rust_builder/cargokit/cmake/resolve_symlinks.ps1 @@ -0,0 +1,34 @@ +function Resolve-Symlinks { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] + [string] $Path + ) + + [string] $separator = '/' + [string[]] $parts = $Path.Split($separator) + + [string] $realPath = '' + foreach ($part in $parts) { + if ($realPath -and !$realPath.EndsWith($separator)) { + $realPath += $separator + } + + $realPath += $part.Replace('\', '/') + + # The slash is important when using Get-Item on Drive letters in pwsh. + if (-not($realPath.Contains($separator)) -and $realPath.EndsWith(':')) { + $realPath += '/' + } + + $item = Get-Item $realPath + if ($item.LinkTarget) { + $realPath = $item.LinkTarget.Replace('\', '/') + } + } + $realPath +} + +$path = Resolve-Symlinks -Path $args[0] +Write-Host $path diff --git a/rust_builder/cargokit/gradle/plugin.gradle b/rust_builder/cargokit/gradle/plugin.gradle new file mode 100644 index 0000000..8c40086 --- /dev/null +++ b/rust_builder/cargokit/gradle/plugin.gradle @@ -0,0 +1,189 @@ +/// This is copied from Cargokit (which is the official way to use it currently) +/// Details: https://fzyzcjy.github.io/flutter_rust_bridge/manual/integrate/builtin + +import java.nio.file.Paths +import javax.inject.Inject +import org.apache.tools.ant.taskdefs.condition.Os +import org.gradle.process.ExecOperations + +CargoKitPlugin.file = buildscript.sourceFile + +apply plugin: CargoKitPlugin + +class CargoKitExtension { + String manifestDir; // Relative path to folder containing Cargo.toml + String libname; // Library name within Cargo.toml. Must be a cdylib +} + +abstract class CargoKitBuildTask extends DefaultTask { + + @Inject + abstract ExecOperations getExecOperations() + + @Input + String buildMode + + @Input + String buildDir + + @Input + String outputDir + + @Input + String ndkVersion + + @Input + String sdkDirectory + + @Input + int compileSdkVersion; + + @Input + int minSdkVersion; + + @Input + String pluginFile + + @Input + List targetPlatforms + + @TaskAction + def build() { + if (project.cargokit.manifestDir == null) { + throw new GradleException("Property 'manifestDir' must be set on cargokit extension"); + } + + if (project.cargokit.libname == null) { + throw new GradleException("Property 'libname' must be set on cargokit extension"); + } + + def executableName = Os.isFamily(Os.FAMILY_WINDOWS) ? "run_build_tool.cmd" : "run_build_tool.sh" + def path = Paths.get(new File(pluginFile).parent, "..", executableName); + + def manifestDir = Paths.get(project.buildscript.sourceFile.parent, project.cargokit.manifestDir) + + def rootProjectDir = project.rootProject.projectDir + + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { + execOperations.exec { + commandLine 'chmod', '+x', path + } + } + + execOperations.exec { + executable path + args "build-gradle" + environment "CARGOKIT_ROOT_PROJECT_DIR", rootProjectDir + environment "CARGOKIT_TOOL_TEMP_DIR", "${buildDir}/build_tool" + environment "CARGOKIT_MANIFEST_DIR", manifestDir + environment "CARGOKIT_CONFIGURATION", buildMode + environment "CARGOKIT_TARGET_TEMP_DIR", buildDir + environment "CARGOKIT_OUTPUT_DIR", outputDir + environment "CARGOKIT_NDK_VERSION", ndkVersion + environment "CARGOKIT_SDK_DIR", sdkDirectory + environment "CARGOKIT_COMPILE_SDK_VERSION", compileSdkVersion + environment "CARGOKIT_MIN_SDK_VERSION", minSdkVersion + environment "CARGOKIT_TARGET_PLATFORMS", targetPlatforms.join(",") + environment "CARGOKIT_JAVA_HOME", System.properties['java.home'] + } + } +} + +class CargoKitPlugin implements Plugin { + + static String file; + + private Plugin findFlutterPlugin(Project rootProject) { + _findFlutterPlugin(rootProject.childProjects) + } + + private Plugin _findFlutterPlugin(Map projects) { + for (project in projects) { + for (plugin in project.value.getPlugins()) { + if (plugin.class.name == "com.flutter.gradle.FlutterPlugin" || plugin.class.name == "FlutterPlugin") { + return plugin; + } + } + def plugin = _findFlutterPlugin(project.value.childProjects); + if (plugin != null) { + return plugin; + } + } + return null; + } + + @Override + void apply(Project project) { + def plugin = findFlutterPlugin(project.rootProject); + + project.extensions.create("cargokit", CargoKitExtension) + + if (plugin == null) { + print("Flutter plugin not found, CargoKit plugin will not be applied.") + return; + } + + def cargoBuildDir = "${project.buildDir}/build" + + // Determine if the project is an application or library + def isApplication = plugin.project.plugins.hasPlugin('com.android.application') + def variants = isApplication ? plugin.project.android.applicationVariants : plugin.project.android.libraryVariants + + variants.all { variant -> + + final buildType = variant.buildType.name + + def cargoOutputDir = "${project.buildDir}/jniLibs/${buildType}"; + def jniLibs = project.android.sourceSets.maybeCreate(buildType).jniLibs; + jniLibs.srcDir(new File(cargoOutputDir)) + + def List platforms + try { + platforms = com.flutter.gradle.FlutterPluginUtils.getTargetPlatforms(project).collect() + } catch (Exception ignored) { + platforms = plugin.getTargetPlatforms().collect() + } + + // Same thing addFlutterDependencies does in flutter.gradle + if (buildType == "debug") { + platforms.add("android-x86") + platforms.add("android-x64") + } + + // The task name depends on plugin properties, which are not available + // at this point + project.getGradle().afterProject { + def taskName = "cargokitCargoBuild${project.cargokit.libname.capitalize()}${buildType.capitalize()}"; + + if (project.tasks.findByName(taskName)) { + return + } + + if (plugin.project.android.ndkVersion == null) { + throw new GradleException("Please set 'android.ndkVersion' in 'app/build.gradle'.") + } + + def task = project.tasks.create(taskName, CargoKitBuildTask.class) { + buildMode = variant.buildType.name + buildDir = cargoBuildDir + outputDir = cargoOutputDir + ndkVersion = plugin.project.android.ndkVersion + sdkDirectory = plugin.project.android.sdkDirectory + minSdkVersion = plugin.project.android.defaultConfig.minSdkVersion.apiLevel as int + compileSdkVersion = plugin.project.android.compileSdkVersion.substring(8) as int + targetPlatforms = platforms + pluginFile = CargoKitPlugin.file + } + def onTask = { newTask -> + if (newTask.name == "merge${buildType.capitalize()}NativeLibs") { + newTask.dependsOn task + // Fix gradle 7.4.2 not picking up JNI library changes + newTask.outputs.upToDateWhen { false } + } + } + project.tasks.each onTask + project.tasks.whenTaskAdded onTask + } + } + } +} diff --git a/rust_builder/cargokit/run_build_tool.cmd b/rust_builder/cargokit/run_build_tool.cmd new file mode 100755 index 0000000..c45d0aa --- /dev/null +++ b/rust_builder/cargokit/run_build_tool.cmd @@ -0,0 +1,91 @@ +@echo off +setlocal + +setlocal ENABLEDELAYEDEXPANSION + +SET BASEDIR=%~dp0 + +if not exist "%CARGOKIT_TOOL_TEMP_DIR%" ( + mkdir "%CARGOKIT_TOOL_TEMP_DIR%" +) +cd /D "%CARGOKIT_TOOL_TEMP_DIR%" + +SET BUILD_TOOL_PKG_DIR=%BASEDIR%build_tool +SET DART=%FLUTTER_ROOT%\bin\cache\dart-sdk\bin\dart + +set BUILD_TOOL_PKG_DIR_POSIX=%BUILD_TOOL_PKG_DIR:\=/% + +( + echo name: build_tool_runner + echo version: 1.0.0 + echo publish_to: none + echo. + echo environment: + echo sdk: '^>=3.0.0 ^<4.0.0' + echo. + echo dependencies: + echo build_tool: + echo path: %BUILD_TOOL_PKG_DIR_POSIX% +) >pubspec.yaml + +if not exist bin ( + mkdir bin +) + +( + echo import 'package:build_tool/build_tool.dart' as build_tool; + echo void main^(List^ args^) ^{ + echo build_tool.runMain^(args^); + echo ^} +) >bin\build_tool_runner.dart + +SET PRECOMPILED=bin\build_tool_runner.dill + +REM To detect changes in package we compare output of DIR /s (recursive) +set PREV_PACKAGE_INFO=.dart_tool\package_info.prev +set CUR_PACKAGE_INFO=.dart_tool\package_info.cur + +DIR "%BUILD_TOOL_PKG_DIR%" /s > "%CUR_PACKAGE_INFO%_orig" + +REM Last line in dir output is free space on harddrive. That is bound to +REM change between invocation so we need to remove it +( + Set "Line=" + For /F "UseBackQ Delims=" %%A In ("%CUR_PACKAGE_INFO%_orig") Do ( + SetLocal EnableDelayedExpansion + If Defined Line Echo !Line! + EndLocal + Set "Line=%%A") +) >"%CUR_PACKAGE_INFO%" +DEL "%CUR_PACKAGE_INFO%_orig" + +REM Compare current directory listing with previous +FC /B "%CUR_PACKAGE_INFO%" "%PREV_PACKAGE_INFO%" > nul 2>&1 + +If %ERRORLEVEL% neq 0 ( + REM Changed - copy current to previous and remove precompiled kernel + if exist "%PREV_PACKAGE_INFO%" ( + DEL "%PREV_PACKAGE_INFO%" + ) + MOVE /Y "%CUR_PACKAGE_INFO%" "%PREV_PACKAGE_INFO%" + if exist "%PRECOMPILED%" ( + DEL "%PRECOMPILED%" + ) +) + +REM There is no CUR_PACKAGE_INFO it was renamed in previous step to %PREV_PACKAGE_INFO% +REM which means we need to do pub get and precompile +if not exist "%PRECOMPILED%" ( + echo Running pub get in "%cd%" + "%DART%" pub get --no-precompile + "%DART%" compile kernel bin/build_tool_runner.dart +) + +"%DART%" "%PRECOMPILED%" %* + +REM 253 means invalid snapshot version. +If %ERRORLEVEL% equ 253 ( + "%DART%" pub get --no-precompile + "%DART%" compile kernel bin/build_tool_runner.dart + "%DART%" "%PRECOMPILED%" %* +) diff --git a/rust_builder/cargokit/run_build_tool.sh b/rust_builder/cargokit/run_build_tool.sh new file mode 100755 index 0000000..24b0ed8 --- /dev/null +++ b/rust_builder/cargokit/run_build_tool.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash + +set -e + +BASEDIR=$(dirname "$0") + +mkdir -p "$CARGOKIT_TOOL_TEMP_DIR" + +cd "$CARGOKIT_TOOL_TEMP_DIR" + +# Write a very simple bin package in temp folder that depends on build_tool package +# from Cargokit. This is done to ensure that we don't pollute Cargokit folder +# with .dart_tool contents. + +BUILD_TOOL_PKG_DIR="$BASEDIR/build_tool" + +if [[ -z $FLUTTER_ROOT ]]; then # not defined + DART=dart +else + DART="$FLUTTER_ROOT/bin/cache/dart-sdk/bin/dart" +fi + +cat << EOF > "pubspec.yaml" +name: build_tool_runner +version: 1.0.0 +publish_to: none + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + build_tool: + path: "$BUILD_TOOL_PKG_DIR" +EOF + +mkdir -p "bin" + +cat << EOF > "bin/build_tool_runner.dart" +import 'package:build_tool/build_tool.dart' as build_tool; +void main(List args) { + build_tool.runMain(args); +} +EOF + +# Create alias for `shasum` if it does not exist and `sha1sum` exists +if ! [ -x "$(command -v shasum)" ] && [ -x "$(command -v sha1sum)" ]; then + shopt -s expand_aliases + alias shasum="sha1sum" +fi + +# Dart run will not cache any package that has a path dependency, which +# is the case for our build_tool_runner. So instead we precompile the package +# ourselves. +# To invalidate the cached kernel we use the hash of ls -LR of the build_tool +# package directory. This should be good enough, as the build_tool package +# itself is not meant to have any path dependencies. + +if [[ "$OSTYPE" == "darwin"* ]]; then + PACKAGE_HASH=$(ls -lTR "$BUILD_TOOL_PKG_DIR" | shasum) +else + PACKAGE_HASH=$(ls -lR --full-time "$BUILD_TOOL_PKG_DIR" | shasum) +fi + +PACKAGE_HASH_FILE=".package_hash" + +if [ -f "$PACKAGE_HASH_FILE" ]; then + EXISTING_HASH=$(cat "$PACKAGE_HASH_FILE") + if [ "$PACKAGE_HASH" != "$EXISTING_HASH" ]; then + rm "$PACKAGE_HASH_FILE" + fi +fi + +# Run pub get if needed. +if [ ! -f "$PACKAGE_HASH_FILE" ]; then + "$DART" pub get --no-precompile + "$DART" compile kernel bin/build_tool_runner.dart + echo "$PACKAGE_HASH" > "$PACKAGE_HASH_FILE" +fi + +# Rebuild the tool if it was deleted by Android Studio +if [ ! -f "bin/build_tool_runner.dill" ]; then + "$DART" compile kernel bin/build_tool_runner.dart +fi + +set +e + +"$DART" bin/build_tool_runner.dill "$@" + +exit_code=$? + +# 253 means invalid snapshot version. +if [ $exit_code == 253 ]; then + "$DART" pub get --no-precompile + "$DART" compile kernel bin/build_tool_runner.dart + "$DART" bin/build_tool_runner.dill "$@" + exit_code=$? +fi + +exit $exit_code diff --git a/rust_builder/ios/Classes/dummy_file.c b/rust_builder/ios/Classes/dummy_file.c new file mode 100644 index 0000000..e06dab9 --- /dev/null +++ b/rust_builder/ios/Classes/dummy_file.c @@ -0,0 +1 @@ +// This is an empty file to force CocoaPods to create a framework. diff --git a/rust_builder/ios/rust_lib_diagd.podspec b/rust_builder/ios/rust_lib_diagd.podspec new file mode 100644 index 0000000..73a4621 --- /dev/null +++ b/rust_builder/ios/rust_lib_diagd.podspec @@ -0,0 +1,45 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint rust_lib_diagd.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'rust_lib_diagd' + s.version = '0.0.1' + s.summary = 'A new Flutter FFI plugin project.' + s.description = <<-DESC +A new Flutter FFI plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + + # This will ensure the source files in Classes/ are included in the native + # builds of apps using this FFI plugin. Podspec does not support relative + # paths, so Classes contains a forwarder C file that relatively imports + # `../src/*` so that the C sources can be shared among all target platforms. + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'Flutter' + s.platform = :ios, '11.0' + + # Flutter.framework does not contain a i386 slice. + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } + s.swift_version = '5.0' + + s.script_phase = { + :name => 'Build Rust library', + # First argument is relative path to the `rust` folder, second is name of rust library + :script => 'sh "$PODS_TARGET_SRCROOT/../cargokit/build_pod.sh" ../../rust rust_lib_diagd', + :execution_position => :before_compile, + :input_files => ['${BUILT_PRODUCTS_DIR}/cargokit_phony'], + # Let XCode know that the static library referenced in -force_load below is + # created by this build step. + :output_files => ["${BUILT_PRODUCTS_DIR}/librust_lib_diagd.a"], + } + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES', + # Flutter.framework does not contain a i386 slice. + 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386', + 'OTHER_LDFLAGS' => '-force_load ${BUILT_PRODUCTS_DIR}/librust_lib_diagd.a', + } +end \ No newline at end of file diff --git a/rust_builder/linux/CMakeLists.txt b/rust_builder/linux/CMakeLists.txt new file mode 100644 index 0000000..55a53bb --- /dev/null +++ b/rust_builder/linux/CMakeLists.txt @@ -0,0 +1,21 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) +cmake_policy(SET CMP0079 NEW) + +# Project-level configuration. +set(PROJECT_NAME "rust_lib_diagd") +project(${PROJECT_NAME} LANGUAGES CXX) + +include("../cargokit/cmake/cargokit.cmake") +apply_cargokit(${PROJECT_NAME} ../../rust rust_lib_diagd "") +target_link_libraries(${BINARY_NAME} PRIVATE "${${PROJECT_NAME}_cargokit_lib}") + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(rust_lib_diagd_bundled_libraries + "${${PROJECT_NAME}_cargokit_lib}" + PARENT_SCOPE +) diff --git a/rust_builder/macos/Classes/dummy_file.c b/rust_builder/macos/Classes/dummy_file.c new file mode 100644 index 0000000..e06dab9 --- /dev/null +++ b/rust_builder/macos/Classes/dummy_file.c @@ -0,0 +1 @@ +// This is an empty file to force CocoaPods to create a framework. diff --git a/rust_builder/macos/rust_lib_diagd.podspec b/rust_builder/macos/rust_lib_diagd.podspec new file mode 100644 index 0000000..019b2e1 --- /dev/null +++ b/rust_builder/macos/rust_lib_diagd.podspec @@ -0,0 +1,44 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint rust_lib_diagd.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'rust_lib_diagd' + s.version = '0.0.1' + s.summary = 'A new Flutter FFI plugin project.' + s.description = <<-DESC +A new Flutter FFI plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + + # This will ensure the source files in Classes/ are included in the native + # builds of apps using this FFI plugin. Podspec does not support relative + # paths, so Classes contains a forwarder C file that relatively imports + # `../src/*` so that the C sources can be shared among all target platforms. + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'FlutterMacOS' + + s.platform = :osx, '10.11' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } + s.swift_version = '5.0' + + s.script_phase = { + :name => 'Build Rust library', + # First argument is relative path to the `rust` folder, second is name of rust library + :script => 'sh "$PODS_TARGET_SRCROOT/../cargokit/build_pod.sh" ../../rust rust_lib_diagd', + :execution_position => :before_compile, + :input_files => ['${BUILT_PRODUCTS_DIR}/cargokit_phony'], + # Let XCode know that the static library referenced in -force_load below is + # created by this build step. + :output_files => ["${BUILT_PRODUCTS_DIR}/librust_lib_diagd.a"], + } + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES', + # Flutter.framework does not contain a i386 slice. + 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386', + 'OTHER_LDFLAGS' => '-force_load ${BUILT_PRODUCTS_DIR}/librust_lib_diagd.a', + } +end \ No newline at end of file diff --git a/rust_builder/pubspec.yaml b/rust_builder/pubspec.yaml new file mode 100644 index 0000000..93a8b21 --- /dev/null +++ b/rust_builder/pubspec.yaml @@ -0,0 +1,34 @@ +name: rust_lib_diagd +description: "Utility to build Rust code" +version: 0.0.1 +publish_to: none + +environment: + sdk: '>=3.3.0 <4.0.0' + flutter: '>=3.3.0' + +dependencies: + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + +dev_dependencies: + ffi: ^2.0.2 + ffigen: ^20.1.1 + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + +flutter: + plugin: + platforms: + android: + ffiPlugin: true + ios: + ffiPlugin: true + linux: + ffiPlugin: true + macos: + ffiPlugin: true + windows: + ffiPlugin: true diff --git a/rust_builder/windows/.gitignore b/rust_builder/windows/.gitignore new file mode 100644 index 0000000..b3eb2be --- /dev/null +++ b/rust_builder/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/rust_builder/windows/CMakeLists.txt b/rust_builder/windows/CMakeLists.txt new file mode 100644 index 0000000..73b763c --- /dev/null +++ b/rust_builder/windows/CMakeLists.txt @@ -0,0 +1,20 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "rust_lib_diagd") +project(${PROJECT_NAME} LANGUAGES CXX) + +include("../cargokit/cmake/cargokit.cmake") +apply_cargokit(${PROJECT_NAME} ../../../../../../rust rust_lib_diagd "") + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(rust_lib_diagd_bundled_libraries + "${${PROJECT_NAME}_cargokit_lib}" + PARENT_SCOPE +) diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..3102989 --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,7 @@ +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('diagnostics basic test placeholder', () { + expect(1 + 1, equals(2)); + }); +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..ad7b95a --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(diagd LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "diagd") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..38f7d7b --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + rust_lib_diagd +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..2782c6e --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "diagd" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "diagd" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "diagd.exe" "\0" + VALUE "ProductName", "diagd" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..ddad5bd --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,62 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + for (const auto& arg : command_line_arguments) { + if (arg == "--tui" || arg == "-t") { + if (!::AttachConsole(ATTACH_PARENT_PROCESS)) { + ::AllocConsole(); + } + HMODULE hMod = ::LoadLibraryW(L"rust_lib_diagd.dll"); + if (hMod) { + typedef int (*run_tui_fn)(); + run_tui_fn run_tui = (run_tui_fn)::GetProcAddress(hMod, "diagd_run_tui"); + if (run_tui) { + int code = run_tui(); + ::FreeLibrary(hMod); + return code; + } + } + return EXIT_FAILURE; + } + } + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"diagd", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_